UNPKG

prism-code-editor

Version:

Lightweight, extensible code editor component for the web using Prism

94 lines (93 loc) 3.17 kB
import { r as regexEscape } from "./index-2teoWRgh.js"; import { a as createTemplate } from "./index-Bb4AMnd0.js"; const template = createTemplate( '<div style="color:#0000;display:none;contain:strict;padding:0 var(--_pse) 0 var(--padding-left)" aria-hidden=true>' ); const matchTemplate = createTemplate("<span> "); const testBoundary = (str, position, pattern = /[_\p{N}\p{L}]{2}/u) => { if (!position) return false; return pattern.test( str.slice( position - (str.codePointAt(position - 2) > 65535 ? 2 : 1), position + (str.codePointAt(position) > 65535 ? 2 : 1) ) ); }; const createSearchAPI = (editor) => { const nodes = [new Text()], nodeValues = [], container = template(), matchPositions = [], stopSearch = () => { if (matchPositions[0]) { matchPositions.length = 0; container.style.display = "none"; } }; let regex; let nodeCount = 0; editor.overlays.append(container); return { search(str, caseSensitive, wholeWord, useRegExp, selection, filter, pattern) { if (!str) return stopSearch(); if (!useRegExp) str = regexEscape(str); const value = editor.value; const searchStr = selection ? value.slice(...selection) : value; const offset = selection ? selection[0] : 0; let match; let l; let index; let i = 0; try { regex = RegExp(str, `gum${caseSensitive ? "" : "i"}`); while (match = regex.exec(searchStr)) { l = match[0].length; index = match.index + offset; if (!l) regex.lastIndex += value.codePointAt(index) > 65535 ? 2 : 1; if (wholeWord && (testBoundary(value, index, pattern) || testBoundary(value, index + l, pattern))) continue; if (!filter || filter(index, index + l)) matchPositions[i++] = [index, index + l]; } } catch (e) { stopSearch(); return e.message; } if (i) { matchPositions.length = i; l = Math.min(i * 2, 2e4); for (let i2 = nodes.length; i2 <= l; ) { nodes[i2++] = matchTemplate(); nodes[i2++] = new Text(); } for (let i2 = nodeCount - 1; i2 > l; ) nodes[i2--].remove(); if (nodeCount <= l) container.append(...nodes.slice(nodeCount, l + 1)); for (let i2 = 0, prevEnd = 0; i2 < l; ++i2) { const [start, end] = matchPositions[i2 / 2]; const before = value.slice(prevEnd, start); const match2 = value.slice(start, prevEnd = end); if (before != nodeValues[i2]) nodes[i2].data = nodeValues[i2] = before; if (match2 != nodeValues[++i2]) nodes[i2].firstChild.data = nodeValues[i2] = match2; } nodes[l].data = nodeValues[l] = value.slice(matchPositions[l / 2 - 1][1]); container.style.display = ""; nodeCount = l + 1; } else stopSearch(); }, container, get regex() { return regex; }, matches: matchPositions, stopSearch }; }; export { createSearchAPI as c }; //# sourceMappingURL=search-DMBoe0SI.js.map