UNPKG

@alifd/adaptor-helper

Version:
93 lines (79 loc) 2.09 kB
import { STATE_MARK } from "./state-mark"; export var NodeType; (function (NodeType) { NodeType["divider"] = "divider"; NodeType["node"] = "node"; NodeType["comment"] = "comment"; })(NodeType || (NodeType = {})); export var ContentType; (function (ContentType) { ContentType["text"] = "text"; ContentType["icon"] = "icon"; })(ContentType || (ContentType = {})); var getChildren = function getChildren() { var template = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; if (!template) { return []; } return template.replace(/(\[.*?\])/g, "\n$1\n").split("\n").filter(function (v) { return !!v; }).map(function (d) { switch (true) { case /^\[(.*)\]$/.test(d): return { type: "icon", value: RegExp.$1 }; default: return { type: "text", value: d }; } }); }; export var parseData = function parseData(text) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { parseContent: false }; if (!text) { return []; } var root = { type: NodeType.node, state: "normal", value: "", children: [] }; var stack = [root]; text.split("\n").filter(function (line) { return line.trim(); }).forEach(function (line) { var re = /^(\t*)([#\-~*]?)(.*)$/.exec(line); var indent = (re[1] || "").length; var prefix = re[2] || ""; var item = { type: NodeType.node, state: "normal", value: re[3] || "", children: [] }; if (prefix === "-" && /^-{2,}$/.test(item.value)) { item.type = NodeType.divider; } else if (prefix === "#") { item.type = NodeType.comment; } else { item.state = STATE_MARK[prefix]; } if (item.type === "node" && options.parseContent) { item.value = getChildren(item.value); } while (indent <= stack.length - 2) { stack.pop(); } stack[stack.length - 1].children.push(item); stack.push(item); }); return root.children; }; export default parseData;