highlight-chars.js (1621B)
1 "use strict"; 2 3 /** 4 * Find characters in a container and creates CSS Highlights for them. 5 * @param {Node} container - The container node to search within. 6 */ 7 function highlightChars(container) { 8 const chars = { 9 "「": "open", 10 "」": "close", 11 "(": "open", 12 ")": "close", 13 "。": "dot", 14 "、": "dot", 15 ".": "dot", 16 ",": "dot", 17 ":": "colon", 18 ";": "colon", 19 }; 20 const style = [ 21 "::highlight(open) { background-color: orange; }", 22 "::highlight(close) { background-color: springgreen; }", 23 "::highlight(dot) { background-color: skyblue; }", 24 "::highlight(colon) { background-color: wheat; }", 25 ].join("\n"); 26 const style_element = document.createElement("style"); 27 style_element.textContent = style; 28 document.head.appendChild(style_element); 29 30 const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT); 31 while (walker.nextNode()) { 32 const textNode = walker.currentNode; 33 const text = textNode.nodeValue; 34 for (let i = 0; i < text.length; ++i) { 35 const char = text[i]; 36 const name = chars[char]; 37 if (!name) { 38 continue; 39 } 40 let highlight = CSS.highlights.get(name); 41 if (!highlight) { 42 highlight = new Highlight(); 43 CSS.highlights.set(name, highlight); 44 } 45 const range = document.createRange(); 46 range.setStart(textNode, i); 47 range.setEnd(textNode, i + 1); 48 highlight.add(range); 49 } 50 } 51 } 52 53 window.addEventListener("load", () => { 54 const container = document.getElementById("container"); 55 highlightChars(container ? container : document.body); 56 });