curvature
Version:

1,275 lines (1,259 loc) • 79.4 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.View = void 0;
var _Bindable = require("./Bindable");
var _ViewList = require("./ViewList");
var _Router = require("./Router");
var _Uuid = require("./Uuid");
var _Dom = require("./Dom");
var _Tag = require("./Tag");
var _Bag = require("./Bag");
var _RuleSet = require("./RuleSet");
var _Mixin = require("./Mixin");
var _PromiseMixin = require("../mixin/PromiseMixin");
var _EventTargetMixin = require("../mixin/EventTargetMixin");
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var dontParse = Symbol('dontParse');
var expandBind = Symbol('expandBind');
var uuid = Symbol('uuid');
var moveIndex = 0;
var View = /*#__PURE__*/function (_Mixin$with) {
_inherits(View, _Mixin$with);
var _super = _createSuper(View);
function View() {
var _this;
var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var mainView = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
_classCallCheck(this, View);
_this = _super.call(this, args, mainView);
_this[_EventTargetMixin.EventTargetMixin.EventTargetParent] = mainView;
Object.defineProperty(_assertThisInitialized(_this), 'args', {
value: _Bindable.Bindable.make(args)
});
Object.defineProperty(_assertThisInitialized(_this), uuid, {
value: _this.constructor.uuid()
});
Object.defineProperty(_assertThisInitialized(_this), 'nodesAttached', {
value: new _Bag.Bag(function (i, s, a) {})
});
Object.defineProperty(_assertThisInitialized(_this), 'nodesDetached', {
value: new _Bag.Bag(function (i, s, a) {})
});
Object.defineProperty(_assertThisInitialized(_this), '_onRemove', {
value: new _Bag.Bag(function (i, s, a) {})
});
Object.defineProperty(_assertThisInitialized(_this), 'cleanup', {
value: []
});
Object.defineProperty(_assertThisInitialized(_this), 'parent', {
value: mainView
});
Object.defineProperty(_assertThisInitialized(_this), 'views', {
value: new Map()
});
Object.defineProperty(_assertThisInitialized(_this), 'viewLists', {
value: new Map()
});
Object.defineProperty(_assertThisInitialized(_this), 'withViews', {
value: new Map()
});
Object.defineProperty(_assertThisInitialized(_this), 'tags', {
value: _Bindable.Bindable.make({})
});
Object.defineProperty(_assertThisInitialized(_this), 'nodes', {
value: _Bindable.Bindable.make([])
});
Object.defineProperty(_assertThisInitialized(_this), 'timeouts', {
value: new Map()
});
Object.defineProperty(_assertThisInitialized(_this), 'intervals', {
value: []
});
Object.defineProperty(_assertThisInitialized(_this), 'frames', {
value: []
});
Object.defineProperty(_assertThisInitialized(_this), 'ruleSet', {
value: new _RuleSet.RuleSet()
});
Object.defineProperty(_assertThisInitialized(_this), 'preRuleSet', {
value: new _RuleSet.RuleSet()
});
Object.defineProperty(_assertThisInitialized(_this), 'subBindings', {
value: {}
});
Object.defineProperty(_assertThisInitialized(_this), 'templates', {
value: {}
});
Object.defineProperty(_assertThisInitialized(_this), 'eventCleanup', {
value: []
});
Object.defineProperty(_assertThisInitialized(_this), 'unpauseCallbacks', {
value: new Map()
});
Object.defineProperty(_assertThisInitialized(_this), 'interpolateRegex', {
value: /(\[\[((?:\$+)?[\w\.\|-]+)\]\])/g
});
Object.defineProperty(_assertThisInitialized(_this), 'rendered', {
value: new Promise(function (accept, reject) {
return Object.defineProperty(_assertThisInitialized(_this), 'renderComplete', {
value: accept
});
})
});
_this.onRemove(function () {
if (!_this[_EventTargetMixin.EventTargetMixin.Parent]) {
return;
}
_this[_EventTargetMixin.EventTargetMixin.Parent] = null;
});
_this.controller = _assertThisInitialized(_this);
_this.template = "";
_this.firstNode = null;
_this.lastNode = null;
_this.viewList = null;
_this.mainView = null;
_this.preserve = false;
_this.removed = false;
_this.loaded = Promise.resolve(_assertThisInitialized(_this));
// return Bindable.make(this);
return _this;
}
_createClass(View, [{
key: "_id",
get: function get() {
return this[uuid];
}
}, {
key: "onFrame",
value: function onFrame(callback) {
var _this2 = this;
var stopped = false;
var cancel = function cancel() {
stopped = true;
};
var c = function c(timestamp) {
if (_this2.removed || stopped) {
return;
}
if (!_this2.paused) {
callback(Date.now());
}
requestAnimationFrame(c);
};
requestAnimationFrame(function () {
return c(Date.now());
});
this.frames.push(cancel);
return cancel;
}
}, {
key: "onNextFrame",
value: function onNextFrame(callback) {
return requestAnimationFrame(function () {
return callback(Date.now());
});
}
}, {
key: "onIdle",
value: function onIdle(callback) {
return requestIdleCallback(function () {
return callback(Date.now());
});
}
}, {
key: "onTimeout",
value: function onTimeout(time, callback) {
var _this3 = this;
var timeoutInfo = {
timeout: null,
callback: null,
time: time,
fired: false,
created: new Date().getTime(),
paused: false
};
var wrappedCallback = function wrappedCallback() {
callback();
timeoutInfo.fired = true;
_this3.timeouts["delete"](timeoutInfo.timeout);
};
var timeout = setTimeout(wrappedCallback, time);
timeoutInfo.callback = wrappedCallback;
timeoutInfo.timeout = timeout;
this.timeouts.set(timeoutInfo.timeout, timeoutInfo);
return timeout;
}
}, {
key: "clearTimeout",
value: function (_clearTimeout) {
function clearTimeout(_x) {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return _clearTimeout.toString();
};
return clearTimeout;
}(function (timeout) {
var _iterator = _createForOfIteratorHelper(this.timeouts),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
callback = _step$value[0],
timeoutInfo = _step$value[1];
clearTimeout(timeoutInfo.timeout);
this.timeouts["delete"](timeoutInfo.timeout);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
})
}, {
key: "onInterval",
value: function onInterval(time, callback) {
var timeout = setInterval(callback, time);
this.intervals.push({
timeout: timeout,
callback: callback,
time: time,
paused: false
});
return timeout;
}
}, {
key: "clearInterval",
value: function (_clearInterval) {
function clearInterval(_x2) {
return _clearInterval.apply(this, arguments);
}
clearInterval.toString = function () {
return _clearInterval.toString();
};
return clearInterval;
}(function (timeout) {
for (var i in this.intervals) {
if (timeout === this.intervals[i].timeout) {
clearInterval(this.intervals[i].timeout);
delete this.intervals[i];
}
}
})
}, {
key: "pause",
value: function pause() {
var paused = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
if (paused === undefined) {
this.paused = !this.paused;
}
this.paused = paused;
if (this.paused) {
var _iterator2 = _createForOfIteratorHelper(this.timeouts),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _step2$value = _slicedToArray(_step2.value, 2),
callback = _step2$value[0],
timeout = _step2$value[1];
if (timeout.fired) {
this.timeouts["delete"](timeout.timeout);
continue;
}
clearTimeout(timeout.timeout);
timeout.paused = true;
timeout.time = Math.max(0, timeout.time - (Date.now() - timeout.created));
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
for (var i in this.intervals) {
clearInterval(this.intervals[i].timeout);
}
} else {
var _iterator3 = _createForOfIteratorHelper(this.timeouts),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var _step3$value = _slicedToArray(_step3.value, 2),
_callback = _step3$value[0],
_timeout = _step3$value[1];
if (!_timeout.paused) {
continue;
}
if (_timeout.fired) {
this.timeouts["delete"](_timeout.timeout);
continue;
}
_timeout.timeout = setTimeout(_timeout.callback, _timeout.time);
_timeout.paused = false;
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
for (var _i2 in this.intervals) {
if (!this.intervals[_i2].timeout.paused) {
continue;
}
this.intervals[_i2].timeout.paused = false;
this.intervals[_i2].timeout = setInterval(this.intervals[_i2].callback, this.intervals[_i2].time);
}
var _iterator4 = _createForOfIteratorHelper(this.unpauseCallbacks),
_step4;
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var _step4$value = _slicedToArray(_step4.value, 2),
_callback2 = _step4$value[1];
_callback2();
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
this.unpauseCallbacks.clear();
}
var _iterator5 = _createForOfIteratorHelper(this.viewLists),
_step5;
try {
for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
var _step5$value = _slicedToArray(_step5.value, 2),
tag = _step5$value[0],
viewList = _step5$value[1];
viewList.pause(!!paused);
}
} catch (err) {
_iterator5.e(err);
} finally {
_iterator5.f();
}
for (var _i3 in this.tags) {
if (Array.isArray(this.tags[_i3])) {
for (var j in this.tags[_i3]) {
this.tags[_i3][j].pause(!!paused);
}
continue;
}
this.tags[_i3].pause(!!paused);
}
}
}, {
key: "render",
value: function render() {
var _this$nodes,
_this4 = this;
var parentNode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var insertPoint = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (parentNode instanceof View) {
parentNode = parentNode.firstNode.parentNode;
}
if (insertPoint instanceof View) {
insertPoint = insertPoint.firstNode;
}
if (this.firstNode) {
return this.reRender(parentNode, insertPoint);
}
this.dispatchEvent(new CustomEvent('render'));
var templateParsed = this.template instanceof DocumentFragment ? this.template.cloneNode(true) : View.templates.has(this.template);
var subDoc = templateParsed ? this.template instanceof DocumentFragment ? templateParsed : View.templates.get(this.template).cloneNode(true) : document.createRange().createContextualFragment(this.template);
if (!templateParsed && !(this.template instanceof DocumentFragment)) {
View.templates.set(this.template, subDoc.cloneNode(true));
}
this.mainView || this.preRuleSet.apply(subDoc, this);
this.mapTags(subDoc);
this.mainView || this.ruleSet.apply(subDoc, this);
if (window.devMode === true) {
this.firstNode = document.createComment("Template ".concat(this._id, " Start"));
this.lastNode = document.createComment("Template ".concat(this._id, " End"));
} else {
this.firstNode = document.createTextNode('');
this.lastNode = document.createTextNode('');
}
(_this$nodes = this.nodes).push.apply(_this$nodes, [this.firstNode].concat(_toConsumableArray(Array.from(subDoc.childNodes)), [this.lastNode]));
this.postRender(parentNode);
this.dispatchEvent(new CustomEvent('rendered'));
if (!this.dispatchAttach()) {
return;
}
if (parentNode) {
var rootNode = parentNode.getRootNode();
if (insertPoint) {
parentNode.insertBefore(this.firstNode, insertPoint);
parentNode.insertBefore(this.lastNode, insertPoint);
} else {
parentNode.appendChild(this.firstNode);
parentNode.appendChild(this.lastNode);
}
parentNode.insertBefore(subDoc, this.lastNode);
moveIndex++;
if (rootNode.isConnected) {
this.attached(rootNode, parentNode);
this.dispatchAttached(rootNode, parentNode);
} else {
var firstDomAttach = function firstDomAttach(event) {
if (!event.target.isConnected) {
return;
}
_this4.attached(rootNode, parentNode);
_this4.dispatchAttached(rootNode, parentNode);
parentNode.removeEventListener('cvDomAttached', firstDomAttach);
};
parentNode.addEventListener('cvDomAttached', firstDomAttach);
}
}
this.renderComplete(this.nodes);
return this.nodes;
}
}, {
key: "dispatchAttach",
value: function dispatchAttach() {
return this.dispatchEvent(new CustomEvent('attach', {
cancelable: true,
target: this
}));
}
}, {
key: "dispatchAttached",
value: function dispatchAttached(rootNode, parentNode) {
var view = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
this.dispatchEvent(new CustomEvent('attached', {
detail: {
view: view || this,
node: parentNode,
root: rootNode,
mainView: this
}
}));
this.dispatchDomAttached(view);
var _iterator6 = _createForOfIteratorHelper(this.nodesAttached.items()),
_step6;
try {
for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
var callback = _step6.value;
callback(rootNode, parentNode);
}
} catch (err) {
_iterator6.e(err);
} finally {
_iterator6.f();
}
}
}, {
key: "dispatchDomAttached",
value: function dispatchDomAttached(view) {
var _this5 = this;
this.nodes.filter(function (n) {
return n.nodeType !== Node.COMMENT_NODE;
}).forEach(function (child) {
if (!child.matches) {
return;
}
_Dom.Dom.mapTags(child, false, function (tag, walker) {
if (!tag.matches) {
return;
}
tag.dispatchEvent(new CustomEvent('cvDomAttached', {
target: tag,
detail: {
view: view || _this5,
mainView: _this5
}
}));
});
child.dispatchEvent(new CustomEvent('cvDomAttached', {
target: child,
detail: {
view: view || _this5,
mainView: _this5
}
}));
});
}
}, {
key: "reRender",
value: function reRender(parentNode, insertPoint) {
var willReRender = this.dispatchEvent(new CustomEvent('reRender'), {
cancelable: true,
target: this
});
if (!willReRender) {
return;
}
var subDoc = new DocumentFragment();
if (this.firstNode.isConnected) {
var detach = this.nodesDetached.items();
for (var i in detach) {
detach[i]();
}
}
subDoc.append.apply(subDoc, _toConsumableArray(this.nodes));
if (parentNode) {
if (insertPoint) {
parentNode.insertBefore(this.firstNode, insertPoint);
parentNode.insertBefore(this.lastNode, insertPoint);
} else {
parentNode.appendChild(this.firstNode);
parentNode.appendChild(this.lastNode);
}
parentNode.insertBefore(subDoc, this.lastNode);
this.dispatchEvent(new CustomEvent('reRendered'), {
cancelable: true,
target: this
});
var rootNode = parentNode.getRootNode();
if (rootNode.isConnected) {
this.attached(rootNode, parentNode);
this.dispatchAttached(rootNode, parentNode);
}
}
return this.nodes;
}
}, {
key: "mapTags",
value: function mapTags(subDoc) {
var _this6 = this;
_Dom.Dom.mapTags(subDoc, false, function (tag, walker) {
if (tag[dontParse]) {
return;
}
if (tag.matches) {
tag = _this6.mapInterpolatableTag(tag);
tag = tag.matches('[cv-template]') && _this6.mapTemplateTag(tag) || tag;
tag = tag.matches('[cv-slot]') && _this6.mapSlotTag(tag) || tag;
tag = tag.matches('[cv-prerender]') && _this6.mapPrendererTag(tag) || tag;
tag = tag.matches('[cv-link]') && _this6.mapLinkTag(tag) || tag;
tag = tag.matches('[cv-attr]') && _this6.mapAttrTag(tag) || tag;
tag = tag.matches('[cv-expand]') && _this6.mapExpandableTag(tag) || tag;
tag = tag.matches('[cv-ref]') && _this6.mapRefTag(tag) || tag;
tag = tag.matches('[cv-on]') && _this6.mapOnTag(tag) || tag;
tag = tag.matches('[cv-each]') && _this6.mapEachTag(tag) || tag;
tag = tag.matches('[cv-bind]') && _this6.mapBindTag(tag) || tag;
tag = tag.matches('[cv-with]') && _this6.mapWithTag(tag) || tag;
tag = tag.matches('[cv-if]') && _this6.mapIfTag(tag) || tag;
tag = tag.matches('[cv-view]') && _this6.mapViewTag(tag) || tag;
} else {
tag = _this6.mapInterpolatableTag(tag);
}
if (tag !== walker.currentNode) {
walker.currentNode = tag;
}
});
}
}, {
key: "mapExpandableTag",
value: function mapExpandableTag(tag) {
/*/
const tagCompiler = this.compileExpandableTag(tag);
const newTag = tagCompiler(this);
tag.replaceWith(newTag);
return newTag;
/*/
var existing = tag[expandBind];
if (existing) {
existing();
tag[expandBind] = false;
}
var _Bindable$resolve = _Bindable.Bindable.resolve(this.args, tag.getAttribute('cv-expand'), true),
_Bindable$resolve2 = _slicedToArray(_Bindable$resolve, 2),
proxy = _Bindable$resolve2[0],
expandProperty = _Bindable$resolve2[1];
tag.removeAttribute('cv-expand');
if (!proxy[expandProperty]) {
proxy[expandProperty] = {};
}
proxy[expandProperty] = _Bindable.Bindable.make(proxy[expandProperty]);
this.onRemove(tag[expandBind] = proxy[expandProperty].bindTo(function (v, k, t, d, p) {
if (d || v === undefined) {
tag.removeAttribute(k, v);
return;
}
if (v === null) {
tag.setAttribute(k, '');
return;
}
tag.setAttribute(k, v);
}));
// let expandProperty = tag.getAttribute('cv-expand');
// let expandArg = Bindable.makeBindable(
// this.args[expandProperty] || {}
// );
// tag.removeAttribute('cv-expand');
// for(let i in expandArg)
// {
// if(i === 'name' || i === 'type')
// {
// continue;
// }
// let debind = expandArg.bindTo(i, ((tag,i)=>(v)=>{
// tag.setAttribute(i, v);
// })(tag,i));
// this.onRemove(()=>{
// debind();
// if(expandArg.isBound())
// {
// Bindable.clearBindings(expandArg);
// }
// });
// }
return tag;
//*/
}
}, {
key: "compileExpandableTag",
value: function compileExpandableTag(sourceTag) {
return function (bindingView) {
var tag = sourceTag.cloneNode(true);
var expandProperty = tag.getAttribute('cv-expand');
var expandArg = _Bindable.Bindable.make(bindingView.args[expandProperty] || {});
tag.removeAttribute('cv-expand');
var _loop = function _loop() {
if (i === 'name' || i === 'type') {
return "continue";
}
var debind = expandArg.bindTo(i, function (tag, i) {
return function (v) {
tag.setAttribute(i, v);
};
}(tag, i));
bindingView.onRemove(function () {
debind();
if (expandArg.isBound()) {
_Bindable.Bindable.clearBindings(expandArg);
}
});
};
for (var i in expandArg) {
var _ret = _loop();
if (_ret === "continue") continue;
}
return tag;
};
}
}, {
key: "mapAttrTag",
value: function mapAttrTag(tag) {
//*/
var tagCompiler = this.compileAttrTag(tag);
var newTag = tagCompiler(this);
tag.replaceWith(newTag);
return newTag;
/*/
let attrProperty = tag.getAttribute('cv-attr');
tag.removeAttribute('cv-attr');
let pairs = attrProperty.split(',');
let attrs = pairs.map((p) => p.split(':'));
for (let i in attrs)
{
let proxy = this.args;
let bindProperty = attrs[i][1];
let property = bindProperty;
if(bindProperty.match(/\./))
{
[proxy, property] = Bindable.resolve(
this.args
, bindProperty
, true
);
}
let attrib = attrs[i][0];
this.onRemove(proxy.bindTo(
property
, (v)=>{
if(v == null)
{
tag.setAttribute(attrib, '');
return;
}
tag.setAttribute(attrib, v);
}
));
}
return tag;
//*/
}
}, {
key: "compileAttrTag",
value: function compileAttrTag(sourceTag) {
var attrProperty = sourceTag.getAttribute('cv-attr');
var pairs = attrProperty.split(/[,;]/);
var attrs = pairs.map(function (p) {
return p.split(':');
});
sourceTag.removeAttribute('cv-attr');
return function (bindingView) {
var tag = sourceTag.cloneNode(true);
var _loop2 = function _loop2() {
var bindProperty = attrs[i][1] || attrs[i][0];
var _Bindable$resolve3 = _Bindable.Bindable.resolve(bindingView.args, bindProperty, true),
_Bindable$resolve4 = _slicedToArray(_Bindable$resolve3, 2),
proxy = _Bindable$resolve4[0],
property = _Bindable$resolve4[1];
var attrib = attrs[i][0];
bindingView.onRemove(proxy.bindTo(property, function (v, k, t, d) {
if (d || v === undefined) {
tag.removeAttribute(attrib, v);
return;
}
if (v === null) {
tag.setAttribute(attrib, '');
return;
}
tag.setAttribute(attrib, v);
}));
};
for (var i in attrs) {
_loop2();
}
return tag;
};
}
}, {
key: "mapInterpolatableTag",
value: function mapInterpolatableTag(tag) {
var _this7 = this;
var regex = this.interpolateRegex;
if (tag.nodeType === Node.TEXT_NODE) {
var original = tag.nodeValue;
if (!this.interpolatable(original)) {
return tag;
}
var header = 0;
var match;
var _loop3 = function _loop3() {
var bindProperty = match[2];
var unsafeHtml = false;
var unsafeView = false;
var propertySplit = bindProperty.split('|');
var transformer = false;
if (propertySplit.length > 1) {
transformer = _this7.stringTransformer(propertySplit.slice(1));
bindProperty = propertySplit[0];
}
if (bindProperty.substr(0, 2) === '$$') {
unsafeHtml = true;
unsafeView = true;
bindProperty = bindProperty.substr(2);
}
if (bindProperty.substr(0, 1) === '$') {
unsafeHtml = true;
bindProperty = bindProperty.substr(1);
}
if (bindProperty.substr(0, 3) === '000') {
expand = true;
bindProperty = bindProperty.substr(3);
return "continue";
}
var staticPrefix = original.substring(header, match.index);
header = match.index + match[1].length;
var staticNode = document.createTextNode(staticPrefix);
staticNode[dontParse] = true;
tag.parentNode.insertBefore(staticNode, tag);
var dynamicNode;
if (unsafeHtml) {
dynamicNode = document.createElement('div');
} else {
dynamicNode = document.createTextNode('');
}
dynamicNode[dontParse] = true;
var proxy = _this7.args;
var property = bindProperty;
if (bindProperty.match(/\./)) {
var _Bindable$resolve5 = _Bindable.Bindable.resolve(_this7.args, bindProperty, true);
var _Bindable$resolve6 = _slicedToArray(_Bindable$resolve5, 2);
proxy = _Bindable$resolve6[0];
property = _Bindable$resolve6[1];
}
tag.parentNode.insertBefore(dynamicNode, tag);
if (_typeof(proxy) !== 'object') {
return "break";
}
proxy = _Bindable.Bindable.make(proxy);
var debind = proxy.bindTo(property, function (v, k, t) {
if (t[k] !== v && (t[k] instanceof View || t[k] instanceof Node || t[k] instanceof _Tag.Tag)) {
if (!t[k].preserve) {
t[k].remove();
}
}
dynamicNode.nodeValue = '';
if (unsafeView && !(v instanceof View)) {
var _v;
var unsafeTemplate = (_v = v) !== null && _v !== void 0 ? _v : '';
v = new View(_this7.args, _this7);
v.template = unsafeTemplate;
}
if (transformer) {
v = transformer(v);
}
if (v instanceof View) {
v[_EventTargetMixin.EventTargetMixin.EventTargetParent] = _this7;
var onAttach = function onAttach(rootNode, parentNode) {
v.dispatchAttached(rootNode, parentNode, _this7);
};
_this7.nodesAttached.add(onAttach);
v.render(tag.parentNode, dynamicNode);
var cleanup = function cleanup() {
if (!v.preserve) {
v.remove();
}
};
_this7.onRemove(cleanup);
v.onRemove(function () {
_this7.nodesAttached.remove(onAttach);
_this7._onRemove.remove(cleanup);
});
} else if (v instanceof Node) {
tag.parentNode.insertBefore(v, dynamicNode);
_this7.onRemove(function () {
return v.remove();
});
} else if (v instanceof _Tag.Tag) {
if (v.node) {
tag.parentNode.insertBefore(v.node, dynamicNode);
_this7.onRemove(function () {
return v.remove();
});
} else {
v.remove();
}
} else {
if (v instanceof Object && v.__toString instanceof Function) {
v = v.__toString();
}
if (unsafeHtml) {
dynamicNode.innerHTML = v;
} else {
dynamicNode.nodeValue = v;
}
}
dynamicNode[dontParse] = true;
});
_this7.onRemove(debind);
};
while (match = regex.exec(original)) {
var _ret2 = _loop3();
if (_ret2 === "continue") continue;
if (_ret2 === "break") break;
}
var staticSuffix = original.substring(header);
var staticNode = document.createTextNode(staticSuffix);
staticNode[dontParse] = true;
tag.parentNode.insertBefore(staticNode, tag);
tag.nodeValue = '';
} else if (tag.nodeType === Node.ELEMENT_NODE) {
var _loop4 = function _loop4() {
if (!_this7.interpolatable(tag.attributes[i].value)) {
return "continue";
}
var header = 0;
var match;
var original = tag.attributes[i].value;
var attribute = tag.attributes[i];
var bindProperties = {};
var segments = [];
while (match = regex.exec(original)) {
segments.push(original.substring(header, match.index));
if (!bindProperties[match[2]]) {
bindProperties[match[2]] = [];
}
bindProperties[match[2]].push(segments.length);
segments.push(match[1]);
header = match.index + match[1].length;
}
segments.push(original.substring(header));
var _loop5 = function _loop5() {
var proxy = _this7.args;
var property = j;
var propertySplit = j.split('|');
var transformer = false;
var longProperty = j;
if (propertySplit.length > 1) {
transformer = _this7.stringTransformer(propertySplit.slice(1));
property = propertySplit[0];
}
if (property.match(/\./)) {
var _Bindable$resolve7 = _Bindable.Bindable.resolve(_this7.args, property, true);
var _Bindable$resolve8 = _slicedToArray(_Bindable$resolve7, 2);
proxy = _Bindable$resolve8[0];
property = _Bindable$resolve8[1];
}
var matching = [];
var bindProperty = j;
var matchingSegments = bindProperties[longProperty];
// const changeAttribute = (v, k, t, d) => {
// tag.setAttribute(attribute.name, segments.join(''));
// };
_this7.onRemove(proxy.bindTo(property, function (v, k, t, d) {
if (transformer) {
v = transformer(v);
}
for (var _i4 in bindProperties) {
for (var _j in bindProperties[longProperty]) {
segments[bindProperties[longProperty][_j]] = t[_i4];
if (k === property) {
segments[bindProperties[longProperty][_j]] = v;
}
}
}
if (!_this7.paused) {
// changeAttribute(v,k,t,d);
tag.setAttribute(attribute.name, segments.join(''));
} else {
// this.unpauseCallbacks.set(attribute, () => changeAttribute(v,k,t,d));
_this7.unpauseCallbacks.set(attribute, function () {
return tag.setAttribute(attribute.name, segments.join(''));
});
}
}));
_this7.onRemove(function () {
if (!proxy.isBound()) {
_Bindable.Bindable.clearBindings(proxy);
}
});
};
for (var j in bindProperties) {
_loop5();
}
};
for (var i = 0; i < tag.attributes.length; i++) {
var _ret3 = _loop4();
if (_ret3 === "continue") continue;
}
}
return tag;
}
}, {
key: "mapRefTag",
value: function mapRefTag(tag) {
var refAttr = tag.getAttribute('cv-ref');
var _refAttr$split = refAttr.split(':'),
_refAttr$split2 = _slicedToArray(_refAttr$split, 3),
refProp = _refAttr$split2[0],
_refAttr$split2$ = _refAttr$split2[1],
refClassname = _refAttr$split2$ === void 0 ? null : _refAttr$split2$,
_refAttr$split2$2 = _refAttr$split2[2],
refKey = _refAttr$split2$2 === void 0 ? null : _refAttr$split2$2;
var refClass = _Tag.Tag;
if (refClassname) {
refClass = this.stringToClass(refClassname);
}
tag.removeAttribute('cv-ref');
Object.defineProperty(tag, '___tag___', {
enumerable: false,
writable: true
});
this.onRemove(function () {
tag.___tag___ = null;
tag.remove();
});
var parent = this;
var direct = this;
if (this.viewList) {
parent = this.viewList.parent;
// if(!this.viewList.parent.tags[refProp])
// {
// this.viewList.parent.tags[refProp] = [];
// }
// let refKeyVal = this.args[refKey];
// this.viewList.parent.tags[refProp][refKeyVal] = new refClass(
// tag, this, refProp, refKeyVal
// );
} else {
// this.tags[refProp] = new refClass(
// tag, this, refProp
// );
}
var tagObject = new refClass(tag, this, refProp, undefined, direct);
tag.___tag___ = tagObject;
this.tags[refProp] = tagObject;
while (parent) {
var refKeyVal = this.args[refKey];
if (refKeyVal !== undefined) {
if (!parent.tags[refProp]) {
parent.tags[refProp] = [];
}
parent.tags[refProp][refKeyVal] = tagObject;
} else {
parent.tags[refProp] = tagObject;
}
if (!parent.parent) {
break;
}
parent = parent.parent;
}
return tag;
}
}, {
key: "mapBindTag",
value: function mapBindTag(tag) {
var _this8 = this;
var bindArg = tag.getAttribute('cv-bind');
var proxy = this.args;
var property = bindArg;
var top = null;
if (bindArg.match(/\./)) {
var _Bindable$resolve9 = _Bindable.Bindable.resolve(this.args, bindArg, true);
var _Bindable$resolve10 = _slicedToArray(_Bindable$resolve9, 3);
proxy = _Bindable$resolve10[0];
property = _Bindable$resolve10[1];
top = _Bindable$resolve10[2];
}
if (proxy !== this.args) {
this.subBindings[bindArg] = this.subBindings[bindArg] || [];
this.onRemove(this.args.bindTo(top, function () {
while (_this8.subBindings.length) {
_this8.subBindings.shift()();
}
}));
}
var unsafeHtml = false;
if (property.substr(0, 1) === '$') {
property = property.substr(1);
unsafeHtml = true;
}
var debind = proxy.bindTo(property, function (v, k, t, d, p) {
if ((p instanceof View || p instanceof Node || p instanceof _Tag.Tag) && p !== v) {
p.remove();
}
var autoChangedEvent = new CustomEvent('cvAutoChanged', {
bubbles: true
});
if (['INPUT', 'SELECT', 'TEXTAREA'].includes(tag.tagName)) {
var _type = tag.getAttribute('type');
if (_type && _type.toLowerCase() === 'checkbox') {
tag.checked = !!v;
tag.dispatchEvent(autoChangedEvent);
} else if (_type && _type.toLowerCase() === 'radio') {
tag.checked = v == tag.value;
tag.dispatchEvent(autoChangedEvent);
} else if (_type !== 'file') {
if (tag.tagName === 'SELECT') {
var selectOption = function selectOption() {
for (var i = 0; i < tag.options.length; i++) {
var option = tag.options[i];
if (option.value == v) {
tag.selectedIndex = i;
}
}
};
selectOption();
_this8.nodesAttached.add(selectOption);
} else {
tag.value = v == null ? '' : v;
}
tag.dispatchEvent(autoChangedEvent);
}
} else {
if (v instanceof View) {
var _iterator7 = _createForOfIteratorHelper(tag.childNodes),
_step7;
try {
for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
var node = _step7.value;
node.remove();
}
} catch (err) {
_iterator7.e(err);
} finally {
_iterator7.f();
}
var onAttach = function onAttach(parentNode) {
v.dispatchDomAttached(_this8);
// if(v.nodes.length && v.dispatchAttach())
// {
// v.attached(parentNode.getRootNode(), parentNode, this);
// v.dispatchAttached(parentNode.getRootNode(), parentNode, this);
// }
};
_this8.nodesAttached.add(onAttach);
v[_EventTargetMixin.EventTargetMixin.EventTargetParent] = _this8;
v.render(tag);
v.onRemove(function () {
return _this8.nodesAttached.remove(onAttach);
});
} else if (v instanceof Node) {
tag.insert(v);
} else if (v instanceof _Tag.Tag) {
tag.append(v.node);
} else if (unsafeHtml) {
if (tag.innerHTML !== v) {
v = String(v);
if (tag.innerHTML === v.substring(0, tag.innerHTML.length)) {
tag.innerHTML += v.substring(tag.innerHTML.length);
} else {
var _iterator8 = _createForOfIteratorHelper(tag.childNodes),
_step8;
try {
for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
var _node = _step8.value;
_node.remove();
}
} catch (err) {
_iterator8.e(err);
} finally {
_iterator8.f();
}
tag.innerHTML = v;
}
_Dom.Dom.mapTags(tag, false, function (t) {
return t[dontParse] = true;
});
}
} else {
if (tag.textContent !== v) {
var _iterator9 = _createForOfIteratorHelper(tag.childNodes),
_step9;
try {
for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
var _node2 = _step9.value;
_node2.remove();
}
} catch (err) {
_iterator9.e(err);
} finally {
_iterator9.f();
}
tag.textContent = v;
}
}
}
});
if (proxy !== this.args) {
this.subBindings[bindArg].push(debind);
}
this.onRemove(debind);
var type = tag.getAttribute('type');
var multi = tag.getAttribute('multiple');
var inputListener = function inputListener(event) {
if (event.target !== tag) {
return;
}
if (type && type.toLowerCase() === 'checkbox') {
if (tag.checked) {
proxy[property] = event.target.getAttribute('value');
} else {
proxy[property] = false;
}
} else if (event.target.matches('[contenteditable=true]')) {
proxy[property] = event.target.innerHTML;
} else if (type === 'file' && multi) {
var files = Array.from(event.target.files);
var current = proxy[property] || _Bindable.Bindable.onDeck(proxy, property);
if (!current || !files.length) {
proxy[property] = files;
} else {
var _loop6 = function _loop6(i) {
if (files[i] !== current[i]) {
files[i].toJSON = function () {
return {
name: file[i].name,
size: file[i].size,
type: file[i].type,
date: file[i].lastModified
};
};
current[i] = files[i];
return "break";
}
};
for (var i in files) {
var _ret4 = _loop6(i);
if (_ret4 === "break") break;
}
}
} else if (type === 'file' && !multi && event.target.files.length) {
var _file = event.target.files.item(0);
_file.toJSON = function () {
return {
name: _file.name,
size: _file.size,
type: _file.type,
date: _file.lastModified
};
};
proxy[property] = _file;
} else {
proxy[property] = event.target.value;
}
};
if (type === 'file' || type === 'radio') {
tag.addEventListener('change', inputListener);
} else {
tag.addEventListener('input', inputListener);
tag.addEventListener('change', inputListener);
tag.addEventListener('value-changed', inputListener);
}
this.onRemove(function () {
if (type === 'file' || type === 'radio') {
tag.removeEventListener('change', inputListener);
} else {
tag.removeEventListener('input', inputListener);
tag.removeEventListener('change', inputListener);
tag.removeEventListener('value-changed', inputListener);
}
});
tag.removeAttribute('cv-bind');
return tag;
}
}, {
key: "mapOnTag",
value: function mapOnTag(tag) {
var _this9 = this;
var referents = String(tag.getAttribute('cv-on'));
referents.split(';').map(function (a) {
return a.split(':');
}).forEach(function (a) {
a = a.map(function (a) {
return a.trim();
});
var argLen = a.length;
var eventName = String(a.shift()).trim();
var callbackName = String(a.shift() || eventName).trim();
var eventFlags = String(a.shift() || '').trim();
var argList = [];
var groups = /(\w+)(?:\(([$\w\s-'",]+)\))?/.exec(callbackName);
if (groups) {
callbackName = groups[1].replace(/(^[\s\n]+|[\s\n]+$)/, '');
if (groups[2]) {
argList = groups[2].split(',').map(function (s) {
return s.trim();
});
}
}
if (!argList.length) {
argList.push('$event');
}
if (!eventName || argLen === 1) {
eventName = callbackName;
}
var eventMethod;
var parent = _this9;
var _loop7 =