omi v0.3.0 - parse the component string by html2json.js

This commit is contained in:
kmdjs 2017-02-18 19:39:50 +08:00
parent 54335b371d
commit d3964587b9
11 changed files with 1599 additions and 340 deletions

358
dist/omi.js vendored
View File

@ -1,5 +1,5 @@
/*!
* Omi v0.2.2 By dntzhang
* Omi v0.3.0 By dntzhang
* Github: https://github.com/AlloyTeam/omi
* MIT Licensed.
*/
@ -1003,8 +1003,6 @@ return /******/ (function(modules) { // webpackBootstrap
value: true
});
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 _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);
@ -1023,6 +1021,10 @@ return /******/ (function(modules) { // webpackBootstrap
var _diff2 = _interopRequireDefault(_diff);
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"); } }
@ -1323,11 +1325,6 @@ return /******/ (function(modules) { // webpackBootstrap
_this7._childrenInstalled(child);
});
}
}, {
key: '_getConstructorNameByMagic',
value: function _getConstructorNameByMagic(c) {
return (c + "").split("(")[0].replace("function", "").trim();
}
}, {
key: '_fixForm',
value: function _fixForm() {
@ -1388,7 +1385,7 @@ return /******/ (function(modules) { // webpackBootstrap
if (isFirst) {
var parentData = arr ? this._extractPropertyFromString(RegExp.$1, this.parent) : null;
var groupArr = childStr.match(/\s+group-data=['|"](\S*)['|"][\s+|/]/);
this.data = Object.assign(this.data, this._getDataset(childStr), parentData, groupArr ? this._extractPropertyFromString(RegExp.$1, this.parent)[this._omiGroupDataIndex] : null);
this.data = Object.assign(this.data, this._dataset, parentData, groupArr ? this._extractPropertyFromString(RegExp.$1, this.parent)[this._omiGroupDataIndex] : null);
} else {
if (this.dataFirst) {
this.data = Object.assign({}, this._getDataset(childStr), this.data);
@ -1426,27 +1423,17 @@ return /******/ (function(modules) { // webpackBootstrap
}
}, {
key: '_getDataset',
value: function _getDataset(str) {
value: function _getDataset(childStr) {
var _this8 = this;
var arr = str.match(/\s+data-(\S*)=['|"](\S*)['|"]/g);
if (arr) {
var _ret = function () {
var obj = {};
arr.forEach(function (item) {
var arr = item.split('=');
obj[_this8._capitalize(arr[0].replace(/\s+data-/, ''))] = arr[1].replace(/['|"]/g, '');
arr = null;
});
return {
v: obj
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
//this.BODY_ELEMENT.innerHTML = str ;
//return this.BODY_ELEMENT.firstChild.dataset;
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
Object.keys(attr).forEach(function (key) {
if (key.indexOf('data-') === 0) {
_this8._dataset[_this8._capitalize(key.replace('data-', ''))] = attr[key];
}
});
return this._dataset;
}
}, {
key: '_capitalize',
@ -1471,25 +1458,23 @@ return /******/ (function(modules) { // webpackBootstrap
}, {
key: '_extractChildren',
value: function _extractChildren(child) {
var _this9 = this;
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*)['|"][\s+|/]/);
var name = RegExp.$1;
var cmi = this.children[i];
arr.forEach(function (childStr, i) {
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
var name = attr.tag;
delete attr.tag;
var cmi = _this9.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))) {
if (cmi && cmi.___omi_constructor_name === name) {
cmi._childRender(childStr);
continue;
} else {
(function () {
var ChildClass = _omi2['default'].getClassFromString(name);
@ -1497,48 +1482,42 @@ return /******/ (function(modules) { // webpackBootstrap
var sub_child = new ChildClass(Object.assign({}, child.childrenData[i]), false);
sub_child._omiChildStr = childStr;
sub_child.parent = child;
sub_child.___omi_constructor_name = name;
sub_child._dataset = {};
var evtArr = childStr.match(/[\s\t\n]+on(\S*)=['|"](\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];
Object.keys(attr).forEach(function (key) {
var value = attr[key];
if (key.indexOf('on') === 0) {
var handler = sub_child.parent[value];
if (handler) {
sub_child.data[evtArr[0]] = handler.bind(sub_child.parent);
sub_child.data[key] = handler.bind(sub_child.parent);
}
});
}
var groupNameArr = childStr.match(/\s+group-data=['|"](\S*)['|"][\s+|/]/);
if (groupNameArr) {
if (child._omiGroupDataCounter.hasOwnProperty(RegExp.$1)) {
child._omiGroupDataCounter[RegExp.$1]++;
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[RegExp.$1];
} else {
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[RegExp.$1] = 0;
} else if (key === 'group-data') {
if (child._omiGroupDataCounter.hasOwnProperty(value)) {
child._omiGroupDataCounter[value]++;
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value];
} else {
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value] = 0;
}
} else if (key === 'omi-id') {
_omi2['default'].mapping[value] = sub_child;
} else if (key === 'name') {
child[value] = sub_child;
} else if (key.indexOf('data-') === 0) {
sub_child._dataset[_this9._capitalize(key.replace('data-', ''))] = value;
}
}
});
sub_child._childRender(childStr, true);
var mo_ids = childStr.match(/omi-id=['|"](\S*)['|"][\s+|/]/);
if (mo_ids) {
_omi2['default'].mapping[RegExp.$1] = sub_child;
}
if (!cmi) {
child.children.push(sub_child);
} else {
child.children[i] = sub_child;
}
var nameArr = childStr.match(/\s+name=['|"](\S*)['|"][\s+|/]/);
if (nameArr) {
child[RegExp.$1] = sub_child;
}
sub_child._childRender(childStr, true);
})();
}
}
});
}
}
}]);
@ -1852,6 +1831,249 @@ return /******/ (function(modules) { // webpackBootstrap
exports['default'] = setDOM;
/***/ },
/* 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("</") == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
}
// start tag
} else if (html.indexOf("<") == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf("<");
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? "" : html.substring(index);
if (handler.chars) handler.chars(text);
}
} else {
html = html.replace(new RegExp("([\\s\\S]*?)<\/" + stack.last() + "[^>]*>"), 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 <img src="hoge.png"/>
// 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;
/***/ }
/******/ ])
});

358
dist/omi.lite.js vendored
View File

@ -1,5 +1,5 @@
/*!
* Omi v0.2.2 By dntzhang
* Omi v0.3.0 By dntzhang
* Github: https://github.com/AlloyTeam/omi
* MIT Licensed.
*/
@ -386,8 +386,6 @@ return /******/ (function(modules) { // webpackBootstrap
value: true
});
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 _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);
@ -406,6 +404,10 @@ return /******/ (function(modules) { // webpackBootstrap
var _diff2 = _interopRequireDefault(_diff);
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"); } }
@ -706,11 +708,6 @@ return /******/ (function(modules) { // webpackBootstrap
_this7._childrenInstalled(child);
});
}
}, {
key: '_getConstructorNameByMagic',
value: function _getConstructorNameByMagic(c) {
return (c + "").split("(")[0].replace("function", "").trim();
}
}, {
key: '_fixForm',
value: function _fixForm() {
@ -771,7 +768,7 @@ return /******/ (function(modules) { // webpackBootstrap
if (isFirst) {
var parentData = arr ? this._extractPropertyFromString(RegExp.$1, this.parent) : null;
var groupArr = childStr.match(/\s+group-data=['|"](\S*)['|"][\s+|/]/);
this.data = Object.assign(this.data, this._getDataset(childStr), parentData, groupArr ? this._extractPropertyFromString(RegExp.$1, this.parent)[this._omiGroupDataIndex] : null);
this.data = Object.assign(this.data, this._dataset, parentData, groupArr ? this._extractPropertyFromString(RegExp.$1, this.parent)[this._omiGroupDataIndex] : null);
} else {
if (this.dataFirst) {
this.data = Object.assign({}, this._getDataset(childStr), this.data);
@ -809,27 +806,17 @@ return /******/ (function(modules) { // webpackBootstrap
}
}, {
key: '_getDataset',
value: function _getDataset(str) {
value: function _getDataset(childStr) {
var _this8 = this;
var arr = str.match(/\s+data-(\S*)=['|"](\S*)['|"]/g);
if (arr) {
var _ret = function () {
var obj = {};
arr.forEach(function (item) {
var arr = item.split('=');
obj[_this8._capitalize(arr[0].replace(/\s+data-/, ''))] = arr[1].replace(/['|"]/g, '');
arr = null;
});
return {
v: obj
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
//this.BODY_ELEMENT.innerHTML = str ;
//return this.BODY_ELEMENT.firstChild.dataset;
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
Object.keys(attr).forEach(function (key) {
if (key.indexOf('data-') === 0) {
_this8._dataset[_this8._capitalize(key.replace('data-', ''))] = attr[key];
}
});
return this._dataset;
}
}, {
key: '_capitalize',
@ -854,25 +841,23 @@ return /******/ (function(modules) { // webpackBootstrap
}, {
key: '_extractChildren',
value: function _extractChildren(child) {
var _this9 = this;
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*)['|"][\s+|/]/);
var name = RegExp.$1;
var cmi = this.children[i];
arr.forEach(function (childStr, i) {
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
var name = attr.tag;
delete attr.tag;
var cmi = _this9.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))) {
if (cmi && cmi.___omi_constructor_name === name) {
cmi._childRender(childStr);
continue;
} else {
(function () {
var ChildClass = _omi2['default'].getClassFromString(name);
@ -880,48 +865,42 @@ return /******/ (function(modules) { // webpackBootstrap
var sub_child = new ChildClass(Object.assign({}, child.childrenData[i]), false);
sub_child._omiChildStr = childStr;
sub_child.parent = child;
sub_child.___omi_constructor_name = name;
sub_child._dataset = {};
var evtArr = childStr.match(/[\s\t\n]+on(\S*)=['|"](\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];
Object.keys(attr).forEach(function (key) {
var value = attr[key];
if (key.indexOf('on') === 0) {
var handler = sub_child.parent[value];
if (handler) {
sub_child.data[evtArr[0]] = handler.bind(sub_child.parent);
sub_child.data[key] = handler.bind(sub_child.parent);
}
});
}
var groupNameArr = childStr.match(/\s+group-data=['|"](\S*)['|"][\s+|/]/);
if (groupNameArr) {
if (child._omiGroupDataCounter.hasOwnProperty(RegExp.$1)) {
child._omiGroupDataCounter[RegExp.$1]++;
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[RegExp.$1];
} else {
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[RegExp.$1] = 0;
} else if (key === 'group-data') {
if (child._omiGroupDataCounter.hasOwnProperty(value)) {
child._omiGroupDataCounter[value]++;
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value];
} else {
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value] = 0;
}
} else if (key === 'omi-id') {
_omi2['default'].mapping[value] = sub_child;
} else if (key === 'name') {
child[value] = sub_child;
} else if (key.indexOf('data-') === 0) {
sub_child._dataset[_this9._capitalize(key.replace('data-', ''))] = value;
}
}
});
sub_child._childRender(childStr, true);
var mo_ids = childStr.match(/omi-id=['|"](\S*)['|"][\s+|/]/);
if (mo_ids) {
_omi2['default'].mapping[RegExp.$1] = sub_child;
}
if (!cmi) {
child.children.push(sub_child);
} else {
child.children[i] = sub_child;
}
var nameArr = childStr.match(/\s+name=['|"](\S*)['|"][\s+|/]/);
if (nameArr) {
child[RegExp.$1] = sub_child;
}
sub_child._childRender(childStr, true);
})();
}
}
});
}
}
}]);
@ -1235,6 +1214,249 @@ return /******/ (function(modules) { // webpackBootstrap
exports['default'] = setDOM;
/***/ },
/* 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("</") == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
}
// start tag
} else if (html.indexOf("<") == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf("<");
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? "" : html.substring(index);
if (handler.chars) handler.chars(text);
}
} else {
html = html.replace(new RegExp("([\\s\\S]*?)<\/" + stack.last() + "[^>]*>"), 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 <img src="hoge.png"/>
// 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;
/***/ }
/******/ ])
});

356
dist/omi.server.js vendored
View File

@ -1011,8 +1011,6 @@
value: true
});
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 _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);
@ -1031,6 +1029,10 @@
var _diff2 = _interopRequireDefault(_diff);
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"); } }
@ -1331,11 +1333,6 @@
_this7._childrenInstalled(child);
});
}
}, {
key: '_getConstructorNameByMagic',
value: function _getConstructorNameByMagic(c) {
return (c + "").split("(")[0].replace("function", "").trim();
}
}, {
key: '_fixForm',
value: function _fixForm() {
@ -1396,7 +1393,7 @@
if (isFirst) {
var parentData = arr ? this._extractPropertyFromString(RegExp.$1, this.parent) : null;
var groupArr = childStr.match(/\s+group-data=['|"](\S*)['|"][\s+|/]/);
this.data = Object.assign(this.data, this._getDataset(childStr), parentData, groupArr ? this._extractPropertyFromString(RegExp.$1, this.parent)[this._omiGroupDataIndex] : null);
this.data = Object.assign(this.data, this._dataset, parentData, groupArr ? this._extractPropertyFromString(RegExp.$1, this.parent)[this._omiGroupDataIndex] : null);
} else {
if (this.dataFirst) {
this.data = Object.assign({}, this._getDataset(childStr), this.data);
@ -1434,27 +1431,17 @@
}
}, {
key: '_getDataset',
value: function _getDataset(str) {
value: function _getDataset(childStr) {
var _this8 = this;
var arr = str.match(/\s+data-(\S*)=['|"](\S*)['|"]/g);
if (arr) {
var _ret = function () {
var obj = {};
arr.forEach(function (item) {
var arr = item.split('=');
obj[_this8._capitalize(arr[0].replace(/\s+data-/, ''))] = arr[1].replace(/['|"]/g, '');
arr = null;
});
return {
v: obj
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
//this.BODY_ELEMENT.innerHTML = str ;
//return this.BODY_ELEMENT.firstChild.dataset;
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
Object.keys(attr).forEach(function (key) {
if (key.indexOf('data-') === 0) {
_this8._dataset[_this8._capitalize(key.replace('data-', ''))] = attr[key];
}
});
return this._dataset;
}
}, {
key: '_capitalize',
@ -1479,25 +1466,23 @@
}, {
key: '_extractChildren',
value: function _extractChildren(child) {
var _this9 = this;
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*)['|"][\s+|/]/);
var name = RegExp.$1;
var cmi = this.children[i];
arr.forEach(function (childStr, i) {
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
var name = attr.tag;
delete attr.tag;
var cmi = _this9.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))) {
if (cmi && cmi.___omi_constructor_name === name) {
cmi._childRender(childStr);
continue;
} else {
(function () {
var ChildClass = _omi2['default'].getClassFromString(name);
@ -1505,48 +1490,42 @@
var sub_child = new ChildClass(Object.assign({}, child.childrenData[i]), false);
sub_child._omiChildStr = childStr;
sub_child.parent = child;
sub_child.___omi_constructor_name = name;
sub_child._dataset = {};
var evtArr = childStr.match(/[\s\t\n]+on(\S*)=['|"](\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];
Object.keys(attr).forEach(function (key) {
var value = attr[key];
if (key.indexOf('on') === 0) {
var handler = sub_child.parent[value];
if (handler) {
sub_child.data[evtArr[0]] = handler.bind(sub_child.parent);
sub_child.data[key] = handler.bind(sub_child.parent);
}
});
}
var groupNameArr = childStr.match(/\s+group-data=['|"](\S*)['|"][\s+|/]/);
if (groupNameArr) {
if (child._omiGroupDataCounter.hasOwnProperty(RegExp.$1)) {
child._omiGroupDataCounter[RegExp.$1]++;
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[RegExp.$1];
} else {
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[RegExp.$1] = 0;
} else if (key === 'group-data') {
if (child._omiGroupDataCounter.hasOwnProperty(value)) {
child._omiGroupDataCounter[value]++;
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value];
} else {
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value] = 0;
}
} else if (key === 'omi-id') {
_omi2['default'].mapping[value] = sub_child;
} else if (key === 'name') {
child[value] = sub_child;
} else if (key.indexOf('data-') === 0) {
sub_child._dataset[_this9._capitalize(key.replace('data-', ''))] = value;
}
}
});
sub_child._childRender(childStr, true);
var mo_ids = childStr.match(/omi-id=['|"](\S*)['|"][\s+|/]/);
if (mo_ids) {
_omi2['default'].mapping[RegExp.$1] = sub_child;
}
if (!cmi) {
child.children.push(sub_child);
} else {
child.children[i] = sub_child;
}
var nameArr = childStr.match(/\s+name=['|"](\S*)['|"][\s+|/]/);
if (nameArr) {
child[RegExp.$1] = sub_child;
}
sub_child._childRender(childStr, true);
})();
}
}
});
}
}
}]);
@ -1860,6 +1839,249 @@
exports['default'] = setDOM;
/***/ },
/* 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("</") == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
}
// start tag
} else if (html.indexOf("<") == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf("<");
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? "" : html.substring(index);
if (handler.chars) handler.chars(text);
}
} else {
html = html.replace(new RegExp("([\\s\\S]*?)<\/" + stack.last() + "[^>]*>"), 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 <img src="hoge.png"/>
// 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;
/***/ }
/******/ ])
});

View File

@ -72,9 +72,14 @@
}
_createClass(App, [{
key: 'SFDSF',
value: function SFDSF() {
alert(2);
}
}, {
key: 'render',
value: function render() {
return '\n <div>\n <Hello data-name="Omi" />\n </div>\n ';
return '\n <div>\n <Hello data-name="Omi"\n data-img="<img src=\'http://images2015.cnblogs.com/blog/105416/201701/105416-20170120114244046-622856943.png\' >"\n onXX="SFDSF"\n onXXX="SFDSdF"\n omi-id="aa" />\n </div>\n ';
}
}]);
@ -125,11 +130,12 @@
key: 'handleClick',
value: function handleClick(target, evt) {
alert(target.innerHTML);
this.data.onXX();
}
}, {
key: 'render',
value: function render() {
return '\n <div>\n \t<h1 onclick="handleClick(this, event)">Hello ,{{name}}!</h1>\n </div>\n \t\t';
return '\n <div>\n{{{img}}}\n \t<h1 onclick="handleClick(this, event)">Hello ,{{name}}!</h1>\n </div>\n \t\t';
}
}]);
@ -409,6 +415,57 @@
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;
};
module.exports = Omi;
/***/ },
@ -1055,6 +1112,10 @@
var _diff2 = _interopRequireDefault(_diff);
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"); } }
@ -1070,9 +1131,9 @@
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 = this._data = JSON.parse(this._hidden.value);
this.data = JSON.parse(this._hidden.value);
} else {
this.data = this._data = data || {};
this.data = data || {};
this._omi_server_rendering = server;
this.id = this._omi_server_rendering ? 1000000 + _omi2['default'].getInstanceId() : _omi2['default'].getInstanceId();
}
@ -1083,8 +1144,11 @@
this._addedItems = [];
this._omi_order = [];
_omi2['default'].instances[this.id] = this;
this.dataFirst = true;
this._omi_scoped_attr = _omi2['default'].STYLESCOPEDPREFIX + this.id;
//this.BODY_ELEMENT = document.createElement('body');
this._preCSS = null;
this._omiGroupDataCounter = {};
if (this._omi_server_rendering || isReRendering) {
this.install();
this._render(true);
@ -1128,6 +1192,10 @@
this.node = hdNode;
} else {
(0, _diff2['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();
}
}
//update added components
@ -1265,7 +1333,7 @@
}
//get node prop from parent node
if (this.renderTo) {
this.node = document.querySelector("[" + _omi2['default'].STYLESCOPEDPREFIX + this.id + "]");
this.node = document.querySelector("[" + this._omi_scoped_attr + "]");
this._queryElements(this);
this._fixForm();
}
@ -1279,7 +1347,7 @@
this.HTML = '<input type="hidden" omi_scoped_' + this.id + ' >';
return this.HTML;
}
childStr = childStr.replace("<child", "<div").replace("/>", "></div>");
//childStr = childStr.replace("<child", "<div").replace("/>", "></div>");
this._mergeData(childStr, isFirst);
this._generateHTMLCSS();
this._extractChildren(this);
@ -1298,6 +1366,7 @@
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
@ -1307,30 +1376,46 @@
}, {
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;
var _this5 = this;
var nodes = _omi2['default'].$$('*[ref]', this.node);
nodes.forEach(function (node) {
if (node.hasAttribute(_this5._omi_scoped_attr)) {
_this5.refs[node.getAttribute('ref')] = node;
}
});
var attr = this.node.getAttribute('ref');
if (attr) {
this.refs[attr] = this.node;
}
}
}, {
key: '_execPlugins',
value: function _execPlugins() {
var _this6 = this;
Object.keys(_omi2['default'].plugins).forEach(function (item) {
var nodes = _omi2['default'].$$('*[' + item + ']', _this6.node);
nodes.forEach(function (node) {
if (node.hasAttribute(_this6._omi_scoped_attr)) {
_omi2['default'].plugins[item](node, _this6);
}
});
if (_this6.node.hasAttribute(item)) {
_omi2['default'].plugins[item](_this6.node, _this6);
}
});
}
}, {
key: '_childrenInstalled',
value: function _childrenInstalled(root) {
var _this5 = this;
var _this7 = this;
root.children.forEach(function (child) {
child.installed();
_this5._childrenInstalled(child);
_this7._childrenInstalled(child);
});
}
}, {
key: '_getConstructorNameByMagic',
value: function _getConstructorNameByMagic(c) {
return (c + "").split("(")[0].replace("function", "").trim();
}
}, {
key: '_fixForm',
value: function _fixForm() {
@ -1349,6 +1434,10 @@
}
});
_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) {
@ -1377,15 +1466,24 @@
value: function _createHiddenNode() {
var hdNode = document.createElement("input");
hdNode.setAttribute("type", "hidden");
hdNode.setAttribute(_omi2['default'].STYLESCOPEDPREFIX + this.id, "");
hdNode.setAttribute(this._omi_scoped_attr, '');
return hdNode;
}
}, {
key: '_mergeData',
value: function _mergeData(childStr, isFirst) {
var arr = childStr.match(/\s*data=['|"](\S*)['|"]/);
this.data = Object.assign({}, this._getDataset(childStr), arr ? this.parent[RegExp.$1] : null, this._data);
console.log(this._getDataset(childStr));
var arr = childStr.match(/\s+data=['|"](\S*)['|"][\s+|/]/);
if (isFirst) {
var parentData = arr ? this._extractPropertyFromString(RegExp.$1, this.parent) : null;
var groupArr = childStr.match(/\s+group-data=['|"](\S*)['|"][\s+|/]/);
this.data = Object.assign(this.data, this._dataset, parentData, groupArr ? this._extractPropertyFromString(RegExp.$1, this.parent)[this._omiGroupDataIndex] : null);
} else {
if (this.dataFirst) {
this.data = Object.assign({}, this._getDataset(childStr), this.data);
} else {
this.data = Object.assign({}, this.data, this._getDataset(childStr));
}
}
isFirst && this.install();
}
}, {
@ -1393,14 +1491,14 @@
value: function _generateHTMLCSS() {
this.CSS = this.style() || '';
if (this.CSS) {
this.CSS = _style2['default'].scoper(this.CSS, "[" + _omi2['default'].STYLESCOPEDPREFIX + this.id + "]");
this.CSS = _style2['default'].scoper(this.CSS, "[" + this._omi_scoped_attr + "]");
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), _omi2['default'].STYLESCOPEDPREFIX + this.id).trim();
this.HTML = this._scopedAttr(_omi2['default'].template(tpl ? tpl : "", this.data), this._omi_scoped_attr).trim();
if (this._omi_server_rendering) {
this.HTML = '\r\n<style id="' + _omi2['default'].STYLEPREFIX + this.id + '">\r\n' + this.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';
@ -1416,19 +1514,17 @@
}
}, {
key: '_getDataset',
value: function _getDataset(str) {
console.log(str);
var obj = {};
var arr = str.match(/data-(\S*)=['|"](\S*)['|"]/g);
arr.forEach(function (item) {
var arr = item.split('=');
obj[_capitalize(arr[0].replace('data-', ''))] = arr[1].replace(/['|"]/g, '');
arr = null;
value: function _getDataset(childStr) {
var _this8 = this;
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
Object.keys(attr).forEach(function (key) {
if (key.indexOf('data-') === 0) {
_this8._dataset[_this8._capitalize(key.replace('data-', ''))] = attr[key];
}
});
console.log(obj);
return obj;
//this.BODY_ELEMENT.innerHTML = str ;
//return this.BODY_ELEMENT.firstChild.dataset;
return this._dataset;
}
}, {
key: '_capitalize',
@ -1439,67 +1535,80 @@
}).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: '_extractChildren',
value: function _extractChildren(child) {
var _this9 = this;
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];
arr.forEach(function (childStr, i) {
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
var name = attr.tag;
delete attr.tag;
var cmi = _this9.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))) {
if (cmi && cmi.___omi_constructor_name === name) {
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);
var sub_child = new ChildClass(Object.assign({}, child.childrenData[i]), false);
sub_child._omiChildStr = childStr;
sub_child.parent = child;
sub_child.___omi_constructor_name = name;
sub_child._dataset = {};
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];
Object.keys(attr).forEach(function (key) {
var value = attr[key];
if (key.indexOf('on') === 0) {
var handler = sub_child.parent[value];
if (handler) {
sub_child.data[evtArr[0]] = handler.bind(sub_child.parent);
sub_child.data[key] = handler.bind(sub_child.parent);
}
});
}
sub_child._childRender(childStr, true);
} else if (key === 'group-data') {
if (child._omiGroupDataCounter.hasOwnProperty(value)) {
child._omiGroupDataCounter[value]++;
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value];
} else {
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value] = 0;
}
} else if (key === 'omi-id') {
_omi2['default'].mapping[value] = sub_child;
} else if (key === 'name') {
child[value] = sub_child;
} else if (key.indexOf('data-') === 0) {
sub_child._dataset[_this9._capitalize(key.replace('data-', ''))] = value;
}
});
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;
}
var nameArr = childStr.match(/\s*name=['|"](\S*)['|"]/);
if (nameArr) {
child[RegExp.$1] = sub_child;
}
sub_child._childRender(childStr, true);
})();
}
}
});
}
}
}]);
@ -1585,7 +1694,7 @@
});
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) {
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 + "].";
});
@ -1609,6 +1718,12 @@
var HTML_ELEMENT = document.createElement('html');
var BODY_ELEMENT = document.createElement('body');
var isIE = function isIE(ver) {
var b = document.createElement('b');
b.innerHTML = '<!--[if IE ' + ver + ']><i></i><![endif]-->';
return b.getElementsByTagName('i').length === 1;
};
/**
* @description
* Updates existing dom to match a new dom.
@ -1634,6 +1749,10 @@
}
}
if (isIE(8)) {
prev.parentNode.replaceChild(next, prev);
return;
}
// Update the node.
setNode(prev, next);
}
@ -1803,5 +1922,248 @@
exports['default'] = setDOM;
/***/ },
/* 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("</") == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
}
// start tag
} else if (html.indexOf("<") == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf("<");
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? "" : html.substring(index);
if (handler.chars) handler.chars(text);
}
} else {
html = html.replace(new RegExp("([\\s\\S]*?)<\/" + stack.last() + "[^>]*>"), 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 <img src="hoge.png"/>
// 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;
/***/ }
/******/ ]);

View File

@ -13,10 +13,12 @@ class Hello extends Omi.Component {
}
handleClick(target, evt){
alert(target.innerHTML);
this.data.onXX();
}
render() {
return `
<div>
{{{img}}}
<h1 onclick="handleClick(this, event)">Hello ,{{name}}!</h1>
</div>
`;

View File

@ -8,10 +8,18 @@ class App extends Omi.Component {
super(data);
}
SFDSF(){
alert(2)
}
render() {
return `
<div>
<Hello data-name="Omi" />
<Hello data-name="Omi"
data-img="<img src='http://images2015.cnblogs.com/blog/105416/201701/105416-20170120114244046-622856943.png' >"
onXX="SFDSF"
onXXX="SFDSdF"
omi-id="aa" />
</div>
`;

View File

@ -1,6 +1,6 @@
{
"name": "omi",
"version": "0.2.2",
"version": "0.3.0",
"description": "Open and modern framework for building user interfaces.",
"main": "dist/omi.js",
"scripts": {

View File

@ -2,6 +2,7 @@ import Omi from './omi.js';
import style from './style.js';
import scopedEvent from './event.js';
import setDOM from './diff.js';
import html2json from './html2json.js';
class Component {
constructor(data, server) {
@ -269,10 +270,6 @@ class Component {
})
}
_getConstructorNameByMagic(c){
return (c+"").split("(")[0].replace("function","").trim();
}
_fixForm (){
Omi.$$('input',this.node).forEach(element =>{
@ -329,7 +326,7 @@ class Component {
if(isFirst) {
let parentData = arr ? this._extractPropertyFromString(RegExp.$1, this.parent) : null;
let groupArr = childStr.match(/\s+group-data=['|"](\S*)['|"][\s+|/]/);
this.data = Object.assign(this.data, this._getDataset(childStr), parentData, groupArr ? this._extractPropertyFromString(RegExp.$1, this.parent)[this._omiGroupDataIndex] : null);
this.data = Object.assign(this.data, this._dataset, parentData, groupArr ? this._extractPropertyFromString(RegExp.$1, this.parent)[this._omiGroupDataIndex] : null);
}else{
if(this.dataFirst){
this.data = Object.assign({},this._getDataset(childStr),this.data);
@ -364,19 +361,15 @@ class Component {
});
}
_getDataset(str) {
let arr = str.match(/\s+data-(\S*)=['|"](\S*)['|"]/g);
if(arr) {
let obj = {};
arr.forEach(item => {
let arr = item.split('=');
obj[this._capitalize(arr[0].replace(/\s+data-/, ''))] = arr[1].replace(/['|"]/g, '');
arr = null;
});
return obj;
}
//this.BODY_ELEMENT.innerHTML = str ;
//return this.BODY_ELEMENT.firstChild.dataset;
_getDataset(childStr) {
let json = html2json(childStr);
let attr = json.child[0].attr;
Object.keys(attr).forEach(key => {
if(key.indexOf('data-') === 0){
this._dataset[this._capitalize(key.replace('data-', ''))] = attr[key];
}
});
return this._dataset;
}
_capitalize (str){
@ -398,74 +391,63 @@ class Component {
}
_extractChildren(child) {
_extractChildren(child){
if (Omi.customTags.length > 0) {
child.HTML = this._replaceTags(Omi.customTags, child.HTML);
}
let arr = child.HTML.match(/<child[^>][\s\S]*?tag=['|"](\S*)['|"][\s\S]*?\/>/g);
if (arr) {
const len = arr.length;
for (let i = 0; i < len; i++) {
let childStr = arr[i];
childStr.match(/\s+tag=['|"](\S*)['|"][\s+|/]/);
let name = RegExp.$1;
if(arr){
arr.forEach( (childStr, i) =>{
let json = html2json(childStr);
let attr = json.child[0].attr;
let name = attr.tag;
delete attr.tag;
let 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))) {
if (cmi && cmi.___omi_constructor_name === name) {
cmi._childRender(childStr);
continue;
} else {
let ChildClass = Omi.getClassFromString(name);
if (!ChildClass) throw "Can't find Class called [" + name+"]";
let sub_child = new ChildClass( Object.assign({},child.childrenData[i] ),false);
sub_child._omiChildStr = childStr;
sub_child.parent = child;
sub_child.___omi_constructor_name = name;
sub_child._dataset = {};
let evtArr = childStr.match(/[\s\t\n]+on(\S*)=['|"](\S*)['|"][\s+|/]/g);
if(evtArr) {
evtArr.forEach((item) => {
let evtArr = item.trim().split("=");
let hdName = evtArr[1].replace(/['|"]/g, "");
let handler = sub_child.parent[hdName];
Object.keys(attr).forEach(key => {
const value = attr[key];
if (key.indexOf('on') === 0) {
let handler = sub_child.parent[value];
if (handler) {
sub_child.data[evtArr[0]] = handler.bind(sub_child.parent);
sub_child.data[key] = handler.bind(sub_child.parent);
}
})
}
let groupNameArr = childStr.match(/\s+group-data=['|"](\S*)['|"][\s+|/]/);
if (groupNameArr) {
if(child._omiGroupDataCounter.hasOwnProperty(RegExp.$1)){
child._omiGroupDataCounter[RegExp.$1]++;
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[RegExp.$1];
}else{
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[RegExp.$1] = 0;
} else if (key === 'group-data') {
if (child._omiGroupDataCounter.hasOwnProperty(value)) {
child._omiGroupDataCounter[value]++;
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value];
} else {
sub_child._omiGroupDataIndex = child._omiGroupDataCounter[value] = 0;
}
} else if (key === 'omi-id'){
Omi.mapping[value] = sub_child;
}else if (key === 'name'){
child[value] = sub_child;
}else if(key.indexOf('data-') === 0){
sub_child._dataset[this._capitalize(key.replace('data-', ''))] = value;
}
}
});
sub_child._childRender(childStr,true);
let mo_ids = childStr.match(/omi-id=['|"](\S*)['|"][\s+|/]/);
if (mo_ids) {
Omi.mapping[RegExp.$1] = sub_child;
}
if (!cmi) {
child.children.push(sub_child);
} else {
child.children[i] = sub_child;
}
let nameArr = childStr.match(/\s+name=['|"](\S*)['|"][\s+|/]/);
if (nameArr) {
child[RegExp.$1] = sub_child;
}
sub_child._childRender(childStr,true);
}
}
});
}
}
}

239
src/html2json.js Normal file
View File

@ -0,0 +1,239 @@
/*
* 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 (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("</") == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
}
// start tag
} else if (html.indexOf("<") == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf("<");
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? "" : html.substring(index);
if (handler.chars)
handler.chars(text);
}
} else {
html = html.replace(new RegExp("([\\s\\S]*?)<\/" + stack.last() + "[^>]*>"), 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(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 <img src="hoge.png"/>
// add to parents
var parent = bufArray[0] || results;
if (parent.child === undefined) {
parent.child = [];
}
parent.child.push(node);
} else {
bufArray.unshift(node);
}
},
end: function(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(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;
};
export default html2json;

View File

@ -21,7 +21,7 @@ class Hello extends Omi.Component {
}
}
var hello =Omi.render(new Hello({ name:'dntzhang'}),'body');
var hello = Omi.render(new Hello({ name:'dntzhang'}),'body');
describe("A suite is just a function", function() {
@ -66,10 +66,10 @@ describe("_replaceTags ", function() {
describe("_getDataset ", function() {
var dataset = hello._getDataset('<div data-a="a" data-b="b"></div>');
hello._dataset = {};
hello._getDataset('<div data-a="a" data-b="b"></div>');
it("_getDataset", function() {
expect(dataset.a).toBe('a');
expect(hello._dataset.a).toBe('a');
});
});

View File

@ -72,7 +72,7 @@ if(ENV === 'build'){
},
plugins: [
// Avoid publishing files when compilation fails
new webpack.BannerPlugin(" Omi v0.2.2 By dntzhang \r\n Github: https://github.com/AlloyTeam/omi\r\n MIT Licensed."),
new webpack.BannerPlugin(" Omi v0.3.0 By dntzhang \r\n Github: https://github.com/AlloyTeam/omi\r\n MIT Licensed."),
new webpack.NoErrorsPlugin()
],
stats: {