UNPKG

monogon

Version:

Modern syntax highlighting for developer tooling

57 lines 1.77 kB
/** * Calculates ranges to highlight based on regex * * @param {RegExp} search * @param {HTMLElement} element * * @return Range[] */ export const getRanges = (search, element) => { const textNode = element.childNodes[0]; const content = textNode.textContent?.toLowerCase(); if (!content) return []; const indexes = []; const matches = [...content.matchAll(search)]; matches.forEach((match) => { indexes.push({ s: match.index, e: match.index + match[0].length }); }); return indexes.map((index) => { const range = new Range(); range.setStart(textNode, index.s); range.setEnd(textNode, index.e); return range; }); }; /** * Creates function that applies highlights to element */ const createHighlightFn = (name, highlight, el, scope) => { return CSS.highlights.set(`${name}-${scope}`, new Highlight(...getRanges(highlight.regex, el))); }; /** * Creates css ::highlight {} node */ const createHighlightCss = (name, highlight, scope) => { return `::highlight(${name}-${scope}) { color: var(${highlight.css}); }`; }; /** * Converts highlight definitions to usable module */ export const transformModule = (highlights, codeNode, scope) => { return Object.entries(highlights).map(([name, definition]) => ({ apply: () => createHighlightFn(name, definition, codeNode, scope), css: createHighlightCss(name, definition, scope), })); }; export const monoLog = (message, error = false) => { if (import.meta.env.DEV) { if (!error) { console.warn('%c [monogon]', 'color: #56b9c8', message); } else { console.error('%c [monogon]', 'color: #56b9c8', message); } } }; //# sourceMappingURL=utils.js.map