import { escape } from "lodash-es"; const CODE_BLOCK_REG = /```([\s\S]*?)```\n?/g; const BOLD_TEXT_REG = /\*\*(.+?)\*\*/g; const EM_TEXT_REG = /\*(.+?)\*/g; const DOT_LI_REG = /[*-] /g; const NUM_LI_REG = /(\d+)\. /g; export const TODO_BLOCK_REG = /- \[ \] /g; export const DONE_BLOCK_REG = /- \[x\] /g; // tag regex export const TAG_REG = /#([^\s#]+?) /g; // markdown image regex export const IMAGE_URL_REG = /!\[.*?\]\((.+?)\)\n?/g; // markdown link regex export const LINK_URL_REG = /\[(.*?)\]\((.+?)\)/g; // linked memo regex export const MEMO_LINK_REG = /@\[(.+?)\]\((.+?)\)/g; const parseMarkedToHtml = (markedStr: string): string => { const htmlText = markedStr .replace(/([\u4e00-\u9fa5])([A-Za-z0-9?.,;[\]]+)/g, "$1 $2") .replace(/([A-Za-z0-9?.,;[\]]+)([\u4e00-\u9fa5])/g, "$1 $2") .replace(CODE_BLOCK_REG, "
$1
") .replace(TODO_BLOCK_REG, "") .replace(DONE_BLOCK_REG, "") .replace(DOT_LI_REG, "") .replace(NUM_LI_REG, "$1.") .replace(BOLD_TEXT_REG, "$1") .replace(EM_TEXT_REG, "$1"); return htmlText; }; const parseHtmlToRawText = (htmlStr: string): string => { const tempEl = document.createElement("div"); tempEl.className = "memo-content-text"; tempEl.innerHTML = htmlStr; const text = tempEl.innerText; return text; }; interface FormatterConfig { inlineImage: boolean; } const defaultFormatterConfig: FormatterConfig = { inlineImage: false, }; const formatMemoContent = (content: string, addtionConfig?: Partial) => { const config = { ...defaultFormatterConfig, ...addtionConfig, }; const tempElement = document.createElement("div"); tempElement.innerHTML = parseMarkedToHtml(escape(content)); let outputString = tempElement.innerHTML; if (config.inlineImage) { outputString = outputString.replace(IMAGE_URL_REG, ""); } else { outputString = outputString.replace(IMAGE_URL_REG, ""); } return outputString .replace(MEMO_LINK_REG, "$1") .replace(LINK_URL_REG, "$1") .replace(TAG_REG, "#$1 "); }; export { formatMemoContent, parseHtmlToRawText };