2022-06-21 17:19:12 +05:30
|
|
|
const TEXT_NODE = 3;
|
|
|
|
|
|
|
|
const isTextNode = ({ nodeType }) => nodeType === TEXT_NODE;
|
|
|
|
|
|
|
|
const isBlank = (str) => !str || /^\s*$/.test(str);
|
|
|
|
|
|
|
|
const isMatch = (s1, s2) => !isBlank(s1) && s1.trim() === s2.trim();
|
|
|
|
|
2022-11-25 23:54:43 +05:30
|
|
|
const createSpan = (content, classList) => {
|
2022-06-21 17:19:12 +05:30
|
|
|
const span = document.createElement('span');
|
|
|
|
span.innerText = content;
|
2022-11-25 23:54:43 +05:30
|
|
|
span.classList = classList || '';
|
2022-06-21 17:19:12 +05:30
|
|
|
return span;
|
|
|
|
};
|
|
|
|
|
2022-11-25 23:54:43 +05:30
|
|
|
const wrapSpacesWithSpans = (text) =>
|
|
|
|
text.replace(/ /g, createSpan(' ').outerHTML).replace(/\t/g, createSpan(' ').outerHTML);
|
2022-06-21 17:19:12 +05:30
|
|
|
|
2022-11-25 23:54:43 +05:30
|
|
|
const wrapTextWithSpan = (el, text, classList) => {
|
2022-06-21 17:19:12 +05:30
|
|
|
if (isTextNode(el) && isMatch(el.textContent, text)) {
|
2022-11-25 23:54:43 +05:30
|
|
|
const newEl = createSpan(text.trim(), classList);
|
2022-06-21 17:19:12 +05:30
|
|
|
el.replaceWith(newEl);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-11-25 23:54:43 +05:30
|
|
|
const wrapNodes = (text, classList) => {
|
2022-06-21 17:19:12 +05:30
|
|
|
const wrapper = createSpan();
|
2022-10-11 01:57:18 +05:30
|
|
|
// eslint-disable-next-line no-unsanitized/property
|
2022-06-21 17:19:12 +05:30
|
|
|
wrapper.innerHTML = wrapSpacesWithSpans(text);
|
2022-11-25 23:54:43 +05:30
|
|
|
wrapper.childNodes.forEach((el) => wrapTextWithSpan(el, text, classList));
|
2022-06-21 17:19:12 +05:30
|
|
|
return wrapper.childNodes;
|
|
|
|
};
|
|
|
|
|
|
|
|
export { wrapNodes, isTextNode };
|