import { DirectiveBinding } from 'vue';
const DEFAULT_HIGHLIGHT = 'text-[#F5313E]';
export const clearEm = (content = '') => { return content && typeof content === 'string' ? content.replace(/<em>(.*?)<\/em>/g, '$1') : content; };
export const clearHighlight = (content = '', highlightClass = DEFAULT_HIGHLIGHT) => { return content && typeof content === 'string' ? content.replace(new RegExp(`<span class="${highlightClass}">(.*?)<\/span>`, 'gi'), '$1') : content; };
export const clearAllHighlight = (content = '', highlightClass = DEFAULT_HIGHLIGHT) => { return content ? clearEm(clearHighlight(content, highlightClass)) : content; };
export function escapeRegExp(content = '') { return content && typeof content === 'string' ? content.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : content; }
const setHighlight = ( content = '', keyword: string | string[], highlightClass = DEFAULT_HIGHLIGHT, ) => { content = clearHighlight(content, highlightClass) || ''; if (typeof keyword === 'string' && keyword) { const regex = new RegExp(`(${escapeRegExp(keyword)})`, 'gi'); return content.replace(regex, `<span class="${highlightClass}">$1</span>`); } else if (Array.isArray(keyword) && keyword.includes(content)) { return `<span class="${highlightClass}">${content}</span>`; } else { return content.replace(/<em>(.*?)<\/em>/g, `<span class="${highlightClass}">$1</span>`); } };
const handleHighlight = (el: HTMLElement, binding: DirectiveBinding) => {
const { clear = false, keyword = false } = binding.modifiers;
const content = binding.value || el.textContent || ''; const highlightClass = binding.arg || DEFAULT_HIGHLIGHT;
if (clear) { el.innerHTML = clearAllHighlight(content, highlightClass); } else if (keyword) { const { text = '', keyword: keywordText } = binding.value; const replaceContent = setHighlight(clearEm(text || ''), keywordText, highlightClass); el.innerHTML = replaceContent; } else if (/<em>(.*?)<\/em>/g.test(content)) { const replaceContent = setHighlight(content, '', highlightClass); el.innerHTML = replaceContent; } else { el.innerHTML = content; } };
export const vHighlight = { mounted(el: HTMLElement, binding: DirectiveBinding) { handleHighlight(el, binding); }, updated(el: HTMLElement, binding: DirectiveBinding) { handleHighlight(el, binding); }, };
|