import { REGEXP, IMAGE_SPLIT } from "./constant"; import emoji, { prefixUrl, ext } from "./emoji"; const emojiObejct = arrayToObject(emoji, "title"); export function isFunction(functionToCheck) { return ( functionToCheck && {}.toString.call(functionToCheck) === "[object Function]" ); } export function isUrl(userInput) { const regexp = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/g; var res = userInput.match(regexp); if (res === null) return false; else return true; } /** * 将对象数组转换为对象 * @param {array} array Array of Objects * @param {string} keyField string */ export function arrayToObject(array, keyField) { return array.reduce((obj, item) => { obj[item[keyField]] = item; return obj; }, {}); } /** * HTML 编码 * 将 < > 等字符串进行编码 * @param {string} str 文本 */ export function htmlEncode(str) { if (!str) return ""; return str.replace(/<>/gim, function(i) { return "&#" + i.charCodeAt(0) + ";"; }); } /** * 渲染编辑器 * [x] => * @param {strig} content */ export function renderContent(content, onClick) { let newContent = content; if (newContent.indexOf(IMAGE_SPLIT) !== -1) { newContent = newContent.split(IMAGE_SPLIT); newContent.pop(); newContent = newContent.join(""); } return htmlEncode(newContent).replace(REGEXP, function(a, b) { const src = a.slice(1, -1); // 兼容旧的评 // 因为旧的评论用 [img url] 方式存储的 if (isUrl(src)) { return `
${src}`; } const value = emojiObejct[src] ? emojiObejct[src].value : src; return `${value}`; }); }