]+>).*?<\/card>/gi, function (_, tag) {
//获取Card属性
var attributes = getAttrMap(tag);
var type = attributes.type,
name = attributes.name,
value = attributes.value,
editable = attributes.editable;
var isInline = type === 'inline';
var tagName = isInline ? 'span' : 'div';
var list = ['<'.concat(tagName)];
list.push(' '.concat(CARD_TYPE_KEY, '="').concat(type || '', '"'));
list.push(' '.concat(READY_CARD_KEY, '="').concat(name || '', '"'));
if (editable !== '') list.push(' '.concat(CARD_EDITABLE_KEY, '="').concat(editable || 'false', '"'));
Object.keys(attributes).forEach(function (attrsName) {
if (attrsName.indexOf('data-') === 0 && attrsName.indexOf('data-card') !== 0) {
list.push(' '.concat(attrsName, '="').concat(attributes[attrsName] || '', '"'));
}
});
if (value !== undefined) {
list.push(' '.concat(CARD_VALUE_KEY, '="').concat(value, '"'));
}
list.push('>'.concat(tagName, '>'));
return list.join('');
});
};
/**
* 验证是否是合法的url地址
* @param url URL地址
*/
var validUrl = function validUrl(url) {
if (typeof url !== 'string') {
return false;
}
url = url.toLowerCase(); // https://developer.mozilla.org/en-US-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
if (url.startsWith('data:text/html')) {
return false;
}
if (!!!url.match(/^\S*$/)) {
return false;
}
if (!!['http:', 'https:', 'data:', 'ftp:'].some(function (protocol) {
return url.startsWith(protocol);
})) {
return true;
}
if (url.startsWith('./') || url.startsWith('/')) {
return true;
}
if (url.indexOf(':') < 0) {
return true;
}
return false;
};
var sanitizeUrl = function sanitizeUrl(url) {
return validUrl(url) ? url : '';
};
/**
* 格式化编辑器值,移除光标标记标签,以及标签无效属性
* @param value
* @returns
*/
var formatEngineValue = function formatEngineValue(value) {
if (!value) return value;
var newValue = value.replace(/<(anchor|focus|cursor)[^>]*?\/>/gi, '');
return /^]*?)>
<\/p>$/i.test(newValue) ? value.replace(RegExp.$1, '') : value;
};
/**
* 格式化热键
* @param key 热键
*/
var formatHotkey = function formatHotkey(key) {
var keys = key.toLowerCase().split('+');
keys = keys.map(function (key) {
if (key === 'mod') {
return isMacos ? '⌘' : 'Ctrl';
} else if (key === 'opt') {
return isMacos ? 'Option' : 'Alt';
} else if (key.length > 1) {
return key.substr(0, 1).toUpperCase() + key.substr(1).toLowerCase();
}
return key.toUpperCase();
});
return keys.join('+');
};
/**
* 获取列表样式
* @param type 类型
* @param code
*/
var getListStyle = function getListStyle(type) {
var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (!(code = +code)) return '•';
switch (type === null || type === void 0 ? void 0 : type.toLowerCase()) {
case 'disc':
return '•';
case 'circle':
return '◦';
case 'square':
return '◼';
case 'lower-alpha':
return String.fromCharCode('a'.charCodeAt(0) + code);
case 'lower-roman':
return String.fromCharCode(8559 + code);
case 'decimal':
default:
return code;
}
};
var getDocument = function getDocument(node) {
if (typeof document === 'undefined' && typeof global['__amWindow'] === 'undefined') throw 'document is not defined,If you are using ssr, you can assign a value to the `__amWindow` global variable.';
return node ? node.ownerDocument || node['document'] || node : typeof document === 'undefined' ? global['__amWindow'].document : document;
};
/**
* 移除空的文本节点,并连接相邻的文本节点
* @param node 节点
*/
var combinText = function combinText(node) {
if (!(node instanceof Node)) node = node[0];
node.normalize();
};
/**
* 获取一个 dom 元素内所有的 textnode 类型的元素
* @param {Node} node - dom节点
* @param {Function} filter - 过滤器
* @return {Array} 获取的文本节点
*/
var getTextNodes = function getTextNodes(node, filter) {
var textNodes = [];
if (filter && !filter(node)) {
return textNodes;
}
var nodes = node.childNodes;
for (var i = 0; i < nodes.length; i++) {
var _node = nodes[i];
var nodeType = _node.nodeType;
if (nodeType === 3) {
textNodes.push(_node);
} else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
textNodes = textNodes.concat(getTextNodes(_node, filter));
}
}
return textNodes;
};
var getParentInRoot = function getParentInRoot(node) {
var _node$parentElement;
return node.nodeType === getDocument().ELEMENT_NODE && node.getAttribute(DATA_ELEMENT) === ROOT ? undefined : ((_node$parentElement = node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : node.parentNode) || undefined;
};
/**
* 是否是引擎
* @param editor 编辑器
*/
var isEngine = function isEngine(editor) {
return editor.kind === 'engine';
};
/**
* 是否是View
* @param editor 编辑器
*/
var isView = function isView(editor) {
return editor.kind === 'view';
};
var createMarkdownIt = function createMarkdownIt(editor) {
var presetName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
var markdown = new Markdown__default['default'](presetName, {
html: true,
typographer: true,
linkify: true
});
editor.trigger('markdown-it', markdown);
return markdown;
};
var convertMarkdown = function convertMarkdown(editor, markdown, tokens) {
var checkInline = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var renderer = markdown.renderer,
options = markdown.options;
var isHit = false;
var blockTags = editor.schema.getTags('blocks');
var textContent = '';
var nodeContent = [];
tokens.forEach(function (token, index) {
var type = token.type,
tag = token.tag,
children = token.children,
nesting = token.nesting;
var result = editor.trigger('markdown-it-token', {
token: token,
markdown: markdown,
callback: function callback(result) {
textContent += result;
}
});
if (result === false) {
isHit = true;
return;
}
var content = '';
if (type === 'inline' && children) {
var _renderer$renderInlin;
content = (_renderer$renderInlin = renderer.renderInline(children, options, {})) !== null && _renderer$renderInlin !== void 0 ? _renderer$renderInlin : '';
if (checkInline && children.find(function (child) {
return child.type === 'image' || child.type.endsWith('_inline') || child.type.endsWith('_open');
})) {
isHit = true;
}
} else if (typeof renderer.rules[type] !== 'undefined') {
var _renderer$rules$type;
content = (_renderer$rules$type = renderer.rules[type](tokens, index, options, {}, renderer)) !== null && _renderer$rules$type !== void 0 ? _renderer$rules$type : '';
} else {
var _renderer$renderToken;
content = (_renderer$renderToken = renderer.renderToken(tokens, index, options)) !== null && _renderer$renderToken !== void 0 ? _renderer$renderToken : '';
}
if (nesting === 1) {
nodeContent.push('');
textContent += content;
} else if (nesting === 0) {
if (nodeContent.length === 0) {
textContent += content;
if (tag && !isHit) isHit = true;
} else if (!!content) nodeContent[nodeContent.length - 1] += content;
} else if (nesting === -1) {
var _nodeContent;
if (nodeContent.length > 0 && !nodeContent[nodeContent.length - 1] && blockTags.includes(tag)) nodeContent[nodeContent.length - 1] += '
';
textContent += (_nodeContent = nodeContent[nodeContent.length - 1]) !== null && _nodeContent !== void 0 ? _nodeContent : '';
nodeContent.pop();
if (nodeContent.every(function (content) {
return !content;
})) nodeContent = [];
textContent += content;
if (!isHit && tag !== 'p') isHit = true;
}
});
if (isHit && textContent) return textContent;
return null;
};
var DATA_UUID = 'data-uuid';
var DATA_COLOR = 'data-color';
/**
* 事件
*/
var Event$1 = /*#__PURE__*/function () {
function Event() {
_classCallCheck(this, Event);
this.listeners = {};
}
_createClass(Event, [{
key: "on",
value:
/**
* 绑定事件
* @param {string} eventType 事件名称
* @param {Function} listener 事件处理方法
* @param {boolean} options 是否重写事件
*/
function on(eventType, listener, options) {
if (!this.listeners[eventType]) {
this.listeners[eventType] = [];
}
if (_typeof(options) !== 'object' || !options.once) this.listeners[eventType].push(listener);
}
/**
* 解除绑定
* @param {string} eventType
* @param listener
*/
}, {
key: "off",
value: function off(eventType, listener) {
var listeners = this.listeners[eventType];
if (!listeners) {
return;
}
for (var i = 0; i < listeners.length; i++) {
if (listeners[i] === listener) {
listeners.splice(i, 1);
break;
}
}
}
/**
* 触发事件
* @param eventType 事件类型
* @param args 事件参数
*/
}, {
key: "trigger",
value: function trigger(eventType) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var listeners = this.listeners[eventType];
if (listeners) {
var result = undefined;
listeners.every(function (listener) {
result = listener.apply(void 0, args);
return typeof result !== 'boolean' || result !== false;
});
return result;
}
return undefined;
}
}, {
key: "destroy",
value: function destroy() {
var _this = this;
Object.keys(this.listeners).forEach(function (type) {
_this.listeners[type].forEach(function (listener) {
_this.off(type, listener);
});
});
}
}]);
return Event;
}();
var isNodeEntry = function isNodeEntry(selector) {
return !!selector && selector.get !== undefined;
};
var isNodeList = function isNodeList(selector) {
return !!selector && selector.entries !== undefined;
};
var isNode = function isNode(selector) {
return !!selector && selector.nodeType !== undefined;
};
/**
* 如果元素被指定的选择器字符串选择,Element.matches() 方法返回true; 否则返回false。
* @param element 节点
* @param selector 选择器
*/
var isMatchesSelector = function isMatchesSelector(element, selector) {
if (element.nodeType !== Node.ELEMENT_NODE || !selector) {
return false;
}
var defaultMatches = function defaultMatches(element, selector) {
var _getDocument;
var matches = (_getDocument = getDocument(element)) === null || _getDocument === void 0 ? void 0 : _getDocument.querySelectorAll(selector),
i = matches ? matches.length : 0;
while (--i >= 0 && (matches === null || matches === void 0 ? void 0 : matches.item(i)) !== element) {}
return i > -1;
};
var matchesSelector = element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.msMatchesSelector || element.oMatchesSelector || element.matchesSelector || defaultMatches;
return matchesSelector.call(element, selector);
};
var isCard = function isCard(element) {
return element.nodeName === CARD_TAG || !!element.getAttribute(CARD_TYPE_KEY);
};
/**
* 判断当前节点是否为block类型的Card组件
*/
var isBlockCard = function isBlockCard(element) {
return 'block' === element.getAttribute(CARD_TYPE_KEY);
};
/**
* 判断当前节点是否为inline类型的Card组件
* @returns
*/
var isInlineCard = function isInlineCard(element) {
return 'inline' === element.getAttribute(CARD_TYPE_KEY);
};
/**
* 是否是可编辑器卡片
* @returns
*/
var isEditableCard = function isEditableCard(element) {
return element.getAttribute(DATA_ELEMENT) === EDITABLE || element.getAttribute(CARD_EDITABLE_KEY) === 'true' || !!(element === null || element === void 0 ? void 0 : element.querySelector(EDITABLE_SELECTOR));
};
/**
* 判断当前节点是否为根节点
*/
var isRoot = function isRoot(element, root) {
return element.getAttribute(DATA_ELEMENT) === ROOT && (!root || element === root);
};
var isEditable = function isEditable(element) {
return isRoot(element) || element.getAttribute(DATA_ELEMENT) === EDITABLE;
};
/**
* 判断当前是否在根节点内
*/
var inEditor = function inEditor(element, root) {
if (element.nodeType === Node.ELEMENT_NODE && isRoot(element, root)) {
return false;
}
var closetRoot = closest(element, ROOT_SELECTOR);
return !!closetRoot && (!root || closetRoot === root);
};
/**
* 是否是光标标记节点
* @returns
*/
var isCursor = function isCursor(element) {
var dataElement = element.getAttribute(DATA_ELEMENT);
return !!dataElement && [ANCHOR, FOCUS, CURSOR].indexOf(dataElement) > -1;
};
/**
* 根据查询器查询符合条件的离当前元素节点最近的父节点
* @param element 当前节点
* @param selector 查询器
* @return 返回一个 NodeEntry 实例
*/
var closest = function closest(element, selector) {
var callback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (node) {
return node.parentElement || undefined;
};
var node = element || undefined;
while (node) {
if (isMatchesSelector(node, selector)) {
return node;
}
node = callback(node);
}
return node;
};
/**
* 缓存selector创建的node
*/
var nodeCaches = new Map();
/**
* 解析节点
* @param selector 选择器
* @param isSpecialText 是否为特殊文本比如 \u200b 0宽字符
* @param context 上下文节点,默认使用 getDocument 获取document
*/
function domParser(selector, context) {
if (!selector) return []; //文本字符串
if (typeof selector === 'string') {
//特殊字符,或者html代码
var isTag = false;
if (!context || (isTag = /<[^>]+>/g.test(selector))) {
var isTr = selector.indexOf('
]*-->/g, '');
var cacheNode = nodeCaches.get(selector);
if (cacheNode) {
if (isTr) {
var tbody = cacheNode.querySelector('tbody');
return tbody ? tbody.cloneNode(true).childNodes : [];
}
if (isTd) {
var tr = cacheNode.querySelector('tr');
return tr ? tr.cloneNode(true).childNodes : [];
}
return cacheNode.cloneNode(true).childNodes;
}
/**
* 无法单独解析 tr、td 标签,如果有tr、td标签这里需要补充 table 节点的结构
*/
if (isTr) {
selector = '');
}
if (isTd) {
selector = '');
} //创建一个空节点,用来包裹需要生成的节点
var container = getDocument().createElement('div');
container.innerHTML = selector;
nodeCaches.set(selector, container.cloneNode(true));
if (isTr) {
var _tbody = container.querySelector('tbody');
return _tbody ? _tbody.childNodes : [];
}
if (isTd) {
var _tr = container.querySelector('tr');
return _tr ? _tr.childNodes : [];
} // 返回解析后的所有子级
return container.childNodes;
} //默认根据选择器查询所有
return context.querySelectorAll(selector);
} //类型为 NodeList ,node数组 直接返回
if (isNodeList(selector) || Array.isArray(selector)) {
return selector;
} //类型为 DOMNode 类型
if (isNodeEntry(selector)) {
var nodes = [];
selector.each(function (node) {
nodes.push(node);
});
return nodes;
} // 片段
if (isNode(selector) && selector.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
var _nodes = [];
var _iterator = _createForOfIteratorHelper(selector.childNodes),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
_nodes.push(child);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return _nodes;
} // 其他
return [selector];
}
/**
* 扩展 Node 类
* @class NodeEntry
* @constructor
* @param nodes 需要扩展的 NodeList
* @param context 节点上下文,或根节点
*/
var NodeEntry = /*#__PURE__*/function () {
function NodeEntry(nodes, context) {
var _this = this;
_classCallCheck(this, NodeEntry);
this.events = [];
this.document = null;
this.context = void 0;
this.name = '';
this.type = void 0;
this.window = null;
this.display = void 0;
this.fragment = void 0;
if (isNode(nodes)) {
if (nodes.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
this.fragment = nodes;
}
nodes = [nodes];
}
nodes.forEach(function (node, index) {
_this[index] = node;
_this.events[index] = new Event$1(); // 初始化事件对象
});
var baseNode = this[0];
if (baseNode) {
this.document = getDocument(context);
this.context = context;
var nodeName = baseNode.nodeName,
nodeType = baseNode.nodeType;
this.name = nodeName.toLowerCase();
this.type = nodeType;
this.window = this.document.defaultView || window;
}
}
/**
* 遍历
* @param {Function} callback 回调函数
* @return 返回当前实例
*/
_createClass(NodeEntry, [{
key: "length",
get: function get() {
var len = 0,
node;
while (node = this[len]) {
len++;
}
return len;
}
}, {
key: "each",
value: function each(callback) {
var i = 0,
node;
while (node = this[i]) {
if (callback(node, i) === false) {
break;
}
i++;
}
return this;
}
/**
* 将 NodeEntry 转换为 Array
* @return {Array} 返回数组
*/
}, {
key: "toArray",
value: function toArray() {
var nodeArray = [];
this.each(function (node) {
nodeArray.push(new NodeEntry(node));
});
return nodeArray;
}
/**
* 判断当前节点是否为 Node.ELEMENT_NODE 节点类型
* @return {boolean}
*/
}, {
key: "isElement",
value: function isElement() {
return this.type === Node.ELEMENT_NODE;
}
/**
* 判断当前节点是否为 Node.TEXT_NODE 节点类型
* @return {boolean}
*/
}, {
key: "isText",
value: function isText() {
return this.type === Node.TEXT_NODE;
}
/**
* 判断当前节点是否为Card组件
*/
}, {
key: "isCard",
value: function isCard$1() {
var element = this.get();
return (element === null || element === void 0 ? void 0 : element.nodeType) === Node.ELEMENT_NODE && isCard(element);
}
/**
* 判断当前节点是否为block类型的Card组件
*/
}, {
key: "isBlockCard",
value: function isBlockCard$1() {
var element = this.get();
return (element === null || element === void 0 ? void 0 : element.nodeType) === Node.ELEMENT_NODE && isBlockCard(element);
}
/**
* 判断当前节点是否为inline类型的Card组件
* @returns
*/
}, {
key: "isInlineCard",
value: function isInlineCard$1() {
var element = this.get();
return (element === null || element === void 0 ? void 0 : element.nodeType) === Node.ELEMENT_NODE && isInlineCard(element);
}
/**
* 是否是可编辑器卡片
* @returns
*/
}, {
key: "isEditableCard",
value: function isEditableCard$1() {
var element = this.get();
return (element === null || element === void 0 ? void 0 : element.nodeType) === Node.ELEMENT_NODE && isEditableCard(element);
}
/**
* 判断当前节点是否为根节点
*/
}, {
key: "isRoot",
value: function isRoot$1(root) {
var _root$;
var element = this.get();
return (element === null || element === void 0 ? void 0 : element.nodeType) === Node.ELEMENT_NODE && isRoot(element, root ? (_root$ = root[0]) !== null && _root$ !== void 0 ? _root$ : root : undefined);
}
}, {
key: "isEditable",
value: function isEditable$1() {
var element = this.get();
return (element === null || element === void 0 ? void 0 : element.nodeType) === Node.ELEMENT_NODE && isEditable(element);
}
/**
* 判断当前是否在根节点内
*/
}, {
key: "inEditor",
value: function inEditor$1(root) {
var _root$2;
var element = this.get();
return !!element && inEditor(element, root ? (_root$2 = root[0]) !== null && _root$2 !== void 0 ? _root$2 : root : undefined);
}
/**
* 是否是光标标记节点
* @returns
*/
}, {
key: "isCursor",
value: function isCursor$1() {
var element = this.get();
return (element === null || element === void 0 ? void 0 : element.nodeType) === Node.ELEMENT_NODE && isCursor(element);
}
}, {
key: "get",
value: function get() {
var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return this.length === 0 ? null : this[index];
}
/**
* 获取当前第 index 节点
* @param {number} index
* @return {NodeEntry|undefined} NodeEntry 类,或 undefined
*/
}, {
key: "eq",
value: function eq(index) {
return index > -1 && index < this.length ? new NodeEntry(this[index]) : undefined;
}
/**
* 获取当前节点所在父节点中的索引
* @return {number} 返回索引
*/
}, {
key: "index",
value: function index() {
var _this$get;
var prev = (_this$get = this.get()) === null || _this$get === void 0 ? void 0 : _this$get.previousSibling;
var index = 0;
while (prev && prev.nodeType === Node.ELEMENT_NODE) {
index++;
prev = prev.previousSibling;
}
return index;
}
/**
* 获取当前节点父节点
* @return 父节点
*/
}, {
key: "parent",
value: function parent() {
var _thisEl$parentElement;
var thisEl = this.get();
var node = (_thisEl$parentElement = thisEl === null || thisEl === void 0 ? void 0 : thisEl.parentElement) !== null && _thisEl$parentElement !== void 0 ? _thisEl$parentElement : thisEl === null || thisEl === void 0 ? void 0 : thisEl.parentNode;
return node ? new NodeEntry(node) : undefined;
}
/**
* 查询当前节点的子节点
* @param selector 查询器
* @return 符合条件的子节点
*/
}, {
key: "children",
value: function children(selector) {
if (0 === this.length) return new NodeEntry([]);
var childNodes = this.get().childNodes;
if (selector) {
var nodes = [];
for (var i = 0; i < childNodes.length; i++) {
var node = childNodes[i];
if (isMatchesSelector(node, selector)) {
nodes.push(node);
}
}
return new NodeEntry(nodes);
}
return new NodeEntry(childNodes);
}
/**
* 获取当前节点第一个子节点
* @return NodeEntry 子节点
*/
}, {
key: "first",
value: function first() {
var _this$get2;
if (this.fragment) return this.eq(0) || null;
var node = this.length === 0 ? null : (_this$get2 = this.get()) === null || _this$get2 === void 0 ? void 0 : _this$get2.firstChild;
return node ? new NodeEntry(node) : null;
}
/**
* 获取当前节点最后一个子节点
* @return NodeEntry 子节点
*/
}, {
key: "last",
value: function last() {
var _this$get3;
if (this.fragment) return this.eq(this.length - 1) || null;
var node = this.length === 0 ? null : (_this$get3 = this.get()) === null || _this$get3 === void 0 ? void 0 : _this$get3.lastChild;
return node ? new NodeEntry(node) : null;
}
/**
* 返回元素节点之前的兄弟节点(包括文本节点、注释节点)
* @return NodeEntry 节点
*/
}, {
key: "prev",
value: function prev() {
var _this$get4;
var node = this.length === 0 ? null : (_this$get4 = this.get()) === null || _this$get4 === void 0 ? void 0 : _this$get4.previousSibling;
return node ? new NodeEntry(node) : null;
}
/**
* 返回元素节点之后的兄弟节点(包括文本节点、注释节点)
* @return NodeEntry 节点
*/
}, {
key: "next",
value: function next() {
var _this$get5;
var node = this.length === 0 ? null : (_this$get5 = this.get()) === null || _this$get5 === void 0 ? void 0 : _this$get5.nextSibling;
return node ? new NodeEntry(node) : null;
}
/**
* 返回元素节点之前的兄弟元素节点(不包括文本节点、注释节点)
* @return NodeEntry 节点
*/
}, {
key: "prevElement",
value: function prevElement() {
var node = this.length === 0 ? null : this.get().previousElementSibling;
return node ? new NodeEntry(node) : null;
}
/**
* 返回元素节点之后的兄弟元素节点(不包括文本节点、注释节点)
* @return NodeEntry 节点
*/
}, {
key: "nextElement",
value: function nextElement() {
var node = this.length === 0 ? null : this.get().nextElementSibling;
return node ? new NodeEntry(node) : null;
}
/**
* 返回元素节点所在根节点路径,默认根节点为 document.body
* @param context 根节点,默认为 document.body
* @param filter 获取index的时候过滤
* @param callback 获取index的时候回调
* @return 路径
*/
}, {
key: "getPath",
value: function getPath(context, filter, callback) {
context = context || document.body;
var path = [];
if (this.length > 0) {
var index = this.getIndex(filter);
if (callback) {
var value = callback(index, path, this);
if (value) path = value;
} else path.unshift(index);
}
if (this.equal(context)) return path;
var parent = this.parent();
while (parent && !parent.equal(context)) {
var _index = parent.getIndex(filter);
if (callback) {
var _value = callback(_index, path, parent);
if (_value) path = _value;
} else path.unshift(_index);
parent = parent.parent();
}
return path;
}
/**
* 判断元素节点是否包含要查询的节点
* @param {NodeInterface | Node} node 要查询的节点
* @return {boolean} 是否包含
*/
}, {
key: "contains",
value: function contains(node) {
var _domNode;
var domNode = isNode(node) ? node : node.get();
if (this.length === 0) {
return false;
}
if (this.get().nodeType === Node.DOCUMENT_NODE && ((_domNode = domNode) === null || _domNode === void 0 ? void 0 : _domNode.nodeType) !== Node.DOCUMENT_NODE) {
return true;
}
if (domNode === this[0]) return true;
while (domNode = ((_domNode$parentElemen = (_domNode2 = domNode) === null || _domNode2 === void 0 ? void 0 : _domNode2.parentElement) !== null && _domNode$parentElemen !== void 0 ? _domNode$parentElemen : (_domNode3 = domNode) === null || _domNode3 === void 0 ? void 0 : _domNode3.parentNode) || null) {
var _domNode$parentElemen, _domNode2, _domNode3;
if (domNode === this[0]) {
return true;
}
}
return false;
}
/**
* 根据查询器查询当前元素节点
* @param {string} selector 查询器
* @return 返回一个 NodeEntry 实例
*/
}, {
key: "find",
value: function find(selector) {
if (this.length > 0 && (this.isElement() || this.fragment)) {
var _ref;
var nodeList = (_ref = this.fragment ? this.fragment : this.get()) === null || _ref === void 0 ? void 0 : _ref.querySelectorAll(selector);
return new NodeEntry(nodeList || []);
}
return new NodeEntry([]);
}
/**
* 根据查询器查询符合条件的离当前元素节点最近的父节点
* @param selector 查询器
* @return 返回一个 NodeEntry 实例
*/
}, {
key: "closest",
value: function closest(selector) {
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (node) {
var _node$parentElement;
return (_node$parentElement = node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : node.parentNode || undefined;
};
var nodeList = [];
var node = this.get() || undefined;
while (node) {
if (isMatchesSelector(node, selector)) {
nodeList.push(node);
return new NodeEntry(nodeList);
}
node = callback(node);
}
return new NodeEntry(nodeList);
}
/**
* 为当前元素节点绑定事件
* @param {string} eventType 事件类型
* @param {Function} listener 事件函数
* @return 返回当前实例
*/
}, {
key: "on",
value: function on(eventType, listener, options) {
var _this2 = this;
this.each(function (node, i) {
node.addEventListener(eventType, listener, options);
if (_this2.events[i]) _this2.events[i].on(eventType, listener, options);
});
return this;
}
/**
* 移除当前元素节点事件
* @param {string} eventType 事件类型
* @param {Function} listener 事件函数
* @return 返回当前实例
*/
}, {
key: "off",
value: function off(eventType, listener, options) {
var _this3 = this;
this.each(function (node, i) {
node.removeEventListener(eventType, listener, options);
if (_this3.events[i]) _this3.events[i].off(eventType, listener, options);
});
return this;
}
/**
* 获取当前元素节点相对于视口的位置
* @param {Object} defaultValue 默认值
* @return {Object}
* {
* top,
* bottom,
* left,
* right
* }
*/
}, {
key: "getBoundingClientRect",
value: function getBoundingClientRect(defaultValue) {
if (this.length === 0) return undefined;
try {
var element = this.get();
var rect = element.getBoundingClientRect();
var top = document.documentElement.clientTop;
var left = document.documentElement.clientLeft;
return {
top: rect.top - top,
bottom: rect.bottom - top,
left: rect.left - left,
right: rect.right - left
};
} catch (error) {
console.error(error);
}
return defaultValue;
}
/**
* 移除当前元素所有已绑定的事件
* @return 当前 NodeEntry 实例
*/
}, {
key: "removeAllEvents",
value: function removeAllEvents() {
var _this4 = this;
this.each(function (node, i) {
if (!_this4.events[i]) {
return;
}
Object.keys(_this4.events[i].listeners).forEach(function (eventType) {
var listeners = _this4.events[i].listeners[eventType];
for (var _i = 0; _i < listeners.length; _i++) {
_this4.off(eventType, listeners[_i]);
_this4.events[i].off(eventType, listeners[_i]);
node.removeEventListener(eventType, listeners[_i], false);
}
});
});
return this;
}
}, {
key: "attributes",
value: function attributes(key, val) {
if (key === undefined) {
var element = this.get();
if (!element) return {};
var attrs = {};
var attributes = element.attributes;
for (var i = attributes.length; i--;) {
var item = attributes[i];
attrs[item.name] = item.value;
}
return attrs;
}
if (_typeof(key) === 'object') {
for (var k in key) {
var v = key[k];
this.attributes(k, v);
}
return this;
}
if (val === undefined) {
var _element = this.get();
return this.length > 0 && this.isElement() ? (_element === null || _element === void 0 ? void 0 : _element.getAttribute(key)) || '' : '';
}
var isRemoveStyle = key === 'style' && val === '';
this.each(function (node) {
if (!(node instanceof Element)) return;
if (isRemoveStyle) node.removeAttribute('style');else node.setAttribute(key, val.toString());
});
return this;
}
/**
* 移除元素节点属性
* @param {string} key 属性名称
* @return 返当前实例
*/
}, {
key: "removeAttributes",
value: function removeAttributes(key) {
this.each(function (node) {
if (!(node instanceof Element)) return;
node.removeAttribute(key);
});
return this;
}
/**
* 判断元素节点是否包含某个 class
* @param {string} className 样式名称
* @return {boolean} 是否包含
*/
}, {
key: "hasClass",
value: function hasClass(className) {
if (this.length === 0) return false;
var element = this.get();
if (!element) return false;
var i = 0,
name = null;
var classList = element.classList || {};
while (name = classList[i]) {
if (name === className) return true;
i++;
}
return false;
}
/**
* 为元素节点增加一个 class
* @param {string} className
* @return 返当前实例
*/
}, {
key: "addClass",
value: function addClass(className) {
this.each(function (node) {
if (!(node instanceof Element)) return;
node.classList.add(className);
});
return this;
}
/**
* 移除元素节点 class
* @param {string} className
* @return 返当前实例
*/
}, {
key: "removeClass",
value: function removeClass(className) {
this.each(function (node) {
if (!(node instanceof Element)) return;
node.classList.remove(className);
});
return this;
}
}, {
key: "css",
value: function css(key, val) {
if (key === undefined) {
// 没有参数,返回style所有属性
return getStyleMap(this.attributes('style') || '');
}
if (_typeof(key) === 'object') {
for (var attr in key) {
var value = key[attr];
this.css(attr, value);
}
return this;
} // 获取style样式值
if (val === undefined) {
if (this.length === 0 || this.isText()) {
return '';
}
var element = this.get();
if (!element) return '';
return element.style[toCamelCase(key)] || getComputedStyle(this[0], key) || '';
}
this.each(function (node) {
var element = node;
element.style[toCamelCase(key)] = val.toString();
if (element.style.length === 0) element.removeAttribute('style');
});
return this;
}
/**
* 获取元素节点宽度
* @return {number} 宽度
*/
}, {
key: "width",
value: function width() {
var width = this.css('width');
if (width === 'auto') {
var element = this.get();
width = element.offsetWidth.toString();
}
return width ? removeUnit(width) || 0 : 0;
}
/**
* 获取元素节点高度
* @return {number} 高度
*/
}, {
key: "height",
value: function height() {
var height = this.css('height');
if (height === 'auto') {
var element = this.get();
height = element.offsetHeight.toString();
}
return height ? parseFloat(height) || 0 : 0;
}
}, {
key: "html",
value: function html(_html) {
if (_html !== undefined) {
var children = domParser(_html);
this.each(function (node) {
if (node.nodeType !== Node.ELEMENT_NODE) return;
var child = node.firstChild;
while (child) {
var next = child.nextSibling;
node.removeChild(child);
child = next;
}
children.forEach(function (child) {
node.appendChild(child.cloneNode(true));
});
});
return this;
}
return this.length > 0 && this[0] instanceof Element ? this[0].innerHTML : '';
}
}, {
key: "text",
value: function text(_text) {
var _this$get6;
// 返回的数据包含 HTML 特殊字符,innerHTML 之前需要 escape
// https://developer.mozilla.org/en-US-US/docs/Web/API/Node/textContent
if (_text !== undefined) {
this.each(function (node) {
node.textContent = _text;
});
return this;
}
if (this.length === 0) return '';
return ((_this$get6 = this.get()) === null || _this$get6 === void 0 ? void 0 : _this$get6.textContent) || '';
}
/**
* 设置元素节点为显示状态
* @param {string} display display值
* @return 当前实例
*/
}, {
key: "show",
value: function show(display) {
if (display === undefined) {
display = this.display || '';
}
if (display === 'none') {
display = '';
}
if (this.css('display') !== 'none') {
return this;
}
return this.css('display', display);
}
/**
* 设置元素节点为隐藏状态
* @return 当前实例
*/
}, {
key: "hide",
value: function hide() {
var _this$get7;
if (this.length === 0) {
return this;
}
this.display = (_this$get7 = this.get()) === null || _this$get7 === void 0 ? void 0 : _this$get7.style.display;
return this.css('display', 'none');
}
/**
* 移除当前实例所有元素节点
* @return 当前实例
*/
}, {
key: "remove",
value: function remove() {
var _this5 = this;
this.each(function (node, index) {
var _node$parentElement2;
var parent = (_node$parentElement2 = node.parentElement) !== null && _node$parentElement2 !== void 0 ? _node$parentElement2 : node.parentNode;
if (!parent) {
return;
}
parent.removeChild(node);
delete _this5[index];
});
return this;
}
/**
* 清空元素节点下的所有子节点
* @return 当前实例
*/
}, {
key: "empty",
value: function empty() {
this.each(function (node) {
var child = node.firstChild;
while (child) {
var next = child.nextSibling;
node.removeChild(child);
child = next;
}
});
return this;
}
/**
* 比较两个元素节点是否相同
* @param {NodeEntry|Node} node 比较的节点
* @return {boolean} 是否相同
*/
}, {
key: "equal",
value: function equal(node) {
if (isNode(node)) return this.get() === node;
if (isNodeEntry(node)) return this.get() === node.get();
return false;
}
}, {
key: "clone",
value: function clone(deep) {
var nodes = [];
this.each(function (node) {
nodes.push(node.cloneNode(deep));
});
return new NodeEntry(nodes);
}
/**
* 在元素节点的开头插入指定内容
* @param selector 选择器或元素节点
* @return 当前实例
*/
}, {
key: "prepend",
value: function prepend(selector) {
var nodes = domParser(selector, this.context);
var isClone = typeof selector === 'string' && /<.+>/.test(selector);
this.each(function (node) {
for (var i = nodes.length - 1; i >= 0; i--) {
var child = isClone ? nodes[i].cloneNode(true) : nodes[i];
if (node.firstChild) {
node.insertBefore(child, node.firstChild);
} else {
node.appendChild(child);
}
}
});
return this;
}
/**
* 在元素节点的结尾插入指定内容
* @param selector 选择器或元素节点
* @return 当前实例
*/
}, {
key: "append",
value: function append(selector) {
var nodes = domParser(selector, this.context);
var isClone = typeof selector === 'string' && /<.+>/.test(selector);
this.each(function (node) {
for (var i = 0; i < nodes.length; i++) {
var child = isClone ? nodes[i].cloneNode(true) : nodes[i];
if (typeof selector === 'string') {
if (node instanceof Element) node.append(child);
} else {
node.appendChild(child);
}
}
});
return this;
}
/**
* 在元素节点前插入新的节点
* @param selector 选择器或元素节点
* @return 当前实例
*/
}, {
key: "before",
value: function before(selector) {
var nodes = domParser(selector, this.context);
var isClone = typeof selector === 'string' && /<.+>/.test(selector);
this.each(function (node) {
var _node$parentElement3;
var parentNode = (_node$parentElement3 = node.parentElement) !== null && _node$parentElement3 !== void 0 ? _node$parentElement3 : node.parentNode;
if (!parentNode) return;
nodes.forEach(function (child) {
if (isClone) child = child.cloneNode(true);
parentNode.insertBefore(child, node);
node = child;
});
});
return this;
}
/**
* 在元素节点后插入内容
* @param selector 选择器或元素节点
* @return 当前实例
*/
}, {
key: "after",
value: function after(selector) {
var nodes = domParser(selector, this.context);
var isClone = typeof selector === 'string' && /<.+>/.test(selector);
this.each(function (node) {
var _node$parentElement4;
var parentNode = (_node$parentElement4 = node.parentElement) !== null && _node$parentElement4 !== void 0 ? _node$parentElement4 : node.parentNode;
if (!parentNode) return;
nodes.forEach(function (child) {
if (isClone) child = child.cloneNode(true);
if (node.nextSibling) {
parentNode.insertBefore(child, node.nextSibling);
node = child;
} else {
parentNode.appendChild(child);
}
});
});
return this;
}
/**
* 将元素节点替换为新的内容
* @param selector 选择器或元素节点
* @return 当前实例
*/
}, {
key: "replaceWith",
value: function replaceWith(selector) {
var newNodes = [];
var nodes = domParser(selector, this.context);
var isClone = typeof selector === 'string' && /<.+>/.test(selector);
this.each(function (node) {
var _node$parentElement5;
var parentNode = (_node$parentElement5 = node.parentElement) !== null && _node$parentElement5 !== void 0 ? _node$parentElement5 : node.parentNode;
if (!parentNode) return;
var newNode = isClone ? nodes[0].cloneNode(true) : nodes[0];
try {
parentNode.replaceChild(newNode, node);
newNodes.push(newNode);
} catch (error) {}
});
return new NodeEntry(newNodes);
}
}, {
key: "getRoot",
value: function getRoot() {
return this.closest(ROOT_SELECTOR);
}
}, {
key: "traverse",
value: function traverse(callback) {
var order = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var includeCard = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var onStart = arguments.length > 3 ? arguments[3] : undefined;
var onEnd = arguments.length > 4 ? arguments[4] : undefined;
var walk = function walk(node) {
var isCard = node.isCard();
if ( // 不能是 fragment 或者 fragment 只有一个子节点,且子节点是 card
isCard && (!node.fragment || node.fragment.childNodes.length === 1) && (!includeCard || includeCard === 'editable' && !node.isEditableCard())) {
return;
}
var child = order ? node.first() : node.last();
while (child) {
var next = order ? child.next() : child.prev();
if (onStart) onStart(child);
var result = callback(child);
if (result === false) {
if (onEnd) onEnd(child, next);
return;
}
if (result !== true) {
var isResultChild = result && typeof result !== 'boolean';
if (isResultChild) {
if (onEnd) onEnd(child, result);
child = result;
}
isCard = child.isCard();
if (isCard) {
// 遍历任意卡片
if (includeCard === true) {
if (isResultChild) callback(child);
walk(child);
} else if (includeCard === 'editable' && child.isEditableCard()) {
(function () {
var editableElements = child.find(EDITABLE_SELECTOR);
editableElements.each(function (_, index) {
var editableElement = editableElements.eq(index);
if (editableElement) walk(editableElement);
});
})();
}
} else {
if (isResultChild) callback(child);
walk(child);
}
}
if (onEnd) onEnd(child, next);
child = next;
}
};
callback(this);
walk(this);
}
}, {
key: "getChildByPath",
value: function getChildByPath(path, filter) {
var node = this.get();
if (path.length === 0) return node;
var getChildNode = function getChildNode(index) {
var i = 0;
var _iterator = _createForOfIteratorHelper(node.childNodes),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
if (filter && !filter(child)) continue;
if (i == index) return child;
i++;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return;
};
for (var i = 0; path[i] !== undefined;) {
var childNode = getChildNode(path[i]);
if (!childNode) break;
node = childNode;
i++;
}
return node;
}
}, {
key: "getIndex",
value: function getIndex(filter) {
var _el$parentElement;
var el = this[0];
var parent = (_el$parentElement = el.parentElement) !== null && _el$parentElement !== void 0 ? _el$parentElement : el.parentNode;
if (!parent) return 0;
var i = 0;
var _iterator2 = _createForOfIteratorHelper(parent.childNodes),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var child = _step2.value;
if (filter && !filter(child)) continue;
if (child === this[0]) return i;
i++;
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return -1;
}
}, {
key: "findParent",
value: function findParent() {
var _container$, _element$parentElemen;
var container = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.closest(ROOT_SELECTOR);
var element = (_container$ = container[0]) !== null && _container$ !== void 0 ? _container$ : container;
var parent = (_element$parentElemen = element.parentElement) !== null && _element$parentElemen !== void 0 ? _element$parentElemen : element.parentNode;
if (this.length === 0 || !parent) return null;
var node = this[0];
while ((parent = (_node$parentElement6 = node.parentElement) !== null && _node$parentElement6 !== void 0 ? _node$parentElement6 : node.parentNode) && parent !== element) {
var _node$parentElement6;
node = parent;
}
if (!parent) return null;
return new NodeEntry(node);
}
}, {
key: "allChildren",
value: function allChildren() {
var includeCard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var childNodes = [];
this.traverse(function (node) {
childNodes.push(node);
}, undefined, includeCard);
childNodes.shift();
return childNodes;
}
}, {
key: "getViewport",
value: function getViewport() {
var _this$parent;
var _ref2 = this.window || {
innerHeight: 0,
innerWidth: 0
},
innerHeight = _ref2.innerHeight,
innerWidth = _ref2.innerWidth;
var element = this.isText() ? (_this$parent = this.parent()) === null || _this$parent === void 0 ? void 0 : _this$parent.get() : this.get();
if (!element) return {
top: 0,
left: 0,
bottom: 0,
right: 0
};
var rect = element.getBoundingClientRect();
var top = rect.top,
left = rect.left,
bottom = rect.bottom,
right = rect.right;
return {
top: top,
left: left,
bottom: Math.min(bottom, innerHeight),
right: Math.min(right, innerWidth)
};
}
}, {
key: "inViewport",
value: function inViewport(view) {
var _ref3, _viewNode$parentEleme;
var simpleMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var viewNode = null;
if (view.type !== Node.ELEMENT_NODE) {
var _view$0$parentElement;
if (!view.document) return false;
viewNode = view.document.createElement('span');
var parent = (_view$0$parentElement = view[0].parentElement) !== null && _view$0$parentElement !== void 0 ? _view$0$parentElement : view[0].parentNode;
if (view.next()) {
parent === null || parent === void 0 ? void 0 : parent.insertBefore(viewNode, view[0].nextSibling);
} else {
parent === null || parent === void 0 ? void 0 : parent.appendChild(viewNode);
}
view = new NodeEntry(viewNode);
}
var viewElement = view.get();
if (!viewElement) return true;
var _viewElement$getBound = viewElement.getBoundingClientRect(),
top = _viewElement$getBound.top,
left = _viewElement$getBound.left,
right = _viewElement$getBound.right,
bottom = _viewElement$getBound.bottom;
var vp = this.getViewport();
if (viewNode) (_ref3 = (_viewNode$parentEleme = viewNode.parentElement) !== null && _viewNode$parentEleme !== void 0 ? _viewNode$parentEleme : viewNode.parentNode) === null || _ref3 === void 0 ? void 0 : _ref3.removeChild(viewNode); // 简单模式,只判断任一方向是否在视口内
if (simpleMode) {
return top > 0 && top <= vp.bottom || bottom > 0 && bottom <= vp.bottom;
}
return top > 0 && top >= vp.top && left > 0 && left >= vp.left && bottom <= vp.bottom && right <= vp.right;
}
}, {
key: "scrollIntoView",
value: function scrollIntoView(view) {
var _view$document;
var align = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'nearest';
if (typeof ((_view$document = view.document) === null || _view$document === void 0 ? void 0 : _view$document.body.scrollIntoView) === 'function') {
var _ref5, _viewElement$parentEl;
var viewElement = null;
if (view.type !== Node.ELEMENT_NODE || view.name.toLowerCase() === 'br') {
var _ref4, _view$0$parentElement2;
viewElement = view.document.createElement('span');
viewElement.innerHTML = ' ';
(_ref4 = (_view$0$parentElement2 = view[0].parentElement) !== null && _view$0$parentElement2 !== void 0 ? _view$0$parentElement2 : view[0].parentNode) === null || _ref4 === void 0 ? void 0 : _ref4.insertBefore(viewElement, view[0]);
view = new NodeEntry(viewElement);
}
if (!this.inViewport(view)) {
var _view$get;
(_view$get = view.get()) === null || _view$get === void 0 ? void 0 : _view$get.scrollIntoView({
block: align,
inline: align
});
}
if (viewElement) (_ref5 = (_viewElement$parentEl = viewElement.parentElement) !== null && _viewElement$parentEl !== void 0 ? _viewElement$parentEl : viewElement.parentNode) === null || _ref5 === void 0 ? void 0 : _ref5.removeChild(viewElement);
}
}
}]);
return NodeEntry;
}();
/**
* 查询节点返回NodeInterface
* @param selector 选择器
* @param context 节点上下文,或根节点
* @param nodeConstructor 需要使用的模型,默认 DOMNOde
*/
var $ = (function (selector, context, clazz) {
if (context === undefined) context = getDocument();
var nodes = domParser(selector, context);
var entry = new (clazz || NodeEntry)(nodes, context ? context : undefined);
if (isNode(selector) && selector.nodeType === window.Node.DOCUMENT_FRAGMENT_NODE) entry.fragment = selector;
return entry;
});
var defaultConversion = [{
from: function from(_name, _styles, attributes) {
return !!attributes[CARD_KEY] || !!attributes[READY_CARD_KEY];
},
to: function to(_, style, attributes) {
var value = attributes[CARD_VALUE_KEY];
var oldAttrs = _objectSpread2({}, attributes);
attributes = _defineProperty({
type: attributes[CARD_TYPE_KEY],
name: (attributes[CARD_KEY] || attributes[READY_CARD_KEY]).toLowerCase(),
editable: attributes[CARD_EDITABLE_KEY]
}, DATA_ID, attributes[DATA_ID]); //其它 data 属性
for (var attrName in oldAttrs) {
if (attrName !== READY_CARD_KEY && attrName.indexOf('data-') === 0 && attrName.indexOf('data-card') !== 0) {
attributes[attrName] = oldAttrs[attrName];
}
}
if (value !== undefined) {
attributes.value = value;
}
var card = $('');
for (var _attrName in attributes) {
card.attributes(_attrName, attributes[_attrName]);
}
return card;
}
}, {
from: function from(_name, _styles, attributes) {
return (_name === 'div' || _name === 'section') && (!attributes[CARD_KEY] || !attributes[READY_CARD_KEY]) && attributes[DATA_ELEMENT] !== ROOT;
},
to: function to(_, style, attributes) {
var p = $('');
p.css(style);
for (var attrName in attributes) {
p.attributes(attrName, attributes[attrName]);
}
return p;
}
}, {
from: function from(name) {
return [CURSOR, ANCHOR, FOCUS].includes(name);
},
to: function to(name) {
return {
node: $("<".concat(name, " />")),
replace: true
};
}
}];
var _attributes3, _attributes4, _attributes5, _attributes6;
var defualtSchema = [{
type: 'block',
attributes: _defineProperty({}, DATA_ID, '*')
}, // {
// type: 'inline',
// attributes: {
// [DATA_ID]: '*',
// },
// },
// {
// type: 'mark',
// attributes: {
// [DATA_ID]: '*',
// },
// },
{
name: 'p',
type: 'block',
allowIn: ['$root']
}, {
name: 'br',
type: 'inline',
isVoid: true
}, {
name: ANCHOR,
type: 'inline',
isVoid: true
}, {
name: FOCUS,
type: 'inline',
isVoid: true
}, {
name: CURSOR,
type: 'inline',
isVoid: true
}, {
name: 'span',
type: 'mark',
attributes: _defineProperty({}, DATA_ELEMENT, {
required: true,
value: ['anchor', 'cursor', 'focus']
})
}, {
name: 'card',
type: 'inline',
attributes: {
name: {
required: true,
value: /\w+/
},
type: {
required: true,
value: 'inline'
},
editable: '*',
value: '*'
}
}, {
name: 'span',
type: 'inline',
attributes: (_attributes3 = {}, _defineProperty(_attributes3, CARD_KEY, {
required: true,
value: /\w+/
}), _defineProperty(_attributes3, CARD_TYPE_KEY, {
required: true,
value: 'inline'
}), _defineProperty(_attributes3, CARD_VALUE_KEY, '*'), _defineProperty(_attributes3, CARD_EDITABLE_KEY, '*'), _defineProperty(_attributes3, "class", '*'), _defineProperty(_attributes3, "contenteditable", '*'), _attributes3)
}, {
name: 'span',
type: 'inline',
attributes: (_attributes4 = {}, _defineProperty(_attributes4, READY_CARD_KEY, {
required: true,
value: /\w+/
}), _defineProperty(_attributes4, CARD_TYPE_KEY, {
required: true,
value: 'inline'
}), _defineProperty(_attributes4, CARD_VALUE_KEY, '*'), _defineProperty(_attributes4, CARD_EDITABLE_KEY, '*'), _defineProperty(_attributes4, "class", '*'), _defineProperty(_attributes4, "contenteditable", '*'), _attributes4)
}, {
name: 'card',
type: 'block',
attributes: {
name: {
required: true,
value: /\w+/
},
type: {
required: true,
value: 'block'
},
editable: '*',
value: '*'
}
}, {
name: 'div',
type: 'block',
attributes: (_attributes5 = {}, _defineProperty(_attributes5, CARD_KEY, {
required: true,
value: /\w+/
}), _defineProperty(_attributes5, CARD_TYPE_KEY, {
required: true,
value: 'block'
}), _defineProperty(_attributes5, CARD_VALUE_KEY, '*'), _defineProperty(_attributes5, CARD_EDITABLE_KEY, '*'), _defineProperty(_attributes5, "class", '*'), _defineProperty(_attributes5, "contenteditable", '*'), _attributes5)
}, {
name: 'div',
type: 'block',
attributes: (_attributes6 = {}, _defineProperty(_attributes6, READY_CARD_KEY, {
required: true,
value: /\w+/
}), _defineProperty(_attributes6, CARD_TYPE_KEY, {
required: true,
value: 'block'
}), _defineProperty(_attributes6, CARD_VALUE_KEY, '*'), _defineProperty(_attributes6, CARD_EDITABLE_KEY, '*'), _defineProperty(_attributes6, "class", '*'), _defineProperty(_attributes6, "contenteditable", '*'), _attributes6)
}];
var DATA_CONTENTEDITABLE_KEY = 'contenteditable';
var _counters = 0;
var uuid = function uuid() {
var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return Number(Math.random().toString().substring(2, 7) + n + Date.now()).toString(36);
};
var valueCaches = new Map();
var hashId = (function (value) {
var unique = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var prefix = '';
if (typeof value !== 'string') {
var _value$;
var node = (_value$ = value[0]) !== null && _value$ !== void 0 ? _value$ : value;
if (node.nodeType === Node.ELEMENT_NODE) {
var element = node;
var name = element.localName;
prefix = name.substring(0, 1);
value = name;
var attributes = element.attributes;
for (var i = attributes.length; i--;) {
var item = attributes[i];
if (~~[DATA_ID, 'id'].indexOf(item.name)) value += "".concat(item.name, "=\"").concat(item.value, "\"");
}
} else {
var _node$textContent;
value = (_node$textContent = node.textContent) !== null && _node$textContent !== void 0 ? _node$textContent : '';
}
}
var cachePerfix = valueCaches.get(value);
if (!cachePerfix) {
var base64 = window.btoa(encodeURIComponent(value)).replace(/=/g, '');
var indexs = [];
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'].forEach(function (char, i) {
var index = base64.indexOf(char);
indexs.push(~index ? index : base64.length % i ? 0 : 1);
});
var str = Number(indexs.join('')).toString(36).replace(/0/g, '');
prefix = prefix + str.substr(0, 4) + str.substr(-4);
valueCaches.set(value, prefix);
} else {
prefix = cachePerfix;
}
var hash = prefix;
if (unique) {
var key = "".concat(hash, "-").concat(uuid(_counters));
_counters++;
return key;
}
return hash;
});
var NodeModel = /*#__PURE__*/function () {
function NodeModel(editor) {
var _this = this;
_classCallCheck(this, NodeModel);
this.editor = void 0;
this.addBrForBlock = function (blockNode) {
if (blockNode.isText()) return;
var children = blockNode.get().childNodes; // 非光标标记的字节的数量
var notCursorCount = 0;
var allText = true;
var hasBlock = false;
var isP = blockNode.name === 'p';
var _iterator = _createForOfIteratorHelper(children),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
if (allText && child.nodeType === Node.TEXT_NODE) {
allText = false;
} else if (!isP && !hasBlock && child.nodeType === Node.ELEMENT_NODE && _this.isBlock(child)) {
hasBlock = true;
}
if (child.nodeType === Node.ELEMENT_NODE && [ANCHOR, FOCUS, CURSOR].indexOf(child.getAttribute(DATA_ELEMENT) || '') < 1) {
notCursorCount++;
}
if (!allText && notCursorCount > 1) {
break;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (isP && notCursorCount === 0) {
var br = document.createElement('br');
blockNode.each(function (children) {
children.appendChild(br.cloneNode());
});
}
if (!hasBlock && allText && _this.isBlock(blockNode) && (children.length !== 1 || children[0].nodeName !== 'BR') && _this.isEmptyWithTrim(blockNode)) {
blockNode.empty();
blockNode.append(document.createElement('br'));
}
};
this.editor = editor;
}
_createClass(NodeModel, [{
key: "isVoid",
value: function isVoid(node) {
var schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.editor.schema;
var name = typeof node === 'string' ? node : '';
if (isNode(node)) name = node.nodeName.toLowerCase();else if (isNodeEntry(node)) name = node.name;
return schema.find(function (rule) {
return rule.name === name && rule.isVoid === true;
}).length > 0;
}
}, {
key: "isMark",
value: function isMark(node) {
var _node$nodeName$toLowe, _node$nodeName;
var schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.editor.schema;
return schema.getTags('marks').includes(((_node$nodeName$toLowe = (_node$nodeName = node.nodeName) === null || _node$nodeName === void 0 ? void 0 : _node$nodeName.toLowerCase()) !== null && _node$nodeName$toLowe !== void 0 ? _node$nodeName$toLowe : node.name).toLowerCase()) && schema.getType(node) === 'mark';
}
/**
* 是否是inline标签
* @param node 节点
*/
}, {
key: "isInline",
value: function isInline(node) {
var _node$nodeName$toLowe2, _node$nodeName2;
var schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.editor.schema;
return schema.getTags('inlines').includes((_node$nodeName$toLowe2 = (_node$nodeName2 = node.nodeName) === null || _node$nodeName2 === void 0 ? void 0 : _node$nodeName2.toLowerCase()) !== null && _node$nodeName$toLowe2 !== void 0 ? _node$nodeName$toLowe2 : node.name) && schema.getType(node) === 'inline';
}
/**
* 是否是块级节点
* @param node 节点
*/
}, {
key: "isBlock",
value: function isBlock(node) {
var _node$nodeName$toLowe3, _node$nodeName3;
var schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.editor.schema;
return schema.getTags('blocks').includes(((_node$nodeName$toLowe3 = (_node$nodeName3 = node.nodeName) === null || _node$nodeName3 === void 0 ? void 0 : _node$nodeName3.toLowerCase()) !== null && _node$nodeName$toLowe3 !== void 0 ? _node$nodeName$toLowe3 : node.name).toLowerCase()) && schema.getType(node) === 'block';
}
/**
* 判断block节点的子节点是否不包含blcok 节点
*/
}, {
key: "isNestedBlock",
value: function isNestedBlock(node) {
if (!this.isBlock(node)) return false;
var element = !!node.length ? node[0] : node;
if (!element) return false;
var child = element.firstChild;
while (child) {
if (this.isBlock(child)) return false;
child = child.nextSibling;
}
return true;
}
/**
* 判断节点是否是顶级根节点,父级为编辑器根节点,且,子级节点没有block节点
* @param node 节点
* @returns
*/
}, {
key: "isRootBlock",
value: function isRootBlock(node, schema) {
var _node$parent;
//父级不是根节点
if (!((_node$parent = node.parent()) === null || _node$parent === void 0 ? void 0 : _node$parent.isEditable())) return false;
if (!this.isNestedBlock(node)) return false; //并且规则上不可以设置子节点
return (schema || this.editor.schema).find(function (schema) {
return schema.name === node.name;
}).every(function (schema) {
if (schema.type !== 'block') return false;
var allowIn = schema.allowIn;
if (!allowIn) return true;
return allowIn.indexOf('$root') > -1;
});
}
/**
* 判断节点下的文本是否为空
* @param withTrim 是否 trim
*/
}, {
key: "isEmpty",
value: function isEmpty(node, withTrim) {
var _value, _value2;
if (node.length > 0 && node.isElement()) {
var _node$fragment;
// 卡片不为空
var attributes = node.attributes();
var element = (_node$fragment = node.fragment) !== null && _node$fragment !== void 0 ? _node$fragment : node.get();
var results = Array.from(element.querySelectorAll("".concat(CARD_SELECTOR, ",").concat(READY_CARD_SELECTOR, ",").concat(EDITABLE_SELECTOR, ",br")));
if (attributes[CARD_KEY] || attributes[READY_CARD_KEY] || results.some(function (e) {
return e.hasAttribute(CARD_KEY) || e.hasAttribute(READY_CARD_KEY);
}) && !results.some(function (e) {
return e.getAttribute(DATA_ELEMENT) === EDITABLE;
})) {
return false;
} // 非br节点的空节点不为空
if (node.name !== 'br' && this.isVoid(node)) {
return false;
} // 多个br节点不为空
if (results.filter(function (e) {
return e.localName === 'br';
}).length > 1) {
return false;
}
}
var value = node.isText() ? node[0].nodeValue || '' : node.text();
value = (_value = value) === null || _value === void 0 ? void 0 : _value.replace(/\u200B/g, '');
value = (_value2 = value) === null || _value2 === void 0 ? void 0 : _value2.replace(/\r\n|\n|\t/, '');
if (value && withTrim) {
value = value.trim();
}
return value === '';
}
/**
* 判断一个节点下的文本是否为空,或者只有空白字符
*/
}, {
key: "isEmptyWithTrim",
value: function isEmptyWithTrim(node) {
return this.isEmpty(node, true);
}
/**
* 判断节点包括子节点是否为空
* @param node 节点
* @returns
*/
}, {
key: "isEmptyWidthChild",
value: function isEmptyWidthChild(node) {
if (node.length === 0) return true;
if (node.isCard()) return false;
if (node.isText()) return this.isEmpty(node);
var childNodes = node[0].childNodes;
if (childNodes.length === 0) return true;
for (var i = 0; i < childNodes.length; i++) {
var child = childNodes[i];
if (child.nodeType === Node.TEXT_NODE) {
if (child['data'].replace(/\u200b/g, '') !== '') return false;
} else if (child.nodeType === Node.ELEMENT_NODE) {
if (child.nodeName.toLowerCase() === 'li' && !this.editor.list.isEmptyItem($(child))) return false;
if (child.hasAttribute(CARD_KEY)) return false;
if (!this.isEmptyWidthChild($(child))) {
return false;
}
}
}
return true;
}
/**
* 判断节点是否为列表节点
* @param node 节点或者节点名称
*/
}, {
key: "isList",
value: function isList(node) {
var name = typeof node === 'string' ? node : '';
if (isNode(node)) name = node.nodeName.toLowerCase();else if (isNodeEntry(node)) name = node.name;
return ['ul', 'ol'].indexOf(name) > -1;
}
/**
* 判断节点是否是自定义列表
* @param node 节点
*/
}, {
key: "isCustomize",
value: function isCustomize(node) {
var list = this.editor.list;
switch (node.name) {
case 'li':
return node.hasClass(list.CUSTOMZIE_LI_CLASS);
case 'ul':
return node.hasClass(list.CUSTOMZIE_UL_CLASS);
default:
return false;
}
}
/**
* 去除包裹
* @param node 需要去除包裹的节点
*/
}, {
key: "unwrap",
value: function unwrap(node) {
var child = node.first();
var nodes = [];
while (child) {
var next = child.next();
node.before(child);
nodes.push(child);
child = next;
}
node.remove();
return nodes;
}
/**
* 包裹节点
* @param source 需要包裹的节点
* @param outer 包裹的外部节点
* @param mergeSame 合并相同名称的节点样式和属性在同一个节点上
*/
}, {
key: "wrap",
value: function wrap(source, outer) {
var _this2 = this;
var mergeSame = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var mark = this.editor.mark;
if (isNode(source)) source = $(source);
outer = this.clone(outer, false); // 文本节点
if (source.isText()) {
outer.append(this.clone(source, false));
return source.replaceWith(outer);
} // 包裹样式节点
if (mergeSame && this.isMark(outer)) {
//合并属性和样式值
var outerClone = this.clone(outer, false, false);
if (source.name === outer.name) {
var attributes = source.attributes();
delete attributes.style;
delete attributes[DATA_ID];
Object.keys(attributes).forEach(function (key) {
if (!outer.attributes(key)) outer.attributes(key, attributes[key]);else {
var _attributes = outer.attributes(key).split(',');
if (_attributes[key] !== undefined && _attributes.indexOf(_attributes[key]) < 0) _attributes.push(_attributes[key]);
outer.attributes(key, _attributes.join(','));
}
});
var styles = source.css();
Object.keys(styles).forEach(function (key) {
if (!outer.css(key)) outer.css(key, styles[key]);
});
outer.append(this.clone(source, true, false).children());
} else {
outer.append(this.clone(source, true, false));
}
var children = outer.allChildren();
children.forEach(function (child) {
if (!child.isText() && _this2.isMark(child) && mark.compare(child, outerClone)) {
_this2.unwrap(child);
}
});
return source.replaceWith(outer);
} // 其它情况
var parent = source.parent();
var shadowNode = this.clone(source, false, false);
source.after(shadowNode);
outer.append(source); // 没有父级节点就直接返回包裹后的节点
return parent ? shadowNode.replaceWith(outer) : outer;
}
/**
* 合并节点
* @param source 合并的节点
* @param target 需要合并的节点
* @param remove 合并后是否移除
*/
}, {
key: "merge",
value: function merge(source, target) {
var remove = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
if (source.equal(target)) return; //要合并的节点是文本,就直接追加
if (target.isText()) {
source.append(target);
this.removeSide(source);
return;
}
var _this$editor = this.editor,
block = _this$editor.block,
mark = _this$editor.mark,
list = _this$editor.list;
var mergedNode = target;
var toIsList = this.isList(source);
var fromIsList = this.isList(target.name); // p 与列表合并时需要做特殊处理
if (toIsList && !fromIsList) {
var liBlocks = source.find('li'); //没有li标签
if (liBlocks.length === 0) {
return;
} //设置被合并节点为最后一个li标签
source = $(liBlocks[liBlocks.length - 1]);
} //被合并的节点为列表
if (!toIsList && fromIsList) {
//查找li节点
var _liBlocks = target.find('li');
if (_liBlocks.length > 0) {
//设置需要合并的节点为第一个li节点
target = $(_liBlocks[0]);
}
if (_liBlocks[1]) {
mergedNode = $(_liBlocks[0]);
}
} // 自定义列表合并
if (this.isCustomize(source)) {
var _sourceFirst, _sourceFirst2;
// 源节点如果还有card节点,
var sourceFirst = source.first();
if (!((_sourceFirst = sourceFirst) === null || _sourceFirst === void 0 ? void 0 : _sourceFirst.isCard())) {
// 源节点没有卡片节点就添加
var plugins = list.getPlugins();
var pluginName = list.getPluginNameByNode(source);
var _plugin = plugins.find(function (p) {
return p.constructor.pluginName === pluginName;
});
if (_plugin === null || _plugin === void 0 ? void 0 : _plugin.cardName) {
list.addCardToCustomize(source, _plugin.cardName);
sourceFirst = source.first();
}
} // 源节点卡片名称与目标节点卡片一样就删除目标节点的第一个卡片节点
if (this.isCustomize(target) && !((_sourceFirst2 = sourceFirst) === null || _sourceFirst2 === void 0 ? void 0 : _sourceFirst2.equal(target))) {
var targetFirst = target.first();
if ((targetFirst === null || targetFirst === void 0 ? void 0 : targetFirst.isCard()) && sourceFirst.attributes(CARD_KEY) === targetFirst.attributes(CARD_KEY)) targetFirst.remove();
}
} //被合并的节点最后一个子节点为br,则移除
var toNodeLast = source.last();
var child = target.first();
var plugin = block.findPlugin(source); //循环追加
while (child) {
var _child$get, _child$parent;
var next = child.next();
var markPlugin = mark.findPlugin(child);
if (plugin && markPlugin && plugin.disableMark && plugin.disableMark.indexOf(markPlugin.constructor.pluginName) > -1) {
var result = this.unwrap(child);
result.forEach(function (children) {
source.append(children);
});
} // 孤立的零宽字符删除
else if (child.isText() && /\u200b/.test(child.text())) {
var parent = child.parent();
var prev = child.prev();
var _next = child.next(); // 不在mark里面,或者没有父级节点,它的上级节点或者下级节点不是inline
if (!parent || !this.isMark(parent) && (prev && !this.isInline(prev) || _next && !this.isInline(_next))) {
child.remove();
child = _next;
continue;
}
} // 移除mark插件下面的所有零宽字符
else if (markPlugin && ((_child$get = child.get()) === null || _child$get === void 0 ? void 0 : _child$get.childNodes.length) === 1) {
var _prev = child.prev();
if (!_prev || _prev.isText()) {
child.allChildren().forEach(function (child) {
var _child$next;
var text = child.text();
if (child.type === getDocument().TEXT_NODE && !!text && !((_child$next = child.next()) === null || _child$next === void 0 ? void 0 : _child$next.isCursor())) {
child.text(text.replace(/\u200b/, ''));
}
});
}
} //追加到要合并的列表中
if (child.length > 0 && !child.equal(source) && !((_child$parent = child.parent()) === null || _child$parent === void 0 ? void 0 : _child$parent.equal(source))) source.append(child);
child = next;
} //移除需要合并的节点
if (remove) mergedNode.remove();
if (toNodeLast && toNodeLast.name === 'br') {
var _next2 = toNodeLast.next();
while (_next2) {
if (_next2.isCursor()) {
toNodeLast.remove();
break;
}
_next2 = _next2.next();
}
}
this.removeSide(source);
}
/**
* 将源节点的子节点追加到目标节点,并替换源节点
* @param source 旧节点
* @param target 新节点
*/
}, {
key: "replace",
value: function replace(source, target) {
var _source$first, _source$first2;
var copyId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var clone = this.clone(target, false, copyId);
var childNode = this.isCustomize(source) && source.name === 'li' && ((_source$first = source.first()) === null || _source$first === void 0 ? void 0 : _source$first.isCard()) ? (_source$first2 = source.first()) === null || _source$first2 === void 0 ? void 0 : _source$first2.next() : source.first();
while (childNode) {
var nextNode = childNode.next();
clone.append(childNode);
childNode = nextNode;
}
if (source.isText()) {
clone.append(source.clone());
}
return source.replaceWith(clone);
}
/**
* 光标位置插入文本
* @param text 文本
* @param range 光标
*/
}, {
key: "insertText",
value: function insertText(text, range) {
var _this$insert;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer); // 范围为折叠状态时先删除内容
if (!safeRange.collapsed) {
change.delete(range);
}
var node = doc.createTextNode(text);
(_this$insert = this.insert(node, safeRange)) === null || _this$insert === void 0 ? void 0 : _this$insert.handleBr();
if (!range) change.apply(safeRange);
return safeRange;
}
/**
* 在光标位置插入一个节点
* @param node 节点
* @param range 光标
* @param removeCurrentEmptyBlock 当前光标行是空行时是否删除
*/
}, {
key: "insert",
value: function insert(node, range) {
var _this3 = this;
var removeCurrentEmptyBlock = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (isNodeEntry(node)) {
if (node.length === 0) throw 'Not found node';
node = node[0];
}
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
block = editor.block,
schema = editor.schema,
mark = editor.mark;
range = range || change.range.get();
var _range$cloneRange$shr = range.cloneRange().shrinkToTextNode(),
startNode = _range$cloneRange$shr.startNode,
startOffset = _range$cloneRange$shr.startOffset;
var prev = startNode.prev();
var parent = startNode.parent();
var text = startNode.text() || '';
var leftText = text.substr(0, startOffset); //文本节点
if (startNode.isText() && /\u200b$/.test(leftText)) {
//零宽字符前面还有其它字符。或者节点前面还有节点,不能是inline节点。或者前面没有节点了,并且父级不是inline节点
if (text.length > 1 && (prev && !this.isInline(prev) || !prev && parent && !this.isInline(parent))) {
var textNode = startNode.get();
var splitNode = textNode.splitText(startOffset - 1);
var splitText = splitNode.textContent;
if (splitText && splitText.length > 0) splitNode.splitText(1);
splitNode.remove();
}
} // 是否在卡片上,卡片还没有渲染
var elementType = parent === null || parent === void 0 ? void 0 : parent.attributes(CARD_ELEMENT_KEY);
if (!elementType && startNode.isCard()) {
range.setStartAfter(startNode);
} // 检测是否位于卡片两边节点
if (elementType && parent && ['left', 'right'].includes(elementType)) {
var cardComponent = editor.card.find(parent);
if (cardComponent) {
if (elementType === 'left') {
range.setStartBefore(cardComponent.root);
} else {
range.setStartAfter(cardComponent.root);
}
}
}
if (this.isBlock(node)) {
// 如果当前光标位置的block节点是空节点,就不用分割
var _range = range,
commonAncestorNode = _range.commonAncestorNode;
if (commonAncestorNode.isText()) {
commonAncestorNode = editor.block.closest(commonAncestorNode);
}
var _splitNode = null;
if (this.isBlock(commonAncestorNode) && this.isEmpty(commonAncestorNode)) {
_splitNode = removeCurrentEmptyBlock ? commonAncestorNode : undefined;
} else {
var isFirst = false;
if (block.isFirstOffset(range, 'start')) {
isFirst = true;
}
_splitNode = block.split(range);
if (isFirst) {
var _splitNode2;
_splitNode = (_splitNode2 = _splitNode) === null || _splitNode2 === void 0 ? void 0 : _splitNode2.prev();
}
}
var blockNode = block.closest(range.startNode.isEditable() ? range.cloneRange().shrinkToElementNode().shrinkToTextNode().startNode : range.startNode);
if (blockNode.isRoot() && !range.startNode.next()) {
blockNode.append(node);
} else if (!blockNode.isCard() && schema.isAllowIn(blockNode.name, node.nodeName.toLowerCase())) {
blockNode.find('br').remove();
blockNode.append(node);
} else {
var _blockNode$get2;
var parentBlock = blockNode.parent();
while (parentBlock && this.isBlock(parentBlock) && !blockNode.isEditable() && (!parentBlock.isEditable() || parentBlock.isCard()) && !schema.isAllowIn(parentBlock.name, node.nodeName.toLowerCase())) {
blockNode = parentBlock;
parentBlock = blockNode.parent();
}
var canMergeTags = schema.getCanMergeTags();
var name = node.nodeName.toLowerCase();
var fragmentLaste = null;
if (_splitNode && blockNode.name === name && canMergeTags.includes(blockNode.name)) {
var _blockNode$get;
blockNode = _splitNode;
var fragment = document.createDocumentFragment();
var children = [];
var hasNext = (_blockNode$get = blockNode.get()) === null || _blockNode$get === void 0 ? void 0 : _blockNode$get.nextSibling;
node.childNodes.forEach(function (child) {
if (!hasNext) children.unshift(child);else children.push(child);
});
fragment.append.apply(fragment, children);
node = fragment;
fragmentLaste = fragment.lastChild;
}
if (blockNode.isEditable() && ((_blockNode$get2 = blockNode.get()) === null || _blockNode$get2 === void 0 ? void 0 : _blockNode$get2.childNodes.length) === 0) {
blockNode.append(node);
} else {
if (this.isEmptyWidthChild(blockNode) || block.isLastOffset(range, 'start')) {
blockNode.after(node); // 没有分割就不会有新增的行就不用删除
if (this.isEmptyWidthChild(blockNode) && _splitNode) blockNode.remove();
} else {
blockNode.before(node);
if (_splitNode && this.isEmptyWidthChild(_splitNode)) _splitNode.remove();
}
if (fragmentLaste) node = fragmentLaste;
}
}
if (node instanceof Element || node instanceof DocumentFragment) editor.nodeId.generate(node);
} else {
var targetNode = block.closest(range.startNode.isEditable() ? range.cloneRange().shrinkToElementNode().shrinkToTextNode().startNode : range.startNode);
var targetPlugin = targetNode ? block.findPlugin(targetNode) : undefined; //先移除不能放入块级节点的mark标签
if (targetPlugin) {
var nodeDom = $(node);
var isUnwrap = function isUnwrap(markNode) {
if (_this3.isMark(markNode)) {
var markPlugin = mark.findPlugin(markNode);
if (!markPlugin) return;
if (targetPlugin.disableMark && targetPlugin.disableMark.indexOf(markPlugin.constructor.pluginName) > -1) {
return true;
}
}
return false;
};
nodeDom.allChildren().forEach(function (markNode) {
if (isUnwrap(markNode)) {
_this3.unwrap(markNode);
}
});
if (isUnwrap(nodeDom)) {
var _fragment = nodeDom.document.createDocumentFragment();
nodeDom.children().each(function (child) {
_fragment.appendChild(child);
});
nodeDom.remove();
node = _fragment.childNodes[_fragment.childNodes.length - 1];
range.insertNode(_fragment);
} else range.insertNode(node);
if (nodeDom.length === 0) return range;
} else range.insertNode(node);
}
if (node.nodeType === Node.ELEMENT_NODE && (node.hasAttribute(READY_CARD_KEY) || node.hasAttribute(CARD_KEY))) {
return range.collapse(false);
}
return range.select(node, this.isVoid(node) || node.nodeType === Node.TEXT_NODE ? false : true).shrinkToElementNode().collapse(false);
}
/**
* 设置节点属性
* @param node 节点
* @param props 属性
*/
}, {
key: "setAttributes",
value: function setAttributes(node, attrs) {
var style = attrs.style;
for (var key in attrs) {
if (key === 'style') continue;
if (key === 'className') {
var value = attrs[key];
if (Array.isArray(value)) {
value.forEach(function (name) {
return node.addClass(name);
});
} else node.addClass(value);
} else node.attributes(key, attrs[key].toString());
}
if (typeof style === 'number') style = {};else if (typeof style === 'string') style = getStyleMap(style);
style = style || {};
var keys = Object.keys(style);
for (var _key in style) {
var val = style[_key];
if (/^0(px|em)?$/.test(val.toString())) {
val = '';
}
node.css(_key, val.toString());
}
if (keys.length === 0 || Object.keys(node.attributes('style')).length === 0) {
node.removeAttributes('style');
}
return node;
}
/**
* 移除值为负的样式
* @param node 节点
* @param style 样式名称
*/
}, {
key: "removeMinusStyle",
value: function removeMinusStyle(node, style) {
if (node.isElement()) {
var styles = node.css();
if (styles[style]) {
var val = parseInt(styles[style] || '0', 10) || 0;
if (val < 0) node.css(style, '');
}
}
}
/**
* 合并节点下的子节点,两个相同的相邻节点的子节点
* @param node 当前节点
*/
}, {
key: "mergeChild",
value: function mergeChild(node) {
var _this$editor2 = this.editor,
schema = _this$editor2.schema,
list = _this$editor2.list;
var topTags = schema.getAllowInTags(); //获取第一个子节点
var childDom = node.first(); //遍历全部子节点
while (childDom) {
//获取下一个子节点
var nextNode = childDom.next();
while ( //如果下一个子节点不为空,并且与上一个子节点名称一样
nextNode && childDom.name === nextNode.name && ( //并且上一个节点是可拥有block子节点的节点 或者是 ul、li 并且list列表类型是一致的
topTags.indexOf(childDom.name) > -1 && !this.isList(childDom) || this.isList(childDom) && list.isSame(childDom, nextNode))) {
//获取下一个节点的下一个节点
var nNextNode = nextNode.next(); //合并下一个节点
var nextChildNode = nextNode.first(); //循环要合并节点的子节点
while (nextChildNode) {
var next = nextChildNode.next();
childDom.append(nextChildNode);
nextChildNode = next;
}
nextNode.remove(); //继续合并当前子节点的子节点
this.mergeChild(childDom);
nextNode = nNextNode;
}
childDom = nextNode;
}
}
/**
* 删除节点两边标签
* @param node 节点
* @param tagName 标签名称,默认为br标签
*/
}, {
key: "removeSide",
value: function removeSide(node) {
var tagName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'br';
// 删除第一个 BR
var firstNode = node.first();
if ((firstNode === null || firstNode === void 0 ? void 0 : firstNode.name) === tagName && node.children().toArray().filter(function (node) {
return !node.isCursor();
}).length > 1) {
firstNode.remove();
} // 删除最后一个 BR
var lastNode = node.last();
if ((lastNode === null || lastNode === void 0 ? void 0 : lastNode.name) === tagName && node.children().toArray().filter(function (node) {
return !node.isCursor();
}).length > 1) {
lastNode.remove();
}
}
}, {
key: "flat",
value:
/**
* 扁平化节点
* @param node 节点
* @param root 根节点
*/
function flat(node) {
var root = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node;
var block = this.editor.block; //第一个子节点
var childNode = node.first();
var tempNode = node.fragment ? $('') : this.clone(node, false);
while (childNode) {
//获取下一个兄弟节点
var nextNode = childNode.next(); //如果当前子节点是块级的Card组件,或者是简单的block
if (childNode.isBlockCard() || this.isNestedBlock(childNode)) {
block.flat(childNode, root);
} //如果当前是块级标签,递归循环
else if (this.isBlock(childNode)) {
childNode = this.flat(childNode, root);
} else {
var cloneNode = this.clone(tempNode, false);
var isLI = 'li' === cloneNode.name;
childNode.before(cloneNode);
while (childNode) {
var _childNode$parent;
nextNode = childNode.next();
var isBR = 'br' === childNode.name && !isLI;
if (isBR && ((_childNode$parent = childNode.parent()) === null || _childNode$parent === void 0 ? void 0 : _childNode$parent.isRoot())) {
cloneNode.append(childNode);
} //判断当前节点末尾是否是换行符,有换行符就跳出
if (childNode.isText()) {
var text = childNode.text(); //先移除开头的换行符
var match = /^((\n|\r)+)/.exec(text);
var isBegin = false;
if (match) {
text = text.substring(match[1].length);
isBegin = true;
if (text.length === 0) {
childNode.remove();
}
} //移除末尾换行符
match = /((\n|\r)+)$/.exec(text);
if (match) {
childNode.text(text.substr(0, match.index));
cloneNode.append(childNode);
break;
} else if (isBegin && childNode.length > 0) {
childNode.text(text);
}
}
if (childNode.length > 0) cloneNode.append(childNode); //判断下一个节点的开头是换行符,有换行符就跳出
if (nextNode) {
var _text = nextNode.text();
var _match = /^(\n|\r)+/.exec(_text);
if (_match) {
break;
}
}
if (isBR || !nextNode || this.isBlock(nextNode) || nextNode.isBlockCard()) break;
childNode = nextNode;
}
this.removeSide(cloneNode);
block.flat(cloneNode, root);
this.addBrForBlock(cloneNode);
}
this.addBrForBlock(childNode);
this.removeSide(childNode);
childNode = nextNode;
} // 重新更新框架的引用
if (node.fragment) {
node = $(node.fragment);
} //如果没有子节点了,就移除当前这个节点
childNode = node.first();
if (!childNode) node.remove();
return node;
}
/**
* 标准化节点
* @param node 节点
*/
}, {
key: "normalize",
value: function normalize(node) {
node = this.flat(node);
this.mergeChild(node);
return node;
}
}, {
key: "html",
value: function html(node, val) {
var _this4 = this;
if (val === undefined) {
var _node$get;
return node.length > 0 ? ((_node$get = node.get()) === null || _node$get === void 0 ? void 0 : _node$get.innerHTML) || '' : '';
}
node.each(function (node) {
if (!(node instanceof Element)) return;
node.innerHTML = val;
_this4.editor.nodeId.generateAll(node);
});
return node;
}
/**
* 复制元素节点
* @param {boolean} deep 是否深度复制
* @return 复制后的元素节点
*/
}, {
key: "clone",
value: function clone(node, deep) {
var copyId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var nodeId = this.editor.nodeId;
var nodes = [];
node.each(function (node) {
var cloneNode = node.cloneNode(deep);
var nodeDom = $(cloneNode);
if (!copyId) {
nodeId.generateAll(nodeDom, true);
if (nodeId.isNeed(nodeDom)) {
nodeId.generate(nodeDom, true);
}
}
nodes.push(cloneNode);
});
return $(nodes);
}
/**
* 获取批量追加子节点后的outerHTML
* @param nodes 节点集合
* @param selector 追加的节点
*/
}, {
key: "getBatchAppendHTML",
value: function getBatchAppendHTML(nodes, selector) {
var _appendNode$get;
if (nodes.length === 0) return selector;
var appendNode = selector.startsWith("\\u") || selector.startsWith('') ? $(selector, null) : $(selector);
nodes.forEach(function (node) {
node = node.clone(false);
node.append(appendNode);
appendNode = node;
});
return ((_appendNode$get = appendNode.get()) === null || _appendNode$get === void 0 ? void 0 : _appendNode$get.outerHTML) || '';
}
}, {
key: "removeZeroWidthSpace",
value: function removeZeroWidthSpace(node) {
var _this5 = this;
node.traverse(function (child) {
var node = child[0];
if (node.nodeType !== Node.TEXT_NODE) {
return;
}
var text = node.nodeValue;
if ((text === null || text === void 0 ? void 0 : text.length) !== 2) {
return;
}
var next = node.nextSibling;
var prev = node.previousSibling;
if (text.charCodeAt(1) === 0x200b && next && next instanceof Element && [ANCHOR, FOCUS, CURSOR].indexOf(next.getAttribute(DATA_ELEMENT) || '') >= 0) {
return;
}
var parent = child.parent();
if (text.charCodeAt(1) === 0x200b && (!next && parent && _this5.isInline(parent) || next && _this5.isInline(next))) {
return;
}
if (text.charCodeAt(0) === 0x200b && (!prev && parent && _this5.isInline(parent) || prev && _this5.isInline(prev))) {
return;
}
if (text.charCodeAt(0) === 0x200b) {
var _ref, _newNode$parentElemen;
var newNode = node.splitText(1);
if (newNode.previousSibling) (_ref = (_newNode$parentElemen = newNode.parentElement) !== null && _newNode$parentElemen !== void 0 ? _newNode$parentElemen : newNode.parentNode) === null || _ref === void 0 ? void 0 : _ref.removeChild(newNode.previousSibling);
}
});
}
}]);
return NodeModel;
}();
var Selection = /*#__PURE__*/function () {
/**
* 移除光标位置占位标签
* @param value 需要移除的字符串
*/
function Selection(editor, range) {
var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
_classCallCheck(this, Selection);
this.range = void 0;
this.editor = void 0;
this.key = '';
this.anchor = null;
this.focus = null;
this.editor = editor;
this.range = range;
this.key = key;
}
_createClass(Selection, [{
key: "has",
value: function has() {
return !!this.focus && !!this.anchor;
}
}, {
key: "create",
value: function create() {
var _this$range = this.range,
commonAncestorNode = _this$range.commonAncestorNode,
startNode = _this$range.startNode,
endNode = _this$range.endNode; // 超出编辑区域
if (!commonAncestorNode.isEditable() && !commonAncestorNode.inEditor()) {
return;
}
var document = commonAncestorNode.document;
if (!document) return; // 为了增加容错性,删除已有的标记
var root = commonAncestorNode.closest(ROOT_SELECTOR);
if (this.key) {
root.find("[data-anchor-id=\"".concat(this.key, "\"]")).remove();
root.find("[data-focus-id=\"".concat(this.key, "\"]")).remove();
root.find("[data-cursor-id=\"".concat(this.key, "\"]")).remove();
} else {
var _anchor = root.find(ANCHOR_SELECTOR);
_anchor.each(function (_, index) {
var node = _anchor.eq(index);
if (node && !node.attributes('data-anchor-id')) node.remove();
});
var _focus = root.find(FOCUS_SELECTOR);
_focus.each(function (_, index) {
var node = _focus.eq(index);
if (node && !node.attributes('data-focus-id')) node.remove();
});
var cursor = root.find(CURSOR_SELECTOR);
cursor.each(function (_, index) {
var node = cursor.eq(index);
if (node && !node.attributes('data-cursor-id')) node.remove();
});
} // card 组件
var card = startNode.closest(CARD_SELECTOR);
if (card.length > 0) {
var cardLeft = startNode.closest(CARD_LEFT_SELECTOR);
if (cardLeft.length > 0) {
this.range.setStartBefore(card);
}
var cardRight = startNode.closest(CARD_RIGHT_SELECTOR);
if (cardRight.length > 0) {
this.range.setStartAfter(card);
}
}
if (!startNode.equal(endNode)) {
var _card = endNode.closest(CARD_SELECTOR);
if (_card.length > 0) {
var _cardLeft = endNode.closest(CARD_LEFT_SELECTOR);
if (_cardLeft.length > 0) {
this.range.setEndBefore(_card);
}
var _cardRight = endNode.closest(CARD_RIGHT_SELECTOR);
if (_cardRight.length > 0) {
this.range.setEndAfter(_card);
}
}
} // cursor
if (this.range.collapsed) {
var _cursor = $(document.createElement('span'));
_cursor.attributes(DATA_ELEMENT, CURSOR);
if (this.key) {
_cursor.attributes('data-cursor-id', this.key);
}
this.range.insertNode(_cursor);
this.anchor = _cursor;
this.focus = _cursor;
return;
} // anchor
var startRange = this.range.cloneRange();
startRange.collapse(true);
var anchor = $(document.createElement('span'));
anchor.attributes(DATA_ELEMENT, ANCHOR);
if (this.key) {
anchor.attributes('data-anchor-id', this.key);
}
startRange.insertNode(anchor);
this.range.setStartAfter(anchor); // focus
var endRange = this.range.cloneRange();
endRange.collapse(false);
var focus = $(document.createElement('span'));
focus.attributes(DATA_ELEMENT, FOCUS);
if (this.key) {
focus.attributes('data-focus-id', this.key);
}
endRange.insertNode(focus);
this.anchor = anchor;
this.focus = focus;
}
}, {
key: "move",
value: function move() {
var _this$anchor$get2, _this$focus$get2;
if (!this.focus || !this.anchor) {
return;
} // 在有指定key的情况下,如果标记节点被移除了就去查找
if (this.key) {
var _this$focus$get, _this$anchor$get;
var commonAncestorNode = this.range.commonAncestorNode;
var root = commonAncestorNode.closest(ROOT_SELECTOR);
if (!this.focus.inEditor() || !((_this$focus$get = this.focus.get()) === null || _this$focus$get === void 0 ? void 0 : _this$focus$get.isConnected)) {
this.focus = root.find("[data-".concat(this.focus.attributes(DATA_ELEMENT), "-id=\"").concat(this.key, "\"]"));
}
if (!this.anchor.inEditor() || !((_this$anchor$get = this.anchor.get()) === null || _this$anchor$get === void 0 ? void 0 : _this$anchor$get.isConnected)) {
this.anchor = root.find("[data-".concat(this.anchor.attributes(DATA_ELEMENT), "-id=\"").concat(this.key, "\"]"));
}
}
var node = this.editor.node;
if (!((_this$anchor$get2 = this.anchor.get()) === null || _this$anchor$get2 === void 0 ? void 0 : _this$anchor$get2.isConnected)) {
this.anchor = this.range.commonAncestorNode.find("[".concat(DATA_ELEMENT, "=\"anchor\"]"));
}
if (!((_this$focus$get2 = this.focus.get()) === null || _this$focus$get2 === void 0 ? void 0 : _this$focus$get2.isConnected)) {
this.focus = this.range.commonAncestorNode.find("[".concat(DATA_ELEMENT, "=\"focus\"]"));
}
if (this.anchor.equal(this.focus)) {
var _parent$get;
var cursor = this.anchor;
var _parent = cursor.parent();
if (!_parent) return;
node.removeZeroWidthSpace(_parent);
_parent[0].normalize();
var isCardCursor = false;
var prevNode = cursor.prev();
var nextNode = cursor.next(); // 具有 block css 属性的行内Card,不调整光标位置
if (prevNode && prevNode.isCard()) {
var cardRight = prevNode.find(CARD_RIGHT_SELECTOR);
if (cardRight.length > 0) {
this.range.select(cardRight, true);
this.range.collapse(false);
isCardCursor = true;
}
} else if (nextNode && nextNode.isCard()) {
var cardLeft = nextNode.find(CARD_LEFT_SELECTOR);
if (cardLeft.length > 0) {
this.range.select(cardLeft, true);
this.range.collapse(false);
isCardCursor = true;
}
}
if (!isCardCursor) {
this.range.setStartBefore(cursor[0]);
this.range.collapse(true);
}
if (isEdge) {
_parent[0].normalize();
cursor.remove();
} else {
cursor.remove();
_parent[0].normalize();
}
if (_parent.name === 'p' && ((_parent$get = _parent.get()) === null || _parent$get === void 0 ? void 0 : _parent$get.childNodes.length) === 0) {
_parent.append($('
'));
}
return;
} // collapsed = false
// range start
var parent = this.anchor.parent();
if (parent) {
node.removeZeroWidthSpace(parent);
if (this.anchor.length > 0) this.range.setStartBefore(this.anchor);
this.anchor.remove();
parent[0].normalize();
} // range end
parent = this.focus.parent();
if (parent) {
var _parent$get2;
node.removeZeroWidthSpace(parent);
if (this.focus.length > 0) this.range.setEndBefore(this.focus);
this.focus.remove();
parent[0].normalize();
if (parent.name === 'p' && ((_parent$get2 = parent.get()) === null || _parent$get2 === void 0 ? void 0 : _parent$get2.childNodes.length) === 0) {
parent.append($('
'));
}
if (isSafari) {
var selection = window.getSelection();
selection === null || selection === void 0 ? void 0 : selection.removeAllRanges();
selection === null || selection === void 0 ? void 0 : selection.addRange(this.range.base);
}
}
}
}, {
key: "getNode",
value: function getNode(source) {
var position = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'center';
var isClone = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {
return true;
};
var node = isClone ? source.clone(true) : source;
if (!this.focus || !this.anchor) {
return node;
} // 删除右侧
if (position === 'left' || position === 'center') {
var selectionNode = position !== 'center' ? this.anchor : this.focus;
var focus = $(this.key ? "[data-".concat(selectionNode.attributes(DATA_ELEMENT), "-id=\"").concat(this.key, "\"]") : "[".concat(DATA_ELEMENT, "=").concat(selectionNode.attributes(DATA_ELEMENT), "]"), node.get());
if (!this.key) {
focus = focus.toArray().find(function (node) {
return !node.attributes("data-".concat(selectionNode.attributes(DATA_ELEMENT), "-id"));
});
}
var isRemove = false;
node.traverse(function (node) {
if (focus && node.equal(focus)) {
var _parent$get3;
var parent = node.parent();
focus.remove();
if ((parent === null || parent === void 0 ? void 0 : parent.name) === 'p' && ((_parent$get3 = parent.get()) === null || _parent$get3 === void 0 ? void 0 : _parent$get3.childNodes.length) === 0) {
parent.append($('
'));
}
isRemove = true;
return;
}
if (isRemove && callback(node) && (node.attributes(DATA_ELEMENT) !== selectionNode.attributes(DATA_ELEMENT) || selectionNode.attributes(DATA_ELEMENT) === 'cursor')) node.remove();
}, true);
} // 删除左侧
if (position === 'right' || position === 'center') {
var _selectionNode = position !== 'center' ? this.focus : this.anchor;
var anchor = $(this.key ? "[data-".concat(_selectionNode.attributes(DATA_ELEMENT), "-id=\"").concat(this.key, "\"]") : "[".concat(DATA_ELEMENT, "=").concat(_selectionNode.attributes(DATA_ELEMENT), "]"), node.get());
if (!this.key) {
anchor = anchor.toArray().find(function (node) {
return !node.attributes("data-".concat(_selectionNode.attributes(DATA_ELEMENT), "-id"));
});
}
var _isRemove = false;
node.traverse(function (node) {
if (anchor && node.equal(anchor)) {
var _parent$get4;
var parent = node.parent();
anchor.remove();
if ((parent === null || parent === void 0 ? void 0 : parent.name) === 'p' && ((_parent$get4 = parent.get()) === null || _parent$get4 === void 0 ? void 0 : _parent$get4.childNodes.length) === 0) {
parent.append($('
'));
}
_isRemove = true;
return;
}
if (_isRemove && callback(node) && (node.attributes(DATA_ELEMENT) !== _selectionNode.attributes(DATA_ELEMENT) || _selectionNode.attributes(DATA_ELEMENT) === 'cursor')) node.remove();
}, false);
}
return node;
}
}]);
return Selection;
}();
Selection.removeTags = function (value) {
return value.replace(//gi, '').replace(//gi, '').replace(//gi, '');
};
function isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
}
function isPlainObject(o) {
if (!isObject(o)) {
return false;
} // If has modified constructor
var ctor = o.constructor;
if (ctor === undefined) {
return true;
} // If has modified prototype
var prot = ctor.prototype;
if (isObject(prot) === false) {
return false;
} // If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
} // Most likely a plain Object
return true;
}
var transientWeakMap = new WeakMap();
var isTransientElementCache = function isTransientElementCache(node, transientElements, loadingCards) {
var element = isNode(node) ? node : node[0];
var isTransient = transientWeakMap.get(element);
if (isTransient !== undefined) {
return isTransient;
}
isTransient = isTransientElement(element, transientElements, loadingCards);
transientWeakMap.set(element, isTransient);
return isTransient;
};
var isTransientElement = function isTransientElement(node, transientElements, loadingCards) {
var element = isNode(node) ? node : node[0];
if (element.nodeType === Node.ELEMENT_NODE) {
var dataElement = element.getAttribute(DATA_ELEMENT) || ''; //范围标记
if ([CURSOR, ANCHOR, FOCUS].indexOf(dataElement) > -1) {
return true;
} //data-element=ui 属性
if (!!element.getAttribute(DATA_TRANSIENT_ELEMENT) || dataElement === UI) {
return true;
}
var parent = element.parentElement;
var parentDataElement = (parent === null || parent === void 0 ? void 0 : parent.getAttribute(DATA_ELEMENT)) || '';
if (dataElement === ROOT || parentDataElement === ROOT) return false;
var curIsCard = isCard(element); //父级是卡片,并且没有可编辑区域
var parentIsLoading = parent === null || parent === void 0 ? void 0 : parent.getAttribute(CARD_LOADING_KEY);
if (parentIsLoading && parent) loadingCards === null || loadingCards === void 0 ? void 0 : loadingCards.push($(parent));
if (!curIsCard && parent && isCard(parent) && !isEditableCard(parent)) {
return true;
}
if (transientElements) {
if (curIsCard) return false;
var _element = transientElements.find(function (element) {
return element === node[0];
});
if (_element) {
if (_element['__card_root']) loadingCards === null || loadingCards === void 0 ? void 0 : loadingCards.push(_element['__card_root']);
return true;
}
}
var closestNode = closest(element, "".concat(CARD_SELECTOR, ",").concat(UI_SELECTOR), getParentInRoot);
if (!closestNode || !(closestNode instanceof Element)) return false;
if (closestNode.getAttribute(DATA_ELEMENT) === UI) {
return true;
} //在卡片里面,并且卡片不是可编辑卡片 或者是标记为正在异步渲染时的卡片的子节点
if (closestNode.getAttribute(CARD_LOADING_KEY)) {
loadingCards === null || loadingCards === void 0 ? void 0 : loadingCards.push($(closestNode));
}
if (!curIsCard && isCard(closestNode) && !isEditableCard(closestNode)) {
return true;
}
if (!curIsCard || isEditableCard(element) || !parent) return false; //当前是卡片,父级也是卡片
var parentCard = closest(parent, CARD_SELECTOR, getParentInRoot);
if (!parentCard || !(parentCard instanceof Element)) return false; // 如果父级是可编辑卡片,并且在加载中,过滤掉其子节点
var loadingCard = parentCard.getAttribute(CARD_LOADING_KEY);
if (loadingCard && parentCard) {
loadingCards === null || loadingCards === void 0 ? void 0 : loadingCards.push($(parentCard));
}
if (parentCard && isCard(parentCard) && !isEditableCard(parentCard)) {
return true;
}
} else if (element.nodeType === Node.TEXT_NODE) {
var _parent = element.parentElement;
return !!_parent && isTransientElementCache(_parent);
}
return false;
};
var isTransientAttribute = function isTransientAttribute(node, attr) {
var element = isNode(node) ? node : node[0];
if (isRoot(element)) return true;
if (isCard(element) && ['id', 'class', 'style', CARD_LOADING_KEY].includes(attr)) return true;
var transient = element.getAttribute(DATA_TRANSIENT_ATTRIBUTES);
if (transient === '*' || transient && transient.split(',').some(function (value) {
return value.trim().toLowerCase() === attr.toLowerCase();
})) return true;
return false;
};
var Range = /*#__PURE__*/function () {
function Range(_editor, _range) {
var _this = this;
_classCallCheck(this, Range);
this.editor = void 0;
this.base = void 0;
this.toRange = function () {
return _this.base;
};
this.collapse = function (toStart) {
_this.base.collapse(toStart);
return _this;
};
this.cloneRange = function () {
return Range.from(_this.editor, _this.base.cloneRange());
};
this.select = function (node, contents) {
if (contents) {
_this.base.selectNodeContents(isNodeEntry(node) ? node[0] : node);
} else {
_this.base.selectNode(isNodeEntry(node) ? node[0] : node);
}
return _this;
};
this.getText = function () {
var contents = _this.cloneContents();
return contents.textContent;
};
this.getClientRect = function () {
var item = _this.getClientRects().item(0);
if (!item) {
item = _this.getBoundingClientRect();
}
return item;
};
this.enlargeFromTextNode = function () {
var enlargePosition = function enlargePosition(node, offset, type) {
var _node$nodeValue;
if (node.nodeType !== Node.TEXT_NODE) {
return;
}
if (offset === 0) {
switch (type) {
case 'start':
_this.setStartBefore(node);
break;
case 'end':
_this.setEndBefore(node);
break;
}
} else if (offset === ((_node$nodeValue = node.nodeValue) === null || _node$nodeValue === void 0 ? void 0 : _node$nodeValue.length)) {
switch (type) {
case 'start':
_this.setStartAfter(node);
break;
case 'end':
_this.setEndAfter(node);
break;
}
}
};
enlargePosition(_this.startContainer, _this.startOffset, 'start');
enlargePosition(_this.endContainer, _this.endOffset, 'end');
return _this;
};
this.shrinkToTextNode = function () {
var shrinkPosition = function shrinkPosition(node, offset, type) {
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
var childNodes = node.childNodes;
if (childNodes.length === 0) {
return;
}
var left;
var right;
var child;
if (offset > 0) {
left = childNodes[offset - 1];
}
if (offset < childNodes.length) {
right = childNodes[offset];
}
if (left && left.nodeType === Node.TEXT_NODE) {
var _child$nodeValue;
child = left;
offset = ((_child$nodeValue = child.nodeValue) === null || _child$nodeValue === void 0 ? void 0 : _child$nodeValue.length) || 0;
}
if (right && right.nodeType === Node.TEXT_NODE) {
child = right;
offset = 0;
}
if (!child) {
return;
}
switch (type) {
case 'start':
_this.setStart(child, offset);
break;
case 'end':
_this.setEnd(child, offset);
break;
}
};
shrinkPosition(_this.startContainer, _this.startOffset, 'start');
shrinkPosition(_this.endContainer, _this.endOffset, 'end');
return _this;
};
this.enlargeToElementNode = function () {
var toBlock = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var toTop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var range = _this.enlargeFromTextNode();
var nodeApi = _this.editor.node;
var enlargePosition = function enlargePosition(node, offset, isStart) {
var _domNode$get;
var domNode = $(node);
if (domNode.type === Node.TEXT_NODE || !toBlock && nodeApi.isBlock(domNode) || domNode.isEditable()) {
return;
}
var parent;
if (offset === 0) {
while (!domNode.prev()) {
parent = domNode.parent();
if (!parent || !toBlock && nodeApi.isBlock(parent)) {
break;
}
if (!parent.inEditor() || parent.isEditable()) {
break;
}
if (!toTop) {
if (!toBlock && parent.isElement()) break;
if (toBlock && nodeApi.isBlock(parent)) break;
}
domNode = parent;
}
if (isStart) {
range.setStartBefore(domNode[0]);
} else {
range.setEndBefore(domNode[0]);
}
} else if (offset === ((_domNode$get = domNode.get()) === null || _domNode$get === void 0 ? void 0 : _domNode$get.childNodes.length)) {
while (!domNode.next()) {
parent = domNode.parent();
if (!parent || !toBlock && nodeApi.isBlock(parent)) {
break;
}
if (!parent.inEditor() || parent.isEditable()) {
break;
}
if (!toTop) {
if (!toBlock && parent.isElement()) break;
if (toBlock && nodeApi.isBlock(parent)) break;
}
domNode = parent;
}
if (isStart) {
range.setStartAfter(domNode[0]);
} else {
range.setEndAfter(domNode[0]);
}
}
};
enlargePosition(range.startContainer, range.startOffset, true);
enlargePosition(range.endContainer, range.endOffset, false);
return _this;
};
this.shrinkToElementNode = function () {
var node = _this.editor.node;
var child;
var childDom;
while (_this.startContainer.nodeType === Node.ELEMENT_NODE && (child = _this.startContainer.childNodes[_this.startOffset]) && (childDom = $(child)) && child.nodeType === Node.ELEMENT_NODE && !childDom.isCursor() && !node.isVoid(child) && (!childDom.isCard() || childDom.isEditableCard() || childDom.find(CARD_LEFT_SELECTOR).length > 0)) {
_this.setStart(child, 0);
}
while (_this.endContainer.nodeType === Node.ELEMENT_NODE && _this.endOffset > 0 && (child = _this.endContainer.childNodes[_this.endOffset - 1]) && (childDom = $(child)) && child.nodeType === Node.ELEMENT_NODE && !node.isVoid(child) && !childDom.isCursor() && (!childDom.isCard() || childDom.isEditableCard() || childDom.find(CARD_RIGHT_SELECTOR).length > 0)) {
_this.setEnd(child, child.childNodes.length);
}
return _this;
};
this.createSelection = function () {
var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var selection = new Selection(_this.editor, _this, key);
selection.create();
return selection;
};
this.getSubRanges = function () {
var includeCard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var filterSingleSelectableCard = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var ranges = [];
_this.commonAncestorNode.traverse(function (child) {
if (child.isText()) {
var _childNode$nodeValue;
var offset = 0;
var childNode = child.get();
var valueLength = ((_childNode$nodeValue = childNode.nodeValue) === null || _childNode$nodeValue === void 0 ? void 0 : _childNode$nodeValue.length) || 0;
var start = _this.comparePoint(childNode, offset);
var end = _this.comparePoint(childNode, valueLength);
var docRange = Range.create(_this.editor);
if (start < 0) {
if (end < 0) return;
if (end === 0) {
docRange.setOffset(childNode, _this.startOffset, valueLength);
} else {
docRange.setOffset(childNode, _this.startOffset, _this.endOffset);
}
} else {
if (start !== 0) return;
if (end < 0) return;
if (end === 0) {
docRange.setOffset(childNode, offset, valueLength);
} else {
docRange.setOffset(childNode, offset, _this.endOffset);
}
}
ranges.push(docRange);
} else if (includeCard && child.isCard() && !child.isEditableCard()) {
var _centerEl$parentEleme;
var cardComponent = _this.editor.card.find(child);
if (!cardComponent || filterSingleSelectableCard && cardComponent.constructor.singleSelectable === false) return;
var center = cardComponent.getCenter();
var centerEl = center.get();
var body = (_centerEl$parentEleme = centerEl === null || centerEl === void 0 ? void 0 : centerEl.parentElement) !== null && _centerEl$parentEleme !== void 0 ? _centerEl$parentEleme : centerEl === null || centerEl === void 0 ? void 0 : centerEl.parentNode;
if (!body || !center.inEditor()) return;
var _offset = center.index();
var _childNode = child.get();
var _start = _this.comparePoint(body, _offset);
var _end = _this.comparePoint(body, _offset + 1);
var _docRange = Range.create(_this.editor);
if (_start < 0) {
if (_end < 0) return;
if (_end === 0) {
_docRange.setOffset(_childNode, _this.startOffset, _offset + 1);
} else {
_docRange.setOffset(_childNode, _this.startOffset, _this.endOffset);
}
} else {
if (_start !== 0) return;
if (_end < 0) return;
if (_end === 0) {
_docRange.setOffset(body, _offset, _offset + 1);
} else {
_docRange.setOffset(body, _offset, _this.endOffset);
}
}
ranges.push(_docRange);
}
});
if (ranges.length === 0) ranges.push(_this);
return ranges;
};
this.setOffset = function (node, start, end) {
if (isNodeEntry(node)) node = node[0];
_this.setStart(node, start);
_this.setEnd(node, end);
return _this;
};
this.findElements = function () {
var startContainer = _this.startContainer,
endContainer = _this.endContainer,
startOffset = _this.startOffset,
endOffset = _this.endOffset,
collapsed = _this.collapsed;
var elements = [];
if (startContainer !== endContainer || collapsed === true || startContainer.nodeType === Node.TEXT_NODE) {
return elements;
}
var childNodes = startContainer.childNodes;
for (var i = startOffset; i < endOffset; i++) {
elements.push(childNodes[i]);
}
return elements;
};
this.inCard = function () {
var card = _this.startNode.closest(CARD_SELECTOR);
return card && card.length > 0;
};
this.getStartOffsetNode = function () {
var startContainer = _this.startContainer,
startOffset = _this.startOffset;
if (startContainer.nodeType === Node.ELEMENT_NODE || startContainer.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
return startContainer.childNodes[startOffset] || startContainer.childNodes[startOffset - 1] || startContainer;
}
return startContainer;
};
this.getEndOffsetNode = function () {
var endContainer = _this.endContainer,
endOffset = _this.endOffset;
if (endContainer.nodeType === Node.ELEMENT_NODE || endContainer.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
return endContainer.childNodes[endOffset] || endContainer.childNodes[endOffset - 1] || endContainer;
}
return endContainer;
};
this.scrollIntoView = function () {
var endElement = _this.endNode.get();
if (isMobile && endElement && endElement.scrollIntoView) {
endElement.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'center'
});
}
};
this.scrollRangeIntoView = function () {
var _node$parentElement;
var node = _this.getEndOffsetNode();
var root = node.nodeType === Node.TEXT_NODE ? (_node$parentElement = node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : node.parentNode : node;
var rect = _this.collapsed ? root.getBoundingClientRect() : _this.getClientRect();
var innerHeight = window.innerHeight;
if (rect.bottom >= innerHeight || rect.bottom <= 0) {
root.scrollIntoView({
block: 'center'
});
}
};
this.scrollIntoViewIfNeeded = function () {
var container = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.editor.container;
var view = arguments.length > 1 ? arguments[1] : undefined;
if (_this.collapsed) {
container.scrollIntoView($(_this.getEndOffsetNode()));
} else {
var startNode = _this.getStartOffsetNode();
var endNode = _this.getEndOffsetNode();
$(startNode).scrollIntoView(view);
$(endNode).scrollIntoView(view);
}
};
this.containsCard = function () {
var collapsed = _this.collapsed,
commonAncestorNode = _this.commonAncestorNode;
return !collapsed && (3 !== commonAncestorNode.type && commonAncestorNode.find(CARD_SELECTOR).length > 0 || commonAncestorNode.closest(CARD_SELECTOR).length > 0);
};
this.handleBr = function (isLeft) {
var _block$last;
var editor = _this.editor;
var list = editor.list;
var block = editor.block.closest(_this.commonAncestorNode);
block.find('br').each(function (br) {
var _parent$first;
var domBr = $(br);
var prev = domBr.prev();
var next = domBr.next();
var parent = domBr.parent();
if ((!prev || (parent === null || parent === void 0 ? void 0 : parent.hasClass(list.CUSTOMZIE_LI_CLASS)) && (parent === null || parent === void 0 ? void 0 : (_parent$first = parent.first()) === null || _parent$first === void 0 ? void 0 : _parent$first.equal(prev))) && next && next.name !== 'br' && !next.isCursor() || !next && prev && prev.name !== 'br') {
var _parent$first2;
if (isLeft && prev && !((parent === null || parent === void 0 ? void 0 : parent.hasClass(list.CUSTOMZIE_LI_CLASS)) && (parent === null || parent === void 0 ? void 0 : (_parent$first2 = parent.first()) === null || _parent$first2 === void 0 ? void 0 : _parent$first2.equal(domBr.prev())))) return;
domBr.remove();
}
});
var first = block.first();
var children = block.children();
if (!first || children.length === 1 && block.hasClass(list.CUSTOMZIE_LI_CLASS) && (first === null || first === void 0 ? void 0 : first.isCard())) {
block.append($('
'));
return _this;
}
if (children.length === 1 && first.isText() && first.text().replace(/\r\n|\n|\t|\u200b/g, '').length === 0) {
block.html('
');
return _this;
}
if (children.length === 2 && block.hasClass(list.CUSTOMZIE_LI_CLASS) && (first === null || first === void 0 ? void 0 : first.isCard()) && ['cursor', 'anchor', 'focus'].includes(((_block$last = block.last()) === null || _block$last === void 0 ? void 0 : _block$last.attributes(DATA_ELEMENT)) || '')) {
var _block$first;
(_block$first = block.first()) === null || _block$first === void 0 ? void 0 : _block$first.after('
');
}
return _this;
};
this.getPrevNode = function () {
_this.enlargeFromTextNode();
var startNode = _this.startNode,
startOffset = _this.startOffset;
if (startNode.isText()) {
return;
}
var childNodes = startNode.children();
if (childNodes.length === 0) {
return;
}
return childNodes.eq(startOffset - 1);
};
this.getNextNode = function () {
_this.enlargeFromTextNode();
var endNode = _this.endNode,
endOffset = _this.endOffset;
if (endNode.isText()) {
return;
}
var childNodes = endNode.children();
if (childNodes.length === 0) {
return;
}
return childNodes.eq(endOffset);
};
this.editor = _editor;
this.base = _range;
}
_createClass(Range, [{
key: "collapsed",
get: function get() {
return this.base.collapsed;
}
}, {
key: "endOffset",
get: function get() {
return this.base.endOffset;
}
}, {
key: "startOffset",
get: function get() {
return this.base.startOffset;
}
}, {
key: "startContainer",
get: function get() {
return this.base.startContainer;
}
}, {
key: "endContainer",
get: function get() {
return this.base.endContainer;
}
}, {
key: "commonAncestorContainer",
get: function get() {
return this.base.commonAncestorContainer;
}
}, {
key: "cloneContents",
value: function cloneContents() {
return this.base.cloneContents();
}
}, {
key: "deleteContents",
value: function deleteContents() {
return this.base.deleteContents();
}
}, {
key: "extractContents",
value: function extractContents() {
return this.base.extractContents();
}
}, {
key: "getBoundingClientRect",
value: function getBoundingClientRect() {
return this.base.getBoundingClientRect();
}
}, {
key: "getClientRects",
value: function getClientRects() {
return this.base.getClientRects();
}
}, {
key: "insertNode",
value: function insertNode(node) {
var _startNode$get, _startNode$first;
if (isNodeEntry(node)) node = node[0];
var startNode = this.startNode;
if (!$(node).isCursor() && ((_startNode$get = startNode.get()) === null || _startNode$get === void 0 ? void 0 : _startNode$get.childNodes.length) === 1 && ((_startNode$first = startNode.first()) === null || _startNode$first === void 0 ? void 0 : _startNode$first.name) === 'br') {
var _startNode$first2;
(_startNode$first2 = startNode.first()) === null || _startNode$first2 === void 0 ? void 0 : _startNode$first2.remove();
} else if (startNode.name === 'br') {
startNode.remove();
} // 防止文本节点被插入到根节点上
if ((node.nodeType === Node.TEXT_NODE || node.nodeName === 'BR') && startNode.isEditable()) {
this.shrinkToElementNode().shrinkToTextNode();
}
if (node instanceof Element || node instanceof DocumentFragment) this.editor.nodeId.generate(node);
this.base.insertNode(node);
}
}, {
key: "isPointInRange",
value: function isPointInRange(node, offset) {
if (isNodeEntry(node)) node = node[0];
return this.base.isPointInRange(node, offset);
}
}, {
key: "comparePoint",
value: function comparePoint(node, offset) {
if (isNodeEntry(node)) node = node[0];
return this.base.comparePoint(node, offset);
}
}, {
key: "setEnd",
value: function setEnd(node, offset) {
if (isNodeEntry(node)) node = node[0];
return this.base.setEnd(node, offset);
}
}, {
key: "setEndAfter",
value: function setEndAfter(node) {
if (isNodeEntry(node)) node = node[0];
if (!node.parentNode) return;
return this.base.setEndAfter(node);
}
}, {
key: "setEndBefore",
value: function setEndBefore(node) {
if (isNodeEntry(node)) node = node[0];
if (!node.parentNode) return;
return this.base.setEndBefore(node);
}
}, {
key: "setStart",
value: function setStart(node, offset) {
if (isNodeEntry(node)) node = node[0];
return this.base.setStart(node, offset);
}
}, {
key: "setStartAfter",
value: function setStartAfter(node) {
if (isNodeEntry(node)) node = node[0];
if (!node.parentNode) return;
return this.base.setStartAfter(node);
}
}, {
key: "setStartBefore",
value: function setStartBefore(node) {
if (isNodeEntry(node)) node = node[0];
if (!node.parentNode) return;
return this.base.setStartBefore(node);
}
}, {
key: "toString",
value: function toString() {
return this.base.toString();
}
}, {
key: "startNode",
get: function get() {
return $(this.base.startContainer);
}
}, {
key: "endNode",
get: function get() {
return $(this.base.endContainer);
}
}, {
key: "commonAncestorNode",
get: function get() {
return $(this.base.commonAncestorContainer);
}
}, {
key: "deepCut",
value: function deepCut() {
if (!this.collapsed) this.extractContents();
var startNode = this.startNode;
if (!startNode.isEditable()) {
var node = startNode;
if (node && !node.isEditable()) {
var parentNode = node.parent();
while (parentNode && !parentNode.isEditable()) {
node = parentNode;
parentNode = parentNode.parent();
}
this.setEndAfter(node[0]);
var contents = this.extractContents();
this.insertNode(contents);
this.collapse(true);
}
}
}
/**
* 对比两个范围是否相等
* @param range 范围
*/
}, {
key: "equal",
value: function equal(range) {
return this.startContainer === range.startContainer && this.startOffset === range.startOffset && this.endContainer === range.endContainer && this.endOffset === range.endOffset;
}
/**
* 获取当前选区最近的根节点
*/
}, {
key: "getRootBlock",
value: function getRootBlock() {
if (this.startNode.isEditable()) return this.startNode.children().eq(this.startOffset);
var node = this.startNode;
while (((_node = node) === null || _node === void 0 ? void 0 : _node.parent()) && !node.parent().isEditable()) {
var _node;
node = node.parent();
}
return node;
}
}, {
key: "filterPath",
value: function filterPath() {
var _this2 = this;
var includeCardCursor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var cardCaches = [];
return function (node) {
var element = $(node);
if (includeCardCursor && node instanceof HTMLElement && ~['left', 'right', 'center', 'body'].indexOf(node.getAttribute(CARD_ELEMENT_KEY) || '')) {
var cardElement = _this2.editor.card.closest(element);
if (cardElement && cardElement.length > 0) cardCaches.push(cardElement);
return true;
}
if (includeCardCursor && element.isCard() && cardCaches.includes(element)) return true;
return !isTransientElementCache(element);
};
}
}, {
key: "toPath",
value: function toPath() {
var _this3 = this;
var includeCardCursor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var root = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.editor.container;
var range = this.cloneRange();
var node = range.commonAncestorNode;
if (!node.isRoot() && !node.inEditor()) return;
range.shrinkToElementNode().shrinkToTextNode();
var getPath = function getPath(node, offset) {
var _node$parent;
var rootBeginId = node.attributes(DATA_ID);
var rootBeginIndex = rootBeginId ? 0 : -1;
var path = node.getPath(root, ((_node$parent = node.parent()) === null || _node$parent === void 0 ? void 0 : _node$parent.isRoot()) ? undefined : _this3.filterPath(includeCardCursor), function (index, path, node) {
// 找不到索引,就重置之前的位置
if (index === -1) {
rootBeginId = '';
rootBeginIndex = -1;
return [];
}
if (!rootBeginId) {
rootBeginId = node.attributes(DATA_ID);
rootBeginIndex = path.length;
}
path.unshift(index);
return;
});
rootBeginIndex = path.length - rootBeginIndex;
path.push(offset);
return {
path: path,
id: rootBeginId,
bi: rootBeginIndex
};
};
return {
start: getPath(range.startNode, range.startOffset),
end: getPath(range.endNode, range.endOffset)
};
}
}]);
return Range;
}();
Range.create = void 0;
Range.from = void 0;
Range.fromPath = void 0;
Range.create = function (editor) {
var doc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document;
var point = arguments.length > 2 ? arguments[2] : undefined;
var range;
if (point) range = doc.caretRangeFromPoint(point.x, point.y);else range = doc.createRange();
return Range.from(editor, range);
};
Range.from = function (editor) {
var win = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window;
if (!isRange(win)) {
var selection = isSelection(win) ? win : win.getSelection();
if (selection && selection.rangeCount > 0) {
win = selection.getRangeAt(0);
} else return null;
}
return new Range(editor, win);
};
Range.fromPath = function (editor, path) {
var _root$get, _root$get2;
var includeCardCursor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var root = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : editor.container;
var startPath = path.start.path.slice();
var endPath = path.end.path.slice();
var startOffset = startPath.pop();
var endOffset = endPath.pop();
var getNode = function getNode(path) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : root.get();
var domNode = context;
for (var i = 0; i < path.length; i++) {
var p = path[i];
if (p < 0) {
p = 0;
}
var needNode = undefined;
var domChild = domNode.firstChild;
var offset = 0;
while (domChild) {
if (!(domChild instanceof Element) || !domChild.getAttribute(DATA_TRANSIENT_ELEMENT) && domChild.getAttribute(DATA_ELEMENT) !== UI || includeCardCursor && ['left', 'right'].includes(domChild.getAttribute(CARD_ELEMENT_KEY) || '')) {
if (offset === p || !domChild.nextSibling) {
needNode = domChild;
break;
}
offset++;
domChild = domChild.nextSibling;
} else {
domChild = domChild.nextSibling;
}
}
if (!needNode) break;
domNode = needNode;
}
return domNode;
};
var setRange = function setRange(method, range, node, offset) {
if (node !== null) {
var _node$nodeValue2;
if (offset < 0) {
offset = 0;
}
if (node.nodeType === Node.ELEMENT_NODE && offset > node.childNodes.length) {
offset = node.childNodes.length;
}
if (node.nodeType === Node.TEXT_NODE && offset > (((_node$nodeValue2 = node.nodeValue) === null || _node$nodeValue2 === void 0 ? void 0 : _node$nodeValue2.length) || 0)) {
var _node$nodeValue3;
offset = ((_node$nodeValue3 = node.nodeValue) === null || _node$nodeValue3 === void 0 ? void 0 : _node$nodeValue3.length) || 0;
}
range[method](node, offset);
}
};
var beginContext = path.start.id ? (_root$get = root.get()) === null || _root$get === void 0 ? void 0 : _root$get.querySelector("[".concat(DATA_ID, "=\"").concat(path.start.id, "\"]")) : root.get();
var startNode = getNode(path.start.bi > -1 && beginContext instanceof Element ? startPath.slice(path.start.bi) : startPath, beginContext instanceof Element ? beginContext : undefined);
var endContext = path.end.id ? (_root$get2 = root.get()) === null || _root$get2 === void 0 ? void 0 : _root$get2.querySelector("[".concat(DATA_ID, "=\"").concat(path.end.id, "\"]")) : root;
var endNode = getNode(path.end.bi > -1 && endContext instanceof Element ? endPath.slice(path.end.bi) : endPath, endContext instanceof Element ? endContext : undefined);
var range = Range.create(editor, document);
setRange('setStart', range, startNode, startOffset === undefined ? 0 : startOffset);
setRange('setEnd', range, endNode, endOffset === undefined ? 0 : endOffset);
return range;
};
var isSelection = function isSelection(param) {
return param.getRangeAt !== undefined;
};
var isRange = function isRange(param) {
return param.collapsed !== undefined;
};
var isRangeInterface = function isRangeInterface(selector) {
return !!selector && selector.base !== undefined;
};
function styleInject(css, ref) {
if ( ref === void 0 ) ref = {};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') { return; }
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var css_248z = ".data-drop-cursor {\n\tposition: absolute;\n\twidth: 2px;\n\tbackground-color: #347EFF;\n}\n\ndiv.data-drag-image {\n\tbackground-color: #f9f9f9;\n}";
styleInject(css_248z);
var DragoverHelper = /*#__PURE__*/function () {
function DragoverHelper(engine, options) {
_classCallCheck(this, DragoverHelper);
this.x = 0;
this.y = 0;
this.doc = document;
this.range = void 0;
this.caretRange = void 0;
this.targetCard = void 0;
this.caretCard = void 0;
this.isCardLeftRange = false;
this.engine = void 0;
this.options = {
className: 'data-drop-cursor'
};
this.engine = engine;
this.options = _objectSpread2(_objectSpread2({}, this.options), options);
}
/**
* 获取当前坐标点的选区
* @returns
*/
_createClass(DragoverHelper, [{
key: "getRangeForPoint",
value: function getRangeForPoint() {
// https://developer.mozilla.org/zh-CN/docs/Web/API/DocumentOrShadowRoot/caretPositionFromPoint
// https://developer.mozilla.org/en-US/docs/Web/API/Document/caretRangeFromPoint
var doc = this.doc,
x = this.x,
y = this.y; // caretRangeFromPoint 已弃用
if (doc.caretRangeFromPoint !== undefined) {
var range = Range.create(this.engine, doc, {
x: x,
y: y
});
if (range) return range;
}
if (event && event['rangeParent'] !== undefined) {
var _range = Range.create(this.engine, doc);
_range.setStart(event['rangeParent'], event['rangeOffset']);
_range.collapse(true);
return _range;
}
return;
}
/**
* 获取卡片
*/
}, {
key: "getCard",
value: function getCard() {
return this.targetCard || this.caretCard;
}
/**
* 解析事件参数
* @param e 事件
*/
}, {
key: "parseEvent",
value: function parseEvent(e) {
// 文件从 Finder 拖进来,不触发 dragstart 事件
// Card拖动,禁止浏览器行为
// 禁止拖图进浏览器,浏览器默认打开图片文件
e.preventDefault();
e.stopPropagation();
if (e.dataTransfer) {
e.dataTransfer.dropEffect = 'move';
}
var card = this.engine.card;
this.x = e.clientX;
this.y = e.clientY;
var target = $(e.target || []);
this.doc = target.document || document;
this.targetCard = card.find(target); // 当前鼠标精确击中的Card
this.caretRange = this.getRangeForPoint();
this.caretCard = this.caretRange ? card.find(this.caretRange.commonAncestorContainer) : undefined;
} // 有选区时获得的最近Card
}, {
key: "getRange",
value: function getRange() {
var caretRange = this.caretRange,
doc = this.doc,
x = this.x;
var card = this.getCard();
var cardCaretRange;
if (card && card.root.length > 0) {
cardCaretRange = Range.create(this.engine, doc);
var _ref = card.root.getBoundingClientRect() || {
left: 0,
right: 0
},
left = _ref.left,
right = _ref.right;
var centerX = (left + right) / 2;
cardCaretRange.select(card.root.get()); // 以卡中点为中心为分割线,逼近两侧可插入的区间
if (centerX < x) {
cardCaretRange.collapse(false);
this.isCardLeftRange = false;
} else {
cardCaretRange.collapse(true);
this.isCardLeftRange = true;
}
}
this.range = cardCaretRange || caretRange;
return this.range;
}
/**
* 获取光标位置
* @param width 光标宽度,默认为2
*/
}, {
key: "getRect",
value: function getRect() {
var _this$range, _rect;
var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2;
var isCardLeftRange = this.isCardLeftRange,
range = this.range;
var card = this.getCard();
if (card && card.root.length > 0 && range) {
if (isCardLeftRange) {
// 如果选区在Card左侧,则向后选取一个元素,选中Card区域
range.setEnd(range.commonAncestorContainer, range.endOffset + 1);
var _range$getBoundingCli = range.getBoundingClientRect(),
_left = _range$getBoundingCli.left,
_bottom2 = _range$getBoundingCli.bottom,
_top2 = _range$getBoundingCli.top;
range.setEnd(range.commonAncestorContainer, range.endOffset - 1);
return {
x: _left - width,
y: _top2,
height: _bottom2 - _top2
};
} // 如果选区在Card右侧,则向前选取一个元素,选中Card区域
range.setStart(range.commonAncestorContainer, range.startOffset - 1);
var _range$getBoundingCli2 = range.getBoundingClientRect(),
right = _range$getBoundingCli2.right,
_top = _range$getBoundingCli2.top,
_bottom = _range$getBoundingCli2.bottom;
range.setStart(range.commonAncestorContainer, range.startOffset + 1);
return {
x: right - width,
y: _top,
height: _bottom - _top
};
} // 如果Card根节点不存在,则原逻辑不变
var rect = (_this$range = this.range) === null || _this$range === void 0 ? void 0 : _this$range.getBoundingClientRect();
if (((_rect = rect) === null || _rect === void 0 ? void 0 : _rect.height) === 0) {
var _this$range2;
var node = (_this$range2 = this.range) === null || _this$range2 === void 0 ? void 0 : _this$range2.startContainer;
rect = node.getBoundingClientRect();
}
var _ref2 = rect || {},
left = _ref2.left,
top = _ref2.top,
bottom = _ref2.bottom;
return {
x: left,
y: top,
height: (bottom || 0) - (top || 0)
};
}
}, {
key: "getCursor",
value: function getCursor() {
var className = this.options.className;
return $("body > div.".concat(className));
}
}, {
key: "removeCursor",
value: function removeCursor() {
this.getCursor().remove();
}
}, {
key: "setCursor",
value: function setCursor() {
this.removeCursor();
var className = this.options.className;
var cursor = $(""));
$(document.body).append(cursor);
}
}]);
return DragoverHelper;
}();
var ChangeEvent = /*#__PURE__*/function () {
function ChangeEvent(engine) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, ChangeEvent);
this.events = {};
this.globalEvents = {};
this.engine = void 0;
this.isComposing = void 0;
this.isSelecting = void 0;
this.dragoverHelper = void 0;
this.options = void 0;
this.keydownRange = null;
this.engine = engine; // 中文输入状态
this.isComposing = false; // 选择范围状态
this.isSelecting = false;
this.dragoverHelper = new DragoverHelper(engine);
this.options = options;
} // return true:焦点在Card里的其它输入框
// return false:焦点在编辑区域,触发 change、select 事件
_createClass(ChangeEvent, [{
key: "isCardInput",
value: function isCardInput(e) {
var node = e.target ? $(e.target) : null;
while (node) {
if (node.isEditable()) {
return false;
}
if (node.attributes(CARD_ELEMENT_KEY) === 'center') {
return true;
}
if (node.attributes(DATA_ELEMENT) === UI) {
return true;
}
var parent = node.parent();
if (!parent) break;
node = parent;
}
return false;
}
}, {
key: "onInput",
value: function onInput(callback) {
var _this = this;
var bindInput = this.options.bindInput;
if (bindInput && !bindInput()) return;
var androidCustomeListComposingNode = null; // 处理中文输入法状态
// https://developer.mozilla.org/en-US-US/docs/Web/Events/compositionstart
this.onContainer('compositionstart', function (event) {
if (_this.engine.readonly) {
return;
}
if (!_this.isCardInput(event)) {
_this.engine.model.mutation.startCache();
} // 组合输入法缓存协同
var _this$engine = _this.engine,
change = _this$engine.change,
node = _this$engine.node,
block = _this$engine.block,
list = _this$engine.list;
var range = change.range.get().cloneRange().shrinkToTextNode().enlargeToElementNode(); // 如果光标在自定义列表项节点前输入先自定义删除,不然排版不对
if (!range.collapsed) {
var startBlock = block.closest(range.startNode);
var endBlock = block.closest(range.endNode);
if ((node.isCustomize(startBlock) || node.isCustomize(endBlock)) && !startBlock.equal(endBlock)) {
var _list$backspaceEvent;
(_list$backspaceEvent = list.backspaceEvent) === null || _list$backspaceEvent === void 0 ? void 0 : _list$backspaceEvent.trigger(new KeyboardEvent(''));
}
}
_this.isComposing = true;
});
var submitInput = function submitInput(e) {
if (!_this.isComposing) {
// 清理输入前插入到自定义列表的卡片后的零宽字符
if (isAndroid && androidCustomeListComposingNode) {
var first = androidCustomeListComposingNode.first();
var next = first === null || first === void 0 ? void 0 : first.next();
if (next === null || next === void 0 ? void 0 : next.isText()) {
var text = next.text();
if (/^\u200b/.test(text)) {
var textNode = next.get();
textNode === null || textNode === void 0 ? void 0 : textNode.splitText(1);
textNode === null || textNode === void 0 ? void 0 : textNode.remove();
}
}
var range = _this.engine.change.range.get();
var startNode = range.startNode,
startOffset = range.startOffset;
if (range.collapsed && (startNode === null || startNode === void 0 ? void 0 : startNode.isText())) {
var _text = startNode.text();
var sufix = _text.substring(startOffset);
if (/^\u200b/.test(sufix)) {
startNode.text(_text.substring(0, startOffset) + sufix.substring(1));
range.setOffset(startNode, startOffset, startOffset);
_this.engine.change.range.select(range);
}
}
androidCustomeListComposingNode = null;
}
callback(e); // 组合输入法结束后提交协同
_this.engine.model.mutation.submitCache();
}
};
this.onContainer('compositionend', function (e) {
if (_this.engine.readonly) {
return;
}
_this.isComposing = false; // 日文输入法,input 后未即时触发 compositionend 方法,这里检测如果还在突变缓存中就提交
setTimeout(function () {
if (_this.engine.model.mutation.isCache) {
submitInput(e);
}
}, 40);
}); //对系统工具栏操作拦截,一般针对移动端的文本上下文工具栏
//https://rawgit.com/w3c/input-events/v1/index.html#interface-InputEvent-Attributes
this.onContainer('beforeinput', function (event) {
if (_this.engine.readonly) return; // safari 组合输入法会直接插入@字符,这里统一全部拦截输入@字符的时候再去触发@事件
var _this$engine2 = _this.engine,
change = _this$engine2.change,
card = _this$engine2.card,
node = _this$engine2.node,
block = _this$engine2.block,
list = _this$engine2.list;
if (event.data === '@' && !_this.isCardInput(event)) {
// 如果没有要对 @ 字符处理的就不拦截
var result = _this.engine.trigger('keydown:at', event);
if (result === false) {
_this.engine.model.mutation.submitCache();
event.preventDefault();
}
}
if (!change.rangePathBeforeCommand) change.cacheRangeBeforeCommand();
var sourceRange = change.range.get(); // 单独选中卡片或者selection处于卡片边缘,手动删除卡片
var range = sourceRange.cloneRange().shrinkToTextNode().enlargeToElementNode(); // 修复 safari 浏览器在列表首次输入组合输入法时会删除li节点
var startNode = range.startNode;
if (isSafari && event.inputType === 'deleteCompositionText' && startNode.name === 'li' && startNode.length > 0 && !node.isCustomize(startNode)) {
var childNodes = startNode[0].childNodes;
if (childNodes.length === 1 && childNodes[0].nodeName !== 'BR') {
startNode.prepend('
');
setTimeout(function () {
var childNodes = startNode[0].childNodes;
if (childNodes.length === 2 && childNodes[0].nodeName === 'BR' && childNodes[1].nodeName === 'BR') {
childNodes[0].remove();
}
}, 0);
}
} // 安卓在自定义列表前组合输入的时候会出现字符错乱
// 解决:在列表下的自定义卡片后面插入一个零宽字符,等组合输入法完成后再删除
if (isAndroid && startNode.name === 'li' && range.startOffset === 1 && node.isCustomize(startNode) && _this.isComposing) {
var first = startNode.first();
var next = first === null || first === void 0 ? void 0 : first.next();
var addTemp = function addTemp() {
var zeroText = $("\u200B", null);
first === null || first === void 0 ? void 0 : first.after(zeroText);
range.setOffset(zeroText, 1, 1);
change.range.select(range);
androidCustomeListComposingNode = startNode;
};
if (next === null || next === void 0 ? void 0 : next.isText()) {
var text = next.text();
if (!/^\u200b/.test(text)) {
addTemp();
}
} else {
if ((next === null || next === void 0 ? void 0 : next.name) === 'br') {
next.remove();
}
addTemp();
}
}
if (!range.collapsed) {
if (range.commonAncestorNode.attributes(CARD_ELEMENT_KEY) === 'body') card.remove(range.commonAncestorNode);else {
if (range.startNode.attributes(CARD_ELEMENT_KEY) === 'body') card.remove(range.startNode);
if (range.endNode.attributes(CARD_ELEMENT_KEY) === 'body') card.remove(range.endNode);
}
}
if (range.startNode.isRoot()) {
var _startNode = range.getStartOffsetNode();
if (_startNode instanceof Element && isCard(_startNode) && !_startNode.querySelector(CARD_CENTER_SELECTOR)) {
card.remove(_startNode);
}
if (!range.collapsed && range.endNode.isRoot()) {
var endNode = range.getEndOffsetNode();
if (endNode instanceof Element && isCard(endNode) && !endNode.querySelector(CARD_CENTER_SELECTOR)) {
card.remove(endNode);
}
}
} // 如果光标在自定义列表项节点前输入先自定义删除,不然排版不对
if (!range.collapsed && !_this.isComposing) {
var startBlock = block.closest(range.startNode);
var endBlock = block.closest(range.endNode);
if ((node.isCustomize(startBlock) || node.isCustomize(endBlock)) && !startBlock.equal(endBlock)) {
var _list$backspaceEvent2;
(_list$backspaceEvent2 = list.backspaceEvent) === null || _list$backspaceEvent2 === void 0 ? void 0 : _list$backspaceEvent2.trigger(new KeyboardEvent(''));
node.insertText(event.data || '');
}
}
var inputType = event.inputType; // 在组合输入法未正常执行结束命令插入就先提交协同
if (_this.isComposing && (!inputType || !inputType.includes('Composition'))) {
_this.engine.model.mutation.submitCache();
}
var commandTypes = ['format', 'history'];
if (inputType) {
commandTypes.forEach(function (type) {
if (inputType.indexOf(type) === 0) {
event.preventDefault();
var commandName = inputType.substring(type.length).toLowerCase();
if (_this.engine.command.queryEnabled(commandName)) {
_this.engine.command.execute(commandName);
}
}
});
}
});
var inputTimeout = null;
this.onContainer('input', function (event) {
var _card$active$root$get;
if (_this.engine.readonly) {
return;
}
if (_this.isCardInput(event)) {
return;
}
if (_this.engine.isEmpty()) {
_this.engine.showPlaceholder();
} else {
_this.engine.hidePlaceholder();
}
var _this$engine3 = _this.engine,
change = _this$engine3.change,
card = _this$engine3.card;
if (event.target instanceof Element && isEditable(event.target) && card.active && card.active.root.isBlockCard() && !card.active.isEditable && ((_card$active$root$get = card.active.root.get()) === null || _card$active$root$get === void 0 ? void 0 : _card$active$root$get.isContentEditable)) {
var range = change.range.get();
var newBlock = $("
");
card.active.root.before(newBlock);
card.remove(card.active.root);
range.select(newBlock, true);
change.range.select(range);
return;
}
if (inputTimeout) clearTimeout(inputTimeout);
inputTimeout = setTimeout(function () {
submitInput(event);
}, 10);
});
}
}, {
key: "onSelect",
value: function onSelect(callback, onStart, onEnd) {
var _this2 = this;
var bindSelect = this.options.bindSelect;
if (bindSelect && !bindSelect()) return; // 模拟 selection change 事件
this.onContainer(isMobile ? 'touchstart' : 'mousedown', function (event) {
if (_this2.isCardInput(event)) {
return;
}
_this2.isSelecting = true;
if (onStart) onStart(event);
});
this.onDocument(isMobile ? 'touchend' : 'mouseup', function (e) {
if (!_this2.isSelecting) {
return;
}
_this2.isSelecting = false; // mouseup 瞬间选择状态不会马上被取消,需要延迟
window.setTimeout(function () {
callback(e);
if (onEnd) onEnd(e);
}, 10);
});
this.onContainer('keydown', function () {
var range = Range.from(_this2.engine);
_this2.keydownRange = range;
}); // 补齐通过键盘选中的情况
this.onContainer('keyup', function (e) {
if (_this2.engine.readonly) {
return;
}
if (_this2.isCardInput(e)) {
return;
} // command + 方向键不会触发 keyup 事件,所以先用 e.key === 'Meta' 代替 isHotkey('mod+方向键',e)
if (isHotkey__default['default']('left', e) || isHotkey__default['default']('right', e) || isHotkey__default['default']('up', e) || isHotkey__default['default']('down', e) || e.key === 'Meta' || isHotkey__default['default']('shift+left', e) || isHotkey__default['default']('shift+right', e) || isHotkey__default['default']('shift+up', e) || isHotkey__default['default']('shift+down', e) || isHotkey__default['default']('ctrl+b', e) || isHotkey__default['default']('ctrl+f', e) || isHotkey__default['default']('ctrl+n', e) || isHotkey__default['default']('ctrl+p', e) || isHotkey__default['default']('ctrl+a', e) || isHotkey__default['default']('ctrl+e', e) || isHotkey__default['default']('home', e) || isHotkey__default['default']('end', e)) {
var range = Range.from(_this2.engine);
if (_this2.keydownRange && range && range.equal(_this2.keydownRange)) return;
if (!_this2.isComposing) {
callback(e);
}
}
});
}
}, {
key: "onPaste",
value: function onPaste(callback) {
var _this3 = this;
var bindPaste = this.options.bindPaste;
if (bindPaste && !bindPaste()) return;
var isPasteText = false;
this.onContainer('keydown', function (e) {
if (_this3.engine.readonly) {
return;
}
if (!isHotkey__default['default']('mod', e) || !isHotkey__default['default']('shift', e) || !isHotkey__default['default']('v', e)) {
isPasteText = false;
}
if (isHotkey__default['default']('mod+shift+v', e) || isHotkey__default['default']('mod+alt+shift+v', e)) {
isPasteText = true;
}
}); // https://developer.mozilla.org/en-US-US/docs/Web/Events/paste
this.onDocument('paste', function (e) {
var range = _this3.engine.change.range.get();
if (!_this3.engine.container.contains(range.commonAncestorNode)) return;
if (_this3.engine.readonly) {
return;
}
if (_this3.isCardInput(e)) {
return;
}
e.preventDefault();
var data = _this3.engine.clipboard.getData(e);
var dataIsPasteText = isPasteText;
isPasteText = false;
callback(_objectSpread2(_objectSpread2({}, data), {}, {
isPasteText: dataIsPasteText
}));
});
}
}, {
key: "onDrop",
value: function onDrop(callback) {
var _this4 = this;
var bindDrop = this.options.bindDrop;
if (bindDrop && !bindDrop()) return;
var cardComponet;
var dragImage;
var dropRange;
var dragStart = function dragStart(e) {
if (!e.target || _this4.engine.readonly) return;
e.stopPropagation();
_this4.dragoverHelper.setCursor();
var targetNode = $(e.target); // 拖动Card
var dragCardTrigger = targetNode.attributes('drag-card-trigger');
cardComponet = _this4.engine.card.find(!!dragCardTrigger ? dragCardTrigger : targetNode);
if (cardComponet) {
var _cardComponet$toolbar, _e$dataTransfer;
(_cardComponet$toolbar = cardComponet.toolbarModel) === null || _cardComponet$toolbar === void 0 ? void 0 : _cardComponet$toolbar.hideCardToolbar(); // https://kryogenix.org/code/browser/custom-drag-image.html
dragImage = cardComponet.find('img.data-drag-image');
if (dragImage.length > 0) {
dragImage = _this4.engine.node.clone(dragImage);
} else {
dragImage = $('');
var cardRootElement = cardComponet.root.get();
if (cardRootElement) {
dragImage.css({
width: cardRootElement.clientWidth + 'px',
height: cardRootElement.clientHeight + 'px'
});
}
}
dragImage.css({
position: 'absolute',
top: '-99999px',
right: '-99999px'
});
$(document.body).append(dragImage);
(_e$dataTransfer = e.dataTransfer) === null || _e$dataTransfer === void 0 ? void 0 : _e$dataTransfer.setDragImage(dragImage[0], 0, 0);
}
};
this.onRoot('dragstart', dragStart);
this.onContainer('dragstart', dragStart);
this.onContainer('dragover', function (e) {
if (_this4.engine.readonly) return;
var dragoverHelper = _this4.dragoverHelper;
var cursor = dragoverHelper.getCursor();
if (cursor.length !== 0) {
dragoverHelper.parseEvent(e);
dropRange = dragoverHelper.getRange();
var rect = dragoverHelper.getRect();
cursor.css({
height: rect.height + 'px',
top: Math.round(window.pageYOffset + (rect.y || 0)) + 'px',
left: Math.round(window.pageXOffset + (rect.x || 0)) + 'px'
});
} else _this4.dragoverHelper.setCursor();
});
this.onContainer('dragleave', function () {
_this4.dragoverHelper.removeCursor();
});
this.onContainer('dragend', function () {
_this4.dragoverHelper.removeCursor();
if (dragImage) {
dragImage.remove();
dragImage = undefined;
}
});
this.onContainer('drop', function (e) {
if (_this4.engine.readonly) return; // 禁止拖图进浏览器,浏览器默认打开图片文件
e.preventDefault();
_this4.dragoverHelper.removeCursor();
if (dragImage) {
dragImage.remove();
dragImage = undefined;
}
var transfer = e.dataTransfer;
var files = []; // Edge 兼容性处理
try {
if (transfer && transfer.items && transfer.items.length > 0) {
Array.from(transfer.items).forEach(function (item) {
if (item.kind === 'file') {
var file = item.getAsFile();
if (file) files.push(file);
}
});
} else if (transfer && transfer.files && transfer.files.length > 0) {
files = Array.from(transfer.files);
}
} catch (err) {
if (transfer && transfer.files && transfer.files.length > 0) {
files = Array.from(transfer.files);
}
}
var data = {
event: e,
range: dropRange,
card: cardComponet,
files: files
};
callback(data);
cardComponet = undefined;
});
}
}, {
key: "onDocument",
value: function onDocument(eventType, listener, index) {
this.addEvent('document', eventType, listener, index);
}
}, {
key: "onWindow",
value: function onWindow(eventType, listener, index) {
this.addEvent('window', eventType, listener, index);
}
}, {
key: "onContainer",
value: function onContainer(eventType, listener, index) {
this.addEvent('container', eventType, listener, index);
}
}, {
key: "onRoot",
value: function onRoot(eventType, listener, index) {
this.addEvent('root', eventType, listener, index);
}
}, {
key: "addEvent",
value: function addEvent(type, eventType, listener, index) {
var _this5 = this;
if (!this.globalEvents[type]) {
this.globalEvents[type] = [];
}
if (!this.globalEvents[type].find(function (event) {
return event.type === eventType;
})) {
var globalListener = function globalListener() {
var listeners = _this5.events[type].filter(function (event) {
return event.type === eventType;
});
var result;
for (var i = 0; i < listeners.length; i++) {
var _listeners$i;
result = (_listeners$i = listeners[i]).listener.apply(_listeners$i, arguments);
if (result === false) {
break;
}
}
return result;
};
switch (type) {
case 'container':
this.engine.container.on(eventType, globalListener);
break;
case 'root':
this.engine.root.on(eventType, globalListener);
break;
case 'document':
document.addEventListener(eventType, globalListener);
break;
case 'window':
window.addEventListener(eventType, globalListener);
break;
}
this.globalEvents[type].push({
type: eventType,
listener: globalListener
});
}
if (!this.events[type]) this.events[type] = [];
if (index !== undefined) {
this.events[type].splice(index, 0, {
type: eventType,
listener: listener
});
} else {
this.events[type].push({
type: eventType,
listener: listener
});
}
}
}, {
key: "destroy",
value: function destroy() {
var _this6 = this;
Object.keys(this.globalEvents).forEach(function (type) {
var events = _this6.globalEvents[type];
events.forEach(function (event) {
if (type === 'window') {
window.removeEventListener(event.type, event.listener);
} else if (type === 'document') {
document.removeEventListener(event.type, event.listener);
} else if (type === 'container') {
_this6.engine.container.off(event.type, event.listener);
} else if (type === 'root') {
_this6.engine.root.off(event.type, event.listener);
}
});
});
}
}]);
return ChangeEvent;
}();
var TextParser = /*#__PURE__*/function () {
function TextParser(source) {
_classCallCheck(this, TextParser);
this.source = void 0;
this.source = source;
}
_createClass(TextParser, [{
key: "toHTML",
value: function toHTML() {
var html = escape(this.source);
html = html.replace(/\n/g, '').replace(/
<\/p>/g, '
').replace(/^\s/, ' ').replace(/\s$/, ' ').replace(/\s\s/g, ' ');
if (html.indexOf('') >= 0) {
html = '
'.concat(html, '
');
}
return html;
}
}]);
return TextParser;
}();
var attrsToString = function attrsToString(attributes) {
var attrsString = '';
for (var key in attributes) {
if (key === 'style') {
continue;
}
var val = escape(attributes[key]);
attrsString += ' '.concat(key, '="').concat(val, '"');
}
return attrsString.trim();
};
var stylesToString = function stylesToString(styles) {
var stylesString = '';
for (var key in styles) {
key = key.toLowerCase();
var val = escape(styles[key]);
if (/^(padding|margin|text-indent)/.test(key) && removeUnit(val) === 0) {
continue;
}
if (key.endsWith('color')) {
val = colord.colord(val).toHex();
}
stylesString += ' '.concat(key, ': ').concat(val, ';');
}
return stylesString.trim();
};
var Parser = /*#__PURE__*/function () {
/**
* 对节点进行正常化转换,在解析编辑器值的时候设置为false可以提升性能。设置为ture的时候可以对不确定的html进行转换,例如粘贴的时候
*/
function Parser(source, editor, paserBefore) {
var isNormalize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
_classCallCheck(this, Parser);
this.root = void 0;
this.editor = void 0;
this.isNormalize = true;
this.editor = editor;
this.isNormalize = isNormalize;
if (typeof source === 'string') {
var _source;
source = source.replace(//gi, '');
source = source.replace(/]+?)\/>/gi, function (_, t) {
return '');
}); // 移除掉img事件绑定,img 标签在 DOMParser 中会加载 onload 和 onerror 事件
source = (_source = source) === null || _source === void 0 ? void 0 : _source.replace(//gi, function (str) {
return str.replace(/\son[a-zA-Z]{1,20}=/g, 'notallow=');
}); // 在 p 里包含 div 标签时 DOMParser 解析错误
// foo
// 变成
// foo
source = source.replace(/|\s+[^>]*>)/gi, '|\s+[^>]*>)/gi, '|\s+[^>]*>)/gi, '
|\s+[^>]*>)/gi, '
".concat(html, ""));
} else if (isNodeEntry(source)) {
this.root = source;
} else {
this.root = $(source);
}
if (paserBefore) paserBefore(this.root);
}
_createClass(Parser, [{
key: "convert",
value: function convert(conversion, node, schema) {
var value = conversion.transform(node);
var oldRules = [];
var nodeApi = this.editor.node;
var convertAfterNode = null;
while (value) {
var _newNode$get;
var _value = value,
rule = _value.rule;
oldRules.push(rule);
var _value$node = value.node,
name = _value$node.name,
attributes = _value$node.attributes,
style = _value$node.style;
if (name !== 'card') delete attributes[DATA_ID];
delete attributes['id'];
var newNode = $("<".concat(name, " />"));
nodeApi.setAttributes(newNode, _objectSpread2(_objectSpread2({}, attributes), {}, {
style: style
})); //把旧节点的子节点追加到新节点下
(_newNode$get = newNode.get()) === null || _newNode$get === void 0 ? void 0 : _newNode$get.append.apply(_newNode$get, _toConsumableArray(node.get().childNodes));
if (node.isCard()) {
node.replaceWith(newNode);
return newNode;
} else {
if (value.replace) {
node.replaceWith(newNode);
node = newNode;
} else {
//把包含旧子节点的新节点追加到旧节点下
newNode.each(function (newNode) {
var oldNode = node.get();
if (oldNode && oldNode instanceof Element) oldNode.append(newNode);
});
}
if (!convertAfterNode || convertAfterNode.length === 0) convertAfterNode = newNode;
if (nodeApi.isBlock(newNode, schema)) {
//排除之前的过滤规则后再次过滤
value = conversion.transform(newNode, function (r) {
return oldRules.indexOf(r) < 0;
});
continue;
}
} //排除之前的过滤规则后再次过滤
value = conversion.transform(node, function (r) {
return oldRules.indexOf(r) < 0;
});
}
return convertAfterNode;
}
}, {
key: "normalize",
value: function normalize(root, schema, conversion) {
var _this = this;
var editor = this.editor;
var nodeApi = editor.node;
var inlineApi = editor.inline; //转换标签和分割 mark 和 inline
// 不分割,就只转换卡片
if (!this.isNormalize) {
if (!conversion) return;
var cards = root.find(CARD_SELECTOR);
cards.each(function (_, index) {
var cardNode = cards.eq(index);
if (!cardNode) return;
_this.convert(conversion, cardNode, schema);
});
var cursors = root.find("".concat(CURSOR_SELECTOR, ",").concat(ANCHOR_SELECTOR, ",").concat(FOCUS_SELECTOR));
cursors.each(function (_, index) {
var cursor = cursors.eq(index);
if (!cursor) return;
_this.convert(conversion, cursor, schema);
});
return;
} // 过滤分割
var filter = function filter(node) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'mark';
//获取节点属性样式
var attributes = node.attributes();
var style = getStyleMap(attributes.style || '');
delete attributes.style;
if (Object.keys(attributes).length === 0 && Object.keys(style).length === 0) return;
var attrCount = Object.keys(attributes).length;
var styleCount = Object.keys(style).length; //复制一个节点
var newNode = node.clone(); //过滤不符合当前节点规则的属性样式
schema.filter(node, attributes, style, true); //移除 data-id,以免在下次判断类型的时候使用缓存
newNode.removeAttributes(DATA_ID); //移除符合当前节点的属性样式,剩余的属性样式组成新的节点
var attrKeys = Object.keys(attributes);
var filterAttrCount = 0;
attrKeys.forEach(function (name) {
if (attributes[name]) {
filterAttrCount++;
newNode.removeAttributes(name);
}
});
var filterStyleCount = 0;
var styleKeys = Object.keys(style);
styleKeys.forEach(function (name) {
if (style[name]) {
filterStyleCount++;
newNode.css(name, '');
}
}); // 如果这个节点过滤掉所有属性样式后还是一个有效的节点就替换掉当前节点
if ((filterAttrCount === attrCount && filterStyleCount === styleCount || filterAttrCount === 0 && filterStyleCount === 0) && schema.getType(newNode) === type) {
node.before(newNode);
var children = node.children();
newNode.append(children.length > 0 ? children : type === 'block' ? '
' : $("\u200B", null));
node.remove();
node = newNode;
return;
}
if (newNode.attributes('style').trim() === '') newNode.removeAttributes('style');
return newNode;
};
root.traverse(function (node) {
if (node[0] === root[0] || ['style', 'script', 'meta'].includes(node.name)) return;
if (node.isElement()) {
var isCard = node.isCard(); //转换标签
if (conversion && (!schema.getType(node) || isCard)) {
var newNode = _this.convert(conversion, node, schema);
if (newNode) {
if (isCard) return true;
return newNode;
}
}
if (isCard) return; //当前节点是 mark 节点
if (nodeApi.isMark(node, schema)) {
var _ret = function () {
//过滤掉当前mark节点属性样式并使用剩下的属性样式组成新的节点
var oldRules = [];
var rule = schema.getRule(node);
if (rule) {
var _ret2 = function () {
var _node$get;
oldRules.push(rule);
if (((_node$get = node.get()) === null || _node$get === void 0 ? void 0 : _node$get.childNodes.length) === 0) {
editor.mark.repairCursor(node);
}
var newNode = filter(node);
if (!newNode) return {
v: {
v: void 0
}
}; //获取这个新的节点所属类型,并且不能是之前节点一样的规则
var type = schema.getType(newNode, function (rule) {
return rule.name === newNode.name && rule.type === 'mark' && oldRules.indexOf(rule) < 0;
});
if (!type) {
if (conversion) {
var newChildren = _this.convert(conversion, newNode, schema);
if (newChildren && newChildren.length > 0) {
var children = node.children();
newChildren.append(children.length > 0 ? children : $("\u200B", null));
node.append(newNode.length === 0 ? newChildren : newNode.children());
return {
v: {
v: void 0
}
};
}
}
} //如果是mark节点,使用新节点包裹旧节点子节点
var tempNode = node;
while (type === 'mark') {
var _children = tempNode.children();
var appendTarget = newNode;
while (true) {
var _children2 = appendTarget.children();
if (_children2.length > 0) {
appendTarget = _children2;
} else {
break;
}
}
appendTarget.append(_children.length > 0 ? _children : $("\u200B", null));
tempNode.append(newNode);
tempNode = newNode;
newNode = filter(newNode);
if (!newNode) break; //获取这个新的节点所属类型,并且不能是之前节点一样的规则
type = schema.getType(newNode, function (rule) {
return rule.name === newNode.name && rule.type === 'mark' && oldRules.indexOf(rule) < 0;
});
if (!type) {
if (conversion) {
var _newChildren = _this.convert(conversion, newNode, schema);
if (_newChildren && _newChildren.length > 0) {
newNode = newNode.length > 0 ? newNode.children() : _newChildren;
type = 'mark';
continue;
}
}
break;
}
rule = schema.getRule(newNode);
if (!rule) break;
oldRules.push(rule);
}
}();
if (_typeof(_ret2) === "object") return _ret2.v;
}
}();
if (_typeof(_ret) === "object") return _ret.v;
} else if (nodeApi.isInline(node)) {
//当前节点是 inline 节点,inline 节点不允许嵌套、不允许放入mark节点
return inlineApi.flat(node, schema);
}
} else if (node.isText()) {
var text = node.text();
if (/^\n+$/.test(text) || /^\s+$/.test(text)) {
var element = node.get();
var prev = element.previousSibling;
var next = element.nextSibling;
var prevType = prev ? schema.getType(prev) : undefined;
var nextType = next ? schema.getType(next) : undefined; // 节点前面
if (!prev && next && (!nextType || nextType === 'block')) {
node.remove();
return;
} // 节点后面
if (!next && prev && (!prevType || prevType === 'block')) {
node.remove();
}
}
}
});
}
}, {
key: "traverse",
value: function traverse(node) {
var schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var conversion = arguments.length > 2 ? arguments[2] : undefined;
var callbacks = arguments.length > 3 ? arguments[3] : undefined;
var includeCard = arguments.length > 4 ? arguments[4] : undefined;
var nodeApi = this.editor.node;
var child = node.first();
while (child) {
if (['style', 'script', 'meta'].includes(child.name)) {
child = child.next();
continue;
}
if (child.isElement()) {
var name = child.name;
var attributes = child.attributes();
if (attributes[DATA_ELEMENT] === UI) {
child = child.next();
continue;
}
var styles = getStyleMap(attributes.style || ''); //删除属性中的style属性
delete attributes.style; // Card Combine 相关节点
if (['left', 'right'].indexOf(attributes[CARD_ELEMENT_KEY]) >= 0) {
child = child.next();
continue;
}
var passed = true;
var type = undefined;
if (schema && attributes[DATA_ELEMENT] !== EDITABLE) {
//不符合规则,跳过
type = schema.getType(child);
if (type === undefined) {
var _parent$get, _child$get;
passed = false;
var parent = child.parent();
if (parent && nodeApi.isBlock(parent, schema) && // 子节点只有一个
((_parent$get = parent.get()) === null || _parent$get === void 0 ? void 0 : _parent$get.childNodes.length) === 1 && // 没有子节点
((_child$get = child.get()) === null || _child$get === void 0 ? void 0 : _child$get.childNodes.length) === 0) {
var newChild = $('
');
child.before(newChild);
child.remove();
child = newChild;
name = newChild.name;
attributes = {};
styles = {};
passed = true;
}
} else {
//过滤不符合规则的属性和样式
schema.filter(child, attributes, styles);
}
} // 执行回调函数
if (attributes[CARD_ELEMENT_KEY] !== 'center' && callbacks.onOpen && passed) {
var result = callbacks.onOpen(child, name, attributes, styles); //终止遍历当前节点
if (result === false) {
child = child.next();
continue;
}
} // Card不遍历子节点
if (name !== 'card' && (!attributes[CARD_KEY] || attributes[CARD_EDITABLE_KEY] === 'true') || includeCard) {
this.traverse(child, schema, conversion, callbacks, includeCard);
} // 执行回调函数
if (attributes[CARD_ELEMENT_KEY] !== 'center' && callbacks.onClose && passed) {
callbacks.onClose(child, name, attributes, styles);
}
} else if (child.isText()) {
var text = child[0].nodeValue ? escape(child[0].nodeValue) : '';
if (text === '' && nodeApi.isBlock(child.parent(), schema || undefined)) {
if (!child.prev()) {
text = text.replace(/^[ \n]+/, '');
}
if (!child.next()) {
text = text.replace(/[ \n]+$/, '');
}
}
var childPrev = child.prev();
var childNext = child.next();
if (childPrev && nodeApi.isBlock(childPrev, schema || undefined) && childNext && nodeApi.isBlock(childNext, schema || undefined) && text.trim() === '') {
text = text.trim();
} // 删除 zero width space,删除后会导致空行中如果有mark节点,那么空行会没有高度
// text = text.replace(/\u200B/g, '');
if (callbacks.onText) {
callbacks.onText(child, text);
}
}
child = child.next();
}
}
/**
* 遍历 DOM 树,生成符合标准的 XML 代码
* @param schema 标签保留规则
* @param conversion 标签转换规则
* @param replaceSpaces 是否替换空格
* @param customTags 是否将光标、卡片节点转换为标准代码
*/
}, {
key: "toValue",
value: function toValue() {
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var conversion = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var replaceSpaces = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var customTags = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var result = [];
var editor = this.editor;
var nodeApi = editor.node;
var root = this.root.clone(true);
if (schema) this.normalize(root, schema, conversion);
editor.trigger('parse:value-before', root);
this.traverse(root, schema, conversion, {
onOpen: function onOpen(child, name, attributes, styles) {
var _child$get2;
if (editor.trigger('parse:value', child, attributes, styles, result) === false) return false;
result.push('<');
result.push(name);
if (Object.keys(attributes).length > 0) {
result.push(' ' + attrsToString(attributes));
}
if (Object.keys(styles).length > 0) {
var stylesString = stylesToString(styles);
if (stylesString !== '') {
result.push(' style="');
result.push(stylesString);
result.push('"');
}
}
if (nodeApi.isVoid(name, schema ? schema : undefined) && ((_child$get2 = child.get()) === null || _child$get2 === void 0 ? void 0 : _child$get2.childNodes.length) === 0) {
result.push(' />');
} else {
result.push('>');
}
return;
},
onText: function onText(_, text) {
if (replaceSpaces && text.length > 1) {
text = text.replace(/[\u00a0 ]+/g, function (item) {
var strArray = [];
item = item.replace(/\u00a0/g, ' ');
for (var n = 0; n < item.length; n++) {
strArray[n] = n % 2 == 0 ? item[n] : ' ';
}
return strArray.join('');
});
}
result.push(text);
},
onClose: function onClose(_, name) {
if (nodeApi.isVoid(name, schema ? schema : undefined)) return;
result.push(''.concat(name, '>'));
}
});
editor.trigger('parse:value-after', result); //移除前后的换行符
if (result.length > 0 && /^\n+/g.test(result[0])) {
result[0] = result[0].replace(/^\n+/g, '');
}
if (result.length > 0 && /\n+$/g.test(result[result.length - 1])) {
result[result.length - 1] = result[result.length - 1].replace(/\n+$/g, '');
}
var value = result.join('');
return customTags ? transformCustomTags(value) : value;
}
/**
* 转换为HTML代码
* @param inner 内包裹节点
* @param outter 外包裹节点
*/
}, {
key: "toHTML",
value: function toHTML(inner, outter) {
var element = $('');
var editor = this.editor;
var style = editor.container.css();
if (inner && outter) {
$(inner).append(this.root).css(style);
element.append(outter);
} else {
element.append(this.root);
}
editor.trigger('parse:html-before', this.root);
editor.trigger('parse:html', element);
editor.trigger('parse:html-after', element);
return element.html().replace(/\u200b/g, '');
}
/**
* 返回DOM树
*/
}, {
key: "toDOM",
value: function toDOM() {
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var conversion = arguments.length > 1 ? arguments[1] : undefined;
var value = this.toValue(schema, conversion, false, true);
var doc = new DOMParser().parseFromString(value, 'text/html');
var fragment = doc.createDocumentFragment();
var nodes = doc.body.childNodes;
while (nodes.length > 0) {
var node = nodes[0];
fragment.appendChild(node);
}
return fragment;
}
/**
* 转换为文本
* @param schema Schema 规则
* @param includeCard 是否遍历卡片内部
* @param formatOL 是否格式化有序列表,- a
- b
-> 1. a 2. b
*/
}, {
key: "toText",
value: function toText() {
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var includeCard = arguments.length > 1 ? arguments[1] : undefined;
var formatOL = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var root = this.root.clone(true);
var result = [];
var editor = this.editor;
this.traverse(root, null, null, {
onOpen: function onOpen(node, name, attributes, styles) {
if (editor.trigger('parse:text', node, attributes, styles, result) === false) {
return false;
}
if (name === 'br') {
result.push('\n');
}
if (formatOL && node.name === 'li') {
if (node.hasClass(editor.list.CUSTOMZIE_LI_CLASS)) {
return;
}
var parent = node.parent();
var styleType = parent === null || parent === void 0 ? void 0 : parent.css('listStyleType');
if ((parent === null || parent === void 0 ? void 0 : parent.name) === 'ol') {
var start = parent[0]['start'];
var index = start ? start : 1;
result.push("".concat(getListStyle(styleType, index), ". "));
parent.attributes('start', index + 1);
} else if ((parent === null || parent === void 0 ? void 0 : parent.name) === 'ul') {
result.push(getListStyle(styleType) + ' ');
}
}
return;
},
onText: function onText(_, text) {
text = unescape(text);
text = text.replace(/\u00a0/g, ' ');
text = text.replace(/\u200b/g, '');
result.push(text);
},
onClose: function onClose(node, name) {
var nodeApi = editor.node;
if (name === 'p' || nodeApi.isBlock(node, schema || editor.schema)) {
var children = Array.from(node.get().childNodes); // 子节点还有block节点,则不换行
if (children.length === 0 || children.some(function (child) {
if (child instanceof Text) return false;
if (child.nodeName === 'BR') return true;
var type = (schema || editor.schema).getType(child);
if (!type || type === 'block') return true;
return false;
})) return;
result.push('\n');
}
}
}, includeCard);
return result.join('').trim();
}
}]);
return Parser;
}();
var Paste = /*#__PURE__*/function () {
function Paste(source, engine) {
_classCallCheck(this, Paste);
this.source = void 0;
this.engine = void 0;
this.schema = void 0;
this.source = source;
this.engine = engine;
this.schema = this.engine.schema.clone();
}
_createClass(Paste, [{
key: "parser",
value: function parser() {
var _this = this;
var conversion = this.engine.conversion.clone();
this.engine.trigger('paste:schema', this.schema);
var parser = new Parser(this.source, this.engine, function (root) {
_this.engine.trigger('paste:origin', root);
});
return parser.toDOM(this.schema, conversion);
}
}, {
key: "getDefaultStyle",
value: function getDefaultStyle() {
var container = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.engine.container;
var defaultStyle = {
color: colord.colord(container.css('color')).toHex(),
'background-color': colord.colord(container.css('background-color')).toHex(),
'font-size': container.css('font-size')
};
return defaultStyle;
}
}, {
key: "elementNormalize",
value: function elementNormalize(fragment) {
var _this2 = this;
var defaultStyle = this.getDefaultStyle();
var _this$engine = this.engine,
inline = _this$engine.inline,
list = _this$engine.list;
var nodeApi = this.engine.node;
var markApi = this.engine.mark;
var blockApi = this.engine.block;
var currentMarkPlugins = [];
$(fragment).traverse(function (node) {
var _parent2, _parent4, _parent9;
var parent = node.parent(); // 跳过已被删除的节点
if (!parent || node.isCard() || node.fragment === fragment) {
return undefined;
}
if (node.isText()) {
var text = node.text(); // if (/\x20/.test(text)) {
// text = text.replace(/\x20/g, ' ');
// node.text(text);
// }
if (/\u200b/.test(text)) {
var isRemove = true;
var next = node.next();
var prev = node.prev();
var _parent = node.parent();
if (_parent && nodeApi.isMark(_parent, _this2.schema)) isRemove = false;else if (_parent && nodeApi.isInline(_parent, _this2.schema)) isRemove = false;else if (next && nodeApi.isInline(next, _this2.schema)) isRemove = false;else if (prev && nodeApi.isInline(prev, _this2.schema)) isRemove = false;
if (isRemove) {
text = text.replace(/\u200b/g, '');
node.text(text);
}
} else if (/^\n(\t)[0,]$/.test(text)) {
var _parent$get;
node.remove();
if (((_parent$get = parent.get()) === null || _parent$get === void 0 ? void 0 : _parent$get.childNodes.length) === 0) {
parent.after('
');
parent.remove();
}
return;
} else if (/^\n$/.test(text)) {
if (nodeApi.isList(parent)) {
node.remove();
return;
}
var _next = node.next();
if (_next && nodeApi.isBlock(_next)) node.remove();
}
if (nodeApi.isList(parent)) {
var _next2 = node.next();
var _prev = node.prev();
var addCardToCustomize = function addCardToCustomize(node, target) {
if (nodeApi.isCustomize(node)) {
var first = node.first();
if (first && first.isCard()) {
var cardName = first.attributes(CARD_KEY) || first.attributes(READY_CARD_KEY);
if (cardName) list.addCardToCustomize(target, cardName);
}
}
};
var cloneLi = null;
if ((_next2 === null || _next2 === void 0 ? void 0 : _next2.name) === 'li') {
cloneLi = _next2.clone();
addCardToCustomize(_next2, cloneLi);
} else if ((_prev === null || _prev === void 0 ? void 0 : _prev.name) === 'li') {
cloneLi = _prev.clone();
addCardToCustomize(_prev, cloneLi);
} else {
cloneLi = $("");
}
node.before(cloneLi);
cloneLi.append(node);
return cloneLi;
}
return undefined;
}
var styles = node.css();
for (var key in defaultStyle) {
var value = styles[key];
if (!value) continue;
if (key.endsWith('color')) {
value = colord.colord(value).toHex();
}
if (value.toLowerCase() === defaultStyle[key].toLowerCase()) {
node.css(key, '');
}
} //处理后如果不是一个有效的节点就移除包裹
var type = _this2.schema.getType(node);
if (!type) {
var first = node.first();
nodeApi.unwrap(node);
return first;
}
nodeApi.removeMinusStyle(node, 'text-indent');
if (nodeApi.isList(node)) {
node.css('padding-left', '');
}
var attributes = node.attributes(); // 删除空 style 属性
if (attributes.style && attributes.style.trim() === '') {
node.removeAttributes('style');
} // 删除空 span
while (node.name === 'span' && nodeApi.isEmpty(node)) {
var children = node.children();
if (children.length > 0) {
break;
}
parent = node.parent();
node.remove();
if (!parent) return undefined;
node = parent;
parent = node.parent();
if (!parent) return undefined;
type = undefined;
attributes = undefined;
}
if (!attributes) attributes = node.attributes(); // 跳过Card
if (attributes[READY_CARD_KEY]) {
return undefined;
}
var nodeIsBlock = type ? type === 'block' : nodeApi.isBlock(node, _this2.schema);
var nodeIsVoid = nodeApi.isVoid(node, _this2.schema);
var parentIsBlock = nodeApi.isBlock(parent, _this2.schema); // 删除零高度的空行
if (nodeIsBlock && attributes['data-type'] !== 'p' && !nodeIsVoid && !parentIsBlock && //!node.isSolid() &&
nodeApi.html(node) === '') {
node.remove();
return undefined;
} // 段落
if (attributes['data-type'] === 'p') {
node.removeAttributes('data-type');
}
if (nodeIsBlock && ((_parent2 = parent) === null || _parent2 === void 0 ? void 0 : _parent2.name) === 'p') {
var _parent3;
nodeApi.unwrap(parent);
parent = node.parent();
if (((_parent3 = parent) === null || _parent3 === void 0 ? void 0 : _parent3.fragment) === fragment) parent = undefined;
parentIsBlock = parent ? nodeApi.isBlock(parent, _this2.schema) : false;
}
var parentIsList = parent ? nodeApi.isList(parent) : false; // 补齐 ul 或 ol
if (node.name === 'li' && parent && !parentIsList) {
var ul = $('');
node.before(ul);
ul.append(node);
return undefined;
}
if (nodeApi.isList(node) && parent && nodeApi.isList(parent)) {
// 分割付节点list
var leftList = [];
var rightList = [];
var isLeft = true;
var rootChildren = parent.children().toArray();
var tempList = parent.clone();
var appendToTemp = function appendToTemp() {
var _tempList$get$childNo, _tempList$get;
if (((_tempList$get$childNo = (_tempList$get = tempList.get()) === null || _tempList$get === void 0 ? void 0 : _tempList$get.childNodes.length) !== null && _tempList$get$childNo !== void 0 ? _tempList$get$childNo : 0) > 0) {
if (isLeft) leftList.push(tempList);else rightList.push(tempList);
tempList = parent.clone();
return true;
}
return false;
};
/**
*
*
*
*/
rootChildren.forEach(function (child, index) {
if (!child) return;
if (isLeft && child.equal(node)) {
// 最后一个位置加入到右边
if (rootChildren.length - 1 === index) {
appendToTemp();
rightList.push(node);
} // 在第一个位置,加入到最左边
else if (index === 0) leftList.push(node); // 中间位置,先append,然后加入到左边
else {
appendToTemp();
leftList.push(node);
}
isLeft = false;
return;
}
if (child.name === 'li') {
tempList.append(child);
return;
} else {
appendToTemp();
}
if (isLeft) leftList.push(child);else rightList.push(child);
});
appendToTemp();
var indent = parent.attributes(list.INDENT_KEY) || '0';
node.attributes(list.INDENT_KEY, indent);
list.addIndent(node, 1);
var _prev2 = parent;
leftList.forEach(function (childNode) {
var _child$get;
var child = $(childNode);
if (!child || ((_child$get = child.get()) === null || _child$get === void 0 ? void 0 : _child$get.childNodes.length) === 0) return;
_prev2.after(child);
_prev2 = child;
});
rightList.forEach(function (childNode) {
var _child$get2;
var child = $(childNode);
if (!child || ((_child$get2 = child.get()) === null || _child$get2 === void 0 ? void 0 : _child$get2.childNodes.length) === 0) return;
_prev2.after(child);
_prev2 = child;
});
parent.remove();
return node || undefined;
} // 补齐 li
if (node.name !== 'li' && parentIsList) {
if (node.name === 'br') {
node.remove();
return undefined;
}
var li = $('');
node.before(li);
li.append(node);
return undefined;
} // two- three
four
/**
*
- 缺少用户添加问题输入框说明/placeholder的功能
- 缺少拖动添加功能
- 填空式
- 调整填空题类型(名字、电话等),如标题为空的情况下,应该自动换成对应类型的标题
- 选择式
*/
if (nodeApi.isList(node) && ((_parent4 = parent) === null || _parent4 === void 0 ? void 0 : _parent4.name) === 'li') {
var _parent5, _parent6, _parent6$parent, _parent7, _parent8, _next4;
// li没有父节点就移除包裹
var rootListElement = (_parent5 = parent) === null || _parent5 === void 0 ? void 0 : _parent5.parent();
if (!rootListElement) {
nodeApi.unwrap(parent);
return undefined;
} // 分割付节点list
var _leftList = rootListElement.clone();
var _rightList = rootListElement.clone();
var _isLeft = true;
var _rootChildren = rootListElement.children().toArray();
_rootChildren.forEach(function (child) {
if (!child) return;
if (_isLeft && child.equal(parent)) {
_isLeft = false;
return;
}
if (_isLeft) _leftList.append(child);else _rightList.append(child);
});
var isCustomizeList = (_parent6 = parent) === null || _parent6 === void 0 ? void 0 : (_parent6$parent = _parent6.parent()) === null || _parent6$parent === void 0 ? void 0 : _parent6$parent.hasClass('data-list');
var _children = (_parent7 = parent) === null || _parent7 === void 0 ? void 0 : _parent7.children();
var _li = null;
var _next3 = null;
_children.each(function (child, index) {
var node = _children.eq(index);
if (!node || nodeApi.isEmptyWithTrim(node) && !nodeApi.isVoid(node)) {
return;
}
var isList = nodeApi.isList(node);
var leftLast = _leftList[_leftList.length - 1];
if (isList) {
var _$;
var _indent = ((_$ = $(leftLast)) === null || _$ === void 0 ? void 0 : _$.attributes(list.INDENT_KEY)) || '0';
node.attributes(list.INDENT_KEY, _indent);
list.addIndent(node, 1);
_leftList[_leftList.length] = node[0];
_li = null;
return;
} else if (nodeApi.isBlock(child, _this2.schema)) {
var len = _leftList.length;
_leftList[len] = node[0];
_leftList[len + 1] = _leftList.clone()[0];
_li = null;
return;
}
if (!_li) {
var _$2;
_li = isCustomizeList ? $("")) : $('');
var last = (_$2 = $(leftLast)) === null || _$2 === void 0 ? void 0 : _$2.last();
if (last) last === null || last === void 0 ? void 0 : last.after(_li);else $(leftLast).append(_li);
}
_li.append(child);
if (!_next3) {
_next3 = _li;
}
});
(_parent8 = parent) === null || _parent8 === void 0 ? void 0 : _parent8.remove();
var _prev3 = rootListElement;
_leftList.each(function (childNode) {
var _child$get3;
var child = $(childNode);
if (!child || ((_child$get3 = child.get()) === null || _child$get3 === void 0 ? void 0 : _child$get3.childNodes.length) === 0) return;
_prev3.after(child);
_prev3 = child;
});
_rightList.each(function (childNode) {
var _child$get4;
var child = $(childNode);
if (!child || ((_child$get4 = child.get()) === null || _child$get4 === void 0 ? void 0 : _child$get4.childNodes.length) === 0) return;
_prev3.after(child);
_prev3 = child;
});
rootListElement.remove();
return ((_next4 = _next3) === null || _next4 === void 0 ? void 0 : _next4.next()) || _leftList.next() || undefined;
} // p 改成 li
if (node.name === 'p' && parentIsList) {
var newNode = $('');
nodeApi.replace(node, newNode);
return newNode;
} // 处理空 Block
if (nodeIsBlock && !nodeIsVoid && nodeApi.html(node).trim() === '') {
// to
if (nodeApi.isRootBlock(node, _this2.schema) || node.name === 'li') {
nodeApi.html(node, '
');
}
} // foo
if (nodeIsBlock && ((_parent9 = parent) === null || _parent9 === void 0 ? void 0 : _parent9.name) === 'li') {
var _node$get$childNodes, _node$get;
//
var childNodes = (_node$get$childNodes = (_node$get = node.get()) === null || _node$get === void 0 ? void 0 : _node$get.childNodes) !== null && _node$get$childNodes !== void 0 ? _node$get$childNodes : [];
if (node.name === 'p') {
var _next5 = node.next();
if (childNodes.length === 0 && !_next5) {
node.append('
');
}
var _first = node.first();
if (_next5 && _next5.name === 'p') {
node.append('
');
}
nodeApi.unwrap(node);
return _first;
} else {
var pParent = parent.parent();
if (!pParent) return undefined;
var _leftList2 = pParent.clone();
var _rightList2 = pParent.clone();
var _prev4 = parent.prev();
while (_prev4) {
_leftList2.prepend(_prev4);
_prev4 = parent.prev();
}
var _next6 = parent.next();
while (_next6) {
_rightList2.append(_next6);
_next6 = parent.next();
}
var leftLi = parent.clone();
var rightLi = parent.clone();
var prevC = node.prev();
while (prevC) {
leftLi.prepend(prevC);
prevC = node.prev();
}
var nextC = node.next();
while (nextC) {
rightLi.append(nextC);
nextC = node.next();
}
pParent.after(node);
if (leftLi.first()) _leftList2.append(leftLi);
if (rightLi.first()) _rightList2.prepend(rightLi);
if (_leftList2.first()) pParent.before(_leftList2);
if (_rightList2.first()) node.after(_rightList2);
pParent.remove();
return undefined;
}
}
if (!nodeIsBlock && nodeApi.isInline(node) && !node.isCard() && !nodeIsVoid) {
var isVoid = node.allChildren().some(function (node) {
return nodeApi.isVoid(node, _this2.schema);
});
if (nodeApi.isEmptyWithTrim(node) && !isVoid) node.remove();else inline.repairCursor(node);
} // 移除两边的 BR
nodeApi.removeSide(node); // 处理嵌套
var nodeParent = parent;
var handleBlock = function handleBlock(node) {
if (nodeParent && !nodeParent.fragment && nodeApi.isBlock(node, _this2.schema) && nodeApi.isBlock(nodeParent, _this2.schema) && !_this2.schema.isAllowIn(nodeParent.name, node.name)) {
var _children2 = node.children();
nodeApi.unwrap(node);
_children2.each(function (_, index) {
handleBlock(_children2.eq(index));
});
}
};
handleBlock(node); // 处理block在其它非block节点下的情况
while (node.length > 0 && nodeParent && !nodeParent.fragment && nodeApi.isBlock(node, _this2.schema) && !nodeApi.isBlock(nodeParent, _this2.schema)) {
var nodeClone = node.clone();
nodeApi.unwrap(node);
nodeParent.before(nodeClone);
nodeClone.append(nodeParent);
node = nodeClone;
nodeParent = node.parent();
}
var nodeIsMark = nodeApi.isMark(node, _this2.schema); // 处理有关mark不能嵌入到block节点内的情况
if (node.length > 0 && nodeIsMark) {
var block = blockApi.closest(node);
if (!block.equal(node)) {
var _blockPlugin$disableM;
var markPlugin = markApi.findPlugin(node);
var blockPlugin = blockApi.findPlugin(block);
if (markPlugin && (blockPlugin === null || blockPlugin === void 0 ? void 0 : (_blockPlugin$disableM = blockPlugin.disableMark) === null || _blockPlugin$disableM === void 0 ? void 0 : _blockPlugin$disableM.includes(markPlugin.name))) {
var child = node.first();
nodeApi.unwrap(node);
return child || undefined;
}
}
} // mark 相同的嵌套
if (nodeIsMark) {
var _markPlugin = markApi.findPlugin(node);
var topMarkPlugins = currentMarkPlugins.concat();
topMarkPlugins.pop();
if (_markPlugin) {
var plugin = topMarkPlugins.find(function (item) {
var _item$plugin;
return ((_item$plugin = item.plugin) === null || _item$plugin === void 0 ? void 0 : _item$plugin.name) === _markPlugin.name && item.node.length > 0 && !item.node.equal(node);
});
if (plugin) {
var _plugin$node$get;
if (((_plugin$node$get = plugin.node.get()) === null || _plugin$node$get === void 0 ? void 0 : _plugin$node$get.childNodes.length) === 1) {
nodeApi.unwrap(plugin.node);
} else {
nodeApi.unwrap(node);
}
return;
}
}
} // mark 按级别排序
nodeParent = parent;
if (node.length > 0 && nodeParent && nodeApi.isMark(nodeParent, _this2.schema) && nodeIsMark) {
var _currentMarkPlugins;
var pMarkPlugin = markApi.findPlugin(nodeParent);
var cMarkPlugin = (_currentMarkPlugins = currentMarkPlugins[currentMarkPlugins.length - 1]) === null || _currentMarkPlugins === void 0 ? void 0 : _currentMarkPlugins.plugin;
if (pMarkPlugin && cMarkPlugin && cMarkPlugin.mergeLeval > pMarkPlugin.mergeLeval) {
var cloneParent = nodeParent.clone(false);
var childrenNodes = nodeParent.children().toArray();
var startP = cloneParent.clone();
var endP = cloneParent.clone();
var isStart = true;
var index = -1;
childrenNodes.forEach(function (children, i) {
if (children.equal(node)) {
var nChildren = node.children();
cloneParent.append(nChildren);
node.append(cloneParent);
isStart = false;
index = i;
} else if (isStart) {
startP.append(children);
} else {
endP.append(children);
}
});
if (index > 0) {
nodeParent.before(startP);
}
if (index < childrenNodes.length - 1) {
nodeParent.after(endP);
}
if (index > -1) {
nodeParent.before(node);
nodeParent.remove();
currentMarkPlugins.splice(currentMarkPlugins.length - 2, 1);
return node;
}
}
}
return undefined;
}, undefined, undefined, function (startNode) {
if (nodeApi.isMark(startNode)) {
var plugin = markApi.findPlugin(startNode);
startNode['is_mark'] = true;
currentMarkPlugins.push({
plugin: plugin,
node: startNode
});
}
}, function (endNode) {
if (endNode['is_mark']) {
currentMarkPlugins.pop();
}
});
}
}, {
key: "normalize",
value: function normalize() {
var _this3 = this;
var forceGenerateAllId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var nodeApi = this.engine.node;
var fragment = this.parser();
this.elementNormalize(fragment);
var range = this.engine.change.range.get();
var root = range.commonAncestorNode;
var inline = this.engine.inline.closest(root);
if (root.inEditor() && !inline.isCard() && nodeApi.isInline(inline, this.schema)) {
this.removeElementNodes($(fragment));
return fragment;
}
if (root.inEditor() && root.isText() && range.startContainer === range.endContainer) {
var text = root[0].nodeValue;
var leftText = text === null || text === void 0 ? void 0 : text.substr(0, range.startOffset);
var rightText = text === null || text === void 0 ? void 0 : text.substr(range.endOffset); // 光标在 [text](|) 里
if (/\[.*?\]\($/.test(leftText || '') && /^\)/.test(rightText || '')) {
this.removeElementNodes($(fragment));
return fragment;
}
}
$(fragment).traverse(function (node) {
var _node$get2;
if (node.fragment === fragment) return undefined;
var first = (_node$get2 = node.get()) === null || _node$get2 === void 0 ? void 0 : _node$get2.firstChild;
if (node.length > 0 && node[0].parentNode) _this3.engine.trigger('paste:each', node); // 删除非block节点的换行 \r\n\r\n 0 && match.index < _text.length - 1) {
var nextReg = matchNode.get().splitText(match.index);
var endReg = nextReg.splitText(match[0].length);
matchNode.after(nextReg);
nextReg.after(endReg);
if (!matchNode.text()) matchNode.remove();
var endNode = $(endReg);
matchNode = endNode;
_text = endNode.text();
match = /((\n)+)/.exec(_text);
}
} // 删除包含Card的 pre 标签
else if (node.name === 'pre' && node.find(READY_CARD_SELECTOR).length > 0) {
nodeApi.unwrap(node);
} // 如果这个节点被移除了,直接遍历他的子节点
if (node.length === 0 && first) return $(first);
return undefined;
});
this.engine.trigger('paste:each-after', $(fragment));
var node = nodeApi.normalize($(fragment));
if (node.fragment) fragment = node.fragment;
fragment.normalize();
var fragmentNode = $(fragment);
var children = fragmentNode.find('ul,ol');
children.each(function (_, index) {
var child = children.eq(index);
if (child && nodeApi.isList(child)) {
_this3.engine.list.addStart(child);
}
});
this.engine.nodeId.generateAll($(fragment), forceGenerateAllId);
return fragment;
}
}, {
key: "removeElementNodes",
value: function removeElementNodes(fragment) {
var _this4 = this;
var nodes = fragment.allChildren();
nodes.forEach(function (node) {
if (node.isElement()) {
_this4.engine.node.unwrap(node);
}
});
}
}]);
return Paste;
}();
/**
* 卡片类型
*/
(function (CardType) {
CardType["INLINE"] = "inline";
CardType["BLOCK"] = "block";
})(exports.CardType || (exports.CardType = {}));
(function (CardActiveTrigger) {
CardActiveTrigger["CARD_CHANGE"] = "card_change";
CardActiveTrigger["CLICK"] = "click";
CardActiveTrigger["MOUSE_DOWN"] = "mouse_down";
})(exports.CardActiveTrigger || (exports.CardActiveTrigger = {}));
(function (SelectStyleType) {
SelectStyleType["NONE"] = "none";
SelectStyleType["BACKGROUND"] = "background";
SelectStyleType["BORDER"] = "border";
})(exports.SelectStyleType || (exports.SelectStyleType = {}));
var _lastePasteRange = /*#__PURE__*/_classPrivateFieldLooseKey("lastePasteRange");
var NativeEvent = /*#__PURE__*/function () {
function NativeEvent(engine) {
_classCallCheck(this, NativeEvent);
this.engine = void 0;
Object.defineProperty(this, _lastePasteRange, {
writable: true,
value: void 0
});
this.prevSelection = null;
this.engine = engine;
}
_createClass(NativeEvent, [{
key: "repairInput",
value: function repairInput(event, range) {
var _range = range,
commonAncestorNode = _range.commonAncestorNode;
var card = this.engine.card.find(commonAncestorNode);
var _this$engine = this.engine,
node = _this$engine.node,
mark = _this$engine.mark,
change = _this$engine.change;
if (card && card.type === exports.CardType.INLINE) {
if (card.isLeftCursor(commonAncestorNode)) {
var cardLeft = commonAncestorNode.closest(CARD_LEFT_SELECTOR);
var cardLeftText = cardLeft.text().replace(/\u200B/g, '');
if (cardLeftText) {
cardLeftText = escape(cardLeftText);
range.setStartBefore(card.root);
range.collapse(true);
node.html(cardLeft, '');
node.insertText(cardLeftText, range);
change.apply(range);
}
} else if (card.isRightCursor(commonAncestorNode)) {
var cardRight = commonAncestorNode.closest(CARD_RIGHT_SELECTOR);
var cardRightText = cardRight.text().replace(/\u200B/g, '');
if (cardRightText) {
cardRightText = escape(cardRightText); // 卡片有样式,并且后面没有节点了
var next = card.root.next();
var marks = card.queryMarks ? card.queryMarks(true) : [];
if (marks.length > 0) {
var newNode = marks[marks.length - 1];
newNode.append(cardRightText);
for (var i = marks.length - 2; i >= 0; i--) {
newNode = marks[i].append(newNode);
}
card.root.after(newNode);
range.select(newNode, true).collapse(false);
} else if (next && (next.isText() || node.isMark(next))) {
range.select(next, true).collapse(true);
node.insertText(cardRightText, range);
} else {
range.setEndAfter(card.root);
range.collapse(false);
node.insertText(cardRightText, range);
}
node.html(cardRight, '');
change.apply(range);
}
} else change.range.toTrusty(range);
}
var _range$cloneRange$shr = range.cloneRange().shrinkToTextNode(),
startNode = _range$cloneRange$shr.startNode,
startOffset = _range$cloneRange$shr.startOffset;
var parent = startNode.parent(); //输入时删除mark标签内零宽字符。
if (startNode.isText() && parent && node.isMark(parent)) {
var textNode = startNode.get();
var text = startNode.text();
var inputType = event.inputType; //mark 插件禁止跟随样式时,将输入字符设置到mark标签外
//输入光标在mark节点末尾
if (startOffset === text.length && event.data && inputType && inputType.indexOf('insert') === 0) {
var markParent = parent;
var markTops = []; //循环查找
while (markParent && node.isMark(markParent)) {
var _markParent, _markParent2;
var markPlugin = mark.findPlugin(markParent); //插件禁止跟随
if (markPlugin && !markPlugin.followStyle) {
markTops.push(markParent);
}
markParent = markParent.parent(); //如果还有位于下方的同级节点,并且父级节点也是mark节点,说明当前光标不在末尾了
var markParentP = (_markParent = markParent) === null || _markParent === void 0 ? void 0 : _markParent.parent();
if (((_markParent2 = markParent) === null || _markParent2 === void 0 ? void 0 : _markParent2.next()) && markParentP && node.isMark(markParentP)) {
break;
}
} //查看下一个节点是否是紧紧挨着的相同样式如果有,那就继续跟随样式
var startNext = startNode.next();
markTops.forEach(function (markTop, index) {
//第一种:abc123 或者 abc123 继续跟随
//第二种:abc123 或者 abc123 继续跟随
//第三种: abc123 继续跟随
//是开始节点所在的mark节点,如果开始节点后面有节点就继续跟随
if (parent.equal(markTop) && startNext) {
markTops.splice(index, 1);
return;
}
var next = markTop.next();
var curNode = markTop; //循环找到下一个节点,如果没有下一级节点,从父级节点查找父级的下一级。如果有下一级节点,并且父节点
while (!next && curNode) {
//找到父节点
var _parent = curNode.parent(); //如果父节点是块级节点,就不找了
if (_parent && node.isBlock(_parent)) break; //找到父级节点的下一级
next = (_parent === null || _parent === void 0 ? void 0 : _parent.next()) || null;
curNode = _parent;
}
var first = next;
while (first && !first.isText()) {
if (node.isMark(first) && mark.compare(first, markTop)) {
markTops.splice(index, 1);
break;
}
first = first.first();
}
});
if (markTops.length > 0) {
var lastText = textNode.splitText(text.length - event.data.length);
lastText.remove();
if (node.isEmpty(parent)) parent.remove();
mark.unwrap(markTops.map(function (mark) {
return mark.clone();
}));
node.insertText(text.substr(text.length - event.data.length));
mark.merge();
range = change.range.get().cloneRange().shrinkToTextNode();
startNode = range.startNode;
startOffset = range.startOffset;
textNode = startNode.get();
text = startNode.text();
}
} //输入光标在mark节点开始位置
else if (event.data && startOffset === event.data.length && inputType && inputType.indexOf('insert') === 0) {
var _markParent3 = parent;
var _markTops = []; //循环查找
while (_markParent3 && node.isMark(_markParent3)) {
var _markParent4, _markParent5;
var _markPlugin = mark.findPlugin(_markParent3); //插件禁止跟随
if (_markPlugin && !_markPlugin.followStyle) {
_markTops.push(_markParent3);
}
_markParent3 = _markParent3.parent(); //如果还有位于下方的同级节点,并且父级节点也是mark节点,说明当前光标不在末尾了
var _markParentP = (_markParent4 = _markParent3) === null || _markParent4 === void 0 ? void 0 : _markParent4.parent();
if (((_markParent5 = _markParent3) === null || _markParent5 === void 0 ? void 0 : _markParent5.prev()) && _markParentP && node.isMark(_markParentP)) {
break;
}
} //查看上一个节点是否是紧紧挨着的相同样式如果有,那就继续跟随样式
var startPrev = startNode.prev();
_markTops.forEach(function (markTop, index) {
//第一种:abc123 或者 abc123 继续跟随
//第二种:abc123 或者 abc123 继续跟随
//第三种: 123abc 继续跟随
//是开始节点所在的mark节点,如果开始节点后面有节点就继续跟随
if (parent.equal(markTop) && startPrev) {
_markTops.splice(index, 1);
return;
}
var prev = markTop.prev();
var curNode = markTop; //循环找到上一个节点,如果没有上一级节点,从父级节点查找父级的上一级。如果有上一级节点,并且父节点
while (!prev && curNode) {
//找到父节点
var _parent2 = curNode.parent(); //如果父节点是块级节点,就不找了
if (_parent2 && node.isBlock(_parent2)) break; //找到父级节点的下一级
prev = (_parent2 === null || _parent2 === void 0 ? void 0 : _parent2.prev()) || null;
curNode = _parent2;
}
var last = prev;
while (last && !last.isText()) {
if (node.isMark(last) && mark.compare(last, markTop)) {
_markTops.splice(index, 1);
break;
}
last = last.last();
}
});
if (_markTops.length > 0) {
textNode.splitText(event.data.length);
textNode.remove();
if (node.isEmpty(parent)) parent.remove();
mark.unwrap(_markTops.map(function (mark) {
return mark.clone();
}));
node.insertText(event.data === '' ? '\xa0' : event.data);
mark.merge();
range = change.range.get().cloneRange().shrinkToTextNode();
startNode = range.startNode;
startOffset = range.startOffset;
textNode = startNode.get();
text = startNode.text();
}
} //输入时删除mark标签内零宽字符。
if (text.length > 0 && /^\u200B$/g.test(text.substr(0, 1))) {
textNode.splitText(1);
textNode.remove();
}
} //输入时删除mark标签外最后的零宽字符
var prev = startNode.prev();
if (startNode.isText() && prev && node.isMark(prev)) {
var _textNode = startNode.get();
var _text = startNode.text();
if (_text.length > 0 && /^\u200B$/g.test(_text.substr(0, 1))) {
_textNode.splitText(1);
_textNode.remove();
}
}
}
}, {
key: "handleSelectionChange",
value: function handleSelectionChange() {
var _this$prevSelection,
_this$prevSelection2,
_this$prevSelection3,
_this$prevSelection4,
_this = this;
var _this$engine2 = this.engine,
change = _this$engine2.change,
container = _this$engine2.container,
card = _this$engine2.card;
if (change.isComposing()) return;
var window = container.window;
var selection = window === null || window === void 0 ? void 0 : window.getSelection();
if (((_this$prevSelection = this.prevSelection) === null || _this$prevSelection === void 0 ? void 0 : _this$prevSelection.anchorNode) === (selection === null || selection === void 0 ? void 0 : selection.anchorNode) && ((_this$prevSelection2 = this.prevSelection) === null || _this$prevSelection2 === void 0 ? void 0 : _this$prevSelection2.anchorOffset) === (selection === null || selection === void 0 ? void 0 : selection.anchorOffset) && ((_this$prevSelection3 = this.prevSelection) === null || _this$prevSelection3 === void 0 ? void 0 : _this$prevSelection3.focusNode) === (selection === null || selection === void 0 ? void 0 : selection.focusNode) && ((_this$prevSelection4 = this.prevSelection) === null || _this$prevSelection4 === void 0 ? void 0 : _this$prevSelection4.focusOffset) === (selection === null || selection === void 0 ? void 0 : selection.focusOffset)) return;
this.prevSelection = selection ? {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
} : null;
if (selection && selection.anchorNode) {
var range = Range.from(this.engine, selection); // 不在编辑器内不处理
if (!range.commonAncestorNode.inEditor(container)) return;
change.onSelect(); // 判断当前光标是否包含卡片或者在卡片内部
var containsCard = range.containsCard() || range.commonAncestorNode.closest(CARD_SELECTOR).length > 0 && range.startNode.closest("".concat(CARD_LEFT_SELECTOR, ",").concat(CARD_RIGHT_SELECTOR, ",").concat(UI_SELECTOR)).length === 0;
var isSingle = range.collapsed;
if (!isSingle) {
var startNode = range.startNode,
endNode = range.endNode,
startOffset = range.startOffset,
endOffset = range.endOffset;
var startElement = startNode.isElement() && !startNode.isCard() ? startNode.children().eq(startOffset) : startNode;
var endElement = endNode.isElement() && !endNode.isCard() ? endNode.children().eq(endOffset - 1) : endNode;
if (startElement && endElement && startElement.isCard() && startElement.equal(endElement)) {
isSingle = true;
}
}
card.each(function (card) {
var center = card.getCenter();
if (center && center.length > 0) {
var isSelect = selection.containsNode ? selection.containsNode(center[0]) : false;
if (!isSelect && containsCard && selection.focusNode) {
var focusCard = _this.engine.card.find(selection.focusNode);
if (focusCard) {
isSingle = !selection.anchorNode || focusCard.root.contains(selection.anchorNode);
if (isSingle && card.root.equal(focusCard.root)) {
isSelect = true;
}
} // 找到一次其它的就不需要再去比对了
if (isSelect && isSingle) containsCard = false;
}
var autoSelected = card.constructor.autoSelected;
card.select(isSelect && (!isSingle || autoSelected !== false));
}
});
}
}
}, {
key: "init",
value: function init() {
var _this2 = this;
var _this$engine3 = this.engine,
change = _this$engine3.change,
card = _this$engine3.card,
clipboard = _this$engine3.clipboard;
change.event.onInput(function (event) {
var range = change.range.get();
_this2.repairInput(event, range);
change.range.select(range);
change.onSelect(range);
change.change();
});
change.event.onDocument('selectionchange', function () {
_this2.handleSelectionChange();
});
change.event.onSelect(function (event) {
var range = change.range.get();
if (range.startNode.closest(ROOT_SELECTOR).length === 0) return;
if (range.collapsed && range.containsCard()) {
change.range.toTrusty(range);
}
change.range.select(range); // 方向键选择不触发 card 激活
if (!isHotkey.isHotkey('shift+left', event) && !isHotkey.isHotkey('shift+right', event) && !isHotkey.isHotkey('shift+up', event) && !isHotkey.isHotkey('shift+down', event)) {
card.activate(range.commonAncestorNode);
}
change.onSelect(range);
}, function () {
change.onSelectStart();
}, function () {
change.onSelectEnd();
});
change.event.onDocument('mousedown', function (e) {
if (!e.target) return;
var targetNode = $(e.target); // 点击元素已被移除
if (targetNode.closest('body').length === 0) {
return;
} // 阅读模式节点
if (targetNode.closest('.am-view').length > 0) {
return;
} // 工具栏、侧边栏、内嵌工具栏的点击
var node = targetNode;
while (node) {
var attrValue = node.attributes(DATA_ELEMENT);
if (attrValue && [ROOT, EDITABLE].indexOf(attrValue) < 0) {
return;
}
node = node.parent();
}
card.activate(targetNode, exports.CardActiveTrigger.MOUSE_DOWN, e);
});
change.event.onDocument('copy', function (event) {
var range = change.range.get();
if (!_this2.engine.container.contains(range.commonAncestorNode)) return;
clipboard.write(event);
});
change.event.onDocument('cut', function (event) {
var range = change.range.get();
if (!_this2.engine.container.contains(range.commonAncestorNode) || _this2.engine.readonly) return;
var data = clipboard.write(event, undefined);
if (data) {
event.stopPropagation();
clipboard.cut();
change.change();
}
});
var convertMD = function convertMD(text) {
change.cacheRangeBeforeCommand();
var markdown = createMarkdownIt(_this2.engine, 'zero');
markdown.enable(['paragraph', 'html_inline', 'newline']); //.disable(['strikethrough', 'emphasis', 'link', 'image', 'table', 'code', 'blockquote', 'hr', 'list', 'heading'])
var tokens = markdown.parse(text, {});
if (tokens.length === 0) return;
return convertMarkdown(_this2.engine, markdown, tokens);
};
var pasteMarkdown = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(text) {
var _this2$engine$options;
var result, handlePaste;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
// 先解析text
result = convertMD(text);
if (!(result === null)) {
_context.next = 3;
break;
}
return _context.abrupt("return");
case 3:
handlePaste = function handlePaste() {
_this2.engine.history.saveOp();
change.cacheRangeBeforeCommand();
_this2.paste(result, _classPrivateFieldLooseBase(_this2, _lastePasteRange)[_lastePasteRange], undefined, false);
};
if (!(((_this2$engine$options = _this2.engine.options.markdown) === null || _this2$engine$options === void 0 ? void 0 : _this2$engine$options.mode) !== 'confirm')) {
_context.next = 7;
break;
}
handlePaste();
return _context.abrupt("return");
case 7:
// 提示是否要转换
_this2.engine.messageConfirm('markdown', _this2.engine.language.get('checkMarkdown', 'title')).then(function () {
handlePaste();
}).catch(function (err) {
if (err) _this2.engine.messageError('markdown', err);
});
case 8:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function pasteMarkdown(_x) {
return _ref.apply(this, arguments);
};
}();
change.event.onPaste(function (data) {
var html = data.html,
text = data.text,
files = data.files,
isPasteText = data.isPasteText;
var source = '';
if (files.length === 0) {
// 纯文本粘贴
if (isPasteText) {
var value = '';
if (text) value = text;else if (html) value = new Parser(html, _this2.engine).toText();
source = new TextParser(value).toHTML();
} else {
// 富文本粘贴
if (html && html.indexOf('') > -1) {
source = html;
} else if (html) {
source = html;
} else if (text) {
source = new TextParser(text).toHTML();
}
}
}
if (_this2.engine.trigger('paste:event', data, source) === false) return;
if (files.length === 0) {
change.cacheRangeBeforeCommand();
_this2.paste(source);
var markdown = _this2.engine.options.markdown || {};
if (markdown.mode !== false) {
// 单独的链接不做解析,由 paste:each 触发执行
if (!markdown.check && text && !/^https?:\/\/\S+$/i.test(text.trim())) {
if (!text) return; // 没有 html,直接转换 markdown
if (!html) {
setTimeout(function () {
pasteMarkdown(text);
}, 0);
return;
} // 检测 text 中是否有markdown语法
var rows = text.split(/\r\n|\n/) || ''; // 所有有效的段落
var rowCount = 0; // 有语法的段落
var validCount = 0;
var isCodeblock = false; // 有序列表的markdown 对比html中的有序列表节点,如果不存在节点才算作markdown
var root = new DOMParser().parseFromString(html, 'text/html');
var lis = root.querySelectorAll('li');
var orderTexts = [];
lis.forEach(function (li) {
var _li$textContent, _li$parentElement;
var text = (_li$textContent = li.textContent) !== null && _li$textContent !== void 0 ? _li$textContent : '';
if (((_li$parentElement = li.parentElement) === null || _li$parentElement === void 0 ? void 0 : _li$parentElement.nodeName) === 'OL' || /\d\.\s+/.test(text)) {
orderTexts.push(text);
}
});
for (var i = 0; i < rows.length; i++) {
var rowText = rows[i];
if (!rowText.trim()) continue;
if (rowText.startsWith('```')) {
if (!isCodeblock) {
isCodeblock = true;
validCount++;
rowCount++;
} else {
isCodeblock = false;
}
continue;
}
if (isCodeblock) continue;
rowCount++;
if (/^(#|\*|-|\+|\[ \]|\[x\]|>){1,}\s+/.test(rowText)) {
validCount++;
} else if (/^\d\.\s+/.test(rowText)) {
if (!orderTexts.includes(rowText) && !orderTexts.includes(rowText.replace(/^\d\./, '').trim())) {
validCount++;
}
} else if (/^(---|\*\*\*|\+\+\+)/.test(rowText)) {
validCount++;
} else if (/(\*|~|\^|_|\`|\]\(https?:\/\/)/.test(rowText)) {
validCount++;
}
}
if (validCount > 0 && (rowCount === 0 || validCount / rowCount > 0.5)) {
setTimeout(function () {
pasteMarkdown(text);
}, 0);
}
} else if (markdown.check) {
markdown.check(text !== null && text !== void 0 ? text : '', html !== null && html !== void 0 ? html : '').then(function (result) {
if (!!result) {
pasteMarkdown(result);
}
});
}
}
}
});
var canInsert = function canInsert(range) {
// 找不到目标位置
// TODO: 临时解决,如果 drop Range 在Card里则不触发
return !range || card.closest(range.commonAncestorContainer);
};
change.event.onDrop(function (_ref2) {
var event = _ref2.event,
range = _ref2.range,
card = _ref2.card,
files = _ref2.files;
if (card) {
event.preventDefault();
if (canInsert(range)) return;
var cardEntry = card.constructor;
var cardName = cardEntry.cardName;
var cardValue = card.getValue();
_this2.engine.card.remove(card.root);
change.range.select(range);
_this2.engine.card.insert(cardName, cardValue);
}
if (files.length > 0) {
event.preventDefault();
if (canInsert(range)) return;
change.range.select(range);
_this2.engine.trigger('drop:files', files);
}
});
}
}, {
key: "paste",
value: function paste(source, range, callback) {
var _this3 = this;
var followActiveMark = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var insert = arguments.length > 4 ? arguments[4] : undefined;
var forceGenerateAllId = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
var change = this.engine.change;
var fragment = new Paste(source, this.engine).normalize(forceGenerateAllId);
this.engine.trigger('paste:before', fragment);
if (insert) insert(fragment, range, undefined, followActiveMark);else change.insert(fragment, range, function (range) {
var _endNode$get;
_this3.engine.trigger('paste:insert', range);
var cloneRange = range.cloneRange();
var endNode = cloneRange.endNode;
var cardId = '';
if (endNode.isCard() && ((_endNode$get = endNode.get()) === null || _endNode$get === void 0 ? void 0 : _endNode$get.childNodes.length) === 0) {
cloneRange.setEndAfter(endNode);
cardId = endNode.attributes(DATA_ID);
}
_classPrivateFieldLooseBase(_this3, _lastePasteRange)[_lastePasteRange] = cloneRange;
range.collapse(false); // 卡片会出现未渲染的情况,选中在卡片后面
var card = range.startNode.closest("".concat(CARD_SELECTOR, ",").concat(READY_CARD_SELECTOR));
if (card.length > 0) {
var attributes = card.attributes();
if (attributes[CARD_LOADING_KEY] || attributes[READY_CARD_KEY]) {
range.setStartAfter(card);
}
}
var selection = range.createSelection();
_this3.engine.card.render(undefined, function (count) {
selection.move();
if (cardId) {
var newCard = _this3.engine.container.find("[data-id=\"".concat(cardId, "\"]"));
if (newCard.length > 0) {
cloneRange.setEndAfter(newCard);
_classPrivateFieldLooseBase(_this3, _lastePasteRange)[_lastePasteRange] = cloneRange;
}
}
range.scrollRangeIntoView();
change.range.select(range);
if (callback) {
callback(count);
}
_this3.engine.trigger('paste:after');
});
}, followActiveMark);
}
}]);
return NativeEvent;
}();
var _lastBlurRange = /*#__PURE__*/_classPrivateFieldLooseKey("lastBlurRange");
var _otpions = /*#__PURE__*/_classPrivateFieldLooseKey("otpions");
var ChangeRange = /*#__PURE__*/function () {
function ChangeRange(engine) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, ChangeRange);
this.engine = void 0;
Object.defineProperty(this, _lastBlurRange, {
writable: true,
value: void 0
});
Object.defineProperty(this, _otpions, {
writable: true,
value: void 0
});
this.engine = engine;
_classPrivateFieldLooseBase(this, _otpions)[_otpions] = options;
}
_createClass(ChangeRange, [{
key: "setLastBlurRange",
value: function setLastBlurRange(range) {
if (range === null || range === void 0 ? void 0 : range.commonAncestorNode.inEditor()) _classPrivateFieldLooseBase(this, _lastBlurRange)[_lastBlurRange] = range;else _classPrivateFieldLooseBase(this, _lastBlurRange)[_lastBlurRange] = undefined;
}
/**
* 获取安全可控的光标对象
* @param range 默认当前光标
*/
}, {
key: "toTrusty",
value: function toTrusty() {
var range = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.get();
// 如果不在编辑器内,聚焦到编辑器
var commonAncestorNode = range.commonAncestorNode;
if (!commonAncestorNode.isEditable() && !commonAncestorNode.inEditor()) {
range.select(this.engine.container, true).shrinkToElementNode().collapse(false);
} //卡片
var rangeClone = range.cloneRange();
rangeClone.collapse(true);
this.setCardRang(rangeClone);
if (!range.startNode.equal(rangeClone.startNode) || range.startOffset !== rangeClone.startOffset) range.setStart(rangeClone.startContainer, rangeClone.startOffset);
rangeClone = range.cloneRange();
rangeClone.collapse(false);
this.setCardRang(rangeClone);
if (!range.endNode.equal(rangeClone.endNode) || range.endOffset !== rangeClone.endOffset) range.setEnd(rangeClone.endContainer, rangeClone.endOffset);
if (range.collapsed) {
rangeClone = range.cloneRange();
rangeClone.enlargeFromTextNode();
var startNode = $(rangeClone.startContainer);
var startOffset = rangeClone.startOffset;
if (this.engine.node.isInline(startNode) && startOffset === 0) {
range.setStartBefore(startNode[0]);
}
if (this.engine.node.isInline(startNode) && startOffset === startNode[0].childNodes.length) {
range.setStartAfter(startNode[0]);
}
range.collapse(true);
}
return range;
}
}, {
key: "setCardRang",
value: function setCardRang(range) {
var _this = this;
var startNode = range.startNode,
startOffset = range.startOffset;
var card = this.engine.card;
var component = card.find(startNode);
if (component) {
var _startNode$0$parentEl;
var cardCenter = component.getCenter().get();
if (cardCenter && (!startNode.isElement() || ((_startNode$0$parentEl = startNode[0].parentElement) !== null && _startNode$0$parentEl !== void 0 ? _startNode$0$parentEl : startNode[0].parentNode) !== component.root[0] || startNode.attributes(CARD_ELEMENT_KEY))) {
var comparePoint = function comparePoint() {
var doc_rang = Range.create(_this.engine);
doc_rang.select(cardCenter, true);
return doc_rang.comparePoint(startNode, startOffset) < 0;
};
if ('inline' === component.type) {
range.select(component.root);
range.collapse(comparePoint());
return;
}
if (comparePoint()) {
card.focusPrevBlock(component, range, true);
} else {
card.focusNextBlock(component, range, true);
}
}
}
}
}, {
key: "get",
value: function get() {
var container = this.engine.container;
var window = container.window;
var range = Range.from(this.engine, window, false);
if (!range) {
range = Range.create(this.engine, window.document).select(container, true).shrinkToElementNode().collapse(false);
}
return range;
}
}, {
key: "select",
value: function select(range) {
var _endNode$get, _startNode$get3, _range$startNode$get;
var triggerSelect = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var _this$engine = this.engine,
container = _this$engine.container,
inline = _this$engine.inline,
node = _this$engine.node,
change = _this$engine.change;
var window = container.window;
var selection = window === null || window === void 0 ? void 0 : window.getSelection();
if (change.isComposing()) return; //折叠状态
if (range.collapsed) {
var _startNode$get, _startNode$get2, _startNode$first, _startNode$last;
var _startNode = range.startNode,
_startOffset = range.startOffset; //如果节点下只要一个br标签,并且是
,那么选择让光标选择在
if ((_startNode.isElement() && 1 === _startOffset && 1 === ((_startNode$get = _startNode.get()) === null || _startNode$get === void 0 ? void 0 : _startNode$get.childNodes.length) || 2 === _startOffset && 2 === ((_startNode$get2 = _startNode.get()) === null || _startNode$get2 === void 0 ? void 0 : _startNode$get2.childNodes.length) && ((_startNode$first = _startNode.first()) === null || _startNode$first === void 0 ? void 0 : _startNode$first.isCard())) && 'br' === ((_startNode$last = _startNode.last()) === null || _startNode$last === void 0 ? void 0 : _startNode$last.name)) {
range.setStart(_startNode, _startOffset - 1);
range.collapse(true);
} // 卡片左右侧光标零宽字符节点
if (_startNode.isText()) {
var parent = _startNode.parent();
if ((parent === null || parent === void 0 ? void 0 : parent.attributes(CARD_ELEMENT_KEY)) === 'right' && _startOffset === 0) {
range.setStart(_startNode, 1);
range.collapse(true);
} else if ((parent === null || parent === void 0 ? void 0 : parent.attributes(CARD_ELEMENT_KEY)) === 'left' && _startOffset === 1) {
range.setStart(_startNode, 0);
range.collapse(true);
}
}
} //修复inline光标
var _range$cloneRange$shr = range.cloneRange().shrinkToTextNode(),
startNode = _range$cloneRange$shr.startNode,
endNode = _range$cloneRange$shr.endNode,
startOffset = _range$cloneRange$shr.startOffset,
endOffset = _range$cloneRange$shr.endOffset;
var prev = startNode.prev();
var next = endNode.next(); //光标上一个节点是inline节点,让其选择在inline节点后的零宽字符后面
if (prev && !prev.isCard() && !node.isVoid(prev) && node.isInline(prev)) {
var text = startNode.text(); //前面是inline节点,后面是零宽字符
if (/^\u200B/g.test(text) && startOffset === 0) {
range.setStart(endNode, startOffset + 1);
if (range.collapsed) range.collapse(true);
}
} //光标下一个节点是inline节点,让其选择在inline节点前面的零宽字符前面
if (next && !next.isCard() && !node.isVoid(next) && node.isInline(next)) {
var _text = endNode.text();
if (/\u200B$/g.test(_text) && endOffset === _text.length) {
range.setEnd(endNode, endOffset - 1);
if (range.collapsed) range.collapse(false);
}
} //光标内侧位置
var inlineNode = inline.closest(startNode);
if (!inlineNode.isCard() && node.isInline(inlineNode) && !node.isVoid(inlineNode)) {
var _startNode$parent, _endNode$parent;
//左侧
if (startNode.isText() && !startNode.prev() && ((_startNode$parent = startNode.parent()) === null || _startNode$parent === void 0 ? void 0 : _startNode$parent.equal(inlineNode)) && startOffset === 0) {
var _text2 = startNode.text();
if (/^\u200B/g.test(_text2)) {
range.setStart(startNode, startOffset + 1);
if (range.collapsed) range.collapse(true);
}
} //右侧
if (endNode.isText() && !endNode.next() && ((_endNode$parent = endNode.parent()) === null || _endNode$parent === void 0 ? void 0 : _endNode$parent.equal(inlineNode))) {
var _text3 = endNode.text();
if (endOffset === _text3.length && /\u200B$/g.test(_text3)) {
range.setEnd(endNode, endOffset - 1);
if (range.collapsed) range.collapse(false);
}
}
}
startNode = range.startNode;
endNode = range.endNode;
if (startNode.isText() || endNode.isText()) {
var cloneRange = range.cloneRange().enlargeFromTextNode();
startNode = cloneRange.startNode;
endNode = cloneRange.endNode;
}
var startChildNodes = startNode.children(); // 自定义列表节点选中卡片前面就让光标到卡片后面去
if (node.isCustomize(startNode) && startOffset === 0) {
range.setStart(startNode, 1);
}
if (node.isCustomize(endNode) && endOffset === 0) {
range.setEnd(endNode, 1);
}
var otStopped = this.engine.model.mutation.isStopped; // 空节点添加br
if (startNode.name === 'p' && !otStopped) {
if (startChildNodes.length === 0) startNode.append('
');else if (!isFirefox && startChildNodes.length > 1 && startChildNodes[startChildNodes.length - 2].nodeName !== 'BR' && startChildNodes[startChildNodes.length - 1].nodeName === 'BR') {
var br = startNode.last();
br === null || br === void 0 ? void 0 : br.remove();
}
}
if (!range.collapsed && !otStopped && endNode.name === 'p' && ((_endNode$get = endNode.get()) === null || _endNode$get === void 0 ? void 0 : _endNode$get.childNodes.length) === 0) {
endNode.append('
');
}
var startChildren = startNode.children(); // 列表节点没有子节点
if (node.isList(startNode) && !otStopped && (startChildren.length === 0 || startChildren[0].nodeName === 'BR')) {
var newNode = $('
');
this.engine.nodeId.create(newNode);
startNode.before(newNode);
startNode.remove();
startNode = newNode;
} // 空列表添加br
if (startNode.name === 'li' && !otStopped) {
var _startNode$first2;
if (node.isCustomize(startNode) && !((_startNode$first2 = startNode.first()) === null || _startNode$first2 === void 0 ? void 0 : _startNode$first2.isCard())) {
var _startNode$parent2, _cardItem$first;
var cardItem = (_startNode$parent2 = startNode.parent()) === null || _startNode$parent2 === void 0 ? void 0 : _startNode$parent2.children().toArray().find(function (child) {
var _child$first;
return (_child$first = child.first()) === null || _child$first === void 0 ? void 0 : _child$first.isCard();
});
var cardKey = cardItem === null || cardItem === void 0 ? void 0 : (_cardItem$first = cardItem.first()) === null || _cardItem$first === void 0 ? void 0 : _cardItem$first.attributes(CARD_KEY);
if (cardKey) {
this.engine.list.addCardToCustomize(startNode, cardKey);
} else {
this.engine.list.unwrapCustomize(startNode);
}
}
if (startChildNodes.length === 0) {
startNode.append('
');
} else if (!node.isCustomize(startNode) && startChildNodes.length > 1 && startChildNodes[startChildNodes.length - 2].nodeName !== 'BR' && startChildNodes[startChildNodes.length - 1].nodeName === 'BR') {
var _startNode$last2;
(_startNode$last2 = startNode.last()) === null || _startNode$last2 === void 0 ? void 0 : _startNode$last2.remove();
} else if (node.isCustomize(startNode) && startChildNodes.length === 1) {
startNode.append('
');
} else if (node.isCustomize(startNode) && startChildNodes.length > 2 && startChildNodes[startChildNodes.length - 2].nodeName !== 'BR' && startChildNodes[startChildNodes.length - 1].nodeName === 'BR') {
var _startNode$last3;
(_startNode$last3 = startNode.last()) === null || _startNode$last3 === void 0 ? void 0 : _startNode$last3.remove();
}
}
if (!range.collapsed && endNode.name === 'li' && !otStopped) {
var endChildNodes = endNode.children();
if (endChildNodes.length === 0) {
endNode.append('
');
} else if (!node.isCustomize(endNode) && endChildNodes.length > 1 && endChildNodes[endChildNodes.length - 2].nodeName !== 'BR' && endChildNodes[endChildNodes.length - 1].nodeName === 'BR') {
var _startNode$last4;
(_startNode$last4 = startNode.last()) === null || _startNode$last4 === void 0 ? void 0 : _startNode$last4.remove();
} else if (node.isCustomize(endNode) && endChildNodes.length === 1) {
endNode.append('
');
} else if (node.isCustomize(endNode) && endChildNodes.length > 2 && endChildNodes[endChildNodes.length - 2].nodeName !== 'BR' && endChildNodes[endChildNodes.length - 1].nodeName === 'BR') {
var _startNode$last5;
(_startNode$last5 = startNode.last()) === null || _startNode$last5 === void 0 ? void 0 : _startNode$last5.remove();
}
}
if (startNode.isEditable() && !otStopped && ((_startNode$get3 = startNode.get()) === null || _startNode$get3 === void 0 ? void 0 : _startNode$get3.childNodes.length) === 0 && !this.engine.model.mutation.isStopped) {
startNode.html('
');
} //在非折叠,或者当前range对象和selection中的对象不一致的时候重新设置range
if (selection && (range.collapsed || selection.rangeCount > 0 && !range.equal(selection.getRangeAt(0))) && ((_range$startNode$get = range.startNode.get()) === null || _range$startNode$get === void 0 ? void 0 : _range$startNode$get.isConnected)) {
selection.removeAllRanges();
selection.addRange(range.toRange());
}
var onSelect = _classPrivateFieldLooseBase(this, _otpions)[_otpions].onSelect;
if (onSelect && triggerSelect) onSelect(range);
}
/**
* 聚焦编辑器
* @param toStart true:开始位置,false:结束位置,默认为之前操作位置
*/
}, {
key: "focus",
value: function focus(toStart) {
var _editableElement$get,
_this2 = this;
var range = _classPrivateFieldLooseBase(this, _lastBlurRange)[_lastBlurRange] || this.get();
if (toStart !== undefined) {
range.select(this.engine.container, true).shrinkToElementNode().collapse(toStart);
}
this.select(range);
var editableElement = range.commonAncestorNode.closest(EDITABLE_SELECTOR);
editableElement === null || editableElement === void 0 ? void 0 : (_editableElement$get = editableElement.get()) === null || _editableElement$get === void 0 ? void 0 : _editableElement$get.focus();
if (editableElement.length > 0 && !this.engine.container.equal(editableElement)) {
var _this$engine$containe;
var mouseEvent = new MouseEvent('mousedown');
(_this$engine$containe = this.engine.container.get()) === null || _this$engine$containe === void 0 ? void 0 : _this$engine$containe.dispatchEvent(mouseEvent);
setTimeout(function () {
var _this2$engine$contain;
var mouseEvent = new MouseEvent('mouseup');
(_this2$engine$contain = _this2.engine.container.get()) === null || _this2$engine$contain === void 0 ? void 0 : _this2$engine$contain.dispatchEvent(mouseEvent);
}, 0);
}
}
}, {
key: "blur",
value: function blur() {
var _range$commonAncestor, _this$engine$containe2;
var range = this.get();
(_range$commonAncestor = range.commonAncestorNode.closest(EDITABLE_SELECTOR).get()) === null || _range$commonAncestor === void 0 ? void 0 : _range$commonAncestor.blur();
(_this$engine$containe2 = this.engine.container.get()) === null || _this$engine$containe2 === void 0 ? void 0 : _this$engine$containe2.blur();
this.engine.trigger('blur');
}
}]);
return ChangeRange;
}();
var FLUSHING = new WeakMap();
var SELECT_FLUSHING = new WeakMap();
var ChangeModel = /*#__PURE__*/function () {
function ChangeModel(engine) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, ChangeModel);
this.engine = void 0;
this.options = void 0;
this.event = void 0;
this.valueCached = null;
this.onChange = void 0;
this.onRealtimeChange = void 0;
this.onSelect = void 0;
this.onSelectStart = void 0;
this.onSelectEnd = void 0;
this.onSetValue = void 0;
this.rangePathBeforeCommand = void 0;
this.marks = [];
this.blocks = [];
this.inlines = [];
this.changeTrigger = [];
this.range = void 0;
this.nativeEvent = void 0;
this.options = options;
this.engine = engine;
this.event = new ChangeEvent(engine, {});
this.onChange = this.options.onChange || function () {};
this.onRealtimeChange = this.options.onRealtimeChange || function () {};
var prevRange = null;
this.onSelect = function (range) {
var _prevRange, _prevRange2, _prevRange3, _prevRange4;
var mark = engine.mark,
block = engine.block,
inline = engine.inline;
range = range || _this.range.get();
_this.marks = mark.findMarks(range);
_this.blocks = block.findBlocks(range);
_this.inlines = inline.findInlines(range);
if (((_prevRange = prevRange) === null || _prevRange === void 0 ? void 0 : _prevRange.startContainer) === range.startContainer && ((_prevRange2 = prevRange) === null || _prevRange2 === void 0 ? void 0 : _prevRange2.startOffset) === range.startOffset && ((_prevRange3 = prevRange) === null || _prevRange3 === void 0 ? void 0 : _prevRange3.endContainer) === range.endContainer && ((_prevRange4 = prevRange) === null || _prevRange4 === void 0 ? void 0 : _prevRange4.endOffset) === range.endOffset) return;
prevRange = {
startContainer: range.startContainer,
startOffset: range.startOffset,
endContainer: range.endContainer,
endOffset: range.endOffset
};
if (!SELECT_FLUSHING.get(_this.engine)) {
SELECT_FLUSHING.set(_this.engine, true);
Promise.resolve().then(function () {
SELECT_FLUSHING.set(_this.engine, false);
if (_this.options.onSelect) _this.options.onSelect();
});
}
};
this.onSelectStart = function () {
if (_this.options.onSelectStart) _this.options.onSelectStart();
};
this.onSelectEnd = function () {
if (_this.options.onSelectEnd) _this.options.onSelectEnd();
};
this.onSetValue = this.options.onSetValue || function () {};
this.range = new ChangeRange(engine, {
onSelect: function onSelect(range) {
_this.onSelect(range);
}
});
this.nativeEvent = new NativeEvent(engine);
}
_createClass(ChangeModel, [{
key: "init",
value: function init() {
this.nativeEvent.init();
}
}, {
key: "_change",
value: function _change() {
if (!this.isComposing()) {
this.engine.card.gc();
var trigger = this.changeTrigger.length === 2 ? 'both' : this.changeTrigger[0] === 'remote' ? 'remote' : 'local';
this.onChange(trigger);
this.changeTrigger = [];
}
}
}, {
key: "change",
value: function change(isRemote, applyNodes) {
var _this2 = this;
var trigger = isRemote ? 'remote' : 'local'; //动态触发可编辑卡片的onChange事件
var editableElement = undefined;
if (isRemote) {
applyNodes === null || applyNodes === void 0 ? void 0 : applyNodes.forEach(function (node) {
editableElement = node.closest(EDITABLE_SELECTOR);
if (editableElement && editableElement.length > 0) {
var card = _this2.engine.card.find(editableElement, true);
if (card === null || card === void 0 ? void 0 : card.onChange) card === null || card === void 0 ? void 0 : card.onChange(trigger, editableElement);
}
});
} else {
var range = this.range.get();
var startNode = range.startNode; //如果开始节点在编辑器中就查找可编辑器卡片节点。如果是UI节点,就找到 trigger-card-id 属性,再找到card
if (startNode.inEditor()) {
editableElement = startNode.closest(EDITABLE_SELECTOR);
} else {
var uiElement = startNode.closest(UI_SELECTOR);
var cardId = uiElement.attributes(TRIGGER_CARD_ID);
if (cardId) {
var _this$engine$card$fin;
editableElement = (_this$engine$card$fin = this.engine.card.find(cardId)) === null || _this$engine$card$fin === void 0 ? void 0 : _this$engine$card$fin.root.closest(EDITABLE_SELECTOR);
}
}
if (editableElement && editableElement.length > 0) {
var card = this.engine.card.find(editableElement, true);
if (card === null || card === void 0 ? void 0 : card.onChange) card === null || card === void 0 ? void 0 : card.onChange(trigger, editableElement);
} else {
applyNodes === null || applyNodes === void 0 ? void 0 : applyNodes.forEach(function (node) {
editableElement = node.closest(EDITABLE_SELECTOR);
if (editableElement && editableElement.length > 0) {
var _card = _this2.engine.card.find(editableElement, true);
if (_card === null || _card === void 0 ? void 0 : _card.onChange) _card === null || _card === void 0 ? void 0 : _card.onChange(trigger, editableElement);
}
});
}
}
this.onRealtimeChange(trigger);
if (this.changeTrigger.indexOf(trigger) < 0) this.changeTrigger.push(trigger);
if (!FLUSHING.get(this.engine)) {
FLUSHING.set(this.engine, true);
Promise.resolve().then(function () {
FLUSHING.set(_this2.engine, false);
_this2._change();
});
}
}
}, {
key: "isComposing",
value: function isComposing() {
return this.event.isComposing;
}
}, {
key: "isSelecting",
value: function isSelecting() {
return this.event.isSelecting;
}
}, {
key: "initValue",
value: function initValue(range) {
var _container$get, _node$get;
var apply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var container = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.engine.container;
var html = container.html();
var defaultHtml = '
';
if (html === defaultHtml || (((_container$get = container.get()) === null || _container$get === void 0 ? void 0 : _container$get.childNodes.length) || 0) > 0) return;
var emptyHtml = html || defaultHtml;
var node = $(emptyHtml);
if (((_node$get = node.get()) === null || _node$get === void 0 ? void 0 : _node$get.childNodes.length) === 0) node.html('
');
container.empty().append(node);
var safeRange = range || this.range.get();
if (!range && apply) {
safeRange.select(node, true).collapse(false);
this.apply(safeRange);
}
}
}, {
key: "setValue",
value: function setValue(value, onParse, callback) {
var range = this.range.get();
var _this$engine = this.engine,
schema = _this$engine.schema,
conversion = _this$engine.conversion,
container = _this$engine.container,
history = _this$engine.history,
mark = _this$engine.mark,
card = _this$engine.card;
if (value === '') {
this.engine.container.html(value);
this.initValue(undefined, false);
if (callback) callback(0);
} else {
var parser = new Parser(value, this.engine, function (root) {
mark.removeEmptyMarks(root);
root.allChildren('editable').forEach(function (child) {
if (onParse) {
onParse(child);
}
});
}, false);
container.html(parser.toValue(schema, conversion, false, true));
card.render(undefined, function (count) {
if (callback) callback(count);
});
var cursor = container.find(CURSOR_SELECTOR);
var selection = new Selection(this.engine, range);
if (cursor.length > 0) {
selection.anchor = cursor;
selection.focus = cursor;
}
var anchor = container.find(ANCHOR_SELECTOR);
var focus = container.find(FOCUS_SELECTOR);
if (anchor.length > 0 && focus.length > 0) {
selection.anchor = anchor;
selection.focus = focus;
}
if (selection.anchor && selection.focus) {
selection.move();
this.range.select(range);
this.onSelect();
}
this.onSetValue();
history.clear();
}
this.change();
}
}, {
key: "setHtml",
value: function setHtml(html, callback) {
var _this3 = this;
var _this$engine2 = this.engine,
card = _this$engine2.card,
container = _this$engine2.container;
this.nativeEvent.paste(html, undefined, callback, true, function (fragment, _range, _rangeCallback, _followActiveMark) {
container.empty().append(fragment);
card.render(undefined, function (count) {
_this3.initValue(undefined, false);
_this3.engine.trigger('paste:after');
if (callback) callback(count);
});
_this3.change();
}, false);
}
}, {
key: "setMarkdown",
value: function setMarkdown(text, callback) {
var _this4 = this;
var markdown = createMarkdownIt(this.engine, 'zero');
markdown.enable(['paragraph', 'html_inline', 'newline']); //.disable(['strikethrough', 'emphasis', 'link', 'image', 'table', 'code', 'blockquote', 'hr', 'list', 'heading'])
var tokens = markdown.parse(text, {});
if (tokens.length === 0) return;
var result = convertMarkdown(this.engine, markdown, tokens);
if (!result) result = text;
var _this$engine3 = this.engine,
card = _this$engine3.card,
container = _this$engine3.container;
this.nativeEvent.paste(result, undefined, callback, true, function (fragment, _range, _rangeCallback, _followActiveMark) {
container.empty().append(fragment);
card.render(undefined, function (count) {
_this4.initValue(undefined, false);
_this4.engine.trigger('paste:after');
if (callback) callback(count);
});
_this4.change();
});
}
}, {
key: "getOriginValue",
value: function getOriginValue() {
var container = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.engine.container;
var isClone = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var _this$engine4 = this.engine,
schema = _this$engine4.schema,
conversion = _this$engine4.conversion;
return new Parser(isClone ? container.clone(true) : container, this.engine, undefined, false).toValue(schema, conversion);
}
}, {
key: "getValue",
value: function getValue() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var value;
if (options.ignoreCursor || this.isComposing()) {
value = this.getOriginValue();
} else {
var range = this.range.get();
var container = this.engine.container.clone(true);
if (!range.inCard()) {
var path = range.toPath(true);
if (!path) return this.getOriginValue(container, false);
range = Range.fromPath(this.engine, path, true, container);
range.createSelection();
}
value = this.getOriginValue(container, false);
}
return value;
}
}, {
key: "cacheRangeBeforeCommand",
value: function cacheRangeBeforeCommand() {
this.rangePathBeforeCommand = this.range.get().toPath();
}
}, {
key: "getRangePathBeforeCommand",
value: function getRangePathBeforeCommand() {
var rangePath = this.rangePathBeforeCommand;
this.rangePathBeforeCommand = undefined;
return rangePath;
}
}, {
key: "isEmpty",
value: function isEmpty() {
var _this$engine5 = this.engine,
container = _this$engine5.container,
node = _this$engine5.node,
schema = _this$engine5.schema;
var tags = schema.getAllowInTags();
var children = container.children();
return children.length === 0 || children.length === 1 && node.isEmpty(container) && !container.allChildren().some(function (child) {
return tags.includes(child.name);
});
}
}, {
key: "combinText",
value: function combinText$1() {
combinText(this.engine.container);
}
/**
* 应用一个具有改变dom结构的操作
* @param range 光标
*/
}, {
key: "apply",
value: function apply(range) {
this.combinText();
var _this$engine6 = this.engine,
inline = _this$engine6.inline,
mark = _this$engine6.mark,
nodeId = _this$engine6.nodeId;
if (range) {
var selection = range.createSelection('change-apply');
inline.findInlines(range).forEach(function (inlineNode) {
return inline.repairCursor(inlineNode);
});
mark.findMarks(range).forEach(function (markNode) {
return mark.repairCursor(markNode);
});
selection.move();
range.shrinkToTextNode();
this.range.select(range);
}
this.change();
nodeId.generateAll(this.engine.container);
}
/**
* 插入片段
* @param fragment 片段
* @param range 指定光标区域
* @param callback 插入后的回调函数
* @param followActiveMark 删除后空标签是否跟随当前激活的mark样式
*/
}, {
key: "insert",
value: function insert(fragment, range) {
var _this5 = this;
var callback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
var followActiveMark = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var _this$engine7 = this.engine,
block = _this$engine7.block,
list = _this$engine7.list,
schema = _this$engine7.schema,
mark = _this$engine7.mark,
inline = _this$engine7.inline;
var nodeApi = this.engine.node;
range = range || this.range.toTrusty();
var firstBlock = block.closest(range.startNode);
var lastBlock = block.closest(range.endNode);
var onlyOne = lastBlock[0] === firstBlock[0];
var isBlockLast = block.isLastOffset(range, 'end');
var mergeTags = schema.getCanMergeTags();
var allowInTags = schema.getAllowInTags();
var mergeNode = firstBlock.closest(mergeTags.join(','));
var isCollapsed = range.collapsed;
var childNodes = fragment.childNodes;
var firstNode = $(fragment.firstChild || []);
var unwrapToFirst = function unwrapToFirst() {
var _first$first;
var fragmentNode = $(fragment);
var first = fragmentNode.first(); //如果光标在文本节点,并且父级节点不是根节点,移除粘贴数据的第一个节点块级节点,让其内容接在光标所在行
var cloneRange = range.cloneRange().shrinkToElementNode().shrinkToTextNode();
var startNode = cloneRange.startNode;
if (startNode.inEditor() && first && first.name === 'p' && !(first.length === 1 && ((_first$first = first.first()) === null || _first$first === void 0 ? void 0 : _first$first.name) === 'br')) {
// 粘贴第一行居中样式会丢失
if (startNode.name === 'p' && nodeApi.isEmptyWidthChild(startNode)) {
var styles = first.css();
startNode.css(styles);
}
nodeApi.unwrap(first);
}
};
if (!isCollapsed) {
this.delete(range, onlyOne || !isBlockLast, followActiveMark);
if (nodeApi.isEmptyWidthChild(range.startNode)) range.shrinkToElementNode().shrinkToTextNode();
unwrapToFirst();
} else {
unwrapToFirst();
if (range.startNode.isText()) {
var inlineNode = inline.closest(range.startNode);
var text = range.startNode.text();
if (inlineNode.length === 0 && !inlineNode.equal(range.startNode) && /^\u200B/.test(text)) range.startNode.text(text.substr(1));
}
}
var startRange = undefined;
var apply = function apply(range) {
if (startRange && startRange.node[0].isConnected) {
range.shrinkToElementNode().setStart(startRange.node, startRange.offset);
range.enlargeToElementNode();
}
block.merge(range);
list.merge(undefined, range);
mark.merge(range);
inline.flat(range);
if (callback) callback(range);
_this5.apply(range);
};
if (nodeApi.isList(range.startNode) || range.startNode.closest('li').length > 0) {
var children = range.startNode.children();
startRange = {
node: range.startNode,
offset: children.length === 1 && children[0].nodeName === 'BR' ? 0 : range.startOffset
};
list.insert(fragment, range);
apply(range);
return;
}
if (!firstNode[0]) {
apply(range);
return;
} // 第一个子节点不是block节点就追加到当前节点下
if (!nodeApi.isBlock(firstNode)) {
range.shrinkToElementNode();
if (childNodes.length > 0) {
var _children = range.startNode.children();
startRange = {
node: range.startNode,
offset: _children.length === 1 && _children[0].nodeName === 'BR' ? 0 : range.startOffset
};
}
var nextNode = firstNode.next();
var beforeNode = firstNode;
var newRange = nodeApi.insert(firstNode, range);
if (newRange) range = newRange;
while (nextNode && !nodeApi.isBlock(nextNode)) {
if (range.startContainer.nodeType === Node.TEXT_NODE) range.enlargeToElementNode().collapse(false);
var newNext = nextNode.next();
beforeNode.after(nextNode);
beforeNode = nextNode; //nodeApi.insert(nextNode, range);
nextNode = newNext;
}
if (beforeNode !== firstNode) {
range.select(beforeNode, true).collapse(false);
}
if (childNodes.length === 0) {
apply(range);
return;
}
}
var cloneRange = range.cloneRange().enlargeToElementNode(true).collapse(false);
var startNode = cloneRange.startContainer.childNodes[range.startOffset === 0 ? 0 : range.startOffset - 1];
var endNode = cloneRange.startContainer.childNodes[range.startOffset];
if (childNodes.length !== 0) {
var lastNode = $(childNodes[childNodes.length - 1]);
if ('br' === lastNode.name) {
lastNode.remove();
lastNode = $(childNodes[childNodes.length - 1]);
}
if (!startRange) {
var _children2 = range.startNode.children();
startRange = {
node: range.startNode,
offset: _children2.length === 1 && _children2[0].nodeName === 'BR' ? 0 : range.startOffset
};
}
var node = $(childNodes[0]);
var prev = null;
var appendNodes = [];
while (node && node.length > 0) {
var _node$get2, _node$get3;
nodeApi.removeSide(node);
var next = node.next();
if (!next) {
lastNode = node;
}
if (prev) {
prev.after(node);
} else {
if (nodeApi.isInline(range.startNode)) {
range.setStartAfter(range.startNode);
range.collapse(true);
}
nodeApi.insert(node, range, true);
if (nodeApi.isInline(node)) {
range.setEndAfter(node);
range.collapse(false);
}
}
if ((_node$get2 = node.get()) === null || _node$get2 === void 0 ? void 0 : _node$get2.isConnected) appendNodes.push(node);
if (!nodeApi.isBlock(node) && !(next === null || next === void 0 ? void 0 : next.isText())) {
if (prev) {
range.select(node, true).collapse(false);
}
prev = null;
} else {
prev = node;
}
if (!next && ((_node$get3 = node.get()) === null || _node$get3 === void 0 ? void 0 : _node$get3.isConnected) && !nodeApi.isInline(node)) {
range.select(node, true).collapse(false);
} // 被删除了重新设置开始节点位置
if (startRange && !startRange.node[0].isConnected) {
var parent = node.parent();
if (parent) {
startRange = {
node: parent,
offset: node.index()
};
}
}
node = next;
}
if (mergeNode[0]) {
appendNodes.forEach(function (element) {
if (mergeTags.indexOf(element.name) < 0 && element.closest(mergeNode.name).length === 0) {
nodeApi.wrap(element, nodeApi.clone(mergeNode, false, false));
}
});
} //range.shrinkToElementNode().collapse(false);
// const component = card.find(range.startNode);
// if (component) component.focus(range, false);
}
var getFirstChild = function getFirstChild(node) {
var child = node.first();
if (!child || !nodeApi.isBlock(child)) return node;
while (allowInTags.indexOf(child ? child.name : '') > -1) {
child = child.first();
}
return child;
};
var getLastChild = function getLastChild(node) {
var child = node.last();
if (!child || !nodeApi.isBlock(child)) return node;
while (allowInTags.indexOf(child ? child.name : '') > -1) {
child = child.last();
}
return child;
};
var isSameListChild = function isSameListChild(_lastNode, _firstNode) {
if (_lastNode.isCard() || firstNode.isCard()) return;
var fParent = _firstNode.parent();
var lParent = _lastNode.parent();
var isSameParent = fParent && !fParent.isEditable() && lParent && !lParent.isEditable() && fParent.name === lParent.name;
return 'p' === _firstNode.name && isSameParent || _lastNode.name === _firstNode.name && isSameParent && !('li' === _lastNode.name && !list.isSame(_lastNode.parent(), _firstNode.parent()));
};
var removeEmptyNode = function removeEmptyNode(node) {
while (!node.isEditable()) {
var _parent = node.parent();
node.remove();
if (!_parent || !nodeApi.isEmpty(_parent)) break;
node = _parent;
}
};
var clearList = function clearList(lastNode, nextNode) {
if (lastNode.name === nextNode.name && 'p' === lastNode.name) {
var attr = nextNode.attributes();
if (attr[DATA_ID]) delete attr[DATA_ID];
lastNode.attributes(attr);
}
if (nodeApi.isEmptyWidthChild(lastNode) && !nodeApi.isEmptyWidthChild(nextNode)) {
lastNode.get().innerHTML = '';
}
if (nodeApi.isCustomize(lastNode) === nodeApi.isCustomize(nextNode)) list.unwrapCustomize(nextNode);
};
if (startNode) {
var _firstNode = getFirstChild($(startNode.nextSibling || []));
var _lastNode = getLastChild($(startNode));
if (_lastNode.name === 'p' && _firstNode.name !== _lastNode.name && isSameListChild(_lastNode, _firstNode)) {
clearList(_lastNode, _firstNode);
nodeApi.merge(_lastNode, _firstNode, false);
removeEmptyNode(_firstNode);
}
}
if (endNode) {
var prevNode = getLastChild($(endNode.previousSibling || []));
var _nextNode = getFirstChild($(endNode));
if (prevNode && isSameListChild(prevNode, _nextNode)) {
nodeApi.merge(prevNode, _nextNode, false);
removeEmptyNode(_nextNode);
}
}
apply(range);
}
}, {
key: "paste",
value: function paste(html, range, callback) {
this.nativeEvent.paste(html, range, callback, true);
}
/**
* 删除内容
* @param range 光标,默认获取当前光标
* @param isDeepMerge 删除后是否合并
* @param followActiveMark 删除后空标签是否跟随当前激活的mark样式
*/
}, {
key: "delete",
value: function _delete(range, isDeepMerge) {
var _endNode$parent, _startNode$get, _startNode$get2, _startNode$get3, _prevNode$parent, _startNode$get4;
var followActiveMark = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var safeRange = range || this.range.toTrusty();
if (safeRange.collapsed) {
if (this.isEmpty()) this.initValue(safeRange);
if (!range) this.apply(safeRange);
return;
}
var _this$engine8 = this.engine,
mark = _this$engine8.mark,
inline = _this$engine8.inline,
card = _this$engine8.card;
var nodeApi = this.engine.node;
var blockApi = this.engine.block;
var cloneRange = safeRange.cloneRange();
cloneRange.collapse(true);
var activeMarks = followActiveMark ? mark.findMarks(cloneRange) : [];
safeRange.enlargeToElementNode(); // 获取上面第一个 Block
var block = blockApi.closest(safeRange.cloneRange().shrinkToElementNode().shrinkToTextNode().enlargeToElementNode().startNode); // 获取的 block 超出编辑范围
if (!block.inEditor() && !block.isRoot()) {
if (this.isEmpty()) this.initValue(safeRange);
if (!range) this.apply(safeRange);
return;
} // 选中开始节点是卡片,并且光标位置在根节点,就先删除卡片
if (block.isRoot()) {
var child = block.children().eq(safeRange.startOffset);
while ((_child = child) === null || _child === void 0 ? void 0 : _child.isCard()) {
var _child;
var isBreak = child.equal(safeRange.endNode) || child.contains(safeRange.endNode);
var next = child.next() || undefined;
var component = card.find(child);
if (component) card.removeNode(component);else child.remove();
if (isBreak) {
child = undefined;
break;
}
child = next;
}
if (!child) {
if (this.isEmpty()) this.initValue(safeRange);
if (!range) this.apply(safeRange);
return;
}
block = child;
}
var endNode = safeRange.endNode,
endOffset = safeRange.endOffset;
var isMoreLine = !blockApi.closest(safeRange.startNode).equal(blockApi.closest(endNode)); // aaa -> aaacursor />
var inlineNode = inline.closest(endNode);
if (inlineNode.length > 0 && ((_endNode$parent = endNode.parent()) === null || _endNode$parent === void 0 ? void 0 : _endNode$parent.equal(inlineNode))) {
if (endNode.isText()) {
var text = endNode.text();
if (endOffset === text.length - 1) {
safeRange.setEndAfter(inlineNode);
}
}
}
var endContentNode = safeRange.cloneRange().shrinkToElementNode().shrinkToTextNode().getEndOffsetNode(); // 先删除范围内的所有内容
safeRange.extractContents();
var startNode = safeRange.startNode;
if (startNode.isEditable() && ((_startNode$get = startNode.get()) === null || _startNode$get === void 0 ? void 0 : _startNode$get.childNodes.length) === 0) {
startNode.html('
');
this.engine.nodeId.generate(startNode);
} // 删除了卡片内的节点,就把卡片删除
startNode = safeRange.shrinkToElementNode().shrinkToTextNode().enlargeToElementNode().startNode;
if (startNode.isCard() && startNode.find(CARD_CENTER_SELECTOR).length === 0) card.remove(startNode);
safeRange.collapse(true); // 后续处理
startNode = safeRange.shrinkToElementNode().shrinkToTextNode().enlargeToElementNode().startNode; // 删除后的之前开始选中节点是空节点就删除掉
if (block.isElement() && !block.equal(startNode) && block.get().childNodes.length === 0) {
block.remove();
} // 只删除了文本,不做处理
if (startNode.isText() || !block.inEditor()) {
if (this.isEmpty()) this.initValue(safeRange);
if (!range) this.apply(safeRange);
return;
}
var isRemoveStartNode = false;
if (isMoreLine && ((_startNode$get2 = startNode.get()) === null || _startNode$get2 === void 0 ? void 0 : _startNode$get2.childNodes.length) === 0) {
var _selection$anchor, _selection$anchor$get, _selection$focus, _selection$focus$get;
var selection = safeRange.createSelection();
startNode.remove();
if (((_selection$anchor = selection.anchor) === null || _selection$anchor === void 0 ? void 0 : (_selection$anchor$get = _selection$anchor.get()) === null || _selection$anchor$get === void 0 ? void 0 : _selection$anchor$get.isConnected) && ((_selection$focus = selection.focus) === null || _selection$focus === void 0 ? void 0 : (_selection$focus$get = _selection$focus.get()) === null || _selection$focus$get === void 0 ? void 0 : _selection$focus$get.isConnected)) {
selection.move();
}
isRemoveStartNode = true;
startNode = safeRange.startNode;
}
var prevNode = block;
var nextNode = endContentNode && endContentNode.isConnected ? startNode : null;
var isEmptyNode = ((_startNode$get3 = startNode.get()) === null || _startNode$get3 === void 0 ? void 0 : _startNode$get3.childNodes.length) === 0;
if (!isEmptyNode && startNode.length > 0 && startNode.inEditor()) {
var _startNode$0$firstChi, _startNode$first;
if (startNode[0].childNodes.length === 1 && ((_startNode$0$firstChi = startNode[0].firstChild) === null || _startNode$0$firstChi === void 0 ? void 0 : _startNode$0$firstChi.nodeType) === Node.ELEMENT_NODE && nodeApi.isCustomize(startNode) && ((_startNode$first = startNode.first()) === null || _startNode$first === void 0 ? void 0 : _startNode$first.isCard())) isEmptyNode = true;
}
if (isEmptyNode && nodeApi.isBlock(startNode) && startNode.inEditor()) {
if (nodeApi.isList(startNode)) {
startNode.remove();
} else {
var html = nodeApi.getBatchAppendHTML(activeMarks, '
');
if (startNode.isEditable()) {
html = "".concat(html, "
");
}
startNode.append($(html));
var br = startNode.find('br');
var parent = br.parent();
if (parent && nodeApi.isMark(parent)) {
nodeApi.replace(br, $("\u200B", null));
}
safeRange.select(startNode, true);
}
safeRange.shrinkToElementNode().shrinkToTextNode();
safeRange.collapse(false);
if (this.isEmpty()) this.initValue(safeRange);
if (!range) this.apply(safeRange);
return;
} //深度合并
var deepMergeNode = function deepMergeNode(range, prevNode, nextNode, marks) {
var isDeepMerge = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
if (nodeApi.isBlock(prevNode) && !nodeApi.isVoid(prevNode) && !prevNode.isCard()) {
range.select(prevNode, true);
range.collapse(false);
var _selection = range.shrinkToElementNode().shrinkToTextNode().createSelection();
var _parent2 = nextNode.parent();
nodeApi.merge(prevNode, nextNode);
while (_parent2 && nodeApi.isBlock(_parent2) && nodeApi.isEmpty(_parent2)) {
_parent2.remove();
_parent2 = _parent2.parent();
}
_selection.move();
range.enlargeToElementNode(true);
var prev = range.getPrevNode();
var next = range.getNextNode(); // 合并之后变成空 Block
var _startNode = range.startNode;
if (!prev && !next && nodeApi.isBlock(_startNode)) {
_startNode.append($(nodeApi.getBatchAppendHTML(marks, '
')));
range.select(_startNode.find('br'), true);
range.collapse(false);
}
if (prev && next && !prev.isCard() && !next.isCard() && isDeepMerge) {
deepMergeNode(range, prev, next, marks);
}
}
};
if (prevNode && nextNode && nextNode.length > 0 && nodeApi.isBlock(prevNode) && nodeApi.isBlock(nextNode) && !prevNode.equal(nextNode) && !((_prevNode$parent = prevNode.parent()) === null || _prevNode$parent === void 0 ? void 0 : _prevNode$parent.equal(nextNode)) && nextNode.inEditor()) {
deepMergeNode(safeRange, prevNode, nextNode, activeMarks, isDeepMerge);
}
startNode.children().each(function (node) {
var domNode = $(node);
if (!nodeApi.isVoid(domNode) && domNode.isElement() && '' === nodeApi.html(domNode)) domNode.remove(); //给inline节点添加零宽字符,用于光标选择
if (nodeApi.isInline(domNode)) {
inline.repairCursor(domNode);
}
}); //移除空列表
if (nodeApi.isList(startNode) && nodeApi.isEmpty(startNode)) {
startNode.remove();
} //修复inline节点光标选择在最后的零宽字符上时,将光标位置移到inline节点末尾
cloneRange = safeRange.cloneRange().shrinkToTextNode();
if (cloneRange.startNode.isText() && /^\u200B/g.test(cloneRange.startNode.text()) && cloneRange.startOffset === 0) {
var prev = cloneRange.startNode.prev();
if (prev && this.engine.node.isInline(prev)) {
safeRange.select(prev, true);
safeRange.collapse(false);
}
}
if (nodeApi.isBlock(startNode) && ((_startNode$get4 = startNode.get()) === null || _startNode$get4 === void 0 ? void 0 : _startNode$get4.childNodes.length) === 0) {
startNode.html('
');
}
if (isRemoveStartNode) {
var _prevNode$get;
if (nodeApi.isBlock(prevNode) && ((_prevNode$get = prevNode.get()) === null || _prevNode$get === void 0 ? void 0 : _prevNode$get.childNodes.length) === 0) {
prevNode.html('
');
}
if (prevNode.inEditor()) safeRange.select(prevNode, true).collapse(false);
}
if (this.isEmpty()) this.initValue(safeRange);
if (!range) this.apply(safeRange);
}
/**
* 去除当前光标最接近的block节点或传入的节点外层包裹
* @param node 节点
*/
}, {
key: "unwrap",
value: function unwrap(node) {
var block = this.engine.block;
var range = this.range.get();
node = node || block.closest(range.startNode);
if (!node.inEditor()) {
return;
}
var selection = range.createSelection();
this.engine.node.unwrap(node);
selection.move();
this.range.select(range);
}
/**
* 删除当前光标最接近的block节点或传入的节点后与前面一个节点后合并
* @param node 节点
*/
}, {
key: "mergeAfterDelete",
value: function mergeAfterDelete(node) {
var _prevBlock$get, _prevBlock$first;
var _this$engine9 = this.engine,
block = _this$engine9.block,
card = _this$engine9.card,
list = _this$engine9.list,
mark = _this$engine9.mark;
var nodeApi = this.engine.node;
var range = this.range.get();
node = node || block.closest(range.startNode);
var children = node.children();
if (children.length === 0) {
node.append($('
'));
this.apply(range);
return;
} //
abc
,先删除 br 標簽
var first = node.first();
if (children.length > 1 && (first === null || first === void 0 ? void 0 : first.name) === 'br') {
first === null || first === void 0 ? void 0 : first.remove();
return;
}
var prevBlock = node.prev(); // 前面没有节点
if (!prevBlock) {
var parent = node.parent();
if ((parent === null || parent === void 0 ? void 0 : parent.inEditor()) && !(parent === null || parent === void 0 ? void 0 : parent.isEditable())) {
this.unwrap(node);
}
return;
} // 前面是Card
if (prevBlock.isCard()) {
if (children.length === 1 && (first === null || first === void 0 ? void 0 : first.name) === 'br' || nodeApi.isEmpty(node)) {
node.remove();
}
var component = card.find(prevBlock);
if (component) {
card.focus(component);
return;
}
} // 前面是 void 节点
if (nodeApi.isVoid(prevBlock)) {
prevBlock.remove();
this.apply(range);
return;
} // 前面是空段落
if (nodeApi.isRootBlock(prevBlock) && nodeApi.isEmpty(prevBlock)) {
prevBlock.remove();
this.apply(range);
return;
} // 前面是文本节点
if (prevBlock.isText()) {
var paragraph = $('');
prevBlock.before(paragraph);
paragraph.append(prevBlock);
prevBlock = paragraph;
}
if (nodeApi.isList(prevBlock)) {
prevBlock = prevBlock.last();
} // 只有一个
时先删除
if (children.length === 1 && (first === null || first === void 0 ? void 0 : first.name) === 'br') {
first === null || first === void 0 ? void 0 : first.remove();
} else if (prevBlock && ((_prevBlock$get = prevBlock.get()) === null || _prevBlock$get === void 0 ? void 0 : _prevBlock$get.childNodes.length) === 1 && ((_prevBlock$first = prevBlock.first()) === null || _prevBlock$first === void 0 ? void 0 : _prevBlock$first.name) === 'br') {
var _prevBlock$first2;
(_prevBlock$first2 = prevBlock.first()) === null || _prevBlock$first2 === void 0 ? void 0 : _prevBlock$first2.remove();
}
if (!prevBlock || prevBlock.isText()) {
this.unwrap(node);
} else {
var selection = range.createSelection();
nodeApi.merge(prevBlock, node);
selection.move();
this.range.select(range);
mark.merge();
list.merge();
}
}
}, {
key: "destroy",
value: function destroy() {
this.event.destroy();
}
}]);
return ChangeModel;
}();
/**
* Returns the host window of a DOM node
*/
var getDefaultView = function getDefaultView(value) {
return value && value.ownerDocument && value.ownerDocument.defaultView || null;
};
/**
* Check if a DOM node is an element node.
*/
var isDOMElement = function isDOMElement(value) {
return isDOMNode(value) && value.nodeType === 1;
};
var isDOMHTMLElement = function isDOMHTMLElement(value) {
if (!isDOMElement(value)) return false;
if (typeof HTMLElement !== 'undefined') return value instanceof HTMLElement;
return value.style instanceof CSSStyleDeclaration;
};
/**
* Check if a value is a DOM node.
*/
var isDOMNode = function isDOMNode(value) {
var _getDefaultView;
var window = (_getDefaultView = getDefaultView(value)) !== null && _getDefaultView !== void 0 ? _getDefaultView : globalThis.window;
return !!window && value instanceof window.Node;
};
/**
* Check if a DOM node is an element node.
*/
var isDOMText = function isDOMText(value) {
return isDOMNode(value) && value.nodeType === 3;
};
var Text$1 = {
isText: function isText(value) {
return isPlainObject(value) && typeof value.text === 'string';
},
create: function create(text) {
return {
text: text
};
}
};
var Element$1 = {
isElement: function isElement(value) {
return isPlainObject(value) && Array.isArray(value.children);
},
create: function create(type) {
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var children = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
return _objectSpread2(_objectSpread2({
type: type
}, props), {}, {
children: children
});
}
};
var toDOM = function toDOM(node) {
if (Text$1.isText(node)) {
return document.createTextNode(node.text);
} else if (Element$1.isElement(node)) {
var type = node.type,
children = node.children;
var element = null;
try {
element = document.createElement(type.replace(/[-_\[\]\s]/g, ''));
} catch (error) {
element = document.createElement('span');
}
for (var _i = 0, _Object$entries = Object.entries(node); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
key = _Object$entries$_i[0],
value = _Object$entries$_i[1];
if (key === 'type' || key === 'children') continue;
element.setAttribute(key, value);
}
if (node[CARD_KEY] && !node[READY_CARD_KEY]) {
element.setAttribute(READY_CARD_KEY, node[CARD_KEY]);
element.removeAttribute(CARD_KEY);
}
var _iterator = _createForOfIteratorHelper(children),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
element.appendChild(toDOM(child));
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return element;
}
throw new Error('Cannot convert node to DOM');
};
var findDOMByPath = function findDOMByPath(engine, root, path) {
var isForceRenderCard = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
// 正在加载中的节点,直接渲染
if (isForceRenderCard && isDOMElement(root) && root.hasAttribute(CARD_LOADING_KEY)) {
var card = engine.card;
var cardComponent = card.find(root);
if (cardComponent) {
cardComponent.getCenter().empty();
card.renderComponent(cardComponent);
}
}
var offset = path[0];
var index = 0;
var _iterator = _createForOfIteratorHelper(root.childNodes),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
if (isTransientElementCache(child)) continue;
if (offset === index) {
if (path.length === 1) {
return {
parent: root,
node: child,
offset: -1
};
}
return findDOMByPath(engine, child, path.slice(1));
}
index++;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (path.length > 1) throw new Error('Cannot find element');
return {
parent: root,
node: root,
offset: offset
};
};
var applyToDOM = function applyToDOM(engine, operation, isRemote) {
var card = engine.card;
var path = operation.path;
var _findDOMByPath = findDOMByPath(engine, engine.container[0], path),
parent = _findDOMByPath.parent,
domNode = _findDOMByPath.node,
domOffset = _findDOMByPath.offset;
if (operation.type === 'insert_node') {
var node = operation.node;
var element = toDOM(node);
var $element = $(element); // if (
// !isDOMElement(element) ||
// !isCard(element) ||
// (isEditableCard(element) &&
// $element.closest(EDITABLE_SELECTOR).isEditable())
// ) {
if (parent !== domNode) {
parent.insertBefore(element, domNode);
} else {
parent.appendChild(element);
}
if (isDOMElement(element) && isCard(element)) {
element.setAttribute(CARD_LOADING_KEY, isRemote ? 'remote' : 'true');
}
var id = node[DATA_ID];
engine.card.render($element);
if ($element[0].isConnected || !id) return $element;
var el = parent.querySelector("[".concat(DATA_ID, "=\"").concat(id, "\"]"));
return el ? $(el) : $element; // }
// return;
} else if (operation.type === 'remove_node') {
if (domOffset === -1) {
if (isDOMElement(domNode) && isCard(domNode)) {
if (isRemote) {
card.removeRemote(domNode);
} else {
card.remove(domNode, false);
}
} else parent.removeChild(domNode);
return isRoot(parent) ? undefined : $(parent);
}
return;
} else if (operation.type === 'set_node') {
if (domOffset === -1 && isDOMElement(domNode)) {
var properties = operation.properties,
newProperties = operation.newProperties;
for (var _i = 0, _Object$entries = Object.entries(properties); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 1),
key = _Object$entries$_i[0];
domNode.removeAttribute(key);
}
for (var _i2 = 0, _Object$entries2 = Object.entries(newProperties); _i2 < _Object$entries2.length; _i2++) {
var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
_key = _Object$entries2$_i[0],
value = _Object$entries2$_i[1];
if (value === null) {
domNode.removeAttribute(_key);
} else {
domNode.setAttribute(_key, value);
}
}
var $node = $(domNode);
if (isCard(domNode)) {
var component = card.find(domNode);
if (!component) return;
if (!component.isEditable) card.reRender(component);
if (component.isEditable && component.onChange) component.onChange(isRemote ? 'remote' : 'local', $node);
}
return $node;
}
} else if (operation.type === 'insert_text') {
var offset = operation.offset,
text = operation.text;
if (domOffset === -1 && isDOMText(domNode)) {
var _domNode$nodeValue;
var content = (_domNode$nodeValue = domNode.nodeValue) !== null && _domNode$nodeValue !== void 0 ? _domNode$nodeValue : '';
domNode.nodeValue = content.slice(0, offset) + text + content.slice(offset);
return $(domNode);
}
} else if (operation.type === 'remove_text') {
var _offset = operation.offset,
_text = operation.text;
if (domOffset === -1 && isDOMText(domNode)) {
var _domNode$nodeValue2;
var _content = (_domNode$nodeValue2 = domNode.nodeValue) !== null && _domNode$nodeValue2 !== void 0 ? _domNode$nodeValue2 : '';
domNode.nodeValue = _content.slice(0, _offset) + _content.slice(_offset + _text.length);
return $(domNode);
}
}
return;
};
var ENGINE_TO_MEMBER = new WeakMap();
var createMember = function createMember() {
var current = null;
var members = [];
return {
getMembers: function getMembers() {
return members;
},
add: function add(collaborationMember) {
members.push(collaborationMember);
},
remove: function remove(uuid) {
var index = members.findIndex(function (m) {
return m.uuid === uuid;
});
if (index !== -1) {
members.splice(index, 1);
}
},
getCurrent: function getCurrent() {
return current;
},
setCurrent: function setCurrent(uuid) {
var collaborationMember = typeof uuid === 'string' ? members.find(function (m) {
return m.uuid === uuid;
}) : uuid;
if (collaborationMember) {
current = collaborationMember;
}
}
};
};
var CollaborationMember = {
fromEngine: function fromEngine(engine) {
var member = ENGINE_TO_MEMBER.get(engine);
if (!member) {
member = createMember();
ENGINE_TO_MEMBER.set(engine, member);
}
return member;
}
};
var config = {
childList: true,
subtree: true,
attributes: true,
characterData: true,
attributeOldValue: true,
characterDataOldValue: true
};
var MUTATION_TO_ENGINE = new WeakMap();
var createMutation = function createMutation(engine) {
var isCache = false;
var isStopped = true;
var cachedRecords = [];
var ee = new EventEmitter2.EventEmitter2();
var observer = new MutationObserver(function (records) {
if (isCache) {
var _cachedRecords;
(_cachedRecords = cachedRecords).push.apply(_cachedRecords, _toConsumableArray(records));
}
if (!isStopped && !isCache) {
ee.emit('change', records);
}
});
var mutation = {
get isStopped() {
return isStopped;
},
get isCache() {
return isCache;
},
onChange: function onChange(fn) {
ee.on('change', fn);
},
offChange: function offChange(fn) {
ee.off('change', fn);
},
start: function start() {
var container = engine.container[0];
if (isStopped) {
observer.observe(container, config);
isStopped = false;
}
},
stop: function stop() {
if (!isStopped) {
observer.disconnect();
isStopped = true;
}
},
startCache: function startCache() {
if (!isCache) {
cachedRecords = [];
isCache = true;
}
},
submitCache: function submitCache() {
if (isCache) {
setTimeout(function () {
if (engine.change.isComposing()) return;
isCache = false;
cachedRecords = cachedRecords.map(function (record) {
if (record.type === 'characterData') {
if (record.target.nodeType === document.TEXT_NODE) {
record['text-data'] = record.target.textContent;
}
}
return record;
});
if (cachedRecords.length > 0) ee.emit('change', cachedRecords);
cachedRecords = [];
}, 20);
}
},
destroyCache: function destroyCache() {
if (isCache) {
setTimeout(function () {
isCache = false;
cachedRecords = [];
}, 20);
}
},
getCaches: function getCaches() {
return cachedRecords;
},
destroy: function destroy() {
ee.removeAllListeners();
mutation.stop();
}
};
return mutation;
};
var Mutation = {
from: function from(engine) {
var mutation = MUTATION_TO_ENGINE.get(engine);
if (!mutation) {
mutation = createMutation(engine);
MUTATION_TO_ENGINE.set(engine, mutation);
}
return mutation;
},
destroy: function destroy(engine) {
var mutation = MUTATION_TO_ENGINE.get(engine);
mutation === null || mutation === void 0 ? void 0 : mutation.destroy();
}
};
var NODE_TO_INDEX = new WeakMap();
var NODE_TO_PARENT = new WeakMap();
var Path = {
isPath: function isPath(value) {
return Array.isArray(value) && value.every(function (v) {
return typeof v === 'number';
});
},
setPath: function setPath(node, parent, index) {
NODE_TO_INDEX.set(node, index);
NODE_TO_PARENT.set(node, parent);
},
getPath: function getPath(node) {
var path = [];
var current = node;
while (current) {
var parent = NODE_TO_PARENT.get(current);
if (!parent) break;
var index = NODE_TO_INDEX.get(current);
if (index === undefined) throw new Error("Invalid index in ".concat(JSON.stringify(current)));
path.unshift(index);
current = parent;
}
return path;
},
getIndex: function getIndex(node) {
var index = NODE_TO_INDEX.get(node);
if (index === undefined) throw new Error("Invalid index in ".concat(node));
return index;
},
isEqual: function isEqual(path, other) {
if (path.length !== other.length) return false;
return path.every(function (p, i) {
return p === other[i];
});
},
isReverse: function isReverse(path, other) {
var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
if (path.length !== other.length) return false;
var index = path.length - 1;
var clone = other.slice();
clone[index] = clone[index] - offset;
return Path.isEqual(path, clone);
},
commonLength: function commonLength(path, other) {
var alen = path.length;
var blen = other.length;
if (alen === 0) return -1;
if (blen === 0) return null;
alen--;
blen--;
for (var i = 0; i < alen; i++) {
var p = path[i];
if (i >= blen || p !== other[i]) return null;
}
return alen;
},
next: function next(path) {
if (path.length === 0) {
throw new Error("Cannot get the next path of a root path [".concat(path, "], because it has no next index."));
}
var last = path[path.length - 1];
return path.slice(0, -1).concat(last + 1);
}
};
var DOMNODE_TO_NODE = new WeakMap();
var NODE_TO_SCHEMA_TYPE = new WeakMap();
var NODE_TO_IS_VOID = new WeakMap();
var Node$1 = {
createFromDOM: function createFromDOM(domNode, schema) {
if (isTransientElementCache(domNode)) return;
var nodeName = domNode.nodeName,
nodeValue = domNode.nodeValue;
if (isDOMElement(domNode)) {
var attributes = domNode.attributes,
childNodes = domNode.childNodes;
var props = {};
var _iterator = _createForOfIteratorHelper(attributes),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _step.value,
name = _step$value.name,
value = _step$value.value;
if (isTransientAttribute(domNode, name)) continue;
if (name === 'style' && isDOMHTMLElement(domNode)) {
props['style'] = toHex(domNode.style.cssText || value);
} else {
props[name] = String(value);
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var children = [];
var _iterator2 = _createForOfIteratorHelper(childNodes),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _child = _step2.value;
var node = Node$1.createFromDOM(_child, schema);
if (node) {
children.push(node);
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
var element = Element$1.create(nodeName.toLowerCase(), props, children);
for (var i = 0; i < children.length; i++) {
var child = children[i];
Path.setPath(child, element, i);
}
Node$1.setDOM(element, domNode, schema);
return element;
}
var text = Text$1.create(String(nodeValue));
Node$1.setDOM(text, domNode);
return text;
},
findNode: function findNode(domNode) {
return DOMNODE_TO_NODE.get(domNode);
},
setDOM: function setDOM(node, domNode, schema) {
DOMNODE_TO_NODE.set(domNode, node);
if (schema && Element$1.isElement(node)) Node$1.setSchemaType(node, domNode, schema);
},
setSchemaType: function setSchemaType(element, node, schema) {
var type = schema.getType(node);
if (type) {
NODE_TO_SCHEMA_TYPE.set(element, type);
}
var isVoid = schema.find(function (rule) {
return rule.name === element.type && rule.isVoid === true;
}).length > 0;
NODE_TO_IS_VOID.set(element, isVoid);
},
isBlock: function isBlock(node) {
if (Element$1.isElement(node)) {
return NODE_TO_SCHEMA_TYPE.get(node) === 'block';
}
return false;
},
isInline: function isInline(node) {
if (Element$1.isElement(node)) {
return NODE_TO_SCHEMA_TYPE.get(node) === 'inline';
}
return false;
},
isMark: function isMark(node) {
if (Element$1.isElement(node)) {
return NODE_TO_SCHEMA_TYPE.get(node) === 'mark';
}
return false;
},
isVoid: function isVoid(node) {
if (Element$1.isElement(node)) {
return NODE_TO_IS_VOID.get(node) === true || ~['img', 'br', 'area', 'col', 'embed', 'hr', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'].indexOf(node.type);
}
return false;
},
get: function get(root, path) {
var node = root;
var _iterator3 = _createForOfIteratorHelper(path),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var index = _step3.value;
if (Element$1.isElement(node)) {
node = node.children[index];
} else {
throw new Error('Cannot find element');
}
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
return node;
}
};
var validSibling = function validSibling(node, sibling) {
var defaultNode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (!sibling || !sibling.isConnected) {
sibling = defaultNode;
}
if (!sibling) return defaultNode;
while (sibling.parentNode !== node) {
var parent = sibling.parentNode;
if (!parent || !node.contains(parent)) return defaultNode;
sibling = parent;
}
return sibling;
};
var transform = function transform(engine, records) {
var mutationNodes = [];
var expandSibling = function expandSibling(mutationNode, oldNode, previousSibling, nextSibling) {
var _mutationNode$previou, _mutationNode$nextSib;
var currentPreviousSibling = mutationNode.previousSibling,
currentNextSibling = mutationNode.nextSibling;
if (previousSibling && (!currentPreviousSibling || currentPreviousSibling.compareDocumentPosition(previousSibling) & globalThis.Node.DOCUMENT_POSITION_PRECEDING) || (currentPreviousSibling === null || currentPreviousSibling === void 0 ? void 0 : currentPreviousSibling.parentNode) !== mutationNode.node) {
mutationNode.previousSibling = validSibling(mutationNode.node, previousSibling, currentPreviousSibling);
}
if (nextSibling && (!currentNextSibling || currentNextSibling.compareDocumentPosition(nextSibling) & globalThis.Node.DOCUMENT_POSITION_FOLLOWING) || (currentNextSibling === null || currentNextSibling === void 0 ? void 0 : currentNextSibling.parentNode) !== mutationNode.node) {
mutationNode.nextSibling = validSibling(mutationNode.node, nextSibling, currentNextSibling);
}
if (mutationNode.previousSibling === oldNode) {
mutationNode.previousSibling = oldNode.previousSibling;
}
if (mutationNode.nextSibling === oldNode) {
mutationNode.nextSibling = oldNode.nextSibling;
}
if (mutationNode.previousSibling !== previousSibling && ((_mutationNode$previou = mutationNode.previousSibling) === null || _mutationNode$previou === void 0 ? void 0 : _mutationNode$previou.contains(previousSibling))) {
mutationNode.previousSibling = mutationNode.previousSibling.previousSibling;
}
if (mutationNode.nextSibling !== nextSibling && ((_mutationNode$nextSib = mutationNode.nextSibling) === null || _mutationNode$nextSib === void 0 ? void 0 : _mutationNode$nextSib.contains(nextSibling))) {
mutationNode.nextSibling = mutationNode.nextSibling.nextSibling;
}
};
var validMutationNode = function validMutationNode(node, previousSibling, nextSibling) {
var hasMutation = false;
var _iterator = _createForOfIteratorHelper(mutationNodes),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var mutationNode = _step.value;
var currentNode = mutationNode.node;
if (node === currentNode || currentNode.contains(node)) {
hasMutation = true;
expandSibling(mutationNode, currentNode, previousSibling, nextSibling);
} else if (node.contains(currentNode)) {
hasMutation = true;
mutationNode.node = node;
var oldPreviousSibling = mutationNode.previousSibling,
oldNextSibling = mutationNode.nextSibling;
mutationNode.previousSibling = validSibling(node, previousSibling, oldPreviousSibling);
mutationNode.nextSibling = validSibling(node, nextSibling, oldNextSibling);
expandSibling(mutationNode, currentNode, oldPreviousSibling, oldNextSibling);
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return hasMutation;
};
var _iterator2 = _createForOfIteratorHelper(records),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var record = _step2.value;
var type = record.type,
attributeName = record.attributeName;
var target = record.target;
var isEditorRoot = false;
if (isDOMElement(target) && isRoot(target)) {
isEditorRoot = true;
}
if (!target.isConnected || isTransientElementCache(target) || type === 'attributes' && (isEditorRoot || attributeName && isTransientAttribute(target, attributeName))) {
continue;
}
var _previousSibling2 = record.previousSibling,
_nextSibling = record.nextSibling;
if (type === 'childList') {
var addedNodes = record.addedNodes;
if (addedNodes.length > 0) {
if (!_previousSibling2) {
_previousSibling2 = addedNodes[0].previousSibling;
}
if (!_nextSibling) {
_nextSibling = addedNodes[addedNodes.length - 1].nextSibling;
}
}
if (!_previousSibling2 && _nextSibling) {
_previousSibling2 = _nextSibling.previousSibling;
}
if (!_nextSibling && _previousSibling2) {
_nextSibling = _previousSibling2.nextSibling;
}
} else if (type === 'characterData' || type === 'attributes') {
if (!_previousSibling2) {
_previousSibling2 = target.previousSibling;
}
if (!_nextSibling) {
_nextSibling = target.nextSibling;
}
if (type === 'attributes' || !isDOMElement(target)) {
var parent = target.parentElement;
if (!parent || isTransientElementCache(parent)) continue;
target = parent;
}
}
if (validMutationNode(target, _previousSibling2, _nextSibling)) continue;
mutationNodes.push({
node: target,
previousSibling: validSibling(target, _previousSibling2),
nextSibling: validSibling(target, _nextSibling)
});
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
var operations = [];
for (var _i = 0, _mutationNodes = mutationNodes; _i < _mutationNodes.length; _i++) {
var _previousSibling, _parentNode$children;
var mutationNode = _mutationNodes[_i];
var node = mutationNode.node;
var previousSibling = mutationNode.previousSibling,
nextSibling = mutationNode.nextSibling;
var parentNode = Node$1.findNode(node);
if (!parentNode) {
continue;
}
if (!Element$1.isElement(parentNode)) throw new Error('parentNode is not an element');
var parentPath = Path.getPath(parentNode);
if (previousSibling) {
while (isTransientElementCache(previousSibling) || previousSibling === node.firstChild) {
previousSibling = previousSibling.previousSibling;
if (!previousSibling) break;
}
}
if (nextSibling) {
while (isTransientElementCache(nextSibling) || nextSibling === node.lastChild) {
nextSibling = nextSibling.nextSibling;
if (!nextSibling) break;
}
}
var previousNode = previousSibling ? Node$1.findNode(previousSibling) : null;
var nextNode = nextSibling ? Node$1.findNode(nextSibling) : null;
var previousIndex = previousNode ? Path.getIndex(previousNode) : -1;
var nextIndex = nextNode ? Path.getIndex(nextNode) : parentNode.children.length;
var children = []; // 在model中找不到对应的node,说明是新增的,这里就无法确定到底是从哪个位置新增的,所以只能设置为null从头开始遍历
var next = previousNode ? (_previousSibling = previousSibling) === null || _previousSibling === void 0 ? void 0 : _previousSibling.nextSibling : null;
if (!next) {
next = node.firstChild;
previousIndex = -1;
}
while (next && next !== nextSibling) {
var _node = Node$1.createFromDOM(next, engine.schema);
if (_node) {
children.push(_node);
}
next = next.nextSibling;
}
var start = previousIndex + 1; // const end = nextIndex - 1;
var oldChildren = parentNode.children.slice(start, nextIndex);
operations.push.apply(operations, _toConsumableArray(diff(engine, oldChildren, children, parentPath, start)));
(_parentNode$children = parentNode.children).splice.apply(_parentNode$children, [start, oldChildren.length].concat(children));
for (var i = start; i < parentNode.children.length; i++) {
Path.setPath(parentNode.children[i], parentNode, i);
}
}
return operations;
};
var diff = function diff(engine, a, b, path) {
var index = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
var isLoading = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
var len = Math.max(a.length, b.length);
var operations = [];
for (var i = 0; i < len; i++) {
var node = a[i];
var newNode = b[i];
var currentPath = path.concat(i + index); // insert node
if (!node) {
operations.push({
type: 'insert_node',
path: currentPath,
node: newNode
});
} // remove node
else if (!newNode) {
operations.unshift({
type: 'remove_node',
path: path.concat(i + index),
node: node
});
} else {
var isElement = Element$1.isElement(node);
var element = isElement ? node : null;
var text = isElement ? null : node;
var newIsElement = Element$1.isElement(newNode);
var newElement = newIsElement ? newNode : null;
var newText = newIsElement ? null : newNode;
isLoading = isLoading || !!newElement && isLoadingCard(engine, newElement);
if (isElement !== newIsElement || element && newElement && element.type !== newElement.type) {
operations.unshift({
type: 'remove_node',
path: currentPath,
node: node,
undoable: isLoading
});
operations.push({
type: 'insert_node',
path: currentPath,
node: newNode,
undoable: isLoading
});
continue;
}
var hasAttributeChange = false;
var getAttributes = function getAttributes(node) {
var attributes = {};
for (var key in node) {
if (~['children', 'text', 'type'].indexOf(key)) continue;
attributes[key] = node[key];
}
return attributes;
};
var attributes = getAttributes(node);
var attributesLength = Object.keys(attributes).length;
var newAttributes = getAttributes(newNode);
var newAttributesLength = Object.keys(newAttributes).length;
if (attributesLength !== newAttributesLength) {
hasAttributeChange = true;
} else {
for (var key in attributes) {
if (attributes[key] !== newAttributes[key]) {
hasAttributeChange = true;
break;
}
}
}
if (hasAttributeChange) {
var cardValue = newAttributes[CARD_VALUE_KEY];
var operation = {
type: 'set_node',
path: currentPath,
properties: attributes,
newProperties: newAttributes,
undoable: isLoading
};
if (cardValue) {
var value = decodeCardValue(cardValue);
var component = engine.card.find(value.id);
if ((component === null || component === void 0 ? void 0 : component.writeHistoryOnValueChange) && component.writeHistoryOnValueChange(value) === false) {
operation.undoable = true;
}
}
operations.push(operation);
}
if (element && newElement) operations.push.apply(operations, _toConsumableArray(diff(engine, element.children, newElement.children, currentPath, 0, isLoading)));else if (text && newText && text.text !== newText.text) {
operations.push.apply(operations, _toConsumableArray(transformText(text.text, newText.text, currentPath, isLoading)));
}
}
}
return operations;
};
var transformText = function transformText(a, b, path) {
var isLoading = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var operations = [];
var patches = new diffMatchPatch.diff_match_patch().patch_make(a, b);
Object.keys(patches).forEach(function (key) {
var patch = patches[key];
if (patch.start1 === null) return;
var offset = patch.start1;
patch.diffs.forEach(function (diff) {
var _diff = _slicedToArray(diff, 2),
type = _diff[0],
data = _diff[1];
if (type !== diffMatchPatch.DIFF_DELETE) {
if (type !== diffMatchPatch.DIFF_INSERT) {
if (type === diffMatchPatch.DIFF_EQUAL) {
offset += data.length;
}
} else {
operations.push({
type: 'insert_text',
text: data,
path: path,
offset: offset,
undoable: isLoading
});
}
} else {
operations.unshift({
type: 'remove_text',
text: data,
path: path,
offset: offset,
undoable: isLoading
});
}
});
});
return operations;
};
var isLoadingCard = function isLoadingCard(engine, element) {
var cardKey = element[CARD_KEY];
var cardType = element[CARD_TYPE_KEY];
var dataId = element[DATA_ID];
if (cardKey && cardType && dataId) {
var _engine$container$get;
var cardNode = (_engine$container$get = engine.container.get()) === null || _engine$container$get === void 0 ? void 0 : _engine$container$get.querySelector("[".concat(DATA_ID, "=\"").concat(dataId, "\"]"));
if (cardNode === null || cardNode === void 0 ? void 0 : cardNode.getAttribute(CARD_LOADING_KEY)) {
return true;
}
}
return false;
};
var Operation = {
transform: transform,
diff: diff,
inverse: function inverse(operation) {
switch (operation.type) {
case 'insert_node':
{
return _objectSpread2(_objectSpread2({}, operation), {}, {
type: 'remove_node'
});
}
case 'remove_node':
{
return _objectSpread2(_objectSpread2({}, operation), {}, {
type: 'insert_node'
});
}
case 'insert_text':
{
return _objectSpread2(_objectSpread2({}, operation), {}, {
type: 'remove_text'
});
}
case 'remove_text':
{
return _objectSpread2(_objectSpread2({}, operation), {}, {
type: 'insert_text'
});
}
case 'set_node':
{
var properties = operation.properties,
newProperties = operation.newProperties;
return _objectSpread2(_objectSpread2({}, operation), {}, {
type: 'set_node',
properties: newProperties,
newProperties: properties
});
}
}
},
isReverse: function isReverse(a, b) {
if (a.type === 'insert_node' && b.type === 'remove_node' || a.type === 'remove_node' && b.type === 'insert_node') {
return isEqual__default['default'](a.node, b.node) && Path.isEqual(a.path, b.path);
}
if (a.type === 'insert_text' && b.type === 'remove_text') {
var aPath = a.path.concat(a.offset);
var bPath = b.path.concat(b.offset);
return isEqual__default['default'](a.text, b.text) && (isEqual__default['default'](aPath, bPath) || Path.isReverse(aPath, bPath, a.text.length) || Path.isReverse(bPath, aPath, a.text.length));
}
if (a.type === 'remove_text' && b.type === 'insert_text') {
var _aPath = a.path.concat(a.offset);
var _bPath = b.path.concat(b.offset);
return isEqual__default['default'](a.text, b.text) && isEqual__default['default'](_aPath, _bPath);
}
return false;
},
canOpAffectPath: function canOpAffectPath(operation, path) {
return Path.commonLength(path, operation.path) !== null;
}
};
var autoAdjustOverflow = {
adjustX: true,
adjustY: true
};
var targetOffset = [0, 0];
var placements = {
left: {
points: ['cr', 'cl'],
overflow: autoAdjustOverflow,
offset: [-4, 0],
targetOffset: targetOffset
},
right: {
points: ['cl', 'cr'],
overflow: autoAdjustOverflow,
offset: [4, 0],
targetOffset: targetOffset
},
top: {
points: ['bc', 'tc'],
overflow: autoAdjustOverflow,
offset: [0, -4],
targetOffset: targetOffset
},
bottom: {
points: ['tc', 'bc'],
overflow: autoAdjustOverflow,
offset: [0, 4],
targetOffset: targetOffset
},
topLeft: {
points: ['bl', 'tl'],
overflow: autoAdjustOverflow,
offset: [0, -4],
targetOffset: targetOffset
},
leftTop: {
points: ['tr', 'tl'],
overflow: autoAdjustOverflow,
offset: [-4, 0],
targetOffset: targetOffset
},
topRight: {
points: ['br', 'tr'],
overflow: autoAdjustOverflow,
offset: [0, -4],
targetOffset: targetOffset
},
rightTop: {
points: ['tl', 'tr'],
overflow: autoAdjustOverflow,
offset: [4, 0],
targetOffset: targetOffset
},
bottomRight: {
points: ['tr', 'br'],
overflow: autoAdjustOverflow,
offset: [0, 4],
targetOffset: targetOffset
},
rightBottom: {
points: ['bl', 'br'],
overflow: autoAdjustOverflow,
offset: [4, 0],
targetOffset: targetOffset
},
bottomLeft: {
points: ['tl', 'bl'],
overflow: autoAdjustOverflow,
offset: [0, 4],
targetOffset: targetOffset
},
leftBottom: {
points: ['br', 'bl'],
overflow: autoAdjustOverflow,
offset: [-4, 0],
targetOffset: targetOffset
}
};
var css_248z$1 = ".data-tooltip {\r\n\tfont-size: 14px;\r\n\tfont-variant: tabular-nums;\r\n\tline-height: 1.5;\r\n\tcolor: rgba(0, 0, 0, 0.65);\r\n\t-webkit-box-sizing: border-box;\r\n\tbox-sizing: border-box;\r\n\tmargin: 0;\r\n\tpadding: 0;\r\n\tlist-style: none;\r\n\tposition: absolute;\r\n\tz-index: 1060;\r\n\tdisplay: block;\r\n\tvisibility: visible;\r\n\tmax-width: 320px;\r\n\tword-wrap:break-word;\r\n top: 0;\r\n}\r\n\r\n.data-tooltip-hidden {\r\n\topacity: 0;\r\n\tvisibility: hidden;\r\n\ttransition: opacity 0.3s ease-in-out;\r\n}\r\n\r\n.data-tooltip-active {\r\n\topacity: 1;\r\n\tvisibility: visible;\r\n}\r\n\r\n.data-tooltip-placement-top,.data-tooltip-placement-topLeft,.data-tooltip-placement-topRight {\r\n\tpadding-bottom: 8px;\r\n}\r\n\r\n.data-tooltip-placement-right,.data-tooltip-placement-rightTop,.data-tooltip-placement-rightBottom {\r\n\tpadding-left: 8px;\r\n}\r\n\r\n.data-tooltip-placement-bottom,.data-tooltip-placement-bottomLeft,.data-tooltip-placement-bottomRight {\r\n\tpadding-top: 8px;\r\n}\r\n\r\n.data-tooltip-placement-left,.data-tooltip-placement-leftTop,.data-tooltip-placement-leftBottom {\r\n\tpadding-right: 8px;\r\n}\r\n\r\n.data-tooltip-inner {\r\n\tpadding: 6px 8px;\r\n\tcolor: #fff;\r\n\ttext-align: left;\r\n\ttext-decoration: none;\r\n\tbackground-color: rgba(0, 0, 0, 0.75);\r\n\tborder-radius: 4px;\r\n\t-webkit-box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\r\n\tbox-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\r\n\tword-wrap: break-word;\r\n}\r\n\r\n.data-tooltip-arrow {\r\n\tposition: absolute;\r\n\twidth: 0;\r\n\theight: 0;\r\n\tborder-color: transparent;\r\n\tborder-style: solid;\r\n}\r\n\r\n.data-tooltip-placement-top .data-tooltip-arrow,.data-tooltip-placement-topLeft .data-tooltip-arrow,.data-tooltip-placement-topRight .data-tooltip-arrow {\r\n\tbottom: 3px;\r\n\tborder-width: 5px 5px 0;\r\n\tborder-top-color: rgba(0, 0, 0, 0.75);\r\n}\r\n\r\n.data-tooltip-placement-top .data-tooltip-arrow {\r\n\tleft: 50%;\r\n\tmargin-left: -5px;\r\n}\r\n\r\n.data-tooltip-placement-topLeft .data-tooltip-arrow {\r\n\tleft: 16px;\r\n}\r\n\r\n.data-tooltip-placement-topRight .data-tooltip-arrow {\r\n\tright: 16px;\r\n}\r\n\r\n.data-tooltip-placement-right .data-tooltip-arrow,.data-tooltip-placement-rightTop .data-tooltip-arrow,.data-tooltip-placement-rightBottom .data-tooltip-arrow {\r\n\tleft: 3px;\r\n\tborder-width: 5px 5px 5px 0;\r\n\tborder-right-color: rgba(0, 0, 0, 0.75);\r\n}\r\n\r\n.data-tooltip-placement-right .data-tooltip-arrow {\r\n\ttop: 50%;\r\n\tmargin-top: -5px;\r\n}\r\n\r\n.data-tooltip-placement-rightTop .data-tooltip-arrow {\r\n\ttop: 8px;\r\n}\r\n\r\n.data-tooltip-placement-rightBottom .data-tooltip-arrow {\r\n\tbottom: 8px;\r\n}\r\n\r\n.data-tooltip-placement-left .data-tooltip-arrow,.data-tooltip-placement-leftTop .data-tooltip-arrow,.data-tooltip-placement-leftBottom .data-tooltip-arrow {\r\n\tright: 3px;\r\n\tborder-width: 5px 0 5px 5px;\r\n\tborder-left-color: rgba(0, 0, 0, 0.75);\r\n}\r\n\r\n.data-tooltip-placement-left .data-tooltip-arrow {\r\n\ttop: 50%;\r\n\tmargin-top: -5px;\r\n}\r\n\r\n.data-tooltip-placement-leftTop .data-tooltip-arrow {\r\n\ttop: 8px;\r\n}\r\n\r\n.data-tooltip-placement-leftBottom .data-tooltip-arrow {\r\n\tbottom: 8px;\r\n}\r\n\r\n.data-tooltip-placement-bottom .data-tooltip-arrow,.data-tooltip-placement-bottomLeft .data-tooltip-arrow,.data-tooltip-placement-bottomRight .data-tooltip-arrow {\r\n\ttop: 3px;\r\n\tborder-width: 0 5px 5px;\r\n\tborder-bottom-color: rgba(0, 0, 0, 0.75);\r\n}\r\n\r\n.data-tooltip-placement-bottom .data-tooltip-arrow {\r\n\tleft: 50%;\r\n\tmargin-left: -5px;\r\n}\r\n\r\n.data-tooltip-placement-bottomLeft .data-tooltip-arrow {\r\n\tleft: 16px;\r\n}\r\n\r\n.data-tooltip-placement-bottomRight .data-tooltip-arrow {\r\n\tright: 16px;\r\n}";
styleInject(css_248z$1);
var template = function template(options) {
return "\n ");
};
var Tooltip = /*#__PURE__*/function () {
function Tooltip() {
_classCallCheck(this, Tooltip);
}
_createClass(Tooltip, null, [{
key: "show",
value: function show(node, title) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
placement: 'top'
};
Tooltip.hide();
var root = $(template(options)); // 设置提示文字
if (typeof title === 'string') root.find('[data-role=tooltip]').html(title);else root.find('[data-role=tooltip]').append(title); // 计算定位
var doc = getDocument();
var body = $(doc.body);
body.append(root);
var rect = domAlign__default['default'](root.get(), node.get(), _objectSpread2({}, placements[options.placement]));
var align = Object.keys(placements).find(function (p) {
var points = placements[p].points;
return points[0] === rect.points[0] && points[1] === rect.points[1];
});
if (align !== options.placement) {
root.removeClass("data-tooltip-placement-".concat(options.placement)).addClass("data-tooltip-placement-".concat(align));
}
root.addClass('data-tooltip-active');
}
}, {
key: "hide",
value: function hide() {
var doc = getDocument();
$(doc.body).find("div[".concat(DATA_ELEMENT, "=tooltip]")).remove();
}
}]);
return Tooltip;
}();
var template$1 = function template(options) {
return "\n \n \n ").concat(options.content, "\n \n ");
};
var Button = /*#__PURE__*/function () {
function Button(options) {
_classCallCheck(this, Button);
this.options = void 0;
this.root = void 0;
this.options = options;
this.root = $(template$1(options));
if (options.style) {
this.root.attributes('style', options.style);
}
if (options.class) {
this.root.addClass(options.class);
}
}
_createClass(Button, [{
key: "getPlacement",
value: function getPlacement() {
var dataPlacement = this.root.closest('.data-toolbar').attributes('data-placement') || 'top';
return dataPlacement.startsWith('top') ? 'top' : 'bottom';
}
}, {
key: "render",
value: function render(container) {
var _this = this;
var _this$options = this.options,
title = _this$options.title,
didMount = _this$options.didMount,
onClick = _this$options.onClick,
link = _this$options.link;
container.append(this.root);
if (title) {
this.root.on('mouseenter', function () {
var placement = _this.getPlacement();
Tooltip.show(_this.root, typeof title === 'function' ? title() : title, {
placement: placement
});
});
this.root.on('mouseleave', function () {
Tooltip.hide();
});
this.root.on('mousedown', function () {
Tooltip.hide();
});
}
if (!link && onClick) {
this.root.find('a').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
onClick(e, _this.root);
});
}
if (didMount) {
didMount(this.root);
}
}
}]);
return Button;
}();
var template$2 = function template(options) {
var checked = !!options.checked;
if (options.getState) checked = options.getState();
return "\n ");
};
var _default = /*#__PURE__*/function () {
function _default(options) {
_classCallCheck(this, _default);
this.options = void 0;
this.root = void 0;
this.switch = void 0;
this.options = options;
}
_createClass(_default, [{
key: "renderTo",
value: function renderTo(container) {
var _this = this;
this.root = $(template$2(this.options));
this.switch = this.root.find('.switch-btn');
container.append(this.root);
this.root.on('mousedown', function (e) {
return e.preventDefault();
});
var onClick = this.options.onClick;
this.root.on('click', function (e) {
e.stopPropagation();
if (onClick) {
onClick(e, _this.root);
_this.updateSwitch();
}
});
}
}, {
key: "updateSwitch",
value: function updateSwitch() {
if (this.options.getState) {
if (this.options.getState()) {
var _this$switch;
(_this$switch = this.switch) === null || _this$switch === void 0 ? void 0 : _this$switch.addClass('switch-checked');
} else {
var _this$switch2;
(_this$switch2 = this.switch) === null || _this$switch2 === void 0 ? void 0 : _this$switch2.removeClass('switch-checked');
}
}
}
}]);
return _default;
}();
var template$3 = function template(options) {
return "\n \n \n ").concat(options.content, "\n \n
");
};
var _default$1 = /*#__PURE__*/function () {
function _default(options) {
_classCallCheck(this, _default);
this.options = void 0;
this.root = void 0;
this.options = options;
}
_createClass(_default, [{
key: "renderTo",
value: function renderTo(container) {
var _this = this;
this.root = $(template$3(this.options));
container.append(this.root);
var onClick = this.options.onClick;
if (onClick) {
this.root.on('click', function (event) {
return onClick(event, _this.root);
});
}
}
}]);
return _default;
}();
var template$4 = function template(options) {
return "\n \n ").concat(options.content, "\n \n ");
};
var Dropdown = /*#__PURE__*/function () {
function Dropdown(options) {
var _this = this;
_classCallCheck(this, Dropdown);
this.options = void 0;
this.root = void 0;
this.dropdown = void 0;
this.documentMouseDown = function (e) {
var _this$dropdown;
if (!_this.root) return;
if (!_this.root[0].contains(e.target) && ((_this$dropdown = _this.dropdown) === null || _this$dropdown === void 0 ? void 0 : _this$dropdown.hasClass('show'))) {
_this.hideDropdown();
}
};
this.options = options;
}
_createClass(Dropdown, [{
key: "initToggleEvent",
value: function initToggleEvent() {
var _this2 = this;
var dropdownBtn = this.root.find('.data-toolbar-dropdown');
dropdownBtn.on('mousedown', function (e) {
e.preventDefault();
e.stopPropagation();
});
dropdownBtn.on('click', function (e) {
e.stopPropagation();
_this2.toggleDropdown();
});
document.addEventListener('mousedown', this.documentMouseDown, true);
}
}, {
key: "toggleDropdown",
value: function toggleDropdown() {
var _this$dropdown2;
if ((_this$dropdown2 = this.dropdown) === null || _this$dropdown2 === void 0 ? void 0 : _this$dropdown2.hasClass('show')) {
this.hideDropdown();
} else {
this.showDropdown();
}
}
}, {
key: "showDropdown",
value: function showDropdown() {
var _this$dropdown3;
(_this$dropdown3 = this.dropdown) === null || _this$dropdown3 === void 0 ? void 0 : _this$dropdown3.addClass('show');
}
}, {
key: "hideDropdown",
value: function hideDropdown() {
var _this$dropdown4;
(_this$dropdown4 = this.dropdown) === null || _this$dropdown4 === void 0 ? void 0 : _this$dropdown4.removeClass('show');
}
}, {
key: "getPlacement",
value: function getPlacement() {
var dataPlacement = this.root.closest('.data-toolbar').attributes('data-placement') || 'top';
return dataPlacement.startsWith('top') ? 'top' : 'bottom';
}
}, {
key: "renderTooltip",
value: function renderTooltip() {
var _this3 = this;
var title = this.options.title;
if (title) {
this.root.on('mouseenter', function () {
var placement = _this3.getPlacement();
Tooltip.show(_this3.root, typeof title === 'function' ? title() : title, {
placement: placement
});
});
this.root.on('mouseleave', function () {
Tooltip.hide();
});
this.root.on('mousedown', function () {
Tooltip.hide();
});
}
}
}, {
key: "renderDropdown",
value: function renderDropdown() {
var _this4 = this;
this.dropdown = this.root.find('.dropdown-container');
var items = this.options.items;
items.forEach(function (item) {
switch (item.type) {
case 'switch':
return new _default(item).renderTo(_this4.dropdown);
case 'button':
return new _default$1(item).renderTo(_this4.dropdown);
}
});
this.dropdown.on('click', function (e) {
e.stopPropagation();
_this4.hideDropdown();
});
}
}, {
key: "render",
value: function render(container) {
this.root = $(template$4(this.options));
container.append(this.root);
this.initToggleEvent();
this.renderTooltip();
this.renderDropdown();
var didMount = this.options.didMount;
if (didMount) {
didMount(this.root);
}
}
}, {
key: "destroy",
value: function destroy() {
document.removeEventListener('mousedown', this.documentMouseDown, true);
}
}]);
return Dropdown;
}();
var template$5 = function template(options) {
return "\n \n ".concat(options.prefix ? "" + escape(options.prefix) + '' : '', "").concat(options.suffix ? "" + escape(options.suffix) + '' : '', "\n ");
};
var Input = /*#__PURE__*/function () {
function Input(options) {
_classCallCheck(this, Input);
this.options = void 0;
this.root = void 0;
this.onEnter = void 0;
this.onInput = void 0;
this.onChange = void 0;
this.options = options;
this.root = $(template$5(options));
this.onEnter = options.onEnter || function () {};
this.onInput = options.onInput || function () {};
this.onChange = options.onChange || function () {};
}
_createClass(Input, [{
key: "find",
value: function find(role) {
var expr = '[data-role='.concat(role, ']');
return this.root.find(expr);
}
}, {
key: "render",
value: function render(container) {
var _this = this;
var _this$options = this.options,
value = _this$options.value,
didMount = _this$options.didMount;
var input = this.find('input');
var inputElement = input.get();
if (!inputElement) return;
inputElement.value = (value !== undefined ? value : '').toString();
input.on('keydown', function (e) {
e.stopPropagation();
if (isHotkey__default['default']('enter', e)) {
e.preventDefault();
inputElement.blur();
_this.onEnter(inputElement.value);
}
});
input.on('input', function () {
_this.onInput(inputElement.value);
});
input.on('change', function () {
setTimeout(function () {
_this.onChange(inputElement.value);
}, 10);
});
container.append(this.root);
if (didMount) didMount(this.root);
}
}]);
return Input;
}();
var template$6 = function template(options) {
var checked = !!options.checked;
if (options.getState) checked = options.getState();
return "\n ");
};
var _default$2 = /*#__PURE__*/function () {
function _default(options) {
_classCallCheck(this, _default);
this.options = void 0;
this.root = void 0;
this.switch = void 0;
this.options = options;
this.root = $(template$6(options));
this.switch = this.root.find('.switch-btn');
if (options.class) {
this.root.addClass(options.class);
}
}
_createClass(_default, [{
key: "render",
value: function render(container) {
var _this = this;
var _this$options = this.options,
didMount = _this$options.didMount,
onClick = _this$options.onClick;
container.append(this.root);
this.root.on('mousedown', function (e) {
return e.preventDefault();
});
this.root.on('click', function (e) {
e.stopPropagation();
if (onClick) {
onClick(e, _this.root);
_this.updateSwitch();
}
});
if (didMount) {
didMount(this.root);
}
}
}, {
key: "updateSwitch",
value: function updateSwitch() {
if (this.options.getState) {
if (this.options.getState()) {
var _this$switch;
(_this$switch = this.switch) === null || _this$switch === void 0 ? void 0 : _this$switch.addClass('switch-checked');
} else {
var _this$switch2;
(_this$switch2 = this.switch) === null || _this$switch2 === void 0 ? void 0 : _this$switch2.removeClass('switch-checked');
}
}
}
}]);
return _default;
}();
var css_248z$2 = ".data-toolbar {\n\tposition: absolute;\n\topacity: 0;\n\tvisibility: hidden;\n\twidth: auto;\n\tline-height: 26px;\n\tdisplay: flex;\n\tflex-direction: row;\n\tfont-size: 14px;\n\tfont-weight: normal;\n\ttext-indent: 0;\n\t-webkit-user-select: none;\n\t-moz-user-select: none;\n\t user-select: none;\n z-index: 127;\n}\n\n.data-toolbar-active {\n\topacity: 1;\n\tvisibility: visible;\n}\n\n.data-toolbar-block {\n\ttop: auto;\n\tbottom: -46px;\n\tleft: -1px;\n\tright: auto;\n\theight: 40px;\n}\n\n.data-toolbar-btn {\n\tline-height: 26px;\n\tmin-width: 28px;\n\tdisplay: inline-block;\n\ttext-align: center;\n\tcolor: #595959;\n\ttransition: background-color 0.3s ease-in-out;\n\tcursor: pointer;\n}\n\n.data-toolbar-btn-disabled,.data-toolbar-btn-disabled:hover {\n\tbackground-color: transparent;\n\tbox-shadow: none;\n\tcursor: not-allowed;\n}\n\n.data-toolbar-group {\n\tborder: 1px solid rgba(226, 226, 226, 0.84);\n border-radius: 4px;\n box-shadow: 0px 2px 4px 0px rgb(225 225 225 / 50%);\n background: #fff;\n position: relative;\n display: inline-flex;\n padding: 5px;\n align-items: center;\n}\n\n.data-toolbar-item {\n\tposition: relative;\n\tdisplay: inline-block;\n\tline-height: 26px;\n\ttext-align: left;\n\tcolor: #595959;\n\tflex: 0 0 auto;\n font-size: 12px;\n cursor: pointer;\n}\n\n.data-toolbar-item:not(.data-toolbar-item-input):hover, .data-toolbar-item.active:not(.data-toolbar-item-input){\n background-color: #f4f4f4;\n border-radius: 2px;\n}\n\n.data-toolbar-item > * {\n font-size: 12px !important;\n}\n\n.data-toolbar-item[disabled] {\n\topacity: 0.5;\n\tcursor: not-allowed;\n}\n\n.data-toolbar-item-split {\n\twidth: 1px;\n\theight: 16px;\n\tline-height: 16px;\n\tmargin: 6px 4px;\n\tborder-left: 1px solid #e8e8e8;\n\tdisplay: inline-block;\n}\n\n.data-toolbar-item-dropdown-active {\n\topacity: 1;\n\tvisibility: visible;\n\ttransform: translateY(0px);\n}\n\n.data-toolbar-item-input {\n\tdisplay: flex;\n margin: 0 4px;\n}\n\n.data-toolbar-item-input .data-toolbar-input {\n width: 46px;\n line-height: 12px;\n font-size: 12px;\n outline: none;\n border: 1px solid #dadada;\n border-radius: 4px;\n}\n\n.data-toolbar-item-input .data-toolbar-input::-moz-selection {\n color: inherit;\n background:transparent\n}\n\n.data-toolbar-item-input .data-toolbar-input::selection {\n color: inherit;\n background:transparent\n}\n\n.data-toolbar-item-input .data-toolbar-input:focus::-moz-selection\n{\n color: #fff;\n background: #1890ff;\n}\n\n.data-toolbar-item-input .data-toolbar-input:focus::selection\n{\n color: #fff;\n background: #1890ff;\n}\n\n.data-toolbar-item-dropdown .dropdown-container {\n\tdisplay: none;\n\tposition: absolute;\n\tpadding: 8px 0;\n\ttop: 100%;\n\tmargin-top: 6px;\n\tborder-radius: 2px;\n\tbackground-color: #fff;\n\tbox-shadow: 0 1px 4px -2px rgba(0, 0, 0, 0.13), 0 2px 8px 0 rgba(0, 0, 0, 0.08), 0 8px 16px 4px rgba(0, 0, 0, 0.04);\n z-index: 99999;\n}\n\n.data-toolbar-item-dropdown .dropdown-container.show {\n\tdisplay: block;\n}\n\n.data-toolbar-dropdown-item {\n\tpadding: 2px 16px;\n\tmargin: 0;\n\twhite-space: nowrap;\n\tline-height: 26px;\n\tcolor: #404040;\n\tcursor: pointer;\n display: block;\n}\n\n.data-toolbar-dropdown-item:hover {\n\tbackground-color: #f5f5f5;\n}\n\n.data-toolbar-dropdown-switch {\n\tdisplay: flex;\n\talign-items: center;\n}\n\n.data-toolbar-dropdown-switch .data-toolbar-dropdown-item-content {\n\tflex: 1;\n margin-right: 4px;\n}\n\n.data-toolbar-dropdown-switch .switch-btn {\n margin: 0;\n padding: 0;\n color: #595959;\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5;\n list-style: none;\n -webkit-font-feature-settings: \"tnum\";\n font-feature-settings: \"tnum\";\n position: relative;\n display: inline-block;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n vertical-align: middle;\n background-color: rgba(0,0,0,.25);\n border: 0;\n border-radius: 100px;\n cursor: pointer;\n -webkit-transition: all .2s;\n transition: all .2s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n min-width: 28px;\n height: 16px;\n line-height: 16px;\n}\n\n.data-toolbar-dropdown-switch .switch-btn.switch-checked {\n background-color: #347EFF\n}\n\n.data-toolbar-dropdown-switch .switch-btn .switch-handle {\n top: 2px;\n left: 2px;\n width: 12px;\n height: 12px;\n}\n\n.data-toolbar-dropdown-switch .switch-btn .switch-handle, .data-toolbar-dropdown-switch .switch-btn .switch-handle:before {\n position: absolute;\n -webkit-transition: all .2s ease-in-out;\n transition: all .2s ease-in-out;\n}\n\n.data-toolbar-dropdown-switch .switch-btn.switch-checked .switch-handle {\n left: calc(100% - 14px);\n}\n\n.data-toolbar-dropdown-switch .switch-btn .switch-handle:before {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background-color: #fff;\n border-radius: 9px;\n -webkit-box-shadow: 0 2px 4px 0 rgb(0 35 11 / 20%);\n box-shadow: 0 2px 4px 0 rgb(0 35 11 / 20%);\n content: \"\";\n}\n\n.data-toolbar-dropdown-switch .switch-btn .switch-inner {\n display: block;\n margin: 0 5px 0 18px;\n font-size: 12px;\n color: #fff;\n -webkit-transition: margin .2s;\n transition: margin .2s;\n}\n\n.data-toolbar-dropdown-switch .switch-btn.switch-checked .switch-inner {\n margin: 0 18px 0 5px;\n}\n.data-toolbar-switch {\n\tdisplay: flex;\n\talign-items: center;\n padding: 0 4px;\n cursor: pointer;\n width: -webkit-max-content;\n width: -moz-max-content;\n width: max-content;\n}\n\n.data-toolbar-switch:hover {\n background-color: #f4f4f4;\n border-radius: 2px;\n}\n\n.data-toolbar-switch .switch-content {\n\tflex: 1;\n margin-right: 4px;\n}\n\n.data-toolbar-switch .switch-btn {\n margin: 0;\n padding: 0;\n color: #595959;\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5;\n list-style: none;\n -webkit-font-feature-settings: \"tnum\";\n font-feature-settings: \"tnum\";\n position: relative;\n display: inline-block;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n vertical-align: middle;\n background-color: rgba(0,0,0,.25);\n border: 0;\n border-radius: 100px;\n cursor: pointer;\n -webkit-transition: all .2s;\n transition: all .2s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n min-width: 28px;\n height: 16px;\n line-height: 16px;\n}\n\n.data-toolbar-switch .switch-btn.switch-checked {\n background-color: #347EFF\n}\n\n.data-toolbar-switch .switch-btn .switch-handle {\n top: 2px;\n left: 2px;\n width: 12px;\n height: 12px;\n}\n\n.data-toolbar-switch .switch-btn .switch-handle, .data-toolbar-switch .switch-btn .switch-handle:before {\n position: absolute;\n -webkit-transition: all .2s ease-in-out;\n transition: all .2s ease-in-out;\n}\n\n.data-toolbar-switch .switch-btn.switch-checked .switch-handle {\n left: calc(100% - 14px);\n}\n\n.data-toolbar-switch .switch-btn .switch-handle:before {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background-color: #fff;\n border-radius: 9px;\n -webkit-box-shadow: 0 2px 4px 0 rgb(0 35 11 / 20%);\n box-shadow: 0 2px 4px 0 rgb(0 35 11 / 20%);\n content: \"\";\n}\n\n.data-toolbar-switch .switch-btn .switch-inner {\n display: block;\n margin: 0 5px 0 18px;\n font-size: 12px;\n color: #fff;\n -webkit-transition: margin .2s;\n transition: margin .2s;\n}\n\n.data-toolbar-switch .switch-btn.switch-checked .switch-inner {\n margin: 0 18px 0 5px;\n}";
styleInject(css_248z$2);
var template$7 = function template() {
return "");
};
var Toolbar = /*#__PURE__*/function () {
function Toolbar(options) {
_classCallCheck(this, Toolbar);
this.options = void 0;
this.root = void 0;
this.items = [];
this.options = _objectSpread2({}, options);
this.root = $(template$7());
}
_createClass(Toolbar, [{
key: "getPlacement",
value: function getPlacement() {
var dataPlacement = this.root.attributes('data-placement') || 'top';
return dataPlacement.startsWith('top') ? 'top' : 'bottom';
}
}, {
key: "addItems",
value: function addItems(node) {
var _this = this;
this.options.items.forEach(function (options) {
var item;
if (options.type === 'button') {
item = new Button(options);
item.render(node);
}
if (options.type === 'switch') {
item = new _default$2(options);
item.render(node);
}
if (options.type === 'input') {
var inputOptions = options;
item = new Input(inputOptions);
item.render(node);
}
if (options.type === 'dropdown') {
item = new Dropdown(options);
item.render(node);
}
if (options.type === 'node') {
var nodeOptions = options;
var nodeItem = nodeOptions.node;
nodeItem.addClass('data-toolbar-item');
var title = nodeOptions.title;
if (title) {
nodeItem.on('mouseenter', function () {
var placement = _this.getPlacement();
Tooltip.show(nodeItem, typeof title === 'function' ? title() : title, {
placement: placement
});
});
nodeItem.on('mouseleave', function () {
Tooltip.hide();
});
nodeItem.on('mousedown', function () {
Tooltip.hide();
});
}
node.append(nodeItem);
if (options.didMount) options.didMount(nodeItem);
}
if (item) _this.items.push(item);
});
}
}, {
key: "find",
value: function find(role) {
var expr = '[data-role='.concat(role, ']');
return this.root.find(expr);
}
}, {
key: "destroy",
value: function destroy() {
this.root.remove();
}
}, {
key: "hide",
value: function hide() {
this.root.removeClass('data-toolbar-active');
}
}, {
key: "show",
value: function show() {
this.root.addClass('data-toolbar-active');
}
}, {
key: "renderGroup",
value: function renderGroup() {
return $('');
}
}, {
key: "render",
value: function render(container) {
var group = this.renderGroup();
this.root.append(group);
this.addItems(group);
if (container) {
container.append(this.root);
}
this.root.addClass('data-toolbar-block');
return this.root;
}
}, {
key: "update",
value: function update(options) {
this.options = options;
this.root.empty();
var group = this.renderGroup();
this.root.append(group);
this.addItems(group);
}
}]);
return Toolbar;
}();
var USER_BACKGROUND_CLASS = 'ot-user-background';
var USER_CURSOR_CLASS = 'ot-user-cursor';
var USER_CURSOR_CARD_CLASS = 'ot-user-cursor-card';
var USER_MASK_CLASS = 'ot-card-mask';
var USER_CURSOR_TRIGGER_CLASS = 'ot-user-cursor-trigger';
var USER_CURSOR_TRIGGER_ACTIVE_CLASS = 'ot-user-cursor-trigger-active';
var BACKGROUND_TO_ELEMNT = new Map();
var CURSOR_TO_ELEMNT = new Map();
var MASK_TO_ELEMNT = new Map();
var RangeColoring = /*#__PURE__*/function () {
function RangeColoring(engine) {
_classCallCheck(this, RangeColoring);
this.engine = void 0;
this.root = void 0;
this.hideCursorInfoTimeoutMap = void 0;
this.engine = engine;
this.root = engine.root;
this.hideCursorInfoTimeoutMap = {};
}
_createClass(RangeColoring, [{
key: "destroy",
value: function destroy() {
var _iterator = _createForOfIteratorHelper(BACKGROUND_TO_ELEMNT),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
key = _step$value[0],
child = _step$value[1];
child.remove();
BACKGROUND_TO_ELEMNT.delete(key);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var _iterator2 = _createForOfIteratorHelper(CURSOR_TO_ELEMNT),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _step2$value = _slicedToArray(_step2.value, 2),
_key = _step2$value[0],
_child = _step2$value[1];
_child.remove();
CURSOR_TO_ELEMNT.delete(_key);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
var _iterator3 = _createForOfIteratorHelper(MASK_TO_ELEMNT),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var _step3$value = _slicedToArray(_step3.value, 2),
_key2 = _step3$value[0],
_child2 = _step3$value[1];
_child2.remove();
MASK_TO_ELEMNT.delete(_key2);
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
}
}, {
key: "getRectWithRange",
value: function getRectWithRange(node, range) {
var _node$get;
var rangeReact = range.getClientRect();
var react = (_node$get = node.get()) === null || _node$get === void 0 ? void 0 : _node$get.getBoundingClientRect();
return new DOMRect(rangeReact.left - ((react === null || react === void 0 ? void 0 : react.left) || 0), rangeReact.top - ((react === null || react === void 0 ? void 0 : react.top) || 0), rangeReact.right - rangeReact.left, rangeReact.bottom - rangeReact.top);
}
}, {
key: "isWrapByRange",
value: function isWrapByRange(range) {
var clientReact = range.cloneRange().collapse(true).getClientRect();
var clientReact1 = range.cloneRange().collapse(false).getClientRect();
return clientReact.bottom !== clientReact1.bottom;
}
}, {
key: "drawSubRang",
value: function drawSubRang(node, canvas, range, style) {
var startOffset = range.startOffset,
startNode = range.startNode,
endNode = range.endNode;
var start = range.startOffset;
var endOffset = range.endOffset;
var startTop = range.getClientRect().top;
var drawOffset = startOffset;
while (start < endOffset) {
range.setStart(range.commonAncestorContainer, start);
range.setEnd(range.commonAncestorContainer, start + 1);
var curRect = range.getClientRect();
if (curRect.top > startTop || start === endOffset - 1) {
range.setStart(range.commonAncestorContainer, drawOffset);
drawOffset = start;
startTop = curRect.top;
var rect = this.getRectWithRange(node, range);
canvas.clearRect(rect);
canvas.drawRect(_objectSpread2(_objectSpread2({}, rect.toJSON()), style));
}
start++;
}
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
}
}, {
key: "drawBackground",
value: function drawBackground(range, options) {
var _this$engine$scrollNo,
_containerElement$get,
_cardInfo,
_this = this;
var card = this.engine.card;
var uuid = options.uuid,
color = options.color;
var targetCanvas;
var child = BACKGROUND_TO_ELEMNT.get(uuid);
var containerElement = (_this$engine$scrollNo = this.engine.scrollNode) !== null && _this$engine$scrollNo !== void 0 ? _this$engine$scrollNo : this.root;
var clear = function clear() {
if (child && child.length > 0) {
child.attributes(DATA_COLOR, color.toString());
var canvas = child[0]['__canvas'];
if (!child[0]['__clear']) {
canvas.clear();
child[0]['__clear'] = true;
}
return canvas;
}
};
if (range.collapsed) {
clear();
return [range];
}
if (child && child.length > 0) {
targetCanvas = clear();
} else {
child = $(""));
containerElement.append(child);
BACKGROUND_TO_ELEMNT.set(uuid, child);
targetCanvas = new TinyCanvas({
container: child.get()
});
child[0]['__canvas'] = targetCanvas;
}
child.get().style.cssText = 'position: absolute; top: 0; left: 0; transform: translateX(0) translateY(0); will-change: transform; pointer-events: none;';
child[0]['__range'] = range.cloneRange();
var parentWidth = ((_containerElement$get = containerElement.get()) === null || _containerElement$get === void 0 ? void 0 : _containerElement$get.clientWidth) || containerElement.width();
var parentHeight = this.root.height();
targetCanvas.resize(parentWidth, parentHeight);
child[0]['__clear'] = false;
var cardInfo = card.find(range.commonAncestorNode, true); //如果是卡片,并且选区不在内容模块中,而是在卡片两侧的光标位置处,就不算作卡片
if (cardInfo && !cardInfo.isCenter(range.commonAncestorNode)) {
cardInfo = undefined;
}
var tinyColor = colord.colord(color);
var rgb = tinyColor.alpha(0.3).toRgbString();
var fill = {
fill: rgb
};
var subRanges = range.getSubRanges();
if (((_cardInfo = cardInfo) === null || _cardInfo === void 0 ? void 0 : _cardInfo.isEditable) && cardInfo.drawBackground) {
var result = cardInfo.drawBackground(child, range, targetCanvas);
if (result === false) return [range];
if (!!result) {
if (Array.isArray(result)) subRanges = result;else {
if (result.x < 0) {
targetCanvas.resize(parentWidth - result.x, parentHeight);
child.css('transform', "translateX(".concat(result.x, "px) translateY(0)"));
result.x = 0;
}
targetCanvas.clearRect(result);
targetCanvas.drawRect(_objectSpread2(_objectSpread2({}, result.toJSON()), fill));
return [range];
}
}
} else if (cardInfo) {
return [range];
}
subRanges.forEach(function (subRange) {
if (_this.isWrapByRange(subRange)) {
_this.drawSubRang(child, targetCanvas, subRange, fill);
} else {
var rect = _this.getRectWithRange(child, subRange);
targetCanvas.clearRect(rect);
targetCanvas.drawRect(Object.assign({}, rect.toJSON(), fill));
}
});
return subRanges;
}
}, {
key: "getNodeRect",
value: function getNodeRect(node, rect) {
var _parent$first;
//自定义列表项的第一个card跳过
var parent = node.parent();
if (node.isCard() && (parent === null || parent === void 0 ? void 0 : parent.hasClass(this.engine.list.CUSTOMZIE_LI_CLASS)) && (parent === null || parent === void 0 ? void 0 : (_parent$first = parent.first()) === null || _parent$first === void 0 ? void 0 : _parent$first.equal(node)) && node.next()) {
node = node.next();
}
if (node.isElement()) {
rect = node.get().getBoundingClientRect();
}
if (node.isText()) {
var range = Range.create(this.engine).cloneRange();
range.select(node, true);
rect = range.getClientRect();
}
return rect;
}
}, {
key: "getCursorRect",
value: function getCursorRect(selector) {
var _this$root$get, _node$get2;
var leftSpace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var parentRect = ((_this$root$get = this.root.get()) === null || _this$root$get === void 0 ? void 0 : _this$root$get.getBoundingClientRect()) || {
top: 0,
left: 0
};
if (isRangeInterface(selector)) {
var range = selector;
var startNode = range.startNode;
range.shrinkToElementNode();
var _rect = range.getClientRect();
if (startNode.isElement() && _rect.height === 0) {
var childNode = $(startNode[0].childNodes[range.startOffset]);
if (childNode && childNode.length > 0) {
_rect = this.getNodeRect(childNode, _rect);
} else {
childNode = startNode.first();
if (childNode && childNode.length > 0) {
_rect = this.getNodeRect(childNode, _rect);
}
}
}
var _top = _rect.top - (parentRect.top || 0);
var _left = _rect.left - (parentRect.left || 0) - leftSpace;
var height = _rect.height;
return {
top: _top + 'px',
left: _left + 'px',
height: height > 0 ? height + 'px' : -1,
elementHeight: _rect.height || 0
};
}
var node = selector;
var outlineWidth = removeUnit(node.css('outline-width'));
var rect = ((_node$get2 = node.get()) === null || _node$get2 === void 0 ? void 0 : _node$get2.getBoundingClientRect()) || {
top: 0,
left: 0,
height: 0
};
var top = rect.top - parentRect.top - 1;
var left = rect.left - parentRect.left;
if (outlineWidth) {
top -= outlineWidth + 1;
left -= 2;
}
return {
left: left + 'px',
top: top + 'px',
height: 0,
elementHeight: rect.height || 0
};
}
}, {
key: "setCursorRect",
value: function setCursorRect(uuid, node, rect) {
var element = node.get();
if (!element) return;
if (-1 !== rect.height) {
element.style.cssText += "top: 0; left: 0; height: ".concat(rect.height, "; transform: translateX(").concat(rect.left, ") translateY(").concat(rect.top, "); will-change: transform, height;");
if (0 === rect.height) {
node.addClass(USER_CURSOR_CARD_CLASS);
return;
}
node.removeClass(USER_CURSOR_CARD_CLASS);
} else {
node.remove();
CURSOR_TO_ELEMNT.delete(uuid);
}
}
}, {
key: "showCursorInfo",
value: function showCursorInfo(node, member) {
var uuid = member.uuid,
color = member.color;
if (this.hideCursorInfoTimeoutMap[uuid]) {
clearTimeout(this.hideCursorInfoTimeoutMap[uuid]);
}
var trigger = node.find(".".concat(USER_CURSOR_TRIGGER_CLASS));
var bgColor = node.css('background-color');
node.attributes('data-old-background-color', bgColor);
trigger.addClass("".concat(USER_CURSOR_TRIGGER_ACTIVE_CLASS));
node.css('background-color', color);
trigger.css('background-color', color);
}
}, {
key: "hideCursorInfo",
value: function hideCursorInfo(node) {
var trigger = node.find(".".concat(USER_CURSOR_TRIGGER_CLASS));
var bgColor = node.attributes('data-old-background-color');
trigger.removeClass("".concat(USER_CURSOR_TRIGGER_ACTIVE_CLASS));
node.css('background-color', bgColor);
trigger.css('background-color', bgColor);
}
}, {
key: "drawCursor",
value: function drawCursor(selector, member, showInfo) {
var _this2 = this;
var uuid = member.uuid,
name = member.name,
color = member.color;
var cursorRect = this.getCursorRect(selector);
var childCursor = CURSOR_TO_ELEMNT.get(uuid);
if (childCursor && childCursor.length > 0) {
this.setCursorRect(uuid, childCursor, cursorRect);
} else {
var userCursor = "\n \n
").concat(escape(name || ''), "
\n
");
childCursor = $(userCursor);
CURSOR_TO_ELEMNT.set(uuid, childCursor);
var trigger = childCursor.find(".".concat(USER_CURSOR_TRIGGER_CLASS));
if (cursorRect.elementHeight === 0) {
// 刚加载获取不到高度,就定时循环获取,获取次数超过50次就不再获取
var count = 0;
var getRect = function getRect() {
count++;
cursorRect = _this2.getCursorRect(selector);
if (cursorRect.elementHeight < 20 && count <= 50) {
setTimeout(function () {
getRect();
}, 20);
} else {
_this2.setCursorRect(uuid, childCursor, cursorRect);
}
};
getRect();
} else {
this.setCursorRect(uuid, childCursor, cursorRect);
}
childCursor.on('mouseenter', function () {
return _this2.showCursorInfo(childCursor, member);
});
var transitionState = true;
childCursor.on('transitionstart', function () {
transitionState = false;
});
childCursor.on('transitionend', function () {
transitionState = true;
});
childCursor.on('mouseleave', function () {
if (transitionState) {
_this2.hideCursorInfo(childCursor);
}
});
childCursor.css('background-color', color);
trigger.css('background-color', color);
this.root.append(childCursor);
}
if (childCursor && childCursor[0]) {
childCursor.css('z-index', ''); // 如果当前有最大化的卡片,并且要画的光标不在最大化卡片内就隐藏这个光标
var maximizeCard = this.engine.card.components.find(function (component) {
return component.isMaximize;
});
if (maximizeCard) {
var card = this.engine.card.closest(isRangeInterface(selector) ? selector.startNode : selector, true);
if (!card || !maximizeCard.root.equal(card)) {
childCursor.css('z-index', 120);
}
}
childCursor[0]['__target'] = isRangeInterface(selector) ? selector.toPath(true) : selector;
if (showInfo === false) return childCursor;
this.showCursorInfo(childCursor, member);
if (this.hideCursorInfoTimeoutMap[uuid]) {
clearTimeout(this.hideCursorInfoTimeoutMap[uuid]);
}
this.hideCursorInfoTimeoutMap[uuid] = setTimeout(function () {
_this2.hideCursorInfo(childCursor);
}, 2000);
return childCursor;
}
return;
}
}, {
key: "drawCard",
value: function drawCard(node, cursor, member) {
var _this$root$get2,
_node$get3,
_this3 = this;
var language = this.engine.language;
var parentRect = ((_this$root$get2 = this.root.get()) === null || _this$root$get2 === void 0 ? void 0 : _this$root$get2.getBoundingClientRect()) || {
left: 0,
top: 0,
width: 0,
height: 0
};
var nodeRect = ((_node$get3 = node.get()) === null || _node$get3 === void 0 ? void 0 : _node$get3.getBoundingClientRect()) || {
left: 0,
top: 0,
width: 0,
height: 0
};
var cssText = "top: 0; left: 0; transform: translateX(".concat(nodeRect.left - parentRect.left, "px) translateY(").concat(nodeRect.top - parentRect.top, "px); will-change: transform;");
var mask = MASK_TO_ELEMNT.get(member.uuid);
if (mask && mask.length > 0) {
mask[0]['__node'] = node[0];
mask.get().style.cssText = cssText;
return;
}
mask = $(""));
MASK_TO_ELEMNT.set(member.uuid, mask);
mask[0]['__node'] = node[0];
if (nodeRect.height === 0) {
// 刚加载获取不到高度,就定时循环获取,获取次数超过50次就不再获取
var count = 0;
var getRect = function getRect() {
var _node$get4;
count++;
nodeRect = ((_node$get4 = node.get()) === null || _node$get4 === void 0 ? void 0 : _node$get4.getBoundingClientRect()) || {
left: 0,
top: 0,
width: 0,
height: 0
};
if (nodeRect.height < 20 && count <= 50) {
setTimeout(function () {
getRect();
}, 20);
} else if (mask && mask.length > 0) {
mask.get().style.cssText = cssText + "height: ".concat(nodeRect.height, "px; width: ").concat(nodeRect.width, "px;");
}
};
getRect();
} else {
mask.get().style.cssText = cssText + "height: ".concat(nodeRect.height, "px; width: ").concat(nodeRect.width, "px;");
}
mask.on('mouseenter', function () {
_this3.showCursorInfo(cursor, member);
if (mask && mask.length > 0) Tooltip.show(mask, language.get('card', 'lockAlert').toString(), {
placement: 'bottomLeft'
});
});
mask.on('mousemove', function (event) {
var tooltipElement = $("div[".concat(DATA_ELEMENT, "=tooltip]"));
var tooltip = tooltipElement.get();
if (tooltip) tooltip.style.cssText = "left: 0; top: 0; transform: translateX(".concat(event.pageX - 16, "px) translateY(").concat(event.pageY + 32, "px); will-change: transform;");
});
mask.on('mouseleave', function () {
_this3.hideCursorInfo(cursor);
Tooltip.hide();
});
mask.on('click', function (event) {
event.preventDefault();
event.stopPropagation();
});
mask.on('mousedown', function (event) {
event.preventDefault();
event.stopPropagation();
});
this.root.append(mask);
}
}, {
key: "setCardSelectedByOther",
value: function setCardSelectedByOther(card, member) {
var _ref = member || {},
uuid = _ref.uuid,
color = _ref.color;
if (color) {
var tinyColor = colord.colord(color);
var rgb = tinyColor.alpha(0.3).toRgbString();
var customNode;
if (!card.selectedByOther) {
customNode = card.onSelectByOther(true, {
color: color,
rgb: rgb
});
}
card.selectedByOther = uuid;
return customNode;
}
if (card.selectedByOther) {
card.onSelectByOther(false);
}
card.selectedByOther = false;
}
}, {
key: "setCardActivatedByOther",
value: function setCardActivatedByOther(card, member) {
if (card.isEditable) return;
var _ref2 = member || {},
uuid = _ref2.uuid,
color = _ref2.color;
if (color) {
var tinyColor = colord.colord(color);
var rgb = tinyColor.alpha(0.3).toRgbString();
var customNode;
if (!card.activatedByOther) {
customNode = card.onActivateByOther(true, {
color: color,
rgb: rgb
});
}
card.activatedByOther = uuid;
return customNode;
}
if (card.activatedByOther) {
card.onActivateByOther(false);
}
card.activatedByOther = false;
}
}, {
key: "drawRange",
value: function drawRange(range, member, showInfo) {
var _this4 = this;
var card = this.engine.card;
var uuid = member.uuid;
var _range = range,
commonAncestorNode = _range.commonAncestorNode;
var cardInfo = card.find(commonAncestorNode); //如果是卡片,并且选区不在内容模块中,而是在卡片两侧的光标位置处,就不算作卡片
if (cardInfo && !cardInfo.isCenter(commonAncestorNode)) {
cardInfo = undefined;
} // 移除类似表格类的遮罩层
var removeCardMasks = [];
card.each(function (cardComponent) {
if (cardComponent.isEditable) return;
if (!cardInfo || !cardComponent.root.equal(cardInfo.root)) {
if (cardComponent.activatedByOther === uuid) {
_this4.setCardActivatedByOther(cardComponent);
}
removeCardMasks.push(uuid);
}
});
if (removeCardMasks.length > 0) {
for (var i = 0; i < removeCardMasks.length; i++) {
var _uuid = removeCardMasks[i];
var child = MASK_TO_ELEMNT.get(_uuid);
child === null || child === void 0 ? void 0 : child.remove();
MASK_TO_ELEMNT.delete(_uuid);
}
Tooltip.hide();
} // 不是可编辑卡片
if (cardInfo && !cardInfo.isEditable) {
var _CURSOR_TO_ELEMNT$get;
var root = this.setCardActivatedByOther(cardInfo, member) || cardInfo.root;
(_CURSOR_TO_ELEMNT$get = CURSOR_TO_ELEMNT.get(uuid)) === null || _CURSOR_TO_ELEMNT$get === void 0 ? void 0 : _CURSOR_TO_ELEMNT$get.remove();
CURSOR_TO_ELEMNT.delete(uuid);
var collab = cardInfo.constructor.collab;
if (collab === undefined || collab === true) {
var cursor = this.drawCursor(root, member, showInfo);
if (cursor) this.drawCard(root, cursor, member);
this.drawBackground(range, member);
}
} else {
//可编辑卡片
if (cardInfo) {
var _CURSOR_TO_ELEMNT$get2;
this.drawBackground(range, member);
(_CURSOR_TO_ELEMNT$get2 = CURSOR_TO_ELEMNT.get(uuid)) === null || _CURSOR_TO_ELEMNT$get2 === void 0 ? void 0 : _CURSOR_TO_ELEMNT$get2.remove();
CURSOR_TO_ELEMNT.delete(uuid);
return;
} // 循环卡片设置选中或者非选中效果
card.each(function (cardComponent) {
var centerNode = cardComponent.getCenter();
if (centerNode && centerNode.length > 0) {
if (cardComponent.isEditable) {
if (centerNode.contains(range.startNode) && centerNode.contains(range.endNode) && (range.startNode.closest(EDITABLE_SELECTOR).length > 0 || range.endNode.closest(EDITABLE_SELECTOR).length > 0)) {
_this4.setCardSelectedByOther(cardComponent);
return;
}
}
if (range.isPointInRange(centerNode.get(), 0)) {
_this4.setCardSelectedByOther(cardComponent, member);
} else if (cardComponent.selectedByOther === uuid) {
_this4.setCardSelectedByOther(cardComponent);
}
}
});
var singleCard = card.getSingleSelectedCard(range);
if (singleCard) {
if (singleCard.isEditable) {
var center = singleCard.getCenter();
if (center.contains(range.startNode) && center.contains(range.endNode) && (range.startNode.closest(EDITABLE_SELECTOR).length > 0 || range.endNode.closest(EDITABLE_SELECTOR).length > 0)) {
return;
}
}
var _root = this.setCardSelectedByOther(singleCard, member) || singleCard.root;
this.drawCursor(_root, member, showInfo);
} else {
range.shrinkToElementNode();
var ranges = this.drawBackground(range, member);
if (!range.collapsed) {
ranges.forEach(function (sub) {
if (!sub.collapsed) {
range = sub;
}
});
range.shrinkToElementNode();
range.collapse(false);
}
this.drawCursor(range, member, showInfo);
}
}
}
}, {
key: "updateBackgroundPosition",
value: function updateBackgroundPosition() {
var _iterator4 = _createForOfIteratorHelper(BACKGROUND_TO_ELEMNT.values()),
_step4;
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var node = _step4.value;
var child = node.get();
if (!child) continue;
var range = child['__range'];
var uuid = node.attributes(DATA_UUID);
var color = node.attributes(DATA_COLOR);
this.drawBackground(range, {
uuid: uuid,
color: color
});
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
}
}, {
key: "updateCursorPosition",
value: function updateCursorPosition() {
var _iterator5 = _createForOfIteratorHelper(CURSOR_TO_ELEMNT),
_step5;
try {
for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
var _step5$value = _slicedToArray(_step5.value, 2),
key = _step5$value[0],
node = _step5$value[1];
var child = node.get();
if (!child || !(child instanceof HTMLElement)) continue;
var target = child['__target'];
if (!target) {
node.remove();
CURSOR_TO_ELEMNT.delete(key);
return;
} // range
if (!target.name) target = Range.fromPath(this.engine, target, true);
if (target.startContainer || target.length > 0 && target[0].isConnected) {
var rect = this.getCursorRect(target);
this.setCursorRect(key, node, rect);
} else {
node.remove();
CURSOR_TO_ELEMNT.delete(key);
}
}
} catch (err) {
_iterator5.e(err);
} finally {
_iterator5.f();
}
}
}, {
key: "updateCardPosition",
value: function updateCardPosition() {
var _this$root$get3;
var parentRect = ((_this$root$get3 = this.root.get()) === null || _this$root$get3 === void 0 ? void 0 : _this$root$get3.getBoundingClientRect()) || {
left: 0,
top: 0
};
var _iterator6 = _createForOfIteratorHelper(MASK_TO_ELEMNT),
_step6;
try {
for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
var _step6$value = _slicedToArray(_step6.value, 2),
key = _step6$value[0],
node = _step6$value[1];
var child = node.get();
if (!child || !(child instanceof HTMLElement)) continue;
var target = child['__node'];
if (target === null || target === void 0 ? void 0 : target.isConnected) {
var rect = target.getBoundingClientRect();
child.style.left = rect.left - parentRect.left + 'px';
child.style.top = rect.top - parentRect.top + 'px';
} else {
var _ref3, _child$parentElement;
(_ref3 = (_child$parentElement = child.parentElement) !== null && _child$parentElement !== void 0 ? _child$parentElement : child.parentNode) === null || _ref3 === void 0 ? void 0 : _ref3.removeChild(child);
MASK_TO_ELEMNT.delete(key);
}
}
} catch (err) {
_iterator6.e(err);
} finally {
_iterator6.f();
}
}
}, {
key: "updatePosition",
value: function updatePosition() {
this.updateBackgroundPosition();
this.updateCursorPosition();
this.updateCardPosition();
}
}, {
key: "updateBackgroundAlpha",
value: function updateBackgroundAlpha(range) {
var cursorRect = this.getCursorRect(range);
var _iterator7 = _createForOfIteratorHelper(CURSOR_TO_ELEMNT.values()),
_step7;
try {
for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
var node = _step7.value;
var child = node.get();
if (!child || !(child instanceof HTMLElement)) continue;
var trigger = child.querySelector(".".concat(USER_CURSOR_TRIGGER_CLASS));
var left = child.style.left;
var top = child.style.top;
var bgColor = colord.colord(child.style.backgroundColor);
if (cursorRect.left === left && cursorRect.top === top) {
bgColor.alpha(0.3);
} else {
bgColor.alpha(1);
}
var bgs = bgColor.toRgbString();
child.style.backgroundColor = bgs;
if (trigger) trigger.style.backgroundColor = bgs;
}
} catch (err) {
_iterator7.e(err);
} finally {
_iterator7.f();
}
}
}, {
key: "render",
value: function render(attribute, member, showInfo) {
var path = attribute.path,
uuid = attribute.uuid,
active = attribute.active;
if (path) {
var range = Range.fromPath(this.engine, path, true);
this.drawRange(range, member, active || showInfo);
} else {
this.remove(uuid);
}
}
}, {
key: "remove",
value: function remove(uuid) {
var _ref4,
_this$engine$scrollNo2,
_this$engine$scrollNo3,
_this5 = this;
(_ref4 = (_this$engine$scrollNo2 = (_this$engine$scrollNo3 = this.engine.scrollNode) === null || _this$engine$scrollNo3 === void 0 ? void 0 : _this$engine$scrollNo3.get()) !== null && _this$engine$scrollNo2 !== void 0 ? _this$engine$scrollNo2 : this.root.get()) === null || _ref4 === void 0 ? void 0 : _ref4.querySelectorAll("[".concat(DATA_UUID, "=\"").concat(uuid, "\"]")).forEach(function (dataElement) {
var _ref5, _dataElement$parentEl;
if (dataElement.classList.contains(USER_MASK_CLASS)) {
var target = dataElement['__node'];
var component = target ? _this5.engine.card.find(target) : null;
if (component && !component.isEditable && component.activatedByOther === uuid) {
// 取消锁定
_this5.setCardActivatedByOther(component);
}
}
(_ref5 = (_dataElement$parentEl = dataElement.parentElement) !== null && _dataElement$parentEl !== void 0 ? _dataElement$parentEl : dataElement.parentNode) === null || _ref5 === void 0 ? void 0 : _ref5.removeChild(dataElement);
});
this.engine.card.each(function (component) {
if (component.isEditable || component.selectedByOther !== uuid) return; // 取消锁定
_this5.setCardSelectedByOther(component);
});
}
}]);
return RangeColoring;
}();
var FLUSHING$1 = new WeakMap();
var ModelSelection = /*#__PURE__*/function (_EventEmitter) {
_inherits(ModelSelection, _EventEmitter);
var _super = _createSuper(ModelSelection);
function ModelSelection(engine) {
var _this;
_classCallCheck(this, ModelSelection);
_this = _super.call(this);
_this.engine = void 0;
_this.rangeColoring = void 0;
_this.currentRangePath = void 0;
_this.data = new Map();
_this.member = void 0;
_this.handleResize = function () {
_this.rangeColoring.updatePosition();
};
_this.handleScroll = function (node) {
var _this$engine$containe;
var children = (_this$engine$containe = _this.engine.container.get()) === null || _this$engine$containe === void 0 ? void 0 : _this$engine$containe.childNodes;
if (!children) return;
var _iterator = _createForOfIteratorHelper(_this.data),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _this$member$getCurre, _attr$path;
var _step$value = _slicedToArray(_step.value, 2),
key = _step$value[0],
attr = _step$value[1];
if (key === ((_this$member$getCurre = _this.member.getCurrent()) === null || _this$member$getCurre === void 0 ? void 0 : _this$member$getCurre.uuid)) continue;
if ((_attr$path = attr.path) === null || _attr$path === void 0 ? void 0 : _attr$path.start.id) {
var startOffset = attr.path.start.path[0];
var child = children.item(startOffset);
if (child && node.equal(child)) {
_this.rangeColoring.updatePosition();
break;
}
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
};
_this.handleMouseDown = function () {
var container = _this.engine.container;
container.off('mouseup', _this.handleMouseUp);
container.off('mousemove', _this.emitSelectChange);
container.on('mouseup', _this.handleMouseUp);
container.on('mousemove', _this.emitSelectChange);
};
_this.mouseUpTimeout = null;
_this.handleMouseUp = function () {
var container = _this.engine.container;
container.off('mouseup', _this.handleMouseUp);
container.off('mousemove', _this.emitSelectChange);
if (_this.mouseUpTimeout) clearTimeout(_this.mouseUpTimeout);
_this.mouseUpTimeout = setTimeout(function () {
_this.emitSelectChange();
}, 10);
};
_this.observer = null;
_this.emitSelectChange = function () {
var _this$observer;
var refreshBG = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (_this.engine.change.isComposing()) return;
var current = _this.engine.change.range.get();
(_this$observer = _this.observer) === null || _this$observer === void 0 ? void 0 : _this$observer.disconnect();
var card = _this.engine.card.find(current.commonAncestorContainer, true);
if (card === null || card === void 0 ? void 0 : card.getSelectionNodes) {
var newRange = _this.getCardResizeRange(card);
if (newRange) {
current = newRange.cloneRange();
_this.observer = new ResizeObserver(function () {
newRange = _this.getCardResizeRange(card);
if (newRange) {
_this.onSelectionChange(newRange, true, refreshBG);
} else {
var _this$observer2;
(_this$observer2 = _this.observer) === null || _this$observer2 === void 0 ? void 0 : _this$observer2.disconnect();
}
});
_this.observer.observe(card.root.get());
}
}
if (!current.commonAncestorNode.isRoot() && !current.commonAncestorNode.inEditor()) {
var _current = _this.member.getCurrent();
if (_current) _this.removeAttirbute(_current.uuid);
} else {
_this.onSelectionChange(current, true, refreshBG, false);
}
};
_this.engine = engine;
_this.member = CollaborationMember.fromEngine(engine);
_this.rangeColoring = new RangeColoring(engine);
engine.container.on('keyup', _this.emitSelectChange);
engine.container.on('mousedown', _this.handleMouseDown);
engine.on('scroll', _this.handleScroll, {
passive: true
});
window.addEventListener('resize', _this.handleResize, {
passive: true
});
return _this;
}
_createClass(ModelSelection, [{
key: "getCardResizeRange",
value: function getCardResizeRange(card) {
if (card === null || card === void 0 ? void 0 : card.getSelectionNodes) {
var nodes = card.getSelectionNodes();
if (nodes.length > 0) {
var _end$get;
var range = Range.create(this.engine);
range.setStart(nodes[0], 0);
var end = nodes[nodes.length - 1];
range.setEnd(end, end.isText() ? end.text().length : ((_end$get = end.get()) === null || _end$get === void 0 ? void 0 : _end$get.childNodes.length) || 0);
return range;
}
}
return null;
}
}, {
key: "setAttribute",
value: function setAttribute(attr, member) {
var _this2 = this;
var refreshBG = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var showInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var item = this.data.get(attr.uuid);
if (attr.force || !isEqual__default['default'](item || {}, attr)) {
this.data.set(attr.uuid, Object.assign({}, attr, {
active: !item
}));
var current = this.member.getCurrent();
if (attr.uuid === (current === null || current === void 0 ? void 0 : current.uuid)) {
if (!FLUSHING$1.get(this.engine)) {
FLUSHING$1.set(this.engine, true);
Promise.resolve().then(function () {
FLUSHING$1.set(_this2.engine, false);
if (refreshBG === true) _this2.rangeColoring.updatePosition();
_this2.emit('change', attr);
});
}
} else {
this.rangeColoring.render(attr, member, showInfo);
}
}
}
}, {
key: "removeAttirbute",
value: function removeAttirbute(uuid) {
if (!this.data.has(uuid)) return;
this.data.delete(uuid);
var current = this.member.getCurrent();
if (uuid === (current === null || current === void 0 ? void 0 : current.uuid)) this.emit('change', {
uuid: uuid,
remove: true
});else this.rangeColoring.remove(uuid);
}
}, {
key: "getAttribute",
value: function getAttribute(uuid) {
return this.data.get(uuid);
}
}, {
key: "onSelectionChange",
value: function onSelectionChange(range) {
var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var refreshBG = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var showInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var currentMember = this.member.getCurrent();
if (!currentMember) return;
var card = this.engine.card;
range = range.cloneRange();
var activeCard = card.active;
if (activeCard && !activeCard.isEditable) {
var center = activeCard.getCenter();
if (isTransientElementCache(activeCard.root)) {
var prev = activeCard.root.prev();
if (prev) {
range.select(prev, true).collapse(false);
} else {
range.setStartBefore(activeCard.root);
range.collapse(true);
}
} else if (center && center.length > 0) {
range.select(center.get(), true);
}
}
if (!activeCard && !range.collapsed) {
var startCard = this.engine.card.find(range.startNode, true);
if (startCard && startCard.type === exports.CardType.BLOCK) {
range.setStart(startCard.getCenter().parent(), 1);
}
var endCard = this.engine.card.find(range.endNode, true);
if (endCard && endCard.type === exports.CardType.BLOCK) {
range.setEnd(endCard.getCenter().parent(), 1);
}
} // 显示协作信息时包含左右光标位置
var path = range.toPath(true); // 用作历史记录的不包含卡片左右光标位置
this.currentRangePath = range.toPath();
var current = this.getAttribute(currentMember.uuid);
this.setAttribute(Object.assign({}, current, {
path: path,
uuid: currentMember.uuid,
force: force
}), currentMember, refreshBG, showInfo);
this.rangeColoring.updateBackgroundAlpha(range);
}
}, {
key: "refreshAttributes",
value: function refreshAttributes() {
var _this3 = this;
for (var _len = arguments.length, members = new Array(_len), _key = 0; _key < _len; _key++) {
members[_key] = arguments[_key];
}
members.forEach(function (member) {
var attr = _this3.getAttribute(member.uuid);
if (attr) {
_this3.rangeColoring.render(attr, member);
}
});
}
}, {
key: "destroy",
value: function destroy() {
var container = this.engine.container;
container.off('mouseup', this.handleMouseUp);
container.off('mousemove', this.emitSelectChange);
container.off('keyup', this.emitSelectChange);
container.off('mousedown', this.handleMouseDown);
this.engine.off('scroll', this.handleScroll);
window.removeEventListener('resize', this.handleResize);
}
}]);
return ModelSelection;
}(EventEmitter2.EventEmitter2);
var css_248z$3 = ".ot-user-cursor {\r\n\tposition: absolute;\r\n\tz-index: 125;\r\n\twidth: 2px;\r\n}\r\n\r\n.ot-user-cursor-trigger {\r\n\tposition: absolute;\r\n\ttop: -5px;\r\n\tleft: -2px;\r\n\tborder-radius: 100%;\r\n\tcolor: #ffffff;\r\n\twidth: 6px;\r\n\theight: 6px;\r\n\tfont-size: 0;\r\n\toverflow: hidden;\r\n\ttransition: all 0.1s linear;\r\n}\r\n\r\n.ot-user-cursor-trigger-active {\r\n\ttop: -17px;\r\n\tborder-radius: 2px;\r\n\tcolor: #ffffff;\r\n\tfont-size: 10px;\r\n\tline-height: 18px;\r\n\theight: 18px;\r\n\twidth: auto;\r\n\tpadding: 0 3px;\r\n\twhite-space: nowrap;\r\n}\r\n\r\n.ot-card-mask {\r\n\tposition: absolute;\r\n\tz-index: 10;\r\n\tbackground: transparent;\r\n\tcursor: not-allowed;\r\n}\r\n\r\n.ot-user-background {\r\n z-index: 120;\r\n}\r\n\r\n.ot-user-cursor-card {\r\n\tposition: absolute;\r\n}\r\n\r\n.ot-user-cursor-card .ot-user-cursor-trigger {\r\n\tdisplay: none;\r\n}\r\n\r\n.ot-user-cursor-card .ot-user-cursor-trigger-active {\r\n\tposition: absolute;\r\n\tdisplay: block;\r\n\ttop: -19px;\r\n\tleft: 0;\r\n\tborder-radius: 2px;\r\n\tcolor: #ffffff;\r\n\tfont-size: 10px;\r\n\tline-height: 18px;\r\n\theight: 18px;\r\n\twidth: auto;\r\n\tpadding: 0 3px;\r\n\twhite-space: nowrap;\r\n}";
styleInject(css_248z$3);
var getSideText = function getSideText(engine, node, offset) {
var idNode = engine.block.closest(node);
if (idNode.length > 0) {
var id = idNode.attributes(DATA_ID);
var leftRange = Range.create(engine);
var rightRange = Range.create(engine);
leftRange.setStart(idNode[0], 0);
leftRange.setEnd(node[0], offset);
rightRange.setStart(node[0], offset);
rightRange.setEnd(idNode[0], idNode[0].childNodes.length);
return {
id: id,
leftText: leftRange.toString(),
rightText: rightRange.toString()
};
}
return;
};
var getRangeRemotePath = function getRangeRemotePath(engine) {
try {
var _window$getSelection;
if (((_window$getSelection = window.getSelection()) === null || _window$getSelection === void 0 ? void 0 : _window$getSelection.rangeCount) === 0) return;
var range = Range.from(engine);
if (!range || range.inCard()) return;
if (range.startNode.isRoot()) range.shrinkToElementNode();
var startNode = range.startNode,
startOffset = range.startOffset,
endNode = range.endNode,
endOffset = range.endOffset;
return {
start: getSideText(engine, startNode, startOffset),
end: getSideText(engine, endNode, endOffset)
};
} catch (error) {
engine.messageError('apply-remote-path', error);
return;
}
};
var fromRemoteAttr = function fromRemoteAttr(engine, attr) {
var _engine$container$get;
if (!attr) return;
var id = attr.id,
leftText = attr.leftText,
rightText = attr.rightText;
var node = (_engine$container$get = engine.container.get()) === null || _engine$container$get === void 0 ? void 0 : _engine$container$get.querySelector("[".concat(DATA_ID, "=\"").concat(id, "\"]"));
if (!node) return;
var text = node.textContent || '';
if (text === '') return {
container: node,
offset: 0
};
if (text === null || text === void 0 ? void 0 : text.startsWith(leftText)) {
var _nextChild = node.firstChild;
var _offset = leftText.length;
while (_nextChild && (_nextChild.nodeType !== 3 || (((_nextChild$textConten = _nextChild.textContent) === null || _nextChild$textConten === void 0 ? void 0 : _nextChild$textConten.length) || 0) < _offset)) {
var _nextChild$textConten, _nextChild$textConten2;
if ((((_nextChild$textConten2 = _nextChild.textContent) === null || _nextChild$textConten2 === void 0 ? void 0 : _nextChild$textConten2.length) || 0) < _offset) {
var _nextChild$textConten3;
_offset -= ((_nextChild$textConten3 = _nextChild.textContent) === null || _nextChild$textConten3 === void 0 ? void 0 : _nextChild$textConten3.length) || 0;
_nextChild = _nextChild.nextSibling;
} else {
_nextChild = _nextChild.firstChild;
}
}
return {
container: _nextChild,
offset: _offset
};
}
if (text === null || text === void 0 ? void 0 : text.endsWith(rightText)) {
var _prevChild2, _prevChild2$textConte;
var _offset2 = rightText.length;
var prevChild = node.lastChild;
while (prevChild && (prevChild.nodeType !== 3 || (((_prevChild$textConten = prevChild.textContent) === null || _prevChild$textConten === void 0 ? void 0 : _prevChild$textConten.length) || 0) < _offset2)) {
var _prevChild$textConten, _prevChild$textConten2;
if (((_prevChild$textConten2 = prevChild.textContent) === null || _prevChild$textConten2 === void 0 ? void 0 : _prevChild$textConten2.length) || 0 < _offset2) {
var _prevChild, _prevChild$textConten3;
_offset2 -= ((_prevChild = prevChild) === null || _prevChild === void 0 ? void 0 : (_prevChild$textConten3 = _prevChild.textContent) === null || _prevChild$textConten3 === void 0 ? void 0 : _prevChild$textConten3.length) || 0;
prevChild = prevChild.previousSibling;
} else {
prevChild = prevChild.lastChild;
}
}
return {
container: prevChild,
offset: ((_prevChild2 = prevChild) === null || _prevChild2 === void 0 ? void 0 : (_prevChild2$textConte = _prevChild2.textContent) === null || _prevChild2$textConte === void 0 ? void 0 : _prevChild2$textConte.length) || 0 - _offset2
};
}
var offset = 0;
while (text[offset] === leftText[offset]) {
offset++;
}
var nextChild = node.firstChild;
while (nextChild && (nextChild.nodeType !== 3 || (((_nextChild$textConten4 = nextChild.textContent) === null || _nextChild$textConten4 === void 0 ? void 0 : _nextChild$textConten4.length) || 0) < offset)) {
var _nextChild$textConten4, _nextChild$textConten5;
if (((_nextChild$textConten5 = nextChild.textContent) === null || _nextChild$textConten5 === void 0 ? void 0 : _nextChild$textConten5.length) || 0 < offset) {
var _nextChild$textConten6;
offset -= ((_nextChild$textConten6 = nextChild.textContent) === null || _nextChild$textConten6 === void 0 ? void 0 : _nextChild$textConten6.length) || 0;
nextChild = nextChild.nextSibling;
} else {
nextChild = nextChild.firstChild;
}
}
return {
container: nextChild,
offset: offset
};
};
var applyRangeByRemotePath = function applyRangeByRemotePath(engine, path, callback) {
try {
var _Range$from;
var selection = window.getSelection();
var range = selection ? (_Range$from = Range.from(engine, selection)) === null || _Range$from === void 0 ? void 0 : _Range$from.cloneRange() : undefined;
if (!range) return;
var start = path.start,
end = path.end;
var startInfo;
var endInfo;
if (start) startInfo = fromRemoteAttr(engine, start);
if (end) endInfo = fromRemoteAttr(engine, end);
if (startInfo && startInfo.container) {
range.setStart(startInfo.container, startInfo.offset);
}
if (endInfo && endInfo.container) {
range.setEnd(endInfo.container, endInfo.offset);
}
engine.change.range.select(range, false);
callback === null || callback === void 0 ? void 0 : callback();
} catch (error) {
engine.messageError('apply-remote-path', error);
}
};
var toHTML = function toHTML(node) {
if (Text$1.isText(node)) {
var text = node.text;
return unescape(text).replace(/\u00a0/g, ' ').replace(/\u200b/g, '');
} else if (Element$1.isElement(node)) {
var type = node.type,
children = node.children;
var element = "<".concat(type);
for (var _i = 0, _Object$entries = Object.entries(node); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
key = _Object$entries$_i[0],
value = _Object$entries$_i[1];
if (key === 'type' || key === 'children') continue;
element += " ".concat(key, "=\"").concat(escape(value), "\"");
}
var isVoid = Node$1.isVoid(node);
element += isVoid ? '' : '>';
var _iterator = _createForOfIteratorHelper(children),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
element += toHTML(child);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
element += isVoid ? ' />' : "".concat(type, ">");
return element.replace(/\u200b/g, '');
}
throw new Error('Cannot convert node to value');
};
var toCardValue = function toCardValue(node) {
var type = node[CARD_TYPE_KEY];
if (!type) return '';
var attributes = _defineProperty({
type: type,
value: node[CARD_VALUE_KEY],
name: (node[CARD_KEY] || node[READY_CARD_KEY]).toLowerCase(),
editable: node[CARD_EDITABLE_KEY]
}, DATA_ID, node[DATA_ID]); //其它 data 属性
for (var attrName in node) {
if (attrName !== READY_CARD_KEY && attrName.indexOf('data-') === 0 && attrName.indexOf('data-card') !== 0) {
attributes[attrName] = node[attrName];
}
}
var card = '';
return card;
};
var toValue = function toValue(node, filter) {
if (Text$1.isText(node)) {
var text = node.text;
return unescape(text).replace(/\u00a0/g, ' ').replace(/\u200b/g, '');
} else if (Element$1.isElement(node)) {
var type = node.type,
children = node.children;
if (filter && filter(node) === false) return '';
var isCard = node[CARD_KEY];
if (isCard) return toCardValue(node);
var element = "<".concat(type);
for (var _i = 0, _Object$entries = Object.entries(node); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
key = _Object$entries$_i[0],
value = _Object$entries$_i[1];
if (key === 'type' || key === 'children') continue;
element += " ".concat(key, "=\"").concat(escape(value), "\"");
}
if (Node$1.isVoid(node)) {
return element + ' />';
}
element += '>';
var _iterator = _createForOfIteratorHelper(children),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
element += toValue(child);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
element += "".concat(type, ">");
return element;
}
throw new Error('Cannot convert node to value');
};
var getListType = function getListType(type, indent) {
if (type === 'ol') {
if (indent % 3 === 1) return 'lower-alpha';
if (indent % 3 === 2) return 'lower-roman';
return 'decimal';
} else {
if (indent % 3 === 1) return 'circle';
if (indent % 3 === 2) return 'square';
return 'disc';
}
};
var getIndent = function getIndent(node) {
var dataIndent = node['data-indent'];
if (!dataIndent) {
var style = node['style'];
if (!style) return 0;
var match = style.match(/text-indent: (\d+)(px|em|rem);/);
if (!match) return 0;
dataIndent = match[1];
}
var indent = dataIndent ? parseInt(dataIndent) : 0;
return indent;
};
var toIndent = function toIndent(node) {
var indent = getIndent(node);
return ' '.repeat(indent * 2);
};
var listToText = function listToText(node) {
var start = node['start'];
var classz = node['class'];
if (classz && classz.includes('data-list-task')) return elementToText(node);
var indent = getIndent(node);
var style = getListType(node.type, indent);
var space = toIndent(node);
var typeText = toIndent(node);
var isOrder = node.type === 'ol';
var index = start ? parseInt(start) : 1;
if (!isOrder) {
typeText = "".concat(getListStyle(style), " ");
}
var text = '';
node.children.forEach(function (child, _index) {
if (Element$1.isElement(child)) {
if (child.type === 'li') {
if (isOrder) {
typeText = "".concat(getListStyle(style, index + _index), ". ");
}
text += space + typeText + elementToText(child);
} else {
text += space + elementToText(child);
}
} else {
text += toText(child);
}
});
return text;
};
var elementToText = function elementToText(node) {
var intoCard = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var children = node.children;
var text = toIndent(node);
var hasBlock = !Node$1.isBlock(node) || children.length === 0;
if (node[CARD_KEY] === 'checkbox') {
var value = decodeCardValue(node[CARD_VALUE_KEY]);
var checked = value.checked;
return checked ? '✅' : '🔲';
}
if (intoCard || !node[CARD_KEY] || node[CARD_EDITABLE_KEY] === 'true') {
var _iterator = _createForOfIteratorHelper(children),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
text += toText(child);
if (!hasBlock && Element$1.isElement(child)) {
if (child.type === 'br' || Node$1.isBlock(child)) hasBlock = true;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
return text + (hasBlock ? '' : '\n');
};
var toText = function toText(node) {
var intoCard = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (Text$1.isText(node)) {
var text = node.text;
return unescape(text).replace(/\u00a0/g, ' ').replace(/\u200b/g, '');
} else if (Element$1.isElement(node)) {
var type = node.type;
if (type === 'br') return '\n';
if (type === 'ol' || type === 'ul') {
return listToText(node);
}
return elementToText(node, intoCard);
}
throw new Error('Cannot convert node to text');
};
var ENGINE_TO_MODEL = new WeakMap();
var FLUSHING$2 = new WeakMap();
var createModel = function createModel(engine, root) {
var ee = new EventEmitter2__default['default']();
var history = engine.history,
change = engine.change;
var mutation = Mutation.from(engine);
mutation.onChange(function (records) {
var cloneRoot = cloneDeep__default['default'](engine.model.root);
var operations = Operation.transform(engine, records);
if (operations.length === 0) return;
ee.emit('change', operations, cloneRoot);
history.handleSelfOps(operations.filter(function (op) {
if (op.undoable === true && op.type === 'set_node' && !!op.newProperties[CARD_VALUE_KEY]) {
history.handleNLCardValue(op);
}
return !op.undoable && (op.type !== 'set_node' || !op.newProperties[READY_CARD_KEY]);
}));
engine.trigger('operations', operations);
if (operations.find(function (op) {
return op.type === 'set_node' && op.newProperties[CARD_VALUE_KEY];
})) {
change.change(false);
}
});
if (!engine.readonly) mutation.start();
var selection = new ModelSelection(engine);
selection.on('change', function (attr) {
ee.emit('selection-change', attr);
});
var member = CollaborationMember.fromEngine(engine);
var applyOperations = function applyOperations(operations) {
var applyNodes = [];
var _iterator = _createForOfIteratorHelper(operations),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var operation = _step.value;
var applyNode = applyToDOM(engine, operation, false);
if (applyNode && applyNode.length > 0) {
applyNodes.push(applyNode);
}
if (operation.type === 'insert_node' || operation.type === 'remove_node') {
var path = operation.path,
node = operation.node;
var parent = Node$1.get(model.root, path.slice(0, path.length - 1));
if (Element$1.isElement(parent)) {
var isInsert = operation.type === 'insert_node';
var index = path[path.length - 1];
if (isInsert) parent.children.splice(index, 0, node);else parent.children.splice(index, 1);
if (isInsert && applyNode && applyNode.length > 0) {
(function () {
var setDOM = function setDOM(node, parent, index, domNode) {
Node$1.setDOM(node, domNode, engine.schema);
Path.setPath(node, parent, index);
if (Element$1.isElement(node)) {
for (var i = 0; i < node.children.length; i++) {
var child = node.children[i];
var _findDOMByPath = findDOMByPath(engine, domNode, [i], false),
dom = _findDOMByPath.node;
setDOM(child, node, i, dom);
}
}
};
setDOM(node, parent, index, applyNode[0]);
})();
}
for (var i = path[path.length - 1]; i < parent.children.length; i++) {
var child = parent.children[i];
Path.setPath(child, parent, i);
}
}
} else if (operation.type === 'set_node') {
var _path = operation.path,
properties = operation.properties,
newProperties = operation.newProperties;
var _node = Node$1.get(model.root, _path);
if (_node) {
for (var key in properties) {
delete _node[key];
}
for (var _key in newProperties) {
_node[_key] = newProperties[_key];
}
}
} else if (operation.type === 'insert_text' || operation.type === 'remove_text') {
var _path2 = operation.path,
offset = operation.offset,
text = operation.text;
var _node2 = Node$1.get(model.root, _path2);
if (Text$1.isText(_node2)) {
if (operation.type === 'insert_text') {
_node2.text = _node2.text.slice(0, offset) + text + _node2.text.slice(offset);
} else {
_node2.text = _node2.text.slice(0, offset) + _node2.text.slice(offset + text.length);
}
}
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return applyNodes;
};
var model = {
root: root,
mutation: mutation,
selection: selection,
member: member,
resetRoot: function resetRoot() {
var root = Node$1.createFromDOM(engine.container[0], engine.schema);
if (Element$1.isElement(root)) model.root = root;
},
onChange: function onChange(fn) {
ee.on('change', fn);
},
offChange: function offChange(fn) {
ee.off('change', fn);
},
emitChange: function emitChange(operations) {
ee.emit('change', operations, cloneDeep__default['default'](engine.model.root));
},
onSelectionChange: function onSelectionChange(fn) {
ee.on('selection-change', fn);
},
offSelectionChange: function offSelectionChange(fn) {
ee.off('selection-change', fn);
},
findNode: function findNode(path) {
var node = model.root;
var _iterator2 = _createForOfIteratorHelper(path),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var p = _step2.value;
if (!Element$1.isElement(node)) return undefined;
node = node.children[p];
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return node;
},
apply: function apply(operations) {
var applyNodes = applyOperations(operations);
engine.change.change(false, applyNodes);
return applyNodes;
},
applyRemote: function applyRemote(operations) {
mutation.stop();
var path = getRangeRemotePath(engine);
var applyNodes = applyOperations(operations);
Promise.resolve().then(function () {
mutation.start();
});
if (path && engine.isFocus()) applyRangeByRemotePath(engine, path, selection.emitSelectChange);
engine.change.change(true, applyNodes);
return applyNodes;
},
drawCursor: function drawCursor(attributes) {
if (!FLUSHING$2.get(engine)) {
FLUSHING$2.set(engine, true);
Promise.resolve().then(function () {
FLUSHING$2.set(engine, false);
if (!Array.isArray(attributes)) attributes = [attributes];
var current = member.getCurrent();
var members = member.getMembers();
attributes.forEach(function (attribute) {
if (current && attribute.uuid === current.uuid) return;
var member = members.find(function (m) {
return m.uuid === attribute.uuid;
});
if ('remove' in attribute || !member) selection.removeAttirbute(attribute.uuid);else {
selection.setAttribute(attribute, member);
}
});
});
}
},
toDOM: function toDOM$1(node) {
return toDOM(node !== null && node !== void 0 ? node : model.root);
},
toHTML: function toHTML$1(node) {
var html = !node ? toHTML(model.root) : toHTML(node);
var element = $(html);
if (!node) {
var style = engine.container.css();
element.css(style);
}
engine.trigger('parse:html-before', element);
engine.trigger('parse:html', element);
engine.trigger('parse:html-after', element);
return element.html().replace(/\u200b/g, '');
},
toValue: function toValue$1(node) {
var filter = function filter(node) {
return engine.trigger('parse:node', node);
};
if (!node) return model.root.children.map(function (child) {
return toValue(child, filter);
}).join('');
return toValue(node, filter);
},
toValueAsync: function toValueAsync(node, callback) {
return new Promise( /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(resolve, reject) {
var _loop, pluginName, _ret;
return _regeneratorRuntime().wrap(function _callee$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop(pluginName) {
var plugin, result;
return _regeneratorRuntime().wrap(function _loop$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
plugin = engine.plugin.components[pluginName];
_context.next = 3;
return new Promise(function (resolve) {
if (plugin.waiting) {
plugin.waiting(callback).then(function () {
return resolve(true);
}).catch(resolve);
} else resolve(true);
});
case 3:
result = _context.sent;
if (!(_typeof(result) === 'object')) {
_context.next = 7;
break;
}
reject(result);
return _context.abrupt("return", {
v: void 0
});
case 7:
case "end":
return _context.stop();
}
}
}, _loop);
});
_context2.t0 = _regeneratorRuntime().keys(engine.plugin.components);
case 2:
if ((_context2.t1 = _context2.t0()).done) {
_context2.next = 10;
break;
}
pluginName = _context2.t1.value;
return _context2.delegateYield(_loop(pluginName), "t2", 5);
case 5:
_ret = _context2.t2;
if (!(_typeof(_ret) === "object")) {
_context2.next = 8;
break;
}
return _context2.abrupt("return", _ret.v);
case 8:
_context2.next = 2;
break;
case 10:
resolve(model.toValue(node));
case 11:
case "end":
return _context2.stop();
}
}
}, _callee);
}));
return function (_x, _x2) {
return _ref.apply(this, arguments);
};
}());
},
toText: function toText$1(node, intoCard) {
if (!node) return model.root.children.map(function (child) {
return toText(child, intoCard);
}).join('');
return toText(node, intoCard);
},
destroy: function destroy() {
mutation.destroy();
selection.destroy();
ENGINE_TO_MODEL.delete(engine);
}
};
return model;
};
var Model = {
from: function from(engine) {
var root = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
type: 'div',
children: []
};
var model = ENGINE_TO_MODEL.get(engine);
if (!model) {
model = createModel(engine, root);
ENGINE_TO_MODEL.set(engine, model);
}
return model;
},
destroy: function destroy(engine) {
var model = ENGINE_TO_MODEL.get(engine);
model === null || model === void 0 ? void 0 : model.destroy();
}
};
var setRangeByPath = function setRangeByPath(engine, path) {
if (path) {
var start = path.start,
end = path.end;
if (start && end) {
var beginOffset = start.path[start.path.length - 1];
var endOffset = end.path[end.path.length - 1];
var startClone = start.path.slice();
var endClone = end.path.slice();
startClone.pop();
endClone.pop();
var container = engine.container,
change = engine.change;
var startChild = container.getChildByPath(startClone, function (child) {
return !isTransientElementCache($(child));
});
if (!startChild) return;
var endChild = container.getChildByPath(endClone, function (child) {
return !isTransientElementCache($(child));
});
if (!endChild) return;
var getMaxOffset = function getMaxOffset(node, offset) {
if (node.nodeType === getDocument().TEXT_NODE) {
var text = node.textContent || '';
return text.length < offset ? text.length : offset;
} else {
var childNodes = node.childNodes;
return childNodes.length < offset ? childNodes.length : offset;
}
};
try {
var range = change.range.get();
if (startChild.nodeName === 'BR' || engine.node.isVoid(startChild)) {
range.select(startChild).collapse(false);
} else {
range.setStart(startChild, getMaxOffset(startChild, beginOffset));
range.setEnd(endChild, getMaxOffset(endChild, endOffset));
}
if (!range.collapsed) {
var startCard = engine.card.find(range.startNode, true);
var endCard = engine.card.find(range.endNode, true);
if (startCard && endCard && (startCard === null || startCard === void 0 ? void 0 : startCard.root.equal(endCard.root))) {
var startEditableElement = range.startNode.closest(EDITABLE_SELECTOR);
if (startEditableElement.length === 0) startEditableElement = range.startNode.find(EDITABLE_SELECTOR);
var endEditableElement = range.endNode.closest(EDITABLE_SELECTOR);
if (endEditableElement.length === 0) endEditableElement = range.endNode.find(EDITABLE_SELECTOR);
if (startEditableElement.length > 0 && endEditableElement.length > 0 && !startEditableElement.equal(endEditableElement)) {
range.collapse(true);
}
}
}
change.range.select(range);
range.scrollRangeIntoView();
} catch (error) {
engine.messageError('history setRangeByPath', error);
}
}
}
};
/**
* 历史记录管理器
*/
var _selfWaiting = /*#__PURE__*/_classPrivateFieldLooseKey("selfWaiting");
var HistoryModel = /*#__PURE__*/function () {
// 所有操作片段
// 引擎实例
// 当前还未保存的所有操作
// 当前操作的索引
// 监听的所有过滤事件
// 监听的所有收集本地操作的事件
// 等待监听收集本地操作的回调
function HistoryModel(engine) {
var _this = this;
_classCallCheck(this, HistoryModel);
this.actionOps = [];
this.engine = void 0;
this.currentAction = {
ops: []
};
this.currentActionIndex = 0;
this.filterEvents = [];
this.selfEvents = [];
Object.defineProperty(this, _selfWaiting, {
writable: true,
value: void 0
});
this.lazySave = debounce__default['default'](function () {
_this.saveOp();
}, 200);
this.handlePath = function (path, id, bi) {
var isOp = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var filter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : function (node) {
return !isTransientElementCache($(node));
};
var targetElement = _this.engine.container.find("[".concat(DATA_ID, "=\"").concat(id, "\"]"));
if (targetElement.length > 0 && targetElement.inEditor()) {
var _targetElement$parent;
var newPath = targetElement.getPath(_this.engine.container, ((_targetElement$parent = targetElement.parent()) === null || _targetElement$parent === void 0 ? void 0 : _targetElement$parent.isRoot()) ? undefined : filter);
return (isOp ? newPath.map(function (p) {
return p + 2;
}) : newPath).concat(path.slice(bi));
}
return path;
};
this.engine = engine;
}
_createClass(HistoryModel, [{
key: "resetCurrentAction",
value: function resetCurrentAction() {
this.currentAction = {
ops: []
};
}
/**
* 懒保存当前操作
*/
}, {
key: "reset",
value:
/**
* 重置所有操作
*/
function reset() {
this.actionOps = [];
this.currentActionIndex = 0;
}
/**
* 监听过滤事件
* @param filter 事件
*/
}, {
key: "onFilter",
value: function onFilter(filter) {
this.filterEvents.push(filter);
}
/**
* 监听收集本地操作事件
* @param event 事件
*/
}, {
key: "onSelf",
value: function onSelf(event) {
this.selfEvents.push(event);
}
/**
* 是否有撤销操作
* @returns boolean
*/
}, {
key: "hasUndo",
value: function hasUndo() {
return !!this.getUndoOp();
}
/**
* 是否有重做操作
* @returns boolean
*/
}, {
key: "hasRedo",
value: function hasRedo() {
return !!this.getRedoOp();
}
/**
* 执行撤销操作
*/
}, {
key: "undo",
value: function undo() {
this.saveOp();
var undoOp = this.getUndoOp();
if (undoOp) {
var isUndo = false;
var engine = this.engine;
var change = engine.change;
var model = engine.model;
model.mutation.stop();
try {
model.emitChange(undoOp.ops);
model.apply(undoOp.ops);
this.currentActionIndex--;
isUndo = true;
} catch (error) {
this.reset();
engine.messageError('history-undo', error);
}
if (engine.isEmpty()) change.initValue();
if (isUndo) {
//清除操作前记录的range
change.getRangePathBeforeCommand();
if (undoOp.startRangePath) setRangeByPath(engine, undoOp.startRangePath);
change.change();
engine.trigger('undo');
}
Promise.resolve().then(function () {
model.mutation.start();
});
}
}
/**
* 执行重做操作
*/
}, {
key: "redo",
value: function redo() {
this.saveOp();
var redoOp = this.getRedoOp();
if (redoOp) {
var isRedo = false;
var engine = this.engine;
var change = engine.change;
var model = engine.model;
try {
model.mutation.stop();
model.emitChange(redoOp.ops);
model.apply(redoOp.ops);
this.currentActionIndex++;
isRedo = true;
} catch (error) {
this.reset();
engine.messageError('history-redo', error);
}
if (isRedo) {
// 清除操作前记录的range
change.getRangePathBeforeCommand();
if (redoOp.rangePath) setRangeByPath(this.engine, redoOp.rangePath);
change.change();
engine.trigger('redo');
}
Promise.resolve().then(function () {
model.mutation.start();
});
}
}
/**
* 清空所有历史操作
*/
}, {
key: "clear",
value: function clear() {
var _this2 = this;
setTimeout(function () {
_this2.reset();
}, 10);
}
}, {
key: "saveOp",
value: function saveOp() {
if (this.currentAction && this.currentAction.ops && this.currentAction.ops.length > 0) {
if (this.currentAction.self) {
this.currentAction.rangePath = this.getCurrentRangePath();
this.currentAction.id = random(8);
this.actionOps.splice(this.currentActionIndex);
this.actionOps.push(this.currentAction);
this.currentActionIndex = this.actionOps.length;
this.engine.trigger('historyChange');
}
this.resetCurrentAction(); // 保存成功后清除操作前记录的range
this.engine.change.getRangePathBeforeCommand();
}
}
}, {
key: "handleSelfOps",
value: function handleSelfOps(ops) {
var _this$currentAction,
_this3 = this;
if (!((_this$currentAction = this.currentAction) === null || _this$currentAction === void 0 ? void 0 : _this$currentAction.self)) this.saveOp();
var isSave = false;
ops.forEach(function (op) {
isSave = true;
if (_this3.filterEvents.some(function (filter) {
return filter(op);
})) {
var _this3$actionOps$ops;
if (_this3.actionOps.length > 0 && !op.undoable) (_this3$actionOps$ops = _this3.actionOps[_this3.actionOps.length - 1].ops) === null || _this3$actionOps$ops === void 0 ? void 0 : _this3$actionOps$ops.push(op);
} else {
_this3.currentAction.self = true;
if (!_this3.currentAction.ops) _this3.currentAction.ops = [];
if (!_this3.currentAction.startRangePath) {
_this3.currentAction.startRangePath = _this3.getRangePathBeforeCommand();
}
var lastOp = _this3.currentAction.ops[_this3.currentAction.ops.length - 1];
if (lastOp && Operation.isReverse(op, lastOp)) {
_this3.currentAction.ops.pop();
} else {
_this3.currentAction.ops.push(op);
}
}
}); // 监听收集
if (isSave) {
var callback = undefined;
this.selfEvents.some(function (event) {
callback = event(ops);
return callback !== undefined;
}); // 还有等待处理的
if (_classPrivateFieldLooseBase(this, _selfWaiting)[_selfWaiting]) return;
if (typeof callback === 'boolean') {
if (callback) this.saveOp();else {
this.resetCurrentAction();
}
} else if (_typeof(callback) === 'object') {
_classPrivateFieldLooseBase(this, _selfWaiting)[_selfWaiting] = callback;
callback.then(function (s) {
if (s) {
_this3.saveOp();
} else {
_this3.resetCurrentAction();
}
}).finally(function () {
return _classPrivateFieldLooseBase(_this3, _selfWaiting)[_selfWaiting] = undefined;
});
} else if (callback === undefined) {
this.lazySave();
}
}
}
}, {
key: "handleNLCardValue",
value: function handleNLCardValue(op) {
if (op.undoable === true && op.type === 'set_node') {
var newProperties = op.newProperties;
var value = newProperties[CARD_VALUE_KEY];
if (!value) return;
var newValue = decodeCardValue(value);
this.actionOps.forEach(function (action) {
action.ops.forEach(function (op) {
if (op.type === 'set_node') {
var _newProperties = op.newProperties;
var _value = _newProperties[CARD_VALUE_KEY];
var oldValue = decodeCardValue(_value);
if (newValue.id === oldValue.id) {
_newProperties[CARD_VALUE_KEY] = newValue;
}
} else if (op.type === 'insert_node') {
var node = op.node;
var _value2 = node[CARD_VALUE_KEY];
if (!_value2) return;
var _oldValue = decodeCardValue(_value2);
if (newValue.id === _oldValue.id) {
node[CARD_VALUE_KEY] = newValue;
}
}
});
});
}
}
}, {
key: "handleRemoteOps",
value: function handleRemoteOps(ops) {
var _this4 = this;
if (this.currentAction.self && !_classPrivateFieldLooseBase(this, _selfWaiting)[_selfWaiting]) this.saveOp();
var range = this.engine.change.range.get();
this.actionOps.forEach(function (action) {
if (action.rangePath) {
var _action$rangePath = action.rangePath,
start = _action$rangePath.start,
end = _action$rangePath.end;
if (start.id && start.bi !== undefined) {
start.path = _this4.handlePath(start.path, start.id, start.bi, false, range.filterPath(true));
}
if (end.id && end.bi !== undefined) {
end.path = _this4.handlePath(end.path, end.id, end.bi, false, range.filterPath(true));
}
}
if (action.startRangePath) {
var _action$startRangePat = action.startRangePath,
_start = _action$startRangePat.start,
_end = _action$startRangePat.end;
if (_start.id && _start.bi !== undefined) {
_start.path = _this4.handlePath(_start.path, _start.id, _start.bi, false, range.filterPath(true));
}
if (_end.id && _end.bi !== undefined) {
_end.path = _this4.handlePath(_end.path, _end.id, _end.bi, false, range.filterPath(true));
}
}
});
ops.forEach(function (op) {
if (!_this4.currentAction.ops) {
_this4.currentAction.ops = [];
}
var lastOp = _this4.currentAction.ops[_this4.currentAction.ops.length - 1];
if (lastOp && Operation.isReverse(op, lastOp)) {
_this4.currentAction.ops.pop();
} else {
_this4.currentAction.ops.push(op);
}
_this4.actionOps.some(function (action, index) {
var _action$ops;
var affect = (_action$ops = action.ops) === null || _action$ops === void 0 ? void 0 : _action$ops.some(function (actionOp) {
return Operation.canOpAffectPath(op, actionOp.path);
});
if (affect) {
// this.actionOps.splice(index, this.actionOps.length - index)
var removeArray = [action];
var _loop = function _loop(i) {
var _nextAction$ops;
var nextAction = _this4.actionOps[i];
var nextAffect = (_nextAction$ops = nextAction.ops) === null || _nextAction$ops === void 0 ? void 0 : _nextAction$ops.some(function (actionOp) {
var _action$ops2;
return (_action$ops2 = action.ops) === null || _action$ops2 === void 0 ? void 0 : _action$ops2.some(function (aop) {
return Operation.canOpAffectPath(actionOp, aop.path);
});
});
if (nextAffect) {
var _nextAction2$ops;
removeArray.push(nextAction);
var j = i + 1;
var nextAction2 = _this4.actionOps[j];
if (nextAction2 && ((_nextAction2$ops = nextAction2.ops) === null || _nextAction2$ops === void 0 ? void 0 : _nextAction2$ops.some(function (actionOp) {
var _nextAction$ops2;
return (_nextAction$ops2 = nextAction.ops) === null || _nextAction$ops2 === void 0 ? void 0 : _nextAction$ops2.some(function (aop) {
return Operation.canOpAffectPath(actionOp, aop.path);
});
}))) {
removeArray.push(nextAction2);
}
}
};
for (var i = index + 1; i < _this4.actionOps.length; i++) {
_loop(i);
}
var newActionOps = _this4.actionOps.filter(function (aop) {
return removeArray.find(function (raop) {
return raop.id === aop.id;
}) === undefined;
});
_this4.actionOps = newActionOps;
_this4.currentActionIndex = _this4.actionOps.length;
return affect;
}
return false;
});
});
}
}, {
key: "getUndoOp",
value: function getUndoOp() {
var prevIndex = this.currentActionIndex - 1;
if (this.actionOps[prevIndex]) {
var prevOp = cloneDeep__default['default'](this.actionOps[prevIndex]);
var opIndex = findLastIndex__default['default'](this.actionOps, function (op) {
return op.id == prevOp.id;
});
if (opIndex !== -1) prevOp = this.actionOps[opIndex];else opIndex = prevIndex;
var invertOps = prevOp.ops.map(function (op) {
return Operation.inverse(op);
}).reverse();
try {
return {
self: true,
ops: invertOps,
id: prevOp.id,
type: 'undo',
rangePath: prevOp.rangePath,
startRangePath: prevOp.startRangePath
};
} catch (error) {
this.engine.messageError('history-undo-op', error);
}
}
return;
}
}, {
key: "getRedoOp",
value: function getRedoOp() {
var currentIndex = this.currentActionIndex;
if (this.actionOps[currentIndex]) {
var currentOp = cloneDeep__default['default'](this.actionOps[currentIndex]);
var invertOps = [];
if (currentOp.type === 'undo') {
invertOps = currentOp.ops.map(function (op) {
return Operation.inverse(op);
}).reverse();
} else {
invertOps = currentOp.ops;
}
try {
return {
self: true,
ops: invertOps,
id: currentOp.id,
type: 'redo',
rangePath: currentOp.rangePath,
startRangePath: currentOp.startRangePath
};
} catch (error) {
this.engine.messageError('history-redo-op', error);
}
}
return;
}
}, {
key: "getCurrentRangePath",
value: function getCurrentRangePath() {
var _this$engine = this.engine,
model = _this$engine.model,
change = _this$engine.change;
var currentPath = model.selection.currentRangePath;
return currentPath ? currentPath : change.range.get().toPath();
}
}, {
key: "getRangePathBeforeCommand",
value: function getRangePathBeforeCommand() {
return this.engine.change.getRangePathBeforeCommand() || this.getCurrentRangePath();
}
}]);
return HistoryModel;
}();
/**
* 快捷键管理器
* @class Hotkey
*/
var Hotkey = /*#__PURE__*/function () {
function Hotkey(engine) {
var _this = this;
_classCallCheck(this, Hotkey);
this.engine = void 0;
this.disabled = false;
this.engine = engine; //绑定事件
this.engine.container.on('keydown', function (event) {
return _this.trigger(event);
});
}
_createClass(Hotkey, [{
key: "match",
value: function match(e) {
var _this2 = this;
//遍历插件
Object.keys(this.engine.plugin.components).every(function (name) {
var plugin = _this2.engine.plugin.components[name]; //插件实现了热键方法
if (plugin.hotkey) {
var result = plugin.hotkey(e);
var isCommand = false;
var commandArgs = []; //返回热键字符串,并且匹配当前按下的键
if (typeof result === 'string' && isHotkey__default['default'](result, e)) {
isCommand = true;
} //返回多个热键
else if (Array.isArray(result)) {
//遍历热键
result.some(function (item) {
if (typeof item === 'string') {
if (isHotkey__default['default'](item, e)) {
isCommand = true;
commandArgs = [];
return true;
}
} else {
var key = item.key,
args = item.args;
if (isHotkey__default['default'](key, e)) {
isCommand = true;
commandArgs = Array.isArray(args) ? args : [args];
return true;
}
}
return false;
});
} //返回类型是对象,带执行命令参数
else if (_typeof(result) === 'object' && isHotkey__default['default'](result.key, e)) {
isCommand = true; //参数以数组传递
commandArgs = Array.isArray(result.args) ? result.args : [result.args];
} //有匹配到热键,执行命令
if (isCommand) {
var _this2$engine$command;
e.preventDefault();
(_this2$engine$command = _this2.engine.command).execute.apply(_this2$engine$command, [name].concat(_toConsumableArray(commandArgs)));
return false;
}
}
return true;
});
}
/**
* 处理按键按下事件
* @param e 事件
*/
}, {
key: "trigger",
value: function trigger(e) {
//禁用快捷键不处理
if (this.disabled) {
return;
}
this.match(e);
}
/**
* 启用快捷键
*/
}, {
key: "enable",
value: function enable() {
this.disabled = false;
}
/**
* 禁用快捷键
*/
}, {
key: "disable",
value: function disable() {
this.disabled = true;
}
/**
* 销毁快捷键
*/
}, {
key: "destroy",
value: function destroy() {
this.engine.container.off('keydown', this.trigger);
}
}]);
return Hotkey;
}();
var DefaultKeydown = /*#__PURE__*/function () {
function DefaultKeydown(engine) {
_classCallCheck(this, DefaultKeydown);
this.type = 'keydown';
this.hotkey = '';
this.listeners = [];
this.engine = void 0;
this.engine = engine;
}
_createClass(DefaultKeydown, [{
key: "on",
value: function on(listener) {
this.listeners.push(listener);
}
}, {
key: "unshiftOn",
value: function unshiftOn(listener) {
this.listeners.unshift(listener);
}
}, {
key: "off",
value: function off(listener) {
for (var i = 0; i < this.listeners.length; i++) {
if (this.listeners[i] === listener) {
this.listeners.splice(i, 1);
break;
}
}
}
}, {
key: "trigger",
value: function trigger(event) {
for (var i = 0; i < this.listeners.length; i++) {
var listener = this.listeners[i];
var result = listener(event);
if (result === false) break;
}
}
}, {
key: "destroy",
value: function destroy() {
this.listeners = [];
}
}]);
return DefaultKeydown;
}();
var Backspace = /*#__PURE__*/function (_DefaultKeydown) {
_inherits(Backspace, _DefaultKeydown);
var _super = _createSuper(Backspace);
function Backspace() {
var _this;
_classCallCheck(this, Backspace);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.type = 'keydown';
_this.hotkey = 'backspace';
return _this;
}
_createClass(Backspace, [{
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
container = _this$engine.container;
var range = change.range.get();
change.cacheRangeBeforeCommand(); // 编辑器没有内容
if (change.isEmpty()) {
event.preventDefault();
container.empty();
change.initValue();
return;
} // 可编辑卡片多选时清空内容
var commonAncestorNode = range.commonAncestorNode;
var cardComponent = this.engine.card.find(commonAncestorNode, true);
var selectionNodes = (cardComponent === null || cardComponent === void 0 ? void 0 : cardComponent.isEditable) ? (cardComponent === null || cardComponent === void 0 ? void 0 : cardComponent.getSelectionNodes) ? cardComponent.getSelectionNodes() : [] : [];
if (selectionNodes.length > 0) {
selectionNodes.forEach(function (selectionNode) {
selectionNode.html('');
});
change.apply(range.cloneRange().select(selectionNodes[0], true).collapse(true));
return;
} // 处理 BR
var startNode = range.startNode,
startOffset = range.startOffset;
if (startNode.isEditable()) {
var child = startNode[0].childNodes[startOffset - 1];
var lastNode = $(child);
if (lastNode.name === 'br') {
event.preventDefault();
lastNode.remove();
change.apply(range);
return;
}
}
var result = true;
for (var i = 0; i < this.listeners.length; i++) {
var listener = this.listeners[i];
result = listener(event);
if (result === false) break;
}
if (result === false) {
if (this.engine.scrollNode) range.scrollIntoViewIfNeeded(this.engine.container, this.engine.scrollNode);
return;
} // 范围为展开状态
if (!range.collapsed) {
event.preventDefault();
var prev = startNode.prev();
if ((prev === null || prev === void 0 ? void 0 : prev.name) === 'br') {
prev.remove();
}
change.delete(range);
var afterPrev = range.startNode.prev();
if ((afterPrev === null || afterPrev === void 0 ? void 0 : afterPrev.isCard()) && afterPrev.find(CARD_CENTER_SELECTOR).length === 0) {
afterPrev.remove();
}
change.apply(range);
if (this.engine.scrollNode) range.scrollIntoViewIfNeeded(this.engine.container, this.engine.scrollNode);
return;
} else {
var _brNode;
var brNode = undefined;
if (this.engine.node.isBlock(startNode)) {
var _child = startNode[0].childNodes[startOffset - 1];
brNode = $(_child);
} else if (startNode.name === 'br') {
brNode = startNode;
}
if (((_brNode = brNode) === null || _brNode === void 0 ? void 0 : _brNode.name) === 'br') {
var _prev = brNode.prev();
var next = brNode.next();
var n = next === null || next === void 0 ? void 0 : next.next();
var p = _prev === null || _prev === void 0 ? void 0 : _prev.prev(); // abc
if ((_prev === null || _prev === void 0 ? void 0 : _prev.name) !== 'br' && (next === null || next === void 0 ? void 0 : next.name) === 'br' && (n === null || n === void 0 ? void 0 : n.name) !== 'br') {
event.preventDefault();
brNode.remove();
next.remove();
change.apply(range.shrinkToTextNode());
} else if ((next === null || next === void 0 ? void 0 : next.name) !== 'br' && (_prev === null || _prev === void 0 ? void 0 : _prev.name) === 'br' && (p === null || p === void 0 ? void 0 : p.name) !== 'br') {
event.preventDefault();
brNode.remove();
_prev.remove();
change.apply(range.shrinkToTextNode());
}
}
}
}
}]);
return Backspace;
}(DefaultKeydown);
var Delete = /*#__PURE__*/function (_DefaultKeydown) {
_inherits(Delete, _DefaultKeydown);
var _super = _createSuper(Delete);
function Delete() {
var _this;
_classCallCheck(this, Delete);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.type = 'keydown';
_this.hotkey = 'delete';
return _this;
}
_createClass(Delete, [{
key: "getNext",
value: function getNext(node) {
var _node$parentElement;
var parent = (_node$parentElement = node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : node.parentNode;
return $(node).isEditable() ? null : node.nextSibling ? node.nextSibling : parent === null ? null : this.getNext(parent);
}
}, {
key: "getRange",
value: function getRange(node) {
var hasNext = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if ($(node).isEditable()) return null;
if (!hasNext) {
var next = this.getNext(node);
if (!next) return null;
node = next;
}
while (node) {
var nodeDom = $(node);
if (nodeDom.attributes(CARD_KEY)) {
if (!node.ownerDocument) return null;
var range = Range.create(this.engine, node.ownerDocument);
range.setStartAfter(node);
range.collapse(true);
return range;
}
if (this.engine.node.isBlock(nodeDom)) {
if (!node.ownerDocument) return null;
var _range = Range.create(this.engine, node.ownerDocument);
_range.select(nodeDom, true).collapse(true);
return _range;
}
if (nodeDom.name === 'br') {
var _ref, _node$parentElement2;
if (((_ref = (_node$parentElement2 = node.parentElement) !== null && _node$parentElement2 !== void 0 ? _node$parentElement2 : node.parentNode) === null || _ref === void 0 ? void 0 : _ref.childNodes.length) === 1) return null;
if (!node.ownerDocument) return null;
var _range2 = Range.create(this.engine, node.ownerDocument);
_range2.setStartAfter(node);
_range2.collapse(true);
return _range2;
}
if (node.nodeType === Node.TEXT_NODE) {
if (node['data'].length === 0) return this.getRange(node);
if (!node.ownerDocument) return null;
var _range3 = Range.create(this.engine, node.ownerDocument);
_range3.setStart(node, 1);
_range3.collapse(true);
return _range3;
}
if (node.childNodes.length === 0) return this.getRange(node);
node = node.childNodes[0];
}
return null;
}
}, {
key: "trigger",
value: function trigger(event) {
var change = this.engine.change;
change.cacheRangeBeforeCommand();
var range = change.range.get();
if (!range.collapsed) {
event.preventDefault();
change.delete();
return;
}
var card = this.engine.card.find(range.startNode);
var hasNext = false;
var nextNode;
if (card) {
if (card.isLeftCursor(range.startNode)) {
event.preventDefault();
this.engine.card.select(card);
change.delete();
return;
}
if (!card.isRightCursor(range.startNode)) return;
nextNode = card.root[0];
} else if (range.endContainer.nodeType === Node.TEXT_NODE) {
if (range.endContainer['data'].length > range.endOffset) {
event.preventDefault();
var cloneRange = range.cloneRange();
cloneRange.setEnd(range.endContainer, range.endOffset + 1);
change.range.select(cloneRange);
change.delete();
change.range.select(change.range.get().shrinkToTextNode());
return;
}
nextNode = range.endContainer;
} else {
if (range.endContainer.nodeType !== Node.ELEMENT_NODE) return;
if (range.endContainer.childNodes.length === 0) {
nextNode = range.endContainer;
} else if (range.endOffset === 0) {
var _range$endContainer$f;
if (range.endContainer.childNodes.length !== 1 || ((_range$endContainer$f = range.endContainer.firstChild) === null || _range$endContainer$f === void 0 ? void 0 : _range$endContainer$f.nodeName) !== 'BR') {
hasNext = true;
}
nextNode = range.endContainer.childNodes[range.endOffset];
} else {
nextNode = range.endContainer.childNodes[range.endOffset - 1];
}
}
var nodeRange = this.getRange(nextNode, hasNext);
if (nodeRange) {
event.preventDefault();
var startOffset = range.startOffset;
if (startOffset === 1 && range.startContainer.childNodes.length === 1 && range.startContainer.childNodes[0].nodeName === 'BR') startOffset = 0;
nodeRange.setStart(range.startContainer, startOffset);
change.range.select(nodeRange);
change.delete();
}
for (var i = 0; i < this.listeners.length; i++) {
var listener = this.listeners[i];
var result = listener(event);
if (result === false) break;
}
}
}]);
return Delete;
}(DefaultKeydown);
var Enter = /*#__PURE__*/function (_DefaultKeydown) {
_inherits(Enter, _DefaultKeydown);
var _super = _createSuper(Enter);
function Enter() {
var _this;
_classCallCheck(this, Enter);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.type = 'keydown';
_this.hotkey = 'enter';
return _this;
}
_createClass(Enter, [{
key: "trigger",
value: function trigger(event) {
var change = this.engine.change;
change.cacheRangeBeforeCommand();
var range = change.range.get(); // 选区选中最后的节点
var block = this.engine.block.closest(range.endNode); // 无段落
if (block.isEditable()) {
this.engine.block.wrap('');
}
for (var i = 0; i < this.listeners.length; i++) {
var listener = this.listeners[i];
var result = listener(event);
if (result === false) break;
}
if (this.engine.scrollNode) this.engine.change.range.get().scrollIntoViewIfNeeded(this.engine.container, this.engine.scrollNode);
this.engine.trigger('select');
}
}]);
return Enter;
}(DefaultKeydown);
var Tab = /*#__PURE__*/function (_DefaultKeydown) {
_inherits(Tab, _DefaultKeydown);
var _super = _createSuper(Tab);
function Tab() {
var _this;
_classCallCheck(this, Tab);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.type = 'keydown';
_this.hotkey = 'tab';
return _this;
}
_createClass(Tab, [{
key: "trigger",
value: function trigger(event) {
var node = this.engine.node;
event.preventDefault();
node.insertText(' ');
}
}]);
return Tab;
}(DefaultKeydown);
var ShiftTab = /*#__PURE__*/function (_Default) {
_inherits(ShiftTab, _Default);
var _super = _createSuper(ShiftTab);
function ShiftTab() {
var _this;
_classCallCheck(this, ShiftTab);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.hotkey = 'shift+tab';
return _this;
}
return _createClass(ShiftTab);
}(DefaultKeydown);
var ShitEnter = /*#__PURE__*/function (_DefaultKeydown) {
_inherits(ShitEnter, _DefaultKeydown);
var _super = _createSuper(ShitEnter);
function ShitEnter() {
var _this;
_classCallCheck(this, ShitEnter);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.type = 'keydown';
_this.hotkey = 'shift+enter';
return _this;
}
_createClass(ShitEnter, [{
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
inline = _this$engine.inline,
block = _this$engine.block;
event.preventDefault();
change.cacheRangeBeforeCommand();
var range = change.range.get();
if (range.startNode.closest('li').length === 0) {
var _this$engine$typing$g;
(_this$engine$typing$g = this.engine.typing.getHandleListener('enter', 'keydown')) === null || _this$engine$typing$g === void 0 ? void 0 : _this$engine$typing$g.trigger(event);
return;
} else {
var br = $('
');
inline.insert(br, range);
if (block.isLastOffset(range, 'end')) {
var _br$next, _br$prev;
if ((!br.next() || ((_br$next = br.next()) === null || _br$next === void 0 ? void 0 : _br$next.name) !== 'br') && (!br.prev() || ((_br$prev = br.prev()) === null || _br$prev === void 0 ? void 0 : _br$prev.name) !== 'br')) {
var cloneBr = br.clone();
br.after(cloneBr);
range.select(cloneBr).collapse(false);
}
}
}
for (var i = 0; i < this.listeners.length; i++) {
var listener = this.listeners[i];
var result = listener(event);
if (result === false) break;
}
change.apply(range);
if (this.engine.scrollNode) this.engine.change.range.get().scrollIntoViewIfNeeded(this.engine.container, this.engine.scrollNode);
}
}]);
return ShitEnter;
}(DefaultKeydown);
var Space = /*#__PURE__*/function (_Default) {
_inherits(Space, _Default);
var _super = _createSuper(Space);
function Space() {
var _this;
_classCallCheck(this, Space);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.hotkey = function (event) {
return event.key === ' ';
};
return _this;
}
return _createClass(Space);
}(DefaultKeydown);
var Slash = /*#__PURE__*/function (_Default) {
_inherits(Slash, _Default);
var _super = _createSuper(Slash);
function Slash() {
var _this;
_classCallCheck(this, Slash);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.hotkey = function (event) {
return event.key === '/' || isHotkey__default['default']('/', event) || event.keyCode === 229 && event.code === 'Slash';
};
return _this;
}
return _createClass(Slash);
}(DefaultKeydown);
var All = /*#__PURE__*/function (_Default) {
_inherits(All, _Default);
var _super = _createSuper(All);
function All() {
var _this;
_classCallCheck(this, All);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.hotkey = 'mod+a';
return _this;
}
return _createClass(All);
}(DefaultKeydown);
var Left = /*#__PURE__*/function (_Default) {
_inherits(Left, _Default);
var _super = _createSuper(Left);
function Left() {
var _this;
_classCallCheck(this, Left);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.type = 'keydown';
_this.hotkey = function (event) {
return isHotkey__default['default']('left', event) || isHotkey__default['default']('shift+left', event) || isHotkey__default['default']('ctrl+a', event) || isHotkey__default['default']('ctrl+b', event);
};
return _this;
}
return _createClass(Left);
}(DefaultKeydown);
var Right = /*#__PURE__*/function (_DefaultKeydown) {
_inherits(Right, _DefaultKeydown);
var _super = _createSuper(Right);
function Right() {
var _this;
_classCallCheck(this, Right);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.type = 'keydown';
_this.hotkey = function (event) {
return isHotkey__default['default']('right', event) || isHotkey__default['default']('shift+right', event) || isHotkey__default['default']('ctrl+e', event) || isHotkey__default['default']('ctrl+f', event);
};
return _this;
}
return _createClass(Right);
}(DefaultKeydown);
var Up = /*#__PURE__*/function (_Default) {
_inherits(Up, _Default);
var _super = _createSuper(Up);
function Up() {
var _this;
_classCallCheck(this, Up);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.hotkey = function (event) {
return isHotkey__default['default']('up', event) || isHotkey__default['default']('ctrl+p', event);
};
return _this;
}
return _createClass(Up);
}(DefaultKeydown);
var Down = /*#__PURE__*/function (_Default) {
_inherits(Down, _Default);
var _super = _createSuper(Down);
function Down() {
var _this;
_classCallCheck(this, Down);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.hotkey = function (event) {
return isHotkey__default['default']('down', event) || isHotkey__default['default']('ctrl+n', event);
};
return _this;
}
return _createClass(Down);
}(DefaultKeydown);
var defaultHandles = [{
name: 'default',
handle: DefaultKeydown
}, {
name: 'enter',
handle: Enter,
triggerName: 'keydown:enter'
}, {
name: 'backspace',
handle: Backspace,
triggerName: 'keydown:backspace'
}, {
name: 'delete',
handle: Delete,
triggerName: 'keydown:delete'
}, {
name: 'tab',
handle: Tab,
triggerName: 'keydown:tab'
}, {
name: 'shift-tab',
handle: ShiftTab,
triggerName: 'keydown:shift-tab'
}, {
name: 'shift-enter',
handle: ShitEnter,
triggerName: 'keydown:shift-enter'
}, // {
// name: 'at',
// handle: At,
// triggerName: 'keydown:at',
// },
{
name: 'space',
handle: Space,
triggerName: 'keydown:space'
}, {
name: 'slash',
handle: Slash,
triggerName: 'keydown:slash'
}, {
name: 'all',
handle: All,
triggerName: 'keydown:all'
}, {
name: 'left',
handle: Left,
triggerName: 'keydown:left'
}, {
name: 'right',
handle: Right,
triggerName: 'keydown:right'
}, {
name: 'up',
handle: Up,
triggerName: 'keydown:up'
}, {
name: 'down',
handle: Down,
triggerName: 'keydown:down'
}];
var DefaultKeyup = /*#__PURE__*/function (_DefaultKeydown) {
_inherits(DefaultKeyup, _DefaultKeydown);
var _super = _createSuper(DefaultKeyup);
function DefaultKeyup() {
var _this;
_classCallCheck(this, DefaultKeyup);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.type = 'keyup';
return _this;
}
return _createClass(DefaultKeyup);
}(DefaultKeydown);
var Enter$1 = /*#__PURE__*/function (_Default) {
_inherits(Enter, _Default);
var _super = _createSuper(Enter);
function Enter() {
var _this;
_classCallCheck(this, Enter);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.hotkey = 'enter';
return _this;
}
return _createClass(Enter);
}(DefaultKeyup);
var Backspace$1 = /*#__PURE__*/function (_DefaultKeyup) {
_inherits(Backspace, _DefaultKeyup);
var _super = _createSuper(Backspace);
function Backspace() {
var _this;
_classCallCheck(this, Backspace);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.type = 'keyup';
_this.hotkey = 'backspace';
return _this;
}
_createClass(Backspace, [{
key: "trigger",
value: function trigger(event) {
var change = this.engine.change; // 编辑器没有内容
if (change.isEmpty()) {
event.preventDefault();
return;
}
var result = true;
for (var i = 0; i < this.listeners.length; i++) {
var listener = this.listeners[i];
result = listener(event);
if (result === false) break;
}
}
}]);
return Backspace;
}(DefaultKeyup);
var Tab$1 = /*#__PURE__*/function (_Default) {
_inherits(Tab, _Default);
var _super = _createSuper(Tab);
function Tab() {
var _this;
_classCallCheck(this, Tab);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.hotkey = 'tab';
return _this;
}
return _createClass(Tab);
}(DefaultKeyup);
var Space$1 = /*#__PURE__*/function (_Default) {
_inherits(Space, _Default);
var _super = _createSuper(Space);
function Space() {
var _this;
_classCallCheck(this, Space);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.hotkey = function (event) {
return event.key === ' ';
};
return _this;
}
return _createClass(Space);
}(DefaultKeyup);
var defaultHandles$1 = [{
name: 'default',
handle: DefaultKeyup
}, {
name: 'enter',
handle: Enter$1,
triggerName: 'keyup:enter'
}, {
name: 'backspace',
handle: Backspace$1,
triggerName: 'keyup:backspace'
}, {
name: 'tab',
handle: Tab$1,
triggerName: 'keyup:tab'
}, {
name: 'space',
handle: Space$1,
triggerName: 'keyup:space'
}];
var Typing = /*#__PURE__*/function () {
function Typing(engine) {
var _this = this;
_classCallCheck(this, Typing);
this.engine = void 0;
this.handleListeners = [];
this.bindKeydown = function (event) {
var _this$engine = _this.engine,
readonly = _this$engine.readonly,
card = _this$engine.card; //只读状态
if (readonly) {
//全选禁止默认事件触发
if (isHotkey__default['default']('mod+a', event)) event.preventDefault();
return;
} //跳过卡片
if (event.target && card.find($(event.target))) return;
_this.trigger('keydown', event);
};
this.bindKeyup = function (event) {
var _this$engine2 = _this.engine,
readonly = _this$engine2.readonly,
card = _this$engine2.card; //只读状态
if (readonly) return; //跳过卡片
if (event.target && card.find($(event.target))) return;
_this.trigger('keyup', event);
};
this.engine = engine;
defaultHandles.concat(defaultHandles$1).forEach(function (handle) {
_this.addHandleListener(handle.name, handle.handle, handle.triggerName);
});
var container = engine.container;
container.on('keydown', this.bindKeydown);
container.on('keyup', this.bindKeyup);
}
_createClass(Typing, [{
key: "addHandleListener",
value: function addHandleListener(name, handle, triggerName, triggerParams) {
this.handleListeners.push({
name: name,
handle: new handle(this.engine),
triggerName: triggerName,
triggerParams: triggerParams
});
}
}, {
key: "getHandleListener",
value: function getHandleListener(name, type) {
var _this$handleListeners;
return (_this$handleListeners = this.handleListeners.find(function (listener) {
return listener.name === name && listener.handle.type === type;
})) === null || _this$handleListeners === void 0 ? void 0 : _this$handleListeners.handle;
}
}, {
key: "removeHandleListener",
value: function removeHandleListener(name, type) {
for (var i = 0; i < this.handleListeners.length; i++) {
if (this.handleListeners[i].name === name && this.handleListeners[i].handle.type === type) {
this.handleListeners[i].handle.destroy();
this.handleListeners.splice(i, 1);
break;
}
}
}
}, {
key: "trigger",
value: function trigger(type, event) {
var _this2 = this;
//循环事件
var result = this.handleListeners.filter(function (_ref) {
var handle = _ref.handle;
return handle.type === type;
}).some(function (listener) {
var name = listener.name,
handle = listener.handle,
triggerName = listener.triggerName,
triggerParams = listener.triggerParams;
if (name === 'default' || !!!handle.hotkey) return false;
if (typeof handle.hotkey === 'function' ? handle.hotkey(event) : isHotkey__default['default'](handle.hotkey, event)) {
var _this2$engine;
var params = [event];
if (typeof triggerParams === 'function') params = triggerParams(_this2.engine, event);
if (!triggerName || (_this2$engine = _this2.engine).trigger.apply(_this2$engine, [triggerName].concat(_toConsumableArray(params))) !== false) {
handle.trigger(event);
}
return true;
}
return false;
}); //触发默认事件
if (result === false && this.engine.trigger(type + ':default', event) !== false) {
var _this$getHandleListen;
(_this$getHandleListen = this.getHandleListener('default', type)) === null || _this$getHandleListen === void 0 ? void 0 : _this$getHandleListen.trigger(event);
}
}
}, {
key: "destroy",
value: function destroy() {
var container = this.engine.container;
this.handleListeners = [];
container.off('keydown', this.bindKeydown);
container.off('keyup', this.bindKeyup);
}
}]);
return Typing;
}();
var DATA_PLACEHOLDER = 'data-placeholder';
var DATA_PLACEHOLDER_CLASS = 'am-engine-placeholder';
var Container = /*#__PURE__*/function () {
function Container(selector, options) {
var _this = this;
_classCallCheck(this, Container);
this.options = void 0;
this.node = void 0;
this._focused = false;
this._setFocus = function () {
_this._focused = true;
};
this._setBlur = function () {
_this._focused = false;
};
this.handleClick = function (event) {
var _this$options = _this.options,
engine = _this$options.engine,
autoAppend = _this$options.autoAppend,
autoPrepend = _this$options.autoPrepend;
if (event.target && !engine.readonly && isEngine(engine)) {
var _firstBlock$get, _lastBlock$get, _lastBlock$get2;
var targetNode = $(event.target);
if (!targetNode.isEditable()) return;
var node = $('
');
var container = targetNode.closest("".concat(EDITABLE_SELECTOR, ",").concat(ROOT_SELECTOR)); // 获取编辑器内第一个子节点
var firstBlock = container.first();
if (!firstBlock) {
engine.change.initValue(undefined, true, targetNode);
} //获取到编辑器内最后一个子节点
var lastBlock = container.last();
var isHandle = false; // 存在这个节点,并且鼠标单击位置要小于第一个节点,并且这个节点不是一个空的节点
if (autoPrepend !== false && firstBlock && event.offsetY < (((_firstBlock$get = firstBlock.get()) === null || _firstBlock$get === void 0 ? void 0 : _firstBlock$get.offsetTop) || 0) && !engine.node.isEmptyWidthChild(firstBlock)) {
container.prepend(node);
isHandle = true;
} // 存在这个节点,并且鼠标单击位置要大于最后一个节点,并且这个节点不是一个空的节点
else if (autoAppend !== false && lastBlock && event.offsetY > (((_lastBlock$get = lastBlock.get()) === null || _lastBlock$get === void 0 ? void 0 : _lastBlock$get.offsetTop) || 0) + (((_lastBlock$get2 = lastBlock.get()) === null || _lastBlock$get2 === void 0 ? void 0 : _lastBlock$get2.clientHeight) || 0) && !engine.node.isEmptyWidthChild(lastBlock)) {
container.append(node);
isHandle = true;
} // 有父节点说明已经加到编辑器内了
if (isHandle) {
var range = engine.change.range.get();
range.select(node, true).collapse(false);
engine.change.apply(range);
}
}
};
this.handleFocus = function () {
var engine = _this.options.engine;
_this.triggerFoucs();
if (!engine.model.mutation.isStopped && engine.isEmpty()) engine.change.initValue();
};
this.focusTimeout = null;
this.triggerFoucs = function () {
var engine = _this.options.engine;
if (_this.focusTimeout) clearTimeout(_this.focusTimeout);
_this.focusTimeout = setTimeout(function () {
if (_this._focused) return;
var range = engine.change.range.get();
if (range.commonAncestorNode.isRoot(engine.container) || range.commonAncestorNode.inEditor(engine.container)) {
engine.change.range.setLastBlurRange();
engine.trigger('focus');
}
}, 0);
};
this.onInput = function (e) {
var engine = _this.options.engine;
if (engine.readonly) {
return;
}
if (e.target && engine.card.find($(e.target))) {
return;
}
var range = engine.change.range.get();
range.handleBr(true);
};
this.onRealtimeChange = function () {
var engine = _this.options.engine;
if (engine.isEmpty()) {
engine.showPlaceholder();
} else {
engine.hidePlaceholder();
}
};
this.blurTimeout = null;
this.docMouseDown = function (e) {
if (!e.target) return;
var targetNode = $(e.target);
var engine = _this.options.engine;
if (_this._focused && targetNode.closest(UI_SELECTOR).length === 0 && !targetNode.inEditor(engine.container)) {
if (_this.blurTimeout) clearTimeout(_this.blurTimeout);
var lastRange = engine.change.range.get();
_this.blurTimeout = setTimeout(function () {
var range = engine.change.range.get();
if (!range.commonAncestorNode.inEditor(engine.container)) {
engine.change.range.setLastBlurRange(lastRange);
engine.trigger('blur');
}
}, 0);
}
};
this.node = $(selector);
this.options = options;
this._init();
this._focused = document.activeElement !== null && this.node.equal(document.activeElement);
var _engine = options.engine;
_engine.on('blur', this._setBlur);
_engine.on('focus', this._setFocus);
}
_createClass(Container, [{
key: "_init",
value: function _init() {
var _this$node$attributes,
_this2 = this;
var _this$options2 = this.options,
lang = _this$options2.lang,
tabIndex = _this$options2.tabIndex,
className = _this$options2.className;
this.node.attributes((_this$node$attributes = {}, _defineProperty(_this$node$attributes, DATA_CONTENTEDITABLE_KEY, 'true'), _defineProperty(_this$node$attributes, "role", 'textbox'), _defineProperty(_this$node$attributes, "autocorrect", lang === 'en-US' ? 'on' : 'off'), _defineProperty(_this$node$attributes, "autocomplete", 'off'), _defineProperty(_this$node$attributes, "spellcheck", lang === 'en-US' ? 'true' : 'false'), _defineProperty(_this$node$attributes, 'data-gramm', 'false'), _this$node$attributes));
if (tabIndex !== undefined) {
this.node.attributes('tabindex', tabIndex);
}
if (!this.node.hasClass(ENGINE_CLASS_NAME)) {
this.node.addClass(ENGINE_CLASS_NAME);
}
if (isMobile) this.node.addClass(ENGINE_MOBILE_CLASS_NAME);
if (className !== undefined) {
(Array.isArray(className) ? className : className.split(/\s+/)).forEach(function (name) {
if (name.trim() !== '') _this2.node.addClass(name);
});
}
}
}, {
key: "init",
value: function init() {
var engine = this.options.engine;
this.node.on('input', this.onInput);
engine.on('realtimeChange', this.onRealtimeChange); // 编辑器文档尾部始终保持一行
this.node.on('click', this.handleClick);
document.addEventListener('mousedown', this.docMouseDown);
this.node.on(isMobile ? 'touchstart' : 'mousedown', this.triggerFoucs, {
passive: true
});
this.node.on('focus', this.handleFocus);
}
}, {
key: "isFocus",
value: function isFocus() {
return this._focused;
}
}, {
key: "getNode",
value: function getNode() {
return this.node;
}
}, {
key: "setReadonly",
value: function setReadonly(readonly) {
this.node.attributes(DATA_CONTENTEDITABLE_KEY, readonly ? 'false' : 'true');
}
}, {
key: "showPlaceholder",
value: function showPlaceholder() {
var placeholder = this.options.placeholder;
if (placeholder) {
//const left = this.node.css('padding-left');
//const top = this.node.css('padding-top');
this.node.attributes(_defineProperty({}, DATA_PLACEHOLDER, placeholder));
this.node.addClass(DATA_PLACEHOLDER_CLASS);
}
}
}, {
key: "hidePlaceholder",
value: function hidePlaceholder() {
this.node.removeAttributes(DATA_PLACEHOLDER);
this.node.removeClass(DATA_PLACEHOLDER_CLASS);
}
}, {
key: "destroy",
value: function destroy() {
var _this3 = this;
var _this$options3 = this.options,
className = _this$options3.className,
engine = _this$options3.engine;
engine.on('blur', this._setBlur);
engine.on('focus', this._setFocus);
engine.off('realtimeChange', this.onRealtimeChange);
document.removeEventListener('mousedown', this.docMouseDown);
this.node.removeAttributes(DATA_CONTENTEDITABLE_KEY);
this.node.removeAttributes('role');
this.node.removeAttributes('autocorrect');
this.node.removeAttributes('autocomplete');
this.node.removeAttributes('spellcheck');
this.node.removeAttributes('data-gramm');
this.node.removeAttributes('tabindex');
this.node.removeAttributes(DATA_PLACEHOLDER);
if (this.options.className) {
(Array.isArray(className) ? className : (className || '').split(/\s+/)).forEach(function (name) {
if (name.trim() !== '') _this3.node.removeClass(name);
});
}
if (engine.card.closest(this.node)) this.node.removeClass(ENGINE_CLASS_NAME);
this.node.removeAllEvents();
}
}]);
return Container;
}();
/**
* 语言包管理器
*/
var Language = /*#__PURE__*/function () {
function Language(locale) {
var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Language);
this.data = {};
this.locale = 'zh-CN';
this.locale = locale;
this.data = data;
}
_createClass(Language, [{
key: "add",
value: function add(data) {
this.data = merge__default['default'](this.data, data);
}
}, {
key: "get",
value: function get() {
for (var _len = arguments.length, keys = new Array(_len), _key = 0; _key < _len; _key++) {
keys[_key] = arguments[_key];
}
var get = function get() {
var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var language = arguments.length > 1 ? arguments[1] : undefined;
for (var i = start; i < keys.length; i++) {
var value = language[keys[i]];
if (_typeof(value) === 'object') {
return get(i + 1, value);
}
return value || '';
}
return language;
};
return get(0, this.data[this.locale]);
}
}]);
return Language;
}();
var en = {
dnd: {
title: 'Drag to reposition'
},
copy: {
title: 'Copy',
success: 'Copied successfully',
error: 'Copy error'
},
delete: {
title: 'Delete'
},
copyAnchor: {
title: 'Copy anchor link'
},
link: {
placeholder: 'Please enter a link or anchor and press Enter to confirm',
save: 'Apply',
edit: 'Change',
delete: 'Remove link',
open: 'Open link',
text: 'link'
},
copyContent: {
title: 'copy content'
},
maximize: {
title: 'Maximize',
back: 'Back to document'
},
expand: {
title: 'Embedded preview'
},
collapse: {
title: 'Compact display'
},
card: {
lockAlert: 'Please wait for the other user to finish editing'
},
preferences: {
title: 'Preferences'
},
download: {
title: 'Download'
},
more: {
title: 'More'
},
checkMarkdown: {
title: 'It is detected that the paste content conforms to the Markdown syntax. Do you need to do style conversion?'
},
searchEmtpy: {
title: 'No matching card'
}
};
var cn = {
dnd: {
title: '拖动调整位置'
},
copy: {
title: '复制',
success: '复制成功',
error: '复制失败'
},
delete: {
title: '删除'
},
copyAnchor: {
title: '复制锚点链接'
},
link: {
placeholder: '请输入链接或锚点,回车确认',
save: '保存',
edit: '编辑',
delete: '取消链接',
open: '打开链接',
text: '链接'
},
copyContent: {
title: '复制内容'
},
maximize: {
title: '最大化',
back: '返回文档'
},
expand: {
title: '嵌入预览'
},
collapse: {
title: '紧凑展示'
},
card: {
lockAlert: '请等待对方编辑完毕后,再进入编辑'
},
preferences: {
title: '设置'
},
download: {
title: '下载'
},
more: {
title: '更多'
},
checkMarkdown: {
title: '检测到粘贴内容符合 Markdown 语法,是否需要转换?'
},
searchEmtpy: {
title: '无匹配卡片'
}
};
var language = {
'en-US': en,
'zh-CN': cn
};
var PluginEntry = /*#__PURE__*/_createClass(function PluginEntry(editor, options) {
_classCallCheck(this, PluginEntry);
this.editor = void 0;
this.options = void 0;
this.kind = 'plugin';
this.name = this.constructor.pluginName;
this.disabled = void 0;
this.editor = editor;
this.options = options || {};
var disabled = this.options.disabled;
this.disabled = disabled; // TODO:this.disabledPlugins = disabledPlugins || [];
});
PluginEntry.pluginName = void 0;
var ElementPluginEntry = /*#__PURE__*/function (_PluginEntry) {
_inherits(ElementPluginEntry, _PluginEntry);
var _super = _createSuper(ElementPluginEntry);
function ElementPluginEntry() {
var _this;
_classCallCheck(this, ElementPluginEntry);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.kind = 'element';
_this.sechamCache = void 0;
_this.tagName = void 0;
_this.style = void 0;
_this.attributes = void 0;
_this.variable = void 0;
return _this;
}
_createClass(ElementPluginEntry, [{
key: "init",
value:
/**
* 初始化
*/
function init() {
var _this$editor = this.editor,
schema = _this$editor.schema,
conversion = _this$editor.conversion;
schema.add(this.schema());
if (this.conversion) {
this.conversion().forEach(function (_ref) {
var from = _ref.from,
to = _ref.to;
conversion.add(from, to);
});
}
}
/**
* 将当前插件style属性应用到节点
* @param node 节点
* @param args style 对应 variable 中的变量参数
*/
}, {
key: "setStyle",
value: function setStyle(node) {
var _this2 = this;
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
if (isNode(node)) node = $(node);
if (this.style) {
Object.keys(this.style).forEach(function (styleName) {
var _styleValue$match;
var styleValue = _this2.style[styleName];
if (_typeof(styleValue) === 'object') styleValue = styleValue.value; //替换变量
(_styleValue$match = styleValue.match(/@var\d/g)) === null || _styleValue$match === void 0 ? void 0 : _styleValue$match.forEach(function (regMatch) {
var index = parseInt(regMatch.replace('@var', ''), 10);
styleValue = styleValue.replace(new RegExp(regMatch, 'gm'), args[index] || '');
});
node.css(styleName, styleValue);
});
}
}
/**
* 将当前插件attributes属性应用到节点
* @param node 节点
* @param args attributes 对应 variable 中的变量参数
*/
}, {
key: "setAttributes",
value: function setAttributes(node) {
var _this3 = this;
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
if (isNode(node)) node = $(node);
if (this.attributes) {
Object.keys(this.attributes).forEach(function (attributesName) {
var _attributesValue$matc;
var attributesValue = _this3.attributes[attributesName];
if (_typeof(attributesValue) === 'object') attributesValue = attributesValue.value; //替换变量
(_attributesValue$matc = attributesValue.match(/@var\d/g)) === null || _attributesValue$matc === void 0 ? void 0 : _attributesValue$matc.forEach(function (regMatch) {
var index = parseInt(regMatch.replace('@var', ''), 10);
attributesValue = attributesValue.replace(new RegExp(regMatch, 'gm'), args[index] || '');
});
node.attributes(attributesName, attributesValue);
});
}
}
/**
* 获取节点符合当前插件规则的样式
* @param node 节点
* @returns 样式名称和样式值键值对
*/
}, {
key: "getStyle",
value: function getStyle(node) {
var _this4 = this;
if (isNode(node)) node = $(node);
var values = {};
if (this.style && this.isSelf(node)) {
Object.keys(this.style).forEach(function (styleName) {
node = node;
var value = styleName.toLowerCase().indexOf('color') > -1 ? colord.colord(node.css(styleName) || '').toHex() : node.css(styleName);
var styleValue = _this4.style[styleName];
if (_typeof(styleValue) === 'object') {
value = styleValue.format(value);
}
if (!!value) values[styleName] = value;
});
}
return values;
}
/**
* 获取节点符合当前插件规则的属性
* @param node 节点
* @returns 属性名称和属性值键值对
*/
}, {
key: "getAttributes",
value: function getAttributes(node) {
var _this5 = this;
if (isNode(node)) node = $(node);
var values = {};
if (this.attributes && this.isSelf(node)) {
Object.keys(this.attributes).forEach(function (attributesName) {
var value = node.attributes(attributesName);
var attributesValue = _this5.attributes[attributesName];
if (_typeof(attributesValue) === 'object') {
value = attributesValue.format(value);
}
if (!!value) values[attributesName] = value;
});
}
return values;
}
/**
* 检测当前节点是否符合当前插件设置的规则
* @param node 节点
* @returns true | false
*/
}, {
key: "isSelf",
value: function isSelf(node) {
if (isNode(node)) node = $(node);
var schema = this.schema();
if (Array.isArray(schema)) schema = schema.find(function (_ref2) {
var name = _ref2.name;
return name === node.name;
});
if (!schema) return false;
return (Array.isArray(this.tagName) ? this.tagName.indexOf(node.name) > -1 : node.name === this.tagName) && this.editor.schema.checkNode(node, schema.attributes);
}
/**
* 获取插件设置的属性和样式所生成的规则
*/
}, {
key: "schema",
value: function schema() {
var _this6 = this;
if (this.sechamCache) return this.sechamCache;
var attributes = {};
if (this.attributes) {
//替换变量
Object.keys(this.attributes).forEach(function (attributesName) {
var _attributesValue$matc2;
var attributesValue = _this6.attributes[attributesName];
if (_typeof(attributesValue) === 'object') attributesValue = attributesValue.value;
attributes[attributesName] = attributesValue;
(_attributesValue$matc2 = attributesValue.match(/@var\d/g)) === null || _attributesValue$matc2 === void 0 ? void 0 : _attributesValue$matc2.forEach(function (regMatch) {
if (!_this6.variable) throw 'Please specify the variable type';
attributes[attributesName] = _this6.variable[regMatch];
});
});
}
if (this.style) {
//替换变量
var style = {};
Object.keys(this.style).forEach(function (styleName) {
var _styleValue$match2;
var styleValue = _this6.style[styleName];
if (_typeof(styleValue) === 'object') styleValue = styleValue.value;
(_styleValue$match2 = styleValue.match(/@var\d/g)) === null || _styleValue$match2 === void 0 ? void 0 : _styleValue$match2.forEach(function (regMatch) {
if (!_this6.variable) throw 'Please specify the variable type';
style[styleName] = _this6.variable[regMatch];
});
});
attributes = _objectSpread2(_objectSpread2({}, attributes), {}, {
style: style
});
}
this.sechamCache = {
type: this.kind,
attributes: attributes
};
if (typeof this.tagName === 'string') this.sechamCache.name = this.tagName.toLowerCase();else if (Array.isArray(this.tagName)) {
var sechamValue = [];
this.tagName.forEach(function (name) {
sechamValue.push(_objectSpread2(_objectSpread2({}, _this6.sechamCache), {}, {
name: name
}));
});
this.sechamCache = sechamValue;
}
return this.sechamCache;
}
/**
* 创建符合当前插件规则的节点
* @param args 参数
* @returns 节点
*/
}, {
key: "createElement",
value: function createElement() {
var markNode = $("<".concat(this.tagName, " />"));
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
this.setStyle.apply(this, [markNode].concat(args));
this.setAttributes.apply(this, [markNode].concat(args));
return markNode;
}
}]);
return ElementPluginEntry;
}(PluginEntry);
var isElementPlugin = function isElementPlugin(plugin) {
return plugin.kind === 'element';
};
var BlockEntry = /*#__PURE__*/function (_ElementPluginEntry) {
_inherits(BlockEntry, _ElementPluginEntry);
var _super = _createSuper(BlockEntry);
function BlockEntry() {
var _this;
_classCallCheck(this, BlockEntry);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.kind = 'block';
_this.allowIn = void 0;
_this.disableMark = void 0;
_this.canMerge = void 0;
return _this;
}
_createClass(BlockEntry, [{
key: "schema",
value: function schema() {
var _this2 = this;
var schema = _get(_getPrototypeOf(BlockEntry.prototype), "schema", this).call(this);
if (Array.isArray(schema)) {
return schema.map(function (schema) {
return _objectSpread2(_objectSpread2({}, schema), {}, {
allowIn: _this2.allowIn
});
});
}
return _objectSpread2(_objectSpread2({}, schema), {}, {
allowIn: this.allowIn,
canMerge: this.canMerge
});
}
}]);
return BlockEntry;
}(ElementPluginEntry);
var isBlockPlugin = function isBlockPlugin(plugin) {
return plugin.kind === 'block';
};
var InlineEntry = /*#__PURE__*/function (_ElementPluginEntry) {
_inherits(InlineEntry, _ElementPluginEntry);
var _super = _createSuper(InlineEntry);
function InlineEntry() {
var _this;
_classCallCheck(this, InlineEntry);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.kind = 'inline';
_this.markdown = void 0;
return _this;
}
_createClass(InlineEntry, [{
key: "execute",
value: function execute() {
var editor = this.editor;
if (!isEngine(editor)) return;
var inlineNode = $("<".concat(this.tagName, " />"));
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
this.setStyle.apply(this, [inlineNode].concat(args));
this.setAttributes.apply(this, [inlineNode].concat(args));
var inline = editor.inline;
var trigger = this.isTrigger ? this.isTrigger.apply(this, args) : !this.queryState();
if (trigger) {
inline.wrap(inlineNode);
} else {
inline.unwrap();
}
}
}, {
key: "queryState",
value: function queryState() {
var _this2 = this;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change; //如果没有属性和样式限制,直接查询是否包含当前标签名称
if (!this.style && !this.attributes) return change.inlines.some(function (node) {
return node.name === _this2.tagName;
}); //获取属性和样式限制内的值集合
var values = [];
change.inlines.forEach(function (node) {
values.push.apply(values, _toConsumableArray(Object.values(_this2.getStyle(node))));
values.push.apply(values, _toConsumableArray(Object.values(_this2.getAttributes(node))));
});
return values.length === 0 ? undefined : values;
}
}]);
return InlineEntry;
}(ElementPluginEntry);
var isInlinePlugin = function isInlinePlugin(plugin) {
return plugin.kind === 'inline';
};
var css_248z$4 = ".am-engine ol, .am-engine-view ol, .am-engine ul, .am-engine-view ul {\n margin: 0 0 0 3px;\n padding: 0;\n list-style: none;\n}\n\n.am-engine ol ul,.am-engine-view ol ul,.am-engine ul ul,.am-engine-view ul ul,.am-engine ol ol,.am-engine-view ol ol,.am-engine ul ol,.am-engine-view ul ol {\n\tmargin-left: 0;\n}\n\n.am-engine ol ul li,.am-engine-view ol ul li,.am-engine ul ul li,.am-engine-view ul ul li,.am-engine ol ol li,.am-engine-view ol ol li,.am-engine ul ol li,.am-engine-view ul ol li {\n\tmargin-left: 2em;\n}\n\n.am-engine ol ol[data-indent-new=\"0\"],.am-engine-view ol ol[data-indent-new=\"0\"],.am-engine ul ol[data-indent-new=\"0\"],.am-engine-view ul ol[data-indent-new=\"0\"],.am-engine ol ol[data-indent-new=\"3\"],.am-engine-view ol ol[data-indent-new=\"3\"],.am-engine ul ol[data-indent-new=\"3\"],.am-engine-view ul ol[data-indent-new=\"3\"],.am-engine ol ol[data-indent-new=\"6\"],.am-engine-view ol ol[data-indent-new=\"6\"],.am-engine ul ol[data-indent-new=\"6\"],.am-engine-view ul ol[data-indent-new=\"6\"],.am-engine ol ol[data-indent-new=\"6\"],.am-engine ol ol[data-indent-new=\"9\"],.am-engine-view ol ol[data-indent-new=\"9\"],.am-engine ul ol[data-indent-new=\"9\"],.am-engine-view ul ol[data-indent-new=\"9\"],.am-engine ol ol[data-indent-new=\"12\"],.am-engine-view ol ol[data-indent-new=\"12\"],.am-engine ul ol[data-indent-new=\"12\"],.am-engine-view ul ol[data-indent-new=\"12\"],.am-engine ol ol[data-indent-new=\"15\"],.am-engine-view ol ol[data-indent-new=\"15\"],.am-engine ul ol[data-indent-new=\"15\"],.am-engine-view ul ol[data-indent-new=\"15\"],.am-engine ol ol[data-indent-new=\"18\"],.am-engine-view ol ol[data-indent-new=\"18\"],.am-engine ul ol[data-indent-new=\"18\"],.am-engine-view ul ol[data-indent-new=\"18\"] {\n\tlist-style-type: decimal;\n}\n\n.am-engine ol ol[data-indent-new=\"1\"],.am-engine-view ol ol[data-indent-new=\"1\"],.am-engine ul ol[data-indent-new=\"1\"],.am-engine-view ul ol[data-indent-new=\"1\"],.am-engine ol ol[data-indent-new=\"4\"],.am-engine-view ol ol[data-indent-new=\"4\"],.am-engine ul ol[data-indent-new=\"4\"],.am-engine-view ul ol[data-indent-new=\"4\"],.am-engine ol ol[data-indent-new=\"7\"],.am-engine-view ol ol[data-indent-new=\"7\"],.am-engine ul ol[data-indent-new=\"7\"],.am-engine-view ul ol[data-indent-new=\"7\"],.am-engine ol ol[data-indent-new=\"10\"],.am-engine-view ol ol[data-indent-new=\"10\"],.am-engine ul ol[data-indent-new=\"10\"],.am-engine-view ul ol[data-indent-new=\"10\"],.am-engine ol ol[data-indent-new=\"13\"],.am-engine-view ol ol[data-indent-new=\"13\"],.am-engine ul ol[data-indent-new=\"13\"],.am-engine-view ul ol[data-indent-new=\"13\"],.am-engine ol ol[data-indent-new=\"16\"],.am-engine-view ol ol[data-indent-new=\"16\"],.am-engine ul ol[data-indent-new=\"16\"],.am-engine-view ul ol[data-indent-new=\"16\"],.am-engine ol ol[data-indent-new=\"19\"],.am-engine-view ol ol[data-indent-new=\"19\"],.am-engine ul ol[data-indent-new=\"19\"],.am-engine-view ul ol[data-indent-new=\"19\"] {\n\tlist-style-type: lower-alpha;\n}\n\n.am-engine ol ol[data-indent-new=\"2\"],.am-engine-view ol ol[data-indent-new=\"2\"],.am-engine ul ol[data-indent-new=\"2\"],.am-engine-view ul ol[data-indent-new=\"2\"],.am-engine ol ol[data-indent-new=\"5\"],.am-engine-view ol ol[data-indent-new=\"5\"],.am-engine ul ol[data-indent-new=\"5\"],.am-engine-view ul ol[data-indent-new=\"5\"],.am-engine ol ol[data-indent-new=\"8\"],.am-engine-view ol ol[data-indent-new=\"8\"],.am-engine ul ol[data-indent-new=\"8\"],.am-engine-view ul ol[data-indent-new=\"8\"],.am-engine ol ol[data-indent-new=\"11\"],.am-engine-view ol ol[data-indent-new=\"11\"],.am-engine ul ol[data-indent-new=\"11\"],.am-engine-view ul ol[data-indent-new=\"11\"],.am-engine ol ol[data-indent-new=\"14\"],.am-engine-view ol ol[data-indent-new=\"14\"],.am-engine ul ol[data-indent-new=\"14\"],.am-engine-view ul ol[data-indent-new=\"14\"],.am-engine ol ol[data-indent-new=\"17\"],.am-engine-view ol ol[data-indent-new=\"17\"],.am-engine ul ol[data-indent-new=\"17\"],.am-engine-view ul ol[data-indent-new=\"17\"],.am-engine ol ol[data-indent-new=\"20\"],.am-engine-view ol ol[data-indent-new=\"20\"],.am-engine ul ol[data-indent-new=\"20\"],.am-engine-view ul ol[data-indent-new=\"20\"] {\n\tlist-style-type: lower-roman;\n}\n\n.am-engine ol ul[data-indent-new=\"3\"],.am-engine-view ol ul[data-indent-new=\"3\"],.am-engine ul ul[data-indent-new=\"3\"],.am-engine-view ul ul[data-indent-new=\"3\"],.am-engine ol ul[data-indent-new=\"6\"],.am-engine-view ol ul[data-indent-new=\"6\"],.am-engine ul ul[data-indent-new=\"6\"],.am-engine-view ul ul[data-indent-new=\"6\"],.am-engine ol ul[data-indent-new=\"9\"],.am-engine-view ol ul[data-indent-new=\"9\"],.am-engine ul ul[data-indent-new=\"9\"],.am-engine-view ul ul[data-indent-new=\"9\"],.am-engine ol ul[data-indent-new=\"12\"],.am-engine-view ol ul[data-indent-new=\"12\"],.am-engine ul ul[data-indent-new=\"12\"],.am-engine-view ul ul[data-indent-new=\"12\"],.am-engine ol ul[data-indent-new=\"15\"],.am-engine-view ol ul[data-indent-new=\"15\"],.am-engine ul ul[data-indent-new=\"15\"],.am-engine-view ul ul[data-indent-new=\"15\"],.am-engine ol ul[data-indent-new=\"18\"],.am-engine-view ol ul[data-indent-new=\"18\"],.am-engine ul ul[data-indent-new=\"18\"],.am-engine-view ul ul[data-indent-new=\"18\"] {\n\tlist-style-type: disc;\n}\n\n.am-engine ol ul[data-indent-new=\"1\"],.am-engine-view ol ul[data-indent-new=\"1\"],.am-engine ul ul[data-indent-new=\"1\"],.am-engine-view ul ul[data-indent-new=\"1\"],.am-engine ol ul[data-indent-new=\"4\"],.am-engine-view ol ul[data-indent-new=\"4\"],.am-engine ul ul[data-indent-new=\"4\"],.am-engine-view ul ul[data-indent-new=\"4\"],.am-engine ol ul[data-indent-new=\"7\"],.am-engine-view ol ul[data-indent-new=\"7\"],.am-engine ul ul[data-indent-new=\"7\"],.am-engine-view ul ul[data-indent-new=\"7\"],.am-engine ol ul[data-indent-new=\"10\"],.am-engine-view ol ul[data-indent-new=\"10\"],.am-engine ul ul[data-indent-new=\"10\"],.am-engine-view ul ul[data-indent-new=\"10\"],.am-engine ol ul[data-indent-new=\"13\"],.am-engine-view ol ul[data-indent-new=\"13\"],.am-engine ul ul[data-indent-new=\"13\"],.am-engine-view ul ul[data-indent-new=\"13\"],.am-engine ol ul[data-indent-new=\"16\"],.am-engine-view ol ul[data-indent-new=\"16\"],.am-engine ul ul[data-indent-new=\"16\"],.am-engine-view ul ul[data-indent-new=\"16\"],.am-engine ol ul[data-indent-new=\"19\"],.am-engine-view ol ul[data-indent-new=\"19\"],.am-engine ul ul[data-indent-new=\"19\"],.am-engine-view ul ul[data-indent-new=\"19\"] {\n\tlist-style-type: circle;\n}\n\n.am-engine ol ul[data-indent-new=\"2\"],.am-engine-view ol ul[data-indent-new=\"2\"],.am-engine ul ul[data-indent-new=\"2\"],.am-engine-view ul ul[data-indent-new=\"2\"],.am-engine ol ul[data-indent-new=\"5\"],.am-engine-view ol ul[data-indent-new=\"5\"],.am-engine ul ul[data-indent-new=\"5\"],.am-engine-view ul ul[data-indent-new=\"5\"],.am-engine ol ul[data-indent-new=\"8\"],.am-engine-view ol ul[data-indent-new=\"8\"],.am-engine ul ul[data-indent-new=\"8\"],.am-engine-view ul ul[data-indent-new=\"8\"],.am-engine ol ul[data-indent-new=\"11\"],.am-engine-view ol ul[data-indent-new=\"11\"],.am-engine ul ul[data-indent-new=\"11\"],.am-engine-view ul ul[data-indent-new=\"11\"],.am-engine ol ul[data-indent-new=\"14\"],.am-engine-view ol ul[data-indent-new=\"14\"],.am-engine ul ul[data-indent-new=\"14\"],.am-engine-view ul ul[data-indent-new=\"14\"],.am-engine ol ul[data-indent-new=\"17\"],.am-engine-view ol ul[data-indent-new=\"17\"],.am-engine ul ul[data-indent-new=\"17\"],.am-engine-view ul ul[data-indent-new=\"17\"],.am-engine ol ul[data-indent-new=\"20\"],.am-engine-view ol ul[data-indent-new=\"20\"],.am-engine ul ul[data-indent-new=\"20\"],.am-engine-view ul ul[data-indent-new=\"20\"] {\n\tlist-style-type: square;\n}\n\n.am-engine li,.am-engine-view li {\n\tmargin-left: 23px;\n position: relative;\n}\n\n.am-engine ol,.am-engine-view ol,.am-engine ol[data-indent=\"3\"],.am-engine-view ol[data-indent=\"3\"],.am-engine ol[data-indent=\"6\"],.am-engine-view ol[data-indent=\"6\"],.am-engine ol[data-indent=\"9\"],.am-engine-view ol[data-indent=\"9\"],.am-engine ol[data-indent=\"12\"],.am-engine-view ol[data-indent=\"12\"],.am-engine ol[data-indent=\"15\"],.am-engine-view ol[data-indent=\"15\"],.am-engine ol[data-indent=\"18\"],.am-engine-view ol[data-indent=\"18\"] {\n\tlist-style-type: decimal;\n}\n\n.am-engine ol[data-indent=\"1\"],.am-engine-view ol[data-indent=\"1\"],.am-engine ol[data-indent=\"4\"],.am-engine-view ol[data-indent=\"4\"],.am-engine ol[data-indent=\"7\"],.am-engine-view ol[data-indent=\"7\"],.am-engine ol[data-indent=\"10\"],.am-engine-view ol[data-indent=\"10\"],.am-engine ol[data-indent=\"13\"],.am-engine-view ol[data-indent=\"13\"],.am-engine ol[data-indent=\"16\"],.am-engine-view ol[data-indent=\"16\"],.am-engine ol[data-indent=\"19\"],.am-engine-view ol[data-indent=\"19\"] {\n\tlist-style-type: lower-alpha;\n}\n\n.am-engine ol[data-indent=\"2\"],.am-engine-view ol[data-indent=\"2\"],.am-engine ol[data-indent=\"5\"],.am-engine-view ol[data-indent=\"5\"],.am-engine ol[data-indent=\"8\"],.am-engine-view ol[data-indent=\"8\"],.am-engine ol[data-indent=\"11\"],.am-engine-view ol[data-indent=\"11\"],.am-engine ol[data-indent=\"14\"],.am-engine-view ol[data-indent=\"14\"],.am-engine ol[data-indent=\"17\"],.am-engine-view ol[data-indent=\"17\"],.am-engine ol[data-indent=\"20\"],.am-engine-view ol[data-indent=\"20\"] {\n\tlist-style-type: lower-roman;\n}\n\n.am-engine ul,.am-engine-view ul,.am-engine ul[data-indent=\"3\"],.am-engine-view ul[data-indent=\"3\"],.am-engine ul[data-indent=\"6\"],.am-engine-view ul[data-indent=\"6\"],.am-engine ul[data-indent=\"9\"],.am-engine-view ul[data-indent=\"9\"],.am-engine ul[data-indent=\"12\"],.am-engine-view ul[data-indent=\"12\"],.am-engine ul[data-indent=\"15\"],.am-engine-view ul[data-indent=\"15\"],.am-engine ul[data-indent=\"18\"],.am-engine-view ul[data-indent=\"18\"] {\n\tlist-style-type: disc;\n}\n\n.am-engine ul[data-indent=\"1\"],.am-engine-view ul[data-indent=\"1\"],.am-engine ul[data-indent=\"4\"],.am-engine-view ul[data-indent=\"4\"],.am-engine ul[data-indent=\"7\"],.am-engine-view ul[data-indent=\"7\"],.am-engine ul[data-indent=\"10\"],.am-engine-view ul[data-indent=\"10\"],.am-engine ul[data-indent=\"13\"],.am-engine-view ul[data-indent=\"13\"],.am-engine ul[data-indent=\"16\"],.am-engine-view ul[data-indent=\"19\"],.am-engine ul[data-indent=\"19\"],.am-engine-view ul[data-indent=\"19\"] {\n\tlist-style-type: circle;\n}\n\n.am-engine ul[data-indent=\"2\"],.am-engine-view ul[data-indent=\"2\"],.am-engine ul[data-indent=\"5\"],.am-engine-view ul[data-indent=\"5\"],.am-engine ul[data-indent=\"8\"],.am-engine-view ul[data-indent=\"8\"],.am-engine ul[data-indent=\"11\"],.am-engine-view ul[data-indent=\"11\"],.am-engine ul[data-indent=\"14\"],.am-engine-view ul[data-indent=\"14\"],.am-engine ul[data-indent=\"17\"],.am-engine-view ul[data-indent=\"17\"],.am-engine ul[data-indent=\"20\"],.am-engine-view ul[data-indent=\"20\"] {\n\tlist-style-type: square;\n}\n\n.am-engine ol[data-indent=\"1\"],.am-engine-view ol[data-indent=\"1\"],.am-engine ul[data-indent=\"1\"],.am-engine-view ul[data-indent=\"1\"] {\n\tpadding-left: 2em;\n}\n\n.am-engine ol[data-indent=\"2\"],.am-engine-view ol[data-indent=\"2\"],.am-engine ul[data-indent=\"2\"],.am-engine-view ul[data-indent=\"2\"] {\n\tpadding-left: 4em;\n}\n\n.am-engine ol[data-indent=\"3\"],.am-engine-view ol[data-indent=\"3\"],.am-engine ul[data-indent=\"3\"],.am-engine-view ul[data-indent=\"3\"] {\n\tpadding-left: 6em;\n}\n\n.am-engine ol[data-indent=\"4\"],.am-engine-view ol[data-indent=\"4\"],.am-engine ul[data-indent=\"4\"],.am-engine-view ul[data-indent=\"4\"] {\n\tpadding-left: 8em;\n}\n\n.am-engine ol[data-indent=\"5\"],.am-engine-view ol[data-indent=\"5\"],.am-engine ul[data-indent=\"5\"],.am-engine-view ul[data-indent=\"5\"] {\n\tpadding-left: 10em;\n}\n\n.am-engine ol[data-indent=\"6\"],.am-engine-view ol[data-indent=\"6\"],.am-engine ul[data-indent=\"6\"],.am-engine-view ul[data-indent=\"6\"] {\n\tpadding-left: 12em;\n}\n\n.am-engine ol[data-indent=\"7\"],.am-engine-view ol[data-indent=\"7\"],.am-engine ul[data-indent=\"7\"],.am-engine-view ul[data-indent=\"7\"] {\n\tpadding-left: 14em;\n}\n\n.am-engine ol[data-indent=\"8\"],.am-engine-view ol[data-indent=\"8\"],.am-engine ul[data-indent=\"8\"],.am-engine-view ul[data-indent=\"8\"] {\n\tpadding-left: 16em;\n}\n\n.am-engine ol[data-indent=\"8\"],.am-engine-view ol[data-indent=\"8\"],.am-engine ul[data-indent=\"8\"],.am-engine-view ul[data-indent=\"8\"] {\n\tpadding-left: 16em;\n}\n\n.am-engine ol[data-indent=\"9\"],.am-engine-view ol[data-indent=\"9\"],.am-engine ul[data-indent=\"9\"],.am-engine-view ul[data-indent=\"9\"] {\n\tpadding-left: 18em;\n}\n\n.am-engine ol[data-indent=\"10\"],.am-engine-view ol[data-indent=\"10\"],.am-engine ul[data-indent=\"10\"],.am-engine-view ul[data-indent=\"10\"] {\n\tpadding-left: 20em;\n}\n.am-engine ol[data-indent=\"11\"],.am-engine-view ol[data-indent=\"11\"],.am-engine ul[data-indent=\"11\"],.am-engine-view ul[data-indent=\"11\"] {\n\tpadding-left: 22em;\n}\n\n.am-engine ol[data-indent=\"12\"],.am-engine-view ol[data-indent=\"12\"],.am-engine ul[data-indent=\"8\"],.am-engine-view ul[data-indent=\"12\"] {\n\tpadding-left: 24em;\n}\n\n.am-engine ol[data-indent=\"13\"],.am-engine-view ol[data-indent=\"13\"],.am-engine ul[data-indent=\"13\"],.am-engine-view ul[data-indent=\"13\"] {\n\tpadding-left: 26em;\n}\n\n.am-engine ol[data-indent=\"14\"],.am-engine-view ol[data-indent=\"14\"],.am-engine ul[data-indent=\"14\"],.am-engine-view ul[data-indent=\"14\"] {\n\tpadding-left: 28em;\n}\n\n.am-engine ol[data-indent=\"15\"],.am-engine-view ol[data-indent=\"15\"],.am-engine ul[data-indent=\"15\"],.am-engine-view ul[data-indent=\"15\"] {\n\tpadding-left: 30em;\n}\n.am-engine ol[data-indent=\"16\"],.am-engine-view ol[data-indent=\"16\"],.am-engine ul[data-indent=\"16\"],.am-engine-view ul[data-indent=\"16\"] {\n\tpadding-left: 32em;\n}\n.am-engine ol[data-indent=\"17\"],.am-engine-view ol[data-indent=\"17\"],.am-engine ul[data-indent=\"17\"],.am-engine-view ul[data-indent=\"17\"] {\n\tpadding-left: 34em;\n}\n.am-engine ol[data-indent=\"18\"],.am-engine-view ol[data-indent=\"18\"],.am-engine ul[data-indent=\"18\"],.am-engine-view ul[data-indent=\"18\"] {\n\tpadding-left: 36em;\n}\n.am-engine ol[data-indent=\"19\"],.am-engine-view ol[data-indent=\"19\"],.am-engine ul[data-indent=\"19\"],.am-engine-view ul[data-indent=\"19\"] {\n\tpadding-left: 38em;\n}\n.am-engine ol[data-indent=\"20\"],.am-engine-view ol[data-indent=\"20\"],.am-engine ul[data-indent=\"20\"],.am-engine-view ul[data-indent=\"20\"] {\n\tpadding-left: 40em;\n}\n\n.am-engine .data-list,.am-engine-view .data-list {\n\tcolor: #262626;\n\ttext-indent: 0;\n}\n\n.am-engine .data-list-item,.am-engine-view .data-list-item {\n line-height: inherit;\n position: relative;\n list-style: none;\n text-indent: 0;\n}\n";
styleInject(css_248z$4);
var ListEntry = /*#__PURE__*/function (_BlockEntry) {
_inherits(ListEntry, _BlockEntry);
var _super = _createSuper(ListEntry);
function ListEntry() {
var _this;
_classCallCheck(this, ListEntry);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.cardName = void 0;
_this.isPasteList = false;
_this.canMerge = true;
_this.pasteBefore = function (documentFragment) {
var editor = _this.editor;
if (!_this.cardName || !editor) return;
var list = editor.list;
var node = $(documentFragment);
var children = node.allChildren();
children.forEach(function (domChild) {
if (domChild.name === 'li' && domChild.hasClass(list.CUSTOMZIE_LI_CLASS)) {
var _domChild$first;
//自定义列表,没有卡片节点,就作为普通列表
if (!((_domChild$first = domChild.first()) === null || _domChild$first === void 0 ? void 0 : _domChild$first.isCard())) {
domChild.removeClass(list.CUSTOMZIE_LI_CLASS);
domChild.closest('ul').removeClass(list.CUSTOMZIE_UL_CLASS);
return;
} else {
domChild.closest('ul').addClass(list.CUSTOMZIE_UL_CLASS);
}
}
});
_this.isPasteList = children.some(function (child) {
return child.name === 'li';
});
};
_this.pasteInsert = function () {
var editor = _this.editor;
if (!_this.cardName || !isEngine(editor)) return;
var change = editor.change,
list = editor.list;
var range = change.range.get();
var rootBlock = range.getRootBlock();
var nextBlock = rootBlock === null || rootBlock === void 0 ? void 0 : rootBlock.next();
var customizeItems = nextBlock === null || nextBlock === void 0 ? void 0 : nextBlock.find("li.".concat(list.CUSTOMZIE_LI_CLASS));
if (customizeItems && customizeItems.length > 0) {
customizeItems.each(function (node) {
var domNode = $(node);
if (0 === domNode.find("[".concat(CARD_KEY, "=").concat(_this.cardName, "],[").concat(READY_CARD_KEY, "=").concat(_this.cardName, "]")).length) list.addReadyCardToCustomize(domNode, _this.cardName);
});
}
};
_this.pasteAfter = function () {
if (_this.isPasteList) {
var _this$editor;
(_this$editor = _this.editor) === null || _this$editor === void 0 ? void 0 : _this$editor.list.merge();
}
};
return _this;
}
_createClass(ListEntry, [{
key: "init",
value: function init() {
_get(_getPrototypeOf(ListEntry.prototype), "init", this).call(this);
var editor = this.editor;
if (isEngine(editor)) {
editor.on('paste:before', this.pasteBefore);
editor.on('paste:insert', this.pasteInsert);
editor.on('paste:after', this.pasteAfter);
}
}
}, {
key: "queryState",
value: function queryState() {
var editor = this.editor;
if (!isEngine(editor)) return false;
return editor.list.getPluginNameByNodes(editor.change.blocks) === this.constructor.pluginName;
}
}, {
key: "destroy",
value: function destroy() {
var editor = this.editor;
if (isEngine(editor)) {
editor.off('paste:before', this.pasteBefore);
editor.off('paste:insert', this.pasteInsert);
editor.off('paste:after', this.pasteAfter);
}
}
}]);
return ListEntry;
}(BlockEntry);
var MarkEntry = /*#__PURE__*/function (_ElementPluginEntry) {
_inherits(MarkEntry, _ElementPluginEntry);
var _super = _createSuper(MarkEntry);
function MarkEntry() {
var _this;
_classCallCheck(this, MarkEntry);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.kind = 'mark';
_this.copyOnEnter = void 0;
_this.followStyle = true;
_this.combineValueByWrap = false;
_this.mergeLeval = 1;
return _this;
}
_createClass(MarkEntry, [{
key: "execute",
value: function execute() {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
mark = editor.mark;
var markNode = this.createElement.apply(this, arguments);
var trigger = this.isTrigger ? this.isTrigger.apply(this, arguments) : !this.queryState();
if (trigger) {
if (!this.followStyle && change.range.get().collapsed) {
return;
}
mark.wrap(markNode);
} else {
mark.unwrap(markNode);
}
}
}, {
key: "queryState",
value: function queryState() {
var _this2 = this;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change; //如果没有属性和样式限制,直接查询是否包含当前标签名称
if (!this.style && !this.attributes) return change.marks.some(function (node) {
return node.name === _this2.tagName;
}); //获取属性和样式限制内的值集合
var values = [];
change.marks.forEach(function (node) {
values.push.apply(values, _toConsumableArray(Object.values(_this2.getStyle(node))));
values.push.apply(values, _toConsumableArray(Object.values(_this2.getAttributes(node))));
});
return values.length === 0 ? undefined : values;
}
}, {
key: "schema",
value: function schema() {
var schema = _get(_getPrototypeOf(MarkEntry.prototype), "schema", this).call(this);
if (Array.isArray(schema)) {
return schema.map(function (schema) {
return _objectSpread2({}, schema);
});
}
return _objectSpread2({}, schema);
}
}]);
return MarkEntry;
}(ElementPluginEntry);
var isMarkPlugin = function isMarkPlugin(plugin) {
return plugin.kind === 'mark';
};
var PluginModel = /*#__PURE__*/function () {
function PluginModel(editor) {
_classCallCheck(this, PluginModel);
this.data = {};
this.components = {};
this.editor = void 0;
this.editor = editor;
}
_createClass(PluginModel, [{
key: "init",
value: function init(plugins, config) {
var _this = this;
plugins.forEach(function (pluginClazz) {
_this.data[pluginClazz.pluginName] = pluginClazz;
var plugin = new pluginClazz(_this.editor, config[pluginClazz.pluginName]);
_this.components[pluginClazz.pluginName] = plugin;
if (plugin.init) plugin.init();
});
}
}, {
key: "add",
value: function add(clazz, options) {
this.data[clazz.pluginName] = clazz;
options = _objectSpread2({}, options);
var editor = this.editor;
if (isEngine(editor)) {
var plugin = new clazz(editor, options);
if (plugin.init) plugin.init();
this.components[clazz.pluginName] = plugin;
}
}
}, {
key: "findPlugin",
value: function findPlugin(pluginName) {
var plugin = this.components[pluginName];
if (!plugin) return;
return plugin;
}
}, {
key: "findElementPlugin",
value: function findElementPlugin(pluginName) {
var plugin = this.findPlugin(pluginName);
if (!plugin) return;
if (isElementPlugin(plugin)) {
return plugin;
}
return;
}
}, {
key: "findMarkPlugin",
value: function findMarkPlugin(pluginName) {
var plugin = this.findPlugin(pluginName);
if (!plugin) return;
if (isMarkPlugin(plugin)) {
return plugin;
}
return;
}
}, {
key: "findInlinePlugin",
value: function findInlinePlugin(pluginName) {
var plugin = this.findPlugin(pluginName);
if (!plugin) return;
if (isInlinePlugin(plugin)) {
return plugin;
}
return;
}
}, {
key: "findBlockPlugin",
value: function findBlockPlugin(pluginName) {
var plugin = this.findPlugin(pluginName);
if (!plugin) return;
if (isBlockPlugin(plugin)) {
return plugin;
}
return;
}
}, {
key: "each",
value: function each(callback) {
var _this2 = this;
Object.keys(this.data).forEach(function (name, index) {
if (callback && callback(name, _this2.data[name], index) === false) return;
});
}
}, {
key: "destroy",
value: function destroy() {
var _this3 = this;
Object.keys(this.components).forEach(function (pluginName) {
var plugin = _this3.components[pluginName];
if (plugin.destroy) plugin.destroy();
});
}
}]);
return PluginModel;
}();
/**
* 引擎命令管理器
*/
var Command = /*#__PURE__*/function () {
function Command(editor) {
_classCallCheck(this, Command);
this.editor = void 0;
this.editor = editor;
}
/**
* 查询插件是否启用
* @param name 插件名称
* @returns
*/
_createClass(Command, [{
key: "queryEnabled",
value: function queryEnabled(name) {
var editor = this.editor; // 没有插件
var plugin = editor.plugin.components[name];
if (!plugin || plugin.disabled) return false; // 只读状态下,如果插件没有指定为非禁用,一律禁用
if ((!isEngine(editor) || editor.readonly) && plugin.disabled !== false) return false;
var cardApi = editor.card; // 当前激活非可编辑卡片时全部禁用
if (cardApi.active) {
if ((isMarkPlugin(plugin) || plugin.kind === 'plugin') && cardApi.active.executeMark) return true;
if (cardApi.active.isEditable) return true;
return false;
} // TODO:查询当前所处位置的插件
return true;
}
/**
* 查询插件状态
* @param name 插件名称
* @param args 插件 queryState 返回需要的参数
* @returns
*/
}, {
key: "queryState",
value: function queryState(name) {
var editor = this.editor;
var plugin = editor.plugin.components[name];
if (plugin && plugin.queryState) {
try {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return plugin.queryState(args);
} catch (error) {
editor.messageError('command-query', error);
}
}
}
/**
* 执行命令前缓存当前光标位置并且光标不在编辑范围内就focus到编辑区域内
* @returns
*/
}, {
key: "handleExecuteBefore",
value: function handleExecuteBefore() {
var change;
var editor = this.editor;
if (isEngine(editor)) {
change = editor.change;
var range = change.range.get();
if (!range.commonAncestorNode.isRoot() && !range.commonAncestorNode.inEditor()) {
var uiElement = range.commonAncestorNode.closest(UI_SELECTOR);
var component = undefined;
if (uiElement.length > 0) {
var cardId = uiElement.attributes(TRIGGER_CARD_ID);
if (cardId) {
var card = editor.card;
component = card.find(cardId);
if (component) {
card.select(component);
}
}
}
if (!component) editor.focus();
}
change.cacheRangeBeforeCommand();
}
return change;
}
/**
* 执行插件命令
* @param name 插件名称
* @param args 插件所需要的参数
* @returns
*/
}, {
key: "execute",
value: function execute(name) {
var editor = this.editor;
var plugin = editor.plugin.components[name];
if (plugin && plugin.execute) {
var change = this.handleExecuteBefore();
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
editor.trigger.apply(editor, ['beforeCommandExecute', name].concat(args));
try {
var result = plugin.execute.apply(plugin, args);
change === null || change === void 0 ? void 0 : change.combinText();
change === null || change === void 0 ? void 0 : change.onSelect();
editor.trigger.apply(editor, ['afterCommandExecute', name].concat(args));
return result;
} catch (error) {
editor.messageError('command-execute', error);
}
}
}
/**
* 执行插件里面的一个返回
* @param name 插件名称
* @param method 插件中的方法名称
* @param args 插件中方法所需要的参数
* @returns
*/
}, {
key: "executeMethod",
value: function executeMethod(name, method) {
var editor = this.editor;
var plugin = editor.plugin.components[name];
if (plugin && plugin[method]) {
try {
for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
args[_key3 - 2] = arguments[_key3];
}
var result = plugin[method].apply(plugin, args);
return result;
} catch (error) {
editor.messageError('command-excute-method', error);
}
}
}
}]);
return Command;
}();
/**
* 标签规则
*/
var SCHEMA_KEYS = ['blocks', 'inlines', 'marks', 'globals'];
var Schema = /*#__PURE__*/function () {
function Schema() {
_classCallCheck(this, Schema);
this._all = [];
this._typeMap = {};
this._invalidKeys = [];
this._tagMap = {
blocks: [],
inlines: [],
marks: []
};
this.data = {
blocks: [],
inlines: [],
marks: [],
globals: {}
};
}
_createClass(Schema, [{
key: "add",
value:
/**
* 增加规则
* 只有 type 和 attributes 时,将作为此类型全局属性,与其它所有同类型标签属性将合并
* @param rules 规则
* @param merge 是否合并到已有规则下
*/
function add(rules) {
var _this = this;
var isMerge = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
rules = cloneDeep__default['default'](rules);
if (!Array.isArray(rules)) {
rules = [rules];
}
rules.forEach(function (rule) {
var rules = _this.data["".concat(rule.type, "s")];
if (isSchemaRule(rule)) {
//删除全局属性已有的规则
if (rule.attributes) {
Object.keys(rule.attributes).forEach(function (key) {
if (!_this.data.globals[rule.type]) return;
if (key === 'style') {
Object.keys(rule.attributes.style).forEach(function (styleName) {
if (_this.data.globals[rule.type][key] && _this.data.globals[rule.type][key][styleName] === rule.attributes.style[styleName]) {
delete rule.attributes.style[styleName];
}
});
} else if (_this.data.globals[rule.type][key] === rule.attributes[key]) {
delete rule.attributes[key];
}
});
}
if (rules) {
if (isMerge) {
_this.data["".concat(rule.type, "s")] = rules.map(function (item) {
if (item.name === rule.name) {
item.attributes = merge__default['default'](Object.assign({}, item.attributes), rule.attributes);
}
return item;
});
} else {
rules.push(rule);
}
}
} else if (!!rules) {
_this.data.globals[rule.type] = merge__default['default'](Object.assign({}, _this.data.globals[rule.type]), rule.attributes);
}
});
this.updateTagMap(); //按照必要属性个数排序
var getCount = function getCount(rule) {
var aAttributes = rule.attributes || {};
var aStyles = aAttributes.style || {};
var aCount = 0;
var sCount = 0;
Object.keys(aAttributes).forEach(function (attributesName) {
var attributesValue = aAttributes[attributesName];
if (isSchemaValueObject(attributesValue) && attributesValue.required) aCount++;
});
Object.keys(aStyles).forEach(function (stylesName) {
var stylesValue = aStyles[stylesName];
if (isSchemaValueObject(stylesValue) && stylesValue.required) sCount++;
});
return [aCount, sCount];
};
var _this$data = this.data,
blocks = _this$data.blocks,
marks = _this$data.marks,
inlines = _this$data.inlines;
this._all = [].concat(_toConsumableArray(blocks), _toConsumableArray(marks), _toConsumableArray(inlines)).sort(function (a, b) {
var _getCount = getCount(a),
_getCount2 = _slicedToArray(_getCount, 2),
aACount = _getCount2[0],
aSCount = _getCount2[1];
var _getCount3 = getCount(b),
_getCount4 = _slicedToArray(_getCount3, 2),
bACount = _getCount4[0],
bSCount = _getCount4[1];
if (aACount > bACount) return -1;
if (aACount === bACount) return aSCount === bSCount ? 0 : aSCount > bSCount ? -1 : 1;
return 1;
});
}
}, {
key: "updateTagMap",
value: function updateTagMap() {
var _this2 = this;
this._tagMap.marks = [];
this.data.marks.forEach(function (mark) {
if (~~_this2._tagMap.marks.indexOf(mark.name)) {
_this2._tagMap.marks.push(mark.name);
}
});
this._tagMap.blocks = [];
this.data.blocks.forEach(function (block) {
if (~~_this2._tagMap.blocks.indexOf(block.name)) {
_this2._tagMap.blocks.push(block.name);
}
});
this._tagMap.inlines = [];
this.data.inlines.forEach(function (inline) {
if (~~_this2._tagMap.inlines.indexOf(inline.name)) {
_this2._tagMap.inlines.push(inline.name);
}
});
}
}, {
key: "getTags",
value: function getTags(type) {
return this._tagMap[type];
} // 移除一个规则
}, {
key: "remove",
value: function remove(rule) {
var index = this._all.findIndex(function (r) {
return isEqual__default['default'](r, rule);
});
if (index > -1) this._all.splice(index, 1);
var rules = this.data["".concat(rule.type, "s")];
if (rules) {
index = rules.findIndex(function (r) {
return isEqual__default['default'](r, rule);
});
if (index > -1) rules.splice(index, 1);
}
this._typeMap = {};
this.updateTagMap();
}
/**
* 克隆当前schema对象
*/
}, {
key: "clone",
value: function clone() {
var schema = new Schema();
schema._all = cloneDeep__default['default'](this._all);
schema._typeMap = cloneDeep__default['default'](this._typeMap);
schema._tagMap = cloneDeep__default['default'](this._tagMap);
schema.data = cloneDeep__default['default'](this.data);
return schema;
}
/**
* 查找规则
* @param callback 查找条件
*/
}, {
key: "find",
value: function find(callback) {
var _this3 = this;
var schemas = [];
SCHEMA_KEYS.forEach(function (key) {
if (key !== 'globals') {
var rules = _this3.data[key].filter(callback);
schemas.push.apply(schemas, _toConsumableArray(rules));
}
});
return schemas;
}
}, {
key: "getType",
value: function getType(node, filter) {
var element = isNode(node) ? node : node[0];
if (!element || element.nodeType !== Node.ELEMENT_NODE) return undefined;
var id = element.getAttribute(DATA_ID);
if (!id) id = hashId(element, false);else id = id.split('-')[0];
if (element.nodeName !== 'CARD' && ~this._invalidKeys.indexOf(id)) return undefined;
var map = this._typeMap[id];
if (!!map && (!filter || filter(map))) return map.type;
var reuslt = this.getRule(element, filter);
if (reuslt) this._typeMap[id] = reuslt;else this._invalidKeys.push(id);
return reuslt === null || reuslt === void 0 ? void 0 : reuslt.type;
}
/**
* 根据节点获取符合的规则
* @param node 节点
* @param filter 过滤
* @returns
*/
}, {
key: "getRule",
value: function getRule(node, filter) {
var _this4 = this;
var element = isNode(node) ? node : node[0];
filter = filter || function (rule) {
return rule.name === element.localName;
};
return this._all.find(function (rule) {
return filter(rule) && _this4.checkNode(element, rule.attributes);
});
}
/**
* 检测节点是否符合某一属性规则
* @param node 节点
* @param attributes 属性规则
*/
}, {
key: "checkNode",
value: function checkNode(node) {
var attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var element = isNode(node) ? node : node[0]; //需要属性每一项都能效验通过
for (var attributesName in attributes) {
var _element$getAttribute;
if (attributesName === 'style') continue;
var schema = attributes;
if (!schema[attributesName]) return false;
if (!this.checkValue(schema, attributesName, (_element$getAttribute = element.getAttribute(attributesName)) !== null && _element$getAttribute !== void 0 ? _element$getAttribute : undefined)) return false;
}
var nodeStyles = getStyleMap(element.getAttribute('style') || '');
var styles = attributes.style || {};
for (var styleName in styles) {
if (!styles[styleName]) return false;
if (!this.checkValue(styles, styleName, nodeStyles[styleName])) return false;
}
return true;
}
/**
* 检测值是否符合规则
* @param rule 规则
* @param attributesName 属性名称
* @param attributesValue 属性值
*/
}, {
key: "checkValue",
value: function checkValue(schema, attributesName, attributesValue, force) {
if (!schema[attributesName]) return false;
var rule = schema[attributesName];
if (isSchemaValueObject(rule)) {
//如果没有值,强制状态就返回 false,非强制就返回 true
if (attributesValue === undefined) return !rule.required;
rule = rule.value;
} //默认都不为强制的
else if (!force || attributesValue === undefined) return true;
/**
* 自定义规则解析
*/
if (typeof rule === 'string' && rule.charAt(0) === '@') {
switch (rule) {
case '@number':
rule = /^-?\d+(\.\d+)?$/;
break;
case '@length':
rule = /^-?\d+(\.\d+)?(\w*|%)$/;
break;
case '@color':
rule = /^(rgb(.+?)|#\w{3,8}|\w+)$/i;
break;
case '@url':
rule = validUrl;
break;
}
}
/**
* 字符串解析
*/
if (typeof rule === 'string') {
if (rule === '*') {
return true;
}
if (attributesName === 'class') {
return (attributesValue || '').split(/\s+/).some(function (value) {
return value.trim() === rule;
});
}
return rule === attributesValue;
}
/**
* 数组解析
*/
if (Array.isArray(rule)) {
if (attributesName === 'class') {
if (!attributesValue) attributesValue = '*';
return attributesValue.split(/\s+/).every(function (value) {
return value.trim() === '' ? true : ~rule.indexOf(value.trim());
});
}
return rule.indexOf(attributesValue) > -1;
}
/**
* 解析正则表达式
*/
if (_typeof(rule) === 'object' && typeof rule.test === 'function') {
if (attributesName === 'class') {
return (attributesValue || '').split(/\s+/).every(function (value) {
return value.trim() === '' ? true : rule.test(value.trim());
});
}
return rule.test(attributesValue || '');
}
/**
* 自定义函数解析
*/
if (typeof rule === 'function') {
return rule(attributesValue);
}
return true;
}
/**
* 过滤节点样式
* @param styles 样式
* @param rule 规则
*/
}, {
key: "filterStyles",
value: function filterStyles(styles, rule, callback) {
var _this5 = this;
Object.keys(styles).forEach(function (styleName) {
var _rule$attributes;
if (!((_rule$attributes = rule.attributes) === null || _rule$attributes === void 0 ? void 0 : _rule$attributes.style) || !_this5.checkValue(rule.attributes.style, styleName, styles[styleName], true)) {
if (callback) callback(styleName, styles[styleName]);
delete styles[styleName];
}
});
}
/**
* 过滤节点属性
* @param attributes 属性
* @param rule 规则
*/
}, {
key: "filterAttributes",
value: function filterAttributes(attributes, rule, callback) {
var _this6 = this;
Object.keys(attributes).forEach(function (attributesName) {
if (!rule.attributes || !_this6.checkValue(rule.attributes, attributesName, attributes[attributesName], true)) {
if (callback) callback(attributesName, attributes[attributesName]);
delete attributes[attributesName];
}
});
}
/**
* 过滤满足node节点规则的属性和样式
* @param node 节点,用于获取规则
* @param attributes 属性
* @param styles 样式
* @param apply 是否把过滤的属性和样式应用到节点上
* @returns
*/
}, {
key: "filter",
value: function filter(node, attributes, styles) {
var apply = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var rule = this.getRule(node);
if (!rule) return;
var globals = this.data.globals;
var globalRule = globals[rule.type] ? rule.type : undefined;
var allRule = Object.assign({}, rule, {
attributes: merge__default['default']({}, rule.attributes, globalRule ? globals[globalRule] : {})
});
this.filterAttributes(attributes, allRule, apply ? function (name) {
return node.removeAttributes(name);
} : undefined);
this.filterStyles(styles, allRule, apply ? function (name) {
return node.css(name, '');
} : undefined);
}
/**
* 查找节点符合规则的最顶层的节点名称
* @param name 节点名称
* @param callback 回调函数,判断是否继续向上查找,返回false继续查找
* @returns 最顶级的block节点名称
*/
}, {
key: "closest",
value: function closest(name) {
var _this7 = this;
var topName = name;
this.data.blocks.forEach(function (block) {
if (block.name !== name) return;
var schema = block;
if (schema.allowIn) {
schema.allowIn.forEach(function (parentName) {
if (_this7.isAllowIn(parentName, topName)) {
topName = parentName;
}
});
topName = _this7.closest(topName);
}
});
return topName;
}
/**
* 判断子节点名称是否允许放入指定的父节点中
* @param source 父节点名称
* @param target 子节点名称
* @returns true | false
*/
}, {
key: "isAllowIn",
value: function isAllowIn(source, target) {
//p节点下不允许放其它block节点
if (source === 'p') return false;
return this.data.blocks.some(function (block) {
if (block.name !== target) return;
var schema = block;
if (schema.allowIn && schema.allowIn.indexOf(source) > -1) {
return true;
}
return;
});
}
}, {
key: "addAllowIn",
value: function addAllowIn(parent) {
var child = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'p';
var rule = this.data.blocks.find(function (rule) {
return rule.name === child;
});
if (!rule.allowIn) {
rule.allowIn = [];
}
if (~~rule.allowIn.indexOf(parent)) {
rule.allowIn.push(parent);
}
}
/**
* 获取允许有子block节点的标签集合
* @returns
*/
}, {
key: "getAllowInTags",
value: function getAllowInTags() {
var tags = [];
this.data.blocks.forEach(function (rule) {
var schema = rule;
if (schema.allowIn) {
schema.allowIn.forEach(function (name) {
if (tags.indexOf(name) < 0) tags.push(name);
});
}
});
return tags;
}
/**
* 获取能够合并的block节点的标签集合
* @returns
*/
}, {
key: "getCanMergeTags",
value: function getCanMergeTags() {
var tags = [];
this.data.blocks.forEach(function (rule) {
var schema = rule;
if (schema.canMerge === true) {
if (tags.indexOf(schema.name) < 0) tags.push(schema.name);
}
});
return tags;
}
}]);
return Schema;
}();
var isSchemaValueObject = function isSchemaValueObject(value) {
return value.required !== undefined;
};
var isSchemaRule = function isSchemaRule(rule) {
return !!rule['name'];
};
var Conversion = /*#__PURE__*/function () {
function Conversion(editor) {
_classCallCheck(this, Conversion);
this.editor = void 0;
this.data = [];
this.editor = editor;
}
_createClass(Conversion, [{
key: "getData",
value: function getData() {
return this.data;
}
}, {
key: "clone",
value: function clone() {
var dupData = cloneDeep__default['default'](this.data);
var dupConversion = new Conversion(this.editor);
dupConversion.data = dupData;
return dupConversion;
}
}, {
key: "add",
value: function add(from, to) {
this.data.push({
from: from,
to: to
});
}
}, {
key: "transform",
value: function transform(node, filter) {
var name = node.name;
var attributes = node.attributes();
var style = getStyleMap(attributes.style || '');
var replace = false; //删除属性中的style属性
delete attributes.style; // 光标相关节点
if (node.isCursor()) {
name = attributes[DATA_ELEMENT].toLowerCase();
attributes = {};
style = {};
}
var rule = this.data.find(function (item) {
if (filter && !filter(item)) return;
var from = item.from,
to = item.to;
var result = false;
if (typeof from === 'string') {
result = from === name;
} else if (typeof from === 'function') {
result = from(name, style, attributes);
} else {
var elementNames = Object.keys(from);
result = elementNames.indexOf(name) >= 0 && elementNames.some(function (elementName) {
var elementRules = from[elementName];
return Object.keys(elementRules.style || {}).every(function (styleName) {
var styleValue = elementRules.style[styleName];
return !!style[styleName] && Array.isArray(styleValue) ? styleValue.indexOf(style[styleName]) > -1 : styleValue === style[styleName];
}) && Object.keys(elementRules.attributes || {}).every(function (attributesName) {
var attributesValue = elementRules.attributes[attributesName];
return !!style[attributesName] && Array.isArray(attributesValue) ? attributesValue.indexOf(style[attributesName]) > -1 : attributesValue === style[attributesName];
});
});
}
if (result) {
if (typeof to === 'string') {
name = to;
style = {};
attributes = {};
} else {
var _result = typeof to === 'function' ? to(name, style, attributes) : to;
var resultNode = _result;
if (_result.hasOwnProperty('replace')) {
var newResult = _result;
resultNode = newResult.node;
replace = newResult.replace;
}
name = resultNode.name;
style = resultNode.css();
attributes = resultNode.attributes();
}
}
return result;
});
return rule ? {
rule: rule,
node: {
name: name,
style: style,
attributes: attributes
},
replace: replace
} : undefined;
}
}]);
return Conversion;
}();
var Enter$2 = /*#__PURE__*/function () {
function Enter(engine) {
_classCallCheck(this, Enter);
this.engine = void 0;
this.engine = engine;
}
/**
* 在卡片处插入空段落
* @param range 光标
* @param card 卡片
* @param isStart 是否聚焦到开始位置
*/
_createClass(Enter, [{
key: "insertNewline",
value: function insertNewline(range, card, isStart) {
var change = this.engine.change;
var emptyBlock = $('
');
this.engine.nodeId.generate(emptyBlock);
if (isStart) {
card.root.before(emptyBlock);
} else {
card.root.after(emptyBlock);
}
range.select(emptyBlock, true);
range.collapse(false);
change.range.select(range);
}
/**
* 在卡片节点处按下enter键
*/
}, {
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
card = _this$engine.card;
var range = change.range.get(); // 查找当前光标所在卡片
var component = card.find(range.startNode);
if (!component) return true;
if (component.type === exports.CardType.INLINE) {
// 左侧光标
var cardLeft = range.startNode.closest(CARD_LEFT_SELECTOR);
if (cardLeft.length > 0) {
range.select(component.root);
range.collapse(true);
change.range.select(range);
} // 右侧光标
var cardRight = range.startNode.closest(CARD_RIGHT_SELECTOR);
if (cardRight.length > 0) {
range.select(component.root);
range.collapse(false);
change.range.select(range);
}
} else {
// 左侧光标
var _cardLeft = range.startNode.closest(CARD_LEFT_SELECTOR);
if (_cardLeft.length > 0) {
event.preventDefault();
var prev = component.root.prev();
if (!prev || prev.isCard()) {
card.focusPrevBlock(component, range, true);
change.range.select(range);
} else {
this.insertNewline(range, component, true);
}
return false;
} // 右侧光标
var _cardRight = range.startNode.closest(CARD_RIGHT_SELECTOR);
if (_cardRight.length > 0) {
event.preventDefault();
var next = component.root.next();
if (!next || next.isCard()) {
card.focusNextBlock(component, range, true);
change.range.select(range);
} else {
this.insertNewline(range, component, false);
}
return false;
}
}
return true;
}
}]);
return Enter;
}();
var Backspace$2 = /*#__PURE__*/function () {
function Backspace(engine) {
_classCallCheck(this, Backspace);
this.engine = void 0;
this.engine = engine;
}
/**
* 焦点移动到当前光标最接近的block节点或传入的节点前一个 Block
* @param block 节点
* @param isRemoveEmptyBlock 如果前一个block为空是否删除,默认为否
*/
_createClass(Backspace, [{
key: "focusPrevBlock",
value: function focusPrevBlock(block) {
var isRemoveEmptyBlock = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var change = this.engine.change;
var range = change.range.get();
block = block || this.engine.block.closest(range.startNode);
var prevBlock = block.prev();
if (!prevBlock) {
return;
} // 前面是Card
if (prevBlock.isCard()) {
var card = this.engine.card.find(prevBlock);
if (card) card.focus(range);
return;
} // 前面是列表
if (this.engine.node.isList(prevBlock)) {
prevBlock = prevBlock.last();
}
if (!prevBlock) {
return;
}
if (isRemoveEmptyBlock && this.engine.node.isEmptyWithTrim(prevBlock)) {
prevBlock.remove();
return;
}
range.select(prevBlock, true);
range.collapse(false);
change.range.select(range.shrinkToTextNode());
}
/**
* 在卡片节点处按下backspace键
*/
}, {
key: "trigger",
value: function trigger(event) {
var change = this.engine.change;
var range = change.range.get().cloneRange().shrinkToElementNode().shrinkToTextNode();
if (!range.collapsed) return; // 查找当前光标所在卡片
var card = this.engine.card.find(range.startNode);
if (!card) {
// 光标前面有Card,并且不是自定义列表,移除卡片
var prevNode = range.getPrevNode();
var prevParent = prevNode === null || prevNode === void 0 ? void 0 : prevNode.parent();
if (!event['isDelete'] && prevNode && prevNode.isCard() && (!prevParent || !this.engine.node.isCustomize(prevParent))) {
event.preventDefault();
var cloneRange = range.cloneRange();
cloneRange.setStartBefore(prevNode);
cloneRange.collapse(true);
this.engine.card.remove(prevNode);
change.range.select(cloneRange.shrinkToTextNode());
cloneRange.handleBr();
return false;
}
return true;
}
if (event['isDelete']) return true; // inline 卡片
if (card.type === exports.CardType.INLINE) {
// 左侧光标
var cardLeft = range.startNode.closest(CARD_LEFT_SELECTOR);
if (cardLeft.length > 0) {
var prev = card.root.prev();
if (!prev) {
event.preventDefault();
change.mergeAfterDelete();
return false;
} else {
// 左侧还是卡片删除卡片
var leftCard = this.engine.card.find(prev);
if (leftCard) {
this.engine.card.remove(leftCard.id);
range.handleBr();
return false;
}
range.select(card.root).collapse(true);
}
change.range.select(range);
} // 右侧光标
var cardRight = range.startNode.closest(CARD_RIGHT_SELECTOR);
if (cardRight.length > 0) {
event.preventDefault();
var _cloneRange = range.cloneRange();
_cloneRange.setStartBefore(card.root);
_cloneRange.collapse(true);
this.engine.card.remove(card.id);
change.range.select(_cloneRange.shrinkToTextNode());
_cloneRange.handleBr();
return false;
}
} else {
// 左侧光标
var _cardLeft = range.startNode.closest(CARD_LEFT_SELECTOR);
if (_cardLeft.length > 0) {
var _card$root$parent;
event.preventDefault();
if ((_card$root$parent = card.root.parent()) === null || _card$root$parent === void 0 ? void 0 : _card$root$parent.inEditor()) {
change.unwrap(card.root.parent());
} else {
this.focusPrevBlock(card.root, true);
}
return false;
} // 右侧光标
var _cardRight = range.startNode.closest(CARD_RIGHT_SELECTOR);
if (_cardRight.length > 0) {
event.preventDefault();
this.focusPrevBlock(card.root);
this.engine.card.remove(card.id, false);
if (change.isEmpty()) {
change.initValue();
}
return false;
}
} //改变了光标选区,再次触发事件
if (this.engine.trigger('keydown:backspace', event) === false) return false;
return true;
}
}]);
return Backspace;
}();
var Left$1 = /*#__PURE__*/function () {
function Left(engine) {
_classCallCheck(this, Left);
this.engine = void 0;
this.engine = engine;
}
_createClass(Left, [{
key: "inline",
value: function inline(card, event) {
var change = this.engine.change;
var range = change.range.get().cloneRange();
var singleSelectable = card.constructor.singleSelectable; // 左侧光标
var cardLeft = range.commonAncestorNode.closest(CARD_LEFT_SELECTOR);
if (cardLeft.length > 0) {
var prev = card.root.prev();
if (!prev) {
card.focus(range, true);
} else {
range.setStartBefore(card.root[0]);
range.collapse(true);
}
change.range.select(range);
return true;
} // 右侧光标
var cardRight = range.commonAncestorNode.closest(CARD_RIGHT_SELECTOR);
var isCenter = cardLeft.length === 0 && cardRight.length === 0;
if (cardRight.length > 0 || isCenter) {
event.preventDefault();
if (isCenter) {
var _card$toolbarModel;
card.select(false);
(_card$toolbarModel = card.toolbarModel) === null || _card$toolbarModel === void 0 ? void 0 : _card$toolbarModel.hide();
card.activate(false);
} else if (range.collapsed) {
var cardComponent = this.engine.card.find(range.startNode);
if (cardComponent && cardComponent.onSelectLeft) {
return cardComponent.onSelectLeft(event);
}
}
if (!isCenter && singleSelectable !== false) {
this.engine.card.select(card, event);
} else {
var _card$toolbarModel2;
card.focus(range, true);
card.select(false);
(_card$toolbarModel2 = card.toolbarModel) === null || _card$toolbarModel2 === void 0 ? void 0 : _card$toolbarModel2.hide();
change.range.select(range);
}
return false;
}
return true;
}
}, {
key: "block",
value: function block(component, event) {
var _this$engine = this.engine,
change = _this$engine.change,
card = _this$engine.card;
var range = change.range.get(); // 左侧光标
var cardLeft = range.commonAncestorNode.closest(CARD_LEFT_SELECTOR);
if (cardLeft.length > 0) {
var prev = component.root.prev();
if (prev) {
event.preventDefault();
card.focusPrevBlock(component, range, false);
change.range.select(range);
return false;
}
return;
} // 右侧光标
var cardRight = range.commonAncestorNode.closest(CARD_RIGHT_SELECTOR);
var isCenter = cardLeft.length === 0 && cardRight.length === 0;
if (isCenter) {
var _component$toolbarMod;
component.select(false);
(_component$toolbarMod = component.toolbarModel) === null || _component$toolbarMod === void 0 ? void 0 : _component$toolbarMod.hide();
component.activate(false);
}
if (cardRight.length > 0) {
if (range.collapsed) {
var cardComponent = card.find(range.startNode);
if (cardComponent && cardComponent.onSelectLeft) {
return cardComponent.onSelectLeft(event);
}
}
event.preventDefault();
card.select(component, event);
return false;
}
if (card.getSingleSelectedCard(range)) {
var _component$toolbarMod2;
event.preventDefault();
component.focus(range, true);
component.select(false);
(_component$toolbarMod2 = component.toolbarModel) === null || _component$toolbarMod2 === void 0 ? void 0 : _component$toolbarMod2.hide();
change.range.select(range);
return false;
}
return true;
}
}, {
key: "fincPrevCard",
value: function fincPrevCard(range) {
if (!range.collapsed) return null;
var startNode = range.startNode,
startOffset = range.startOffset;
if (startNode.isText() && startOffset === 0) {
var prev = startNode.prevElement();
if (prev && prev.isCard()) {
return this.engine.card.find(prev);
}
}
return null;
}
}, {
key: "trigger",
value: function trigger(event) {
var change = this.engine.change;
var range = change.range.get();
var card = this.engine.card.getSingleCard(range);
if (!card) {
var prevCard = this.fincPrevCard(range);
if (prevCard) {
event.preventDefault();
prevCard.focus(range, false);
change.range.select(range);
return false;
}
return true;
}
if (isHotkey__default['default']('shift+left', event)) {
return false;
}
return card.type === exports.CardType.INLINE ? this.inline(card, event) : this.block(card, event);
}
}]);
return Left;
}();
var Right$1 = /*#__PURE__*/function () {
function Right(engine) {
_classCallCheck(this, Right);
this.engine = void 0;
this.engine = engine;
}
_createClass(Right, [{
key: "inline",
value: function inline(card, event) {
var change = this.engine.change;
var range = change.range.get();
var singleSelectable = card.constructor.singleSelectable; // 左侧光标
var cardLeft = range.commonAncestorNode.closest(CARD_LEFT_SELECTOR);
var cardRight = range.commonAncestorNode.closest(CARD_RIGHT_SELECTOR);
var isCenter = cardLeft.length === 0 && cardRight.length === 0;
if (cardLeft.length > 0 || isCenter) {
event.preventDefault();
if (isCenter) {
var _card$toolbarModel;
card.select(false);
card.activate(false);
(_card$toolbarModel = card.toolbarModel) === null || _card$toolbarModel === void 0 ? void 0 : _card$toolbarModel.hide();
} else if (range.collapsed) {
var cardComponent = this.engine.card.find(range.startNode);
if (cardComponent && cardComponent.onSelectRight) {
return cardComponent.onSelectRight(event);
}
}
if (!isCenter && singleSelectable !== false) {
this.engine.card.select(card, event);
} else {
var _card$toolbarModel2;
card.focus(range, false);
card.select(false);
(_card$toolbarModel2 = card.toolbarModel) === null || _card$toolbarModel2 === void 0 ? void 0 : _card$toolbarModel2.hide();
change.range.select(range);
}
return false;
} // 右侧光标
if (cardRight.length > 0) {
var next = card.root.next();
if (!next) {
card.focus(range, false);
} else {
range.setEndAfter(card.root[0]);
range.collapse(false);
}
change.range.select(range);
}
return true;
}
}, {
key: "block",
value: function block(component, event) {
var _this$engine = this.engine,
change = _this$engine.change,
card = _this$engine.card;
var range = change.range.get(); // 左侧光标
var cardLeft = range.commonAncestorNode.closest(CARD_LEFT_SELECTOR);
if (cardLeft.length > 0) {
if (range.collapsed) {
var cardComponent = this.engine.card.find(range.startNode);
if (cardComponent && cardComponent.onSelectRight) {
return cardComponent.onSelectRight(event);
}
}
event.preventDefault();
card.select(component, event);
return false;
} // 右侧光标
var cardRight = range.commonAncestorNode.closest(CARD_RIGHT_SELECTOR);
var isCenter = cardLeft.length === 0 && cardRight.length === 0;
if (isCenter) {
var _component$toolbarMod;
component.select(false);
(_component$toolbarMod = component.toolbarModel) === null || _component$toolbarMod === void 0 ? void 0 : _component$toolbarMod.hide();
component.activate(false);
}
if (cardRight.length > 0) {
var next = component.root.next();
if (next) {
event.preventDefault();
card.focusNextBlock(component, range, false);
change.range.select(range);
return false;
}
return;
}
if (this.engine.card.getSingleSelectedCard(range)) {
var _component$toolbarMod2;
event.preventDefault();
component.focus(range, false);
component.select(false);
(_component$toolbarMod2 = component.toolbarModel) === null || _component$toolbarMod2 === void 0 ? void 0 : _component$toolbarMod2.hide();
change.range.select(range);
return false;
}
return true;
}
}, {
key: "fincNextCard",
value: function fincNextCard(range) {
if (!range.collapsed) return null;
var startNode = range.startNode,
startOffset = range.startOffset;
if (startNode.isText()) {
var text = startNode.text();
if (text.length === startOffset) {
var next = startNode.nextElement();
if (next && next.isCard()) {
return this.engine.card.find(next);
}
}
}
return null;
}
}, {
key: "trigger",
value: function trigger(event) {
var change = this.engine.change;
var range = change.range.get();
var card = this.engine.card.getSingleCard(range);
if (!card) {
var nextCard = this.fincNextCard(range);
if (nextCard) {
event.preventDefault();
nextCard.focus(range, true);
change.range.select(range);
return false;
}
return true;
}
if (isHotkey__default['default']('shift+right', event)) {
return;
}
return card.type === exports.CardType.INLINE ? this.inline(card, event) : this.block(card, event);
}
}]);
return Right;
}();
var unactivateCard = function unactivateCard(engine, component) {
var change = engine.change;
var range = change.range.get();
var cardLeft = range.commonAncestorNode.closest(CARD_LEFT_SELECTOR);
var cardRight = range.commonAncestorNode.closest(CARD_RIGHT_SELECTOR);
var isCenter = cardLeft.length === 0 && cardRight.length === 0;
if (isCenter) {
var _component$toolbarMod;
component.select(false);
component.activate(false);
(_component$toolbarMod = component.toolbarModel) === null || _component$toolbarMod === void 0 ? void 0 : _component$toolbarMod.hide();
return true;
}
return false;
};
var Up$1 = /*#__PURE__*/function () {
function Up(engine) {
_classCallCheck(this, Up);
this.engine = void 0;
this.engine = engine;
}
_createClass(Up, [{
key: "common",
value: function common(component, event) {
var _this$engine = this.engine,
change = _this$engine.change,
card = _this$engine.card;
var range = change.range.get();
unactivateCard(this.engine, component);
var prev = component.root.prev();
if (prev) {
event.preventDefault();
card.focusPrevBlock(component, range, false);
change.range.select(range);
return false;
}
return;
}
}, {
key: "inline",
value: function inline(component, event) {
return this.common(component, event);
}
}, {
key: "block",
value: function block(component, event) {
return this.common(component, event);
}
}, {
key: "trigger",
value: function trigger(event) {
var _this$engine2 = this.engine,
change = _this$engine2.change,
card = _this$engine2.card,
block = _this$engine2.block;
var range = change.range.get();
if (range.collapsed) {
var closetBlock = block.closest(range.startNode);
var prev = closetBlock.prev();
if (prev === null || prev === void 0 ? void 0 : prev.isCard()) {
var cardComponent = card.find(prev);
if (cardComponent && cardComponent.onSelectUp) {
return cardComponent.onSelectUp(event);
}
}
}
var singleCard = card.getSingleCard(range);
if (!singleCard) {
return true;
}
if (isHotkey__default['default']('shift+up', event)) {
return;
}
return singleCard.type === exports.CardType.INLINE ? this.inline(singleCard, event) : this.block(singleCard, event);
}
}]);
return Up;
}();
var Down$1 = /*#__PURE__*/function () {
function Down(engine) {
_classCallCheck(this, Down);
this.engine = void 0;
this.engine = engine;
}
_createClass(Down, [{
key: "common",
value: function common(component, event) {
var _this$engine = this.engine,
change = _this$engine.change,
card = _this$engine.card;
var range = change.range.get();
unactivateCard(this.engine, component);
var next = component.root.next();
if (next) {
event.preventDefault();
card.focusNextBlock(component, range, false);
change.range.select(range);
return false;
}
return;
}
}, {
key: "inline",
value: function inline(component, event) {
return this.common(component, event);
}
}, {
key: "block",
value: function block(component, event) {
return this.common(component, event);
}
}, {
key: "trigger",
value: function trigger(event) {
var _this$engine2 = this.engine,
change = _this$engine2.change,
block = _this$engine2.block,
card = _this$engine2.card;
var range = change.range.get();
var singleCard = card.getSingleCard(range);
if (range.collapsed) {
var closetBlock = block.closest(range.startNode);
var next = closetBlock.next();
if (next === null || next === void 0 ? void 0 : next.isCard()) {
var cardComponent = card.find(next);
if (cardComponent && cardComponent.onSelectDown) {
return cardComponent.onSelectDown(event);
}
}
}
if (!singleCard) {
return true;
}
if (isHotkey__default['default']('shift+down', event)) {
return true;
}
return singleCard.type === exports.CardType.INLINE ? this.inline(singleCard, event) : this.block(singleCard, event);
}
}]);
return Down;
}();
var Default = /*#__PURE__*/function () {
function Default(engine) {
_classCallCheck(this, Default);
this.engine = void 0;
this.engine = engine;
}
_createClass(Default, [{
key: "block",
value: function block(component, event) {
var _this$engine = this.engine,
change = _this$engine.change,
card = _this$engine.card;
var range = change.range.get(); // 左侧光标
var cardLeft = range.commonAncestorNode.closest(CARD_LEFT_SELECTOR);
if (cardLeft.length > 0) {
// 其它情况
if (!event.metaKey && !event.ctrlKey) {
card.focusPrevBlock(component, range, true);
change.range.select(range);
}
return true;
} // 右侧光标
var cardRight = range.commonAncestorNode.closest(CARD_RIGHT_SELECTOR);
if (cardRight.length > 0) {
// 其它情况
if (!event.metaKey && !event.ctrlKey) {
card.focusNextBlock(component, range, true);
change.range.select(range);
}
}
return true;
}
}, {
key: "trigger",
value: function trigger(event) {
var change = this.engine.change;
var range = change.range.get();
var card = this.engine.card.getSingleCard(range);
if (!card) return true;
if (card.type === exports.CardType.BLOCK) return this.block(card, event);
return true;
}
}]);
return Default;
}();
var css_248z$5 = ".am-engine .card-selected [data-card-element=\"center\"].data-card-background-selected {\n background: rgba(27, 162, 227, 0.2);\n}\n\n.am-engine .card-selected [data-card-element=\"center\"].data-card-border-selected {\n outline: 2px solid #1890FF;\n border-radius: 2px;\n}\n\n.am-engine .card-selected [data-card-element=\"center\"].data-card-border-selected::-moz-selection {\n background: transparent;\n}\n\n.am-engine .card-selected [data-card-element=\"center\"].data-card-border-selected::selection {\n background: transparent;\n}\n\n.am-engine-view [data-card-element=\"center\"] .data-card-loading,.am-engine [data-card-element=\"center\"] .data-card-loading {\n display: inline-block;\n font-style: normal;\n vertical-align: -0.125em;\n text-align: center;\n text-transform: none;\n line-height: 0;\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n margin-right: 5px;\n padding: 16px;\n width: 100%;\n}\n\n.am-engine-view [data-card-element=\"center\"] .data-card-loading .data-card-spin,.am-engine [data-card-element=\"center\"] .data-card-loading .data-card-spin {\n display: inline-block;\n -webkit-animation: loadingCircle 1s infinite linear;\n animation: loadingCircle 1s infinite linear;\n}\n";
styleInject(css_248z$5);
var CardModel = /*#__PURE__*/function () {
function CardModel(_editor) {
var _this = this;
var lazyRender = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
_classCallCheck(this, CardModel);
this.classes = void 0;
this.components = void 0;
this.lazyRender = void 0;
this.asyncComponents = [];
this.editor = void 0;
this.renderTimeout = void 0;
this.renderAsyncComponents = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var editor;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (_this.renderTimeout) clearTimeout(_this.renderTimeout);
editor = _this.editor;
_this.renderTimeout = setTimeout(function () {
var components = _this.asyncComponents.concat();
components.forEach( /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(card) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
// 在视图内才渲染卡片
if (card.root.length === 0 || editor.root.inViewport(card.root, true) && editor.trigger('card:async-render-component', card) !== false) {
_this.asyncComponents.splice(_this.asyncComponents.findIndex(function (component) {
return component === card;
}), 1);
if (card.root.length > 0 && card.loading) {
if (card.destroy) card.destroy();
card.getCenter().empty();
_this.renderComponent(card);
}
}
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref2.apply(this, arguments);
};
}());
}, 50);
case 3:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
this.classes = {};
this.components = [];
this.editor = _editor;
this.lazyRender = lazyRender;
}
_createClass(CardModel, [{
key: "active",
get: function get() {
return this.components.find(function (component) {
return component.activated;
});
}
}, {
key: "length",
get: function get() {
return this.components.length;
}
}, {
key: "init",
value: function init(cards) {
var _this2 = this,
_editor$scrollNode,
_editor$scrollNode$ge;
var editor = this.editor;
if (isEngine(editor)) {
var _typing$getHandleList, _typing$getHandleList2, _typing$getHandleList3, _typing$getHandleList4, _typing$getHandleList5, _typing$getHandleList6, _typing$getHandleList7;
var typing = editor.typing; //绑定回车事件
var enter = new Enter$2(editor);
(_typing$getHandleList = typing.getHandleListener('enter', 'keydown')) === null || _typing$getHandleList === void 0 ? void 0 : _typing$getHandleList.on(function (event) {
return enter.trigger(event);
}); //删除事件
var backspace = new Backspace$2(editor);
(_typing$getHandleList2 = typing.getHandleListener('backspace', 'keydown')) === null || _typing$getHandleList2 === void 0 ? void 0 : _typing$getHandleList2.on(function (event) {
return backspace.trigger(event);
}); //方向键事件
var left = new Left$1(editor);
(_typing$getHandleList3 = typing.getHandleListener('left', 'keydown')) === null || _typing$getHandleList3 === void 0 ? void 0 : _typing$getHandleList3.on(function (event) {
return left.trigger(event);
});
var right = new Right$1(editor);
(_typing$getHandleList4 = typing.getHandleListener('right', 'keydown')) === null || _typing$getHandleList4 === void 0 ? void 0 : _typing$getHandleList4.on(function (event) {
return right.trigger(event);
});
var up = new Up$1(editor);
(_typing$getHandleList5 = typing.getHandleListener('up', 'keydown')) === null || _typing$getHandleList5 === void 0 ? void 0 : _typing$getHandleList5.on(function (event) {
return up.trigger(event);
});
var down = new Down$1(editor);
(_typing$getHandleList6 = typing.getHandleListener('down', 'keydown')) === null || _typing$getHandleList6 === void 0 ? void 0 : _typing$getHandleList6.on(function (event) {
return down.trigger(event);
});
var _default = new Default(editor);
(_typing$getHandleList7 = typing.getHandleListener('default', 'keydown')) === null || _typing$getHandleList7 === void 0 ? void 0 : _typing$getHandleList7.on(function (event) {
return _default.trigger(event);
});
}
cards.forEach(function (card) {
_this2.classes[card.cardName] = card;
});
if (!this.lazyRender) return;
window.addEventListener('resize', this.renderAsyncComponents, {
passive: true
});
(_editor$scrollNode = editor.scrollNode) === null || _editor$scrollNode === void 0 ? void 0 : (_editor$scrollNode$ge = _editor$scrollNode.get()) === null || _editor$scrollNode$ge === void 0 ? void 0 : _editor$scrollNode$ge.addEventListener('scroll', this.renderAsyncComponents, {
passive: true
});
window.addEventListener('scroll', this.renderAsyncComponents, {
passive: true
});
editor.on('card:async-render', this.renderAsyncComponents);
}
}, {
key: "add",
value: function add(clazz) {
this.classes[clazz.cardName] = clazz;
}
}, {
key: "each",
value: function each(callback) {
this.components.every(function (card, index) {
if (callback && callback(card, index) === false) return false;
return true;
});
}
}, {
key: "closest",
value: function closest(selector, ignoreEditable) {
if (isNode(selector)) selector = $(selector);
if (!selector.isCard()) {
var card = selector.closest(CARD_SELECTOR, function (node) {
var _node$parentElement;
if (node && ignoreEditable ? $(node).isRoot() : $(node).isEditable()) {
return;
}
return ((_node$parentElement = node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : node.parentNode) || undefined;
});
if (!card || card.length === 0) return;
selector = card;
}
return selector;
}
}, {
key: "find",
value: function find(selector, ignoreEditable) {
if (typeof selector !== 'string') {
var cardNode = this.closest(selector, ignoreEditable);
if (!cardNode) return;
selector = cardNode;
}
var getValue = function getValue(node) {
if (isNode(node)) node = $(node);
var value = node.attributes(CARD_VALUE_KEY);
return decodeCardValue(value);
};
var cards = this.components.filter(function (item) {
if (typeof selector === 'string') return item.id === selector;
if (item.root.name !== (isNode(selector) ? selector.nodeName.toString().toLowerCase() : selector.name)) return false;
return item.root.equal(selector) || item.id === getValue(selector).id;
});
if (cards.length === 0) return;
return cards[0];
}
}, {
key: "findBlock",
value: function findBlock(selector) {
if (isNode(selector)) selector = $(selector);
if (!selector.get()) return;
var parent = selector.parent();
if (!parent) return;
var card = this.find(parent);
if (!card) return;
if (card.type === exports.CardType.BLOCK) return card;
return this.findBlock(card.root);
}
}, {
key: "getSingleCard",
value: function getSingleCard(range) {
var card = this.find(range.commonAncestorNode);
if (!card) card = this.getSingleSelectedCard(range);
return card;
}
}, {
key: "getSingleSelectedCard",
value: function getSingleSelectedCard(range) {
var elements = range.findElements();
var node = elements[0];
if (elements.length === 1 && node) {
var domNode = $(node);
if (domNode.isCard()) {
return this.find(domNode);
}
}
return;
} // 插入Card
}, {
key: "insertNode",
value: function insertNode(range, card) {
var isInline = card.type === 'inline';
var editor = this.editor; // 范围为折叠状态时先删除内容
if (!range.collapsed && isEngine(editor)) {
editor.change.delete(range);
}
this.gc();
var inline = editor.inline,
block = editor.block,
node = editor.node; // 插入新 Card
var marks = [];
if (isInline) {
if (isEngine(editor) && card.executeMark) {
marks = editor.change.marks.map(function (mark) {
return mark.clone();
});
var cardComponent = editor.card.find(range.startNode);
if (cardComponent === null || cardComponent === void 0 ? void 0 : cardComponent.queryMarks) {
var _marks;
(_marks = marks).push.apply(_marks, _toConsumableArray(cardComponent.queryMarks()));
}
}
inline.insert(card.root, range);
} else {
block.insert(card.root, range, function (container) {
//获取最外层的block嵌套节点
var blockParent = container.parent();
while (blockParent && !blockParent.isEditable()) {
container = blockParent;
var parent = blockParent.parent();
if (parent && node.isBlock(parent)) {
blockParent = parent;
} else break;
}
return container;
}, true);
}
this.components.push(card); // 矫正错误 HTML 结构
var rootParent = card.root.parent();
if (!isInline && rootParent && rootParent.inEditor() && node.isBlock(rootParent)) {
block.unwrap(rootParent, range);
}
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
this.renderComponent.apply(this, [card].concat(args));
card.focus(range, false);
if (card.didInsert) {
card.didInsert();
}
marks.forEach(function (mark) {
card.executeMark(mark, true);
});
return card;
} // 移除Card
}, {
key: "removeNode",
value: function removeNode(card) {
if (card.destroy) card.destroy();
this.removeComponent(card);
card.root.remove();
} // 更新Card
}, {
key: "updateNode",
value: function updateNode(card, value) {
if (card.destroy) card.destroy();
var center = card.getCenter();
center === null || center === void 0 ? void 0 : center.empty();
card.setValue(value);
for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
this.renderComponent.apply(this, [card].concat(args));
if (card.didUpdate) {
card.didUpdate();
}
} // 将指定节点替换成等待创建的Card DOM 节点
}, {
key: "replaceNode",
value: function replaceNode(node, name, value) {
var clazz = this.classes[name];
if (!clazz) throw ''.concat(name, ': This card does not exist');
var type = (value === null || value === void 0 ? void 0 : value.type) || clazz.cardType;
var dataId = node.attributes(DATA_ID);
var cardNode = transformCustomTags(""));
var readyCard = $(cardNode);
node.before(readyCard);
readyCard.append(node);
return readyCard;
}
}, {
key: "activate",
value: function activate(node, trigger, event) {
var editor = this.editor;
if (!isEngine(editor) || editor.readonly) return; //获取当前卡片所在编辑器的根节点
var container = node.getRoot();
var active = this.active; //如果当前编辑器根节点和引擎的根节点不匹配就不执行,主要是子父编辑器的情况
if (!container.get() || editor.container.equal(container)) {
var card = this.find(node);
var editableElement = node.closest(EDITABLE_SELECTOR);
if (!card && editableElement.length > 0) {
var editableParent = editableElement.parent();
card = editableParent ? this.find(editableParent) : undefined;
}
var blockCard = card ? this.findBlock(card.root) : undefined;
if (blockCard) {
card = blockCard;
}
if (card && card.isCursor(node)) {
if (editableElement.length > 0) {
var _editableParent = editableElement.parent();
card = _editableParent ? this.find(_editableParent) : undefined;
} else card = undefined;
}
var isCurrentActiveCard = card && active && active.root.equal(card.root); // 当前是卡片,但是与当前激活的卡片不一致,就取消当前的卡片激活状态
if (active && !isCurrentActiveCard) {
var _active$toolbarModel;
(_active$toolbarModel = active.toolbarModel) === null || _active$toolbarModel === void 0 ? void 0 : _active$toolbarModel.hide();
active.select(false);
active.activate(false);
}
if (card) {
if (card.activatedByOther) return;
if (!isCurrentActiveCard) {
var _card$toolbarModel;
if (card.constructor.singleSelectable !== false && (trigger !== exports.CardActiveTrigger.CLICK || isEngine(editor))) {
this.select(card, event);
}
if (!card.isEditable && card.constructor.autoSelected !== false) card.select(!card.isEditable);
card.activate(true);
(_card$toolbarModel = card.toolbarModel) === null || _card$toolbarModel === void 0 ? void 0 : _card$toolbarModel.show(event);
} else if (card.isEditable) {
card.select(false);
} else if (trigger === exports.CardActiveTrigger.MOUSE_DOWN && node.name !== 'input' && card.root.find('.data-drag-image').length === 0) {
event === null || event === void 0 ? void 0 : event.preventDefault();
}
editor.change.onSelect();
}
} else if (active) {
var _active$toolbarModel2;
(_active$toolbarModel2 = active.toolbarModel) === null || _active$toolbarModel2 === void 0 ? void 0 : _active$toolbarModel2.hide();
active.select(false);
active.activate(false);
}
}
}, {
key: "select",
value: function select(card, event) {
var editor = this.editor;
if (!isEngine(editor)) return;
if (card.constructor.singleSelectable !== false && (card.type !== exports.CardType.BLOCK || !card.activated)) {
var range = editor.change.range.get().cloneRange();
if (range.startNode.closest(EDITABLE_SELECTOR).length > 0 && (!event || event instanceof MouseEvent && (!event.target || !this.closest(event.target, false))) || card.isEditable || card.isMaximize) return; // 重新设置光标,不加 preventDefault 会导致设置后失效
event === null || event === void 0 ? void 0 : event.preventDefault();
var root = card.root;
var parentNode = root.parent();
var index = parentNode.children().toArray().findIndex(function (child) {
return child.equal(root);
});
range.setStart(parentNode, index);
range.setEnd(parentNode, index + 1);
editor.change.range.select(range);
}
}
}, {
key: "focus",
value: function focus(card) {
var toStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
container = editor.container,
scrollNode = editor.scrollNode;
var range = change.range.get();
card.focus(range, toStart);
change.range.select(range);
this.activate(range.startNode, exports.CardActiveTrigger.MOUSE_DOWN);
change.onSelect();
if (scrollNode) range.scrollIntoViewIfNeeded(container, scrollNode);
}
}, {
key: "insert",
value: function insert(name, value) {
var editor = this.editor;
if (!isEngine(editor)) throw 'Engine not found';
var component = this.create(name, {
value: value
});
var change = editor.change;
var range = change.range.toTrusty();
for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
args[_key3 - 2] = arguments[_key3];
}
var card = this.insertNode.apply(this, [range, component].concat(args));
change.change();
return card;
}
}, {
key: "update",
value: function update(selector, value) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change;
var card = this.find(selector);
if (card) {
for (var _len4 = arguments.length, args = new Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
args[_key4 - 2] = arguments[_key4];
}
this.updateNode.apply(this, [card, value].concat(args));
var range = change.range.get();
card.focus(range, false);
change.change();
}
}
}, {
key: "replace",
value: function replace(source, name, value) {
this.remove(source.root);
for (var _len5 = arguments.length, args = new Array(_len5 > 3 ? _len5 - 3 : 0), _key5 = 3; _key5 < _len5; _key5++) {
args[_key5 - 3] = arguments[_key5];
}
return this.insert.apply(this, [name, value].concat(args));
}
}, {
key: "remove",
value: function remove(selector) {
var hasModify = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
list = editor.list,
node = editor.node;
var range = change.range.get();
var card = this.find(selector);
if (!card) return;
if (card.type === exports.CardType.INLINE) {
range.setEndAfter(card.root[0]);
range.collapse(false);
} else {
this.focusPrevBlock(card, range, hasModify);
}
var parent = card.root.parent();
this.removeNode(card);
list.addBr(range.startNode);
if (parent && node.isEmpty(parent) && !editor.model.mutation.isStopped) {
if (parent.isEditable()) {
node.html(parent, '
');
range.select(parent, true);
range.shrinkToElementNode();
range.collapse(false);
} else {
node.html(parent, '
');
range.select(parent, true);
range.collapse(false);
}
}
if (hasModify) change.apply(range);else {
// 远程移除时,如果调用 change.apply() 会把字符合并在一起,这样就会少一个text节点,后续的ops命令无法找到节点删除
change.range.select(range);
change.change();
}
}
}, {
key: "removeRemote",
value: function removeRemote(selector) {
var editor = this.editor;
if (!isEngine(editor)) return;
var node = editor.node;
var card = this.find(selector);
if (!card) return;
var parent = card.root.parent();
this.removeNode(card);
if (parent && node.isEmpty(parent) && !editor.model.mutation.isStopped) {
if (parent.isEditable()) {
node.html(parent, '
');
} else {
node.html(parent, '
');
}
}
} // 创建Card DOM 节点
}, {
key: "create",
value: function create(name, options) {
var _options$value;
var clazz = this.classes[name];
if (!clazz) throw ''.concat(name, ': This card does not exist');
var type = (options === null || options === void 0 ? void 0 : (_options$value = options.value) === null || _options$value === void 0 ? void 0 : _options$value.type) || clazz.cardType;
if (['inline', 'block'].indexOf(type) < 0) {
throw ''.concat(name, ': the type of card must be "inline", "block"');
}
if (options === null || options === void 0 ? void 0 : options.root) options.root.empty();
var editor = this.editor;
var component = new clazz({
editor: editor,
value: options === null || options === void 0 ? void 0 : options.value,
root: options === null || options === void 0 ? void 0 : options.root
});
var root = component.root;
root.attributes(CARD_TYPE_KEY, type);
root.attributes(CARD_KEY, name);
root.attributes(CARD_LOADING_KEY, 'true');
var tagName = type === exports.CardType.INLINE ? 'span' : 'div'; //center
var center = $("<".concat(tagName, " ").concat(component.isEditable ? DATA_TRANSIENT_ATTRIBUTES + "='*'" : '', "/>"));
center.attributes(CARD_ELEMENT_KEY, 'center'); //body
var body = $('<'.concat(tagName, ' ').concat(CARD_ELEMENT_KEY, '="body" />')); // center
body.append(center);
root.append(body); //可以聚焦的情况下,card左右两边添加光标位置
this.createCursor(component);
if (type === exports.CardType.BLOCK) {
editor.nodeId.generate(component.root);
}
component.init();
return component;
}
}, {
key: "createCursor",
value: function createCursor(component) {
var editor = this.editor;
var cardClazz = component.constructor;
var hasFocus = cardClazz.focus !== undefined ? cardClazz.focus : isEngine(editor) && !editor.readonly;
var center = component.getCenter();
center.removeAttributes(DATA_CONTENTEDITABLE_KEY);
var root = component.root;
root.removeAttributes(DATA_CONTENTEDITABLE_KEY);
var left = component.findByKey('left');
var right = component.findByKey('right');
if (hasFocus) {
center.attributes(DATA_CONTENTEDITABLE_KEY, 'false');
if (!left) {
center.before($("")));
}
if (!right) {
center.after($("")));
}
} else {
left === null || left === void 0 ? void 0 : left.remove();
right === null || right === void 0 ? void 0 : right.remove();
root.attributes(DATA_CONTENTEDITABLE_KEY, 'false');
}
}
}, {
key: "reRender",
value: function reRender() {
var _this3 = this;
for (var _len6 = arguments.length, cards = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
cards[_key6] = arguments[_key6];
}
if (cards.length === 0) cards = this.components;
cards.forEach(function (card) {
if (card.destroy) card.destroy();
_this3.createCursor(card);
card.init();
_this3.renderComponent(card);
});
}
/**
* 渲染
* @param container 需要重新渲染包含卡片的节点,如果不传,则渲染全部待创建的卡片节点
* @param callback 渲染完成后回调
* @param lazyRender 是否懒渲染,默认取决于editor的lazyRender属性
*/
}, {
key: "render",
value: function render(container, callback) {
var _this4 = this;
var lazyRender = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.lazyRender;
var cards = container ? container.isCard() ? container : container.find("".concat(READY_CARD_SELECTOR)) : this.editor.container.find(READY_CARD_SELECTOR);
this.gc();
var asyncRenderCards = [];
var readyCards = [];
var allCards = cards.toArray(); // 卡片内的子节点卡片移除
allCards.forEach(function (cardNode) {
if (!readyCards.find(function (node) {
return node.equal(cardNode);
})) {
readyCards.push(cardNode);
}
var childCards = cardNode.find("".concat(CARD_SELECTOR, ",").concat(READY_CARD_SELECTOR)).toArray();
childCards.forEach(function (childCard) {
if (childCard.equal(cardNode)) return;
var index = readyCards.findIndex(function (node) {
return node.equal(childCard);
});
if (index > -1) {
readyCards.splice(index, 1);
}
});
});
readyCards.forEach(function (cardNode) {
var attributes = cardNode.attributes();
var readyKey = attributes[READY_CARD_KEY];
var key = attributes[CARD_KEY];
var name = readyKey || key;
if (_this4.classes[name]) {
var value = attributes[CARD_VALUE_KEY];
var card;
if (key) {
card = _this4.find(cardNode);
if (card && card.root.equal(cardNode)) {
if (card.destroy) card.destroy();
_this4.removeComponent(card);
}
cardNode.attributes(CARD_LOADING_KEY, 'true');
attributes[CARD_LOADING_KEY] = 'true';
cardNode.empty();
} //ready_card_key 待创建的需要重新生成节点,并替换当前待创建节点
card = _this4.create(name, {
value: decodeCardValue(value),
root: key ? cardNode : undefined
});
Object.keys(attributes).forEach(function (attributesName) {
if (attributesName.indexOf('data-') === 0 && attributesName.indexOf('data-card') !== 0 || attributesName === CARD_LOADING_KEY) {
card.root.attributes(attributesName, attributes[attributesName]);
}
});
if (readyKey) {
cardNode.replaceWith(card.root);
cardNode.remove();
}
_this4.components.push(card); // 重新渲染
asyncRenderCards.push(card);
if (readyKey) {
card.root.removeAttributes(READY_CARD_KEY);
}
}
});
var isTriggerRenderAsync = false;
asyncRenderCards.forEach(function (card) {
// 可编辑卡片不进行异步渲染
if (lazyRender && card.constructor.lazyRender && !card.isEditable) {
if (card.beforeRender) {
var result = card.beforeRender();
var center = card.getCenter();
if (result !== undefined) {
center.append(typeof result === 'string' ? $(result) : result);
}
}
isTriggerRenderAsync = true;
_this4.asyncComponents.push(card);
} else {
_this4.renderComponent(card);
}
});
if (callback) callback(asyncRenderCards.length);
if (isTriggerRenderAsync) {
// 触发当前在视图内的卡片渲染
this.renderAsyncComponents();
}
}
}, {
key: "renderComponent",
value: function renderComponent(card) {
var editor = this.editor;
var center = card.getCenter();
for (var _len7 = arguments.length, args = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) {
args[_key7 - 1] = arguments[_key7];
}
var result = card.render.apply(card, args);
if (result !== undefined) {
center.append(typeof result === 'string' ? $(result) : result);
}
if (card.contenteditable.length > 0) {
var contenteditable = !isEngine(editor) || editor.readonly ? 'false' : 'true';
center.find(card.contenteditable.join(',')).each(function (node) {
var child = $(node);
if (child.attributes(DATA_CONTENTEDITABLE_KEY) !== contenteditable) child.attributes(DATA_CONTENTEDITABLE_KEY, contenteditable);
if (child.attributes(DATA_ELEMENT) !== EDITABLE) child.attributes(DATA_ELEMENT, EDITABLE);
if (isEngine(editor)) {
editor.normalize(child);
}
});
this.render(center);
}
card.didRender();
}
}, {
key: "removeComponent",
value: function removeComponent(card) {
var _this5 = this;
this.each(function (c, index) {
if (c.root.equal(card.root)) {
_this5.components.splice(index, 1);
return false;
}
return;
});
}
}, {
key: "gc",
value: function gc() {
for (var i = 0; i < this.components.length; i++) {
var component = this.components[i];
if (!component.root[0] || component.root.closest('body').length === 0) {
if (component.destroy) component.destroy();
this.components.splice(i, 1);
i--;
}
}
}
}, {
key: "destroy",
value: function destroy() {
var _editor$scrollNode2, _editor$scrollNode2$g;
this.gc();
var editor = this.editor;
window.removeEventListener('resize', this.renderAsyncComponents);
(_editor$scrollNode2 = editor.scrollNode) === null || _editor$scrollNode2 === void 0 ? void 0 : (_editor$scrollNode2$g = _editor$scrollNode2.get()) === null || _editor$scrollNode2$g === void 0 ? void 0 : _editor$scrollNode2$g.removeEventListener('scroll', this.renderAsyncComponents);
window.removeEventListener('scroll', this.renderAsyncComponents);
editor.off('card:async-render', this.renderAsyncComponents);
} // 焦点移动到上一个 Block
}, {
key: "focusPrevBlock",
value: function focusPrevBlock(card, range, hasModify) {
var editor = this.editor;
if (!isEngine(editor)) throw 'Engine not initialized';
var prevBlock;
if (card.type === 'inline') {
var block = editor.block.closest(card.root);
if (block.isEditable()) {
prevBlock = card.root.prevElement();
} else {
prevBlock = block.prevElement();
}
} else {
prevBlock = card.root.prevElement();
}
if (hasModify) {
if (!prevBlock || prevBlock.attributes(CARD_KEY)) {
var _block = $('
');
card.root.before(_block);
range.select(_block, true);
range.collapse(false);
editor.nodeId.generate(_block);
return;
}
} else {
if (!prevBlock) {
return;
}
if (prevBlock.attributes(CARD_KEY)) {
var _editor$card$find;
(_editor$card$find = editor.card.find(prevBlock)) === null || _editor$card$find === void 0 ? void 0 : _editor$card$find.focus(range, false);
return;
}
}
range.select(prevBlock, true).shrinkToElementNode().shrinkToTextNode().collapse(false);
} // 焦点移动到下一个 Block
}, {
key: "focusNextBlock",
value: function focusNextBlock(card, range, hasModify) {
var editor = this.editor;
if (!isEngine(editor)) throw 'Engine not initialized';
var nextBlock;
if (card.type === 'inline') {
var block = editor.block.closest(card.root);
if (block.isEditable()) {
nextBlock = card.root.nextElement();
} else {
nextBlock = block.nextElement();
}
} else {
nextBlock = card.root.nextElement();
}
if (hasModify) {
if (!nextBlock || nextBlock.attributes(CARD_KEY)) {
var _block = $('
');
card.root.after(_block);
range.select(_block, true);
range.collapse(false);
editor.nodeId.generate(_block);
return;
}
} else {
if (!nextBlock) {
return;
}
if (nextBlock.attributes(CARD_KEY)) {
var _editor$card$find2;
(_editor$card$find2 = editor.card.find(nextBlock)) === null || _editor$card$find2 === void 0 ? void 0 : _editor$card$find2.focus(range, true);
return;
}
}
range.select(nextBlock, true).shrinkToElementNode().shrinkToTextNode().collapse(true);
}
}]);
return CardModel;
}();
var _rules = /*#__PURE__*/_classPrivateFieldLooseKey("rules");
var NodeId = /*#__PURE__*/function () {
function NodeId(editor) {
_classCallCheck(this, NodeId);
this.schema = void 0;
Object.defineProperty(this, _rules, {
writable: true,
value: {}
});
this.schema = editor;
}
_createClass(NodeId, [{
key: "init",
value: function init() {
_classPrivateFieldLooseBase(this, _rules)[_rules] = this.getRules();
}
/**
* 根据规则获取需要为节点创建 data-id 的标签名称集合
* @returns
*/
}, {
key: "getRules",
value: function getRules() {
var rules = {}; // const { blocks, inlines, marks } = this.editor.schema.data;
this.schema.data.blocks.forEach(function (schema) {
if (!rules[schema.name]) {
rules[schema.name] = [];
}
rules[schema.name].push(schema);
});
return rules;
}
/**
* 给节点创建data-id
* @param node 节点
* @returns
*/
}, {
key: "create",
value: function create(node) {
if (isNode(node)) node = $(node);
var id = hashId(node);
node.attributes(DATA_ID, id);
return id;
}
/**
* 在根节点内为需要创建data-id的子节点创建data-id
* @param root 根节点
*/
}, {
key: "generateAll",
value: function generateAll(root) {
var _this = this;
var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var rules = _classPrivateFieldLooseBase(this, _rules)[_rules];
var tagNames = Object.keys(rules).join(',');
if (isNodeEntry(root) && root.fragment) {
root = root.fragment;
}
var node = isNode(root) ? root : root.get();
if (!node || node.nodeType === Node.TEXT_NODE) return;
var rootElement = isNode(root) ? root : root.get();
var nodes = rootElement === null || rootElement === void 0 ? void 0 : rootElement.querySelectorAll(tagNames);
var generate = function generate(element) {
// 有ID不再生成
if (!force && element.getAttribute(DATA_ID)) return;
_this.generate(element, force);
};
if (rootElement instanceof Element && tagNames.includes(rootElement.nodeName.toLowerCase())) {
generate(rootElement);
}
nodes === null || nodes === void 0 ? void 0 : nodes.forEach(generate);
}
/**
* 为节点创建一个随机data-id
* @param node 节点
* @param isCreate 如果有,是否需要重新创建
* @returns
*/
}, {
key: "generate",
value: function generate(node) {
var _this2 = this;
var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (isNode(node)) node = $(node);
if (node.isText()) return;
var rules = _classPrivateFieldLooseBase(this, _rules)[_rules]; // 不符合规则
var nodeRules = rules[node.name];
if (!nodeRules || nodeRules.length === 0 || !nodeRules.some(function (rule) {
return _this2.schema.checkNode(node, rule.attributes);
})) {
return;
} // 检测节点是否再ui或者不可编辑卡片内
var closestNode = node.closest("".concat(CARD_SELECTOR, ",").concat(UI_SELECTOR), getParentInRoot); // ui 节点内
if (closestNode.length > 0 && closestNode.attributes(DATA_ELEMENT) === UI) {
return;
} // 卡片内
if (!node.isCard() && closestNode.length > 0 && closestNode.isCard() && !closestNode.isEditableCard()) {
return;
}
if (!force) {
var id = node.attributes(DATA_ID);
if (id) return id;
}
return this.create(node);
}
/**
* 判断一个节点是否需要创建data-id
* @param name 节点名称
* @returns
*/
}, {
key: "isNeed",
value: function isNeed(node) {
var _this3 = this;
var rules = _classPrivateFieldLooseBase(this, _rules)[_rules]; // 不符合规则
var nodeRules = rules[node.name];
if (!nodeRules || nodeRules.length === 0 || !nodeRules.some(function (rule) {
return _this3.schema.checkNode(node, rule.attributes);
})) {
return false;
}
return true;
}
}]);
return NodeId;
}();
var isDragEvent = function isDragEvent(event) {
return !!event.dataTransfer;
};
var Clipboard = /*#__PURE__*/function () {
function Clipboard(editor) {
_classCallCheck(this, Clipboard);
this.editor = void 0;
this.editor = editor;
}
_createClass(Clipboard, [{
key: "getData",
value: function getData(event) {
var _html;
var transfer = isDragEvent(event) ? event.dataTransfer : event.clipboardData;
var html = transfer === null || transfer === void 0 ? void 0 : transfer.getData('text/html');
var text = transfer === null || transfer === void 0 ? void 0 : transfer.getData('text');
var files = []; // Edge 处理
try {
if ((transfer === null || transfer === void 0 ? void 0 : transfer.items) && transfer.items.length > 0) {
Array.from(transfer.items).forEach(function (item) {
var file = item.kind === 'file' ? item.getAsFile() : null;
if (file !== null) {
var _text;
if (file.type && file.type.indexOf('image/png') > -1 && !file.lastModified) {
file = new File([file], 'image.png', {
type: file.type
});
}
file['ext'] = (_text = text) === null || _text === void 0 ? void 0 : _text.split('.').pop();
}
if (file) files.push(file);
});
} else if ((transfer === null || transfer === void 0 ? void 0 : transfer.files) && transfer.files.length > 0) {
files = Array.from(transfer.files);
}
} catch (err) {
if ((transfer === null || transfer === void 0 ? void 0 : transfer.files) && transfer.files.length > 0) {
files = Array.from(transfer.files);
}
} // 从 Mac OS Finder 复制文件
if (html === '' && text && /^.+\.\w+$/.test(text) && files.length > 0) {
text = ''; // 在图片上,点击右键复制
} else if (text === '' && html && /^()?$/.test(html) && files.length > 0) {
html = ''; // 从 Excel、Numbers 复制
} else if ((html || text) && files.length > 0 && !((_html = html) === null || _html === void 0 ? void 0 : _html.startsWith('' + html.replace(/\u200b/g, ''));
event === null || event === void 0 ? void 0 : (_event$clipboardData2 = event.clipboardData) === null || _event$clipboardData2 === void 0 ? void 0 : _event$clipboardData2.setData('text', text.replace(/\u200b/g, ''));
return data;
}
}, {
key: "copy",
value: function copy(data) {
var _this = this;
var trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (typeof data === 'string') {
var isHtml = /<[^>]+>/g.test(data);
if (isHtml) {
copyTo__default['default'](data, {
format: 'text/html',
onCopy: function onCopy(clipboardData) {
clipboardData.setData('text/plain', new Parser(data, _this.editor).toText());
}
});
} else {
copyTo__default['default'](data, {
format: 'text/plain'
});
}
return true;
}
var editor = this.editor;
var selection = window.getSelection();
var range = selection ? Range.from(editor, selection) || Range.create(editor) : Range.create(editor);
var cloneRange = range.cloneRange();
var block = $("
"));
block.css({
position: 'fixed',
top: 0,
clip: 'rect(0, 0, 0, 0)'
});
var clera = function clera() {
block.remove();
selection === null || selection === void 0 ? void 0 : selection.removeAllRanges();
selection === null || selection === void 0 ? void 0 : selection.addRange(cloneRange.toRange());
};
block.on('copy', function (e) {
e.stopPropagation();
_this.write(e, range);
clera();
});
$(document.body).append(block);
block.append(editor.node.clone($(data), true));
if (trigger) {
block.traverse(function (child) {
if (child.equal(block)) return;
editor.trigger('copy', child);
});
}
block.append($('', null));
var first = block.first();
var end = block.last();
range.select(block, true);
range.setStartAfter(first);
range.setEndBefore(end);
selection === null || selection === void 0 ? void 0 : selection.removeAllRanges();
selection === null || selection === void 0 ? void 0 : selection.addRange(range.toRange());
var success = false;
try {
success = document.execCommand('copy');
if (!success) {
throw 'Copy failed';
}
} catch (err) {
editor.messageError('copy', 'The copy command was not executed successfully ', err);
clera();
}
return success;
}
}, {
key: "cut",
value: function cut() {
var editor = this.editor;
var range = Range.from(editor);
if (!range || !isEngine(editor)) return;
var root = range.commonAncestorNode;
var change = editor.change;
change.cacheRangeBeforeCommand();
change.delete(range);
var listElements = editor.node.isList(root) ? root : root.find('ul,ol');
for (var i = 0; i < listElements.length; i++) {
var _list$get;
var list = $(listElements[i]);
var childs = list.find('li');
childs.each(function (child) {
if ('' === child.innerText || isSafari && '\n' === child.innerText) {
var _ref, _child$parentElement;
(_ref = (_child$parentElement = child.parentElement) !== null && _child$parentElement !== void 0 ? _child$parentElement : child.parentNode) === null || _ref === void 0 ? void 0 : _ref.removeChild(child);
}
});
if (((_list$get = list.get()) === null || _list$get === void 0 ? void 0 : _list$get.childNodes.length) === 0) {
list.remove();
}
}
change.range.select(range);
}
}]);
return Clipboard;
}();
var buildParams = function buildParams(prefix, data, traditional, add) {
var name = undefined;
var i = undefined;
var rbracket = /\[\]$/;
if (Array.isArray(data)) {
// Serialize array item.
for (i = 0; i < data.length; i++) {
var value = data[i];
if (traditional || rbracket.test(prefix)) {
// Treat each array item as a scalar.
add(prefix, value);
} else {
buildParams(prefix + '[' + ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' ? i : '') + ']', value, traditional, add);
}
}
} else if (data.toString() === '[object Object]') {
// Serialize object item.
for (name in data) {
if (data.hasOwnProperty(name)) {
buildParams(prefix + '[' + name + ']', data[name], traditional, add);
}
}
} else {
// Serialize scalar item.
add(prefix, data);
}
};
/**
* URL 追加
* @param url url
* @param text 要追加的文本
* @returns
*/
var urlAppend = function urlAppend(url, text) {
return url + (/\?/.test(url) ? '&' : '?') + text;
};
var toQueryString = function toQueryString(data) {
var traditional = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var prefix = undefined;
var values = [];
var add = function add(key, value) {
// If value is a function, invoke it and return its value
if (typeof value === 'function') {
value = value();
} else if (value === null || value === undefined) {
value = '';
}
values[values.length] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
}; // If an array was passed in, assume that it is an array of form elements.
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
add(data[i].name, data[i].value);
}
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for (prefix in data) {
if (data.hasOwnProperty(prefix)) {
buildParams(prefix, data[prefix], traditional, add);
}
}
} // spaces should be + according to spec
return values.join('&').replace(/%20/g, '+');
};
var isFormData = function isFormData(data) {
return typeof FormData !== 'undefined' && data instanceof FormData;
};
var HTTP_REG = /^http/;
var PROTOCO_REG = /(^\w+):\/\//;
var TWO_HUNDO = /^(20\d|1223)$/; // http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
var READY_STATE = 'readyState';
var CONTENT_TYPE = 'Content-Type';
var REQUESTED_WITH = 'X-Requested-With';
var XML_HTTP_REQUEST = 'XMLHttpRequest';
var X_DOMAIN_REQUEST = 'XDomainRequest';
var globalSetup = {
traditional: false,
contentType: 'application/x-www-form-urlencoded',
requestedWith: XML_HTTP_REQUEST,
accept: {
'*': 'text/javascript, text/html, application/xml, text/xml, */*',
xml: 'application/xml, text/xml',
html: 'text/html',
text: 'text/plain',
json: 'application/json, text/javascript',
js: 'application/javascript, text/javascript'
},
dataFilter: function dataFilter(data) {
return data;
}
};
var Ajax = /*#__PURE__*/function () {
/**
* 设置全局选项
* @param options 选项
*/
function Ajax(options) {
var _this$options$doc;
_classCallCheck(this, Ajax);
this.options = void 0;
this.headNode = void 0;
this.request = void 0;
this.isAborted = false;
this.isTimeout = false;
this.timeout = void 0;
this.callbackData = void 0;
this.callbackPrefix = 'request_' + new Date();
this.uuid = 0;
this.promise = void 0;
this.__resolve = void 0;
this.__reject = void 0;
if (typeof options === 'string') {
options = {
url: options
};
}
var _options = options,
url = _options.url;
if (startsWith__default['default'](url, '//')) {
url = window.location.protocol + url;
}
this.options = _objectSpread2(_objectSpread2(_objectSpread2({}, globalSetup), options), {}, {
url: url,
context: options.context || window,
doc: options.doc || getDocument(),
jsonpCallback: options.jsonpCallback || 'callback',
method: options.method || 'GET'
});
this.headNode = (_this$options$doc = this.options.doc) === null || _this$options$doc === void 0 ? void 0 : _this$options$doc.getElementsByTagName('head')[0];
this.initPromise();
this.init();
}
_createClass(Ajax, [{
key: "initPromise",
value: function initPromise() {
var _this = this;
this.promise = new Promise(function (resolve, reject) {
_this.__resolve = resolve;
_this.__reject = reject;
}).catch(function () {});
}
}, {
key: "init",
value: function init() {
var _this2 = this;
var timedOut = function timedOut() {
var _this2$request;
_this2.isTimeout = true;
(_this2$request = _this2.request) === null || _this2$request === void 0 ? void 0 : _this2$request.abort();
};
if (this.timeout) {
clearTimeout(this.timeout);
}
this.timeout = undefined;
if (this.options.timeout) {
this.timeout = setTimeout(timedOut, this.options.timeout);
}
var error = function error(errorMsg, request) {
_this2.triggerError(errorMsg, request);
};
var success = function success(request) {
_this2.triggerSuccess(request);
};
this.getRequest(success, error).then(function (res) {
_this2.request = res;
});
}
}, {
key: "abort",
value: function abort() {
var _this$request;
(_this$request = this.request) === null || _this$request === void 0 ? void 0 : _this$request.abort();
}
}, {
key: "defaultXHR",
value: function defaultXHR() {
var _this$options = this.options,
context = _this$options.context,
crossOrigin = _this$options.crossOrigin;
if (!context) return; // is it x-domain
if (crossOrigin === true) {
var xhrInstance = context[XML_HTTP_REQUEST] ? new context[XML_HTTP_REQUEST]() : null;
if (xhrInstance && 'withCredentials' in xhrInstance) {
return xhrInstance;
}
if (context[X_DOMAIN_REQUEST]) {
return new context[X_DOMAIN_REQUEST]();
}
throw new Error('Browser does not support cross-origin requests');
} else if (context[XML_HTTP_REQUEST]) {
return new context[XML_HTTP_REQUEST]();
} else {
return new context.ActiveXObject('Microsoft.XMLHTTP');
}
}
}, {
key: "succeed",
value: function succeed() {
var _this$request2, _this$request2$status, _this$request3;
var _this$options2 = this.options,
url = _this$options2.url,
context = _this$options2.context;
var protocol = PROTOCO_REG.exec(url);
var protocolValue = protocol ? protocol[1] : '';
if (!protocolValue) {
protocolValue = (context === null || context === void 0 ? void 0 : context.location.protocol) || '';
}
return HTTP_REG.test(protocolValue) ? TWO_HUNDO.test(((_this$request2 = this.request) === null || _this$request2 === void 0 ? void 0 : (_this$request2$status = _this$request2.status) === null || _this$request2$status === void 0 ? void 0 : _this$request2$status.toString()) || '') : !!((_this$request3 = this.request) === null || _this$request3 === void 0 ? void 0 : _this$request3.response);
}
}, {
key: "noop",
value: function noop() {}
}, {
key: "handleReadyState",
value: function handleReadyState(success, error) {
// use _aborted to mitigate against IE err c00c023f
// (can't read props on aborted request objects)
if (this.isAborted) {
return error('Request is aborted', this.request);
}
if (this.isTimeout) {
return error('Request is aborted: timeout', this.request);
}
if (this.request && this.request[READY_STATE] === 4) {
this.request.onreadystatechange = this.noop;
if (this.succeed()) {
success(this.request);
} else {
error(this.request.statusText, this.request);
}
}
}
}, {
key: "setHeaders",
value: function setHeaders(request, headers) {
headers.Accept = headers.Accept || globalSetup.accept[this.options.type || '*']; // breaks cross-origin requests with legacy browsers
if (!this.options.crossOrigin && !headers[REQUESTED_WITH]) {
headers[REQUESTED_WITH] = globalSetup.requestedWith;
}
if (!headers[CONTENT_TYPE] && !isFormData(this.options.data)) {
headers[CONTENT_TYPE] = this.options.contentType || globalSetup.contentType;
}
Object.keys(headers).forEach(function (name) {
request.setRequestHeader(name, headers[name]);
});
}
}, {
key: "setCredentials",
value: function setCredentials(request) {
if (typeof this.options.withCredentials !== 'undefined' && typeof request.withCredentials !== 'undefined') {
request.withCredentials = !!this.options.withCredentials;
}
}
}, {
key: "generalCallback",
value: function generalCallback(data) {
this.callbackData = data;
}
}, {
key: "getCallbackPrefix",
value: function getCallbackPrefix(id) {
return this.callbackPrefix + '_' + id;
}
}, {
key: "handleJsonp",
value: function handleJsonp(url, success, error) {
var _this3 = this,
_this$headNode;
var _this$options3 = this.options,
jsonpCallback = _this$options3.jsonpCallback,
jsonpCallbackName = _this$options3.jsonpCallbackName,
doc = _this$options3.doc,
context = _this$options3.context;
if (!doc || !context) return;
var requestId = this.uuid++;
var cbkey = jsonpCallback || 'callback'; // the 'callback' key
var cbval = jsonpCallbackName || this.getCallbackPrefix(requestId);
var cbreg = new RegExp('((^|\\?|&)' + cbkey + ')=([^&]+)');
var match = url.match(cbreg);
var script = doc.createElement('script');
var loaded = 0;
var isIE10 = navigator.userAgent.indexOf('MSIE 10.0') !== -1;
if (match) {
if (match[3] === '?') {
url = url.replace(cbreg, '$1=' + cbval); // wildcard callback func name
} else {
cbval = match[3]; // provided callback func name
}
} else {
url = urlAppend(url, cbkey + '=' + cbval); // no callback details, add 'em
}
context[cbval] = this.generalCallback;
script.type = 'text/javascript';
script.src = url;
script.async = true;
if (typeof script['onreadystatechange'] !== 'undefined' && !isIE10) {
// need this for IE due to out-of-order onreadystatechange(), binding script
// execution to an event listener gives us control over when the script
// is executed. See http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html
script.htmlFor = script.id = '_request_' + requestId;
}
script.onload = script['onreadystatechange'] = function () {
var _this3$headNode;
if (script[READY_STATE] && script[READY_STATE] !== 'complete' && script[READY_STATE] !== 'loaded' || loaded) {
return false;
}
script.onload = script['onreadystatechange'] = null;
if (script.onclick) {
script.onclick();
} // Call the user callback with the last value stored and clean up values and scripts.
success(_this3.callbackData);
_this3.callbackData = undefined;
(_this3$headNode = _this3.headNode) === null || _this3$headNode === void 0 ? void 0 : _this3$headNode.removeChild(script);
loaded = 1;
return true;
}; // Add the script to the DOM head
(_this$headNode = this.headNode) === null || _this$headNode === void 0 ? void 0 : _this$headNode.appendChild(script); // Enable JSONP timeout
return {
abort: function abort() {
var _this3$headNode2;
script.onload = script['onreadystatechange'] = null;
error('Request is aborted: timeout');
_this3.callbackData = undefined;
(_this3$headNode2 = _this3.headNode) === null || _this3$headNode2 === void 0 ? void 0 : _this3$headNode2.removeChild(script);
loaded = 1;
}
};
}
}, {
key: "getRequest",
value: function () {
var _getRequest = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(success, error) {
var _this$options$method,
_this$options$content,
_this4 = this;
var method, _this$options4, processData, traditional, type, context, xhr, async, before, url, data, http, sendWait, headers;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
method = ((_this$options$method = this.options.method) === null || _this$options$method === void 0 ? void 0 : _this$options$method.toUpperCase()) || 'GET'; // convert non-string objects to query-string form unless o.processData is false
_this$options4 = this.options, processData = _this$options4.processData, traditional = _this$options4.traditional, type = _this$options4.type, context = _this$options4.context, xhr = _this$options4.xhr, async = _this$options4.async, before = _this$options4.before;
if (context) {
_context.next = 4;
break;
}
return _context.abrupt("return", Promise.resolve(undefined));
case 4:
url = this.options.url;
data = this.options.data; // get data
if (!(typeof data === 'function')) {
_context.next = 10;
break;
}
_context.next = 9;
return data();
case 9:
data = _context.sent;
case 10:
if ((((_this$options$content = this.options.contentType) === null || _this$options$content === void 0 ? void 0 : _this$options$content.indexOf('json')) || -1) > -1 && _typeof(data) === 'object' && !isFormData(data)) {
data = JSON.stringify(data);
}
data = processData !== false && data && typeof data !== 'string' && !isFormData(data) ? toQueryString(data, traditional || globalSetup.traditional) : data || null;
http = undefined;
sendWait = false; // if we're working on a GET request and we have data then we should append
// query string to end of URL and not post data
if ((type === 'jsonp' || method === 'GET') && data) {
url = urlAppend(url, data);
data = null;
}
if (!(type === 'jsonp')) {
_context.next = 17;
break;
}
return _context.abrupt("return", Promise.resolve(this.handleJsonp(url, success, error)));
case 17:
// get headers
headers = this.options.headers || {};
if (!(typeof headers === 'function')) {
_context.next = 22;
break;
}
_context.next = 21;
return headers();
case 21:
headers = _context.sent;
case 22:
// get the xhr from the factory if passed
// if the factory returns null, fall-back to ours
http = (typeof xhr === 'function' ? xhr(this.options) : xhr) || this.defaultXHR();
if (http) {
_context.next = 25;
break;
}
return _context.abrupt("return");
case 25:
http.open(method, url, async === false ? false : true);
this.setHeaders(http, headers);
this.setCredentials(http);
if (context[X_DOMAIN_REQUEST] && http instanceof context[X_DOMAIN_REQUEST]) {
http.onload = success;
http.onerror = function () {
error('http error', http);
}; // NOTE: see
// http://social.msdn.microsoft.com/Forums/en-US-US/iewebdevelopment/thread/30ef3add-767c-4436-b8a9-f1ca19b4812e
http.onprogress = this.noop;
sendWait = true;
} else {
http.onreadystatechange = function () {
_this4.handleReadyState(success, error);
};
}
if (before) {
before(http);
}
if (sendWait) {
setTimeout(function () {
var _http;
(_http = http) === null || _http === void 0 ? void 0 : _http.send(data);
}, 200);
} else {
http.send(data);
}
return _context.abrupt("return", Promise.resolve(http));
case 32:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function getRequest(_x, _x2) {
return _getRequest.apply(this, arguments);
}
return getRequest;
}()
}, {
key: "getType",
value: function getType(type) {
// json, javascript, text/plain, text/html, xml
if (!type) {
return undefined;
}
if (type.match('json')) {
return 'json';
}
if (type.match('javascript')) {
return 'js';
}
if (type.match('text')) {
return 'html';
}
if (type.match('xml')) {
return 'xml';
}
return undefined;
}
}, {
key: "triggerSuccess",
value: function triggerSuccess(request) {
var _this$options5 = this.options,
dataFilter = _this$options5.dataFilter,
context = _this$options5.context,
success = _this$options5.success;
if (!context) return;
var type = this.options.type; // use global data filter on response text
var data = (dataFilter || globalSetup.dataFilter)(request.responseText, type);
if (!type) {
type = request && this.getType(request.getResponseHeader('Content-Type'));
} // resp can be undefined in IE
var response = type !== 'jsonp' ? this.request : request;
try {
response['responseText'] = data;
} catch (e) {// can't assign this in IE<=8, just ignore
}
if (data) {
switch (type) {
case 'json':
try {
response = context.JSON.parse(data);
} catch (err) {
return this.triggerError('Could not parse JSON in response', response);
}
break;
case 'html':
response = data;
break;
case 'xml':
response = response.responseXML && response.responseXML.parseError && response.responseXML.parseError.errorCode && response.responseXML.parseError.reason ? null : response.responseXML;
break;
}
}
if (success) {
success(response);
}
this.triggerComplete(response);
if (this.__resolve) this.__resolve(response);
}
}, {
key: "triggerError",
value: function triggerError(errorMsg, request) {
var error = this.options.error;
var e = new Error(errorMsg);
e['xhr'] = request;
if (error) {
error(e);
}
this.triggerComplete(e);
if (this.__reject) this.__reject(e);
}
}, {
key: "triggerComplete",
value: function triggerComplete(request) {
var complete = this.options.complete;
if (this.timeout) {
clearTimeout(this.timeout);
}
this.timeout = undefined;
if (complete) {
complete(request);
}
}
}, {
key: "retry",
value: function retry() {
this.initPromise();
this.init();
}
}, {
key: "then",
value: function then(success, fail) {
var _this$promise;
return (_this$promise = this.promise) === null || _this$promise === void 0 ? void 0 : _this$promise.then(success, fail);
}
}, {
key: "always",
value: function always(fn) {
var _this$promise2;
return (_this$promise2 = this.promise) === null || _this$promise2 === void 0 ? void 0 : _this$promise2.then(fn, fn);
}
}, {
key: "fail",
value: function fail(fn) {
var _this$promise3;
return (_this$promise3 = this.promise) === null || _this$promise3 === void 0 ? void 0 : _this$promise3.then(undefined, fn);
}
}, {
key: "catch",
value: function _catch(fn) {
return this.fail(fn);
}
}]);
return Ajax;
}();
Ajax.setup = function (options) {
Object.keys(options).forEach(function (key) {
if (globalSetup[key]) globalSetup[key] = options[key];
});
};
var mime = {
'image/jpeg': ['jpeg', 'jpg', 'jpe'],
'image/png': ['png'],
'image/gif': ['gif'],
'image/vnd.wap.wbmp': ['wbmp'],
'image/tiff': ['tiff', 'tiff'],
'image/vnd.adobe.photoshop': ['psd'],
'image/svg+xml': ['svg', 'svgz'],
'text/jsx': ['jsx'],
'text/less': ['less'],
'text/css': ['css'],
'text/x-sass': ['sass'],
'text/x-scss': ['scss'],
'text/csv': ['cvs'],
'text/xml': ['xml'],
'text/x-vcard': ['vcf'],
'text/x-vcalendar': ['vcs'],
'text/markdown': ['md'],
'text/plain': ['txt'],
'text/richtext': ['rtx'],
'text/rtf': ['rtf'],
'text/html': ['html', 'htm', 'shtml'],
'text/jade': ['jade'],
'text/javascript': ['js'],
'text/yaml': ['yaml', 'yml'],
'audio/mp3': ['mp3'],
'audio/mp4': ['mp4', 'mp4a'],
'video/mp4': ['mp4'],
'audio/mpeg': ['mpeg', 'mp2', 'mp3'],
'audio/ogg': ['oga'],
'audio/wav': ['wav'],
'audio/wave': ['wav'],
'audio/webm': ['weba'],
'video/x-msvideo': ['avi'],
'video/quicktime': ['mov', 'qt'],
'video/ogg': ['ogv'],
'video/x-sgi-movie': ['movie'],
'application/rss+xml': ['rss'],
'application/json': ['json'],
'application/zip': ['zip'],
'application/gzip': ['gzip'],
'application/pdf': ['pdf'],
'application/postscript': ['ai', 'eps', 'ps'],
'application/msword': ['doc', 'dot'],
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['docx'],
'application/vnd.openxmlformats-officedocument.wordprocessingml.template': ['dotx'],
'application/vnd.ms-excel': ['xls', 'xlm', 'xla', 'xlc', 'xlt', 'xlw'],
'application/vnd.ms-excel.sheet.macroenabled.12': ['xlsm'],
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['xlsx'],
'application/vnd.openxmlformats-officedocument.spreadsheetml.template': ['xltx'],
'application/vnd.ms-powerpoint': ['ppt', 'pps', 'pot'],
'application/vnd.openxmlformats-officedocument.presentationml.presentation': ['pptx'],
'application/vnd.openxmlformats-officedocument.presentationml.slide': ['sldx'],
'application/vnd.openxmlformats-officedocument.presentationml.slideshow': ['ppsx'],
'application/vnd.openxmlformats-officedocument.presentationml.template': ['potx'],
'application/vnd.ms-fontobject': ['eot'],
'application/vnd.android.package-archive': ['apk'],
'application/x-apple-diskimage': ['dmg'],
'application/x-iwork-keynote-sffkey': ['key'],
'application/x-iwork-pages-sffpages': ['pages'],
'application/x-iwork-keynote-sffnumbers': ['numbers'],
'application/x-iwork-numbers-sffnumbers': ['numbers']
};
/**
* 获取文件扩展名
* @param file 文件 或 文件名
* @returns
*/
var getExtensionName = function getExtensionName(file) {
if (typeof file === 'string') {
var _file$split$pop;
return (_file$split$pop = file.split('.').pop()) !== null && _file$split$pop !== void 0 ? _file$split$pop : '';
}
var ext = mime[file.type] ? mime[file.type][0] : '';
if (!ext && 'name' in file) {
var _file$name$split$pop;
ext = (_file$name$split$pop = file.name.split('.').pop()) !== null && _file$name$split$pop !== void 0 ? _file$name$split$pop : '';
}
return ext;
};
/**
* 获取文件大小
* @param size
* @param base
* @returns
*/
var getFileSize = function getFileSize(size) {
var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : isWindows ? 2 : 10;
if (typeof size !== 'number') return '0B';
var options = {
exponent: 2,
round: 1
}; //1KB以下
if (size < 1024) {
options.exponent = -1;
options.round = 0;
} //1M以下
if (size < 1048576) {
options.exponent = 1;
options.round = 0;
}
return filesize__default['default'](size, _objectSpread2({
base: base
}, options));
};
var Uploader = /*#__PURE__*/function () {
function Uploader(options) {
_classCallCheck(this, Uploader);
this.options = void 0;
this.uploadingFiles = [];
this.options = options;
}
_createClass(Uploader, [{
key: "createUid",
value: function createUid(text) {
return Date.now() + '-' + text;
}
}, {
key: "request",
value: function () {
var _request = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(files, name) {
var result, i, file;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
result = [];
i = 0;
case 2:
if (!(i < files.length)) {
_context.next = 13;
break;
}
file = files[i];
if (!file.uid) file.uid = this.createUid(i);
_context.next = 7;
return this.handleBefore(file, files);
case 7:
_context.t0 = _context.sent;
if (!(_context.t0 === true)) {
_context.next = 10;
break;
}
// files.splice(i, 1);
result.push(file);
case 10:
i++;
_context.next = 2;
break;
case 13:
this.upload(result, name);
case 14:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function request(_x, _x2) {
return _request.apply(this, arguments);
}
return request;
}()
}, {
key: "upload",
value: function () {
var _upload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(files) {
var _this = this;
var name,
_args3 = arguments;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
name = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : 'file';
files.forEach( /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(file) {
var formData, _this$options, url, onUploading, onSuccess, onError, withCredentials, crossOrigin, headers, data, _iterator, _step, _step$value, key, value;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
formData = new FormData();
_this$options = _this.options, url = _this$options.url, onUploading = _this$options.onUploading, onSuccess = _this$options.onSuccess, onError = _this$options.onError, withCredentials = _this$options.withCredentials, crossOrigin = _this$options.crossOrigin, headers = _this$options.headers;
data = _this.options.data;
if (!(typeof data === 'function')) {
_context2.next = 7;
break;
}
_context2.next = 6;
return data();
case 6:
data = _context2.sent;
case 7:
if (data) {
if (isFormData(data)) {
_iterator = _createForOfIteratorHelper(data);
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
_step$value = _slicedToArray(_step.value, 2), key = _step$value[0], value = _step$value[1];
formData.append(key, value);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
} else {
Object.keys(data).forEach(function (key) {
formData.append(key, data[key]);
});
}
}
if (file.data) {
Object.keys(file.data).forEach(function (key) {
formData.append(key, file.data[key]);
});
}
formData.append(name, file, file.name);
_context2.next = 12;
return new Ajax({
xhr: function xhr() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function (evt) {
if (evt.lengthComputable) {
if (onUploading) onUploading(file, {
percent: parseInt((evt.loaded / evt.total * 100).toString(), 10)
});
}
}, false);
return xhr;
},
url: url,
data: formData,
contentType: _this.options.contentType,
type: _this.options.type || 'json',
withCredentials: withCredentials,
crossOrigin: crossOrigin,
headers: headers,
success: function success(response) {
if (onSuccess) onSuccess(response, file);
},
error: function error(err) {
if (onError) onError(err, file);
},
method: 'POST',
processData: true
});
case 12:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function (_x4) {
return _ref.apply(this, arguments);
};
}());
case 2:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
function upload(_x3) {
return _upload.apply(this, arguments);
}
return upload;
}()
}, {
key: "handleBefore",
value: function () {
var _handleBefore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(file, files) {
var _this2 = this;
var type, uid, name, size, ext, onBefore;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
type = file.type, uid = file.uid, name = file.name, size = file.size;
ext = getExtensionName(file);
onBefore = this.options.onBefore;
_context5.t0 = onBefore;
if (!_context5.t0) {
_context5.next = 9;
break;
}
_context5.next = 7;
return onBefore(file);
case 7:
_context5.t1 = _context5.sent;
_context5.t0 = _context5.t1 === false;
case 9:
if (!_context5.t0) {
_context5.next = 11;
break;
}
return _context5.abrupt("return", false);
case 11:
return _context5.abrupt("return", new Promise(function (resolve, reject) {
var fileReader = new FileReader();
fileReader.addEventListener('load', function () {
_this2.uploadingFiles[uid] = {
uid: uid,
src: fileReader.result,
name: name,
size: size,
type: type,
ext: ext
}; //全部文件读取完成后再插入编辑器
if (files.every(function (file) {
return !!_this2.uploadingFiles[file.uid];
})) {
Promise.all(_toConsumableArray(files.map(function (file) {
return new Promise( /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(resolve) {
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!_this2.options.onReady) {
_context4.next = 3;
break;
}
_context4.next = 3;
return _this2.options.onReady(_this2.uploadingFiles[file.uid], file);
case 3:
resolve(true);
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return function (_x7) {
return _ref2.apply(this, arguments);
};
}());
}))).then(function () {
resolve(true);
});
} else {
resolve(true);
}
}, false);
fileReader.addEventListener('error', function () {
reject(false);
});
fileReader.readAsDataURL(file);
}));
case 12:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function handleBefore(_x5, _x6) {
return _handleBefore.apply(this, arguments);
}
return handleBefore;
}()
}]);
return Uploader;
}();
var Request = /*#__PURE__*/function () {
function Request() {
_classCallCheck(this, Request);
}
_createClass(Request, [{
key: "ajax",
value: function ajax(options) {
return new Ajax(options);
}
}, {
key: "upload",
value: function upload(options, files, name) {
return new Uploader(options).request(files, name);
}
}, {
key: "getFiles",
value: function getFiles(options) {
var _ref = options || {},
event = _ref.event,
accept = _ref.accept,
multiple = _ref.multiple;
accept = accept || '*';
if (multiple === false) multiple = 1;else if (multiple === undefined || multiple === true) multiple = 100;
var input = document.createElement('input');
input.type = 'file';
input.accept = accept;
input.style.display = 'none';
input.multiple = multiple > 1;
var remove = function remove() {
input.remove();
document.removeEventListener('mousedown', remove);
};
return new Promise(function (resolve) {
var change = function change() {
var _input$files;
var files = [];
var inputFiles = (_input$files = input.files) !== null && _input$files !== void 0 ? _input$files : [];
var maxLength = Math.min(inputFiles.length, multiple);
for (var i = 0; i < maxLength; i++) {
files.push(inputFiles[i]);
}
input.removeEventListener('change', change);
remove();
resolve(files);
};
input.addEventListener('change', change);
document.body.appendChild(input);
if (!event) {
event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
}
try {
if (!!input.dispatchEvent) {
input.dispatchEvent(event);
} else if (!!input['fireEvent']) {
input['fireEvent'](event);
} else throw '';
document.addEventListener('mousedown', remove);
} catch (error) {
input.removeEventListener('change', change);
remove();
resolve([]);
}
});
}
}]);
return Request;
}();
var Backspace$3 = /*#__PURE__*/function () {
function Backspace(engine) {
_classCallCheck(this, Backspace);
this.engine = void 0;
this.engine = engine;
}
/**
* 列表删除事件
* @param e 事件
* @param isDeepMerge 是否深度合并
*/
_createClass(Backspace, [{
key: "trigger",
value: function trigger(event, isDeepMerge) {
var _this$engine = this.engine,
change = _this$engine.change,
command = _this$engine.command,
list = _this$engine.list,
node = _this$engine.node;
var range = change.range.get();
var blockApi = this.engine.block;
if (range.collapsed) {
var _block = blockApi.closest(range.startNode);
if ('li' === _block.name && list.isFirst(range)) {
// 内容已经删除过了
if (event['isDelete']) return false;
event.preventDefault();
command.execute(list.getPluginNameByNode(_block));
return false;
}
} else {
var startNode = range.startNode,
endNode = range.endNode;
var startBlock = blockApi.closest(startNode);
var endBlock = blockApi.closest(endNode);
if ('li' === startBlock.name || 'li' === endBlock.name) {
event.preventDefault();
var cloneRange = range.cloneRange(); // 自定义任务列表,开头位置的卡片让其不选中
var firstChilde = startNode.first();
var customeCard = startNode.isCard() ? startNode : firstChilde;
if (customeCard === null || customeCard === void 0 ? void 0 : customeCard.isCard()) {
if (list.isEmptyItem(startBlock)) {
var _parent$get;
var parent = startBlock.parent();
startBlock.remove();
if (parent && node.isCustomize(parent) && ((_parent$get = parent.get()) === null || _parent$get === void 0 ? void 0 : _parent$get.childNodes.length) === 0) {
parent.remove();
}
}
}
var startParent = 'li' === startBlock.name ? startBlock.parent() : null;
var endParent = 'li' === endBlock.name ? endBlock.parent() : null;
if ('li' === startBlock.name && list.isFirst(range)) {
cloneRange.setStartBefore(startBlock);
}
if ('li' === endBlock.name && blockApi.isLastOffset(range, 'end')) {
cloneRange.setEndAfter(endBlock);
}
change.delete(cloneRange, isDeepMerge); // 光标在列表的最后一行,并且开始光标不在最后一行
if (startBlock.inEditor() && !startBlock.equal(endBlock) && endBlock.inEditor() && 'li' === endBlock.name) {
cloneRange.shrinkToElementNode().shrinkToTextNode();
var selection = cloneRange.createSelection();
startBlock.append(endBlock.children());
endBlock.remove();
selection.move();
}
if ('li' === startBlock.name) {
var _startBlock$get;
if (node.isCustomize(startBlock) && ((_startBlock$get = startBlock.get()) === null || _startBlock$get === void 0 ? void 0 : _startBlock$get.childNodes.length) === 0) startBlock.remove();
}
var removeEmptyParent = function removeEmptyParent(parent) {
if (node.isList(parent)) {
var _parent$get2;
var childNodes = ((_parent$get2 = parent.get()) === null || _parent$get2 === void 0 ? void 0 : _parent$get2.childNodes) || [];
if (childNodes.length == 0) {
parent.remove();
} else if (childNodes.length === 1) {
var first = parent.first();
if (first === null || first === void 0 ? void 0 : first.isCursor()) {
parent.after(first);
parent.remove();
}
}
}
};
if (startParent && startParent.length > 0 && node.isList(startParent)) {
removeEmptyParent(startParent);
}
if (endParent && endParent.length > 0 && node.isList(endParent)) {
removeEmptyParent(endParent);
}
list.addBr(startBlock);
if (!startBlock.equal(endBlock)) list.addBr(endBlock);
range.setStart(cloneRange.startContainer, cloneRange.startOffset);
range.collapse(true);
list.merge();
if (change.isEmpty()) {
change.initValue(range);
}
change.apply(range);
return false;
}
}
if (!blockApi.isFirstOffset(range, 'start')) return;
var block = blockApi.closest(range.startNode); // 在列表里
if (node.isList(block)) {
// 矫正这种情况,
var li = block.first();
if (!li || li.isText()) {
//
event.preventDefault();
change.mergeAfterDelete(block);
return false;
} else {
block = li;
range.setStart(block[0], 0);
range.collapse(true);
change.range.select(range);
}
}
if (block.name === 'li') {
var _block$parent;
if (node.isCustomize(block)) {
return;
}
event.preventDefault();
var listRoot = block.closest('ul');
if ((_block$parent = block.parent()) === null || _block$parent === void 0 ? void 0 : _block$parent.isEditable()) {
// foo
bar
change.mergeAfterDelete(block);
return false;
}
if (listRoot.length > 0) {
command.execute(list.getPluginNameByNode(listRoot));
} else {
// foo
change.unwrap(block);
}
return false;
}
return true;
}
}]);
return Backspace;
}();
var Enter$3 = /*#__PURE__*/function () {
function Enter(engine) {
_classCallCheck(this, Enter);
this.engine = void 0;
this.backspace = void 0;
this.engine = engine;
this.backspace = new Backspace$3(engine);
}
_createClass(Enter, [{
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
command = _this$engine.command,
list = _this$engine.list;
var range = change.range.get();
range.shrinkToElementNode();
var startBlock = this.engine.block.closest(range.startNode);
var endBlock = this.engine.block.closest(range.endNode); //选区开始或结束位置为li
if ('li' === startBlock.name || 'li' === endBlock.name) {
//选区为展开状态,先删除
if (!range.collapsed) {
this.backspace.trigger(event, startBlock.name !== endBlock.name);
range = change.range.get();
}
event.preventDefault(); //如果光标在列表结尾或者开始位置
var pluginName = list.getPluginNameByNode(startBlock);
if (list.isLast(range) && list.isFirst(range)) {
command.execute(pluginName);
} else {
this.engine.block.split();
range = change.range.get(); //const selection = range.createSelection();
var block = this.engine.block.closest(range.endNode);
var plugin = list.getPlugins().find(function (plugin) {
return pluginName === plugin.constructor.pluginName;
});
if (!plugin) return;
if (plugin.cardName) {
var prev = block.prev();
if (prev) {
list.addCardToCustomize(prev, plugin.cardName);
list.addBr(prev);
}
list.addCardToCustomize(block, plugin.cardName);
list.addBr(block);
var next = block.next();
if (next) {
list.addCardToCustomize(next, plugin.cardName);
list.addBr(next);
}
}
list.merge(undefined, range);
list.addBr(range.startNode.closest('ul'));
range.setStart(block, this.engine.node.isCustomize(block) ? 1 : 0);
range.collapse(true).shrinkToTextNode();
change.apply(range);
}
range.scrollIntoView();
return false;
}
return true;
}
}]);
return Enter;
}();
var List = /*#__PURE__*/function () {
/**
* 自定义列表样式
*/
/**
* 自定义列表样式
*/
/**
* 列表缩进key
*/
/**
* 列表项point位置
*/
function List(editor) {
_classCallCheck(this, List);
this.editor = void 0;
this.CUSTOMZIE_UL_CLASS = 'data-list';
this.CUSTOMZIE_LI_CLASS = 'data-list-item';
this.INDENT_KEY = 'data-indent';
this.STYLE_POSITION_NAME = 'list-style-position';
this.STYLE_POSITION_VALUE = 'inside';
this.backspaceEvent = void 0;
this.editor = editor;
}
_createClass(List, [{
key: "init",
value: function init() {
var _this = this;
var editor = this.editor;
if (isEngine(editor)) {
var _editor$typing$getHan, _editor$typing$getHan2;
//绑定回车事件
var enter = new Enter$3(editor);
(_editor$typing$getHan = editor.typing.getHandleListener('enter', 'keydown')) === null || _editor$typing$getHan === void 0 ? void 0 : _editor$typing$getHan.on(function (event) {
return enter.trigger(event);
}); //删除事件
this.backspaceEvent = new Backspace$3(editor);
(_editor$typing$getHan2 = editor.typing.getHandleListener('backspace', 'keydown')) === null || _editor$typing$getHan2 === void 0 ? void 0 : _editor$typing$getHan2.on(function (event) {
var _this$backspaceEvent;
return (_this$backspaceEvent = _this.backspaceEvent) === null || _this$backspaceEvent === void 0 ? void 0 : _this$backspaceEvent.trigger(event);
});
}
}
/**
* 判断列表项节点是否为空
* @param node 节点
*/
}, {
key: "isEmptyItem",
value: function isEmptyItem(node) {
var children = node.children().toArray().filter(function (child) {
if (child.isText()) {
return child.text().replace(/[\n\t]/g, '') !== '';
}
return !child.isCursor();
});
var nodeApi = this.editor.node;
return (//节点名称必须为li
'li' === node.name && ( //空节点
nodeApi.isEmpty(node) || children.length === 0 || ( //子节点只有一个,如果是自定义列表并且第一个是卡片 或者第一个节点是 br标签,就是空节点
1 === children.length ? nodeApi.isCustomize(node) && children[0].isCard() || 'br' === children[0].name : //子节点有两个,并且是自定义列表而且第一个是卡片,并且第二个节点是br标签
2 === children.length && nodeApi.isCustomize(node) && !!children[0].isCard() && 'br' === children[1].name))
);
}
/**
* 判断两个节点是否是一样的List节点
* @param sourceNode 源节点
* @param targetNode 目标节点
*/
}, {
key: "isSame",
value: function isSame(sourceNode, targetNode) {
//节点名称不一样
if (sourceNode.name !== targetNode.name) return false;
var node = this.editor.node; //自定义列表类型不一致,要么都是,要么都不是
if (node.isCustomize(sourceNode) !== node.isCustomize(targetNode)) return false; //判断缩进是否一致
var sourceIndent = parseInt(sourceNode.attributes(this.INDENT_KEY), 10) || 0;
var targetIndent = parseInt(targetNode.attributes(this.INDENT_KEY), 10) || 0;
return sourceIndent === targetIndent;
}
/**
* 判断节点集合是否是指定类型的List列表
* @param blocks 节点集合
* @param name 节点标签类型
* @param card 是否是指定的自定义列表项的卡片名称
*/
}, {
key: "isSpecifiedType",
value: function isSpecifiedType(blocks) {
var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'ul';
var card = arguments.length > 2 ? arguments[2] : undefined;
var node = this.editor.node;
var isSame = true;
blocks.forEach(function (block) {
var _block$parent;
//如果节点内包含了列表节点,则跳过此节点
if (['li', 'p'].indexOf(block.name) === -1 && (block.name === name || block.find(name).length > 0)) return;
switch (block.name) {
case 'li':
//有指定卡片,判断是否是自定义列表项的卡片相同
if (card) {
var _firstChild, _firstChild2;
var firstChild = block.first();
if ((_firstChild = firstChild) === null || _firstChild === void 0 ? void 0 : _firstChild.isCursor()) firstChild = firstChild.next();
isSame = isSame && node.isCustomize(block) && (((_firstChild2 = firstChild) === null || _firstChild2 === void 0 ? void 0 : _firstChild2.attributes(CARD_KEY)) || '') === card;
} else {
isSame = isSame && !node.isCustomize(block);
}
break;
case 'p':
if (block.parent() && ((_block$parent = block.parent()) === null || _block$parent === void 0 ? void 0 : _block$parent.name) !== 'li') {
isSame = false;
}
break;
default:
isSame = false;
break;
}
});
return isSame;
}
}, {
key: "getPlugins",
value: function getPlugins() {
var plugins = [];
var pluginApi = this.editor.plugin;
Object.keys(pluginApi.components).forEach(function (name) {
var plugin = pluginApi.components[name];
if (!!plugin.isCurrent) {
plugins.push(plugin);
}
});
return plugins;
}
/**
* 根据节点获取列表插件名称
* @param block 节点
*/
}, {
key: "getPluginNameByNode",
value: function getPluginNameByNode(block) {
var _this2 = this;
var name = block.name;
var getName = function getName(node) {
var name = '';
_this2.getPlugins().some(function (plugin) {
if (plugin.isCurrent(node)) {
name = plugin.constructor.pluginName;
return true;
}
return;
});
return name;
}; //如果是自定义列表
if (this.editor.node.isCustomize(block)) return getName(block); //如果是li标签
if ('li' === name && block.parent()) return getName(block.parent());
return '';
}
/**
* 获取列表插件名称
* @param blocks 节点集合
*/
}, {
key: "getPluginNameByNodes",
value: function getPluginNameByNodes(blocks) {
var listType = '';
for (var i = 0; i < blocks.length; i++) {
var block = blocks[i]; //节点父级
var parent = block.parent();
var type = '';
switch (block.name) {
case 'li':
case 'ul':
case 'ol':
type = this.getPluginNameByNode(blocks[i]);
break;
case 'p':
if (parent && parent.name === 'li') {
type = this.getPluginNameByNode(parent);
} else {
return '';
}
break;
default:
//如果节点内包含了列表节点,则跳过此节点
if (this.editor.node.isBlock(block) && block.find('ul,ol').length > 0) break;else return '';
}
if (listType && type && listType !== type) {
return '';
}
listType = type;
}
return listType;
}
/**
* 清除自定义列表节点相关属性
* @param node 节点
*/
}, {
key: "unwrapCustomize",
value: function unwrapCustomize(node) {
var nodeApi = this.editor.node;
if (nodeApi.isCustomize(node)) {
switch (node.name) {
case 'li':
if (nodeApi.isCustomize(node)) {
var first = node.first();
if (first === null || first === void 0 ? void 0 : first.isCard()) first.remove();
}
node.removeAttributes('class');
return node;
case 'ul':
node.removeAttributes('class');
return node;
default:
return node;
}
}
return node;
}
/**
* 取消节点的列表
* @param blocks 节点集合
* @param normalBlock 要转换的block默认为
*/
}, {
key: "unwrap",
value: function unwrap(blocks) {
var _this3 = this;
var normalBlock = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : $('');
var indent = 0;
var _this$editor = this.editor,
node = _this$editor.node,
schema = _this$editor.schema;
var globals = schema.data.globals['block'] || {};
var globalStyles = globals.style || {};
blocks.forEach(function (block) {
_this3.unwrapCustomize(block);
if (node.isList(block)) {
indent = parseInt(block.attributes(_this3.INDENT_KEY), 10) || 0;
node.unwrap(block);
}
if (block.name === 'li') {
var toBlock = node.clone(normalBlock, false, false);
if (indent !== 0) {
toBlock.css('text-indent', indent * 2 + 'em');
}
block.removeAttributes(_this3.INDENT_KEY);
var attributes = block.attributes();
Object.keys(attributes).forEach(function (name) {
if (name !== DATA_ID && name !== 'id' && globals[name]) {
toBlock.attributes(name, attributes[name]);
}
});
var styles = block.css();
if (styles['text-align']) _this3.addAlign(toBlock, styles['text-align']);
delete styles['text-align']; // 移除align样式
styles[_this3.STYLE_POSITION_NAME] = ''; // 移除不符合全局条件的样式
Object.keys(styles).forEach(function (name) {
if (!globalStyles[name]) styles[name] = '';
});
toBlock.css(styles);
node.replace(block, toBlock);
}
});
}
/**
* 获取当前选区的修复列表后的节点集合
*/
}, {
key: "normalize",
value: function normalize(range) {
var editor = this.editor;
if (!isEngine(editor)) return [];
var change = editor.change,
block = editor.block,
node = editor.node;
range = range || change.range.get();
var blocks = block.getBlocks(range);
var listNodes = [];
blocks.forEach(function (block, i) {
var parent = block.parent(); //节点是p标签
if (block.name === 'p') {
//p标签被li节点包裹时,去除p标签,并保留子节点和内容
if ((parent === null || parent === void 0 ? void 0 : parent.name) === 'li') {
if (i === 0) {
listNodes.push(parent);
} //去除包裹
node.unwrap(block);
return;
} // =>
if (parent && ['ul', 'ol'].indexOf(parent.name) > -1) {
block = node.replace(block, $(''));
listNodes.push(block);
return;
}
}
if (block.name === 'li' && (parent === null || parent === void 0 ? void 0 : parent.name) === 'li') {
// a => a
if (i === 0) {
listNodes.push(parent);
}
node.unwrap(block);
return;
}
if (['ul', 'ol'].indexOf(block.name) > -1) {
// => ...
if ((parent === null || parent === void 0 ? void 0 : parent.name) === 'li') {
node.unwrap(block);
return;
}
}
listNodes.push(block);
}); // 最后一个 li 如果没选中内容,会在 getBlocks 时抛弃掉,这里需要补回来
var lastBlock = range.endNode.closest('li');
if (!listNodes.some(function (block) {
return block[0] === lastBlock[0];
})) {
listNodes.push(lastBlock);
}
return listNodes;
}
/**
* 将选中列表项列表分割出来单独作为一个列表
*/
}, {
key: "split",
value: function split(range) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
node = editor.node;
var safeRange = range || change.range.toTrusty();
var blocks = this.normalize(range);
if (blocks.length > 0 && (blocks[0].name === 'li' || blocks[blocks.length - 1].name === 'li')) {
var selection = safeRange.createSelection();
var firstBlock = blocks[0];
var lastBlock = blocks[blocks.length - 1];
var middleList = [];
var rightList = [];
var beforeListElement; //选区中最后的li节点的列表节点
var afterListElement; // 当前选中的第一个节点是li,并且这个节点前面还有节点,那就获取选中的节点所在列表的后续节点然后放入middleList
if (firstBlock.prev()) {
beforeListElement = firstBlock.parent();
var indexInRange = 0;
while (blocks[indexInRange] && blocks[indexInRange].name === 'li') {
middleList.push(blocks[indexInRange]);
indexInRange += 1;
}
} // 当前选中的最后一个节点是li,那么获取到这个列表的最后所有的li节点放入rightList
if (lastBlock.next()) {
afterListElement = lastBlock.parent();
var nextBlock = lastBlock.next();
while (nextBlock && nextBlock.name === 'li') {
rightList.push(nextBlock);
nextBlock = nextBlock.next();
}
} //将 rightList 集合添加到最后的列表节点内
var afterListElementClone;
if (rightList.length > 0 && afterListElement) {
afterListElementClone = node.clone(afterListElement, false, false);
rightList.forEach(function (li) {
var _afterListElementClon;
(_afterListElementClon = afterListElementClone) === null || _afterListElementClon === void 0 ? void 0 : _afterListElementClon.append(li[0]);
});
afterListElement.after(afterListElementClone);
}
var beforeListElementClone; //将 middleList 集合添加到前方列表节点内
if (middleList.length > 0 && beforeListElement) {
beforeListElementClone = node.clone(beforeListElement, false, false);
middleList.forEach(function (li) {
var _beforeListElementClo;
(_beforeListElementClo = beforeListElementClone) === null || _beforeListElementClo === void 0 ? void 0 : _beforeListElementClo.append(li[0]);
});
beforeListElement.after(beforeListElementClone);
} //有序列表设置start属性
if (beforeListElement && afterListElement && afterListElement.equal(beforeListElement) && beforeListElement.name === 'ol') {
var newStart = (parseInt(beforeListElement.attributes('start'), 10) || 1) + beforeListElement.find('li').length;
afterListElementClone.attributes('start', newStart);
}
selection.move();
}
if (!range) change.apply(safeRange);
}
}, {
key: "merge",
value: function merge(blocks, range) {
var _this4 = this;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
block = editor.block,
node = editor.node,
schema = editor.schema;
var tags = schema.getCanMergeTags();
if (tags.length === 0) return;
var safeRange = range || change.range.toTrusty();
var cloneRange = safeRange.cloneRange();
var selection = blocks ? undefined : cloneRange.shrinkToElementNode().createSelection();
blocks = blocks || block.getBlocks(safeRange);
var hasMerged = false;
blocks.forEach(function (block) {
block = block.closest('ul,ol');
if (!node.isList(block) || tags.indexOf(block.name) === -1) {
return;
}
var prevBlock = block.prev();
var nextBlock = block.next();
if (prevBlock && _this4.isSame(prevBlock, block)) {
node.merge(prevBlock, block); // 原来 block 已经被移除,重新指向
block = prevBlock;
hasMerged = true;
}
if (nextBlock && _this4.isSame(nextBlock, block)) {
node.merge(block, nextBlock);
hasMerged = true;
}
});
if (hasMerged) {
blocks = block.getBlocks(safeRange);
if (blocks.length > 0) {
var _block = blocks[0].closest('ul,ol');
this.addStart(_block);
}
}
selection === null || selection === void 0 ? void 0 : selection.move();
if (!range && selection !== undefined) change.apply(cloneRange);
}
/**
* 给列表添加start序号
* @param block 列表节点
*/
}, {
key: "addStart",
value: function addStart(block) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
node = editor.node;
if (!block) {
var blocks = editor.block.getBlocks(change.range.get());
if (blocks.length === 0) return;
block = blocks[0].closest('ul,ol');
}
if (!block || !node.isList(block)) return;
var startIndent = parseInt(block.attributes(this.INDENT_KEY), 10) || 0; // 当前选区起始位置如果不是第一层级,需要向前遍历,找到各层级的前序序号
// 直到遇到一个非列表截止,比如 p
var startCache = [];
var cacheIndent = startIndent;
var prevNode = block.prev();
while (prevNode && node.isList(prevNode)) {
if (prevNode.name === 'ol') {
var prevIndent = parseInt(prevNode.attributes(this.INDENT_KEY), 10) || 0;
var prevStart = parseInt(prevNode.attributes('start'), 10) || 1;
var len = prevNode.find('li').length;
if (prevIndent === 0) {
startCache[prevIndent] = prevStart + len;
break;
}
if (prevIndent <= cacheIndent) {
cacheIndent = prevIndent;
startCache[prevIndent] = startCache[prevIndent] || prevStart + len;
}
} else {
cacheIndent = parseInt(prevNode.attributes(this.INDENT_KEY), 10) || 0;
}
prevNode = prevNode.prev();
}
var nextNode = block;
while (nextNode) {
if (node.isList(nextNode)) {
var nextIndent = parseInt(nextNode.attributes(this.INDENT_KEY), 10) || 0;
var nextStart = parseInt(nextNode.attributes('start'), 10);
var _len = nextNode.find('li').length;
if (nextNode.name === 'ol') {
var currentStart = startCache[nextIndent];
if (nextIndent > 0) {
currentStart = currentStart || 1;
if (currentStart > 1) nextNode.attributes('start', currentStart);else nextNode.removeAttributes('start');
startCache[nextIndent] = currentStart + _len;
} else {
if (currentStart && currentStart !== nextStart) {
if (currentStart > 1) nextNode.attributes('start', currentStart);else nextNode.removeAttributes('start');
startCache[nextIndent] = currentStart + _len;
} else {
startCache[nextIndent] = (nextStart || 1) + _len;
startCache = startCache.slice(0, nextIndent + 1);
}
}
}
} else startCache = [];
var next = nextNode.next();
if (!next) break;
nextNode = next;
}
}
/**
* 给列表节点增加缩进
* @param block 列表节点
* @param value 缩进值
*/
}, {
key: "addIndent",
value: function addIndent(block, value, maxValue) {
if (this.editor.node.isList(block)) {
var indentValue = this.getIndent(block);
value = indentValue + (value < 0 ? -1 : 1);
if (maxValue && value > maxValue) value = maxValue;
if (value < 1) {
block.removeAttributes(this.INDENT_KEY);
} else {
block.attributes(this.INDENT_KEY, value);
}
}
}
/**
* 获取列表节点 indent 值
* @param block 列表节点
* @returns
*/
}, {
key: "getIndent",
value: function getIndent(block) {
if (this.editor.node.isList(block)) {
return parseInt(block.attributes(this.INDENT_KEY), 10) || 0;
}
return 0;
}
/**
* 给列表节点增加文字方向
* @param block 列表项节点
* @param align 方向
* @returns
*/
}, {
key: "addAlign",
value: function addAlign(block, align) {
if (block.name !== 'li') return;
if (align && align !== 'left') {
if (['center', 'right'].indexOf(align) > -1) {
block.css(_defineProperty({}, this.STYLE_POSITION_NAME, this.STYLE_POSITION_VALUE));
}
block.css({
'text-align': align
});
} else {
var _block$css2;
block.css((_block$css2 = {}, _defineProperty(_block$css2, this.STYLE_POSITION_NAME, ''), _defineProperty(_block$css2, 'text-align', ''), _block$css2));
}
}
/**
* 为自定义列表项添加卡片节点
* @param node 列表节点项
* @param cardName 卡片名称,必须是支持inline卡片类型
* @param value 卡片值
*/
}, {
key: "addCardToCustomize",
value: function addCardToCustomize(node, cardName, value) {
var _node$get$childNodes$, _node$get;
if (isNode(node)) node = $(node); //必须是li标签
if (node.name !== 'li') return; //第一个子节点必须不是相同卡片
var first = node.first();
if ((first === null || first === void 0 ? void 0 : first.isBlockCard()) || (first === null || first === void 0 ? void 0 : first.isCard()) && first.attributes(CARD_KEY) === cardName) return;
var editor = this.editor; //创建卡片
var card = editor.card;
var component = card.create(cardName, {
value: value
});
var range = Range.create(editor); //设置光标选中空的标签,在这个位置插入卡片
var br = $('
');
if (((_node$get$childNodes$ = (_node$get = node.get()) === null || _node$get === void 0 ? void 0 : _node$get.childNodes.length) !== null && _node$get$childNodes$ !== void 0 ? _node$get$childNodes$ : 0) > 0) {
var _node$first;
(_node$first = node.first()) === null || _node$first === void 0 ? void 0 : _node$first.before(br);
} else {
node.append(br);
}
range.select(br, true); //插入卡片
card.insertNode(range, component);
var lastNode = node.last();
if ((lastNode === null || lastNode === void 0 ? void 0 : lastNode.name) === 'br') {
lastNode.remove();
}
return component;
}
/**
* 为自定义列表项添加待渲染卡片节点
* @param node 列表节点项
* @param cardName 卡片名称,必须是支持inline卡片类型
* @param value 卡片值
*/
}, {
key: "addReadyCardToCustomize",
value: function addReadyCardToCustomize(node, cardName, value) {
if (isNode(node)) node = $(node); //必须是li标签
if (node.name !== 'li') return; //第一个子节点必须不是卡片
var first = node.first();
if ((first === null || first === void 0 ? void 0 : first.isBlockCard()) || (first === null || first === void 0 ? void 0 : first.isCard()) && first.attributes(CARD_KEY) === cardName) return;
var cardRoot = $('');
node.prepend(cardRoot);
this.editor.card.replaceNode(cardRoot, cardName, value);
return cardRoot;
}
/**
* 给列表添加BR标签
* @param node 列表节点项
*/
}, {
key: "addBr",
value: function addBr(node) {
var _this5 = this;
var nodeApi = this.editor.node;
if (nodeApi.isList(node)) {
node.find('li').each(function (node) {
_this5.addBr($(node));
});
} else if (nodeApi.isCustomize(node)) {
var child = node.last();
while ((_child = child) === null || _child === void 0 ? void 0 : _child.isCursor()) {
var _child;
child = child.prev();
}
if (child) {
//自定义节点,并且最后一个是卡片
var children = node.children();
if (children.length === 1 && child.isCard()) {
node.append($('
'));
return;
}
if (children.length > 2 && child.name === 'br') {
var _child$prev;
if (((_child$prev = child.prev()) === null || _child$prev === void 0 ? void 0 : _child$prev.name) !== 'br') child.remove();
return;
}
while (child) {
if (child.equal(node.first()) && (child.isCard() || child.text() === '')) {
node.append($('
'));
return;
} //文本
if (child.type === Node.TEXT_NODE) {
if (child.text() !== '') return;
child = child.prev();
} //节点
else if (child.type === Node.ELEMENT_NODE) {
if (!nodeApi.isMark(child) || child.text() !== '') return;
child = node.prev();
} //其它
else child = child.prev();
}
} else node.append($('
'));
}
}
}, {
key: "insert",
value: function insert(fragment, range) {
var _startElement,
_startElement2,
_startElement3,
_this6 = this;
var editor = this.editor;
if (!isEngine(editor) || fragment.childNodes.length === 0) return;
var change = editor.change,
node = editor.node,
block = editor.block;
var safeRange = range || change.range.toTrusty(); // 光标展开,先删除内容
if (!safeRange.collapsed) change.delete(safeRange, true, true);
var cloneRange = safeRange.cloneRange().shrinkToElementNode();
var startNode = cloneRange.startNode,
startOffset = cloneRange.startOffset;
var startElement = startNode; // 如果是列表,取 offset 的li
if (node.isList(startNode)) {
startElement = startNode.children().eq(startOffset);
}
startElement = (_startElement = startElement) === null || _startElement === void 0 ? void 0 : _startElement.closest('li', function (n) {
return node.isBlock(n) && n.nodeName !== 'LI' ? undefined : n.parentElement || undefined;
}); // 非li不操作
if (((_startElement2 = startElement) === null || _startElement2 === void 0 ? void 0 : _startElement2.length) === 0 || ((_startElement3 = startElement) === null || _startElement3 === void 0 ? void 0 : _startElement3.name) !== 'li') return; // 缩小范围到文本节点
safeRange.shrinkToElementNode().shrinkToTextNode(); // 把列表分割扣出来
//this.split(safeRange);
// 从光标处分割
block.split(safeRange); // 把列表分割扣出来
var selection = safeRange.createSelection('list-insert');
this.split(safeRange);
var apply = function apply(newRange) {
block.merge(newRange);
_this6.merge(undefined, newRange);
selection === null || selection === void 0 ? void 0 : selection.move();
if (!range) {
change.apply(newRange);
}
}; // 第一个节点嵌入到分割节点位置
var beginNode = $(fragment).toArray().some(function (child) {
return node.isBlock(child);
}) ? $(fragment.childNodes[0]) : $('').append($(fragment)); // 要插入的是列表
var listElement = safeRange.startNode.closest('ul,ol');
if (!listElement || !node.isList(listElement)) {
apply(safeRange);
return;
}
var startLi = safeRange.startNode.closest('li'); // 自定义列表节点,补充被切割后的li里面的卡片
if (node.isCustomize(listElement)) {
var _listElement$prev, _listElement$prev$fir;
var cardElement = (_listElement$prev = listElement.prev()) === null || _listElement$prev === void 0 ? void 0 : (_listElement$prev$fir = _listElement$prev.first()) === null || _listElement$prev$fir === void 0 ? void 0 : _listElement$prev$fir.first();
if (cardElement) {
var cardComponent = editor.card.find(cardElement);
if (cardComponent) this.addCardToCustomize(startLi, cardComponent.name, cardComponent.getValue());
}
} // 要插入的不是一个列表,或者是相同的列表,就把第一个节点内容追加到分割后的li后面
var startIsMerge = !node.isList(beginNode) || this.isSame(listElement, beginNode);
if (startIsMerge) {
var _startLi$parent, _startLi$parent$prev;
while (node.isBlock(beginNode)) {
// 如果第一个子节点还是block节点就取这个节点作为第一个节点
var first = beginNode.first();
if (first && node.isBlock(first)) {
beginNode = first;
continue;
} // 如果不是就跳出
break;
} // 删除多余的br标签
var beforeELement = (_startLi$parent = startLi.parent()) === null || _startLi$parent === void 0 ? void 0 : (_startLi$parent$prev = _startLi$parent.prev()) === null || _startLi$parent$prev === void 0 ? void 0 : _startLi$parent$prev.last();
if ((beforeELement === null || beforeELement === void 0 ? void 0 : beforeELement.name) === 'li') {
var beforeChildren = beforeELement === null || beforeELement === void 0 ? void 0 : beforeELement.children();
beforeChildren === null || beforeChildren === void 0 ? void 0 : beforeChildren.each(function (child, index) {
var _beforeChildren$eq;
if (child.nodeName === 'BR') (_beforeChildren$eq = beforeChildren.eq(index)) === null || _beforeChildren$eq === void 0 ? void 0 : _beforeChildren$eq.remove();
}); // 自定义列表,删除第一个卡片
if (node.isCustomize(beginNode)) {
var _beginNode$first;
(_beginNode$first = beginNode.first()) === null || _beginNode$first === void 0 ? void 0 : _beginNode$first.remove();
}
if (beginNode.isBlockCard()) {
var _beforeELement$parent;
(_beforeELement$parent = beforeELement.parent()) === null || _beforeELement$parent === void 0 ? void 0 : _beforeELement$parent.after(beginNode);
} else {
beforeELement === null || beforeELement === void 0 ? void 0 : beforeELement.append(node.isBlock(beginNode) ? beginNode.children() : beginNode);
if (beforeELement) this.addBr(beforeELement);
if (node.isBlock(beginNode)) {
beginNode.remove();
}
}
}
} else {
var _startLi$parent2, _startLi$parent2$prev;
// 如果开头位置不用拼接,判断是否是空节点,空节点就移除
var _beforeELement = (_startLi$parent2 = startLi.parent()) === null || _startLi$parent2 === void 0 ? void 0 : (_startLi$parent2$prev = _startLi$parent2.prev()) === null || _startLi$parent2$prev === void 0 ? void 0 : _startLi$parent2$prev.last();
if (_beforeELement && (node.isEmpty(_beforeELement) || this.isEmptyItem(_beforeELement))) {
var _beforeELement$parent2, _beforeELement$parent3, _beforeELement$parent4;
_beforeELement.remove();
if (((_beforeELement$parent2 = _beforeELement.parent()) === null || _beforeELement$parent2 === void 0 ? void 0 : (_beforeELement$parent3 = _beforeELement$parent2.get()) === null || _beforeELement$parent3 === void 0 ? void 0 : _beforeELement$parent3.childNodes.length) === 0) (_beforeELement$parent4 = _beforeELement.parent()) === null || _beforeELement$parent4 === void 0 ? void 0 : _beforeELement$parent4.remove();
}
} // 只有一行
if (fragment.childNodes.length === 0 || fragment.childNodes.length === 1 && node.isList(fragment.childNodes[0]) && fragment.childNodes[0].childNodes.length === 0) {
var parent = startLi.parent();
if (!beginNode.isBlockCard()) {
var _parent$prev, _parent$prev$last;
if (node.isCustomize(startLi)) {
var _startLi$first;
(_startLi$first = startLi.first()) === null || _startLi$first === void 0 ? void 0 : _startLi$first.remove();
}
startLi.find('br').remove();
parent === null || parent === void 0 ? void 0 : (_parent$prev = parent.prev()) === null || _parent$prev === void 0 ? void 0 : (_parent$prev$last = _parent$prev.last()) === null || _parent$prev$last === void 0 ? void 0 : _parent$prev$last.append(startLi.children());
parent === null || parent === void 0 ? void 0 : parent.remove();
} else if (parent) {
var _parent$get;
if (this.isEmptyItem(startLi) && ((_parent$get = parent.get()) === null || _parent$get === void 0 ? void 0 : _parent$get.childNodes.length) === 1) {
parent.remove();
}
var mergeNodes = [parent];
var prev = beginNode.prev();
if (prev && node.isList(prev)) mergeNodes.push(prev);
this.merge(mergeNodes);
}
apply(safeRange);
return;
}
var startListElment = safeRange.startNode.closest('li').parent();
if (!startListElment) {
apply(safeRange);
return;
}
var fragmentLength = fragment.childNodes.length;
var endNode = $(fragment.childNodes[fragmentLength - 1]);
var endIsMerge = (!node.isList(endNode) || this.isSame(listElement, endNode)) && !endNode.isBlockCard(); // 如果集合中有列表或者block card,使用原节点,如果没有,其它节点都转换为列表
var hasList = false;
for (var i = 0; i < fragment.childNodes.length; i++) {
var childnode = $(fragment.childNodes[i]);
if (node.isList(fragment.childNodes[i]) && !this.isSame(listElement, childnode) || childnode.isBlockCard()) {
hasList = true;
break;
}
}
var prevListElement = startListElment.prev();
var mergeLists = prevListElement ? [prevListElement] : []; // 需要判断最后一个是否交给最后一个节点做合并,如果集合总含有列表就不合并
for (var _i = 0; _i < (endIsMerge && !hasList ? fragmentLength - 1 : fragmentLength); _i++) {
// 每处理一个fragment中的集合就少一个,所以这里始终使用0做为索引
var childElement = $(fragment.childNodes[0]); // 如果是列表
if (node.isList(childElement)) {
var _childElement$get;
if (((_childElement$get = childElement.get()) === null || _childElement$get === void 0 ? void 0 : _childElement$get.childNodes.length) === 0) {
childElement.remove();
continue;
}
startListElment.before(childElement);
mergeLists.push(childElement);
} else {
// 追加为普通节点
if (hasList) {
startListElment === null || startListElment === void 0 ? void 0 : startListElment.before(childElement);
continue;
} // 如果是block节点,要把它的所有子block节点都unwrap
if (node.isBlock(childElement)) {
childElement.allChildren().forEach(function (child) {
if (child.type === getDocument().TEXT_NODE) return;
if (node.isBlock(child)) node.unwrap(child);
});
} // 自定义列表
if (node.isCustomize(startListElment)) {
var _startListElment$firs;
var firstCard = (_startListElment$firs = startListElment.first()) === null || _startListElment$firs === void 0 ? void 0 : _startListElment$firs.first();
if (firstCard && firstCard.isCard()) {
var cardName = firstCard.attributes(CARD_KEY) || firstCard.attributes('name');
var customizeList = this.toCustomize(childElement, cardName);
if (customizeList) {
(Array.isArray(customizeList) ? customizeList : [customizeList]).forEach(function (child) {
startListElment === null || startListElment === void 0 ? void 0 : startListElment.before(child);
});
}
}
} else {
// 非自定义列表
var listElements = this.toNormal(childElement, startListElment.name);
(Array.isArray(listElements) ? listElements : [listElements]).forEach(function (child) {
if (editor.node.isList(child)) startListElment === null || startListElment === void 0 ? void 0 : startListElment.before(child);
});
}
}
}
if (mergeLists.length > 0) this.merge(mergeLists);
if (!startIsMerge && node.isEmptyWidthChild(startListElment)) startListElment.remove(); // 后续不需要拼接到最后节点
if (fragment.childNodes.length === 0) {
// 删除由于分割造成的空行
if (node.isEmpty(startLi) || this.isEmptyItem(startLi)) {
var _startLi$parent3, _startLi$first2, _prevElement$last, _startLi$parent4;
var prevElement = (_startLi$parent3 = startLi.parent()) === null || _startLi$parent3 === void 0 ? void 0 : _startLi$parent3.prev();
startLi.find('br').remove();
if (node.isCustomize(startLi)) (_startLi$first2 = startLi.first()) === null || _startLi$first2 === void 0 ? void 0 : _startLi$first2.remove();
if (prevElement && node.isList(prevElement)) (_prevElement$last = prevElement.last()) === null || _prevElement$last === void 0 ? void 0 : _prevElement$last.append(startLi.children()); // 把光标位置放到前面的li里面
else if (prevElement) prevElement.append(startLi.children());
(_startLi$parent4 = startLi.parent()) === null || _startLi$parent4 === void 0 ? void 0 : _startLi$parent4.remove();
}
apply(safeRange);
return;
} // 最后一个节点嵌入到分割后的最后一个节点内容前面
while (node.isBlock(endNode)) {
// 如果最后一个子节点还是block节点就取这个节点作为最后一个节点
var last = endNode.last();
if (last && node.isBlock(last)) {
endNode = last;
continue;
} // 如果不是就跳出
break;
}
var lasetELement = startLi;
if (lasetELement) {
var _endNode$parent;
if (!((_endNode$parent = endNode.parent()) === null || _endNode$parent === void 0 ? void 0 : _endNode$parent.fragment)) {
var beforeElement = lasetELement;
var _prev = endNode.prev();
while (_prev && _prev.length > 0) {
var pN = _prev.prev();
beforeElement.before(_prev);
beforeElement = _prev;
_prev = pN;
}
} // 删除多余的br标签
if (endNode.name === 'br') endNode.remove();else {
var endChildren = endNode.children();
endChildren.each(function (child, index) {
var _endChildren$eq;
if (child.nodeName === 'BR') (_endChildren$eq = endChildren.eq(index)) === null || _endChildren$eq === void 0 ? void 0 : _endChildren$eq.remove();
});
if (node.isCustomize(lasetELement)) {
var _lasetELement$first;
if (node.isCustomize(endNode)) {
var endNodeCard = endNode.first();
if (endNodeCard === null || endNodeCard === void 0 ? void 0 : endNodeCard.isCard()) endNodeCard.remove();
}
(_lasetELement$first = lasetELement.first()) === null || _lasetELement$first === void 0 ? void 0 : _lasetELement$first.after(node.isBlock(endNode) ? endNode.children() : endNode);
} else {
lasetELement.prepend(node.isBlock(endNode) ? endNode.children() : endNode);
}
this.addBr(lasetELement);
if (node.isBlock(endNode)) endNode.remove();
}
}
apply(safeRange);
}
/**
* block 节点转换为列表项节点
* @param block block 节点
* @param root 列表根节点
* @param cardName 可选,自定义列表项卡片名称
* @param value 可选,自定义列表项卡片值
* @returns
*/
}, {
key: "blockToItem",
value: function blockToItem(block, root, cardName, value) {
var item = $('');
var _this$editor2 = this.editor,
node = _this$editor2.node,
schema = _this$editor2.schema;
if (!node.isList(root)) return root; // 获取缩进
var indent = removeUnit(block.css('text-indent')) / 2; // 复制全局属性
var globals = schema.data.globals['block'] || {};
var attributes = block.attributes();
Object.keys(attributes).forEach(function (name) {
if (name !== DATA_ID && name !== 'id' && globals['name']) {
item.attributes(name, attributes[name]);
}
}); // 复制全局样式,及生成 text-align
var globalStyles = globals.style || {};
var styles = block.css();
if (styles['text-align']) this.addAlign(item, styles['text-align']);
delete styles['text-align'];
delete styles[this.STYLE_POSITION_NAME];
Object.keys(styles).forEach(function (name) {
if (!globalStyles[name]) delete styles[name];
});
item.css(styles); // 替换
block = node.replace(block, item); // 如果是自定义列表,增加卡片
if (cardName) {
block.addClass(this.CUSTOMZIE_LI_CLASS);
this.addCardToCustomize(block, cardName, value);
} // 如果有设置缩进,就设置缩进属性
if (indent) {
root.attributes(this.INDENT_KEY, indent);
}
return node.wrap(block, root);
}
/**
* 将节点转换为自定义节点
* @param blocks 节点
* @param cardName 卡片名称
* @param value 卡片值
*/
}, {
key: "toCustomize",
value: function toCustomize(blocks, cardName, value) {
var _this7 = this;
var tagName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'ul';
var node = this.editor.node;
if (Array.isArray(blocks)) {
var nodes = [];
blocks.forEach(function (block) {
if (node.isCustomize(block)) {
_this7.unwrapCustomize(block);
}
nodes = nodes.concat(_this7.toCustomize(block, cardName, value, tagName));
});
return nodes;
} else {
var customizeRoot = $("<".concat(tagName, " class=\"").concat(this.CUSTOMZIE_UL_CLASS, "\"/>"));
switch (blocks.name) {
case 'li':
blocks.addClass(this.CUSTOMZIE_LI_CLASS);
this.addCardToCustomize(blocks, cardName, value);
return blocks;
case 'ul':
case 'ol':
customizeRoot.attributes(blocks.attributes());
blocks = node.replace(blocks, customizeRoot);
return blocks;
default:
if (blocks.name === 'p' || node.isNestedBlock(blocks) && !blocks.isBlockCard()) {
var _blocks$parent;
if (((_blocks$parent = blocks.parent()) === null || _blocks$parent === void 0 ? void 0 : _blocks$parent.name) === 'li') {
node.unwrap(blocks);
return blocks;
}
blocks = this.blockToItem(blocks, customizeRoot, cardName, value);
}
return blocks;
}
}
}
/**
* 将节点转换为列表节点
* @param blocks 节点
* @param tagName 列表节点名称,ul 或者 ol
* @param start 有序列表开始序号
*/
}, {
key: "toNormal",
value: function toNormal(blocks) {
var _this8 = this;
var tagName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'ul';
var start = arguments.length > 2 ? arguments[2] : undefined;
var node = this.editor.node;
if (Array.isArray(blocks)) {
var nodes = [];
blocks.forEach(function (block) {
var node = _this8.toNormal(block, tagName, start);
nodes = nodes.concat(node);
});
return nodes;
} else {
this.unwrapCustomize(blocks);
var targetNode = $('<'.concat(tagName, ' />'));
switch (blocks.name) {
case 'li':
case tagName:
return blocks;
case 'ol':
case 'ul':
targetNode.attributes(blocks.attributes());
if (targetNode.name === 'ul') targetNode.removeAttributes('start');
blocks = node.replace(blocks, targetNode);
return blocks;
default:
if (blocks.name === 'p' || node.isNestedBlock(blocks) && !blocks.isBlockCard()) {
var _blocks$parent2;
if (((_blocks$parent2 = blocks.parent()) === null || _blocks$parent2 === void 0 ? void 0 : _blocks$parent2.name) === 'li') {
node.unwrap(blocks);
return blocks;
}
blocks = this.blockToItem(blocks, targetNode);
if (start) {
blocks.attributes('start', start);
}
}
return blocks;
}
}
}
/**
* 判断选中的区域是否在List列表的开始
*/
}, {
key: "isFirst",
value: function isFirst(range) {
//获取选区开始节点和位置偏移值
var startNode = range.startNode,
startOffset = range.startOffset; //复制选区
var cloneRange = range.cloneRange(); //找到li节点
var node = 'li' === startNode.name ? startNode : startNode.closest('li'); //如果没有li节点
if (!node[0]) return false; //让选区选择li节点
cloneRange.select(node, true); //设置选区结束位置偏移值
cloneRange.setEnd(startNode[0], startOffset); //复制选区内容
var contents = cloneRange.cloneContents(); //如果选区中没有节点
if (!contents.firstChild) return true;
var firstChild = $(contents.firstChild);
var lastChild = $(contents.lastChild || []); //如果选区中只有一个节点,并且是br标签
if (1 === contents.childNodes.length && 'br' === firstChild.name) return true; //如果选区中只有一个节点,并且是自定义列表并且第一个是Card
if (1 === contents.childNodes.length && node.hasClass(this.CUSTOMZIE_LI_CLASS) && firstChild.isCard()) return true;
var nodeApi = this.editor.node; //如果选区中只有两个节点,并且是自定义列表并且第一个是Card,最后一个为空节点
if (2 === contents.childNodes.length && node.hasClass(this.CUSTOMZIE_LI_CLASS) && firstChild.isCard() && nodeApi.isEmpty(lastChild)) return true; //判断选区内容是否是空节点
var block = $('');
block.append(contents);
return nodeApi.isEmpty(block);
}
/**
* 判断选中的区域是否在List列表的末尾
*/
}, {
key: "isLast",
value: function isLast(range) {
//获取选区范围结束节点和结束位置偏移值
var endNode = range.endNode,
endOffset = range.endOffset; //复制选区
var cloneRange = range.cloneRange(); //找到li节点
var node = 'li' === endNode.name ? endNode : endNode.closest('li'); //如果没有li节点
if (!node[0]) return false; //让选区选择li节点
cloneRange.select(node, true); //设置选区开始位置偏移值
cloneRange.setStart(endNode, endOffset); //复制选区内容
var contents = cloneRange.cloneContents(); //如果选区中没有节点
if (!contents.firstChild) return true;
var firstChild = $(contents.firstChild);
var lastChild = $(contents.lastChild || []); //如果选区中只有一个节点,并且是br标签
if (1 === contents.childNodes.length && 'br' === firstChild.name) return true; //如果选区中只有一个节点,并且是自定义列表并且第一个是Card
if (1 === contents.childNodes.length && node.hasClass(this.CUSTOMZIE_LI_CLASS) && firstChild.isCard()) return true;
var nodeApi = this.editor.node; //如果选区中只有两个节点,并且是自定义列表并且第一个是Card,最后一个为空节点
if (2 === contents.childNodes.length && node.hasClass(this.CUSTOMZIE_LI_CLASS) && firstChild.isCard() && nodeApi.isEmpty(lastChild)) return true; //判断选区内容是否是空节点
var block = $('');
block.append(contents);
return nodeApi.isEmpty(block);
}
}]);
return List;
}();
var Backspace$4 = /*#__PURE__*/function () {
function Backspace(engine) {
_classCallCheck(this, Backspace);
this.engine = void 0;
this.engine = engine;
}
/**
* 在inline节点处按下backspace键
*/
_createClass(Backspace, [{
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
node = _this$engine.node,
block = _this$engine.block;
var range = change.range.get();
var _range$cloneRange$shr = range.cloneRange().shrinkToTextNode(),
collapsed = _range$cloneRange$shr.collapsed,
endNode = _range$cloneRange$shr.endNode,
startNode = _range$cloneRange$shr.startNode,
startOffset = _range$cloneRange$shr.startOffset,
endOffset = _range$cloneRange$shr.endOffset; // 空的block节点下不处理mark
if (collapsed) {
var blockNode = block.closest(startNode);
if (blockNode.length > 0 && node.isEmpty(blockNode)) {
return;
}
}
if (endNode.type === Node.TEXT_NODE || startNode.type === Node.TEXT_NODE) {
//光标展开的情况下,判断光标结束位置是否在mark节点内侧零宽字符后面,不在后面让光标选在后面
if (!collapsed) {
var _markNode = endNode.parent();
if (_markNode && endNode.type === Node.TEXT_NODE && node.isMark(_markNode)) {
var text = endNode.text();
var rightText = text.substr(endOffset); //不位于零宽字符前,不处理
if (!/^\u200b$/.test(rightText)) return true;
range.setEnd(endNode, endOffset + 1);
}
return true;
}
var markNode = startNode.parent(); //开始节点在mark标签内
if (markNode && startNode.type === Node.TEXT_NODE && node.isMark(markNode)) {
if (startOffset < 1) return true;
var _text = startNode.text();
var leftText = _text.substr(startOffset - 1, 1); //不位于零宽字符后,不处理
if (!/^\u200b$/.test(leftText)) return true;
if (startOffset === 1) {
var prev = markNode.prev();
if (prev && !node.isEmpty(prev)) {
var _range$cloneRange$sel = range.cloneRange().select(prev, true).shrinkToTextNode().collapse(false),
_startNode = _range$cloneRange$sel.startNode,
_startOffset = _range$cloneRange$sel.startOffset;
range.setStart(_startNode, _startOffset - 1);
} //在段落的开始位置
else if (!prev && node.isEmpty(markNode)) {
var parent = markNode.parent();
var offset = markNode.getIndex();
markNode.remove();
if (parent) range.setStart(parent, offset <= 0 ? 0 : offset - 1);
}
} else {
range.setStart(startNode, startOffset - 1);
}
return true;
} //mark 标签后面的零宽字符后删除零宽字符前面的字符
markNode = startNode.prev() || undefined;
if (markNode && startNode.type === Node.TEXT_NODE && node.isMark(markNode)) {
var _text2 = startNode.text();
var _leftText = _text2.substr(startOffset - 1, 1); //不位于零宽字符后,不处理
if (!/^\u200b$/.test(_leftText)) return true;
if (startOffset === 1) {
var _range$cloneRange$sel2 = range.cloneRange().select(markNode, true).shrinkToTextNode().collapse(false),
_startNode2 = _range$cloneRange$sel2.startNode,
_startOffset2 = _range$cloneRange$sel2.startOffset;
range.setStart(_startNode2, _startOffset2 - 1);
} else {
range.setStart(startNode, startOffset > 0 ? startOffset - 1 : 0);
}
}
}
return true;
}
}]);
return Backspace;
}();
var Mark = /*#__PURE__*/function () {
function Mark(editor) {
var _this = this;
_classCallCheck(this, Mark);
this.editor = void 0;
this.pluginCaches = new Map();
this.findSameParent = function (parentMark, sourceMark) {
var node = _this.editor.node;
if (node.isMark(parentMark)) {
var parent = undefined;
if (_this.compare(parentMark, sourceMark, true)) {
return true;
} else if (parent = parentMark.parent()) {
return _this.findSameParent(parent, sourceMark);
}
}
return false;
};
this.editor = editor;
}
_createClass(Mark, [{
key: "init",
value: function init() {
var _this2 = this;
var editor = this.editor;
if (isEngine(editor)) {
var _editor$typing$getHan;
//删除事件
var backspace = new Backspace$4(editor);
(_editor$typing$getHan = editor.typing.getHandleListener('backspace', 'keydown')) === null || _editor$typing$getHan === void 0 ? void 0 : _editor$typing$getHan.on(function (event) {
return backspace.trigger(event);
});
editor.on('keydown:space', function (event) {
return _this2.triggerMarkdown(event);
});
editor.on('keydown:enter', function (event) {
return _this2.triggerMarkdown(event);
});
}
}
/**
* 解析markdown
* @param event 事件
*/
}, {
key: "triggerMarkdown",
value: function triggerMarkdown(event) {
var _editor$options$markd;
var editor = this.editor;
if (!isEngine(editor) || ((_editor$options$markd = editor.options.markdown) === null || _editor$options$markd === void 0 ? void 0 : _editor$options$markd.mode) === false) return;
var change = editor.change;
var range = change.range.get();
if (!range.collapsed || change.isComposing()) return;
var _range$cloneRange$shr = range.cloneRange().shrinkToTextNode(),
startNode = _range$cloneRange$shr.startNode,
startOffset = _range$cloneRange$shr.startOffset;
var node = startNode.type === Node.TEXT_NODE ? startNode : startNode.children().eq(startOffset - 1);
if (!node) return;
var cacheRange = range.toPath();
var text = node.type === Node.TEXT_NODE ? node.text().substr(0, startOffset) : node.text();
var markdown = createMarkdownIt(editor, 'zero');
var renderer = markdown.renderer,
options = markdown.options;
var tokens = markdown.parseInline(text, {});
if (tokens.length === 0) return;
var isHit = false;
var textContent = '';
tokens.forEach(function (token) {
var lineContent = '';
var children = token.children || [];
children.forEach(function (child, index) {
var type = child.type;
var result = editor.trigger('markdown-it-token', {
token: token,
markdown: markdown,
callback: function callback(result) {
lineContent += result;
}
});
if (result === false) {
isHit = true;
return;
}
if (!isHit && type !== 'text') {
isHit = true;
}
if (typeof renderer.rules[type] !== 'undefined') {
lineContent += renderer.rules[type](children, index, options, {}, renderer);
} else {
lineContent += renderer.renderToken(children, index, options);
}
});
textContent += lineContent;
});
if (isHit) {
var nodeApi = editor.node;
event.preventDefault();
range.setStart(node[0], 0);
range.setEnd(node[0], startOffset);
change.paste(textContent, range);
change.rangePathBeforeCommand = cacheRange;
range.collapse(false);
range.enlargeToElementNode();
var contentNode = $(textContent);
var last = contentNode.last();
var lastNode = contentNode.eq(contentNode.length - 1);
if (nodeApi.isMark(contentNode) || last && nodeApi.isMark(last) || lastNode && nodeApi.isMark(lastNode)) nodeApi.insertText('\xa0', range);
change.range.select(range);
}
return !isHit;
}
}, {
key: "findPlugin",
value:
/**
* 根据节点查找mark插件实例
* @param node 节点
*/
function findPlugin(mark) {
var _this$editor = this.editor,
node = _this$editor.node,
plugin = _this$editor.plugin,
schema = _this$editor.schema;
if (mark.length === 0 || !node.isMark(mark)) return;
var markClone = mark.get().cloneNode();
var key = markClone.outerHTML;
var result = this.pluginCaches.get(key);
if (result) return result;
for (var pluginName in plugin.components) {
var markPlugin = plugin.components[pluginName];
if (isMarkPlugin(markPlugin) && mark.name === markPlugin.tagName) {
var schemaRule = markPlugin.schema();
if (Array.isArray(schemaRule) ? schemaRule.find(function (rule) {
return schema.checkNode(mark, rule.attributes);
}) : schema.checkNode(mark, schemaRule.attributes)) {
this.pluginCaches.set(key, markPlugin);
return markPlugin;
}
}
}
return result;
}
/**
* 获取最近的 Mark 节点,找不到返回 node
*/
}, {
key: "closest",
value: function closest(source) {
var nodeApi = this.editor.node;
var node = source.parent();
while (node && !node.isEditable() && !nodeApi.isBlock(node)) {
if (nodeApi.isMark(node)) return node;
var parentNode = node.parent();
if (!parentNode) break;
node = parentNode;
}
return source;
}
/**
* 获取向上第一个非 Mark 节点
*/
}, {
key: "closestNotMark",
value: function closestNotMark(node) {
while (this.editor.node.isMark(node) || node.isText()) {
if (node.isEditable()) break;
var parent = node.parent();
if (!parent) break;
node = parent;
}
return node;
}
/**
* 比较两个节点是否相同,包括attributes、style、class
* @param source 源节点
* @param target 目标节点
* @param isCompareValue 是否比较每项属性的值
*/
}, {
key: "compare",
value: function compare(source, target, isCompareValue) {
//节点名称不一致
if (source.name !== target.name) return false; //获取节点属性
var sourceAttributes = source.attributes();
delete sourceAttributes['style'];
delete sourceAttributes[DATA_ID];
var targetAttributes = target.attributes();
delete targetAttributes['style'];
delete targetAttributes[DATA_ID]; //获取节点样式属性
var sourceStyles = source.css();
var targetStyles = target.css();
delete sourceAttributes['class'];
delete targetAttributes['class']; //获取节点样式名称
var sourceClassName = source.get().className.trim();
var targetClassName = target.get().className.trim();
var sourceClasses = sourceClassName !== '' ? sourceClassName.split(/\s+/) : [];
var targetClasses = targetClassName !== '' ? targetClassName.split(/\s+/) : []; //样式名称可能是可变的,如data-fontsize-12和data-fontsize-14代表的是不同的值,如果不需要比较值,直接获取标签样式规则比较
var schema = this.editor.schema;
var schemas = schema.find(function (rule) {
return rule.name === source.name;
});
var compareClass = function compareClass(classNames) {
for (var i = 0; i < schemas.length; i++) {
var schemaRule = schemas[i];
if (schemaRule.attributes && schema.checkValue(schemaRule.attributes, 'class', classNames.join(' ').trim())) {
return schemaRule.attributes['class'].toString();
}
}
return classNames.join(' ').trim();
};
if (!isCompareValue) {
sourceClasses = sourceClasses.length > 0 ? [compareClass(sourceClasses)] : [];
targetClasses = targetClasses.length > 0 ? [compareClass(targetClasses)] : [];
} //属性长度不一致
if (Object.keys(sourceAttributes).length !== Object.keys(targetAttributes).length) return false; //属性名称或值不一致
if (!Object.keys(sourceAttributes).every(function (attributesName) {
return isCompareValue ? sourceAttributes[attributesName] === targetAttributes[attributesName] : !!targetAttributes[attributesName];
})) return false; //样式属性长度不一致
if (Object.keys(sourceStyles).length !== Object.keys(targetStyles).length) return false; //样式属性名称或值不一致
if (!Object.keys(sourceStyles).every(function (styleName) {
return isCompareValue ? sourceStyles[styleName] === targetStyles[styleName] : !!targetStyles[styleName];
})) return false; //样式名称长度不一致
if (sourceClasses.length !== targetClasses.length) return false; //样式名称不一致
if (!sourceClasses.every(function (sourceClass) {
return targetClasses.indexOf(sourceClass) !== -1;
})) return false;
return true;
}
/**
* 判断源节点是否包含目标节点的所有属性名称和样式名称
* @param source 源节点
* @param target 目标节点
*/
}, {
key: "contain",
value: function contain(source, target) {
var attributes = target.attributes();
var styles = attributes['style'] || {};
delete attributes['style'];
var sourceAttributes = source.attributes();
var sourceStyles = sourceAttributes['style'] || {};
delete sourceAttributes['style'];
return Object.keys(attributes).every(function (key) {
return !!sourceAttributes[key];
}) && Object.keys(styles).every(function (key) {
return !sourceStyles[key];
});
}
/**
* 去除一个节点下的所有空 Mark,通过 callback 可以设置其它条件
* @param root 节点
* @param callback 回调
*/
}, {
key: "unwrapEmptyMarks",
value: function unwrapEmptyMarks(root, callback) {
var node = this.editor.node;
var children = root.allChildren();
children.forEach(function (child) {
if (node.isEmpty(child) && node.isMark(child) && (!callback || callback(child))) {
var _children = child.children();
if (_children.length === 1 && _children.isText()) {
child.remove();
} else {
node.unwrap(child);
}
}
});
}
/**
* 在光标重叠位置时分割,在分割时会清空父节点内容再重组,如果需要保持光标右边某节点的追踪,请传入该节点
* @param range 光标
* @param removeMark 要移除的mark空节点
* @param keelpNode 分割光标右侧需要保持追踪的节点
*/
}, {
key: "splitOnCollapsed",
value: function splitOnCollapsed(range, removeMark, keelpNode) {
var _this3 = this;
if (!range.collapsed) return; //扩大光标选区
range.enlargeFromTextNode();
range.shrinkToElementNode();
var startNode = range.startNode;
var startParent = startNode.parent(); //获取卡片
var card = startNode.isCard() ? startNode : startNode.closest(CARD_SELECTOR);
var node = this.editor.node;
if ((card.length === 0 || card.attributes(CARD_TYPE_KEY) !== 'inline') && (node.isMark(startNode) || startParent && node.isMark(startParent))) {
var _rightNodes$find, _zeroWidthNode$0$pare;
// 获取上面第一个非mark标签
var parent = this.closestNotMark(startNode); // 插入范围的开始和结束标记
var selection = range.createSelection(); // 获取标记左侧节点
var left = selection.getNode(parent, 'left'); // 获取标记右侧节点
var right = undefined;
var keelpRoot = undefined;
var keelpPath = [];
if (keelpNode) {
if (isNode(keelpNode)) keelpNode = $(keelpNode); // 获取需要跟踪节点的路径
var path = keelpNode.getPath(parent.get());
var cloneParent = parent.clone(true);
keelpPath = path.slice(1); // 获取需要跟踪节点的root节点
keelpRoot = $(cloneParent.getChildByPath(path.slice(0, 1)));
right = selection.getNode(cloneParent, 'right', false);
} else right = selection.getNode(parent, 'right'); // 删除空标签
this.unwrapEmptyMarks(left, function (node) {
return !node.isCursor();
});
this.unwrapEmptyMarks(right, function (node) {
if (removeMark && !Array.isArray(removeMark)) removeMark = [removeMark]; //没有传指定的mark,那就都移除。否则比较后一致就移除
var isUnwrap = !removeMark || removeMark.length === 0 || !node.isCard() && removeMark.some(function (mark) {
return _this3.compare(node, mark);
});
return isUnwrap;
}); // 清空原父容器,用新的内容代替
var children = parent.children();
children.each(function (_, index) {
var child = children.eq(index);
if (!(child === null || child === void 0 ? void 0 : child.isCard())) {
child === null || child === void 0 ? void 0 : child.remove();
}
});
var appendChild = undefined;
var appendToParent = function appendToParent(childrenNodes) {
childrenNodes.each(function (child, index) {
var childNode = childrenNodes.eq(index);
if (childNode === null || childNode === void 0 ? void 0 : childNode.isCard()) {
appendChild = appendChild ? appendChild.next() : parent.first();
if (appendChild) childrenNodes[index] = appendChild[0];
return;
}
if (appendChild) {
appendChild.after(child);
appendChild = childNode;
} else {
appendChild = childNode;
parent.prepend(child);
}
});
};
var leftChildren = left.children();
var leftNodes = leftChildren.toArray();
appendToParent(leftChildren);
var rightChildren = right.children();
var rightNodes = rightChildren.toArray(); // 根据跟踪节点的root节点和path获取其在rightNodes中的新节点
if (keelpRoot) keelpNode = (_rightNodes$find = rightNodes.find(function (node) {
return node.equal(keelpRoot);
})) === null || _rightNodes$find === void 0 ? void 0 : _rightNodes$find.getChildByPath(keelpPath);
appendToParent(rightChildren);
rightNodes = rightChildren.toArray();
var zeroWidthNode = $("\u200B", null); // 重新设置范围
if (leftNodes.length === 1 && leftNodes[0].name === 'br') {
leftNodes[0].remove();
leftNodes.splice(0, 1);
}
if (rightNodes.length === 1 && rightNodes[0].name === 'br') {
rightNodes[0].remove();
rightNodes.splice(0, 1);
}
if (rightNodes.filter(function (child) {
return !child.isCursor();
}).length > 0) {
var rightContainer = rightNodes[0];
for (var i = 0; i < rightNodes.length - 1; i++) {
rightContainer = rightNodes[i];
if (!rightContainer.isCursor()) break;
} // 右侧没文本
if (node.isEmpty(rightContainer)) {
var firstChild = rightContainer.first();
while (firstChild && !firstChild.isText()) {
rightContainer = firstChild;
firstChild = firstChild.first();
}
if (rightContainer.isText()) {
rightContainer.before(zeroWidthNode);
} else {
rightContainer.prepend(zeroWidthNode);
}
} // 右侧有文本
else {
//在多层mark嵌套的情况下,要移除的mark里面还有其它mark节点,还有要移除的mark外面还有其它mark,需要将其组合起来
var markParent = node.isMark(startNode) ? startNode : startNode.parent();
var wrapZeroNode = zeroWidthNode;
if (removeMark && !Array.isArray(removeMark)) removeMark = [removeMark];
var _loop = function _loop() {
var markClone = markParent.clone(); //不是要移除的mark
if (!removeMark.some(function (mark) {
return _this3.compare(markClone, mark);
})) {
var isZero = zeroWidthNode.equal(wrapZeroNode);
wrapZeroNode = node.wrap(wrapZeroNode, markClone);
if (isZero) zeroWidthNode = wrapZeroNode.first();
}
markParent = markParent.parent();
};
while (removeMark && removeMark.length > 0 && markParent && node.isMark(markParent)) {
_loop();
}
rightContainer.before(wrapZeroNode);
}
range.select(zeroWidthNode).collapse(false);
} else if (leftNodes.filter(function (childNode) {
return !childNode.isCursor();
}).length > 0) {
var leftContainer = leftNodes[leftNodes.length - 1];
leftContainer.after(zeroWidthNode);
range.select(zeroWidthNode).collapse(false);
} else {
range.select(parent, true).collapse(true);
} //替换多个零宽字符为一个零宽字符
var textWithEmpty = false;
parent.children().each(function (child) {
var childNode = $(child);
if (childNode.isText()) {
var textContent = child.textContent;
var text = (textContent === null || textContent === void 0 ? void 0 : textContent.replace(/\u200b+/g, "\u200B")) || '';
if (textContent !== text) {
child.textContent = text;
}
if (textWithEmpty) {
//当前第二个连续零宽字符的下一个节点不能是inline节点
var next = childNode.next(); //当前第二个连续零宽字符没有下一个节点,并且父级节点不能为inline节点
var _parent = childNode.parent();
if ((!next && _parent && !node.isInline(_parent) || next && !node.isInline(next)) && text.startsWith("\u200B")) {
text = text.substring(1);
if (text) child.textContent = text;else childNode.remove();
} else textWithEmpty = false;
}
if (text.endsWith("\u200B")) textWithEmpty = true;
} else textWithEmpty = false;
});
var nodeApi = node; //移除多余的零宽字符
if ((_zeroWidthNode$0$pare = zeroWidthNode[0].parentElement) !== null && _zeroWidthNode$0$pare !== void 0 ? _zeroWidthNode$0$pare : zeroWidthNode[0].parentNode) {
var at = zeroWidthNode[0];
var atText = null;
var atTextLen = 0;
var handleAt = function handleAt(node, findPrev) {
var getAlignNode = function getAlignNode(node) {
return findPrev ? node.previousSibling : node.nextSibling;
};
while (node) {
if (node.nodeType !== at.nodeType) return;
var alignNode = getAlignNode(node);
if (node.textContent === atText) {
var _node$parentElement;
//inline 节点位置的零宽字符跳过
var _parent2 = (_node$parentElement = node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : node.parentNode;
if (alignNode && nodeApi.isInline(alignNode) || !alignNode && _parent2 && nodeApi.isInline(_parent2)) break;
_parent2 === null || _parent2 === void 0 ? void 0 : _parent2.removeChild(node);
node = alignNode;
} else {
var _node$textContent3, _node$parentElement4;
if (findPrev) {
while (atText && ((_node$textContent = node.textContent) === null || _node$textContent === void 0 ? void 0 : _node$textContent.endsWith(atText))) {
var _node$textContent, _node$parentElement2;
//inline 节点位置的零宽字符跳过
var _parent4 = (_node$parentElement2 = node.parentElement) !== null && _node$parentElement2 !== void 0 ? _node$parentElement2 : node.parentNode;
if (alignNode && nodeApi.isInline(alignNode) || !alignNode && _parent4 && nodeApi.isInline(_parent4)) break;
node.textContent = node.textContent.substring(0, node.textContent.length - atTextLen);
}
} else {
while (atText && ((_node$textContent2 = node.textContent) === null || _node$textContent2 === void 0 ? void 0 : _node$textContent2.startsWith(atText))) {
var _node$textContent2, _node$parentElement3;
//inline 节点位置的零宽字符跳过
var _parent5 = (_node$parentElement3 = node.parentElement) !== null && _node$parentElement3 !== void 0 ? _node$parentElement3 : node.parentNode;
if (alignNode && nodeApi.isInline(alignNode) || !alignNode && _parent5 && nodeApi.isInline(_parent5)) break;
node.textContent = node.textContent.substring(atText.length);
}
}
if (((_node$textContent3 = node.textContent) === null || _node$textContent3 === void 0 ? void 0 : _node$textContent3.length) !== 0) return;
var _parent3 = (_node$parentElement4 = node.parentElement) !== null && _node$parentElement4 !== void 0 ? _node$parentElement4 : node.parentNode;
_parent3 === null || _parent3 === void 0 ? void 0 : _parent3.removeChild(node);
node = alignNode;
}
}
};
if (at.nodeType === Node.TEXT_NODE) {
var textContent = at.textContent;
atText = textContent;
atTextLen = atText.length;
handleAt(at.previousSibling, true);
handleAt(at.nextSibling, false);
}
}
}
return keelpNode;
}
/**
* 在光标位置不重合时分割
* @param range 光标
* @param removeMark 要移除的空mark节点
*/
}, {
key: "splitOnExpanded",
value: function splitOnExpanded(range, removeMark) {
if (range.collapsed) return;
range.enlargeToElementNode();
range.shrinkToElementNode();
var startNode = range.startNode,
endNode = range.endNode;
var cardStart = startNode.isCard() ? startNode : startNode.closest(CARD_SELECTOR);
var cardEnd = endNode.isCard() ? endNode : endNode.closest(CARD_SELECTOR);
if (!(cardStart.length > 0 && 'inline' === cardStart.attributes(CARD_TYPE_KEY) || cardEnd.length > 0 && 'inline' === cardEnd.attributes(CARD_TYPE_KEY))) {
//开始非mark标签父节点
var startNotMarkParent = this.closestNotMark(startNode); //结束非mark标签父节点
var endNotMarkParent = this.closestNotMark(endNode);
if (!startNotMarkParent.equal(endNotMarkParent)) {
var startRange = range.cloneRange();
startRange.collapse(true);
var endRange = range.cloneRange();
endRange.collapse(false); //如果开始非mark标签父节点包含结束非mark标签父节点,那么分割的时候会清空 结束非mark标签父节点的内容进行重组。结束非mark标签父节点 将无非找到
//所以需要从被包含的节点开始分割
var keelpNode = undefined;
var startOffset = startRange.startOffset;
var endOffset = endRange.endOffset; //如果开始节点的父节点包含结尾父节点,会将结尾父节点删除重组,导致光标失效,需要先执行开始节点分割,并跟踪结尾节点
if (startNotMarkParent.contains(endNotMarkParent)) {
//先分割开始节点,并跟踪结尾节点
keelpNode = this.splitOnCollapsed(startRange, removeMark, endRange.endNode);
range.setStart(startRange.startContainer, startRange.startOffset); //如果有跟踪到,重新设置结尾节点
if (keelpNode) {
endRange.setOffset(keelpNode, endOffset, endOffset);
} //分割结尾节点
this.splitOnCollapsed(endRange, removeMark);
range.setEnd(endRange.startContainer, endRange.startOffset);
} else {
//结尾父节点包含开始节点父节点
//先分割结尾节点,并跟踪开始节点
keelpNode = this.splitOnCollapsed(endRange, removeMark, startRange.startNode);
range.setEnd(endRange.startContainer, endRange.startOffset); //如果有跟踪到,重新设置开始节点
if (keelpNode) {
startRange.setOffset(keelpNode, startOffset, startOffset);
} //分割开始节点
this.splitOnCollapsed(startRange, removeMark);
range.setStart(startRange.startContainer, startRange.startOffset);
}
return;
}
var node = this.editor.node; // 节点不是样式标签,文本节点时判断父节点
var startParent = startNode.parent();
var startIsMark = node.isMark(startNode) || startParent && node.isMark(startParent);
var endParent = endNode.parent();
var endIsMark = node.isMark(endNode) || endParent && node.isMark(endParent); // 不是样式标签,无需分割
if (!startIsMark && !endIsMark) {
return;
} // 获取上面第一个非样式标签
var commonAncestorNode = range.commonAncestorNode;
if (commonAncestorNode.isText()) {
commonAncestorNode = commonAncestorNode.parent();
}
var parent = this.closestNotMark(commonAncestorNode); // 插入范围的开始和结束标记
var selection = range.createSelection(); // 子节点分别保存在两个变量
var left = selection.getNode(parent, 'left');
var center = selection.getNode(parent);
var right = selection.getNode(parent, 'right'); // 删除空标签
this.unwrapEmptyMarks(left);
this.unwrapEmptyMarks(right); // 清空原父容器,用新的内容代替
var children = parent.children();
children.each(function (_, index) {
var child = children.eq(index);
if (!(child === null || child === void 0 ? void 0 : child.isCard())) {
child === null || child === void 0 ? void 0 : child.remove();
}
});
var appendChild = undefined;
var appendToParent = function appendToParent(childrenNodes) {
childrenNodes.each(function (child, index) {
var childNode = childrenNodes.eq(index);
if (childNode === null || childNode === void 0 ? void 0 : childNode.isCard()) {
appendChild = appendChild ? appendChild.next() : parent.first();
if (appendChild) childrenNodes[index] = appendChild[0];
return;
}
if (appendChild) {
appendChild.after(child);
appendChild = childNode;
} else {
appendChild = childNode;
parent.prepend(child);
}
});
};
var leftChildren = left.children();
appendToParent(leftChildren);
var centerChildren = center.children();
var centerNodes = centerChildren.toArray();
appendToParent(centerChildren);
var rightChildren = right.children();
appendToParent(rightChildren); // 重新设置范围
range.setStartBefore(centerNodes[0][0]);
range.setEndAfter(centerNodes[centerNodes.length - 1][0]);
}
}
/**
* 分割mark标签
* @param removeMark 需要移除的mark标签
*/
}, {
key: "split",
value: function split(range, removeMark) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer);
var collapsed = safeRange.collapsed;
if (typeof removeMark === 'string' || !Array.isArray(removeMark) && removeMark && isNode(removeMark)) {
removeMark = $(removeMark, doc);
}
if (collapsed) {
this.splitOnCollapsed(safeRange, removeMark);
} else {
var selection = safeRange.createSelection('mark-split');
this.splitOnExpanded(safeRange, removeMark);
selection.move();
}
if (!range) change.apply(safeRange);
}
/**
*
* @param node 包裹一个节点
* @param mark 包裹的样式
* @param plugin 包裹的样式节点所属mark插件,如果循环传入可提高效率,否则每次都需要查找。需要使用插件的级别和是否合并等属性
* @returns 未处理返回 void,因为某些原因不能包裹返回 false,包裹成功返回 NodeInterface
*/
}, {
key: "wrapByNode",
value: function wrapByNode(node, mark) {
var _this4 = this;
var plugin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.findPlugin(mark);
var root = arguments.length > 3 ? arguments[3] : undefined;
var nodeApi = this.editor.node; // 要包裹的节点是mark
if (nodeApi.isMark(node)) {
var _node$get;
if (((_node$get = node.get()) === null || _node$get === void 0 ? void 0 : _node$get.childNodes.length) === 0) {
node.html('');
} //找到最底层mark标签添加包裹,abc ,在 span 节点中的text再添加包裹,不在strong外添加包裹
var targetNode = node;
var targetChildrens = targetNode.children().toArray();
var curPlugin = this.findPlugin(targetNode);
var hasSomeMark = false;
while (nodeApi.isMark(targetNode) && targetChildrens.filter(function (child) {
return !child.isCursor();
}).length === 1 && plugin && curPlugin && plugin.mergeLeval <= curPlugin.mergeLeval) {
var targetChild = targetChildrens.find(function (child) {
return !child.isCursor();
});
if (nodeApi.isMark(targetChild)) {
targetNode = targetChild;
targetChildrens = targetNode.children().toArray();
} else if (targetChild.isText()) {
targetNode = targetChild;
} else break; // 过程中如果有一样的插件,提前跳出,交给下面是否合并或者移除的处理
if (plugin.name === curPlugin.name) {
hasSomeMark = true;
break;
}
curPlugin = this.findPlugin(targetNode);
}
nodeApi.removeZeroWidthSpace(targetNode);
var parent = targetNode.parent(); //父级和当前要包裹的节点,属性和值都相同,那就不包裹。只有属性一样,并且父节点只有一个节点那就移除父节点包裹,然后按插件情况合并值
if (targetNode.isText() || hasSomeMark) {
var result = false;
while (parent && nodeApi.isMark(parent)) {
if (this.compare(parent.clone(), mark, true)) {
result = true;
break;
} else if (parent.children().toArray().filter(function (node) {
return !node.isCursor();
}).length === 1) {
var _curPlugin = this.findPlugin(parent); //插件一样,并且并表明要合并值
if (plugin && plugin === _curPlugin && plugin.combineValueByWrap === true) {
nodeApi.wrap(parent, mark, true);
result = true;
break;
} //插件一样,不合并,直接移除
else if (plugin && plugin === _curPlugin) {
nodeApi.unwrap(parent);
result = false;
break;
}
}
parent = parent.parent();
}
if (result) return false;
} // 移除目标子级内相同的插件
var allChildren = targetNode.allChildren();
allChildren.forEach(function (children) {
if (children.type === getDocument().TEXT_NODE) return;
if (nodeApi.isMark(children)) {
var childPlugin = _this4.findPlugin(children);
if (childPlugin === plugin && !(plugin === null || plugin === void 0 ? void 0 : plugin.combineValueByWrap)) nodeApi.unwrap(children);
}
});
return nodeApi.wrap(targetNode, mark);
} else if (node.name === 'br') {
var _parent6 = node.parent();
if (_parent6 && nodeApi.isBlock(_parent6)) {
var cloneMark = mark.clone(true);
cloneMark.html('');
nodeApi.replace(node, cloneMark);
return cloneMark;
}
} else if (node.isCard()) {
var cardComponent = this.editor.card.find(node);
if (cardComponent && cardComponent.executeMark) {
return cardComponent.executeMark(mark, true);
}
} else if (node.isText() && !nodeApi.isEmpty(node)) {
nodeApi.removeZeroWidthSpace(node);
var _parent7 = node.parent(); //父级和当前要包裹的节点,属性和值都相同,那就不包裹。只有属性一样,并且父节点只有一个节点那就移除父节点包裹,然后按插件情况合并值
var _result = false;
while (_parent7 && nodeApi.isMark(_parent7)) {
if (this.compare(_parent7.clone(), mark, true)) {
_result = true;
break;
} else if (_parent7.children().toArray().filter(function (node) {
return !node.isCursor();
}).length === 1 || root && root.equal(_parent7)) {
var _curPlugin3 = this.findPlugin(_parent7); //插件一样,并且并表明要合并值
if (plugin && plugin === _curPlugin3 && plugin.combineValueByWrap === true) {
nodeApi.wrap(_parent7, mark, true);
_result = true;
break;
} //插件一样,不合并,直接移除
else if (plugin && plugin === _curPlugin3) {
var childs = nodeApi.unwrap(_parent7);
var targetMark = childs.find(function (child) {
return !child.isCursor() && nodeApi.isMark(child);
});
if (targetMark) {
_parent7 = targetMark;
} else if (childs.length > 0) {
_parent7 = childs[0].parent();
}
_result = false;
break;
}
}
var newParent = _parent7.parent();
if (newParent && nodeApi.isMark(_parent7)) _parent7 = newParent;else break;
}
if (_result) return false;
var _targetNode = node.parent();
var _curPlugin2 = _targetNode ? this.findPlugin(_targetNode) : undefined;
/**
* 123 -> 123
* 123123 -> 123123
*/
var isHandle = false;
var _loop2 = function _loop2() {
isHandle = true;
var targetChildrens = _targetNode.children().toArray();
var cloneMark = _targetNode.clone();
targetChildrens.forEach(function (targetChild) {
// 零宽字符的文本跳过
if (targetChild.isCursor() || targetChild.type === 3 && /^\u200b$/.test(targetChild.text() || '')) {
return;
}
if (node.equal(targetChild) || targetChild.contains(node)) {
node = nodeApi.wrap(nodeApi.replace(node, cloneMark), mark);
} else {
targetChild = nodeApi.wrap(targetChild, cloneMark);
nodeApi.wrap(targetChild, mark);
}
});
nodeApi.unwrap(_targetNode);
_targetNode = _this4.closest(node);
};
while (_targetNode && nodeApi.isMark(_targetNode) && plugin && _curPlugin2 && plugin.mergeLeval > _curPlugin2.mergeLeval) {
_loop2();
}
if (!isHandle) nodeApi.wrap(node, mark);
return node;
}
return;
}
/**
* 在当前光标选区包裹mark标签
* @param mark mark标签
* @param both mark标签两侧节点
*/
}, {
key: "wrap",
value: function wrap(mark, range) {
var _this5 = this;
var editor = this.editor;
var change = isEngine(editor) ? editor.change : undefined;
if (!range && !change) return;
var node = editor.node;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer);
if (typeof mark === 'string' || isNode(mark)) {
mark = $(mark, doc);
} else mark = mark;
if (!node.isMark(mark)) return;
var commonAncestorNode = safeRange.commonAncestorNode;
if (commonAncestorNode.type === Node.TEXT_NODE) {
commonAncestorNode = commonAncestorNode.parent();
}
var card = editor.card.find(commonAncestorNode, true);
var isEditable = card === null || card === void 0 ? void 0 : card.isEditable;
var nodes = isEditable ? (card === null || card === void 0 ? void 0 : card.getSelectionNodes) ? card.getSelectionNodes() : [] : [commonAncestorNode];
if (nodes.length === 0) {
isEditable = false;
nodes.push(commonAncestorNode);
}
var nodeApi = node;
var plugin = this.findPlugin(mark);
if (safeRange.collapsed && (!isEditable || !(card === null || card === void 0 ? void 0 : card.getSelectionNodes) || nodes.length === 1)) {
if (mark.children().toArray().filter(function (node) {
return !node.isCursor();
}).length === 0) mark.append(doc.createTextNode("\u200B")); //在相通插件下,值不同,插入到同级,不做嵌套
var _safeRange$shrinkToTe = safeRange.shrinkToTextNode(),
startNode = _safeRange$shrinkToTe.startNode;
var parent = startNode.parent();
var levalNodes = [];
var isPushMark = false;
if (startNode.isText()) {
var result = false;
while (parent && nodeApi.isMark(parent)) {
var _parent$get;
if (this.compare(parent.clone(), mark, true)) {
result = true;
break;
}
var curPlugin = this.findPlugin(parent);
if (((_parent$get = parent.get()) === null || _parent$get === void 0 ? void 0 : _parent$get.childNodes.length) === 1) {
//插件一样,并且并表明要合并值
if (plugin && plugin === curPlugin && plugin.combineValueByWrap === true) {
nodeApi.wrap(parent, mark, true);
result = true;
break;
} //插件一样,不合并,分割后插入
else if (plugin && plugin === curPlugin) {
this.split(safeRange);
if (safeRange.collapsed) {
var markParent = parent.parent();
while (markParent && nodeApi.isMark(markParent)) {
mark = nodeApi.wrap(mark, markParent);
markParent = markParent.parent();
}
}
result = false;
break;
}
} // 要插入的mark节点大于当前节点
if (plugin && (!curPlugin || plugin.mergeLeval > curPlugin.mergeLeval)) {
levalNodes.push(parent.clone(false));
} else if (!isPushMark && levalNodes.length > 0) {
levalNodes.push(mark.clone(false));
isPushMark = true;
}
parent = parent.parent();
}
if (result) return;
}
if (levalNodes.length > 0) {
var newMark = levalNodes[0];
newMark.append(mark.children());
for (var i = 1; i < levalNodes.length; i++) {
newMark = nodeApi.wrap(newMark, levalNodes[i]);
}
mark = isPushMark ? newMark : nodeApi.wrap(newMark, mark);
this.split(safeRange);
}
nodeApi.insert(mark, safeRange);
this.merge(safeRange);
safeRange.handleBr();
if (!range) change === null || change === void 0 ? void 0 : change.apply(safeRange);
return;
} // 不是选中可编辑器卡片内部就分割
if (!isEditable) {
this.split(safeRange);
commonAncestorNode = safeRange.commonAncestorNode;
if (commonAncestorNode.type === Node.TEXT_NODE) {
commonAncestorNode = commonAncestorNode.parent();
}
nodes[0] = commonAncestorNode;
} // 插入范围的开始和结束标记
var selection = !isEditable ? safeRange.createSelection() : undefined;
if (selection && !selection.anchor && !selection.focus) {
if (!range) change === null || change === void 0 ? void 0 : change.apply(safeRange);
return;
} // 遍历范围内的节点,添加 Mark
var started = isEditable ? true : false;
nodes.forEach(function (commonAncestorNode) {
commonAncestorNode.traverse(function (child) {
mark = mark;
if (isEditable || !child.equal(selection === null || selection === void 0 ? void 0 : selection.anchor)) {
if (started) {
if (!isEditable && child.equal(selection === null || selection === void 0 ? void 0 : selection.focus)) {
started = false;
return false;
}
var childIsMark = nodeApi.isMark(child);
var _result2 = _this5.wrapByNode(child, mark, plugin, commonAncestorNode); // 要包裹的节点是mark
if (_result2 && typeof _result2 !== 'boolean' && childIsMark) {
var _result2$next;
if (!isEditable && (selection === null || selection === void 0 ? void 0 : selection.focus) && _result2.find("[".concat(DATA_ELEMENT, "=\"").concat(selection.focus.attributes(DATA_ELEMENT), "\"]")).equal(selection.focus)) {
started = false;
return false;
} else if ((selection === null || selection === void 0 ? void 0 : selection.focus) && ((_result2$next = _result2.next()) === null || _result2$next === void 0 ? void 0 : _result2$next.equal(selection.focus))) {
started = false;
return false;
}
}
if (typeof _result2 !== 'undefined') return true;
}
} else {
started = true;
}
return;
}, true, 'editable');
});
selection === null || selection === void 0 ? void 0 : selection.move();
if (isEditable) {
var markNodes = [];
nodes.forEach(function (editableRoot) {
editableRoot.allChildren().forEach(function (child) {
if (child.isElement() && node.isMark(child)) {
markNodes.push(child);
}
});
});
this.mergeMarks(markNodes);
} else this.merge(safeRange);
if (!range) change === null || change === void 0 ? void 0 : change.apply(safeRange);
}
}, {
key: "mergeMarks",
value: function mergeMarks(marks) {
var _this6 = this;
var node = this.editor.node;
marks.forEach(function (mark) {
var prevMark = mark.prev();
var nextMark = mark.next(); //查找是否有一样的父级mark
var parentMark = mark.parent(); //如果有一样的父级mark,则去除包裹
if (parentMark && _this6.findSameParent(parentMark, mark)) {
node.unwrap(mark);
return;
}
if (prevMark && _this6.compare(prevMark, mark, true)) {
node.merge(prevMark, mark); // 原来 mark 已经被移除,重新指向
mark = prevMark;
}
if (nextMark && _this6.compare(nextMark, mark, true)) {
node.merge(mark, nextMark);
} //合并子级mark
var childMarks = [];
var children = mark.children();
children.each(function (_, index) {
var child = children.eq(index);
if (child && !child.isCursor() && node.isMark(child)) {
childMarks.push(child);
}
});
if (childMarks.length > 0) {
_this6.mergeMarks(childMarks);
}
});
}
/**
* 合并当前选区的mark节点
* @param range 光标,默认当前选区光标
*/
}, {
key: "merge",
value: function merge(range) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change;
var safeRange = range || change.range.toTrusty();
var marks = this.findMarks(safeRange);
if (marks.length === 0) {
return;
}
var selection = safeRange.shrinkToElementNode().createSelection();
this.mergeMarks(marks);
selection.move();
safeRange.handleBr();
if (!range) change.apply(safeRange);
}
/**
* 移除多个节点的mark
* @param nodes 要移除的节点集合
* @param removeMark 要移除的mark样式
*/
}, {
key: "unwrapByNodes",
value: function unwrapByNodes(nodes, removeMark) {
var _this7 = this;
var editor = this.editor; // 清除 Mark
var nodeApi = editor.node;
nodes.forEach(function (node) {
removeMark = removeMark;
if (!removeMark || !node.isCard() && (Array.isArray(removeMark) ? removeMark : [removeMark]).some(function (m) {
return _this7.compare(node, m);
})) {
nodeApi.unwrap(node);
} else if (removeMark) {
(Array.isArray(removeMark) ? removeMark : [removeMark]).forEach(function (m) {
var _m$get;
var styleMap = m.css();
Object.keys(styleMap).forEach(function (key) {
node.css(key, '');
}); //移除符合规则的class
var removeClass = (_m$get = m.get()) === null || _m$get === void 0 ? void 0 : _m$get.className.split(/\s+/);
if (removeClass) {
(function () {
var schema = editor.schema;
var schemas = schema.find(function (rule) {
return rule.name === node.name;
});
var _loop3 = function _loop3(i) {
var schemaRule = schemas[i];
removeClass.forEach(function (className) {
className = className.trim();
if (className === '') return;
if (schemaRule.attributes && schema.checkValue(schemaRule.attributes, 'class', className)) {
node.removeClass(className);
}
});
};
for (var i = 0; i < schemas.length; i++) {
_loop3(i);
}
})();
}
});
} else {
node.removeAttributes('class');
node.removeAttributes('style');
}
});
}
/**
* 去掉mark包裹
* @param range 光标
* @param removeMark 要移除的mark标签
*/
}, {
key: "unwrap",
value: function unwrap(removeMark, range) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
node = editor.node;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer) || document;
if (removeMark !== undefined && !Array.isArray(removeMark) && (typeof removeMark === 'string' || isNode(removeMark))) {
removeMark = $(removeMark, doc);
}
var commonAncestorNode = safeRange.commonAncestorNode;
if (commonAncestorNode.type === Node.TEXT_NODE) {
commonAncestorNode = commonAncestorNode.parent();
}
var card = editor.card.find(commonAncestorNode, true);
var isEditable = card === null || card === void 0 ? void 0 : card.isEditable;
var nodes = isEditable ? (card === null || card === void 0 ? void 0 : card.getSelectionNodes) ? card.getSelectionNodes() : [] : [commonAncestorNode];
if (nodes.length === 0) {
isEditable = false;
nodes.push(commonAncestorNode);
} // 不是选中可编辑器卡片内部就分割
if (!isEditable) {
this.split(safeRange, safeRange.collapsed ? removeMark : undefined);
commonAncestorNode = safeRange.commonAncestorNode;
if (commonAncestorNode.type === Node.TEXT_NODE) {
commonAncestorNode = commonAncestorNode.parent();
}
nodes[0] = commonAncestorNode;
}
if (safeRange.collapsed && (!isEditable || !(card === null || card === void 0 ? void 0 : card.getSelectionNodes) || nodes.length === 1)) {
if (!range) change.apply(safeRange);
return;
} // 插入范围的开始和结束标记
var selection = !isEditable ? safeRange.createSelection('mark-unwrap') : undefined;
if (selection && !selection.has()) {
this.merge(safeRange);
if (!range) change.apply(safeRange);
return;
} // 遍历范围内的节点,获取目标 Mark
var markNodes = [];
var started = isEditable ? true : false;
nodes.forEach(function (ancestor) {
ancestor.traverse(function (child) {
if (!isEditable && (child.isText() || !(selection === null || selection === void 0 ? void 0 : selection.anchor))) return;
if (isEditable || (selection === null || selection === void 0 ? void 0 : selection.anchor) && !child.equal(selection.anchor)) {
if (started) {
if (isEditable || !child.equal(selection === null || selection === void 0 ? void 0 : selection.focus)) {
if (node.isMark(child) && !child.isCard() && (isEditable || safeRange.isPointInRange(child, 0))) {
markNodes.push(child);
} else if (child.isCard()) {
var cardComponent = editor.card.find(child);
if (cardComponent && cardComponent.executeMark) {
(Array.isArray(removeMark) ? removeMark : [removeMark]).forEach(function (mark) {
cardComponent.executeMark(mark, false);
});
}
}
}
}
} else if (!isEditable) {
started = true; // 光标开始位置在 abc123 就把 strong 加进去
if ((selection === null || selection === void 0 ? void 0 : selection.anchor) && child.equal(selection.anchor) && !selection.anchor.prev()) {
var parent = selection.anchor.parent();
while (parent && !parent.isCard() && node.isMark(parent)) {
var _parent$get$childNode, _parent$get2;
markNodes.push(parent);
parent = parent.parent();
if (parent && ((_parent$get$childNode = (_parent$get2 = parent.get()) === null || _parent$get2 === void 0 ? void 0 : _parent$get2.childNodes.length) !== null && _parent$get$childNode !== void 0 ? _parent$get$childNode : 0) > 1) break;
}
}
}
}, true, 'editable');
});
this.unwrapByNodes(markNodes, removeMark);
selection === null || selection === void 0 ? void 0 : selection.move();
if (isEditable) {
var _markNodes = [];
nodes.forEach(function (editableRoot) {
editableRoot.allChildren().forEach(function (child) {
if (child.isElement() && node.isMark(child)) {
_markNodes.push(child);
}
});
});
this.mergeMarks(_markNodes);
} else this.merge(safeRange);
if (!range) change.apply(safeRange);
}
/**
* 光标处插入mark标签
* @param mark mark标签
* @param range 指定光标,默认为编辑器选中的光标
*/
}, {
key: "insert",
value: function insert(mark, range) {
var _node$insert;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
node = editor.node;
var safeRange = range || change.range.toTrusty();
if (typeof mark === 'string' || isNode(mark)) {
var doc = getDocument(safeRange.startContainer);
mark = $(mark, doc);
} // 范围为折叠状态时先删除内容
if (!safeRange.collapsed) {
change.delete(safeRange);
} // 插入新 Mark
(_node$insert = node.insert(mark, safeRange)) === null || _node$insert === void 0 ? void 0 : _node$insert.handleBr().select(mark).collapse(false);
if (!range) change.apply(safeRange);
}
/**
* 查找对范围有效果的所有 Mark
* @param range 范围
*/
}, {
key: "findMarks",
value: function findMarks(range) {
var editor = this.editor;
var cloneRange = range.cloneRange();
if (cloneRange.startNode.isRoot()) cloneRange.shrinkToElementNode();
if (!cloneRange.startNode.inEditor() || editor.card.find(cloneRange.startNode)) return [];
var node = editor.node;
var handleRange = function handleRange(allowBlock, range) {
var toStart = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!range.collapsed) return;
var startNode = range.startNode,
startOffset = range.startOffset; //没有父节点
var startParent = startNode.findParent();
if (!startParent) return; //选择父节点内容
var cloneRange = range.cloneRange();
cloneRange.select(startParent, true); //开始位置
if (toStart) {
cloneRange.setEnd(startNode, startOffset);
cloneRange.enlargeFromTextNode();
cloneRange.enlargeToElementNode(true);
var startChildren = startNode.get().childNodes;
var _endNode = cloneRange.endNode,
endOffset = cloneRange.endOffset;
var endChildren = _endNode.get().childNodes;
var endOffsetNode = endChildren.item(endOffset);
var startOffsetNode = startChildren.item(startOffset) || startChildren.item(startOffset - 1);
if (!allowBlock && _endNode.type === Node.ELEMENT_NODE && endOffsetNode && node.isBlock(endOffsetNode) && (startNode.type !== Node.ELEMENT_NODE || !!startOffsetNode && !node.isBlock(startOffsetNode))) return;
cloneRange.select(startParent, true);
cloneRange.setStart(_endNode, endOffset);
cloneRange.shrinkToElementNode();
cloneRange.shrinkToTextNode();
range.setStart(cloneRange.startContainer, cloneRange.startOffset);
range.collapse(true);
} else {
cloneRange.setStart(startNode, startOffset);
cloneRange.enlargeFromTextNode();
cloneRange.enlargeToElementNode(true);
var _startChildren = startNode.get().childNodes;
var startNodeClone = cloneRange.startNode;
var startOffsetClone = cloneRange.startOffset;
var startNodeCloneChildren = startNodeClone.get().childNodes;
var _startOffsetNode = startNodeCloneChildren.item(startOffsetClone);
var startChildrenOffsetNode = _startChildren.item(startOffset) || _startChildren.item(startOffset - 1);
if (!allowBlock && startNodeClone.type === Node.ELEMENT_NODE && _startOffsetNode && node.isBlock(_startOffsetNode) && (startNode.type !== Node.ELEMENT_NODE || startChildrenOffsetNode && !node.isBlock(startChildrenOffsetNode))) return;
cloneRange.select(startParent, true);
cloneRange.setEnd(startNodeClone, startOffsetClone);
cloneRange.shrinkToElementNode();
cloneRange.shrinkToTextNode();
range.setEnd(cloneRange.endContainer, cloneRange.endOffset);
range.collapse(false);
}
}; // 左侧不动,只缩小右侧边界
// foobar
// 改成
// foobar
if (!cloneRange.collapsed) {
var leftRange = cloneRange.cloneRange();
var rightRange = cloneRange.cloneRange();
leftRange.collapse(true);
rightRange.collapse(false);
handleRange(true, leftRange, true);
handleRange(true, rightRange);
cloneRange.setStart(leftRange.startContainer, leftRange.startOffset), cloneRange.setEnd(rightRange.startContainer, rightRange.startOffset);
}
handleRange(false, cloneRange);
var sc = cloneRange.startContainer;
var so = cloneRange.startOffset;
var ec = cloneRange.endContainer;
var eo = cloneRange.endOffset;
var startNode = sc;
var endNode = ec;
if (sc.nodeType === Node.ELEMENT_NODE && sc.childNodes[so]) {
startNode = sc.childNodes[so] || sc;
}
if (ec.nodeType === Node.ELEMENT_NODE && eo > 0 && ec.childNodes[eo - 1]) {
endNode = ec.childNodes[eo - 1] || sc;
} // 折叠状态时,按右侧位置的方式处理
if (cloneRange.collapsed) {
startNode = endNode;
} // 不存在时添加
var addNode = function addNode(nodes, nodeB) {
//if (!nodes.some((nodeA) => nodeA[0] === nodeB[0])) {
nodes.push(nodeB); //}
};
var nodeApi = node; // 向上寻找
var findNodes = function findNodes(node) {
var nodes = [];
while (node) {
if (node.type === Node.ELEMENT_NODE && node.isEditable()) {
break;
}
if (nodeApi.isMark(node) && !node.attributes(CARD_KEY) && !node.attributes(CARD_ELEMENT_KEY)) {
nodes.push(node);
} else if (node.isCard()) {
var cardComponent = editor.card.find(node);
if (cardComponent === null || cardComponent === void 0 ? void 0 : cardComponent.queryMarks) {
nodes.push.apply(nodes, _toConsumableArray(cardComponent.queryMarks()));
}
}
var parent = node.parent();
if (!parent) break;
node = parent;
}
return nodes;
};
var nodes = findNodes($(startNode));
var commonAncestorNode = cloneRange.commonAncestorNode;
var card = editor.card.find(commonAncestorNode, true);
var isEditable = card === null || card === void 0 ? void 0 : card.isEditable;
var selectionNodes = isEditable ? (card === null || card === void 0 ? void 0 : card.getSelectionNodes) ? card.getSelectionNodes() : [] : [commonAncestorNode];
if (selectionNodes.length === 0) {
isEditable = false;
selectionNodes.push(commonAncestorNode);
}
if (!cloneRange.collapsed || isEditable) {
findNodes($(endNode)).forEach(function (nodeB) {
return addNode(nodes, nodeB);
});
if (sc !== ec || isEditable) {
var isBegin = false;
var isEnd = false;
selectionNodes.forEach(function (commonAncestorNode) {
commonAncestorNode.traverse(function (child) {
if (isEnd) return false; //节点不是开始节点
if (child[0] !== sc) {
if (isBegin) {
//节点是结束节点,标记为结束
if (child[0] === ec) {
isEnd = true;
return false;
}
if (nodeApi.isMark(child) && !child.attributes(CARD_KEY) && !child.attributes(CARD_ELEMENT_KEY)) {
addNode(nodes, child);
} else if (child.isCard()) {
var cardComponent = editor.card.find(child);
if (cardComponent === null || cardComponent === void 0 ? void 0 : cardComponent.queryMarks) {
cardComponent.queryMarks().forEach(function (mark) {
addNode(nodes, mark);
});
}
}
}
} else {
//如果是开始节点,标记为开始
isBegin = true;
}
return;
}, true, 'editable');
});
}
}
for (var i = 0; i < nodes.length; i++) {
for (var j = i + 1; j < nodes.length; j++) {
if (nodes[i][0] == nodes[j][0]) {
//第一个等同于第二个,splice方法删除第二个
nodes.splice(j, 1);
j--;
}
}
}
return nodes;
}
/**
* 从下开始往上遍历删除空 Mark,当遇到空 Block,添加 BR 标签
* @param node 节点
* @param addBr 是否添加br
*/
}, {
key: "removeEmptyMarks",
value: function removeEmptyMarks(node, addBr) {
if (node.length === 0 || node.isEditable() || node.isCard() || node.attributes(DATA_ELEMENT)) {
return;
}
var nodeApi = this.editor.node;
if (!node.attributes(DATA_ELEMENT)) {
var _node$get2, _node$first;
var parent = node.parent(); // 包含光标标签
//
if (((_node$get2 = node.get()) === null || _node$get2 === void 0 ? void 0 : _node$get2.childNodes.length) === 1 && ((_node$first = node.first()) === null || _node$first === void 0 ? void 0 : _node$first.attributes(DATA_ELEMENT))) {
if (nodeApi.isMark(node)) {
node.before(node.first());
node.remove();
if (parent) this.removeEmptyMarks(parent, true);
} else if (addBr && nodeApi.isBlock(node)) {
node.prepend('
');
}
return;
}
var html = nodeApi.html(node);
if (html === '' || html === "\u200B") {
if (nodeApi.isMark(node)) {
node.remove();
if (parent) this.removeEmptyMarks(parent, true);
} else if (addBr && nodeApi.isBlock(node)) {
nodeApi.html(node, '
');
}
}
}
}
}, {
key: "repairCursor",
value: function repairCursor(mark) {
var node = this.editor.node;
mark = isNode(mark) ? $(mark) : mark;
var isMark = node.isMark(mark);
if (isMark && !mark.isCursor()) {
var childrenNodes = mark.children();
childrenNodes.each(function (_, index) {
var _child$next;
var child = childrenNodes.eq(index);
if ((child === null || child === void 0 ? void 0 : child.isText()) && !((_child$next = child.next()) === null || _child$next === void 0 ? void 0 : _child$next.isCursor())) {
var text = child.text();
if (text.length === 1 && /\u200b/.test(text)) {
child.remove();
return;
}
child.text(text.replace(/\u200b/g, ''));
}
});
var children = mark.children().toArray().filter(function (node) {
return !node.isCursor();
});
if (children.length < 2) {
if (children.length === 0 || children.length === 1 && children[0].isText() && children[0].text().length === 0) {
if (children.length > 0) children[0].remove();
mark.prepend($("\u200B", null));
}
}
var next = mark.next();
var nextN = next === null || next === void 0 ? void 0 : next.next();
if (next && nextN && next.isText() && /^\u200b$/g.test(next.text()) && !node.isInline(nextN)) {
next.remove();
}
var prev = mark.prev();
var prevP = prev === null || prev === void 0 ? void 0 : prev.prev();
if (prev && prevP && prev.isText() && /^\u200b$/g.test(prev.text()) && !node.isInline(prevP)) {
prev.remove();
}
}
}
}]);
return Mark;
}();
var Backspace$5 = /*#__PURE__*/function () {
function Backspace(engine) {
_classCallCheck(this, Backspace);
this.engine = void 0;
this.engine = engine;
}
/**
* 在inline节点处按下backspace键
*/
_createClass(Backspace, [{
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
mark = _this$engine.mark,
inline = _this$engine.inline,
node = _this$engine.node;
var range = change.range.get();
var _range$cloneRange$shr = range.cloneRange().shrinkToTextNode(),
collapsed = _range$cloneRange$shr.collapsed,
endNode = _range$cloneRange$shr.endNode,
startNode = _range$cloneRange$shr.startNode,
startOffset = _range$cloneRange$shr.startOffset;
if (endNode.type === Node.TEXT_NODE || startNode.type === Node.TEXT_NODE) {
//光标展开的情况下,判断光标结束位置是否在inline节点内左侧零宽字符后面,并且inline节点为空
if (!collapsed) {
var _inlineNode = inline.closest(endNode);
if (node.isInline(_inlineNode) && !_inlineNode.isCard() && node.isEmpty(_inlineNode)) {
//offset 大于 1 说明至少不在左侧,不处理
if (startOffset > 1) return true;
var prev = endNode.prev();
var parent = endNode.parent(); //位于inline 1级子节点下
if (parent && node.isInline(parent)) {
//前面还有节点,不处理
if (prev) return true;
var text = endNode.text();
var leftText = text.substr(0, startOffset); //不位于零宽字符后,不处理
if (!/^\u200b$/.test(leftText)) return true; //光标结束位置选中inline节点零宽字符后
var inlineNext = _inlineNode.next();
var nextText = inlineNext === null || inlineNext === void 0 ? void 0 : inlineNext.text();
if (inlineNext && inlineNext.isText() && nextText && /^\u200b/.test(nextText)) {
range.setEnd(inlineNext, 1);
return false;
}
}
}
if (node.isInline(_inlineNode) && !_inlineNode.isCard()) {
setTimeout(function () {
inline.repairCursor(_inlineNode);
}, 100);
}
return true;
}
var inlineNode = inline.closest(startNode); //开始节点在inline标签内
if (node.isInline(inlineNode)) {
if (inlineNode.isCard()) return true; //offset 大于 1 说明至少不在左侧,不处理
if (startOffset > 1) return true;
var _prev = startNode.prev();
var _parent = startNode.parent(); //位于inline 1级子节点下
if (_parent && node.isInline(_parent)) {
//前面还有节点,不处理
if (_prev) return true;
var _text = startNode.text();
var _leftText = _text.substr(0, startOffset); //不位于零宽字符后,不处理
if (!/\u200b$/.test(_leftText)) return true;
} // 其它内嵌节点内
else if (startOffset === 0) {
//循环判断是否处于inline节点内的第一个零宽字符后面,可能inline节点内包含多个mark或其它标签
while (!_prev && _parent && !node.isInline(_parent)) {
var _parent2;
_prev = _parent.prev();
_parent = (_parent2 = _parent) === null || _parent2 === void 0 ? void 0 : _parent2.parent();
} //前面有节点,并且不是 text 节点,不处理
if (_prev && !_prev.isText()) return true; //前面有text节点
if (_prev) {
//不位于零宽字符后,不处理
if (!/\u200b$/.test(_prev.text())) return true;
}
} else return true; //让光标选择在inline节点前面零宽字符节点前面
var inlinePrev = inlineNode.prev();
var prevText = inlinePrev === null || inlinePrev === void 0 ? void 0 : inlinePrev.text();
if (inlinePrev && inlinePrev.isText() && prevText && /\u200b$/.test(prevText)) {
range.setStart(inlinePrev, prevText.length - 1); //如果inlne节点中没有内容了,选择在inline标签前后零宽字符两侧
if (node.isEmpty(inlineNode)) {
var _inlineNext = inlineNode.next();
var _nextText = _inlineNext === null || _inlineNext === void 0 ? void 0 : _inlineNext.text();
if (_inlineNext && _inlineNext.isText() && _nextText && /^\u200b/.test(_nextText)) {
range.setEnd(_inlineNext, 1);
}
} else {
range.collapse(true);
}
change.range.select(range);
return false;
}
return true;
} // 在inline节点外
else {
var _prev2 = startNode.prev();
var _parent3 = startNode.parent();
var _inlineNode2 = undefined; //在零宽字符后面,并且前面有inline节点
if (_prev2) {
if (node.isInline(_prev2) && !_prev2.isCard()) {
var _text2 = startNode.text();
var _leftText2 = _text2.substr(0, startOffset); //不位于零宽字符后,不处理
if (!/^\u200b$/.test(_leftText2)) return true;
_inlineNode2 = _prev2;
}
} //前方没有节点,考虑是否在mark节点或其它节点内
else if (startOffset === 0) {
//循环判断是否处于inline节点内的第一个零宽字符后面,可能inline节点内包含多个mark或其它标签
while (!_prev2 && _parent3 && !node.isBlock(_parent3)) {
var _parent4;
_prev2 = _parent3.prev();
_parent3 = (_parent4 = _parent3) === null || _parent4 === void 0 ? void 0 : _parent4.parent();
} //前面有节点,并且不是 text 节点,不处理
if (_prev2 && !_prev2.isText()) return true; //前面有text节点
if (_prev2) {
//不位于零宽字符后,不处理
if (!/^\u200b$/.test(_prev2.text())) return true; //位于零宽字符后,并且零宽字符前面是inline节点
_prev2 = _prev2.prev();
if (_prev2 && node.isInline(_prev2)) {
_inlineNode2 = _prev2;
} else return true;
}
} else return true; //让光标选择inline内部最后一个零宽字符前
if (_inlineNode2) {
var last = _inlineNode2.last();
var _text3 = last === null || last === void 0 ? void 0 : last.text();
if (last && last.isText() && _text3 && /\u200b$/.test(_text3)) {
event.preventDefault();
range.setStart(last, _text3.length - 1);
range.collapse(true);
change.range.select(range);
return false;
}
}
}
}
return true;
}
}]);
return Backspace;
}();
var Left$2 = /*#__PURE__*/function () {
function Left(engine) {
_classCallCheck(this, Left);
this.engine = void 0;
this.engine = engine;
}
_createClass(Left, [{
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
inline = _this$engine.inline,
node = _this$engine.node;
var range = change.range.get().cloneRange().shrinkToTextNode();
var startNode = range.startNode,
startOffset = range.startOffset;
var card = this.engine.card.getSingleCard(range);
if (!card && startNode.type === Node.TEXT_NODE) {
// ->
var inlineNode = inline.closest(startNode); //在inline节点内,靠近左侧位置
if (node.isInline(inlineNode)) {
if (inlineNode.isCard()) return; //offset 大于 1 说明至少不在左侧,不处理
if (startOffset > 1) return true;
var prev = startNode.prev();
var parent = startNode.parent(); //位于inline 1级子节点下
if (parent && node.isInline(parent)) {
//前面还有节点,不处理
if (prev) return true;
var text = startNode.text();
var leftText = text.substr(0, startOffset); //不位于零宽字符后,不处理
if (!/^\u200b$/.test(leftText)) return true;
} // 其它内嵌节点内
else if (startOffset === 0) {
//循环判断是否处于inline节点内的第一个零宽字符后面,可能inline节点内包含多个mark或其它标签
while (!prev && parent && !node.isInline(parent)) {
var _parent;
prev = parent.prev();
parent = (_parent = parent) === null || _parent === void 0 ? void 0 : _parent.parent();
} //前面有节点,并且不是 text 节点,不处理
if (prev && !prev.isText()) return true; //前面有text节点
if (prev) {
//不位于零宽字符后,不处理
if (!/^\u200b$/.test(prev.text())) return true;
}
} else return true; //让光标选择在inline节点前面节点
var inlinePrev = inlineNode.prev();
var prevText = inlinePrev === null || inlinePrev === void 0 ? void 0 : inlinePrev.text();
if (inlinePrev && inlinePrev.isText() && prevText && /\u200b$/.test(prevText)) {
event.preventDefault();
var _range$cloneRange = range.cloneRange(),
collapsed = _range$cloneRange.collapsed;
range.setStart(inlinePrev, prevText.length - 1);
if (collapsed) range.collapse(true);
change.range.select(range);
return false;
}
return true;
} // 在inline节点外
else {
var _prev = startNode.prev();
var _parent2 = startNode.parent();
var _inlineNode = undefined; //在零宽字符后面,并且前面有inline节点
if (_prev) {
if (node.isInline(_prev) && !_prev.isCard()) {
var _text = startNode.text();
var _leftText = _text.substr(0, startOffset); //不位于零宽字符后,不处理
if (!/^\u200b$/.test(_leftText)) return true;
_inlineNode = _prev;
}
} //前方没有节点,考虑是否在mark节点或其它节点内
else if (startOffset === 0) {
//循环判断是否处于inline节点内的第一个零宽字符后面,可能inline节点内包含多个mark或其它标签
while (!_prev && _parent2 && !node.isBlock(_parent2)) {
var _parent3;
_prev = _parent2.prev();
_parent2 = (_parent3 = _parent2) === null || _parent3 === void 0 ? void 0 : _parent3.parent();
} //前面有节点,并且不是 text 节点,不处理
if (_prev && !_prev.isText()) return true; //前面有text节点
if (_prev) {
//不位于零宽字符后,不处理
if (!/^\u200b$/.test(_prev.text())) return true; //位于零宽字符后,并且零宽字符前面是inline节点
_prev = _prev.prev();
if (_prev && node.isInline(_prev)) {
_inlineNode = _prev;
} else return true;
}
} else return true; //让光标选择inline内部最后一个零宽字符前
if (_inlineNode) {
event.preventDefault();
var last = _inlineNode.last();
var _text2 = last === null || last === void 0 ? void 0 : last.text();
if (last && last.isText() && _text2 && /\u200b$/.test(_text2)) {
var _range$cloneRange2 = range.cloneRange(),
_collapsed = _range$cloneRange2.collapsed;
range.setStart(last, _text2.length - 1);
if (_collapsed && !isHotkey__default['default']('shift+left', event)) {
range.collapse(true);
}
change.range.select(range);
return false;
}
}
}
}
return true;
}
}]);
return Left;
}();
var Right$2 = /*#__PURE__*/function () {
function Right(engine) {
_classCallCheck(this, Right);
this.engine = void 0;
this.engine = engine;
}
_createClass(Right, [{
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
inline = _this$engine.inline,
node = _this$engine.node;
var range = change.range.get().cloneRange().shrinkToTextNode();
var endNode = range.endNode,
endOffset = range.endOffset;
var card = this.engine.card.getSingleCard(range);
if (!card && endNode.type === Node.TEXT_NODE) {
// ->
var inlineNode = inline.closest(endNode);
var text = endNode.text(); //在inline节点内,靠近右侧位置
if (node.isInline(inlineNode)) {
if (inlineNode.isCard()) return; //offset 小于 文本长度 说明至少不在右侧,不处理
if (endOffset < text.length - 1) return true;
var next = endNode.next();
var parent = endNode.parent(); //位于inline 1级子节点下
if (parent && node.isInline(parent)) {
//后面还有节点,不处理
if (next) return true;
var rightText = text.substr(endOffset); //不位于零宽字符前,不处理
if (!/^\u200b$/.test(rightText)) return true;
} // 其它内嵌节点内,并且开始offset在最后位置,或者在倒数第一前面的位置,浏览器默认会跳出inline节点
else if (endOffset === text.length || endOffset === text.length - 1) {
//循环判断是否处于inline节点内的第一个零宽字符前面,可能inline节点内包含多个mark或其它标签
while (!next && parent && !node.isInline(parent)) {
var _parent;
next = parent.next();
parent = (_parent = parent) === null || _parent === void 0 ? void 0 : _parent.parent();
} //后面有节点,并且不是 text 节点,不处理
if (next && !next.isText()) return true; //后面有text节点
if (next) {
//不位于零宽字符前,不处理
if (!/^\u200b$/.test(next.text())) return true; //选中零宽字符前面
if (endOffset === text.length - 1) {
event.preventDefault();
var _range$cloneRange = range.cloneRange(),
collapsed = _range$cloneRange.collapsed;
range.setEnd(next, 0);
if (collapsed) range.collapse(false);
change.range.select(range);
return false;
}
}
} else return true; //让光标选择在inline节点的下一个零宽字符后面
var inlineNext = inlineNode.next();
var nextText = inlineNext === null || inlineNext === void 0 ? void 0 : inlineNext.text();
if (inlineNext && inlineNext.isText() && nextText && /^\u200b/.test(nextText)) {
event.preventDefault();
var _range$cloneRange2 = range.cloneRange(),
_collapsed = _range$cloneRange2.collapsed;
range.setEnd(inlineNext, 1);
if (_collapsed) range.collapse(false);
change.range.select(range);
return false;
}
return true;
} // 在inline节点外
else {
var _next = endNode.next();
var _parent2 = endNode.parent();
var _inlineNode = undefined; //在零宽字符后面,并且后面有inline节点
if (_next) {
if (node.isInline(_next) && !_next.isCard()) {
var _rightText = text.substr(endOffset); //不位于零宽字符前,不处理
if (!/^\u200b$/.test(_rightText)) return true;
_inlineNode = _next;
}
} //后方没有节点,考虑是否在mark节点或其它节点内
else if (endOffset === text.length) {
//循环判断是否处于inline节点内的最后一个零宽字符前面,可能inline节点内包含多个mark或其它标签
while (!_next && _parent2 && !node.isBlock(_parent2)) {
var _parent3;
_next = _parent2.next();
_parent2 = (_parent3 = _parent2) === null || _parent3 === void 0 ? void 0 : _parent3.parent();
} //后面有节点,并且不是 text 节点,不处理
if (_next && !_next.isText()) return true; //后面有text节点
if (_next) {
//不位于零宽字符前,不处理
if (!/^\u200b$/.test(_next.text())) return true; //位于零宽字符前,并且零宽字符后面是inline节点
_next = _next.next();
if (_next && node.isInline(_next)) {
_inlineNode = _next;
} else return true;
}
} else return true; //让光标选择inline内部最第一个零宽字符后
if (_inlineNode) {
event.preventDefault();
var first = _inlineNode.first();
var _text = first === null || first === void 0 ? void 0 : first.text();
if (first && first.isText() && _text && /^\u200b/.test(_text)) {
var _range$cloneRange3 = range.cloneRange(),
_collapsed2 = _range$cloneRange3.collapsed;
range.setEnd(first, 1);
if (_collapsed2 && !isHotkey__default['default']('shift+right', event)) {
range.collapse(false);
}
change.range.select(range);
return false;
}
}
}
}
return true;
}
}]);
return Right;
}();
var Inline = /*#__PURE__*/function () {
function Inline(editor) {
_classCallCheck(this, Inline);
this.editor = void 0;
this.editor = editor;
}
_createClass(Inline, [{
key: "init",
value: function init() {
var editor = this.editor;
if (isEngine(editor)) {
var _typing$getHandleList, _typing$getHandleList2, _typing$getHandleList3;
var typing = editor.typing,
event = editor.event; //删除事件
var backspace = new Backspace$5(editor);
(_typing$getHandleList = typing.getHandleListener('backspace', 'keydown')) === null || _typing$getHandleList === void 0 ? void 0 : _typing$getHandleList.on(function (event) {
return backspace.trigger(event);
}); //左方向键
var left = new Left$2(editor);
(_typing$getHandleList2 = typing.getHandleListener('left', 'keydown')) === null || _typing$getHandleList2 === void 0 ? void 0 : _typing$getHandleList2.on(function (event) {
return left.trigger(event);
}); //右方向键
var right = new Right$2(editor);
(_typing$getHandleList3 = typing.getHandleListener('right', 'keydown')) === null || _typing$getHandleList3 === void 0 ? void 0 : _typing$getHandleList3.on(function (event) {
return right.trigger(event);
});
}
}
/**
* 修复光标选区位置,acde -> acde
* 否则在ot中,可能无法正确的应用inline节点两边的更改
*/
}, {
key: "repairRange",
value: function repairRange(range) {
var _this$editor = this.editor,
change = _this$editor.change,
node = _this$editor.node;
range = range || change.range.get();
var _range = range,
startNode = _range.startNode,
startOffset = _range.startOffset,
endNode = _range.endNode,
endOffset = _range.endOffset,
collapsed = _range.collapsed;
if (collapsed) return range;
var startInline = this.closest(startNode); //让其选中节点外的 \u200b 零宽字符
if (startInline && node.isInline(startInline) && startOffset <= 1) {
//检测是否处于inline标签内部左侧
var atBefore = true;
var childNode = startNode;
while (childNode && !childNode.equal(startInline)) {
if (childNode.prev()) {
atBefore = false;
break;
}
childNode = childNode.parent();
}
if (atBefore) {
var prev = startInline.prev();
var text = (prev === null || prev === void 0 ? void 0 : prev.text()) || '';
if (prev && prev.isText() && /\u200B$/g.test(text)) {
range.setStart(prev, text.length - 1);
}
}
}
var endInline = this.closest(endNode);
var last = endInline.last();
if (endInline && node.isInline(endInline) && last && endNode.equal(last) && endOffset >= last.text().length - 1) {
//检测是否处于inline标签内部右侧
var atAfter = true;
var _childNode = startNode;
while (_childNode && !_childNode.equal(endInline)) {
if (_childNode.next()) {
atAfter = false;
break;
}
_childNode = _childNode.parent();
}
if (atAfter) {
var next = endInline.next();
var _text = (next === null || next === void 0 ? void 0 : next.text()) || '';
if (next && next.isText() && /^\u200B/g.test(_text)) {
range.setEnd(next, 1);
}
}
}
return range;
}
/**
* 获取最近的 Inline 节点,找不到返回 node
*/
}, {
key: "closest",
value: function closest(source) {
var nodeApi = this.editor.node;
var node = source.parent();
while (node && !node.isEditable() && !nodeApi.isBlock(node)) {
if (nodeApi.isInline(node)) return node;
var parentNode = node.parent();
if (!parentNode) break;
node = parentNode;
}
return source;
}
/**
* 获取向上第一个非 Inline 节点
*/
}, {
key: "closestNotInline",
value: function closestNotInline(node) {
var nodeApi = this.editor.node;
while (nodeApi.isInline(node) || nodeApi.isMark(node) || node.isText()) {
if (node.isEditable()) break;
var parent = node.parent();
if (!parent) break;
node = parent;
}
return node;
}
/**
* 给当前光标节点添加inline包裹
* @param inline inline标签
* @param range 光标,默认获取当前光标
*/
}, {
key: "wrap",
value: function wrap(inline, range) {
var _this = this;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
mark = editor.mark,
node = editor.node;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer);
if (typeof inline === 'string' || isNode(inline)) {
inline = $(inline, doc);
} else inline = inline;
if (!node.isInline(inline)) return;
if (safeRange.collapsed) {
this.insert(inline, safeRange);
if (!range) change.apply(safeRange);
return;
}
mark.split(safeRange);
this.split(safeRange);
var commonAncestorNode = safeRange.commonAncestorNode;
if (commonAncestorNode.type === Node.TEXT_NODE || node.isMark(commonAncestorNode)) {
commonAncestorNode = commonAncestorNode.parent();
while (node.isMark(commonAncestorNode)) {
commonAncestorNode = commonAncestorNode.parent();
}
} // 插入范围的开始和结束标记
var selection = safeRange.enlargeToElementNode().createSelection();
if (!selection.has()) {
if (!range) change.apply(safeRange);
return;
} // 遍历范围内的节点,添加 Inline
var started = false;
var inlineClone = node.clone(inline, false);
var inlnes = [];
commonAncestorNode.traverse(function (child) {
if (!child.equal(selection.anchor)) {
if (started) {
if (child.equal(selection.focus)) {
started = false;
return false;
}
if (node.isInline(child)) {
if (!child.isCard()) {
var children = child.children();
node.unwrap(child);
child = children;
} else {
// 如果不添加,最后选中是一个inline card 的话不会被选中
inlnes.push(child);
}
}
if (node.isMark(child) && !child.isCard() || child.isText()) {
if (node.isEmpty(child)) {
child.remove();
return true;
}
if (!inlineClone.parent()) {
child.before(inlineClone);
}
inlineClone.append(child);
_this.repairCursor(inlineClone);
inlnes.push(inlineClone);
return true;
}
if (inlineClone[0].childNodes.length !== 0 && !!inlineClone.parent()) {
inlineClone = node.clone(inlineClone, false, false);
}
}
return;
} else {
started = true;
return;
}
});
var anchor = selection.anchor,
focus = selection.focus;
var anchorParent = anchor === null || anchor === void 0 ? void 0 : anchor.parent();
if (anchorParent && node.isRootBlock(anchorParent) && !anchor.prev() && !anchor.next()) {
anchor.after('
');
}
if (!anchor.equal(focus)) {
var focusParent = focus === null || focus === void 0 ? void 0 : focus.parent();
if (focusParent && node.isRootBlock(focusParent) && !focus.prev() && !focus.next()) {
focus.before('
');
}
}
selection.move();
if (inlnes.length > 0) {
var firstInline = inlnes[0];
if (!firstInline.isCard()) {
var startNode = firstInline.first();
safeRange.setStart(startNode, 1);
}
var lastInline = inlnes[inlnes.length - 1];
if (!lastInline.isCard()) {
var lastNode = lastInline.last();
safeRange.setEnd(lastNode, lastNode.text().length - 1);
}
}
if (!range) change.apply(safeRange);
}
/**
* 移除inline包裹
* @param range 光标,默认当前编辑器光标,或者需要移除的inline节点
*/
}, {
key: "unwrap",
value: function unwrap(range) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
mark = editor.mark;
var safeRange = !range || !isRangeInterface(range) ? change.range.toTrusty() : range;
this.repairRange(safeRange);
mark.split(safeRange);
var inlineNodes = range && !isRangeInterface(range) ? [range] : this.findInlines(safeRange); // 清除 Inline
var selection = safeRange.createSelection();
inlineNodes.forEach(function (node) {
var _prev, _next, _first, _last;
var prev = node.prev();
if (prev && prev.isCursor()) prev = prev.prev();
var next = node.next();
if (next && next.isCursor()) next = next.prev();
var first = node.first();
if (first && first.isCursor()) first = first.next();
var prevText = ((_prev = prev) === null || _prev === void 0 ? void 0 : _prev.text()) || '';
var nextText = ((_next = next) === null || _next === void 0 ? void 0 : _next.text()) || '';
var firstText = ((_first = first) === null || _first === void 0 ? void 0 : _first.text()) || '';
if (prev && prev.isText() && /\u200B$/g.test(prevText)) {
if (/^\u200B$/g.test(prevText)) prev.remove();else prev.text(prevText.substr(0, prevText.length - 1));
}
if (next && next.isText() && /^\u200B/g.test(nextText)) {
if (/^\u200B$/g.test(nextText)) next.remove();else next.text(nextText.substr(1));
}
if (first && first.isText() && /^\u200B/g.test(firstText)) {
if (/^\u200B$/g.test(firstText)) first.remove();else {
first.get().splitText(1);
first.remove();
}
}
var last = node.last();
if (last && last.isCursor()) last = last.prev();
var lastText = ((_last = last) === null || _last === void 0 ? void 0 : _last.text()) || '';
if (last && last.isText() && /\u200B$/g.test(lastText)) {
if (/^\u200B$/g.test(lastText)) last.remove();else last.get().splitText(lastText.length - 1).remove();
}
editor.node.unwrap(node);
});
selection.move();
mark.merge(safeRange);
if (!range) change.apply(safeRange);
}
/**
* 插入inline标签
* @param inline inline标签
* @param range 光标
*/
}, {
key: "insert",
value: function insert(inline, range) {
var _node$insert, _inline$get;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
node = editor.node,
mark = editor.mark;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer);
if (typeof inline === 'string' || isNode(inline)) {
inline = $(inline, doc);
}
if (!node.isInline(inline)) return; // 范围为折叠状态时先删除内容
if (!safeRange.collapsed) {
change.delete(safeRange);
}
mark.split(safeRange);
this.split(safeRange); // 插入新 Inline
(_node$insert = node.insert(inline, safeRange)) === null || _node$insert === void 0 ? void 0 : _node$insert.select(inline).collapse(false);
if (inline.name !== 'br') {
safeRange.handleBr();
}
var hasChild = ((_inline$get = inline.get()) === null || _inline$get === void 0 ? void 0 : _inline$get.childNodes.length) !== 0;
this.repairCursor(inline); //如果有内容,就让光标选择在节点外的零宽字符前
if (!inline.isCard() && !node.isVoid(inline)) {
if (hasChild) {
var next = inline.next();
safeRange.setStart(next, 1);
safeRange.setEnd(next, 1);
} else {
//如果没有子节点,就让光标选择在最后的零宽字符前面
var last = inline.last();
var text = last.text();
safeRange.setStart(last, text.length - 1);
safeRange.setEnd(last, text.length - 1);
}
}
if (!range) change.apply(safeRange);
}
/**
* 去除一个节点下的所有空 Inline callback 可以设置其它条件
* @param root 节点
* @param callback 回调
*/
}, {
key: "unwrapEmptyInlines",
value: function unwrapEmptyInlines(root, callback) {
var node = this.editor.node;
var children = root.allChildren();
children.forEach(function (child) {
if (node.isEmpty(child) && node.isInline(child) && (!callback || callback(child))) {
node.unwrap(child);
}
});
}
/**
* 在光标重叠位置时分割
* @param range 光标
*/
}, {
key: "splitOnCollapsed",
value: function splitOnCollapsed(range, keelpNode) {
var _this2 = this;
if (!range.collapsed) return; //扩大光标选区
range.enlargeFromTextNode();
range.shrinkToElementNode();
var startNode = range.startNode;
var startParent = startNode.parent(); //获取卡片
var node = this.editor.node;
var card = startNode.isCard() ? startNode : startNode.closest(CARD_SELECTOR);
if ((card.length === 0 || card.attributes(CARD_TYPE_KEY) !== 'inline') && (node.isInline(startNode) || startParent && node.isInline(startParent))) {
var _rightNodes$find;
// 获取上面第一个非inline标签
var parent = this.closestNotInline(startNode); // 插入范围的开始和结束标记
var selection = range.createSelection(); // 获取标记左右两侧节点
var left = selection.getNode(parent, 'left');
var right = undefined;
var keelpRoot = undefined;
var keelpPath = [];
if (keelpNode) {
if (isNode(keelpNode)) keelpNode = $(keelpNode); // 获取需要跟踪节点的路径
var path = keelpNode.getPath(parent.get());
var cloneParent = parent.clone(true);
keelpPath = path.slice(1); // 获取需要跟踪节点的root节点
keelpRoot = $(cloneParent.getChildByPath(path.slice(0, 1)));
right = selection.getNode(cloneParent, 'right', false);
} else right = selection.getNode(parent, 'right'); // 删除空标签
this.unwrapEmptyInlines(left);
this.unwrapEmptyInlines(right); // 清空原父容器,用新的内容代替
var children = parent.children();
children.each(function (_, index) {
var _children$eq;
if (!((_children$eq = children.eq(index)) === null || _children$eq === void 0 ? void 0 : _children$eq.isCard())) {
var _children$eq2;
(_children$eq2 = children.eq(index)) === null || _children$eq2 === void 0 ? void 0 : _children$eq2.remove();
}
});
var appendChild = undefined;
var appendToParent = function appendToParent(childrenNodes) {
childrenNodes.each(function (child, index) {
var childNode = childrenNodes.eq(index);
if (childNode === null || childNode === void 0 ? void 0 : childNode.isCard()) {
appendChild = appendChild ? appendChild.next() : parent.first();
if (appendChild) childrenNodes[index] = appendChild[0];
return;
}
if (appendChild) {
appendChild.after(child);
appendChild = childNode;
} else {
appendChild = childNode;
parent.prepend(child);
}
});
};
var leftChildren = left.children();
var leftNodes = leftChildren.toArray();
appendToParent(leftChildren);
var rightChildren = right.children();
var rightNodes = rightChildren.toArray(); // 根据跟踪节点的root节点和path获取其在rightNodes中的新节点
if (keelpRoot) keelpNode = (_rightNodes$find = rightNodes.find(function (node) {
return node.equal(keelpRoot);
})) === null || _rightNodes$find === void 0 ? void 0 : _rightNodes$find.getChildByPath(keelpPath);
appendToParent(rightChildren);
rightNodes = rightChildren.toArray(); // 重新设置范围
//移除左右两边的 br 标签
if (leftNodes.length === 1 && leftNodes[0].name === 'br') {
leftNodes[0].remove();
leftNodes.splice(0, 1);
}
if (rightNodes.length === 1 && rightNodes[0].name === 'br') {
rightNodes[0].remove();
rightNodes.splice(0, 1);
}
if (rightNodes.filter(function (child) {
return !child.isCursor();
}).length > 0) {
var rightContainer = rightNodes[0];
for (var i = 0; i < rightNodes.length - 1; i++) {
rightContainer = rightNodes[i];
if (!rightContainer.isCursor()) break;
}
range.setStartBefore(rightContainer);
range.collapse(true);
} else if (leftNodes.filter(function (childNode) {
return !childNode.isCursor();
}).length > 0) {
var leftContainer = leftNodes[leftNodes.length - 1];
for (var _i = leftNodes.length - 1; _i >= 0; _i--) {
leftContainer = leftNodes[_i];
if (!leftContainer.isCursor()) break;
}
range.setStartAfter(leftContainer);
range.collapse(true);
} else {
range.select(parent, true).collapse(true);
}
parent.traverse(function (child) {
if (node.isInline(child)) {
_this2.repairCursor(child);
}
});
}
range.enlargeToElementNode(!node.isBlock(range.startNode), false);
return keelpNode;
}
/**
* 在光标位置不重合时分割
* @param range 光标
* @param removeMark 要移除的空mark节点
*/
}, {
key: "splitOnExpanded",
value: function splitOnExpanded(range) {
var _this3 = this;
if (range.collapsed) return;
range.enlargeToElementNode();
range.shrinkToElementNode();
var startNode = range.startNode,
endNode = range.endNode;
var cardStart = startNode.isCard() ? startNode : startNode.closest(CARD_SELECTOR);
var cardEnd = endNode.isCard() ? endNode : endNode.closest(CARD_SELECTOR);
if (!(cardStart.length > 0 && 'inline' === cardStart.attributes(CARD_TYPE_KEY) || cardEnd.length > 0 && 'inline' === cardEnd.attributes(CARD_TYPE_KEY))) {
//开始非inline标签父节点
var startNotInlineParent = this.closestNotInline(startNode); //结束非inine标签父节点
var endNotInlineParent = this.closestNotInline(endNode);
if (!startNotInlineParent.equal(endNotInlineParent)) {
//开始位置
var startRange = range.cloneRange();
startRange.collapse(true); //结束位置
var endRange = range.cloneRange();
endRange.collapse(false); //如果开始非inline标签父节点包含结束非inline标签父节点,那么分割的时候会清空 结束非inline标签父节点的内容进行重组。结束非inline标签父节点 将无非找到
//所以需要从被包含的节点开始分割
var keelpNode = undefined;
var startOffset = startRange.startOffset;
var endOffset = endRange.endOffset; //如果开始节点的父节点包含结尾父节点,会将结尾父节点删除重组,导致光标失效,需要先执行开始节点分割,并跟踪结尾节点
if (startNotInlineParent.contains(endNotInlineParent)) {
//先分割开始节点,并跟踪结尾节点
keelpNode = this.splitOnCollapsed(startRange, endRange.endNode);
range.setStart(startRange.startContainer, startRange.startOffset); //如果有跟踪到,重新设置结尾节点
if (keelpNode) {
endRange.setOffset(keelpNode, endOffset, endOffset);
} //分割结尾节点
this.splitOnCollapsed(endRange);
range.setEnd(endRange.startContainer, endRange.startOffset);
} else {
//结尾父节点包含开始节点父节点
//先分割结尾节点,并跟踪开始节点
keelpNode = this.splitOnCollapsed(endRange, startRange.startNode);
range.setEnd(endRange.startContainer, endRange.startOffset); //如果有跟踪到,重新设置开始节点
if (keelpNode) {
startRange.setOffset(keelpNode, startOffset, startOffset);
} //分割开始节点
this.splitOnCollapsed(startRange);
range.setStart(startRange.startContainer, startRange.startOffset);
}
return;
}
var node = this.editor.node; // 节点不是Inline,文本节点时判断父节点
var startParent = startNode.parent();
var startIsInline = node.isInline(startNode) || startParent && node.isInline(startParent);
var endParent = endNode.parent();
var endIsInline = node.isInline(endNode) || endParent && node.isInline(endParent); // 开始节点和结束节点都不是Inline,无需分割
if (!startIsInline && !endIsInline) {
return;
}
var commonAncestorNode = range.commonAncestorNode;
if (commonAncestorNode.isText()) {
commonAncestorNode = commonAncestorNode.parent();
} // 获取上面第一个非样式标签
var parent = this.closestNotInline(commonAncestorNode); // 插入范围的开始和结束标记
var selection = range.createSelection(); // 标记的左边
var left = selection.getNode(parent, 'left'); // 标记的节点
var center = selection.getNode(parent); // 标记的右边
var right = selection.getNode(parent, 'right'); // 删除空标签
this.unwrapEmptyInlines(left);
this.unwrapEmptyInlines(right); // 清空原父容器,用新的内容代替
var children = parent.children();
children.each(function (_, index) {
var _children$eq3;
if (!((_children$eq3 = children.eq(index)) === null || _children$eq3 === void 0 ? void 0 : _children$eq3.isCard())) {
var _children$eq4;
(_children$eq4 = children.eq(index)) === null || _children$eq4 === void 0 ? void 0 : _children$eq4.remove();
}
});
var appendChild = undefined;
var appendToParent = function appendToParent(childrenNodes) {
childrenNodes.each(function (child, index) {
var _childrenNodes$eq;
if ((_childrenNodes$eq = childrenNodes.eq(index)) === null || _childrenNodes$eq === void 0 ? void 0 : _childrenNodes$eq.isCard()) {
appendChild = appendChild ? appendChild.next() : parent.first();
if (appendChild) childrenNodes[index] = appendChild[0];
return;
}
if (appendChild) {
appendChild.after(child);
appendChild = childrenNodes.eq(index);
} else {
appendChild = childrenNodes.eq(index);
parent.prepend(child);
}
});
};
appendToParent(left.children());
var centerChildren = center.children();
var centerNodes = centerChildren.toArray();
appendToParent(centerChildren);
appendToParent(right.children());
parent.traverse(function (child) {
if (node.isInline(child)) {
_this3.repairCursor(child);
}
}); // 重新设置范围
range.setStartBefore(centerNodes[0][0]);
range.setEndAfter(centerNodes[centerNodes.length - 1][0]);
}
}
/**
* 分割inline标签
*/
}, {
key: "split",
value: function split(range) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change;
var safeRange = range || change.range.toTrusty(); //const selection = safeRange.createSelection('inline-split');
if (safeRange.collapsed) {
this.splitOnCollapsed(safeRange);
} else {
this.splitOnExpanded(safeRange);
} //selection.move()
if (!range) change.apply(safeRange);
}
/**
* 获取光标范围内的所有 inline 标签
* @param range 光标
*/
}, {
key: "findInlines",
value: function findInlines(range) {
var editor = this.editor;
var cloneRange = range.cloneRange();
if (cloneRange.startNode.isRoot()) cloneRange.shrinkToElementNode();
if (!cloneRange.startNode.inEditor() || editor.card.find(cloneRange.startNode)) return [];
var nodeApi = editor.node;
var handleRange = function handleRange(allowBlock, range) {
var toStart = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!range.collapsed) return;
var startNode = range.startNode,
startOffset = range.startOffset; //没有父节点
var startParent = startNode.findParent();
if (!startParent) return; //选择父节点内容
var cloneRange = range.cloneRange();
cloneRange.select(startParent, true); //开始位置
if (toStart) {
cloneRange.setEnd(startNode, startOffset);
cloneRange.enlargeFromTextNode();
cloneRange.enlargeToElementNode(true);
var startChildren = startNode.children();
var _endNode = cloneRange.endNode,
endOffset = cloneRange.endOffset;
var endChildren = _endNode.children();
var endOffsetNode = endChildren.eq(endOffset);
var startOffsetNode = startChildren.eq(startOffset) || startChildren.eq(startOffset - 1);
if (!allowBlock && _endNode.type === Node.ELEMENT_NODE && endOffsetNode && nodeApi.isBlock(endOffsetNode) && (startNode.type !== Node.ELEMENT_NODE || !!startOffsetNode && !nodeApi.isBlock(startOffsetNode))) return;
cloneRange.select(startParent, true);
cloneRange.setStart(_endNode, endOffset);
cloneRange.shrinkToElementNode();
cloneRange.shrinkToTextNode();
range.setStart(cloneRange.startContainer, cloneRange.startOffset);
range.collapse(true);
} else {
cloneRange.setStart(startNode, startOffset);
cloneRange.enlargeFromTextNode();
cloneRange.enlargeToElementNode(true);
var _startChildren = startNode.children();
var startNodeClone = cloneRange.startNode;
var startOffsetClone = cloneRange.startOffset;
var startNodeCloneChildren = startNodeClone.children();
var _startOffsetNode = startNodeCloneChildren.eq(startOffsetClone);
var startChildrenOffsetNode = _startChildren.eq(startOffset) || _startChildren.eq(startOffset - 1);
if (!allowBlock && startNodeClone.type === Node.ELEMENT_NODE && _startOffsetNode && nodeApi.isBlock(_startOffsetNode) && (startNode.type !== Node.ELEMENT_NODE || startChildrenOffsetNode && !nodeApi.isBlock(startChildrenOffsetNode))) return;
cloneRange.select(startParent, true);
cloneRange.setEnd(startNodeClone, startOffsetClone);
cloneRange.shrinkToElementNode();
cloneRange.shrinkToTextNode();
range.setEnd(cloneRange.endContainer, cloneRange.endOffset);
range.collapse(false);
}
}; // 左侧不动,只缩小右侧边界
// foobar
// 改成
// foobar
if (!cloneRange.collapsed) {
var leftRange = cloneRange.cloneRange();
var rightRange = cloneRange.cloneRange();
leftRange.collapse(true);
rightRange.collapse(false);
handleRange(true, leftRange, true);
handleRange(true, rightRange);
cloneRange.setStart(leftRange.startContainer, leftRange.startOffset), cloneRange.setEnd(rightRange.startContainer, rightRange.startOffset);
}
handleRange(false, cloneRange);
var sc = cloneRange.startContainer;
var so = cloneRange.startOffset;
var ec = cloneRange.endContainer;
var eo = cloneRange.endOffset;
var startNode = sc;
var endNode = ec;
if (sc.nodeType === Node.ELEMENT_NODE) {
if (sc.childNodes[so]) {
startNode = sc.childNodes[so] || sc;
}
}
if (ec.nodeType === Node.ELEMENT_NODE) {
if (eo > 0 && ec.childNodes[eo - 1]) {
endNode = ec.childNodes[eo - 1] || sc;
}
} // 折叠状态时,按右侧位置的方式处理
if (cloneRange.collapsed) {
startNode = endNode;
} // 不存在时添加
var addNode = function addNode(nodes, nodeB) {
if (!nodes.some(function (nodeA) {
return nodeA[0] === nodeB[0];
})) {
nodes.push(nodeB);
}
}; // 向上寻找
var findNodes = function findNodes(node) {
var nodes = [];
while (node) {
if (node.isEditable()) break;
if (nodeApi.isInline(node)) nodes.push(node);
var parent = node.parent();
if (!parent) break;
node = parent;
}
return nodes;
};
var nodes = findNodes($(startNode));
var commonAncestorNode = cloneRange.commonAncestorNode;
var card = editor.card.find(commonAncestorNode, true);
var isEditable = card === null || card === void 0 ? void 0 : card.isEditable;
var selectionNodes = isEditable ? (card === null || card === void 0 ? void 0 : card.getSelectionNodes) ? card.getSelectionNodes() : [] : [commonAncestorNode];
if (selectionNodes.length === 0) {
isEditable = false;
selectionNodes.push(commonAncestorNode);
}
if (!cloneRange.collapsed || isEditable) {
findNodes($(endNode)).forEach(function (nodeB) {
return addNode(nodes, nodeB);
});
if (sc !== ec || isEditable) {
var isBegin = false;
var isEnd = false;
selectionNodes.forEach(function (commonAncestorNode) {
commonAncestorNode.traverse(function (child) {
if (isEnd) return false; //节点不是开始节点
if (!child.equal(sc)) {
if (isBegin) {
//节点是结束节点,标记为结束
if (child.equal(ec)) {
isEnd = true;
return false;
}
if (nodeApi.isInline(child) && !child.attributes(CARD_KEY) && !child.attributes(CARD_ELEMENT_KEY)) {
addNode(nodes, child);
}
}
} else {
//如果是开始节点,标记为开始
isBegin = true;
}
return;
});
});
}
}
return nodes;
}
/**
* 修复inline节点光标占位符
* @param node inlne 节点
*/
}, {
key: "repairCursor",
value: function repairCursor(node) {
var _firstChild, _last2;
var nodeApi = this.editor.node;
if (isNode(node)) node = $(node);
if (!nodeApi.isInline(node) || node.closest(CARD_SELECTOR).attributes(CARD_EDITABLE_KEY) === 'false' || nodeApi.isVoid(node) || node.isCard()) {
var prev = node.prev();
var prevText = (prev === null || prev === void 0 ? void 0 : prev.isText()) ? prev.text() : undefined;
if (prevText && /\u200b$/.test(prevText)) {
var pPrev = prev === null || prev === void 0 ? void 0 : prev.prev();
if (!pPrev || !nodeApi.isInline(pPrev)) {
if (prevText.length === 1) {
prev === null || prev === void 0 ? void 0 : prev.remove();
} else {
prev === null || prev === void 0 ? void 0 : prev.text(prevText.slice(0, -1));
}
}
}
var next = node.next();
var nextText = (next === null || next === void 0 ? void 0 : next.isText()) ? next.text() : undefined;
if (nextText && /^\u200b/.test(nextText)) {
var nNext = next === null || next === void 0 ? void 0 : next.next();
if (!nNext || !nodeApi.isInline(nNext)) {
if (nextText.length === 1) {
next === null || next === void 0 ? void 0 : next.remove();
} else {
next === null || next === void 0 ? void 0 : next.text(nextText.slice(1));
}
}
}
return;
}
var childrenNodes = node.children();
childrenNodes.each(function (_, index) {
var child = childrenNodes.eq(index);
if (child === null || child === void 0 ? void 0 : child.isText()) {
var text = child.text();
if (text.length === 1 && /\u200b/.test(text)) {
child.remove();
return;
}
child.text(text.replace(/\u200b/g, ''));
}
});
this.repairBoth(node);
var firstChild = node.first();
if ((_firstChild = firstChild) === null || _firstChild === void 0 ? void 0 : _firstChild.isCursor()) firstChild = firstChild.next();
if (!firstChild || firstChild.type !== Node.TEXT_NODE || !/^\u200B/g.test(firstChild.text())) {
if (!firstChild) node.append($("\u200B", null));else if (firstChild.isText()) {
firstChild.text("\u200B" + firstChild.text());
} else firstChild.before($("\u200B", null));
}
var last = node.last();
if ((_last2 = last) === null || _last2 === void 0 ? void 0 : _last2.isCursor()) last = last.prev();
if (last && (/^\u200B$/g.test(node.text()) || last.type !== Node.TEXT_NODE || !/\u200B$/g.test(last.text()))) {
if (last.isText()) {
last.text(last.text() + "\u200B");
} else last.after($("\u200B", null));
}
}
/**
* 修复节点两侧零宽字符占位
* @param node 节点
*/
}, {
key: "repairBoth",
value: function repairBoth(node) {
var _nodeEl$parentElement;
var nodeApi = this.editor.node;
if (isNode(node)) node = $(node);
var nodeEl = node.get();
if (((_nodeEl$parentElement = nodeEl === null || nodeEl === void 0 ? void 0 : nodeEl.parentElement) !== null && _nodeEl$parentElement !== void 0 ? _nodeEl$parentElement : nodeEl === null || nodeEl === void 0 ? void 0 : nodeEl.parentNode) && !nodeApi.isVoid(node)) {
var zeroNode = $("\u200B", null);
var prev = node.prev();
var prevPrev = prev === null || prev === void 0 ? void 0 : prev.prev();
var prevText = (prev === null || prev === void 0 ? void 0 : prev.text()) || '';
if (!prev || !prev.isText() || !/\u200B$/g.test(prevText) || prevPrev && nodeApi.isInline(prevPrev) && !/\u200B.*\u200B$/g.test(prevText)) {
if (prev && prev.isText()) {
prev.text(prevText + "\u200B");
} else {
node.before(nodeApi.clone(zeroNode, true, false));
}
} else if (prev && prev.isText() && /\u200B\u200B$/g.test(prevText) && prevPrev && !nodeApi.isInline(prevPrev)) {
prev.text(prevText.substr(0, prevText.length - 1));
}
var next = node.next();
var nextText = (next === null || next === void 0 ? void 0 : next.text()) || '';
var nextNext = next === null || next === void 0 ? void 0 : next.next();
if (!next || !next.isText() || !/^\u200B/g.test(nextText) || nextNext && nodeApi.isInline(nextNext) && !/^\u200B\u200B/g.test(nextText)) {
if (next && next.isText()) {
next.text("\u200B" + next.text());
} else {
node.after(nodeApi.clone(zeroNode, true, false));
if ((next === null || next === void 0 ? void 0 : next.name) === 'br') {
next.remove();
}
}
} else if (next && next.isText() && /\u200B\u200B$/g.test(nextText) && nextNext && !nodeApi.isInline(nextNext)) {
next.text(nextText.substr(0, nextText.length - 1));
}
}
}
}, {
key: "flat",
value: function flat(node, schema) {
var _this4 = this;
var editor = this.editor;
if (isRangeInterface(node)) {
var selection = node.cloneRange().shrinkToElementNode().createSelection();
var inlines = this.findInlines(node);
var applyInlines = [];
inlines.forEach(function (inline) {
if (inline.isCard()) return;
var newInline = _this4.flat(inline);
if (newInline) applyInlines.push(newInline);
});
selection.move();
var _nodeApi = editor.node;
applyInlines.forEach(function (inline) {
var _inline$prev, _inline$next;
var prev = (_inline$prev = inline.prev()) === null || _inline$prev === void 0 ? void 0 : _inline$prev.prev();
var next = (_inline$next = inline.next()) === null || _inline$next === void 0 ? void 0 : _inline$next.next();
if (prev && _nodeApi.isMark(prev) && prev.get().childNodes.length === 0) {
prev.remove();
}
if (next && _nodeApi.isMark(next) && next.get().childNodes.length === 0) {
next.remove();
}
});
return;
}
if (node.isCard()) return;
var nodeApi = editor.node;
var markApi = editor.mark; //当前节点是 inline 节点,inline 节点不允许嵌套、不允许放入mark节点
if (nodeApi.isInline(node, schema) && node.name !== 'br') {
var parentInline = this.closest(node); //不允许嵌套
if (!parentInline.equal(node) && nodeApi.isInline(parentInline, schema)) {
nodeApi.unwrap(node);
} //不允许放入mark
else {
var _ret = function () {
var parentMark = markApi.closest(node);
var element = node;
var _loop = function _loop() {
var cloneMark = parentMark.clone();
var cloneInline = node.clone();
var children = parentMark.children();
children.each(function (child) {
// 零宽字符的文本跳过
if (child.nodeType === 3 && /^\u200b$/.test(child.textContent || '')) {
return;
}
var childNode = $(child);
if (element.equal(childNode) || childNode.contains(element)) {
element = nodeApi.wrap(nodeApi.replace(element, cloneMark), cloneInline);
_this4.repairBoth(element);
} else {
nodeApi.wrap(childNode, cloneMark);
}
});
nodeApi.unwrap(parentMark);
parentMark = markApi.closest(element);
};
while (parentMark && !parentMark.equal(node) && nodeApi.isMark(parentMark, schema)) {
_loop();
}
return {
v: element
};
}();
if (_typeof(_ret) === "object") return _ret.v;
}
}
return;
}
}]);
return Inline;
}();
var Enter$4 = /*#__PURE__*/function () {
function Enter(engine) {
_classCallCheck(this, Enter);
this.engine = void 0;
this.engine = engine;
}
_createClass(Enter, [{
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
node = _this$engine.node,
list = _this$engine.list;
var range = change.range.get().shrinkToElementNode().shrinkToTextNode(); // 选区选中最后的节点
var blockApi = this.engine.block;
var block = blockApi.closest(range.endNode); // 嵌套 block
var parent = block.parent();
if (parent && parent.inEditor() && node.isBlock(parent)) {
var _range$startContainer;
if ('li' === parent.name && 'p' === block.name) {
var _block$get, _block$first;
if (1 === ((_block$get = block.get()) === null || _block$get === void 0 ? void 0 : _block$get.childNodes.length) && 'br' === ((_block$first = block.first()) === null || _block$first === void 0 ? void 0 : _block$first.name)) {
block.first().remove();
}
var selection = range.createSelection();
change.unwrap(block);
selection.move();
block = blockApi.closest(range.endNode);
}
if (range.collapsed && (range.startContainer.childNodes.length === 1 && 'BR' === ((_range$startContainer = range.startContainer.firstChild) === null || _range$startContainer === void 0 ? void 0 : _range$startContainer.nodeName) || blockApi.isLastOffset(range, 'end') && blockApi.isFirstOffset(range, 'end'))) {
event.preventDefault();
if (['li'].indexOf(parent.name) >= 0) {
blockApi.unwrap('<'.concat(parent.name, ' />'));
blockApi.setBlocks('<'.concat(parent.name, ' />'));
} else {
blockApi.unwrap('<'.concat(parent.name, ' />'));
blockApi.setBlocks('');
}
return false;
}
}
if (node.isBlock(block) && (!parent || !node.isList(parent)) && !block.isCard()) {
event.preventDefault();
blockApi.insertOrSplit(range, block);
return false;
} // 列表
if (block.name === 'li') {
return;
}
return true;
}
}]);
return Enter;
}();
var Backspace$6 = /*#__PURE__*/function () {
function Backspace(engine) {
_classCallCheck(this, Backspace);
this.engine = void 0;
this.engine = engine;
}
_createClass(Backspace, [{
key: "trigger",
value: function trigger(event) {
var _this$engine = this.engine,
change = _this$engine.change,
node = _this$engine.node,
block = _this$engine.block,
card = _this$engine.card;
var range = change.range.get();
if (!range.collapsed) return;
var prevNode = range.getPrevNode();
if (prevNode && node.isBlock(prevNode) && node.isEmptyWithTrim(prevNode)) {
event.preventDefault();
var parent = prevNode.parent();
prevNode.remove();
if (parent && this.engine.node.isEmpty(parent)) {
if (parent.isEditable()) {
this.engine.node.html(parent, '
');
range.select(parent, true).shrinkToElementNode().collapse(false);
} else {
this.engine.node.html(parent, '
');
range.select(parent, true).collapse(false);
}
change.apply(range);
}
return false;
} // 光标不在段落开始位置时
var isCard = !!card.closest(range.startNode);
if (!isCard && !block.isFirstOffset(range, 'start')) {
var cloneRange = range.cloneRange().shrinkToElementNode().shrinkToTextNode();
if (cloneRange.startContainer.nodeType === Node.TEXT_NODE && function (range) {
var _range = range,
commonAncestorContainer = _range.commonAncestorContainer,
commonAncestorNode = _range.commonAncestorNode;
var commonAncestorParent = commonAncestorNode.parent();
var commonAncestorAttributes = commonAncestorParent === null || commonAncestorParent === void 0 ? void 0 : commonAncestorParent.attributes();
if (range.collapsed && 1 === range.startOffset && range.startContainer === commonAncestorContainer && commonAncestorContainer.nodeType === Node.TEXT_NODE && (!commonAncestorAttributes || !['left', 'right'].includes(commonAncestorAttributes[CARD_ELEMENT_KEY]))) {
var _ref, _ref$childNodes, _commonAncestorContai, _commonAncestorContai2;
range = range.cloneRange();
if ((((_ref = (_commonAncestorContai = commonAncestorContainer.parentElement) !== null && _commonAncestorContai !== void 0 ? _commonAncestorContai : commonAncestorContainer.parentNode) === null || _ref === void 0 ? void 0 : (_ref$childNodes = _ref.childNodes) === null || _ref$childNodes === void 0 ? void 0 : _ref$childNodes.length) || 0) <= 1 && 1 === ((_commonAncestorContai2 = commonAncestorContainer.textContent) === null || _commonAncestorContai2 === void 0 ? void 0 : _commonAncestorContai2.length)) {
var _range2 = range,
startNode = _range2.startNode,
startOffset = _range2.startOffset;
var markNode = startNode.parent(); //开始节点在mark标签内
if (markNode && node.isMark(markNode) && startOffset > 0) {
var text = startNode.text();
var leftText = text.substr(startOffset - 1, 1); //不位于零宽字符后,不处理
if (/^\u200b$/.test(leftText)) {
//选中上一个节点
if (startOffset === 1) {
var prev = markNode.prev();
if (prev && !node.isEmpty(prev)) {
var _range$cloneRange$sel = range.cloneRange().select(prev, true).shrinkToTextNode().collapse(false),
_startNode = _range$cloneRange$sel.startNode,
_startOffset = _range$cloneRange$sel.startOffset;
range.setStart(_startNode, _startOffset - 1);
}
} else {
range.setStart(startNode, startOffset - 1);
}
}
}
if (range.collapsed) range.select(commonAncestorContainer, true);
change.delete(range, true);
change.apply(range);
return true;
}
}
return false;
}(cloneRange)) {
event.preventDefault();
event['isDelete'] = true;
change.change();
}
return;
}
var blockNode = block.closest(range.startNode); // 在正文里
if (!isCard && node.isRootBlock(blockNode)) {
event.preventDefault(); // 空的节点就清空所有的mark空节点以及inline节点,避免重复的合并到上一级节点上
if (node.isEmpty(blockNode)) blockNode.html('
');
change.mergeAfterDelete(blockNode);
change.change(false);
return false;
}
return true;
}
}]);
return Backspace;
}();
var Block = /*#__PURE__*/function () {
function Block(editor) {
_classCallCheck(this, Block);
this.editor = void 0;
this.pluginCaches = new Map();
this.editor = editor;
}
_createClass(Block, [{
key: "init",
value: function init() {
var _this = this;
var editor = this.editor;
if (isEngine(editor)) {
var _typing$getHandleList, _typing$getHandleList2;
var typing = editor.typing,
event = editor.event; //绑定回车事件
var enter = new Enter$4(editor);
(_typing$getHandleList = typing.getHandleListener('enter', 'keydown')) === null || _typing$getHandleList === void 0 ? void 0 : _typing$getHandleList.on(function (event) {
return enter.trigger(event);
}); //删除事件
var backspace = new Backspace$6(editor);
(_typing$getHandleList2 = typing.getHandleListener('backspace', 'keydown')) === null || _typing$getHandleList2 === void 0 ? void 0 : _typing$getHandleList2.on(function (event) {
return backspace.trigger(event);
});
event.on('keyup:space', function (event) {
return _this.triggerMarkdown(event);
});
event.on('keydown:enter', function (event) {
return _this.triggerMarkdown(event);
});
}
}
/**
* 解析markdown
* @param event 事件
*/
}, {
key: "triggerMarkdown",
value: function triggerMarkdown(event) {
var _editor$options$markd;
var editor = this.editor;
if (!isEngine(editor) || ((_editor$options$markd = editor.options.markdown) === null || _editor$options$markd === void 0 ? void 0 : _editor$options$markd.mode) === false) return;
var change = editor.change;
var range = change.range.get();
if (!range.collapsed || change.isComposing()) return;
var startNode = range.startNode,
startOffset = range.startOffset;
var node = startNode.type === Node.TEXT_NODE ? startNode : startNode.children().eq(startOffset - 1);
if (!node) return;
var blockNode = this.closest(node);
if (!editor.node.isRootBlock(blockNode)) return;
var text = node.text().trim();
if (text.replace(/\s|\t|\n|\r\n|\u200b/g, '') === '') return;
var cacheRange = range.toPath();
var markdown = createMarkdownIt(editor, 'zero');
var tokens = markdown.parse(text, {});
if (tokens.length === 0) return;
var content = convertMarkdown(editor, markdown, tokens, false);
if (content) {
var children = blockNode.children();
event.preventDefault();
range.select(blockNode, true);
change.paste(content, range);
var newBlock = this.closest(range.startNode);
if (!newBlock.isRoot() && !newBlock.isCard()) {
children.each(function (child, i) {
if (i > 0) {
newBlock.append(child);
}
});
}
change.rangePathBeforeCommand = cacheRange;
change.range.select(range);
return false;
}
return true;
}
}, {
key: "findPlugin",
value:
/**
* 根据节点查找block插件实例
* @param node 节点
*/
function findPlugin(block) {
var _this$editor = this.editor,
node = _this$editor.node,
schema = _this$editor.schema,
plugin = _this$editor.plugin;
if (block.length === 0 || !node.isBlock(block)) return;
var markClone = block.get().cloneNode();
var key = markClone.outerHTML;
var result = this.pluginCaches.get(key);
if (result) return result;
for (var pluginName in plugin.components) {
var blockPlugin = plugin.components[pluginName];
if (isBlockPlugin(blockPlugin) && (!blockPlugin.tagName || typeof blockPlugin.tagName === 'string' ? block.name === blockPlugin.tagName : blockPlugin.tagName.indexOf(block.name) > -1)) {
var schemaRule = blockPlugin.schema();
if (Array.isArray(schemaRule) ? schemaRule.find(function (rule) {
return schema.checkNode(block, rule.attributes);
}) : schema.checkNode(block, schemaRule.attributes)) {
this.pluginCaches.set(key, blockPlugin);
return blockPlugin;
}
}
}
return result;
}
/**
* 查找Block节点的一级节点。如 div -> H2 返回 H2节点
* @param parentNode 父节点
* @param childNode 子节点
*/
}, {
key: "findTop",
value: function findTop(parentNode, childNode) {
var _this$editor2 = this.editor,
schema = _this$editor2.schema,
node = _this$editor2.node,
list = _this$editor2.list;
var topParentName = schema.closest(parentNode.name);
var topChildName = schema.closest(childNode.name); //如果父节点没有级别或者子节点没有级别就返回子节点
if (topParentName === parent.name || topChildName === childNode.name) return childNode; //如果父节点的级别大于子节点的级别就返回父节点
if (schema.isAllowIn(parentNode.name, childNode.name)) return parentNode; //如果父节点是 ul、ol 这样的List列表,并且子节点也是这样的列表,设置ident
if (node.isList(parentNode) && node.isList(childNode)) {
var childIndent = parseInt(childNode.attributes(list.INDENT_KEY), 10) || 0;
var parentIndent = parseInt(parentNode.attributes(list.INDENT_KEY), 10) || 0;
childNode.attributes(list.INDENT_KEY, parentIndent ? parentIndent + 1 : childIndent + 1);
} //默认返回子节点
return childNode;
}
/**
* 获取最近的block节点,找不到返回 node
* @param node 节点
* @param callback 回调
*/
}, {
key: "closest",
value: function closest(node) {
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
return true;
};
var originNode = node;
while (node) {
if ((node.isEditable() || this.editor.node.isBlock(node)) && callback(node)) {
return node;
}
var parentNode = node.parent();
if (!parentNode) break;
node = parentNode;
}
return originNode;
}
/**
* 在光标位置包裹一个block节点
* @param block 节点
* @param range 光标
*/
}, {
key: "wrap",
value: function wrap(block, range) {
var _this2 = this,
_blocks$;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
node = editor.node,
schema = editor.schema,
list = editor.list,
mark = editor.mark;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer);
if (typeof block === 'string' || isNode(block)) {
block = $(block, doc);
} else block = block;
if (!node.isBlock(block)) return;
var blocks = this.getBlocks(safeRange);
var targetPlugin = this.findPlugin(block); //一样的block插件不嵌套
blocks = blocks.map(function (blockNode) {
var _blockNode;
if (!blockNode || blockNode.isCard()) return null;
var wrapBlock = block;
var blockParent = (_blockNode = blockNode) === null || _blockNode === void 0 ? void 0 : _blockNode.parent();
while (blockParent && !blockParent.isEditable()) {
blockNode = blockParent;
var _parent2 = blockParent.parent();
if (_parent2 && node.isBlock(_parent2)) {
blockParent = _parent2;
} else break;
} //|| blockParent && !blockParent.equal(blockNode) && !blockParent.isRoot() && node.isBlock(blockParent) && !schema.isAllowIn(wrapBlock.name, blockParent.name)
if (!schema.isAllowIn(wrapBlock.name, blockNode.name)) {
//一样的插件,返回子级
if (_this2.findPlugin(blockNode) === targetPlugin) {
return blockNode.children();
}
return null;
}
return blockNode;
}).filter(function (block) {
return block !== null;
}); // 不在段落内
if (blocks.length === 0) {
var root = this.closest(safeRange.startNode);
if (root.isCard() || root.isEditable() || !schema.isAllowIn(block.name, root.name)) return;
var _selection = safeRange.createSelection();
root.children().each(function (node) {
block.append(node);
});
root.append(block);
_selection.move();
return;
}
var selection = safeRange.createSelection();
(_blocks$ = blocks[0]) === null || _blocks$ === void 0 ? void 0 : _blocks$.before(block);
blocks.forEach(function (child) {
if (child) {
//先移除不能放入块级节点的mark标签
if (targetPlugin) {
child.allChildren().forEach(function (markNode) {
if (node.isMark(markNode)) {
var _targetPlugin$disable;
var markPlugin = mark.findPlugin(markNode);
if (!markPlugin) return;
if ((_targetPlugin$disable = targetPlugin.disableMark) === null || _targetPlugin$disable === void 0 ? void 0 : _targetPlugin$disable.indexOf(markPlugin.constructor.pluginName)) {
node.unwrap(markNode);
}
}
});
}
block.append(child);
}
});
selection.move();
this.merge(safeRange);
list.merge(undefined, safeRange);
if (!range) change.apply(safeRange);
}
/**
* 移除光标所在block节点包裹
* @param block 节点
* @param range 光标
*/
}, {
key: "unwrap",
value: function unwrap(block, range) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
node = editor.node;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer);
if (typeof block === 'string' || isNode(block)) {
block = $(block, doc);
} else block = block;
if (!node.isBlock(block)) return;
var blocks = this.getSiblings(safeRange, block);
if (blocks.length === 0) {
return;
}
var firstNodeParent = blocks[0].node.parent();
if (!(firstNodeParent === null || firstNodeParent === void 0 ? void 0 : firstNodeParent.inEditor())) {
return;
}
var hasLeft = blocks.some(function (item) {
return item.position === 'left';
});
var hasRight = blocks.some(function (item) {
return item.position === 'right';
});
var leftParent = undefined;
if (hasLeft) {
var _parent3 = firstNodeParent;
leftParent = node.clone(_parent3, false, false);
_parent3.before(leftParent);
}
var rightParent = undefined;
if (hasRight) {
var _parent = blocks[blocks.length - 1].node.parent();
if (_parent) {
rightParent = node.clone(_parent, false, false);
_parent === null || _parent === void 0 ? void 0 : _parent.after(rightParent);
}
} // 插入范围的开始和结束标记
var selection = safeRange.createSelection();
var nodeApi = node;
blocks.forEach(function (item) {
var status = item.position,
node = item.node,
parent = node.parent();
if (status === 'left') {
var _leftParent;
(_leftParent = leftParent) === null || _leftParent === void 0 ? void 0 : _leftParent.append(node);
}
if (status === 'center') {
var _block;
if ((parent === null || parent === void 0 ? void 0 : parent.name) === ((_block = block) === null || _block === void 0 ? void 0 : _block.name) && (parent === null || parent === void 0 ? void 0 : parent.inEditor())) {
nodeApi.unwrap(parent);
}
}
if (status === 'right') {
var _rightParent;
(_rightParent = rightParent) === null || _rightParent === void 0 ? void 0 : _rightParent.append(node);
}
}); // 有序列表被从中间拆开后,剩余的两个部分的需要保持序号连续
if (leftParent && leftParent.name === 'ol' && rightParent && rightParent.name === 'ol') {
rightParent.attributes('start', (parseInt(leftParent.attributes('start'), 10) || 1) + leftParent.find('li').length);
}
selection.move();
if (!range) change.apply(safeRange);
}
/**
* 获取节点相对于光标开始位置、结束位置下的兄弟节点集合
* @param range 光标
* @param block 节点
*/
}, {
key: "getSiblings",
value: function getSiblings(range, block) {
var _this3 = this;
var blocks = [];
var nodeApi = this.editor.node;
if (!nodeApi.isBlock(block)) return blocks;
var getTargetBlock = function getTargetBlock(node, tagName) {
var block = _this3.closest(node);
while (block) {
var _parent4 = block.parent();
if (!_parent4) break;
if (!block.inEditor()) break;
if (block.text().trim() !== _parent4.text().trim()) break;
if (_parent4.name === tagName) break;
block = _parent4;
}
return block;
};
var startBlock = getTargetBlock(range.startNode, block.name);
var endBlock = getTargetBlock(range.endNode, block.name);
var parentBlock = startBlock.parent();
var position = 'left';
var node = parentBlock === null || parentBlock === void 0 ? void 0 : parentBlock.first();
while (node) {
node = $(node);
if (!nodeApi.isBlock(node)) return blocks;
if (!node.inEditor()) return blocks;
if (node[0] === startBlock[0]) {
position = 'center';
}
blocks.push({
position: position,
node: node
});
if (node[0] === endBlock[0]) {
position = 'right';
}
node = node.next();
}
return blocks;
}
/**
* 分割当前光标选中的block节点
* @param range 光标
*/
}, {
key: "split",
value: function split(range) {
var _sideBlock$get, _sideBlock$first;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
mark = editor.mark,
nodeId = editor.nodeId;
var safeRange = range || change.range.toTrusty(); // 范围为展开状态时先删除内容
if (!safeRange.collapsed) {
change.delete(safeRange);
} // 获取上面第一个 Block
var block = this.closest(safeRange.startNode); // 获取的 block 超出编辑范围
if (!block.isEditable() && !block.inEditor()) {
return;
}
if (block.isEditable()) {
// wo
other
// to
// wo
other
var sc = safeRange.getStartOffsetNode();
if (sc) {
safeRange.select(sc, true).shrinkToElementNode().collapse(false);
}
if (!range) change.apply(safeRange);
return;
}
var cloneRange = safeRange.cloneRange();
cloneRange.shrinkToElementNode().shrinkToTextNode().collapse(true);
var activeMarks = mark.findMarks(cloneRange).filter(function (mark) {
// 回车后,默认是否复制makr样式
var plugin = editor.mark.findPlugin(mark);
return (plugin === null || plugin === void 0 ? void 0 : plugin.copyOnEnter) !== false && (plugin === null || plugin === void 0 ? void 0 : plugin.followStyle) !== false;
});
var sideBlock = this.getBlockByRange({
block: block[0],
range: safeRange,
isLeft: false,
keepDataId: true
});
var nodeApi = editor.node;
sideBlock.traverse(function (node) {
if (!nodeApi.isVoid(node) && (nodeApi.isInline(node) || nodeApi.isMark(node)) && nodeApi.isEmpty(node)) {
node.remove();
}
}, true);
var isEmptyElement = function isEmptyElement(node) {
return nodeApi.isBlock(node) && (node.childNodes.length === 0 || node.innerText === '');
};
if (isEmptyElement(block[0]) && !isEmptyElement(sideBlock[0])) {
nodeId.generate(block, true);
} else {
nodeId.generate(sideBlock, true);
}
block.after(sideBlock); // 里面必须要有节点,插入 BR 之后输入文字自动消失
if (nodeApi.isEmpty(block)) {
nodeApi.html(block, nodeApi.getBatchAppendHTML(activeMarks, activeMarks.length > 0 ? '' : '
'));
}
if (nodeApi.isEmpty(sideBlock)) {
nodeApi.html(sideBlock, nodeApi.getBatchAppendHTML(activeMarks, activeMarks.length > 0 ? '' : '
'));
}
block.children().each(function (child) {
if (nodeApi.isInline(child)) {
editor.inline.repairCursor(child);
}
});
sideBlock.children().each(function (child) {
if (nodeApi.isInline(child)) {
editor.inline.repairCursor(child);
}
}); // 重新设置当前选中范围
safeRange.select(sideBlock, true).shrinkToElementNode();
if (((_sideBlock$get = sideBlock.get()) === null || _sideBlock$get === void 0 ? void 0 : _sideBlock$get.childNodes.length) === 1 && ((_sideBlock$first = sideBlock.first()) === null || _sideBlock$first === void 0 ? void 0 : _sideBlock$first.name) === 'br') {
safeRange.collapse(false);
} else {
safeRange.collapse(true);
}
if (!range) change.apply(safeRange);
return sideBlock;
}
/**
* 在当前光标位置插入block节点
* @param block 节点
* @param range 光标
* @param splitNode 分割节点,默认为光标开始位置的block节点
*/
}, {
key: "insert",
value: function insert(block, range, splitNode) {
var _container$get, _container$first;
var removeCurrentEmptyBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
node = editor.node,
list = editor.list,
inline = editor.inline;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer);
if (typeof block === 'string' || isNode(block)) {
block = $(block, doc);
} else block = block;
if (!node.isBlock(block)) return; // 范围为折叠状态时先删除内容
if (!safeRange.collapsed) {
change.delete(safeRange);
} // 获取上面第一个 Block
var container = this.closest(safeRange.startNode); // 超出编辑范围
if (!container.isEditable() && !container.inEditor()) {
if (!range) change.apply(safeRange);
return;
} // 当前选择范围在段落外面
if (container.isEditable()) {
node.insert(block, safeRange, removeCurrentEmptyBlock);
safeRange.collapse(false);
if (!range) change.apply(safeRange);
return;
}
if (node.isList(safeRange.startNode) || safeRange.startNode.closest('li').length > 0) {
var fragment = doc.createDocumentFragment();
fragment.appendChild(block[0]);
list.insert(fragment, safeRange);
if (!range) change.apply(safeRange);
return;
} //
// to
//
if (((_container$get = container.get()) === null || _container$get === void 0 ? void 0 : _container$get.childNodes.length) === 1 && ((_container$first = container.first()) === null || _container$first === void 0 ? void 0 : _container$first.name) === 'br') {
safeRange.select(container, true).collapse(false);
} // 插入范围的开始和结束标记
var selection = safeRange.enlargeToElementNode().createSelection();
if (!selection.has()) {
if (!range) change.apply(safeRange);
return;
}
container = splitNode ? splitNode(container) : container; // 切割 Block
var leftNodes = selection.getNode(container, 'left');
leftNodes.traverse(function (leftNode) {
if (leftNode.equal(leftNodes)) return;
if (node.isBlock(leftNode) && (node.isEmpty(leftNode) || list.isEmptyItem(leftNode))) {
leftNode.remove();
}
});
var rightNodes = selection.getNode(container, 'right', true, function (child) {
if (child.isCard()) {
var _parent5 = child.parent();
if (_parent5 && node.isCustomize(_parent5)) return false;
}
return true;
}); // 清空原父容器,用新的内容代替
var children = container.children();
if (!node.isEmpty(container)) {
children.each(function (_, index) {
var child = children.eq(index);
if (!(child === null || child === void 0 ? void 0 : child.isCard())) {
var _children$eq;
(_children$eq = children.eq(index)) === null || _children$eq === void 0 ? void 0 : _children$eq.remove();
}
});
}
rightNodes.traverse(function (rightNode) {
if (!rightNode.equal(rightNodes)) return;
if (node.isBlock(rightNode) && (node.isEmpty(rightNode) || list.isEmptyItem(rightNode))) {
rightNode.remove();
} else if (node.isList(rightNode)) {
list.addBr(rightNode);
}
});
if (rightNodes.length > 0 && !node.isEmpty(rightNodes) && !list.isEmptyItem(rightNodes)) {
var right = rightNodes.clone(false);
editor.nodeId.generate(right, true);
var rightChildren = rightNodes.children();
rightChildren.each(function (child, index) {
var _rightChildren$eq;
if ((_rightChildren$eq = rightChildren.eq(index)) === null || _rightChildren$eq === void 0 ? void 0 : _rightChildren$eq.isCard()) {
var card = editor.card.find(child);
if (card) right.append(card.root);
} else right.append(child);
});
rightNodes = right;
container.after(right);
}
if (leftNodes.length > 0 && !node.isEmpty(leftNodes) && !list.isEmptyItem(leftNodes)) {
var appendChild = undefined;
var appendToParent = function appendToParent(childrenNodes) {
childrenNodes.each(function (child, index) {
var childNode = childrenNodes.eq(index);
if (childNode && node.isInline(childNode)) {
inline.repairCursor(childNode);
}
if (childNode === null || childNode === void 0 ? void 0 : childNode.isCard()) {
appendChild = appendChild ? appendChild.next() : container.first();
if (appendChild) childrenNodes[index] = appendChild[0];
return;
}
if (appendChild) {
appendChild.after(child);
appendChild = childNode;
} else {
appendChild = childNode;
container.prepend(child);
}
});
};
appendToParent(leftNodes.children());
}
if (container && container.length > 0) {
safeRange.select(container, true);
safeRange.collapse(false);
}
if (selection.focus) selection.focus.remove();
if (selection.anchor) selection.anchor.remove(); // 插入新 Block
node.insert(block, safeRange, removeCurrentEmptyBlock);
if (!range) change.apply(safeRange);
}
/**
* 设置当前光标所在的所有block节点为新的节点或设置新属性
* @param block 需要设置的节点或者节点属性
* @param range 光标
*/
}, {
key: "setBlocks",
value: function setBlocks(block, range) {
var _this4 = this;
var editor = this.editor;
if (!isEngine(editor)) return;
var node = editor.node,
schema = editor.schema,
mark = editor.mark;
var change = editor.change;
var safeRange = range || change.range.toTrusty();
var doc = getDocument(safeRange.startContainer);
var targetNode = null;
var attributes = {};
if (typeof block === 'string') {
targetNode = $(block, doc);
attributes = targetNode.attributes();
attributes.style = targetNode.css();
} else {
attributes = block;
}
var blocks = this.getBlocks(safeRange); // 编辑器根节点,无段落
var startNode = safeRange.startNode;
if (startNode.isEditable() && blocks.length === 0) {
if (startNode.isCard() || startNode.isEditable()) return;
var newBlock = targetNode || $('');
if (!schema.isAllowIn(newBlock.name, startNode.name)) return;
node.setAttributes(newBlock, attributes);
var _selection2 = safeRange.createSelection();
startNode.children().each(function (node) {
newBlock.append(node);
}); // 复制全局属性
var globals = schema.data.globals['block'] || {};
var oldAttributes = startNode.attributes();
Object.keys(oldAttributes).forEach(function (name) {
if (name !== DATA_ID && name !== 'id' && globals['name']) {
newBlock.attributes(name, oldAttributes[name]);
}
}); // 复制全局样式,及生成 text-align
var globalStyles = globals.style || {};
var styles = startNode.css();
Object.keys(styles).forEach(function (name) {
if (!globalStyles[name]) delete styles[name];
});
newBlock.css(styles);
startNode.append(newBlock);
_selection2.move();
if (!range) change.apply(safeRange);
return;
}
var targetPlugin = targetNode ? this.findPlugin(targetNode) : undefined;
var selection = safeRange.createSelection();
blocks.forEach(function (child) {
// Card 不做处理
if (child.attributes(CARD_KEY)) {
return;
}
if (targetNode) {
// 复制全局属性
var _globals = schema.data.globals['block'] || {};
var _oldAttributes = child.attributes();
Object.keys(_oldAttributes).forEach(function (name) {
if (name !== DATA_ID && name !== 'id' && _globals['name']) {
var _targetNode;
(_targetNode = targetNode) === null || _targetNode === void 0 ? void 0 : _targetNode.attributes(name, _oldAttributes[name]);
}
}); // 复制全局样式,及生成 text-align
var _globalStyles = _globals.style || {};
var _styles = child.css();
Object.keys(_styles).forEach(function (name) {
if (!_globalStyles[name]) delete _styles[name];
});
targetNode.css(_styles);
} // 相同标签,或者只传入样式属性
if (!targetNode || _this4.findPlugin(child) === targetPlugin && child.name === targetNode.name) {
if (targetNode) attributes = targetNode.attributes();
node.setAttributes(child, attributes);
return;
} //如果要包裹的节点可以放入到当前节点中,就不操作
if (targetNode.name !== 'p' && schema.isAllowIn(child.name, targetNode.name)) {
return;
} //先移除不能放入块级节点的mark标签
if (targetPlugin) {
child.allChildren().forEach(function (markNode) {
if (node.isMark(markNode)) {
var markPlugin = mark.findPlugin(markNode);
if (!markPlugin) return;
if (targetPlugin.disableMark && targetPlugin.disableMark.indexOf(markPlugin.constructor.pluginName) > -1) {
node.unwrap(markNode);
}
}
});
}
var newNode = node.replace(child, targetNode);
var parent = newNode.parent();
if (parent && !parent.isEditable() && !schema.isAllowIn(parent.name, newNode.name)) {
node.unwrap(parent);
}
});
selection.move();
if (!range) change.apply(safeRange);
}
/**
* 合并当前光标位置相邻的block
* @param range 光标
*/
}, {
key: "merge",
value: function merge(range) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change,
schema = editor.schema;
var safeRange = range || change.range.toTrusty();
var blocks = this.getBlocks(safeRange);
if (0 === blocks.length) return;
var root = blocks[0].closest(ROOT_SELECTOR);
var tags = schema.getCanMergeTags();
if (tags.length === 0) return;
var block = root.find(tags.join(','));
if (block.length > 0) {
var selection = safeRange.createSelection();
var nextNode = block.next();
while (nextNode && tags.indexOf(nextNode.name) > 0) {
var prevNode = nextNode.prev();
var nextAttributes = nextNode.attributes();
var prevAttributes = prevNode === null || prevNode === void 0 ? void 0 : prevNode.attributes();
if (nextNode.name === (prevNode === null || prevNode === void 0 ? void 0 : prevNode.name) && nextAttributes['class'] === (prevAttributes ? prevAttributes['class'] : undefined) && Object.keys(nextAttributes).join(',') === Object.keys(prevAttributes || {}).join(',')) {
editor.node.merge(prevNode, nextNode);
}
nextNode = nextNode.next();
}
selection.move();
}
if (!range) change.apply(safeRange);
}
/**
* 获取对范围有效果的所有 Block
*/
}, {
key: "findBlocks",
value: function findBlocks(range) {
var _editor$card$find;
var editor = this.editor;
range = range.cloneRange();
if (range.startNode.isRoot()) range.shrinkToElementNode();
if (!range.startNode.inEditor() || ((_editor$card$find = editor.card.find(range.startNode)) === null || _editor$card$find === void 0 ? void 0 : _editor$card$find.type) === exports.CardType.BLOCK) return [];
var sc = range.startContainer;
var so = range.startOffset;
var ec = range.endContainer;
var eo = range.endOffset;
var startNode = sc;
var endNode = ec;
if (sc.nodeType === Node.ELEMENT_NODE) {
if (sc.childNodes[so]) {
startNode = sc.childNodes[so] || sc;
}
}
if (ec.nodeType === Node.ELEMENT_NODE) {
if (eo > 0 && ec.childNodes[eo - 1]) {
endNode = ec.childNodes[eo - 1] || sc;
}
} // 折叠状态时,按右侧位置的方式处理
if (range.collapsed) {
startNode = endNode;
} // 不存在时添加
var addNode = function addNode(nodes, nodeB, preppend) {
if (!nodes.some(function (nodeA) {
return nodeA[0] === nodeB[0];
})) {
if (preppend) {
nodes.unshift(nodeB);
} else {
nodes.push(nodeB);
}
}
}; // 向上寻找
var findNodes = function findNodes(node) {
var nodes = [];
while (node) {
if (node.isEditable()) {
break;
}
if (editor.node.isBlock(node)) {
nodes.push(node);
}
var _parent6 = node.parent();
if (!_parent6) break;
node = _parent6;
}
return nodes;
};
var nodes = this.getBlocks(range); // rang头部应该往数组头部插入节点
findNodes($(startNode)).forEach(function (node) {
return addNode(nodes, node, true);
});
var _range = range,
commonAncestorNode = _range.commonAncestorNode;
var card = editor.card.find(commonAncestorNode, true);
var isEditable = card === null || card === void 0 ? void 0 : card.isEditable;
var selectionNodes = isEditable ? (card === null || card === void 0 ? void 0 : card.getSelectionNodes) ? card.getSelectionNodes() : [] : [];
if (selectionNodes.length === 0) {
isEditable = false;
}
if (!range.collapsed || isEditable) {
findNodes($(endNode)).forEach(function (node) {
return addNode(nodes, node);
});
selectionNodes.forEach(function (commonAncestorNode) {
commonAncestorNode.traverse(function (child) {
if (child.isElement() && !child.isCard() && editor.node.isBlock(child)) {
addNode(nodes, child);
}
}, true, 'editable');
});
}
return nodes;
}
/**
* 判断范围的 {Edge}Offset 是否在 Block 的开始位置
* @param range 光标
* @param edge start | end
*/
}, {
key: "isFirstOffset",
value: function isFirstOffset(range, edge) {
var _range2 = range,
startNode = _range2.startNode,
endNode = _range2.endNode,
startOffset = _range2.startOffset,
endOffset = _range2.endOffset;
var container = edge === 'start' ? startNode : endNode;
var offset = edge === 'start' ? startOffset : endOffset;
range = range.cloneRange();
var block = this.closest(container);
range.select(block, true);
range.setEnd(container[0], offset);
var editor = this.editor;
if (!editor.node.isBlock(container)) range.enlargeToElementNode();
var fragment = range.cloneContents();
if (!fragment.firstChild) {
return true;
}
var node = editor.node;
if (fragment.childNodes.length === 1 && $(fragment.firstChild).name === 'br') {
return true;
}
var emptyNode = $('');
emptyNode.append(fragment);
return node.isEmpty(emptyNode);
}
/**
* 判断范围的 {Edge}Offset 是否在 Block 的最后位置
* @param range 光标
* @param edge start | end
*/
}, {
key: "isLastOffset",
value: function isLastOffset(range, edge) {
var _range3 = range,
startNode = _range3.startNode,
endNode = _range3.endNode,
startOffset = _range3.startOffset,
endOffset = _range3.endOffset;
var container = edge === 'start' ? startNode : endNode;
var offset = edge === 'start' ? startOffset : endOffset;
range = range.cloneRange();
var block = this.closest(container);
range.select(block, true);
range.setStart(container, offset);
var node = this.editor.node;
if (!node.isBlock(container)) range.enlargeToElementNode();
var fragment = range.cloneContents();
if (!fragment.firstChild) {
return true;
}
var emptyNode = $('');
emptyNode.append(fragment);
return 0 >= emptyNode.find('br').length && node.isEmpty(emptyNode);
}
/**
* 获取范围内的所有 Block
* @param range 光标s
*/
}, {
key: "getBlocks",
value: function getBlocks(range) {
range = range.cloneRange();
range.shrinkToElementNode();
range.shrinkToTextNode();
var editor = this.editor;
var node = editor.node;
var startBlock = this.closest(range.startNode);
if (range.startNode.isRoot()) {
startBlock = $(range.getStartOffsetNode());
}
var endBlock = this.closest(range.endNode);
if (range.endNode.isRoot()) {
endBlock = $(range.getEndOffsetNode());
}
var closest = this.closest(range.commonAncestorNode);
var blocks = [];
var started = false;
var _range4 = range,
commonAncestorNode = _range4.commonAncestorNode;
var card = editor.card.find(commonAncestorNode, true);
var isEditable = card === null || card === void 0 ? void 0 : card.isEditable;
var selectionNodes = isEditable ? (card === null || card === void 0 ? void 0 : card.getSelectionNodes) ? card.getSelectionNodes() : [] : [closest];
if (selectionNodes.length === 0) {
isEditable = false;
selectionNodes.push(closest);
}
selectionNodes.forEach(function (selectionNode) {
selectionNode.traverse(function (node) {
var child = $(node);
if (child.equal(startBlock)) {
started = true;
}
if ((started || isEditable) && editor.node.isBlock(child) && !child.isCard() && child.inEditor()) {
blocks.push(child);
}
if (child.equal(endBlock)) {
started = false;
return false;
}
return;
}, true, 'editable');
}); // 未选中文本时忽略该 Block
// 示例:word
another
if (blocks.length > 1 && this.isFirstOffset(range, 'end') && !node.isEmpty(endBlock)) {
blocks.pop();
}
return blocks;
}
/**
* 获取block节点到光标所在位置的blcok节点
* @param options { block, range, isLeft, clone, keepDataId }
* @returns
*/
}, {
key: "getBlockByRange",
value: function getBlockByRange(_ref) {
var block = _ref.block,
range = _ref.range,
isLeft = _ref.isLeft,
_ref$clone = _ref.clone,
clone = _ref$clone === void 0 ? false : _ref$clone,
_ref$keepDataId = _ref.keepDataId,
keepDataId = _ref$keepDataId === void 0 ? false : _ref$keepDataId;
if (isNode(block)) block = $(block);
var editor = this.editor;
var newRange = Range.create(editor, block.document);
if (isLeft) {
newRange.select(block, true);
newRange.setEnd(range.startContainer, range.startOffset);
} else {
newRange.select(block, true);
newRange.setStart(range.endContainer, range.endOffset);
}
var fragement = clone ? newRange.cloneContents() : newRange.extractContents();
var cloneBlock = keepDataId ? block.clone(false) : editor.node.clone(block, false, false);
cloneBlock.append(fragement);
if (clone) {
cloneBlock.find(CARD_SELECTOR).each(function (card) {
var domCard = $(card);
var cardName = domCard.attributes(CARD_KEY);
domCard.attributes(READY_CARD_KEY, cardName);
domCard.removeAttributes(CARD_KEY);
});
}
return cloneBlock;
}
/**
* 获取 Block 左侧文本
* @param block 节点
*/
}, {
key: "getLeftText",
value: function getLeftText(block, range) {
var editor = this.editor;
if (!isEngine(editor)) return '';
range = range || editor.change.range.get();
var leftBlock = this.getBlockByRange({
block: block,
range: range,
isLeft: true,
clone: true
});
return leftBlock.text().replace(/\u200B/g, '');
}
/**
* 删除 Block 左侧文本
* @param block 节点
*/
}, {
key: "removeLeftText",
value: function removeLeftText(block, range) {
var editor = this.editor;
if (!isEngine(editor)) return;
range = range || editor.change.range.get();
if (isNode(block)) block = $(block);
range.createSelection();
var cursor = block.find(CURSOR_SELECTOR);
var isRemove = false; // 删除左侧文本节点
block.traverse(function (node) {
var child = $(node);
if (child.equal(cursor)) {
cursor.remove();
isRemove = true;
return;
}
if (isRemove && child.isText()) {
child.remove();
}
}, false);
}
/**
* 扁平化block节点,防止错误嵌套
* @param block 节点
* @param root 根节点
*/
}, {
key: "flat",
value: function flat(block, root) {
var editor = this.editor;
if (!isEngine(editor)) return;
var schema = editor.schema,
node = editor.node;
var mergeTags = schema.getCanMergeTags(); //获取父级节点
var parentNode = block.parent();
var rootElement = root.fragment ? root[0].parentNode : root.get(); //在根节点内循环
while (parentNode && rootElement && parentNode.get() !== rootElement && parentNode.inEditor()) {
//如果是卡片节点,就在父节点前面插入
if (block.isCard()) parentNode.before(block);else if ( //如果是li标签,并且父级是 ol、ul 列表标签
node.isList(parentNode) && 'li' === block.name || //如果是父级可合并标签,并且当前节点是根block节点,并且不是 父节点一样的block节点
mergeTags.indexOf(parentNode.name) > -1 && node.isBlock(block) && parentNode.name !== block.name) {
//复制节点
var cloneNode = node.clone(parentNode, false, false); //追加到复制的节点
cloneNode.append(block); //设置新的节点
block = cloneNode; //将新的节点插入到父节点之前
parentNode.before(block);
} else {
block = node.replace(block, node.clone(this.findTop(parentNode, block), false, false));
parentNode.before(block);
} //如果没有子节点就移除
if (!parentNode.first()) parentNode.remove(); //设置新的父节点
parentNode = block.parent();
}
}
/**
* 插入一个空的block节点
* @param range 光标所在位置
* @param block 节点
* @returns
*/
}, {
key: "insertEmptyBlock",
value: function insertEmptyBlock(range, block) {
var editor = this.editor;
if (!isEngine(editor)) return;
var change = editor.change;
var blocks = change.blocks,
marks = change.marks;
var nodeApi = editor.node;
this.insert(block);
if (blocks[0]) {
var styles = blocks[0].css();
block.css(styles);
}
var node = block.find('br');
marks.forEach(function (mark) {
// 回车后,默认是否复制makr样式
var plugin = editor.mark.findPlugin(mark);
mark = nodeApi.clone(mark, false, false); //插件判断
if ((plugin === null || plugin === void 0 ? void 0 : plugin.copyOnEnter) !== false && (plugin === null || plugin === void 0 ? void 0 : plugin.followStyle) !== false) {
mark = nodeApi.clone(mark, false, false);
node.before(mark);
mark.append(node);
node = mark;
}
});
node = block.find('br');
var parent = node.parent();
if (parent && nodeApi.isMark(parent)) {
node = nodeApi.replace(node, $("\u200B", null));
}
range.select(node).shrinkToTextNode();
range.collapse(false);
range.scrollIntoView();
change.range.select(range);
}
/**
* 在光标位置插入或分割节点
* @param range 光标所在位置
* @param block 节点
*/
}, {
key: "insertOrSplit",
value: function insertOrSplit(range, block) {
var _block$get, _block$last, _block$first;
var cloneRange = range.cloneRange();
cloneRange.enlargeFromTextNode();
if (this.isLastOffset(range, 'end') || cloneRange.endNode.type === Node.ELEMENT_NODE && (((_block$get = block.get()) === null || _block$get === void 0 ? void 0 : _block$get.childNodes.length) || 0) > 0 && cloneRange.endContainer.childNodes[cloneRange.endOffset] === ((_block$last = block.last()) === null || _block$last === void 0 ? void 0 : _block$last.get()) && 'br' === ((_block$first = block.first()) === null || _block$first === void 0 ? void 0 : _block$first.name)) {
var emptyElement = $("
");
if (block.name === 'p') {
var attributes = block.attributes();
Object.keys(attributes).forEach(function (attributeName) {
if (attributeName === DATA_ID) return;
emptyElement.attributes(attributeName, attributes[attributeName]);
});
}
this.insertEmptyBlock(range, emptyElement);
} else {
this.split();
}
}
}]);
return Block;
}();
var _scrollNode = /*#__PURE__*/_classPrivateFieldLooseKey("_scrollNode");
var Editor = /*#__PURE__*/function () {
function Editor(selector, options) {
var _this = this;
_classCallCheck(this, Editor);
this.kind = 'editor';
this.options = {
lang: 'zh-CN',
locale: {},
plugins: [],
cards: [],
config: {},
iconFonts: "url('//at.alicdn.com/t/font_1456030_lnqmc6a6ca.woff2?t=1638071536645') format('woff2'), url('//at.alicdn.com/t/font_1456030_lnqmc6a6ca.woff?t=1638071536645') format('woff'), url('//at.alicdn.com/t/font_1456030_lnqmc6a6ca.ttf?t=1638071536645') format('truetype')"
};
this.container = void 0;
this.language = void 0;
this.root = void 0;
this.card = void 0;
this.plugin = void 0;
this.node = void 0;
this.nodeId = void 0;
this.list = void 0;
this.mark = void 0;
this.inline = void 0;
this.block = void 0;
this.event = void 0;
this.schema = void 0;
this.conversion = void 0;
this.command = void 0;
this.clipboard = void 0;
this.request = void 0;
Object.defineProperty(this, _scrollNode, {
writable: true,
value: null
});
this.options = _objectSpread2(_objectSpread2({}, this.options), options);
var iconFonts = this.options.iconFonts;
var fontElement = document.querySelector('#am-iconfont');
if (!fontElement && iconFonts !== false) {
fontElement = document.createElement('style');
fontElement.setAttribute('type', 'text/css');
fontElement.setAttribute('id', 'am-iconfont');
var fontsStyle = '@font-face { font-family: "data-icon";';
if (Array.isArray(iconFonts)) {
iconFonts = iconFonts.map(function (font) {
return "url('".concat(font.url, "') format('").concat(font.format, "')");
}).join(',');
}
fontsStyle += "src: ".concat(iconFonts, ";}");
fontElement.innerHTML = fontsStyle;
document.head.appendChild(fontElement);
}
this.container = $(selector);
this.container.attributes(DATA_ELEMENT, ROOT); // 多语言
this.language = new Language(this.options.lang || 'zh-CN', merge__default['default'](language, options === null || options === void 0 ? void 0 : options.locale)); // 事件管理
this.event = new Event$1(); // 命令
this.command = new Command(this); // 节点规则
this.schema = new Schema();
this.schema.add(defualtSchema); // 节点转换规则
this.conversion = new Conversion(this);
defaultConversion.forEach(function (rule) {
return _this.conversion.add(rule.from, rule.to);
}); // 卡片
this.card = new CardModel(this, this.options.lazyRender); // 剪贴板
this.clipboard = new Clipboard(this); // http请求
this.request = new Request(); // 插件
this.plugin = new PluginModel(this); // 节点管理
this.node = new NodeModel(this);
this.nodeId = new NodeId(this.schema); // 列表
this.list = new List(this); // 样式标记
this.mark = new Mark(this); // 行内样式
this.inline = new Inline(this); // 块级节点
this.block = new Block(this); // 编辑器父节点
this.root = $(this.options.root || this.container.parent() || document.body);
var rootPosition = this.root.css('position');
if (!rootPosition || rootPosition === 'static') this.root.css('position', 'relative');
}
_createClass(Editor, [{
key: "scrollNode",
get: function get() {
if (_classPrivateFieldLooseBase(this, _scrollNode)[_scrollNode]) return _classPrivateFieldLooseBase(this, _scrollNode)[_scrollNode];
var scrollNode = this.options.scrollNode;
var sn = scrollNode ? typeof scrollNode === 'function' ? scrollNode() : scrollNode : null; // 查找父级样式 overflow 或者 overflow-y 为 auto 或者 scroll 的节点
var targetValues = ['auto', 'scroll'];
var parent = this.container.parent();
while (!sn && parent && parent.length > 0 && parent.name !== 'body') {
if (targetValues.includes(parent.css('overflow')) || targetValues.includes(parent.css('overflow-y'))) {
sn = parent.get();
break;
} else {
parent = parent.parent();
}
}
if (sn === null) sn = document.documentElement;
_classPrivateFieldLooseBase(this, _scrollNode)[_scrollNode] = sn ? $(sn) : null;
return _classPrivateFieldLooseBase(this, _scrollNode)[_scrollNode];
}
}, {
key: "init",
value: function init() {
// 实例化插件
this.mark.init();
this.inline.init();
this.block.init();
this.list.init();
var _this$options = this.options,
plugins = _this$options.plugins,
cards = _this$options.cards,
config = _this$options.config;
this.card.init(cards !== null && cards !== void 0 ? cards : []);
var configData = typeof config === 'function' ? config(this) : config !== null && config !== void 0 ? config : {};
this.plugin.init(plugins !== null && plugins !== void 0 ? plugins : [], configData);
this.nodeId.init();
}
}, {
key: "setScrollNode",
value: function setScrollNode(node) {
_classPrivateFieldLooseBase(this, _scrollNode)[_scrollNode] = node ? $(node) : null;
}
}, {
key: "on",
value: function on(eventType, listener, options) {
this.event.on(eventType, listener, options);
return this;
}
}, {
key: "off",
value: function off(eventType, listener) {
this.event.off(eventType, listener);
return this;
}
}, {
key: "trigger",
value: function trigger(eventType) {
var _this$event;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return (_this$event = this.event).trigger.apply(_this$event, [eventType].concat(args));
}
}, {
key: "messageSuccess",
value: function messageSuccess(type, message) {
var _console;
for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
(_console = console).log.apply(_console, [type, "success:".concat(message)].concat(args));
}
}, {
key: "messageError",
value: function messageError(type, error) {
var _console2;
for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
args[_key3 - 2] = arguments[_key3];
}
(_console2 = console).error.apply(_console2, [type, "error:".concat(error)].concat(args));
}
}, {
key: "messageConfirm",
value: function messageConfirm(type, message) {
var _console3;
for (var _len4 = arguments.length, args = new Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
args[_key4 - 2] = arguments[_key4];
}
(_console3 = console).log.apply(_console3, [type, "confirm:".concat(message)].concat(args));
return Promise.reject(false);
}
}, {
key: "getSelectionData",
value: function getSelectionData(range) {
var _Range$from,
_contents$firstChild,
_this2 = this;
if (!range) range = (_Range$from = Range.from(this)) !== null && _Range$from !== void 0 ? _Range$from : undefined;
if (!range) return;
range = range.cloneRange(); //.shrinkToElementNode();
var card = range.startNode.closest("[".concat(CARD_KEY, "]"), function (node) {
var _node$parentElement;
return $(node).isEditable() ? undefined : ((_node$parentElement = node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : node.parentNode) || undefined;
});
if (card.length > 0 && !range.collapsed && range.endOffset === 0) {
if (range.endContainer.previousSibling) {
range.setEndAfter(range.endContainer.previousSibling);
}
if (!range.collapsed && range.endOffset > 0 && range.endContainer.childNodes[range.endOffset - 1] === card[0]) {
var cardCenter = range.startNode.closest("[".concat(CARD_ELEMENT_KEY, "=\"center\"]"), function (node) {
var _node$parentElement2;
return $(node).isEditable() ? undefined : ((_node$parentElement2 = node.parentElement) !== null && _node$parentElement2 !== void 0 ? _node$parentElement2 : node.parentNode) || undefined;
});
if (cardCenter.length > 0) {
range.setEnd(cardCenter[0], cardCenter[0].childNodes.length);
} else {
range.setEnd(card[0], card[0].childNodes.length);
}
}
}
var root = range.commonAncestorNode;
card = root.closest("[".concat(CARD_KEY, "]"), function (node) {
var _node$parentElement3;
return $(node).isEditable() ? undefined : ((_node$parentElement3 = node.parentElement) !== null && _node$parentElement3 !== void 0 ? _node$parentElement3 : node.parentNode) || undefined;
});
if (card.length > 0) {
var _cardCenter = root.closest("[".concat(CARD_ELEMENT_KEY, "=\"center\"]"), function (node) {
var _node$parentElement4;
return $(node).isEditable() ? undefined : ((_node$parentElement4 = node.parentElement) !== null && _node$parentElement4 !== void 0 ? _node$parentElement4 : node.parentNode) || undefined;
});
if (_cardCenter.length === 0) {
range.select(card);
root = range.commonAncestorNode;
}
}
if (!root.inEditor() && !root.isRoot()) return;
if (range.collapsed) {
return;
}
var setNodes = function setNodes(nodes) {
if (0 === nodes.length) return {};
for (var i = nodes.length - 1; i > 0; i--) {
var _node = nodes[i];
_node.appendChild(nodes[i - 1]);
}
return {
inner: nodes[0],
outter: nodes[nodes.length - 1]
};
};
card = root.closest("[".concat(CARD_KEY, "]"), function (node) {
var _node$parentElement5;
return ((_node$parentElement5 = node.parentElement) !== null && _node$parentElement5 !== void 0 ? _node$parentElement5 : node.parentNode) || undefined;
});
if (card.length > 0) {
var compnoent = this.card.find(card);
if (compnoent && compnoent.getSelectionNodes) {
var _nodes = compnoent.getSelectionNodes();
if (_nodes.length > 0) {
var _setNodes = setNodes(_nodes.map(function (node) {
return node[0];
})),
_inner = _setNodes.inner,
_outter = _setNodes.outter;
var _html = _nodes.map(function (node) {
return node.html();
}).join('');
var _parser = new Parser("".concat(_html, "
"), this);
_html = _parser.toHTML(_inner, _outter);
var _text = new Parser(_html, this).toText(this.schema, true);
return {
html: _html,
text: _text
};
}
} else if (!(compnoent === null || compnoent === void 0 ? void 0 : compnoent.isEditable)) return;
}
var node = this.node,
list = this.list; // 修复自定义列表选择范围
var customizeStartItem;
var li = range.startNode.closest('li');
if (li && node.isCustomize(li)) {
var endLi = range.endNode.closest('li');
if (!li.equal(endLi) || list.isLast(range) && list.isFirst(range)) {
if (list.isFirst(range)) {
var ul = li.parent();
var index = li.getIndex();
if (ul) range.setStart(ul, index < 0 ? 0 : index);
} else {
var _selection$anchor, _selection$focus;
var _ul = li.parent(); // 选在列表项靠后的节点,把剩余节点拼接成完成的列表项
var selection = range.createSelection();
var rightNode = selection.getNode(li, 'center', true);
(_selection$anchor = selection.anchor) === null || _selection$anchor === void 0 ? void 0 : _selection$anchor.remove();
(_selection$focus = selection.focus) === null || _selection$focus === void 0 ? void 0 : _selection$focus.remove();
if (isEngine(this)) this.change.combinText();
if (rightNode.length > 0) {
var isRemove = false;
rightNode.each(function (_, index) {
var item = rightNode.eq(index);
if (!isRemove && (item === null || item === void 0 ? void 0 : item.name) === 'li') {
isRemove = true;
return;
}
if (isRemove) item === null || item === void 0 ? void 0 : item.remove();
});
var _card = li.first();
var component = _card ? this.card.find(_card) : undefined;
if (component) {
customizeStartItem = rightNode;
this.list.addCardToCustomize(customizeStartItem, component.name, component.getValue());
if (_ul) node.wrap(customizeStartItem, _ul === null || _ul === void 0 ? void 0 : _ul.clone());
}
}
}
}
}
var contents = range.enlargeToElementNode(true).cloneContents(); // 复制纯文本,获取外层的样式包裹层
var nodes = [];
if (root.isText() && contents.childNodes.length === 1 && ((_contents$firstChild = contents.firstChild) === null || _contents$firstChild === void 0 ? void 0 : _contents$firstChild.nodeType) === Node.TEXT_NODE) {
var parent = root.parent();
while (parent && (node.isMark(parent) || node.isInline(parent))) {
nodes.push(parent.clone(false).get());
parent = parent.parent();
}
} // if (customizeStartItem) {
contents.querySelectorAll('li').forEach(function (child) {
var _this2$container$get, _childElement$first;
var childElement = $(child);
var dataId = childElement.attributes(DATA_ID);
if (!dataId) return;
var curentElement = (_this2$container$get = _this2.container.get()) === null || _this2$container$get === void 0 ? void 0 : _this2$container$get.querySelector("[".concat(DATA_ID, "=").concat(dataId, "]")); // 补充自定义列表丢失的卡片
if (node.isCustomize(childElement) && !((_childElement$first = childElement.first()) === null || _childElement$first === void 0 ? void 0 : _childElement$first.isCard()) && (curentElement === null || curentElement === void 0 ? void 0 : curentElement.firstChild)) {
childElement.prepend(node.clone($(curentElement.firstChild), true, false));
}
var parent = curentElement === null || curentElement === void 0 ? void 0 : curentElement.parentElement;
parent = parent ? $(parent.cloneNode(false)) : null;
var childParent = child.parentElement;
if (curentElement && parent && node.isList(parent) && (!childParent || !node.isList(childParent))) {
if (parent.name === 'ol') {
// 设置复制位置的 start 属性,默认不设置
// let start = parseInt(parent.attributes('start') || '0', 10)
// start = $(curentElement).index() + start
// if(start === 0) start = 1
// parent.attributes('start', start);
parent.removeAttributes('start');
}
node.wrap(child, parent);
}
});
var _setNodes2 = setNodes(nodes),
inner = _setNodes2.inner,
outter = _setNodes2.outter;
var listNodes = [];
contents.childNodes.forEach(function (child) {
var childNode = $(child);
if (node.isList(childNode) || childNode.name === 'li') {
listNodes.push(childNode);
}
});
this.nodeId.generateAll($(contents), true); // 合并列表
this.list.merge(listNodes);
var parser = new Parser(contents, this);
var html = parser.toHTML(inner, outter);
var text = new Parser(html, this).toText(this.schema, true);
return {
html: html,
text: text
};
}
}, {
key: "destroy",
value: function destroy() {
this.container.removeAttributes(DATA_ELEMENT);
this.event.destroy();
this.plugin.destroy();
this.card.destroy();
this.container.empty();
}
}]);
return Editor;
}();
var css_248z$6 = " .data-icon {\n font-family: \"data-icon\" !important;\n font-size: 16px;\n font-style: normal;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n }\n\n .data-icon-block-image:before {\n content: \"\\ea20\";\n }\n\n .data-icon-inline-image:before {\n content: \"\\e601\";\n }\n\n .data-icon-no-border:before {\n content: \"\\e608\";\n }\n\n .data-icon-line-height:before {\n content: \"\\e697\";\n }\n\n .data-icon-text:before {\n content: \"\\e600\";\n }\n\n .data-icon-comment:before {\n content: \"\\e73e\";\n }\n\n .data-icon-huanyuan:before {\n content: \"\\e60a\";\n }\n\n .data-icon-label:before {\n content: \"\\e714\";\n }\n\n .data-icon-video:before {\n content: \"\\e741\";\n }\n\n .data-icon-table:before {\n content: \"\\e6a8\";\n }\n\n .data-icon-h:before {\n content: \"\\e7a0\";\n }\n\n .data-icon-collapse-subtree:before {\n content: \"\\e754\";\n }\n\n .data-icon-expand-subtree:before {\n content: \"\\e792\";\n }\n\n .data-icon-sub-node:before {\n content: \"\\e78e\";\n }\n\n .data-icon-sister-node:before {\n content: \"\\e784\";\n }\n\n .data-icon-sup:before {\n content: \"\\e790\";\n }\n\n .data-icon-sub:before {\n content: \"\\e75a\";\n }\n\n .data-icon-maximize:before {\n content: \"\\e752\";\n }\n\n .data-icon-codeblock:before {\n content: \"\\e709\";\n }\n\n .data-icon-emoji:before {\n content: \"\\e73a\";\n }\n\n .data-icon-h4:before {\n content: \"\\e759\";\n }\n\n .data-icon-h1:before {\n content: \"\\e75b\";\n }\n\n .data-icon-h5:before {\n content: \"\\e75c\";\n }\n\n .data-icon-h2:before {\n content: \"\\e75d\";\n }\n\n .data-icon-h3:before {\n content: \"\\e760\";\n }\n\n .data-icon-h6:before {\n content: \"\\e761\";\n }\n\n .data-icon-liuchengtu:before {\n content: \"\\e61c\";\n }\n\n .data-icon-website:before {\n content: \"\\e694\";\n }\n\n .data-icon-preferences:before {\n content: \"\\e788\";\n }\n\n .data-icon-hr:before {\n content: \"\\e76a\";\n }\n\n .data-icon-task-list:before {\n content: \"\\e79f\";\n }\n\n .data-icon-unordered-list:before {\n content: \"\\e777\";\n }\n\n .data-icon-ordered-list:before {\n content: \"\\e795\";\n }\n\n .data-icon-arrow-left:before {\n content: \"\\e748\";\n }\n\n .data-icon-arrow-up:before {\n content: \"\\e769\";\n }\n\n .data-icon-arrow-right:before {\n content: \"\\e779\";\n }\n\n .data-icon-arrow-down:before {\n content: \"\\e79a\";\n }\n\n .data-icon-moremark:before {\n content: \"\\e772\";\n }\n\n .data-icon-clean:before {\n content: \"\\e74d\";\n }\n\n .data-icon-paintformat:before {\n content: \"\\e756\";\n }\n\n .data-icon-lock:before {\n content: \"\\e768\";\n }\n\n .data-icon-loading:before {\n content: \"\\e76b\";\n }\n\n .data-icon-unlock:before {\n content: \"\\e796\";\n }\n\n .data-icon-collapse:before {\n content: \"\\e79e\";\n }\n\n .data-icon-align-bottom:before {\n content: \"\\e72b\";\n }\n\n .data-icon-attachment:before {\n content: \"\\e72c\";\n }\n\n .data-icon-bold:before {\n content: \"\\e72d\";\n }\n\n .data-icon-border-color:before {\n content: \"\\e72e\";\n }\n\n .data-icon-border-all:before {\n content: \"\\e72f\";\n }\n\n .data-icon-border-inner:before {\n content: \"\\e730\";\n }\n\n .data-icon-border-left:before {\n content: \"\\e731\";\n }\n\n .data-icon-border-bottom:before {\n content: \"\\e732\";\n }\n\n .data-icon-border-none:before {\n content: \"\\e733\";\n }\n\n .data-icon-box:before {\n content: \"\\e734\";\n }\n\n .data-icon-border-outer:before {\n content: \"\\e735\";\n }\n\n .data-icon-border-right:before {\n content: \"\\e736\";\n }\n\n .data-icon-clear:before {\n content: \"\\e737\";\n }\n\n .data-icon-close:before {\n content: \"\\e738\";\n }\n\n .data-icon-code-example:before {\n content: \"\\e739\";\n }\n\n .data-icon-clip:before {\n content: \"\\e73b\";\n }\n\n .data-icon-border-up:before {\n content: \"\\e73c\";\n }\n\n .data-icon-code:before {\n content: \"\\e73d\";\n }\n\n .data-icon-command:before {\n content: \"\\e73f\";\n }\n\n .data-icon-compact-display:before {\n content: \"\\e740\";\n }\n\n .data-icon-copy:before {\n content: \"\\e742\";\n }\n\n .data-icon-download:before {\n content: \"\\e743\";\n }\n\n .data-icon-deletecolumn:before {\n content: \"\\e744\";\n }\n\n .data-icon-cut:before {\n content: \"\\e745\";\n }\n\n .data-icon-decreasedecimalplace:before {\n content: \"\\e746\";\n }\n\n .data-icon-drag:before {\n content: \"\\e747\";\n }\n\n .data-icon-delete:before {\n content: \"\\e749\";\n }\n\n .data-icon-drag-circle:before {\n content: \"\\e74a\";\n }\n\n .data-icon-deleterow:before {\n content: \"\\e74b\";\n }\n\n .data-icon-edit:before {\n content: \"\\e74c\";\n }\n\n .data-icon-filter:before {\n content: \"\\e74e\";\n }\n\n .data-icon-expand:before {\n content: \"\\e74f\";\n }\n\n .data-icon-error:before {\n content: \"\\e750\";\n }\n\n .data-icon-freezerowcoloum:before {\n content: \"\\e751\";\n }\n\n .data-icon-freezefirstrow:before {\n content: \"\\e753\";\n }\n\n .data-icon-freezzecolumn:before {\n content: \"\\e755\";\n }\n\n .data-icon-border-style:before {\n content: \"\\e757\";\n }\n\n .data-icon-gotolink:before {\n content: \"\\e758\";\n }\n\n .data-icon-increasedecimalplace:before {\n content: \"\\e75e\";\n }\n\n .data-icon-insertrowbelow:before {\n content: \"\\e75f\";\n }\n\n .data-icon-image:before {\n content: \"\\e762\";\n }\n\n .data-icon-italic:before {\n content: \"\\e763\";\n }\n\n .data-icon-indent:before {\n content: \"\\e764\";\n }\n\n .data-icon-insertrowabove:before {\n content: \"\\e765\";\n }\n\n .data-icon-insertrowright:before {\n content: \"\\e766\";\n }\n\n .data-icon-left-circle-fill:before {\n content: \"\\e767\";\n }\n\n .data-icon-link:before {\n content: \"\\e76c\";\n }\n\n .data-icon-keyboard:before {\n content: \"\\e76d\";\n }\n\n .data-icon-more:before {\n content: \"\\e76e\";\n }\n\n .data-icon-merge-cells:before {\n content: \"\\e76f\";\n }\n\n .data-icon-outdent:before {\n content: \"\\e770\";\n }\n\n .data-icon-mention:before {\n content: \"\\e771\";\n }\n\n .data-icon-plus:before {\n content: \"\\e773\";\n }\n\n .data-icon-minus-circle-o:before {\n content: \"\\e774\";\n }\n\n .data-icon-highlight:before {\n content: \"\\e775\";\n }\n\n .data-icon-paste:before {\n content: \"\\e776\";\n }\n\n .data-icon-insertrowleft:before {\n content: \"\\e778\";\n }\n\n .data-icon-quote:before {\n content: \"\\e77a\";\n }\n\n .data-icon-plus-circle-o:before {\n content: \"\\e77b\";\n }\n\n .data-icon-right-circle-fill:before {\n content: \"\\e77c\";\n }\n\n .data-icon-question-circle-o:before {\n content: \"\\e77d\";\n }\n\n .data-icon-preview:before {\n content: \"\\e77e\";\n }\n\n .data-icon-reload:before {\n content: \"\\e77f\";\n }\n\n .data-icon-rotate-left:before {\n content: \"\\e780\";\n }\n\n .data-icon-math:before {\n content: \"\\e781\";\n }\n\n .data-icon-overflow:before {\n content: \"\\e782\";\n }\n\n .data-icon-redo:before {\n content: \"\\e783\";\n }\n\n .data-icon-searchreplace:before {\n content: \"\\e785\";\n }\n\n .data-icon-save:before {\n content: \"\\e786\";\n }\n\n .data-icon-singleselect:before {\n content: \"\\e787\";\n }\n\n .data-icon-rotate-right:before {\n content: \"\\e789\";\n }\n\n .data-icon-sort-ascending:before {\n content: \"\\e78a\";\n }\n\n .data-icon-sort-descending:before {\n content: \"\\e78b\";\n }\n\n .data-icon-toc:before {\n content: \"\\e78c\";\n }\n\n .data-icon-solit-cells:before {\n content: \"\\e78d\";\n }\n\n .data-icon-translate:before {\n content: \"\\e78f\";\n }\n\n .data-icon-successful:before {\n content: \"\\e791\";\n }\n\n .data-icon-strikethrough:before {\n content: \"\\e793\";\n }\n\n .data-icon-undo:before {\n content: \"\\e794\";\n }\n\n .data-icon-underline:before {\n content: \"\\e797\";\n }\n\n .data-icon-unlink:before {\n content: \"\\e798\";\n }\n\n .data-icon-wrap:before {\n content: \"\\e799\";\n }\n\n .data-icon-upload:before {\n content: \"\\e79b\";\n }\n\n .data-icon-zoom-out:before {\n content: \"\\e79c\";\n }\n\n .data-icon-zoom-in:before {\n content: \"\\e79d\";\n }\n\n .data-icon-align-center:before {\n content: \"\\e725\";\n }\n\n .data-icon-align-justify:before {\n content: \"\\e726\";\n }\n\n .data-icon-align-left:before {\n content: \"\\e727\";\n }\n\n .data-icon-align-top:before {\n content: \"\\e728\";\n }\n\n .data-icon-align-right:before {\n content: \"\\e729\";\n }\n\n .data-icon-align-middle:before {\n content: \"\\e72a\";\n }\n\n.data-anticon {\n display: inline-block;\n font-style: normal;\n vertical-align: -0.125em;\n text-align: center;\n text-transform: none;\n line-height: 0;\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n}\n\n.data-anticon svg {\n display: inline-block;\n}\n\n@-webkit-keyframes loadingCircle {\n 100% {\n transform: rotate(360deg);\n }\n}\n@keyframes loadingCircle {\n 100% {\n transform: rotate(360deg);\n }\n}\n\n.data-anticon .data-anticon-spin {\n display: inline-block;\n -webkit-animation: loadingCircle 1s infinite linear;\n animation: loadingCircle 1s infinite linear;\n}\n\n.data-anticon > * {\n line-height: 1;\n}\n\n.am-engine {\n position: relative;\n background-color: #FFFFFF;\n}\n\n.am-engine.am-engine-placeholder:before {\n content: attr(data-placeholder);\n pointer-events: none;\n position: absolute;\n color: #bbbfc4;\n height: 0;\n}\n\n.am-engine ::-moz-selection {\n background: rgba(180, 213, 254, 0.5) !important;\n color: inherit!important;\n}\n\n.am-engine ::selection {\n background: rgba(180, 213, 254, 0.5) !important;\n color: inherit!important;\n}\n\n.am-engine , .am-engine-view {\n font-family: 'Chinese Quote', 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif, 'Apple Color Emoji';\n\tword-wrap: break-word;\n\toutline-style: none;\n\twhite-space: pre-wrap;\n -webkit-user-select: auto;\n -moz-user-select: auto;\n user-select: auto;\n font-size: 14px;\n line-height: 1.74;\n color: #262626;\n letter-spacing: .05em;\n /* pt / px 换算表:https://websemantics.uk/articles/font-size-conversion/ */\n}\n\n.am-engine > *:first-child,.am-engine-view > *:first-child {\n\tmargin-top: 0 !important;\n}\n\n.am-engine p , .am-engine-view p {\n white-space: normal;\n margin: 0;\n line-height: 1.74;\n}\n\n.am-engine [contenteditable=\"true\"],.am-engine-view [contenteditable=\"true\"] {\n\toutline-style: none;\n}\n\n.am-engine .selection-transparent::-moz-selection,.am-engine-view .selection-transparent::-moz-selection {\n\tbackground: transparent;\n}\n\n.am-engine .selection-transparent::selection,.am-engine-view .selection-transparent::selection {\n\tbackground: transparent;\n}\n/*---------------------------卡片 begin-----------------------*/\n\n.am-engine [data-card-type], .am-engine-view [data-card-type] {\n white-space: normal;\n}\n.am-engine span[data-card-type=\"inline\"],.am-engine-view span[data-card-type=\"inline\"] {\n\tdisplay: inline-block;\n\ttext-indent: 0;\n\tvertical-align: baseline;\n\twhite-space: initial;\n}\n\n.am-engine span[data-card-type=\"inline\"] span[data-card-element],.am-engine-view span[data-card-type=\"inline\"] span[data-card-element] {\n\tdisplay: inline-block;\n}\n\n.am-engine span[data-card-type=\"inline\"] span[data-card-element=\"center\"],.am-engine-view span[data-card-type=\"inline\"] span[data-card-element=\"center\"] {\n\tvertical-align: bottom;\n border-radius: 2px;\n}\n\n.am-engine span[data-card-type=\"inline\"] span[data-card-element=\"left\"],\n.am-engine-view span[data-card-type=\"inline\"] span[data-card-element=\"left\"],\n.am-engine span[data-card-type=\"inline\"] span[data-card-element=\"right\"],.am-engine-view span[data-card-type=\"inline\"] span[data-card-element=\"right\"] {\n\ttext-align: left;\n\t-webkit-user-select: text;\n\t -moz-user-select: text;\n\t user-select: text;\n min-width: 1px;\n background: transparent;\n bottom: 0;\n}\n\n.am-engine span[data-card-type=\"inline\"] span[data-card-element=\"left\"],\n.am-engine-view span[data-card-type=\"inline\"] span[data-card-element=\"left\"] {\n left: -1px;\n}\n\n.am-engine span[data-card-type=\"inline\"] span[data-card-element=\"right\"],.am-engine-view span[data-card-type=\"inline\"] span[data-card-element=\"right\"] {\n right: -1px;\n}\n\n.am-engine span[data-card-type=\"inline\"] span[data-card-element=\"left\"]::-moz-selection,\n.am-engine-view span[data-card-type=\"inline\"] span[data-card-element=\"left\"]::-moz-selection,\n.am-engine span[data-card-type=\"inline\"] span[data-card-element=\"right\"]::-moz-selection,.am-engine-view span[data-card-type=\"inline\"] span[data-card-element=\"right\"]::-moz-selection {\n background: transparent !important;\n}\n\n.am-engine span[data-card-type=\"inline\"] span[data-card-element=\"left\"]::selection,\n.am-engine-view span[data-card-type=\"inline\"] span[data-card-element=\"left\"]::selection,\n.am-engine span[data-card-type=\"inline\"] span[data-card-element=\"right\"]::selection,.am-engine-view span[data-card-type=\"inline\"] span[data-card-element=\"right\"]::selection {\n background: transparent !important;\n}\n\n.am-engine div[data-card-type=\"block\"],.am-engine-view div[data-card-type=\"block\"],.am-engine span[data-card-type=\"inline\"].data-card-block,.am-engine-view span[data-card-type=\"inline\"].data-card-block {\n\tdisplay: block;\n}\n\n.am-engine div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"left\"],.am-engine-view div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"left\"],.am-engine span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"left\"],.am-engine-view span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"left\"],.am-engine div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"right\"],.am-engine-view div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"right\"],.am-engine span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"right\"],.am-engine-view span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"right\"] {\n\tbottom: 0;\n\tposition: absolute;\n\twidth: 2px;\n\toverflow: hidden;\n\toutline: none;\n\ttext-align: left;\n\ttext-indent: 0;\n\t-webkit-box-flex: 0;\n\tflex: 0 0 auto;\n\t-webkit-user-select: text;\n\t-moz-user-select: text;\n\t user-select: text;\n}\n\n.am-engine div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"left\"],.am-engine-view div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"left\"],.am-engine span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"left\"],.am-engine-view span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"left\"] {\n\tleft: -2px;\n\ttext-align: left;\n}\n\n.am-engine div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"right\"],.am-engine-view div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"right\"],.am-engine span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"right\"],.am-engine-view span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"right\"] {\n\tright: -2px;\n\ttext-align: right;\n}\n\n.am-engine div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"left\"]::-moz-selection,\n.am-engine-view div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"left\"]::-moz-selection,\n.am-engine span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"left\"]::-moz-selection,\n.am-engine-view span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"left\"]::-moz-selection {\n background: transparent !important;\n}\n\n.am-engine div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"left\"]::selection,\n.am-engine-view div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"left\"]::selection,\n.am-engine span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"left\"]::selection,\n.am-engine-view span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"left\"]::selection {\n background: transparent !important;\n}\n\n.am-engine div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"right\"]::-moz-selection,\n.am-engine-view div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"right\"]::-moz-selection,\n.am-engine span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"right\"]::-moz-selection,\n.am-engine-view span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"right\"]::-moz-selection {\n\tbackground: transparent !important;\n}\n\n.am-engine div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"right\"]::selection,\n.am-engine-view div[data-card-type=\"block\"] > div[data-card-element=\"body\"] > span[data-card-element=\"right\"]::selection,\n.am-engine span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"right\"]::selection,\n.am-engine-view span[data-card-type=\"inline\"].data-card-block > div[data-card-element=\"body\"] > span[data-card-element=\"right\"]::selection {\n\tbackground: transparent !important;\n}\n\n.am-engine span[data-card-element=\"body\"],.am-engine-view span[data-card-element=\"body\"],.am-engine div[data-card-element=\"body\"],.am-engine-view div[data-card-element=\"body\"] {\n\tposition: relative;\n}\n\n.am-engine span[data-card-element=\"body\"] [data-card-element=\"center\"],.am-engine-view span[data-card-element=\"body\"] [data-card-element=\"center\"],.am-engine div[data-card-element=\"body\"] [data-card-element=\"center\"],.am-engine-view div[data-card-element=\"body\"] [data-card-element=\"center\"] {\n\t-webkit-user-select: text;\n\t-moz-user-select: text;\n\t user-select: text;\n}\n.am-engine span[data-card-element=\"body\"] [data-element=\"editable\"],.am-engine div[data-card-element=\"body\"] [data-element=\"editable\"]\n{\n cursor: text;\n}\n/*---------------------------卡片 end-----------------------*/\n";
styleInject(css_248z$6);
var Engine = /*#__PURE__*/function (_Editor) {
_inherits(Engine, _Editor);
var _super = _createSuper(Engine);
function Engine(selector, options) {
var _this;
_classCallCheck(this, Engine);
_this = _super.call(this, selector, options);
_this._readonly = false;
_this._container = void 0;
_this.kind = 'engine';
_this.typing = void 0;
_this.model = void 0;
_this.change = void 0;
_this.history = void 0;
_this.hotkey = void 0;
_this.options = _objectSpread2(_objectSpread2({}, _this.options), options); // 历史
_this.history = new HistoryModel(_assertThisInitialized(_this)); // 编辑器容器
_this._container = new Container(_this.container, {
engine: _assertThisInitialized(_this),
lang: _this.options.lang,
className: _this.options.className,
tabIndex: _this.options.tabIndex,
placeholder: _this.options.placeholder,
autoPrepend: _this.options.autoPrepend,
autoAppend: _this.options.autoAppend
}); // 编辑器父节点
_this.root = $(_this.options.root || _this.container.parent() || getDocument().body);
var rootPosition = _this.root.css('position');
if (!rootPosition || rootPosition === 'static') _this.root.css('position', 'relative'); // 实例化容器
_this._container.init(); // 编辑器改变时
_this.change = new ChangeModel(_assertThisInitialized(_this), {
onChange: function onChange(trigger) {
return _this.trigger('change', trigger);
},
onSelect: function onSelect() {
return _this.trigger('select');
},
onSelectStart: function onSelectStart() {
return _this.trigger('selectStart');
},
onSelectEnd: function onSelectEnd() {
return _this.trigger('selectEnd');
},
onRealtimeChange: function onRealtimeChange(trigger) {
_this.trigger('realtimeChange', trigger);
},
onSetValue: function onSetValue() {
return _this.trigger('afterSetValue');
}
});
_this.change.init(); // 事件处理
_this.typing = new Typing(_assertThisInitialized(_this)); // 只读
_this._readonly = _this.options.readonly === undefined ? false : _this.options.readonly;
_this._container.setReadonly(_this._readonly); // 快捷键
_this.hotkey = new Hotkey(_assertThisInitialized(_this));
_this.init();
if (_this.isEmpty()) {
_this._container.showPlaceholder();
}
_this.model = Model.from(_assertThisInitialized(_this));
_this.model.resetRoot();
return _this;
}
_createClass(Engine, [{
key: "readonly",
get: function get() {
return this._readonly;
},
set: function set(readonly) {
if (this.readonly === readonly) return;
if (readonly) {
this.hotkey.disable();
this._container.setReadonly(true);
this.model.mutation.stop();
} else {
this.hotkey.enable();
this._container.setReadonly(false);
this.model.mutation.start();
}
this._readonly = readonly;
this.card.reRender(); //广播readonly事件
this.trigger('readonly', readonly);
}
}, {
key: "isFocus",
value: function isFocus() {
return this._container.isFocus();
}
}, {
key: "isEmpty",
value: function isEmpty() {
return this.change.isEmpty();
}
}, {
key: "focus",
value: function focus(toStart) {
this.change.range.focus(toStart);
}
}, {
key: "blur",
value: function blur() {
this.change.range.blur();
}
/**
* @deprecated 请使用 model.toValue 性能更好
*/
}, {
key: "getValue",
value: function getValue() {
var ignoreCursor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var value = this.change.getValue({
ignoreCursor: ignoreCursor
});
return ignoreCursor ? Selection.removeTags(value) : value;
}
/**
* @deprecated 请使用 model.toValueAsync 性能更好
* @param ignoreCursor
* @param callback
* @returns
*/
}, {
key: "getValueAsync",
value: function () {
var _getValueAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var _this2 = this;
var ignoreCursor,
callback,
_args3 = arguments;
return _regeneratorRuntime().wrap(function _callee2$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
ignoreCursor = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : false;
callback = _args3.length > 1 ? _args3[1] : undefined;
return _context3.abrupt("return", new Promise( /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(resolve, reject) {
var _loop, pluginName, _ret;
return _regeneratorRuntime().wrap(function _callee$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop(pluginName) {
var plugin, result;
return _regeneratorRuntime().wrap(function _loop$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
plugin = _this2.plugin.components[pluginName];
_context.next = 3;
return new Promise(function (resolve) {
if (plugin.waiting) {
plugin.waiting(callback).then(function () {
return resolve(true);
}).catch(resolve);
} else resolve(true);
});
case 3:
result = _context.sent;
if (!(_typeof(result) === 'object')) {
_context.next = 7;
break;
}
reject(result);
return _context.abrupt("return", {
v: void 0
});
case 7:
case "end":
return _context.stop();
}
}
}, _loop);
});
_context2.t0 = _regeneratorRuntime().keys(_this2.plugin.components);
case 2:
if ((_context2.t1 = _context2.t0()).done) {
_context2.next = 10;
break;
}
pluginName = _context2.t1.value;
return _context2.delegateYield(_loop(pluginName), "t2", 5);
case 5:
_ret = _context2.t2;
if (!(_typeof(_ret) === "object")) {
_context2.next = 8;
break;
}
return _context2.abrupt("return", _ret.v);
case 8:
_context2.next = 2;
break;
case 10:
resolve(_this2.getValue(ignoreCursor));
case 11:
case "end":
return _context2.stop();
}
}
}, _callee);
}));
return function (_x, _x2) {
return _ref.apply(this, arguments);
};
}()));
case 3:
case "end":
return _context3.stop();
}
}
}, _callee2);
}));
function getValueAsync() {
return _getValueAsync.apply(this, arguments);
}
return getValueAsync;
}()
/**
* @deprecated 请使用 model.toHTML 性能更好
*/
}, {
key: "getHtml",
value: function getHtml() {
var node = $(this.container[0].cloneNode(true));
node.removeAttributes(DATA_CONTENTEDITABLE_KEY);
node.removeAttributes('tabindex');
node.removeAttributes('autocorrect');
node.removeAttributes('autocomplete');
node.removeAttributes('spellcheck');
node.removeAttributes('data-gramm');
node.removeAttributes(DATA_PLACEHOLDER);
node.removeClass(DATA_PLACEHOLDER_CLASS);
node.removeAttributes('role');
return new Parser(node, this).toHTML();
}
}, {
key: "initDocOnReadonly",
value: function initDocOnReadonly() {
if (this.readonly) {
this.model.resetRoot();
}
}
}, {
key: "setValue",
value: function setValue(value, callback) {
value = this.trigger('beforeSetValue', value) || value;
this.change.setValue(value, undefined, callback);
this.normalize();
this.nodeId.generateAll(this.container);
this.initDocOnReadonly();
return this;
}
}, {
key: "setHtml",
value: function setHtml(html, callback) {
var _this3 = this;
this.change.setHtml(html, function (count) {
_this3.normalize();
_this3.container.allChildren('editable').forEach(function (child) {
if (_this3.node.isInline(child)) {
_this3.inline.repairCursor(child);
} else if (_this3.node.isMark(child)) {
_this3.mark.repairCursor(child);
}
});
if (callback) callback(count);
});
this.nodeId.generateAll(this.container);
this.initDocOnReadonly();
return this;
}
}, {
key: "setMarkdown",
value: function setMarkdown(text, callback) {
var _this4 = this;
this.change.setMarkdown(text, function (count) {
_this4.normalize();
_this4.container.allChildren('editable').forEach(function (child) {
if (_this4.node.isInline(child)) {
_this4.inline.repairCursor(child);
} else if (_this4.node.isMark(child)) {
_this4.mark.repairCursor(child);
}
});
if (callback) callback(count);
});
this.nodeId.generateAll(this.container);
this.initDocOnReadonly();
return this;
}
}, {
key: "setJsonValue",
value: function setJsonValue(value, callback) {
var modelValue = this.model.toValue(value);
this.change.setValue(modelValue, undefined, callback);
this.normalize();
this.nodeId.generateAll(this.container);
this.initDocOnReadonly();
return this;
}
}, {
key: "getJsonValue",
value: function getJsonValue() {
return cloneDeep__default['default'](this.model.root);
}
/**
* @deprecated 请使用 model.toText 性能更好
*/
}, {
key: "getText",
value: function getText(includeCard) {
return new Parser(this.container, this).toText(this.schema, includeCard);
}
}, {
key: "normalize",
value: function normalize() {
var _this5 = this;
var container = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.container;
var block = $(''); // 保证所有行内元素都在段落内
var childNodes = container.children();
childNodes.each(function (_, index) {
var node = childNodes.eq(index);
if (!node) return;
if (_this5.node.isBlock(node)) {
if (block.get().childNodes.length > 0) {
node.before(block);
}
block = $('');
} else if (!node.isCursor()) {
block.append(node);
}
});
if (block.get().childNodes.length > 0) {
container.append(block);
} // 处理空段落
childNodes = container.children();
childNodes.each(function (_, index) {
var node = childNodes.eq(index);
if (!node) return;
_this5.node.removeMinusStyle(node, 'text-indent');
if (_this5.node.isRootBlock(node)) {
var childrenLength = node.get().childNodes.length;
if (childrenLength === 0) {
node.append($('
'));
} else {
var child = node.first();
if (childrenLength === 1 && (child === null || child === void 0 ? void 0 : child.name) === 'span' && [CURSOR, ANCHOR, FOCUS].indexOf(child.attributes(DATA_ELEMENT)) >= 0) {
node.prepend($('
'));
}
}
}
});
}
}, {
key: "showPlaceholder",
value: function showPlaceholder() {
this._container.showPlaceholder();
}
}, {
key: "hidePlaceholder",
value: function hidePlaceholder() {
this._container.hidePlaceholder();
}
}, {
key: "destroy",
value: function destroy() {
this._container.destroy();
this.change.destroy();
this.hotkey.destroy();
this.typing.destroy();
this.model.destroy();
this.history.reset();
_get(_getPrototypeOf(Engine.prototype), "destroy", this).call(this);
}
}]);
return Engine;
}(Editor);
var css_248z$7 = ".card-maximize-header {\r\n position: fixed !important;\r\n top: 0;\r\n right: 0;\r\n left: 0;\r\n z-index: 9999;\r\n height: 56px;\r\n background: #fff;\r\n border-bottom: 1px solid #e8e8e8;\r\n width: 100%;\r\n}\r\n\r\n.card-maximize-header .header-crumb {\r\n float: left;\r\n line-height: 32px;\r\n display: flex;\r\n height: 100%;\r\n align-items: center;\r\n -webkit-box-align: center;\r\n -ms-flex-align: center;\r\n}\r\n\r\n.card-maximize-header .header-crumb a\r\n{\r\n color: #595959 !important;\r\n font-size: 14px;\r\n cursor: pointer;\r\n}\r\n\r\n.card-maximize-header .header-crumb .split {\r\n display: inline-block;\r\n vertical-align: middle;\r\n padding: 0 15px;\r\n font-size: 20px;\r\n padding-right: 8px;\r\n font-weight: 200;\r\n margin: 0 8px;\r\n}\r\n\r\n.card-maximize-header .header-crumb .split + a {\r\n display: inline-block;\r\n vertical-align: middle;\r\n}\r\n\r\n.card-maximize-header .header-crumb .split + a:hover {\r\n\tcolor: #8C8C8C;\r\n}\r\n\r\n.data-card-block-max > [data-card-element=\"body\"] > [data-card-element=\"center\"], .data-card-block-max > [data-card-element=\"body\"] > [data-card-element=\"center\"].data-card-background-selected {\r\n top: 96px;\r\n background: #fafafa !important;\r\n position: fixed!important;\r\n right: 0;\r\n bottom: 0;\r\n left: 0;\r\n z-index: 124;\r\n overflow: auto;\r\n padding: 20px;\r\n}\r\n\r\n.am-engine-mobile .data-card-block-max > [data-card-element=\"body\"] > [data-card-element=\"center\"],.am-engine-view .data-card-block-max > [data-card-element=\"body\"] > [data-card-element=\"center\"] {\r\n top:56px;\r\n}";
styleInject(css_248z$7);
var Maximize = /*#__PURE__*/function () {
function Maximize(editor, card) {
_classCallCheck(this, Maximize);
this.card = void 0;
this.node = void 0;
this.editor = void 0;
this.editor = editor;
this.card = card;
}
_createClass(Maximize, [{
key: "restore",
value: function restore() {
this.card.root.removeClass('data-card-block-max');
if (this.node) {
this.node.remove();
this.node = undefined;
}
var editor = this.editor;
if (isEngine(editor)) {
editor.trigger('card:minimize', this.card);
editor.history.reset();
}
}
}, {
key: "maximize",
value: function maximize() {
var _this = this;
if (this.node) return;
var editor = this.editor;
var language = editor.language;
var lang = language.get('maximize', 'back').toString();
var node = $(""));
node.on('click', function (event) {
event.stopPropagation();
});
this.card.root.addClass('data-card-block-max');
var crumnNode = node.find('.header-crumb');
crumnNode.on('click', function () {
_this.card.minimize();
});
var body = this.card.findByKey('body');
body === null || body === void 0 ? void 0 : body.prepend(node);
if (isEngine(editor)) {
editor.trigger('card:maximize', this.card);
editor.history.reset();
}
this.node = node;
}
}]);
return Maximize;
}();
var css_248z$8 = ".data-card-resize {\n position: absolute;\n bottom: -3px;\n right: 0px;\n left: 0px;\n margin: 0 auto;\n z-index: 2;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.data-card-resize-btn{\n background: #d9dbdd;\n border-radius: 3px;\n height: 6px;\n padding: 0 50px;\n display: block;\n}\n\n.data-card-resize-btn svg {\n display: block;\n color: #999;\n}\n\n.data-card-resize-btn:hover {\n cursor: row-resize;\n}";
styleInject(css_248z$8);
var Resize = /*#__PURE__*/function () {
function Resize(editor, card) {
var _this = this;
_classCallCheck(this, Resize);
this.editor = void 0;
this.card = void 0;
this.point = void 0;
this.options = {};
this.component = void 0;
this.start = false;
this.touchStart = function (event) {
event.preventDefault();
event.cancelBubble = true;
_this.point = {
x: event.targetTouches[0].clientX,
y: event.targetTouches[0].clientY
};
var dragStart = _this.options.dragStart;
if (dragStart) dragStart(_this.point);
};
this.dragStart = function (event) {
event.preventDefault();
event.stopPropagation();
event.cancelBubble = true;
_this.point = {
x: event.clientX,
y: event.clientY
};
var dragStart = _this.options.dragStart;
if (dragStart) dragStart(_this.point);
};
this.dragMove = function (event) {
if (_this.point) {
var dragMove = _this.options.dragMove;
if (dragMove) dragMove(event.clientY - _this.point.y);
}
};
this.touchMove = function (event) {
event.preventDefault();
if (_this.point) {
var dragMove = _this.options.dragMove;
if (dragMove) dragMove(event.targetTouches[0].clientY - _this.point.y);
}
};
this.dragEnd = function (event) {
_this.point = undefined;
var dragEnd = _this.options.dragEnd;
if (dragEnd) dragEnd();
};
this.editor = editor;
this.card = card;
}
_createClass(Resize, [{
key: "create",
value: function create(options) {
this.options = options;
var component = $(""));
if (isMobile) {
component.on('touchstart', this.touchStart);
component.on('touchmove', this.touchMove);
component.on('touchend', this.dragEnd);
component.on('touchcancel', this.dragEnd);
} else {
component.on('dragstart', this.dragStart);
document.addEventListener('mousemove', this.dragMove);
document.addEventListener('mouseup', this.dragEnd);
}
component.on('click', function (event) {
event.stopPropagation();
});
this.component = component;
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var container = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.card.root;
var minHeight = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 80;
this.start = false;
var height = 0,
moveHeight = 0;
var card = this.card;
this.create({
dragStart: function dragStart() {
height = container.height();
_this2.start = true;
card.onActivate(false);
},
dragMove: function dragMove(y) {
if (_this2.start) {
moveHeight = height + y;
moveHeight = moveHeight < minHeight ? minHeight : moveHeight;
container.css('height', "".concat(moveHeight, "px"));
}
},
dragEnd: function dragEnd() {
if (_this2.start) {
card.setValue({
height: container.height()
});
_this2.start = false;
card.onActivate(true);
}
}
});
var component = this.component;
if (!component) return;
if (!card.activated) component.hide();
container.append(component);
var value = card.getValue() || {};
if (value.height) {
container.css('height', "".concat(value.height, "px"));
}
}
}, {
key: "show",
value: function show() {
var _this$component;
(_this$component = this.component) === null || _this$component === void 0 ? void 0 : _this$component.show();
}
}, {
key: "hide",
value: function hide() {
var _this$component2;
if (!this.start) (_this$component2 = this.component) === null || _this$component2 === void 0 ? void 0 : _this$component2.hide();
}
}, {
key: "destroy",
value: function destroy() {
var component = this.component;
if (isMobile) {
if (!component) return;
component.off('touchstart', this.touchStart);
component.off('touchmove', this.touchMove);
component.off('touchend', this.dragEnd);
component.off('touchcancel', this.dragEnd);
} else {
component === null || component === void 0 ? void 0 : component.off('dragstart', this.dragStart);
document.removeEventListener('mousemove', this.dragMove);
document.removeEventListener('mouseup', this.dragEnd);
}
component === null || component === void 0 ? void 0 : component.remove();
}
}]);
return Resize;
}();
var _editor = /*#__PURE__*/_classPrivateFieldLooseKey("editor");
var _container = /*#__PURE__*/_classPrivateFieldLooseKey("container");
var _target = /*#__PURE__*/_classPrivateFieldLooseKey("target");
var _align = /*#__PURE__*/_classPrivateFieldLooseKey("align");
var _offset = /*#__PURE__*/_classPrivateFieldLooseKey("offset");
var _root = /*#__PURE__*/_classPrivateFieldLooseKey("root");
var _onUpdate = /*#__PURE__*/_classPrivateFieldLooseKey("onUpdate");
var _updateTimeout = /*#__PURE__*/_classPrivateFieldLooseKey("updateTimeout");
var _observer = /*#__PURE__*/_classPrivateFieldLooseKey("observer");
var Position = /*#__PURE__*/function () {
function Position(editor) {
var _this = this;
_classCallCheck(this, Position);
Object.defineProperty(this, _editor, {
writable: true,
value: void 0
});
Object.defineProperty(this, _container, {
writable: true,
value: void 0
});
Object.defineProperty(this, _target, {
writable: true,
value: void 0
});
Object.defineProperty(this, _align, {
writable: true,
value: 'bottomLeft'
});
Object.defineProperty(this, _offset, {
writable: true,
value: [0, 0]
});
Object.defineProperty(this, _root, {
writable: true,
value: void 0
});
Object.defineProperty(this, _onUpdate, {
writable: true,
value: void 0
});
Object.defineProperty(this, _updateTimeout, {
writable: true,
value: void 0
});
Object.defineProperty(this, _observer, {
writable: true,
value: void 0
});
this.updateListener = function () {
if (_classPrivateFieldLooseBase(_this, _updateTimeout)[_updateTimeout]) clearTimeout(_classPrivateFieldLooseBase(_this, _updateTimeout)[_updateTimeout]);
_classPrivateFieldLooseBase(_this, _updateTimeout)[_updateTimeout] = setTimeout(function () {
_this.update();
}, 50);
};
this.update = function () {
var triggerUpdate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
if (!_classPrivateFieldLooseBase(_this, _container)[_container] || _classPrivateFieldLooseBase(_this, _container)[_container].length === 0 || !_classPrivateFieldLooseBase(_this, _target)[_target] || _classPrivateFieldLooseBase(_this, _target)[_target].length === 0) return;
var rect = domAlign__default['default'](_classPrivateFieldLooseBase(_this, _container)[_container].get(), _classPrivateFieldLooseBase(_this, _target)[_target].get(), _objectSpread2(_objectSpread2({}, placements[_classPrivateFieldLooseBase(_this, _align)[_align]]), {}, {
targetOffset: _classPrivateFieldLooseBase(_this, _offset)[_offset]
}));
if (_classPrivateFieldLooseBase(_this, _onUpdate)[_onUpdate] && triggerUpdate) {
var align = Object.keys(placements).find(function (p) {
var points = placements[p].points;
return points[0] === rect.points[0] && points[1] === rect.points[1];
});
_classPrivateFieldLooseBase(_this, _container)[_container].attributes('data-placement', align);
_classPrivateFieldLooseBase(_this, _onUpdate)[_onUpdate](_objectSpread2(_objectSpread2({}, rect), {}, {
align: align
}));
}
};
_classPrivateFieldLooseBase(this, _editor)[_editor] = editor;
}
_createClass(Position, [{
key: "bind",
value: function bind(container, target) {
var _this2 = this;
var defaultAlign = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _classPrivateFieldLooseBase(this, _align)[_align];
var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _classPrivateFieldLooseBase(this, _offset)[_offset];
var onUpdate = arguments.length > 4 ? arguments[4] : undefined;
_classPrivateFieldLooseBase(this, _container)[_container] = container;
_classPrivateFieldLooseBase(this, _target)[_target] = target;
_classPrivateFieldLooseBase(this, _align)[_align] = defaultAlign;
_classPrivateFieldLooseBase(this, _offset)[_offset] = offset;
_classPrivateFieldLooseBase(this, _root)[_root] = $("");
_classPrivateFieldLooseBase(this, _root)[_root].append(_classPrivateFieldLooseBase(this, _container)[_container]);
_classPrivateFieldLooseBase(this, _editor)[_editor].root.append(_classPrivateFieldLooseBase(this, _root)[_root]);
_classPrivateFieldLooseBase(this, _onUpdate)[_onUpdate] = onUpdate;
if (!isMobile) window.addEventListener('scroll', this.updateListener, {
passive: true
});
window.addEventListener('resize', this.updateListener);
if (isEngine(_classPrivateFieldLooseBase(this, _editor)[_editor]) && !isMobile) {
var _classPrivateFieldLoo;
(_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _editor)[_editor].scrollNode) === null || _classPrivateFieldLoo === void 0 ? void 0 : _classPrivateFieldLoo.on('scroll', this.updateListener, {
passive: true
});
}
if (target && target.length > 0) {
var size = {
width: target.width(),
height: target.height()
};
if (typeof ResizeObserver !== 'undefined') {
_classPrivateFieldLooseBase(this, _observer)[_observer] = new ResizeObserver(function () {
var width = target.width();
var height = target.height();
if (width === size.width && height === size.height) return;
size = {
width: width,
height: height
};
_this2.updateListener();
});
_classPrivateFieldLooseBase(this, _observer)[_observer].observe(target.get());
}
}
this.update();
}
}, {
key: "setOffset",
value: function setOffset(offset) {
_classPrivateFieldLooseBase(this, _offset)[_offset] = offset;
}
}, {
key: "destroy",
value: function destroy() {
var _classPrivateFieldLoo3, _classPrivateFieldLoo4;
_classPrivateFieldLooseBase(this, _onUpdate)[_onUpdate] = undefined;
if (!isMobile) window.removeEventListener('scroll', this.updateListener);
window.removeEventListener('resize', this.updateListener);
if (isEngine(_classPrivateFieldLooseBase(this, _editor)[_editor]) && !isMobile) {
var _classPrivateFieldLoo2;
(_classPrivateFieldLoo2 = _classPrivateFieldLooseBase(this, _editor)[_editor].scrollNode) === null || _classPrivateFieldLoo2 === void 0 ? void 0 : _classPrivateFieldLoo2.off('scroll', this.updateListener);
}
(_classPrivateFieldLoo3 = _classPrivateFieldLooseBase(this, _observer)[_observer]) === null || _classPrivateFieldLoo3 === void 0 ? void 0 : _classPrivateFieldLoo3.disconnect();
(_classPrivateFieldLoo4 = _classPrivateFieldLooseBase(this, _root)[_root]) === null || _classPrivateFieldLoo4 === void 0 ? void 0 : _classPrivateFieldLoo4.remove();
}
}]);
return Position;
}();
var css_248z$9 = ".data-card-dnd {\n position: absolute;\n top: 0;\n left: -21px;\n right: auto;\n bottom: auto;\n width: 18px;\n height: 24px;\n line-height: 24px;\n font-size: 14px;\n font-weight: normal;\n display: none;\n opacity: 0;\n z-index: 125;\n transition: all 0.3s ease-in-out;\n background: rgba(255, 255, 255, 0.9);\n}\n\n.data-card-dnd-active {\n display: block;\n opacity: 1;\n cursor: pointer;\n}\n\n.data-card-dnd:hover {\n\tbackground: #f4f4f4;\n\tcolor: #595959;\n}\n\n.data-card-dnd-trigger {\n width: 18px;\n height: 24px;\n text-align: center;\n color: #BFBFBF;\n font-size: 16px;\n border-radius: 2px 2px;\n cursor: move;\n cursor: grab;\n cursor: -moz-grab;\n cursor: -webkit-grab;\n}\n\n.am-engine-view .data-toolbar-active {\n\tmin-width: 200px;\n}\n\n.data-card-toolbar.data-toolbar-block {\n\ttop: -48px;\n\tbottom: auto;\n\tdisplay: none;\n}\n\n.data-card-toolbar.data-card-toolbar-active {\n\tdisplay: block;\n}\n\n.data-card-toolbar.data-toolbar-active {\n\tdisplay: block;\n}";
styleInject(css_248z$9);
var isCardToolbarItemOptions = function isCardToolbarItemOptions(item) {
return ['button', 'input', 'dropdown', 'node', 'switch'].indexOf(item.type) === -1;
};
var _hideTimeout = /*#__PURE__*/_classPrivateFieldLooseKey("hideTimeout");
var _showTimeout = /*#__PURE__*/_classPrivateFieldLooseKey("showTimeout");
var _defaultAlign = /*#__PURE__*/_classPrivateFieldLooseKey("defaultAlign");
var _dndNode = /*#__PURE__*/_classPrivateFieldLooseKey("dndNode");
var CardToolbar = /*#__PURE__*/function () {
function CardToolbar(editor, card) {
var _this = this;
_classCallCheck(this, CardToolbar);
this.card = void 0;
this.toolbar = void 0;
this.editor = void 0;
this.offset = void 0;
this.position = void 0;
this.dndPosition = void 0;
Object.defineProperty(this, _hideTimeout, {
writable: true,
value: null
});
Object.defineProperty(this, _showTimeout, {
writable: true,
value: null
});
Object.defineProperty(this, _defaultAlign, {
writable: true,
value: 'topLeft'
});
Object.defineProperty(this, _dndNode, {
writable: true,
value: null
});
this.clearHide = function () {
if (_classPrivateFieldLooseBase(_this, _hideTimeout)[_hideTimeout]) clearTimeout(_classPrivateFieldLooseBase(_this, _hideTimeout)[_hideTimeout]);
_classPrivateFieldLooseBase(_this, _hideTimeout)[_hideTimeout] = null;
};
this.clearShow = function () {
if (_classPrivateFieldLooseBase(_this, _showTimeout)[_showTimeout]) clearTimeout(_classPrivateFieldLooseBase(_this, _showTimeout)[_showTimeout]);
_classPrivateFieldLooseBase(_this, _showTimeout)[_showTimeout] = null;
};
this.enterHide = function () {
_this.clearShow();
_classPrivateFieldLooseBase(_this, _hideTimeout)[_hideTimeout] = setTimeout(function () {
var _toolbar$root, _toolbar$root2;
_this.hide();
_classPrivateFieldLooseBase(_this, _hideTimeout)[_hideTimeout] = null;
var toolbar = _this.toolbar;
toolbar === null || toolbar === void 0 ? void 0 : (_toolbar$root = toolbar.root) === null || _toolbar$root === void 0 ? void 0 : _toolbar$root.off('mouseenter', _this.clearHide);
toolbar === null || toolbar === void 0 ? void 0 : (_toolbar$root2 = toolbar.root) === null || _toolbar$root2 === void 0 ? void 0 : _toolbar$root2.off('mouseleave', _this.enterHide);
}, 200);
};
this.enterShow = function () {
_this.clearHide();
_classPrivateFieldLooseBase(_this, _showTimeout)[_showTimeout] = setTimeout(function () {
var _toolbar$root3, _toolbar$root4;
_classPrivateFieldLooseBase(_this, _showTimeout)[_showTimeout] = null;
_this.show();
var toolbar = _this.toolbar;
toolbar === null || toolbar === void 0 ? void 0 : (_toolbar$root3 = toolbar.root) === null || _toolbar$root3 === void 0 ? void 0 : _toolbar$root3.on('mouseenter', _this.clearHide);
toolbar === null || toolbar === void 0 ? void 0 : (_toolbar$root4 = toolbar.root) === null || _toolbar$root4 === void 0 ? void 0 : _toolbar$root4.on('mouseleave', _this.enterHide);
}, 200);
};
this.editor = editor;
this.card = card;
this.position = new Position(editor);
this.dndPosition = new Position(editor);
this.unbindEnterShow();
if (!isEngine(editor) || editor.readonly) {
this.bindEnterShow();
}
}
_createClass(CardToolbar, [{
key: "setDefaultAlign",
value: function setDefaultAlign(align) {
_classPrivateFieldLooseBase(this, _defaultAlign)[_defaultAlign] = align;
}
}, {
key: "bindEnterShow",
value: function bindEnterShow() {
this.card.root.on('mouseenter', this.enterShow);
this.card.root.on('mouseleave', this.enterHide);
}
}, {
key: "unbindEnterShow",
value: function unbindEnterShow() {
this.card.root.off('mouseenter', this.enterShow);
this.card.root.off('mouseleave', this.enterHide);
}
/**
* 设置工具栏偏移量[上x,上y,下x,下y]
* @param offset 偏移量 [tx,ty,bx,by]
*/
}, {
key: "setOffset",
value: function setOffset(offset) {
this.offset = offset;
}
}, {
key: "getContainer",
value: function getContainer() {
var _this$toolbar;
return (_this$toolbar = this.toolbar) === null || _this$toolbar === void 0 ? void 0 : _this$toolbar.root;
}
}, {
key: "getDefaultItem",
value: function getDefaultItem(item) {
var _this2 = this;
var editor = this.editor;
var language = editor.language,
clipboard = editor.clipboard,
card = editor.card;
switch (item.type) {
case 'separator':
return {
key: 'separator',
type: 'node',
node: item.node || $("")
};
case 'copy':
return {
key: 'copy',
type: 'button',
content: item.content || "",
title: item.title || language.get('copy', 'title'),
onClick: function onClick(e, node) {
if (item.onClick) {
item.onClick(e, node);
return;
}
var result = clipboard.copy(_this2.card.root[0], true);
if (result) editor.messageSuccess('copy', language.get('copy', 'success'));else editor.messageError('copy', language.get('copy', 'error'));
}
};
case 'delete':
return {
key: 'delete',
type: 'button',
content: item.content || "",
title: item.title || language.get('delete', 'title').toString(),
onClick: function onClick(e, node) {
if (item.onClick) {
item.onClick(e, node);
return;
}
card.remove(_this2.card.root);
}
};
case 'maximize':
return {
key: 'maximize',
type: 'button',
content: item.content || "",
title: item.title || language.get('maximize', 'title').toString(),
onClick: function onClick(e, node) {
if (item.onClick) {
item.onClick(e, node);
return;
}
_this2.card.maximize();
}
};
case 'more':
return {
key: 'more',
type: 'dropdown',
content: item.content || "",
title: item.title || language.get('more', 'title').toString(),
items: item.items
};
}
return;
}
}, {
key: "getItems",
value: function getItems() {
var _this3 = this;
if (!this.card.toolbar) return [[], []]; //获取客户端配置
var config = this.card.toolbar();
var items = [];
config.forEach(function (item) {
//默认项
if (isCardToolbarItemOptions(item)) {
switch (item.type) {
case 'dnd':
break;
default:
var resultItem = _this3.getDefaultItem(item);
if (resultItem) items.push(resultItem);
}
} else {
items.push(item);
}
});
return [items, config];
}
}, {
key: "create",
value: function create() {
this.hide();
var _this$getItems = this.getItems(),
_this$getItems2 = _slicedToArray(_this$getItems, 2),
items = _this$getItems2[0],
config = _this$getItems2[1];
if (items.length > 0) {
var dnd = config.find(function (item) {
return isCardToolbarItemOptions(item) && item.type === 'dnd';
});
if (dnd && !isMobile && dnd.type === 'dnd') {
//获取渲染节点
var _this$editor = this.editor,
root = _this$editor.root,
language = _this$editor.language;
var dndNode = this.createDnd(dnd.content || '', dnd.title || language.get('dnd', 'title').toString());
root.append(dndNode);
_classPrivateFieldLooseBase(this, _dndNode)[_dndNode] = dndNode;
}
var toolbar = new Toolbar({
items: items
});
toolbar.root.addClass('data-card-toolbar');
toolbar.root.attributes(TRIGGER_CARD_ID, this.card.id); //渲染工具栏
toolbar.render($(document.body));
toolbar.hide();
this.toolbar = toolbar;
}
}
}, {
key: "update",
value: function update() {
var _this$toolbar2;
var _this$getItems3 = this.getItems(),
_this$getItems4 = _slicedToArray(_this$getItems3, 1),
items = _this$getItems4[0];
(_this$toolbar2 = this.toolbar) === null || _this$toolbar2 === void 0 ? void 0 : _this$toolbar2.update({
items: items
});
}
}, {
key: "hide",
value: function hide() {
var _classPrivateFieldLoo;
(_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _dndNode)[_dndNode]) === null || _classPrivateFieldLoo === void 0 ? void 0 : _classPrivateFieldLoo.remove();
this.dndPosition.destroy();
this.hideCardToolbar();
}
}, {
key: "show",
value: function show(event) {
this.showCardToolbar(event);
}
}, {
key: "hideCardToolbar",
value: function hideCardToolbar() {
var _this$toolbar3;
(_this$toolbar3 = this.toolbar) === null || _this$toolbar3 === void 0 ? void 0 : _this$toolbar3.destroy();
this.position.destroy();
}
}, {
key: "showDnd",
value: function showDnd() {
var _this4 = this;
if (!_classPrivateFieldLooseBase(this, _dndNode)[_dndNode]) return;
if (_classPrivateFieldLooseBase(this, _dndNode)[_dndNode].length === 0) return;
if (!this.card.isMaximize) {
if (_classPrivateFieldLooseBase(this, _dndNode)[_dndNode].length > 0) {
_classPrivateFieldLooseBase(this, _dndNode)[_dndNode].addClass('data-card-dnd-active');
setTimeout(function () {
_this4.dndPosition.bind(_classPrivateFieldLooseBase(_this4, _dndNode)[_dndNode], _this4.card.root, 'leftTop', _this4.offset), 10;
});
}
} else {
_classPrivateFieldLooseBase(this, _dndNode)[_dndNode].removeClass('data-card-dnd-active');
}
}
}, {
key: "showCardToolbar",
value: function showCardToolbar(event) {
var _this5 = this;
this.create();
var container = this.getContainer();
if (container && container.length > 0) {
this.showDnd();
var card = this.card;
container.addClass('data-toolbar-active');
container.attributes('toolbar-trigger-key', card.constructor.cardName);
if (this.toolbar) this.toolbar.show();
var prevAlign = _classPrivateFieldLooseBase(this, _defaultAlign)[_defaultAlign];
var position = this.position;
setTimeout(function () {
position.bind(container, card.isMaximize ? card.getCenter().first() : card.root, _classPrivateFieldLooseBase(_this5, _defaultAlign)[_defaultAlign], _this5.offset, function (rect) {
if (_this5.offset && _this5.offset.length === 4 && rect.align === 'bottomLeft' && rect.align !== prevAlign) {
position.setOffset([_this5.offset[2], _this5.offset[3]]);
prevAlign = rect.align;
position.update(false);
} else if (_this5.offset && rect.align === _classPrivateFieldLooseBase(_this5, _defaultAlign)[_defaultAlign] && rect.align !== prevAlign) {
position.setOffset(_this5.offset);
prevAlign = rect.align;
position.update(false);
}
prevAlign = rect.align;
});
}, 10);
}
}
}, {
key: "createDnd",
value: function createDnd(content, title) {
var _this6 = this;
var dndNode = $("\n
\n ").concat(content, "\n
\n
"));
dndNode.on('mouseenter', function () {
Tooltip.show(dndNode, title);
});
dndNode.on('mouseleave', function () {
Tooltip.hide();
});
dndNode.on('mousedown', function (e) {
e.stopPropagation();
Tooltip.hide();
_this6.hideCardToolbar();
});
dndNode.on('mouseup', function () {
_this6.showCardToolbar();
});
return dndNode;
}
}, {
key: "destroy",
value: function destroy() {
this.unbindEnterShow();
this.dndPosition.destroy();
this.position.destroy();
}
}]);
return CardToolbar;
}();
var CardEntry = /*#__PURE__*/function () {
function CardEntry(_ref) {
var _value;
var editor = _ref.editor,
value = _ref.value,
root = _ref.root;
_classCallCheck(this, CardEntry);
this.editor = void 0;
this.root = void 0;
this.toolbarModel = void 0;
this.resizeModel = void 0;
this.activatedByOther = false;
this.selectedByOther = false;
this.contenteditable = [];
this.defaultMaximize = void 0;
this.isMaximize = false;
this._id = void 0;
this.resize = void 0;
this.editor = editor;
var type = ((_value = value) === null || _value === void 0 ? void 0 : _value.type) || this.constructor.cardType;
var tagName = type === 'inline' ? 'span' : 'div';
this.root = root ? root : $('<'.concat(tagName, ' />'));
if (typeof value === 'string') value = decodeCardValue(value);
value = value || {};
value.id = this.getId(value.id);
this._id = value.id;
value.type = type;
this.setValue(value);
this.defaultMaximize = new Maximize(editor, this);
}
_createClass(CardEntry, [{
key: "isEditable",
get:
/**
* 可编辑的节点
*/
function get() {
return this.contenteditable.length > 0;
}
}, {
key: "activated",
get: function get() {
return this.root.hasClass('card-activated');
}
}, {
key: "setActivated",
value: function setActivated(activated) {
activated ? this.root.addClass('card-activated') : this.root.removeClass('card-activated');
}
}, {
key: "selected",
get: function get() {
return this.root.hasClass('card-selected');
}
}, {
key: "setSelected",
value: function setSelected(selected) {
selected ? this.root.addClass('card-selected') : this.root.removeClass('card-selected');
}
}, {
key: "id",
get: function get() {
if (this._id) return this._id;
var attributesValues = this.root.attributes(CARD_VALUE_KEY);
if (!attributesValues) return {};
var value = decodeCardValue(attributesValues);
return _typeof(value) === 'object' ? (value === null || value === void 0 ? void 0 : value.id) || '' : '';
}
}, {
key: "name",
get: function get() {
return this.root.attributes(CARD_KEY);
}
}, {
key: "type",
get: function get() {
var type = this.root.attributes(CARD_TYPE_KEY);
if (!type) {
var attributesValues = this.root.attributes(CARD_VALUE_KEY);
var value = decodeCardValue(attributesValues || '{}');
type = (value === null || value === void 0 ? void 0 : value.type) || this.constructor.cardType;
}
return type;
},
set: function set(type) {
if (!this.name || type === this.type) return; // 替换后重新渲染
var card = this.editor.card;
var attributesValues = this.root.attributes(CARD_VALUE_KEY);
var value = decodeCardValue(attributesValues || '{}');
var component = card.replace(this, this.name, _objectSpread2(_objectSpread2({}, value), {}, {
type: type
}));
card.render(component.root);
component.activate(false);
card.activate(component.root);
}
}, {
key: "loading",
get: function get() {
return !!this.root.attributes(CARD_LOADING_KEY);
}
}, {
key: "init",
value: function init() {
this.root.attributes(CARD_EDITABLE_KEY, this.isEditable ? 'true' : 'false');
var toolbar = this.toolbarModel;
toolbar === null || toolbar === void 0 ? void 0 : toolbar.hide();
toolbar === null || toolbar === void 0 ? void 0 : toolbar.destroy();
var editor = this.editor;
if (this.toolbar) {
this.toolbarModel = new CardToolbar(editor, this);
}
if (this.resize) {
this.resizeModel = new Resize(editor, this);
}
}
}, {
key: "getId",
value: function getId(curId) {
var idCache = [];
this.editor.card.each(function (card) {
idCache.push(card.id);
});
if (curId && idCache.indexOf(curId) < 0) return curId;
var id = random();
while (idCache.indexOf(id) >= 0) {
id = random();
}
return id;
} // 设置 DOM 属性里的数据
}, {
key: "setValue",
value: function setValue(value) {
if (value == null) {
return;
}
var attributesValues = this.root.attributes(CARD_VALUE_KEY);
var currentValue = decodeCardValue(attributesValues || '{}');
if (!!(currentValue === null || currentValue === void 0 ? void 0 : currentValue.id)) delete value['id'];
value = _objectSpread2(_objectSpread2({}, currentValue), value);
if (value.type && (currentValue === null || currentValue === void 0 ? void 0 : currentValue.type) !== value.type) {
this.type = value.type;
}
this.root.attributes(CARD_VALUE_KEY, encodeCardValue(value));
} // 获取 DOM 属性里的数据
}, {
key: "getValue",
value: function getValue() {
var value = this.root.attributes(CARD_VALUE_KEY);
if (!value) return {};
return decodeCardValue(value);
}
/**
* 获取Card内的 DOM 节点
* @param selector
*/
}, {
key: "find",
value: function find(selector) {
return this.root.find(selector);
}
}, {
key: "findByKey",
value: function findByKey(key) {
var body = this.root.first() || $([]);
if (key === 'body' || body.length === 0) return body;
var children = body.children();
var index = ['left', 'center', 'right'].indexOf(key);
if (index > -1) {
return children.toArray().find(function (child) {
return child.attributes(CARD_ELEMENT_KEY) === key;
});
}
var tagName = this.type === exports.CardType.BLOCK ? 'div' : 'span';
var targetNode = this.find("".concat(tagName, "[").concat(CARD_ELEMENT_KEY, "=").concat(key, "]"));
return targetNode.name === tagName && targetNode.attributes(CARD_ELEMENT_KEY) === key ? targetNode : undefined;
}
}, {
key: "activate",
value: function activate(activated) {
if (activated) {
if (!this.activated) {
this.setActivated(activated);
this.onActivate(activated);
}
} else if (this.activated) {
this.setActivated(activated);
this.onActivate(false);
}
}
}, {
key: "select",
value: function select(selected) {
if (!isEngine(this.editor) || this.activatedByOther) {
return;
}
if (selected) {
if (!this.selected && !this.isMaximize) {
this.setSelected(selected);
this.onSelect(selected);
}
} else if (this.selected) {
this.setSelected(selected);
this.onSelect(false);
}
}
}, {
key: "getCenter",
value: function getCenter() {
var center = this.findByKey('center');
if (!center) return $([]);
return center;
}
}, {
key: "isCenter",
value: function isCenter(node) {
var _this$findByKey;
var center = node.closest(this.type === exports.CardType.BLOCK ? "div[".concat(CARD_ELEMENT_KEY, "=center]") : "span[".concat(CARD_ELEMENT_KEY, "=center]"));
return center.length > 0 && !!((_this$findByKey = this.findByKey('center')) === null || _this$findByKey === void 0 ? void 0 : _this$findByKey.equal(center));
}
}, {
key: "isCursor",
value: function isCursor(node) {
return this.isLeftCursor(node) || this.isRightCursor(node);
}
}, {
key: "isLeftCursor",
value: function isLeftCursor(node) {
var _this$findByKey2;
if (node.isElement() && node.attributes(CARD_ELEMENT_KEY) !== 'left') return false;
var cursor = node.closest(CARD_LEFT_SELECTOR);
return cursor.length > 0 && !!((_this$findByKey2 = this.findByKey('left')) === null || _this$findByKey2 === void 0 ? void 0 : _this$findByKey2.equal(cursor));
}
}, {
key: "isRightCursor",
value: function isRightCursor(node) {
var _this$findByKey3;
if (node.isElement() && node.attributes(CARD_ELEMENT_KEY) !== 'right') return false;
var cursor = node.closest(CARD_RIGHT_SELECTOR);
return cursor.length > 0 && !!((_this$findByKey3 = this.findByKey('right')) === null || _this$findByKey3 === void 0 ? void 0 : _this$findByKey3.equal(cursor));
}
}, {
key: "focus",
value: function focus(range, toStart) {
var cardLeft = this.findByKey('left');
var cardRight = this.findByKey('right');
if (!cardLeft || cardLeft.length === 0 || !cardRight || cardRight.length === 0) {
return;
}
var zeroElement = toStart ? cardLeft : cardRight;
range.select(zeroElement, true).shrinkToTextNode();
var textNode = zeroElement.first();
if (!textNode) return;
range.setStart(textNode, toStart ? 0 : 1);
range.collapse(true);
if (isEngine(this.editor)) this.editor.change.range.select(range);
if (this.onFocus) this.onFocus();
}
}, {
key: "maximize",
value: function maximize() {
var _this$toolbarModel;
this.isMaximize = true;
this.defaultMaximize.maximize();
(_this$toolbarModel = this.toolbarModel) === null || _this$toolbarModel === void 0 ? void 0 : _this$toolbarModel.show();
}
}, {
key: "minimize",
value: function minimize() {
var _this$toolbarModel2;
this.isMaximize = false;
this.defaultMaximize.restore();
(_this$toolbarModel2 = this.toolbarModel) === null || _this$toolbarModel2 === void 0 ? void 0 : _this$toolbarModel2.show();
}
/**
* 是否可改变卡片大小,或者传入渲染节点
*/
}, {
key: "onSelect",
value: function onSelect(selected) {
var selectStyleType = this.constructor.selectStyleType;
if (selectStyleType === exports.SelectStyleType.NONE) return;
var selectedClass = "data-card-".concat(selectStyleType, "-selected");
var center = this.getCenter();
if (selected) {
center.addClass(selectedClass);
} else {
center.removeClass(selectedClass);
}
}
}, {
key: "onSelectByOther",
value: function onSelectByOther(selected, value) {
var center = this.getCenter();
var selectStyleType = this.constructor.selectStyleType;
if (selectStyleType === exports.SelectStyleType.BACKGROUND) {
center.css('background-color', selected ? value.rgb : '');
} else {
center.css('outline', selected ? '2px solid ' + value.color : '');
}
var className = 'card-selected-other';
if (selected) this.root.addClass(className);else this.root.removeClass(className);
return center;
}
}, {
key: "onActivate",
value: function onActivate(activated) {
var _this$resizeModel, _this$resizeModel2;
if (!this.resize) return;
if (activated) (_this$resizeModel = this.resizeModel) === null || _this$resizeModel === void 0 ? void 0 : _this$resizeModel.show();else (_this$resizeModel2 = this.resizeModel) === null || _this$resizeModel2 === void 0 ? void 0 : _this$resizeModel2.hide();
}
}, {
key: "onActivateByOther",
value: function onActivateByOther(activated, value) {
return this.onSelectByOther(activated, value);
}
}, {
key: "initToolbar",
value: function initToolbar() {
if (this.toolbar) {
if (!this.toolbarModel) this.toolbarModel = new CardToolbar(this.editor, this);
if (this.activated) {
this.toolbarModel.show();
}
} else {
var _this$toolbarModel3, _this$toolbarModel4;
(_this$toolbarModel3 = this.toolbarModel) === null || _this$toolbarModel3 === void 0 ? void 0 : _this$toolbarModel3.hide();
(_this$toolbarModel4 = this.toolbarModel) === null || _this$toolbarModel4 === void 0 ? void 0 : _this$toolbarModel4.destroy();
this.toolbarModel = undefined;
}
}
}, {
key: "initResize",
value: function initResize() {
if (this.resize) {
if (!this.resizeModel) {
this.resizeModel = new Resize(this.editor, this);
}
var container = typeof this.resize === 'function' ? this.resize() : this.findByKey('body');
if (container && container.length > 0) {
var _this$resizeModel3;
(_this$resizeModel3 = this.resizeModel) === null || _this$resizeModel3 === void 0 ? void 0 : _this$resizeModel3.render(container);
}
}
}
}, {
key: "didUpdate",
value: function didUpdate() {
this.initResize();
this.initToolbar();
}
}, {
key: "beforeRender",
value: function beforeRender() {
var center = this.getCenter();
var loadingElement = $("<".concat(this.type === exports.CardType.BLOCK ? 'div' : 'span', " class=\"").concat(CARD_LOADING_KEY, "\" ").concat(DATA_ELEMENT, "=\"").concat(UI, "\" />"));
loadingElement.append('');
center.empty().append(loadingElement);
}
}, {
key: "didRender",
value: function didRender() {
var _this = this;
if (this.loading) {
this.find(".".concat(CARD_LOADING_KEY)).remove();
setTimeout(function () {
_this.root.removeAttributes(CARD_LOADING_KEY);
}, 200);
}
this.initResize();
this.initToolbar();
if (this.isEditable) {
this.editor.nodeId.generateAll(this.getCenter().get());
}
}
}, {
key: "destroy",
value: function destroy() {
var _this$toolbarModel5, _this$toolbarModel6, _this$resizeModel4, _this$resizeModel5;
(_this$toolbarModel5 = this.toolbarModel) === null || _this$toolbarModel5 === void 0 ? void 0 : _this$toolbarModel5.hide();
(_this$toolbarModel6 = this.toolbarModel) === null || _this$toolbarModel6 === void 0 ? void 0 : _this$toolbarModel6.destroy();
this.toolbarModel = undefined;
(_this$resizeModel4 = this.resizeModel) === null || _this$resizeModel4 === void 0 ? void 0 : _this$resizeModel4.hide();
(_this$resizeModel5 = this.resizeModel) === null || _this$resizeModel5 === void 0 ? void 0 : _this$resizeModel5.destroy();
this.resizeModel = undefined;
}
}]);
return CardEntry;
}();
CardEntry.cardName = void 0;
CardEntry.cardType = void 0;
CardEntry.autoActivate = void 0;
CardEntry.autoSelected = true;
CardEntry.singleSelectable = void 0;
CardEntry.collab = true;
CardEntry.focus = void 0;
CardEntry.selectStyleType = exports.SelectStyleType.BORDER;
CardEntry.lazyRender = false;
var View = /*#__PURE__*/function (_Editor) {
_inherits(View, _Editor);
var _super = _createSuper(View);
function View(selector, options) {
var _this;
_classCallCheck(this, View);
_this = _super.call(this, selector, options);
_this.kind = 'view';
_this.init();
if (!_this.container.hasClass(VIEW_CLASS_NAME)) {
_this.container.addClass(VIEW_CLASS_NAME);
}
return _this;
}
_createClass(View, [{
key: "render",
value: function render(content) {
var _this2 = this;
var trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var parser = new Parser(content, this);
var value = parser.toValue(this.schema, this.conversion, false, true);
this.container.html(value);
this.card.render(this.container, function () {
if (trigger) _this2.trigger('render', _this2.container);
});
}
}]);
return View;
}(Editor);
var css_248z$a = ".data-scrollable::-webkit-scrollbar {\r\n display: none;\r\n overflow: hidden;\r\n }\r\n .data-scrollable.scroll-x {\r\n padding-bottom: 10px;\r\n overflow-x: hidden;\r\n }\r\n \r\n .data-scrollable.scroll-y {\r\n padding-right: 10px;\r\n overflow-y: hidden;\r\n }\r\n\r\n .data-scrollable:hover .data-scrollbar {\r\n display: block;\r\n }\r\n .data-scrollable.scrolling {\r\n -webkit-user-select: none;\r\n -moz-user-select: none;\r\n -ms-user-select: none;\r\n user-select: none;\r\n }\r\n .data-scrollable.scrolling .data-scrollbar {\r\n display: block;\r\n }\r\n .data-scrollable .data-scrollbar {\r\n display: none;\r\n position: absolute;\r\n cursor: default;\r\n transition: opacity 0.3s ease-in-out;\r\n }\r\n .data-scrollable .data-scrollbar .data-scrollbar-trigger {\r\n position: absolute;\r\n background: #c1c1c1;\r\n border-radius: 10px;\r\n cursor: pointer;\r\n }\r\n .data-scrollable .data-scrollbar .data-scrollbar-trigger:hover {\r\n background: #888;\r\n }\r\n .data-scrollable .data-scrollbar.data-scrollbar-x {\r\n height: 8px;\r\n bottom: 0px;\r\n }\r\n .data-scrollable .data-scrollbar.data-scrollbar-x .data-scrollbar-trigger {\r\n height: 8px;\r\n min-width: 60px;\r\n }\r\n .data-scrollable .data-scrollbar.data-scrollbar-y {\r\n top: 0;\r\n width: 8px;\r\n height: 100%;\r\n right: 0px;\r\n }\r\n .data-scrollable .data-scrollbar.data-scrollbar-y .data-scrollbar-trigger {\r\n width: 8px;\r\n min-height: 60px;\r\n }\r\n .data-scrollable .scrollbar-shadow-left {\r\n position: absolute;\r\n z-index: 10;\r\n left: 0;\r\n top: 0;\r\n bottom: 0;\r\n width: 4px;\r\n opacity: 0.8;\r\n background: linear-gradient(270deg, rgba(99, 114, 130, 0) 0, rgba(99, 114, 130, 0.16));\r\n background: -webkit-linear-gradient(right, rgba(99, 114, 130, 0), rgba(99, 114, 130, 0.16));\r\n pointer-events: none;\r\n }\r\n .data-scrollable .scrollbar-shadow-right {\r\n position: absolute;\r\n z-index: 10;\r\n left: 0;\r\n top: 0;\r\n bottom: 0;\r\n width: 4px;\r\n opacity: 0.8;\r\n background: linear-gradient(90deg, rgba(99, 114, 130, 0) 0, rgba(99, 114, 130, 0.16));\r\n background: -webkit-linear-gradient(left, rgba(99, 114, 130, 0), rgba(99, 114, 130, 0.16));\r\n pointer-events: none;\r\n }";
styleInject(css_248z$a);
var _observer$1 = /*#__PURE__*/_classPrivateFieldLooseKey("observer");
var _reverse = /*#__PURE__*/_classPrivateFieldLooseKey("reverse");
var _content = /*#__PURE__*/_classPrivateFieldLooseKey("content");
var _enableScroll = /*#__PURE__*/_classPrivateFieldLooseKey("enableScroll");
var _scroll = /*#__PURE__*/_classPrivateFieldLooseKey("scroll");
var _isScrolling = /*#__PURE__*/_classPrivateFieldLooseKey("isScrolling");
var Scrollbar = /*#__PURE__*/function (_EventEmitter) {
_inherits(Scrollbar, _EventEmitter);
var _super = _createSuper(Scrollbar);
/**
* @param {nativeNode} container 需要添加滚动条的元素
* @param {boolean} x 横向滚动条
* @param {boolean} y 竖向滚动条
* @param {boolean} needShadow 是否显示阴影
*/
function Scrollbar(container) {
var _this;
var _x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var shadow = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var scroll = arguments.length > 4 ? arguments[4] : undefined;
_classCallCheck(this, Scrollbar);
_this = _super.call(this);
_this.container = void 0;
_this.x = void 0;
_this.y = void 0;
_this.shadow = void 0;
_this.scrollBarX = void 0;
_this.slideX = void 0;
_this.slideXDragging = void 0;
_this.scrollBarY = void 0;
_this.slideY = void 0;
_this.slideYDragging = void 0;
_this.shadowLeft = void 0;
_this.shadowRight = void 0;
_this.oWidth = 0;
_this.oHeight = 0;
_this.sWidth = 0;
_this.sHeight = 0;
_this.xWidth = 0;
_this.yHeight = 0;
Object.defineProperty(_assertThisInitialized(_this), _observer$1, {
writable: true,
value: void 0
});
Object.defineProperty(_assertThisInitialized(_this), _reverse, {
writable: true,
value: void 0
});
Object.defineProperty(_assertThisInitialized(_this), _content, {
writable: true,
value: void 0
});
_this.shadowTimer = void 0;
Object.defineProperty(_assertThisInitialized(_this), _enableScroll, {
writable: true,
value: true
});
Object.defineProperty(_assertThisInitialized(_this), _scroll, {
writable: true,
value: void 0
});
Object.defineProperty(_assertThisInitialized(_this), _isScrolling, {
writable: true,
value: false
});
_this.refresh = function () {
var element = _this.container.get();
if (element) {
var _classPrivateFieldLoo, _classPrivateFieldLoo3;
var scrollEnd = function scrollEnd() {
setTimeout(function () {
_classPrivateFieldLooseBase(_assertThisInitialized(_this), _isScrolling)[_isScrolling] = false;
}, 0);
};
var scrollTop = element.scrollTop;
var contentElement = (_classPrivateFieldLoo = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _content)[_content]) === null || _classPrivateFieldLoo === void 0 ? void 0 : _classPrivateFieldLoo.get();
var sPLeft = removeUnit(_this.container.css('padding-left'));
var sPRight = removeUnit(_this.container.css('padding-right'));
var sPTop = removeUnit(_this.container.css('padding-top'));
var sPBottom = removeUnit(_this.container.css('padding-bottom'));
var scrollWidth = contentElement ? _classPrivateFieldLooseBase(_assertThisInitialized(_this), _content)[_content].width() + sPLeft + sPRight : element.scrollWidth;
var scrollHeight = contentElement ? _classPrivateFieldLooseBase(_assertThisInitialized(_this), _content)[_content].height() + sPTop + sPBottom : element.scrollHeight;
_this.oWidth = _this.getWidth();
_this.oHeight = _this.container.height() - removeUnit(_this.container.css('border-top-width')) - removeUnit(_this.container.css('border-bottom-width'));
_this.sWidth = scrollWidth;
_this.sHeight = scrollHeight;
_this.xWidth = Math.floor(_this.oWidth * _this.oWidth / scrollWidth);
_this.yHeight = Math.floor(_this.oHeight * _this.oHeight / scrollHeight);
if (_this.x) {
var _this$slideX, _this$slideX2, _this$shadowLeft, _this$shadowRight;
(_this$slideX = _this.slideX) === null || _this$slideX === void 0 ? void 0 : _this$slideX.css('width', _this.xWidth + 'px');
var display = Math.round(_this.oWidth) - sPLeft - sPRight === _this.sWidth || contentElement && Math.round(_classPrivateFieldLooseBase(_assertThisInitialized(_this), _content)[_content].width()) <= Math.round(_this.oWidth - sPLeft - sPRight) ? 'none' : 'block';
(_this$slideX2 = _this.slideX) === null || _this$slideX2 === void 0 ? void 0 : _this$slideX2.css('display', display);
_this.emit('display', display);
(_this$shadowLeft = _this.shadowLeft) === null || _this$shadowLeft === void 0 ? void 0 : _this$shadowLeft.css('display', display);
(_this$shadowRight = _this.shadowRight) === null || _this$shadowRight === void 0 ? void 0 : _this$shadowRight.css('display', display);
}
if (_this.y) {
var _this$slideY, _this$slideY2;
(_this$slideY = _this.slideY) === null || _this$slideY === void 0 ? void 0 : _this$slideY.css('height', _this.yHeight + 'px');
var _display = Math.round(_this.oHeight) - sPTop - sPBottom === _this.sHeight || contentElement && Math.round(_classPrivateFieldLooseBase(_assertThisInitialized(_this), _content)[_content].height()) <= Math.round(_this.oHeight - sPTop - sPBottom) ? 'none' : 'block';
(_this$slideY2 = _this.slideY) === null || _this$slideY2 === void 0 ? void 0 : _this$slideY2.css('display', _display);
_this.emit('display', _display);
} // 实际内容宽度小于容器滚动宽度(有内容删除了)
if (_this.x && contentElement && element.scrollWidth - sPLeft - sPRight > _classPrivateFieldLooseBase(_assertThisInitialized(_this), _content)[_content].width()) {
_classPrivateFieldLooseBase(_assertThisInitialized(_this), _isScrolling)[_isScrolling] = true;
var _left = element.scrollWidth - sPLeft - sPRight - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _content)[_content].width();
if (_classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll]) {
var _classPrivateFieldLoo2 = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll],
onScrollX = _classPrivateFieldLoo2.onScrollX,
getScrollLeft = _classPrivateFieldLoo2.getScrollLeft;
_left = getScrollLeft ? getScrollLeft(-0) + element.scrollLeft - _left : element.scrollLeft - _left;
if (_left < 0) _left = 0;
if (onScrollX) {
var result = onScrollX(_left);
if (result > 0) element.scrollLeft = result;else element.scrollLeft = 0;
}
_this.scroll({
left: _left
});
} else {
element.scrollLeft -= _left;
scrollEnd();
}
return;
} // 实际内容高度小于容器滚动高度(有内容删除了)
if (_this.y && contentElement && element.scrollHeight - sPTop - sPBottom !== _classPrivateFieldLooseBase(_assertThisInitialized(_this), _content)[_content].height()) {
_classPrivateFieldLooseBase(_assertThisInitialized(_this), _isScrolling)[_isScrolling] = true;
element.scrollTop -= element.scrollHeight - sPTop - sPBottom - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _content)[_content].height();
scrollEnd();
return;
}
var left = ((_classPrivateFieldLoo3 = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll]) === null || _classPrivateFieldLoo3 === void 0 ? void 0 : _classPrivateFieldLoo3.getScrollLeft) ? _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll].getScrollLeft(element.scrollLeft) : element.scrollLeft;
if (_classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll]) {
var _onScrollX = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll].onScrollX;
if (_onScrollX) {
_classPrivateFieldLooseBase(_assertThisInitialized(_this), _isScrolling)[_isScrolling] = true;
var _result = _onScrollX(left);
if (_result > 0) element.scrollLeft = _result;else element.scrollLeft = 0;
scrollEnd();
}
_this.scroll({
left: left
});
} else {
_this.reRenderX(left);
}
_this.reRenderY(scrollTop);
}
};
_this.scroll = function (event) {
var top = 0;
var left = 0;
if (!_classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll] && event instanceof Event) {
var _event$target = event.target,
scrollTop = _event$target.scrollTop,
scrollLeft = _event$target.scrollLeft;
top = scrollTop;
left = scrollLeft;
} else if (!(event instanceof Event)) {
if (event.top === undefined) {
var _this$container$get;
event.top = ((_this$container$get = _this.container.get()) === null || _this$container$get === void 0 ? void 0 : _this$container$get.scrollTop) || 0;
}
if (event.left === undefined) {
var _this$container$get2;
event.left = ((_this$container$get2 = _this.container.get()) === null || _this$container$get2 === void 0 ? void 0 : _this$container$get2.scrollLeft) || 0;
}
top = event.top;
left = event.left;
} else if (!_classPrivateFieldLooseBase(_assertThisInitialized(_this), _isScrolling)[_isScrolling]) {
_this.refresh();
return;
} else return;
_this.reRenderX(left);
_this.reRenderY(top);
};
_this.wheelXScroll = throttle__default['default'](function (event) {
var _classPrivateFieldLoo4, _classPrivateFieldLoo5;
event.preventDefault();
var dir = (isMacos ? event.wheelDeltaX : event.wheelDelta / 120 || -event.detail) > 0 ? 'up' : 'down';
var containerElement = _this.container.get();
if (!containerElement) return;
var width = _this.container.width();
var containerWidth = ((_classPrivateFieldLoo4 = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll]) === null || _classPrivateFieldLoo4 === void 0 ? void 0 : _classPrivateFieldLoo4.getOffsetWidth) ? _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll].getOffsetWidth(width) : width;
var step = Math.max(containerWidth / (isMacos ? 20 - Math.abs(event.wheelDelta) : 8), 20);
var left = (((_classPrivateFieldLoo5 = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll]) === null || _classPrivateFieldLoo5 === void 0 ? void 0 : _classPrivateFieldLoo5.getScrollLeft) ? _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll].getScrollLeft(containerElement.scrollLeft) : containerElement.scrollLeft) + (dir === 'up' ? -step : step);
left = dir === 'up' ? Math.max(0, left) : Math.min(left, _this.sWidth - _this.oWidth);
if (_classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll]) {
var onScrollX = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll].onScrollX;
if (onScrollX) {
var result = onScrollX(left);
if (result > 0) containerElement.scrollLeft = result;else containerElement.scrollLeft = 0;
}
_this.scroll({
left: left
});
} else {
containerElement.scrollLeft = left;
}
}, isMacos ? 50 : 0, {
trailing: true
});
_this.wheelYScroll = throttle__default['default'](function (event) {
event.preventDefault();
var dir = (isMacos ? event.wheelDeltaX : event.wheelDelta / 120 || -event.detail) > 0 ? 'up' : 'down';
var containerElement = _this.container.get();
if (!containerElement) return;
var containerHeight = _this.container.height();
var step = Math.max(containerHeight / (isMacos ? 20 - Math.abs(event.wheelDelta) : 8), 20);
var top = containerElement.scrollTop + (dir === 'up' ? -step : step);
top = dir === 'up' ? Math.max(0, top) : Math.min(top, _this.sHeight - _this.oHeight);
containerElement.scrollTop = top;
}, isMacos ? 100 : 0, {
trailing: true
});
_this.bindWheelScroll = function (event) {
if (!_classPrivateFieldLooseBase(_assertThisInitialized(_this), _enableScroll)[_enableScroll]) return; // 滚轮x和y一致并且x的绝对值要大于y的绝对值才做横向滚动
var isX = _this.x && event.wheelDeltaX !== event.wheelDeltaY && Math.abs(event.wheelDeltaX) > Math.abs(event.wheelDeltaY);
if (isX) {
if (_this.slideX && _this.slideX.css('display') !== 'none') {
_this.wheelXScroll(event);
}
} else if (_this.y && event.wheelDeltaY !== 0) {
if (_this.slideY && _this.slideY.css('display') !== 'none') _this.wheelYScroll(event);
}
};
_this.bindContainerTouchX = function (event) {
if (!event.target || !_classPrivateFieldLooseBase(_assertThisInitialized(_this), _enableScroll)[_enableScroll]) return;
if ($(event.target).hasClass('data-scrollbar-trigger')) return; // 设置滚动方向相反
_classPrivateFieldLooseBase(_assertThisInitialized(_this), _reverse)[_reverse] = true;
_this.scrollXStart(event);
};
_this.bindContainerTouchY = function (event) {
if (!event.target || !_classPrivateFieldLooseBase(_assertThisInitialized(_this), _enableScroll)[_enableScroll]) return;
if ($(event.target).hasClass('data-scrollbar-trigger')) return; // 设置滚动方向相反
_classPrivateFieldLooseBase(_assertThisInitialized(_this), _reverse)[_reverse] = true;
_this.scrollYStart(event);
};
_this.getEventClientOffset = function (event) {
if (event instanceof MouseEvent) {
return {
x: event.clientX,
y: event.clientY
};
}
return {
x: event.touches[0].clientX,
y: event.touches[0].clientY
};
};
_this.scrollX = function (event) {
if (_this.slideXDragging) {
var _this$slideX3;
var _this$slideXDragging = _this.slideXDragging,
point = _this$slideXDragging.point,
position = _this$slideXDragging.position;
var offset = _this.getEventClientOffset(event);
var left = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _reverse)[_reverse] ? position - (offset.x - point) : position + (offset.x - point);
left = Math.max(0, Math.min(left, _this.oWidth - _this.xWidth));
(_this$slideX3 = _this.slideX) === null || _this$slideX3 === void 0 ? void 0 : _this$slideX3.css('left', left + 'px');
var min = left / (_this.oWidth - _this.xWidth);
min = Math.min(1, min);
var containerElement = _this.container.get();
var x = (_this.sWidth - _this.oWidth) * min;
if (_classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll]) {
var onScrollX = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll].onScrollX;
if (onScrollX) {
var result = onScrollX(x);
if (result > 0) containerElement.scrollLeft = result;else containerElement.scrollLeft = 0;
}
_this.scroll({
left: x
});
} else {
containerElement.scrollLeft = x;
}
}
};
_this.scrollY = function (event) {
if (_this.slideYDragging) {
var _this$slideY3;
var _this$slideYDragging = _this.slideYDragging,
point = _this$slideYDragging.point,
position = _this$slideYDragging.position;
var offset = _this.getEventClientOffset(event);
var top = _classPrivateFieldLooseBase(_assertThisInitialized(_this), _reverse)[_reverse] ? position - (offset.y - point) : position + (offset.y - point);
top = Math.max(0, Math.min(top, _this.oHeight - _this.yHeight));
(_this$slideY3 = _this.slideY) === null || _this$slideY3 === void 0 ? void 0 : _this$slideY3.css('top', top + 'px');
var min = top / (_this.oHeight - _this.yHeight);
min = Math.min(1, min);
_this.container.get().scrollTop = (_this.sHeight - _this.oHeight) * min;
}
};
_this.scrollXEnd = function () {
_this.slideXDragging = undefined;
_classPrivateFieldLooseBase(_assertThisInitialized(_this), _reverse)[_reverse] = false;
document.body.removeEventListener(isMobile ? 'touchmove' : 'mousemove', _this.scrollX);
document.body.removeEventListener(isMobile ? 'touchend' : 'mouseup', _this.scrollXEnd);
_this.container.removeClass('scrolling');
};
_this.scrollYEnd = function () {
_this.slideYDragging = undefined;
document.body.removeEventListener(isMobile ? 'touchmove' : 'mousemove', _this.scrollY);
document.body.removeEventListener(isMobile ? 'touchend' : 'mouseup', _this.scrollYEnd);
_this.container.removeClass('scrolling');
};
_this.scrollXStart = function (event) {
var _this$slideX4;
var offset = _this.getEventClientOffset(event);
_this.container.addClass('scrolling');
_this.slideXDragging = {
point: offset.x,
position: parseInt(((_this$slideX4 = _this.slideX) === null || _this$slideX4 === void 0 ? void 0 : _this$slideX4.css('left')) || '0')
};
document.body.addEventListener(isMobile ? 'touchmove' : 'mousemove', _this.scrollX, {
passive: true
});
document.body.addEventListener(isMobile ? 'touchend' : 'mouseup', _this.scrollXEnd, {
passive: true
});
};
_this.scrollYStart = function (event) {
var _this$slideY4;
var offset = _this.getEventClientOffset(event);
_this.container.addClass('scrolling');
_this.slideYDragging = {
point: offset.y,
position: parseInt(((_this$slideY4 = _this.slideY) === null || _this$slideY4 === void 0 ? void 0 : _this$slideY4.css('top')) || '0')
};
document.body.addEventListener(isMobile ? 'touchmove' : 'mousemove', _this.scrollY, {
passive: true
});
document.body.addEventListener(isMobile ? 'touchend' : 'mouseup', _this.scrollYEnd, {
passive: true
});
};
_this.bindXScrollEvent = function () {
if (_this.x) {
var _this$slideX5;
(_this$slideX5 = _this.slideX) === null || _this$slideX5 === void 0 ? void 0 : _this$slideX5.on(isMobile ? 'touchstart' : 'mousedown', _this.scrollXStart, {
passive: true
});
}
};
_this.bindYScrollEvent = function () {
if (_this.y) {
var _this$slideY5;
(_this$slideY5 = _this.slideY) === null || _this$slideY5 === void 0 ? void 0 : _this$slideY5.on(isMobile ? 'touchstart' : 'mousedown', _this.scrollYStart, {
passive: true
});
}
};
_this.reRenderShadow = function (width) {
if (_this.shadow) {
var _this$shadowRight2;
var element = _this.container.get();
if (element) {
var _this$shadowLeft2;
(_this$shadowLeft2 = _this.shadowLeft) === null || _this$shadowLeft2 === void 0 ? void 0 : _this$shadowLeft2.css('left', (_classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll] ? element.scrollLeft : width) + 'px');
}
(_this$shadowRight2 = _this.shadowRight) === null || _this$shadowRight2 === void 0 ? void 0 : _this$shadowRight2.css('left', width + _this.oWidth - 4 + 'px');
}
};
_this.reRenderX = function (left) {
if (_this.x) {
var _this$scrollBarX, _this$slideX6, _this$scrollBarY;
(_this$scrollBarX = _this.scrollBarX) === null || _this$scrollBarX === void 0 ? void 0 : _this$scrollBarX.css('left', left + 'px');
var value = _this.sWidth - _this.oWidth;
var min = value <= 0 ? 0 : left / value;
min = Math.min(1, min);
(_this$slideX6 = _this.slideX) === null || _this$slideX6 === void 0 ? void 0 : _this$slideX6.css('left', (_this.oWidth - _this.xWidth) * min + 'px');
_this.emit('change', {
x: left,
y: removeUnit(((_this$scrollBarY = _this.scrollBarY) === null || _this$scrollBarY === void 0 ? void 0 : _this$scrollBarY.css('top')) || '0')
});
_this.oWidth = _this.getWidth();
_this.reRenderShadow(left);
}
};
_this.reRenderY = function (top) {
if (_this.y) {
var _this$scrollBarY2, _this$slideY6, _this$scrollBarX2;
(_this$scrollBarY2 = _this.scrollBarY) === null || _this$scrollBarY2 === void 0 ? void 0 : _this$scrollBarY2.css('top', top + 'px');
var value = _this.sHeight - _this.oHeight;
var min = value <= 0 ? 0 : top / value;
min = Math.min(1, min);
(_this$slideY6 = _this.slideY) === null || _this$slideY6 === void 0 ? void 0 : _this$slideY6.css('top', (_this.oHeight - _this.yHeight) * min + 'px');
_this.emit('change', {
x: removeUnit(((_this$scrollBarX2 = _this.scrollBarX) === null || _this$scrollBarX2 === void 0 ? void 0 : _this$scrollBarX2.css('left')) || '0'),
y: top
});
}
};
_this.container = isNode(container) ? $(container) : container;
_this.x = _x;
_this.y = y;
_this.shadow = shadow;
_classPrivateFieldLooseBase(_assertThisInitialized(_this), _scroll)[_scroll] = scroll;
_this.init();
return _this;
}
/**
* 设置滚动条内容节点
* @param content
*/
_createClass(Scrollbar, [{
key: "setContentNode",
value: function setContentNode(content) {
_classPrivateFieldLooseBase(this, _content)[_content] = content ? isNode(content) ? $(content) : content : content;
}
}, {
key: "init",
value: function init() {
var children = this.container.children();
var hasScrollbar = false;
children.each(function (child) {
if (!hasScrollbar && $(child).hasClass('data-scrollbar')) {
hasScrollbar = true;
}
});
if (!hasScrollbar) {
this.container.css('position', 'relative');
this.container.addClass('data-scrollable');
if (this.x) {
this.scrollBarX = $(""));
this.slideX = this.scrollBarX.find('.data-scrollbar-trigger');
this.container.append(this.scrollBarX);
this.container.addClass('scroll-x');
}
if (this.y) {
this.scrollBarY = $(""));
this.slideY = this.scrollBarY.find('.data-scrollbar-trigger');
this.container.append(this.scrollBarY);
this.container.addClass('scroll-y');
}
if (this.shadow) {
this.shadowLeft = $(""));
this.shadowRight = $(""));
this.container.append(this.shadowLeft);
this.container.append(this.shadowRight);
}
this.refresh();
this.bindEvents();
}
}
}, {
key: "getWidth",
value: function getWidth() {
var _classPrivateFieldLoo6;
var element = this.container.get();
if (!element) return 0;
var width = this.container.width();
var offsetWidth = ((_classPrivateFieldLoo6 = _classPrivateFieldLooseBase(this, _scroll)[_scroll]) === null || _classPrivateFieldLoo6 === void 0 ? void 0 : _classPrivateFieldLoo6.getOffsetWidth) ? _classPrivateFieldLooseBase(this, _scroll)[_scroll].getOffsetWidth(width) : width;
return offsetWidth;
}
}, {
key: "enableScroll",
value:
/**
* 启用鼠标在内容节点上滚动或在移动设备使用手指滑动
*/
function enableScroll() {
_classPrivateFieldLooseBase(this, _enableScroll)[_enableScroll] = true;
}
/**
* 禁用鼠标在内容节点上滚动或在移动设备使用手指滑动
*/
}, {
key: "disableScroll",
value: function disableScroll() {
_classPrivateFieldLooseBase(this, _enableScroll)[_enableScroll] = false;
}
}, {
key: "bindEvents",
value: function bindEvents() {
if (isMobile) {
// 在节点上滑动手指
if (this.x) {
this.container.on('touchstart', this.bindContainerTouchX, {
passive: true
});
}
if (this.y) {
this.container.on('touchstart', this.bindContainerTouchY, {
passive: true
});
}
} else {
// 在节点上滚动鼠标滚轮
this.container.on(isFirefox ? 'DOMMouseScroll' : 'mousewheel', this.bindWheelScroll);
}
this.container.on('scroll', this.scroll, {
passive: true
});
var containerElement = this.container.get();
if (!containerElement) return; // this.#observer = new ResizeObserver(() => {
// console.log('resize')
// this.refresh();
// });
// this.#observer.observe(containerElement);
window.addEventListener('resize', this.refresh); // 绑定滚动条事件
this.bindXScrollEvent();
this.bindYScrollEvent();
}
/**
* 获取鼠标事件或者触摸事件的 clientX clientY
* @param event
* @returns
*/
}, {
key: "destroy",
value: function destroy() {
var _this$slideX7, _this$slideY7, _classPrivateFieldLoo7;
(_this$slideX7 = this.slideX) === null || _this$slideX7 === void 0 ? void 0 : _this$slideX7.off(isMobile ? 'touchstart' : 'mousedown', this.scrollXStart);
(_this$slideY7 = this.slideY) === null || _this$slideY7 === void 0 ? void 0 : _this$slideY7.off(isMobile ? 'touchstart' : 'mousedown', this.scrollYStart);
if (isMobile) {
if (this.x) this.container.off('touchstart', this.bindContainerTouchX);
if (this.y) this.container.off('touchstart', this.bindContainerTouchY);
} else {
this.container.off(isFirefox ? 'DOMMouseScroll' : 'mousewheel', this.bindWheelScroll);
}
this.container.off('scroll', this.scroll);
this.container.removeClass('data-scrollable');
if (this.x) {
var _this$scrollBarX3;
(_this$scrollBarX3 = this.scrollBarX) === null || _this$scrollBarX3 === void 0 ? void 0 : _this$scrollBarX3.remove();
this.container.removeClass('scroll-x');
}
if (this.y) {
var _this$scrollBarY3;
(_this$scrollBarY3 = this.scrollBarY) === null || _this$scrollBarY3 === void 0 ? void 0 : _this$scrollBarY3.remove();
this.container.removeClass('scroll-y');
}
if (this.shadow) {
var _this$shadowLeft3, _this$shadowRight3;
(_this$shadowLeft3 = this.shadowLeft) === null || _this$shadowLeft3 === void 0 ? void 0 : _this$shadowLeft3.remove();
(_this$shadowRight3 = this.shadowRight) === null || _this$shadowRight3 === void 0 ? void 0 : _this$shadowRight3.remove();
}
(_classPrivateFieldLoo7 = _classPrivateFieldLooseBase(this, _observer$1)[_observer$1]) === null || _classPrivateFieldLoo7 === void 0 ? void 0 : _classPrivateFieldLoo7.disconnect();
window.removeEventListener('resize', this.refresh);
window.removeEventListener('scroll', this.refresh);
}
}]);
return Scrollbar;
}(EventEmitter2.EventEmitter2);
var css_248z$b = ".data-resizer {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n bottom: 0px;\n right: 0;\n z-index: 1;\n outline: 2px solid #1890FF;\n max-width: initial !important;\n}\n.data-resizer img {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n cursor: pointer;\n width: 100%;\n height: 100%;\n opacity: 0.3;\n}\n.data-resizer-holder {\n position: absolute;\n width: 14px;\n height: 14px;\n border: 2px solid #fff;\n border-radius: 50%;\n background: #1890FF;\n display: inline-block;\n}\n.data-resizer-holder-right-top {\n top: -6px;\n right: -6px;\n cursor: nesw-resize;\n}\n.data-resizer-holder-right-bottom {\n bottom: -6px;\n right: -6px;\n cursor: nwse-resize;\n}\n.data-resizer-holder-left-bottom {\n bottom: -6px;\n left: -6px;\n cursor: nesw-resize;\n}\n.data-resizer-holder-left-top {\n left: -6px;\n top: -6px;\n cursor: nwse-resize;\n}\n\n.data-resizer-number {\n position: absolute;\n display: inline-block;\n line-height: 24px;\n padding: 0 4px;\n font-size: 12px;\n border-radius: 3px 3px;\n background: rgba(0, 0, 0, 0.86);\n color: rgba(255, 255, 255, 0.96);\n font-family: 'Lucida Console', Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;\n opacity: 0;\n visibility: hidden;\n transition: opacity 0.3s ease-in-out;\n transform: scale(0.8);\n}\n\n.data-resizer-number-right-top {\n top: 0px;\n right: -6px;\n transform: translateX(100%) scale(0.8);\n}\n\n.data-resizer-number-right-bottom {\n right: -6px;\n bottom: 0px;\n transform: translateX(100%) scale(0.8);\n}\n\n.data-resizer-number-left-bottom {\n left: -6px;\n bottom: 0px;\n transform: translateX(-100%) scale(0.8);\n}\n\n.data-resizer-number-left-top {\n left: -6px;\n top: 0px;\n transform: translateX(-100%) scale(0.8);\n}\n\n.data-resizer-number-active {\n opacity: 1;\n visibility: visible;\n}";
styleInject(css_248z$b);
var Resizer = /*#__PURE__*/function () {
/**
* 是否改变大小中
*/
function Resizer(options) {
var _this = this,
_this$image2;
_classCallCheck(this, Resizer);
this.options = void 0;
this.root = void 0;
this.image = void 0;
this.resizerNumber = void 0;
this.point = {
x: 0,
y: 0
};
this.position = void 0;
this.size = void 0;
this.maxWidth = void 0;
this.resizing = false;
this.onMouseMove = function (event) {
event.preventDefault();
event.stopPropagation();
var _ref = window.TouchEvent && event instanceof TouchEvent ? event.touches[0] : event,
clientX = _ref.clientX,
clientY = _ref.clientY;
if (clientX !== _this.point.x || clientY !== _this.point.y) {
//移动后的宽度
var width = _this.point.x - clientX; //移动后的高度
var height = _this.point.y - clientY;
_this.updateSize(width, height);
}
_this.resizing = true;
};
this.onMouseUp = function (event) {
var _this$image;
event.preventDefault();
event.stopPropagation();
var root = _this.root.get();
if (!root) return;
var clientWidth = root.clientWidth,
clientHeight = root.clientHeight;
_this.size = {
width: clientWidth,
height: clientHeight
};
_this.resizerNumber.removeClass("data-resizer-number-".concat(_this.position));
_this.resizerNumber.removeClass('data-resizer-number-active');
_this.position = undefined;
_this.resizing = false;
_this.root.removeClass('data-resizing');
document.removeEventListener(isMobile ? 'touchmove' : 'mousemove', _this.onMouseMove);
document.removeEventListener(isMobile ? 'touchend' : 'mouseup', _this.onMouseUp);
var onChange = _this.options.onChange;
if (onChange) onChange(_this.size);
(_this$image = _this.image) === null || _this$image === void 0 ? void 0 : _this$image.hide();
};
this.options = options;
this.root = $(this.renderTemplate(options.imgUrl));
if (options.imgUrl) this.image = this.root.find('img');
(_this$image2 = this.image) === null || _this$image2 === void 0 ? void 0 : _this$image2.hide();
this.resizerNumber = this.root.find('.data-resizer-number');
var _this$options = this.options,
_width = _this$options.width,
_height = _this$options.height;
this.size = {
width: _width,
height: _height
};
this.maxWidth = this.options.maxWidth;
}
_createClass(Resizer, [{
key: "renderTemplate",
value: function renderTemplate(imgUrl) {
return "\n\t\t\t\n\t\t\t\t".concat(imgUrl ? "") : '', "\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t");
}
}, {
key: "onMouseDown",
value: function onMouseDown(event, position) {
var _this$image3;
if (this.resizing) return;
event.preventDefault();
event.stopPropagation();
this.root.css('top', ['right-top', 'left-top'].indexOf(position) > -1 ? 'auto' : 0);
this.root.css('left', ['left-top', 'left-bottom'].indexOf(position) > -1 ? 'auto' : 0);
this.root.css('bottom', ['right-bottom', 'left-bottom'].indexOf(position) > -1 ? 'auto' : 0);
this.root.css('right', ['right-top', 'right-bottom'].indexOf(position) > -1 ? 'auto' : 0);
this.point = {
x: window.TouchEvent && event instanceof TouchEvent ? event.touches[0].clientX : event.clientX,
y: window.TouchEvent && event instanceof TouchEvent ? event.touches[0].clientY : event.clientY
};
this.position = position;
this.resizing = true;
this.root.addClass('data-resizing');
this.resizerNumber.addClass("data-resizer-number-".concat(this.position));
this.resizerNumber.addClass('data-resizer-number-active');
(_this$image3 = this.image) === null || _this$image3 === void 0 ? void 0 : _this$image3.show();
document.addEventListener(isMobile ? 'touchmove' : 'mousemove', this.onMouseMove);
document.addEventListener(isMobile ? 'touchend' : 'mouseup', this.onMouseUp);
}
}, {
key: "updateSize",
value: function updateSize(width, height) {
if (['right-top', 'right-bottom'].indexOf(this.position || '') > -1) {
width = this.size.width - width;
} else {
width = this.size.width + width;
}
this.setSize(width, height);
}
}, {
key: "setSize",
value: function setSize(width, height) {
if (width < 24) {
width = 24;
}
var rate = this.options.rate;
if (width > this.maxWidth) {
width = this.maxWidth;
}
height = width * rate;
if (height < 24) {
height = 24;
width = height / rate;
}
width = Math.round(width);
height = Math.round(height);
this.root.css({
width: width + 'px',
height: height + 'px'
});
this.resizerNumber.html("".concat(width, "\xB7").concat(height));
}
}, {
key: "on",
value: function on(eventType, listener) {
this.root.on(eventType, listener);
}
}, {
key: "off",
value: function off(eventType, listener) {
this.root.off(eventType, listener);
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var _this$options2 = this.options,
width = _this$options2.width,
height = _this$options2.height;
this.setSize(width, height);
this.root.find('.data-resizer-holder-right-top').on(isMobile ? 'touchstart' : 'mousedown', function (event) {
return _this2.onMouseDown(event, 'right-top');
});
this.root.find('.data-resizer-holder-right-bottom').on(isMobile ? 'touchstart' : 'mousedown', function (event) {
return _this2.onMouseDown(event, 'right-bottom');
});
this.root.find('.data-resizer-holder-left-bottom').on(isMobile ? 'touchstart' : 'mousedown', function (event) {
return _this2.onMouseDown(event, 'left-bottom');
});
this.root.find('.data-resizer-holder-left-top').on(isMobile ? 'touchstart' : 'mousedown', function (event) {
return _this2.onMouseDown(event, 'left-top');
});
return this.root;
}
}, {
key: "destroy",
value: function destroy() {
this.root.remove();
document.removeEventListener('mousemove', this.onMouseMove);
document.removeEventListener('mouseup', this.onMouseUp);
}
}]);
return Resizer;
}();
Object.defineProperty(exports, 'isHotkey', {
enumerable: true,
get: function () {
return isHotkey__default['default'];
}
});
exports.$ = $;
exports.ANCHOR = ANCHOR;
exports.ANCHOR_SELECTOR = ANCHOR_SELECTOR;
exports.Ajax = Ajax;
exports.BlockPlugin = BlockEntry;
exports.CARD_CENTER_SELECTOR = CARD_CENTER_SELECTOR;
exports.CARD_EDITABLE_KEY = CARD_EDITABLE_KEY;
exports.CARD_ELEMENT_KEY = CARD_ELEMENT_KEY;
exports.CARD_KEY = CARD_KEY;
exports.CARD_LEFT_SELECTOR = CARD_LEFT_SELECTOR;
exports.CARD_LOADING_KEY = CARD_LOADING_KEY;
exports.CARD_RIGHT_SELECTOR = CARD_RIGHT_SELECTOR;
exports.CARD_SELECTOR = CARD_SELECTOR;
exports.CARD_TAG = CARD_TAG;
exports.CARD_TYPE_KEY = CARD_TYPE_KEY;
exports.CARD_VALUE_KEY = CARD_VALUE_KEY;
exports.CURSOR = CURSOR;
exports.CURSOR_SELECTOR = CURSOR_SELECTOR;
exports.Card = CardEntry;
exports.CollaborationMember = CollaborationMember;
exports.Conversion = defaultConversion;
exports.DATA_COLOR = DATA_COLOR;
exports.DATA_CONTENTEDITABLE_KEY = DATA_CONTENTEDITABLE_KEY;
exports.DATA_ELEMENT = DATA_ELEMENT;
exports.DATA_ID = DATA_ID;
exports.DATA_TRANSIENT_ATTRIBUTES = DATA_TRANSIENT_ATTRIBUTES;
exports.DATA_TRANSIENT_ELEMENT = DATA_TRANSIENT_ELEMENT;
exports.DATA_UUID = DATA_UUID;
exports.EDITABLE = EDITABLE;
exports.EDITABLE_SELECTOR = EDITABLE_SELECTOR;
exports.ENGINE_CLASS_NAME = ENGINE_CLASS_NAME;
exports.ENGINE_MOBILE_CLASS_NAME = ENGINE_MOBILE_CLASS_NAME;
exports.Element = Element$1;
exports.ElementPlugin = ElementPluginEntry;
exports.FOCUS = FOCUS;
exports.FOCUS_SELECTOR = FOCUS_SELECTOR;
exports.InlinePlugin = InlineEntry;
exports.ListPlugin = ListEntry;
exports.MarkPlugin = MarkEntry;
exports.Model = Model;
exports.Node = Node$1;
exports.Operation = Operation;
exports.Parser = Parser;
exports.Path = Path;
exports.Plugin = PluginEntry;
exports.Position = Position;
exports.READY_CARD_KEY = READY_CARD_KEY;
exports.READY_CARD_SELECTOR = READY_CARD_SELECTOR;
exports.ROOT = ROOT;
exports.ROOT_SELECTOR = ROOT_SELECTOR;
exports.Range = Range;
exports.Request = Request;
exports.Resizer = Resizer;
exports.Schema = defualtSchema;
exports.Scrollbar = Scrollbar;
exports.Selection = Selection;
exports.TRIGGER_CARD_ID = TRIGGER_CARD_ID;
exports.Text = Text$1;
exports.TinyCanvas = TinyCanvas;
exports.Toolbar = Toolbar;
exports.Tooltip = Tooltip;
exports.UI = UI;
exports.UI_SELECTOR = UI_SELECTOR;
exports.Uploader = Uploader;
exports.VIEW_CLASS_NAME = VIEW_CLASS_NAME;
exports.View = View;
exports.addUnit = addUnit;
exports.closest = closest;
exports.combinText = combinText;
exports.convertMarkdown = convertMarkdown;
exports.createMarkdownIt = createMarkdownIt;
exports.decodeCardValue = decodeCardValue;
exports.default = Engine;
exports.encodeCardValue = encodeCardValue;
exports.escape = escape;
exports.escapeDots = escapeDots;
exports.formatEngineValue = formatEngineValue;
exports.formatHotkey = formatHotkey;
exports.getAttrMap = getAttrMap;
exports.getComputedStyle = getComputedStyle;
exports.getDocument = getDocument;
exports.getExtensionName = getExtensionName;
exports.getFileSize = getFileSize;
exports.getHashId = hashId;
exports.getListStyle = getListStyle;
exports.getParentInRoot = getParentInRoot;
exports.getStyleMap = getStyleMap;
exports.getTextNodes = getTextNodes;
exports.inEditor = inEditor;
exports.isAndroid = isAndroid;
exports.isBlockCard = isBlockCard;
exports.isBlockPlugin = isBlockPlugin;
exports.isCard = isCard;
exports.isChrome = isChrome;
exports.isCursor = isCursor;
exports.isEdge = isEdge;
exports.isEditable = isEditable;
exports.isEditableCard = isEditableCard;
exports.isEngine = isEngine;
exports.isFirefox = isFirefox;
exports.isInlineCard = isInlineCard;
exports.isInlinePlugin = isInlinePlugin;
exports.isIos = isIos;
exports.isMacos = isMacos;
exports.isMarkPlugin = isMarkPlugin;
exports.isMatchesSelector = isMatchesSelector;
exports.isMobile = isMobile;
exports.isNode = isNode;
exports.isNodeEntry = isNodeEntry;
exports.isNodeList = isNodeList;
exports.isPlainObject = isPlainObject;
exports.isRange = isRange;
exports.isRangeInterface = isRangeInterface;
exports.isRoot = isRoot;
exports.isSafari = isSafari;
exports.isSelection = isSelection;
exports.isServer = isServer;
exports.isTransientAttribute = isTransientAttribute;
exports.isTransientElement = isTransientElement;
exports.isTransientElementCache = isTransientElementCache;
exports.isView = isView;
exports.isWindows = isWindows;
exports.random = random;
exports.removeUnit = removeUnit;
exports.sanitizeUrl = sanitizeUrl;
exports.toCamelCase = toCamelCase;
exports.toHex = toHex;
exports.transformCustomTags = transformCustomTags;
exports.unescape = unescape;
exports.unescapeDots = unescapeDots;
exports.uuid = uuid;
exports.validUrl = validUrl;