Debian Codegraph @

pua2ot/src/pua2ot-gui.js

raw
1 /*
2 PUA2OT: A utility for converting MUFI PUA characters to standard
3 Unicode with Junicode's OpenType features.
4
5 Programming for the HTML GUI
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 Load this after pua2ot-common.js.
14 */
15
16 // ------------------------
17 // SET UP GLOBAL VARIABLES
18 // ------------------------
19
20 // Whether "Show code" is currently active.
21 let codeOn = false;
22
23 // Here's where we keep the HTML text we're working with. Don't edit
24 // this, but only a copy.
25 let htmlBackup = document.createElement('div');
26
27 // Here's where we keep the plain text we're working with. Don't edit
28 // this, but only a copy.
29 let textBackup = "";
30
31 // Keep original html file here
32 let htmlDoc = null;
33
34 // ---------------------------------------------
35 // END OF VARIABLE SETUP. FUNCTIONS BEGIN.
36 // ---------------------------------------------
37
38 /*
39 * Converts a string consisting of a space-separated series of
40 * hexadecimal numbers and/or single characters to an array of
41 * hexadecimal strings.
42 *
43 * @param {string} s - The string to convert.
44 * @returns {array} An array of hexadecimal codes, or null if
45 * any of the elements of the input string are not hexadecimal
46 * numbers or not single characters or not in this app's collection
47 * of codes/characters to replace.
48 */
49 function mkHexArray(s) {
50 const hexArray = [];
51 if (s.length == 0) {
52 return hexArray;
53 }
54 const a = cleanup_string(s).split(" ");
55 for (i in a) {
56 let ss = a[i];
57 if (realLength(ss) == 1) {
58 let h = int2hex(ss.codePointAt(0));
59 if (h in PUA_DATA) {
60 hexArray.push(h);
61 } else {
62 return null;
63 }
64 } else {
65 if (realLength(ss) < 4 || !isHex(ss)) {
66 return null;
67 }
68 if (ss in PUA_DATA) {
69 hexArray.push(ss);
70 } else {
71 return null;
72 }
73 }
74 }
75 return hexArray;
76 }
77
78 /*
79 * Converts a string consisting of a space-separated series of
80 * four-letter tags to an array of tags (which must be among
81 * those used by this program).
82 *
83 * @param {string} s - The string to convert.
84 * @return {array} The array of tags, or null if string could not be parsed.
85 */
86 function mkTagArray(s) {
87 const tagArray = [];
88 if (s.length == 0) {
89 return tagArray;
90 }
91 const a = cleanup_string(s).split(" ");
92 for (i in a) {
93 ss = a[i];
94 if (!is_OT_tag(ss)) {
95 return null;
96 }
97 tagArray.push(ss);
98 }
99 return tagArray;
100 }
101
102 /*
103 * Parses a tag and optional index in the format tag or tag[number]
104 * and returns an array where a[0] is the tag and a[1] the index.
105 * Tag names are not validated beyond making sure they are four
106 * characters long.
107 *
108 * @param {string} s - The string to parse.
109 * @returns {array} Array with tag and index.
110 */
111 function parseIndexedTag(s) {
112 openBracket = s.indexOf("[");
113 closeBracket = s.indexOf("]");
114 if (openBracket == -1 || closeBracket == -1) {
115 if (s.length == 4) {
116 return [s, 1];
117 }
118 return null;
119 }
120 const tag = s.slice(0, openBracket);
121 if (tag.length != 4) {
122 return null;
123 }
124 const idxs = s.slice(openBracket + 1, closeBracket);
125 const idx = parseInt(idxs);
126 // Test if idx is NaN.
127 if (idx !== idx) {
128 return null;
129 }
130 return [tag, idx];
131 }
132
133 /*
134 * Tests whether the text we're working with is plain text or html.
135 * @returns {boolean} result of the test.
136 */
137 const isHTMLType = () => htmlDoc != null;
138
139 /*
140 * Prepares a string for export by doing some replacements and
141 * wrapping it in a &lt;div&gt; that turns on the default OpenType
142 * features. Helper for saving and copying.
143 * @returns {string} The processed string.
144 */
145 function exportString() {
146 /*
147 Prepare text for export; wrap it in a div that turns on
148 default features.
149 */
150 let text = destElement.innerHTML;
151 if (text.search("&amp;")) {
152 text = text.replaceAll("&amp;", "&");
153 }
154 fString = featureString(options.defaultTags);
155 const div_open = "<div style=\"font-feature-settings: " + fString + ";\">\n";
156 const div_close = "\n</div>";
157 text = div_open + text + div_close;
158 if (isHTMLType()) {
159 htmlDoc.body.innerHTML = text;
160 return htmlDoc.documentElement.outerHTML;
161 }
162 return text;
163 }
164
165 /**
166 * Prepares and downloads a file containing the converted text. This will
167 * be a plain text file (with html markup) if the original file was plain,
168 * and an html file if the original was html.
169 */
170 function saveFile() {
171 const blob = new Blob([exportString()], {type: 'text/plain'});
172 const url = URL.createObjectURL(blob);
173 const a = document.createElement('a');
174 a.href = url;
175 a.download = (isHTMLType()) ? 'pua2ot_download.html' : 'pua2ot_download.txt';
176 document.body.appendChild(a);
177 a.click();
178 document.body.removeChild(a);
179 URL.revokeObjectURL(url);
180 }
181
182 /**
183 * Adds markup to the source text (from a text file) to show which characters
184 * are being replaced (by default the PUA characters, but usually also the
185 * problematic Unicodes).
186 */
187 function markPuaCharsText() {
188 let found_PUA = false;
189 let resultStr = "";
190 for (var ch of textBackup) {
191 if (isReplaceable(ch)) {
192 found_PUA = true;
193 resultStr += ("<span class='pua'>" + ch + "</span>");
194 } else {
195 resultStr += ch;
196 }
197 }
198 if (found_PUA) {
199 sourceElement.innerHTML = resultStr;
200 }
201 }
202
203 /**
204 * Restore text source to cancel highlighting of PUA chars.
205 */
206 const restoreSourceText = () => sourceElement.innerText = textBackup;
207
208 /**
209 * Adds markup to the source text (from an html file) to show which characters
210 * are being replaced (by default the PUA characters, but usually also the
211 * problematic Unicodes).
212 */
213 function markPuaCharsHtml() {
214 let replacementList = [];
215
216 const clonedDiv = htmlBackup.cloneNode(true);
217
218 const walker = document.createTreeWalker(
219 clonedDiv,
220 NodeFilter.SHOW_TEXT,
221 null
222 )
223 let node;
224 let PUA_found = false;
225 while ((node = walker.nextNode())) {
226 let locl_found = false;
227 let nv = node.nodeValue.trim();
228 if (nv.length > 0) {
229 let resultString = "";
230 for (var ch of nv) {
231 if (isReplaceable(ch)) {
232 PUA_found = locl_found = true;
233 resultString += ("<span class='pua'>" + ch + "</span>");
234 } else {
235 resultString += ch;
236 }
237 }
238 if (locl_found) {
239 const newNode = document.createElement('span');
240 newNode.innerHTML = " " + resultString + " ";
241 replacementList.push([node, newNode]);
242 }
243 }
244 }
245 if (PUA_found) {
246 for (var idx in replacementList) {
247 const replacementItem = replacementList[idx];
248 replacementItem[0].replaceWith(replacementItem[1]);
249 }
250 sourceElement.innerHTML = clonedDiv.innerHTML;
251 }
252 }
253
254 /**
255 * Restore HTML source to cancel highlighting of PUA chars.
256 */
257 const restoreSourceHtml = () => sourceElement.innerHTML = htmlBackup.innerHTML;
258
259 /**
260 *
261 * @param {boolean} repl_ent - Whether to replace the MUFI entities in the text before
262 * other processing.
263 */
264 const plainTextCaller = (repl_ent) => destElement.innerHTML = convert(textBackup, repl_ent, codeOn);
265
266 /**
267 * Calls convert() for an HTML buffer.
268 * @param {boolean} repl_ent - Whether to replace the MUFI entities in the text before
269 * other processing.
270 */
271 function htmlCaller(repl_ent) {
272 console.time("PUATimer");
273
274 let replacementList = [];
275
276 const clonedDiv = htmlBackup.cloneNode(true);
277
278 const walker = document.createTreeWalker(
279 clonedDiv,
280 NodeFilter.SHOW_TEXT,
281 null
282 )
283 while (destElement.firstChild) {
284 destElement.removeChild(destElement.firstChild);
285 }
286 let node;
287 while ((node = walker.nextNode())) {
288 console.log(typeof node.parentNode.classList);
289 console.log(node.parentNode.classList);
290 if (node.parentNode.classList.contains("noconv")) {
291 console.log("text",node.textContent);
292 //replacementList.push([node, null])
293 } else {
294 let nv = node.nodeValue;
295 const hasLeadingWhitespace = /^\s/.test(nv);
296 const hasTrailingWhitespace = /\s$/.test(nv);
297 const leading = hasLeadingWhitespace ? " " : "";
298 const trailing = hasTrailingWhitespace ? " " : "";
299 nv = nv.trim();
300 if (nv.length > 0) {
301 const newNode = document.createElement('span');
302 newNode.innerHTML = leading + convert(nv, repl_ent, codeOn) + trailing;
303 replacementList.push([node, newNode]);
304 }
305 }
306 }
307 for (var idx in replacementList) {
308 const replacementItem = replacementList[idx];
309 replacementItem[0].replaceWith(replacementItem[1]);
310 }
311 destElement.innerHTML = clonedDiv.innerHTML;
312 console.timeEnd("PUATimer");
313 }
314
315 /*
316 * Display contents of "body" element of html file in source box.
317 */
318 function displayInSourceBox() {
319 sourceElement.style.whiteSpace = "normal";
320 sourceElement.style.wordWrap = "break-word";
321 sourceElement.innerHTML = htmlBackup.innerHTML = htmlDoc.body.innerHTML;
322 }
323
324 /**
325 * Copy text to clipboard. We display a message because there is
326 * otherwise no feedback.
327 * @param {string} text - The text to copy.
328 */
329 async function copyToClipboard(text) {
330 try {
331 await navigator.clipboard.writeText(text);
332 alert("Text copied");
333 } catch (err) {
334 alert("Failed to copy text");
335 }
336 }
337
338 /**
339 * Loads a file into the source box.
340 * @param {string} f - Name of a file to load.
341 */
342 function loadFile(f) {
343 const reader = new FileReader();
344 reader.onload = () => {
345 let text = reader.result;
346 if (options.replaceMUFIEntities) {
347 text = replaceEntities(text)
348 }
349 /*
350 These lines detect whether loaded file is html by parsing it.
351 If it is html, we need to grab the body's text nodes and
352 convert them one by one.
353 */
354 const parser = new DOMParser();
355 htmlDoc = parser.parseFromString(text, 'text/html');
356 const hasError = htmlDoc.querySelector('parsererror');
357 const hasElements = htmlDoc.body.children.length > 0;
358 if (!hasError && hasElements) {
359 textCaller = htmlCaller;
360 puaMarker = markPuaCharsHtml;
361 restoreSource = restoreSourceHtml;
362 puaWidget.checked = false;
363 displayInSourceBox(htmlDoc);
364 } else {
365 htmlDoc = null;
366 textCaller = plainTextCaller;
367 puaMarker = markPuaCharsText;
368 restoreSource = restoreSourceText;
369 text = cleanup_string(text);
370 puaWidget.checked = false;
371 sourceElement.innerText = textBackup = text;
372 }
373 textCaller(!codeOn);
374 };
375 reader.readAsText(f);
376 }
377
378 let textCaller = plainTextCaller;
379 let puaMarker = markPuaCharsText;
380 let restoreSource = restoreSourceText;
381
382
383 /* ---------------------------------------------
384 SET UP LISTENERS (with helper functions)
385
386 More legible markup
387 Use entities for Unicode tags
388 Keep problematic Unicodes
389 Default features
390 Non-word tags
391 Language
392 Language picker dialog
393 Download
394 Copy
395 Show code
396 Mark replaced chars in code
397 Drop a file
398 Load file via input button
399 Edit source
400 Variant bases
401 Enlarge axis scale
402 --------------------------------------------- */
403
404 // Access to our two text boxes.
405 let sourceElement = document.querySelector("#sourcebox");
406 let destElement = document.querySelector("#destbox");
407
408 // "More legible markup" checkbox.
409 let legibleWidget = document.getElementById('method_preference');
410 legibleWidget.addEventListener('change', function() {
411 options.methodPriority = this.checked ? "legible" : "compact";
412 textCaller(!codeOn);
413 } );
414
415 // "Use entities for Unicode tags" checkbox.
416 let utagEntitiesWidget = document.getElementById('utag_entities');
417 utagEntitiesWidget.addEventListener('change', function() {
418 options.utagEntities = this.checked;
419 textCaller(!codeOn)
420 } );
421
422 // "Keep problematic Unicodes" checkbox.
423 let keepUnicodesWidget = document.getElementById('problem_unicodes');
424 keepUnicodesWidget.addEventListener('change', function() {
425 options.keepUnicode = this.checked;
426 if (puaWidget.checked) {
427 restoreSource();
428 puaMarker();
429 }
430 textCaller(!codeOn);
431 } );
432
433 /*
434 * Parse a space-separated series of tags in JunicodeManual format
435 * (tag[index] or unindexed tag), plug it into options.defaultTags,
436 * and regenerate the destination text.
437 *
438 * @param {string} tagString - The string to parse.
439 * @returns {boolean} whether the operation was successful.
440 */
441 function applyDefaultTags(tagString) {
442 let err = false;
443 const ar = cleanup_string(tagString).split(' ');
444 const result = {};
445 for (i in ar) {
446 const arr = parseIndexedTag(ar[i]);
447 err = (arr == null);
448 if (err) {
449 break
450 } else {
451 result[arr[0]] = arr[1];
452 }
453 }
454 if (!err) {
455 options.defaultTags = result;
456 destElement.style.fontFeatureSettings = featureString(options.defaultTags);
457 textCaller(!codeOn);
458 }
459 return err;
460 }
461
462 // "Default features" edit box.
463 let defaultFeaturesWidget = document.getElementById('default_features');
464 defaultFeaturesWidget.addEventListener('input', function () {
465 let raws = this.value;
466 let err = false;
467 if (raws.length == 0) {
468 options.defaultTags = {};
469 destElement.style.fontFeatureSettings = "";
470 textCaller(!codeOn);
471 this.style.backgroundColor = 'initial';
472 } else {
473 err = applyDefaultTags(raws);
474 this.style.backgroundColor = err ? 'lightcoral' : 'initial';
475 }
476 } );
477
478 // "Non-word tags" edit box.
479 let nonWordWidget = document.getElementById('non_word_tags');
480 nonWordWidget.addEventListener('input', function () {
481 const e = mkTagArray(nonWordWidget.value);
482 if (e == null) {
483 this.style.backgroundColor = 'lightcoral';
484 } else {
485 options.nonWordTags = e;
486 textCaller(!codeOn);
487 this.style.backgroundColor = 'initial';
488 }
489 } );
490
491 // "Language" dropdown.
492 let lang_code_picker = document.getElementById('lang_code_picker');
493 let languageChoiceWidget = document.getElementById('language_choice');
494 languageChoiceWidget.addEventListener('change', function() {
495 if (this.value == "other") {
496 lang_code_picker.showModal();
497 } else {
498 options.language = this.value;
499 }
500 textCaller(!codeOn);
501 destElement.setAttribute("lang", options.language);
502 sourceElement.setAttribute("lang", options.language);
503 } );
504
505 // Widgets for the language picker dialog.
506 let languageInput = document.getElementById('langInput');
507 let languageCancel = document.getElementById('language_cancel');
508 languageCancel.addEventListener('click', () => {
509 lang_code_picker.close();
510 } );
511
512 // Language picker dialog.
513 let languageSubmit = document.getElementById('language_okay');
514 languageSubmit.addEventListener('click', () => {
515 let value = languageInput.value;
516 if (value.length == 2) {
517 options.language = value;
518 lang_code_picker.close();
519 destElement.setAttribute("lang", value);
520 sourceElement.setAttribute("lang", value);
521 }
522 });
523
524 // "Download" button.
525 let dnlButtonElement = document.querySelector("#dnlbutton");
526 dnlButtonElement.onclick = () => {
527 saveFile();
528 }
529
530 // "Copy" button.
531 let cpyButtonElement = document.querySelector("#cpybutton");
532 cpyButtonElement.onclick = () => {
533 console.log("copying...")
534 copyToClipboard(exportString());
535 }
536
537 // "Show code" checkbox. This also disables the "Copy" and
538 // "Download" buttons.
539 let codeWidget = document.getElementById('show_code');
540 codeWidget.addEventListener('change', function () {
541 if (this.checked) {
542 codeOn = true;
543 destElement.classList.add('codeview');
544 textCaller(false);
545 dnlButtonElement.disabled = true;
546 cpyButtonElement.disabled = true;
547 } else {
548 codeOn = false;
549 destElement.classList.remove('codeview');
550 textCaller(true);
551 dnlButtonElement.disabled = false;
552 cpyButtonElement.disabled = false;
553 }
554 } );
555
556 // "Mark Replaced Chars in Source" checkbox
557 let puaWidget = document.getElementById("mark_pua");
558 let puaLabel = document.getElementById("mark_pua_label");
559 puaWidget.addEventListener('change', function () {
560 this.checked ? puaMarker() : restoreSource();
561 } );
562
563 // Drag and drop events, for the source box.
564 sourceElement.addEventListener('dragover', function(e) {
565 e.preventDefault();
566 this.style.backgroundColor = '#eee';
567 } );
568
569 sourceElement.addEventListener('dragleave', function() {
570 this.style.backgroundColor = '';
571 } );
572
573 // Drop a new file into the source box. We can handle
574 // two kinds of file: plain text (UTF-8) and HTML
575 // (the complete HTML file so we can parse it properly).
576 sourceElement.addEventListener('drop', function(e) {
577 e.preventDefault();
578 this.style.backgroundColor = '';
579 const files = e.dataTransfer.files;
580 if (files.length == 1) {
581 let file = files[0];
582 loadFile(file);
583 fileInputWidget.innerHTML = file.name;
584 }
585 } );
586
587 // “Choose File” button.
588 let fileInputWidget = document.getElementById('file_input');
589 fileInputWidget.addEventListener('change', (event) => {
590 const selected_files = event.target.files;
591 if (selected_files.length >= 1) {
592 loadFile(selected_files[0]);
593 }
594 } );
595
596 /*
597 * Helper for change event for "Edit source" checkbox.
598 */
599 function handleSourceInput() {
600 if (isHTMLType()) {
601 htmlBackup.innerHTML = sourceElement.innerHTML;
602 } else {
603 textBackup = sourceElement.innerText;
604 }
605 textCaller(!codeOn);
606 }
607
608 // "Edit Source" checkbox.
609 let editSrcWidget = document.getElementById('edit_source');
610 editSrcWidget.addEventListener('change', (event) => {
611 if (editSrcWidget.checked) {
612 puaWidget.checked = false;
613 const event = new Event('change');
614 puaWidget.dispatchEvent(event);
615 puaWidget.disabled = true;
616 puaLabel.style.opacity = 0.5;
617 sourceElement.contentEditable = true;
618 sourceElement.addEventListener('input', handleSourceInput);
619 } else {
620 puaWidget.disabled = false;
621 puaLabel.style.opacity = 1.0;
622 sourceElement.removeEventListener('input', handleSourceInput);
623 sourceElement.contentEditable = false;
624 if (isHTMLType()) {
625 htmlBackup.innerHTML = sourceElement.innerHTML;
626 } else {
627 textBackup.innerText = sourceElement.innerText;
628 }
629 }
630 } );
631
632 /*
633 * Helper for "Alternate bases" event.
634 */
635 function varValues() {
636 let varPref = [];
637 for (let i = 0; i < varWidget.options.length; i++) {
638 if (varWidget.options[i].selected) {
639 varPref.push(varWidget.options[i].value);
640 }
641 }
642 options.basePreferences = varPref;
643 }
644
645 let varWidget = document.getElementById('alternate_unicodes');
646 varWidget.addEventListener('change', ()=> {
647 varValues();
648 textCaller(!codeOn);
649 } );
650
651 let enlaWidget = document.getElementById('enlarge_scale');
652 enlaWidget.addEventListener('change', ()=> {
653 s = parseInt(enlaWidget.value);
654 if (s != NaN) {
655 if (s >= 0 && s <=100) {
656 options.enlargedScale = s
657 }
658 }
659 textCaller(!codeOn);
660 } );
661
662 let charSkipWidget = document.getElementById("char_skip");
663 charSkipWidget.addEventListener('input', function() {
664 a = mkHexArray(this.value);
665 if (a == null) {
666 this.style.backgroundColor = 'lightcoral';
667 } else {
668 options.charSkip = a;
669 if (puaWidget.checked) {
670 restoreSource();
671 puaMarker();
672 }
673 textCaller(!codeOn);
674 this.style.backgroundColor = 'initial';
675 }
676 });
677
678 /*
679 Now complete initialization by cleaning up the source text (convert
680 any whitespace sequence to a space), converting, and displaying in
681 the destinaton box.
682 */
683
684 sourceElement.innerText = textBackup = cleanup_string(sourceElement.innerText);
685 applyDefaultTags(defaultFeaturesWidget.value);
686
687 textCaller(!codeOn);