omi/dist/omi.lite.js

1023 lines
36 KiB
JavaScript
Raw Blame History

/*!
* Omi v0.1.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 _component = __webpack_require__(3);
var _component2 = _interopRequireDefault(_component);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_omi2.default.template = function (tpl, data) {
return tpl;
};
_omi2.default.Component = _component2.default;
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_";
//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;
};
}
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[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[tagName];
};
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('.') !== 0) {
var arr = str.split('.');
var len = arr.length;
var current = Omi[arr[0]];
for (var i = 1; i < len; i++) {
current = current[arr[i]];
}
return current;
} else {
return Omi[str];
}
};
//<2F><>ǰ<EFBFBD><C7B0>Component<6E>ľ<EFBFBD>̬<EFBFBD><CCAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƶ<EFBFBD>omi<6D><69><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ȼmakehtml <20><>ie<69><65>child<6C><64><EFBFBD>ʲ<EFBFBD><CAB2><EFBFBD><EFBFBD><EFBFBD><EFBFBD>׵ľ<D7B5>̬<EFBFBD><CCAC><EFBFBD><EFBFBD>
Omi.makeHTML = function (ctor, name) {
var tagName = name || ctor.name;
// fix ie tagName is undefined
if (!tagName) {
tagName = (ctor + "").split("(")[0].replace("function", "").trim();
}
Omi[tagName] = ctor;
Omi.customTags.push(tagName);
return tagName;
};
Omi.render = function (component, renderTo, increment) {
component.renderTo = typeof renderTo === "string" ? document.querySelector(renderTo) : renderTo;
component._omi_increment = increment;
component.install();
component._render(true);
component.installed();
component._childrenInstalled(component);
return component;
};
Omi.get = function (name) {
return Omi.mapping[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 _diff = __webpack_require__(6);
var _diff2 = _interopRequireDefault(_diff);
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, server) {
_classCallCheck(this, Component);
//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 = server;
this.id = _omi2.default.getInstanceId();
this.refs = {};
}
this.children = [];
this.childrenData = [];
this.HTML = null;
this._addedItems = [];
this._omi_order = [];
_omi2.default.instances[this.id] = this;
this.BODY_ELEMENT = document.createElement('body');
if (this._omi_server_rendering || isReRendering) {
this.install();
this._render(true);
this.installed();
this._childrenInstalled(this);
}
}
_createClass(Component, [{
key: 'install',
value: function install() {}
}, {
key: 'installed',
value: function installed() {}
}, {
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: 'update',
value: function update() {
this.beforeUpdate();
if (this.renderTo) {
this._render();
} else {
// update child node
if (this._omi_removed) {
var hdNode = this._createHiddenNode();
this.node.parentNode.replaceChild(hdNode, this.node);
this.node = hdNode;
} else {
(0, _diff2.default)(this.node, (0, _event2.default)(this._childRender(this._omiChildStr), this.id));
}
}
//update added components
this._renderAddedChildren();
this.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: 'setComponentOrder',
value: function setComponentOrder(arr) {
var _this = this;
arr.forEach(function (item, index) {
_this._omi_order[index] = item;
});
this.update();
}
//beforeBegin,beforeEnd,afterBegin,afterEnd
}, {
key: 'addComponent',
value: function addComponent(position, el, component) {
this._addedItems.push({ position: position, el: el, component: component });
this.update();
}
}, {
key: 'removeComponent',
value: function removeComponent(component) {
for (var i = 0, len = this._addedItems.length; i < len; i++) {
if (component.id === this._addedItems[i].component.id) {
this._addedItems.splice(i, 1);
break;
}
}
this.update();
}
}, {
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();
}
}, {
key: '_renderAddedChildren',
value: function _renderAddedChildren() {
var _this2 = this;
this._addedItems.forEach(function (item) {
var target = typeof item.el === "string" ? _this2.node.querySelector(item.el) : item.el;
item.component.install();
item.component._render(true);
item.component.installed();
item.component._childrenInstalled(item.component);
target.insertAdjacentHTML(item.position, item.component.HTML);
});
this.children.forEach(function (child) {
child._renderAddedChildren();
});
}
}, {
key: '_render',
value: function _render(isFirst) {
var _this3 = 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;
}
this._generateHTMLCSS();
this._extractChildren(this);
if (isFirst) {
this.children.forEach(function (item, index) {
_this3._omi_order[index] = index;
});
}
this.children.forEach(function (item, index) {
_this3.HTML = _this3.HTML.replace(item._omiChildStr, _this3.children[_this3._omi_order[index]].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 !== "") {
(0, _diff2.default)(this.node, this.HTML);
} else {
(0, _diff2.default)(this.node, this._createHiddenNode());
}
}
//get node prop from parent node
if (this.renderTo) {
this.node = document.querySelector("[" + _omi2.default.STYLESCOPEDPREFIX + this.id + "]");
this._queryElements(this);
this._fixForm();
}
}
}, {
key: '_childRender',
value: function _childRender(childStr, isFirst) {
var _this4 = this;
if (this._omi_removed) {
this.HTML = '<input type="hidden" omi_scoped_' + this.id + ' >';
return this.HTML;
}
childStr = childStr.replace("<child", "<div").replace("/>", "></div>");
this._mergeData(childStr, isFirst);
this._generateHTMLCSS();
this._extractChildren(this);
if (isFirst) {
this.children.forEach(function (item, index) {
_this4._omi_order[index] = index;
});
}
this.children.forEach(function (item, index) {
_this4.HTML = _this4.HTML.replace(item._omiChildStr, _this4.children[_this4._omi_order[index]].HTML);
});
this.HTML = (0, _event2.default)(this.HTML, this.id);
return this.HTML;
}
}, {
key: '_queryElements',
value: function _queryElements(current) {
current._mixRefs();
current.children.forEach(function (item) {
item.node = current.node.querySelector("[" + _omi2.default.STYLESCOPEDPREFIX + item.id + "]");
//recursion get node prop from parent node
current._queryElements(item);
});
}
}, {
key: '_mixRefs',
value: function _mixRefs() {
var nodes = this.node.querySelectorAll('*[ref]');
var len = nodes.length;
if (len > 0) {
for (var i = 0; i < len; i++) {
var node = nodes[i];
this.refs[node.getAttribute("ref")] = node;
}
}
}
}, {
key: '_childrenInstalled',
value: function _childrenInstalled(root) {
var _this5 = this;
root.children.forEach(function (child) {
child.installed();
_this5._childrenInstalled(child);
});
}
}, {
key: '_getConstructorNameByMagic',
value: function _getConstructorNameByMagic(c) {
return (c + "").split("(")[0].replace("function", "").trim();
}
}, {
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.$$('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) {
var str = array.join("|");
var reg = new RegExp("(<(" + str + "))[^a-zA-Z>][\\s\\S]*?/>", "g");
return html.replace(reg, function (m, a, b) {
return m.replace(a, '<child tag="' + b + '" ');
});
}
}, {
key: '_createHiddenNode',
value: function _createHiddenNode() {
var hdNode = document.createElement("input");
hdNode.setAttribute("type", "hidden");
hdNode.setAttribute(_omi2.default.STYLESCOPEDPREFIX + this.id, "");
return hdNode;
}
}, {
key: '_mergeData',
value: function _mergeData(childStr, isFirst) {
this.data = Object.assign({}, this._getDataset(childStr), this.data);
isFirst && this.install();
}
}, {
key: '_generateHTMLCSS',
value: function _generateHTMLCSS() {
this.CSS = this.style();
var css = "";
if (this.CSS) {
css = _style2.default.scoper(this.CSS, "[" + _omi2.default.STYLESCOPEDPREFIX + this.id + "]");
if (!this._omi_server_rendering) {
_style2.default.addStyle(css, this.id);
}
}
var tpl = this.render();
this.HTML = this._scopedAttr(_omi2.default.template(tpl ? tpl : "", this.data), _omi2.default.STYLESCOPEDPREFIX + this.id).trim();
if (this._omi_server_rendering) {
this.HTML = '\r\n<style id="' + _omi2.default.STYLEPREFIX + this.id + '">\r\n' + css + '\r\n</style>\r\n' + this.HTML;
this.HTML += '\r\n<input type="hidden" data-omi-id="' + this.id + '" class="' + _omi2.default.STYLESCOPEDPREFIX + '_hidden_data" value=\'' + JSON.stringify(this.data) + '\' />\r\n';
}
}
}, {
key: '_scopedAttr',
value: function _scopedAttr(html, id) {
return html.replace(/<[^/]([A-Za-z]*)[^>]*>/g, function (m) {
var str = m.split(" ")[0].replace(">", "");
return m.replace(str, str + " " + id);
});
}
}, {
key: '_getDataset',
value: function _getDataset(str) {
this.BODY_ELEMENT.innerHTML = str;
return this.BODY_ELEMENT.firstChild.dataset;
}
}, {
key: '_extractChildren',
value: function _extractChildren(child) {
if (_omi2.default.customTags.length > 0) {
child.HTML = this._replaceTags(_omi2.default.customTags, child.HTML);
}
var arr = child.HTML.match(/<child[^>][\s\S]*?tag=['|"](\S*)['|"][\s\S]*?\/>/g);
if (arr) {
var len = arr.length;
for (var i = 0; i < len; i++) {
var childStr = arr[i];
childStr.match(/\s*tag=['|"](\S*)['|"]/);
var name = RegExp.$1;
var cmi = this.children[i];
//if not first time to invoke _extractChildren method
//___omi_constructor_name for es5
if (cmi && (cmi.constructor.name === name || cmi.___omi_constructor_name === name || this._getConstructorNameByMagic(cmi.constructor))) {
cmi._childRender(childStr);
continue;
} else {
(function () {
var ChildClass = _omi2.default.getClassFromString(name);
if (!ChildClass) throw "Can't find Class called [" + name + "]";
var sub_child = new ChildClass(child.childrenData[i] || {}, false);
sub_child._omiChildStr = childStr;
sub_child.parent = child;
var evtArr = childStr.match(/[\s\t\n]+on(\S*)=['|"](\S*)['|"]/g);
if (evtArr) {
evtArr.forEach(function (item) {
var evtArr = item.trim().split("=");
var hdName = evtArr[1].replace(/['|"]/g, "");
var handler = sub_child.parent[hdName];
if (handler) {
sub_child.data[evtArr[0]] = handler.bind(sub_child.parent);
}
});
}
sub_child._childRender(childStr, true);
var mo_ids = childStr.match(/omi-id=['|"](\S*)['|"]/);
if (mo_ids) {
_omi2.default.mapping[RegExp.$1] = sub_child;
}
if (!cmi) {
child.children.push(sub_child);
} else {
child.children[i] = sub_child;
}
childStr.match(/\s*name=['|"](\S*)['|"]/);
if (RegExp.$1) {
child[RegExp.$1] = sub_child;
}
})();
}
}
}
}
}]);
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) {
var re = new RegExp("([^\r\n,{}]+)(,(?=[^}]*{)|\s*{)", "g");
css = css.replace(re, function (g0, g1, g2) {
if (g1.match(/^\s*(@media|@keyframes|to|from|@font-face)/)) {
return g1 + g2;
}
if (g1.match(/:scope/)) {
g1 = g1.replace(/([^\s]*):scope/, function (h0, h1) {
if (h1 === "") {
return "> *";
} else {
return "> " + h1;
}
});
}
g1 = g1.replace(/^(\s*)/, g1.trim() + prefix + "," + "$1" + prefix + " ").replace(/\s+/g, ' ');
return g1 + g2;
});
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)=('|")/g, function (eventStr, b, c, d, e) {
if (e.substr(eventStr.length + d, 14) === "Omi.instances[") return eventStr;
return eventStr += "Omi.instances[" + id + "].";
});
});
};
exports.default = scopedEvent;
/***/ },
/* 6 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var NODE_INDEX = '__set-dom-index__';
var ELEMENT_TYPE = 1;
var DOCUMENT_TYPE = 9;
var HTML_ELEMENT = document.createElement('html');
var BODY_ELEMENT = document.createElement('body');
/**
* @description
* Updates existing dom to match a new dom.
*
* @param {HTMLEntity} prev - The html entity to update.
* @param {String|HTMLEntity} next - The updated html(entity).
*/
function setDOM(prev, next) {
// Ensure a realish dom node is provided.
assert(prev && prev.nodeType, 'You must provide a valid node to update.');
// Alias document element with document.
if (prev.nodeType === DOCUMENT_TYPE) prev = prev.documentElement;
// If a string was provided we will parse it as dom.
if (typeof next === 'string') {
if (prev === document.documentElement) {
HTML_ELEMENT.innerHTML = next;
next = HTML_ELEMENT;
} else {
BODY_ELEMENT.innerHTML = next;
next = BODY_ELEMENT.firstChild;
}
}
// Update the node.
setNode(prev, next);
}
/**
* @private
* @description
* Updates a specific htmlNode and does whatever it takes to convert it to another one.
*
* @param {HTMLEntity} prev - The previous HTMLNode.
* @param {HTMLEntity} next - The updated HTMLNode.
*/
function setNode(prev, next) {
// Handle regular element node updates.
if (prev.nodeType === ELEMENT_TYPE) {
// Update all children (and subchildren).
setChildNodes(prev, prev.childNodes, next.childNodes);
// Update the elements attributes / tagName.
if (prev.nodeName === next.nodeName) {
// If we have the same nodename then we can directly update the attributes.
setAttributes(prev, prev.attributes, next.attributes);
} else {
// Otherwise clone the new node to use as the existing node.
var newPrev = next.cloneNode();
// Copy over all existing children from the original node.
while (prev.firstChild) {
newPrev.appendChild(prev.firstChild);
} // Replace the original node with the new one with the right tag.
prev.parentNode.replaceChild(newPrev, prev);
}
} else if (prev.nodeType === next.nodeType) {
// Handle other types of node updates (text/comments/etc).
// If both are the same type of node we can update directly.
prev.nodeValue = next.nodeValue;
} else {
// we have to replace the node.
prev.parentNode.replaceChild(next, prev);
}
}
/*
* @private
* @description
* Utility that will update one list of attributes to match another.
*
* @param {HTMLEntity} parent - The current parentNode being updated.
* @param {Attributes} prev - The previous attributes.
* @param {Attributes} next - The updated attributes.
*/
function setAttributes(parent, prev, next) {
var i, a, b, ns;
// Remove old attributes.
for (i = prev.length; i--;) {
a = prev[i];
ns = a.namespaceURI;
b = next.getNamedItemNS(ns, a.name);
if (!b) prev.removeNamedItemNS(ns, a.name);
}
// Set new attributes.
for (i = next.length; i--;) {
a = next[i];
ns = a.namespaceURI;
b = prev.getNamedItemNS(ns, a.name);
if (!b) {
// Add a new attribute.
next.removeNamedItemNS(ns, a.name);
prev.setNamedItemNS(a);
} else if (b.value !== a.value) {
// Update existing attribute.
b.value = a.value;
}
}
}
/*
* @private
* @description
* Utility that will update one list of childNodes to match another.
*
* @param {HTMLEntity} parent - The current parentNode being updated.
* @param {NodeList} prevChildNodes - The previous children.
* @param {NodeList} nextChildNodes - The updated children.
*/
function setChildNodes(parent, prevChildNodes, nextChildNodes) {
var key, a, b, oldPosition, newPosition;
// Convert nodelists into a usuable map.
var prev = keyNodes(prevChildNodes);
var next = keyNodes(nextChildNodes);
// Remove old nodes.
for (key in prev) {
if (next[key]) continue;
parent.removeChild(prev[key]);
}
// Set new nodes.
for (key in next) {
a = prev[key];
b = next[key];
if (a) {
// Update an existing node.
setNode(a, b);
// Check if the node has moved in the tree.
oldPosition = a[NODE_INDEX];
newPosition = b[NODE_INDEX];
if (oldPosition === newPosition) continue;
// Check if the node has already been properly positioned.
if (prevChildNodes[newPosition] === a) continue;
// Reposition node.
parent.insertBefore(a, prevChildNodes[newPosition]);
} else {
// Append the new node.
parent.appendChild(b);
}
}
}
/**
* @private
* @description
* Converts a nodelist into a keyed map.
* This is used for diffing while keeping elements with 'data-key' or 'id' if possible.
*
* @param {NodeList} childNodes - The childNodes to convert.
* @return {Object}
*/
function keyNodes(childNodes) {
var result = {};
for (var i = childNodes.length, el; i--;) {
el = childNodes[i];
el[NODE_INDEX] = i;
result[getKey(el) || i] = el;
}
return result;
}
/**
* @private
* @description
* Utility to try to pull a key out of an element.
* (Uses 'id' if possible and falls back to 'data-key')
*
* @param {HTMLEntity} node - The node to get the key for.
* @return {String}
*/
function getKey(node) {
if (node.nodeType !== ELEMENT_TYPE) return;
return node.getAttribute('data-key') || node.id;
}
/**
* Confirm that a value is truthy, throws an error message otherwise.
*
* @param {*} val - the val to test.
* @param {String} msg - the error message on failure.
* @throws Error
*/
function assert(val, msg) {
if (!val) throw new Error('set-dom: ' + msg);
}
exports.default = setDOM;
/***/ }
/******/ ])
});
;