Debian Codegraph @

pua2ot/src/pua2ot-embed.js

raw
1 /*
2 PUA2OT: A utility for converting MUFI PUA characters to standard
3 Unicode with Junicode's OpenType features.
4
5 Code for converting a web page on the fly.
6
7 Copyright © 2025-26 by Peter S. Baker
8 Licensed under the Apache License, version 2.0:
9 https://www.apache.org/licenses/LICENSE-2.0
10 */
11
12 /**
13 * Finds all text nodes in the <body> of an
14 * html file and calls convert() to convert them all. Sets
15 * the language automatically if there is a lang attribute on the <body>
16 * or <html> element.
17 */
18 function convertAll() {
19 if (document.body.hasAttribute("lang")) {
20 options.language = document.body.getAttribute("lang")
21 } else if (document.documentElement.hasAttribute("lang")) {
22 options.language = document.documentElement.getAttribute("lang")
23 }
24 console.time("PUATimer");
25
26 let replacements = [];
27
28 document.body.lang = options.language;
29
30 const walker = document.createTreeWalker(
31 document.body,
32 NodeFilter.SHOW_TEXT,
33 {
34 acceptNode: function(node) {
35 if (node.nodeType === Node.TEXT_NODE) {
36 // Only accept text nodes that are not purely whitespace, for example
37 if (node.nodeValue.trim().length > 0) {
38 return NodeFilter.FILTER_ACCEPT;
39 }
40 }
41 return NodeFilter.FILTER_SKIP; // Skip other nodes or empty text nodes
42 }
43 }
44 )
45 let node;
46 while ((node = walker.nextNode())) {
47 let nv = node.nodeValue;
48 let parentEl = node.parentElement;
49 if (parentEl.classList.contains("noconv")) {
50 continue;
51 }
52 nv = cleanup_string(nv);
53 if (nv.length > 0) {
54 const hasLeadingWhitespace = /^\s/.test(nv);
55 const hasTrailingWhitespace = /\s$/.test(nv);
56 const leading = hasLeadingWhitespace ? " " : "";
57 const trailing = hasTrailingWhitespace ? " " : "";
58 nv = convert(nv, true, false);
59 newSpan = document.createElement("span");
60 newSpan.innerHTML = leading + nv + trailing;
61 replacements.push([parentEl, node, newSpan]);
62 }
63 }
64 if (replacements.length > 0) {
65 for (idx in replacements) {
66 r = replacements[idx];
67 r[0].replaceChild(r[2], r[1]);
68 }
69 }
70 console.timeEnd("PUATimer");
71 }