From 489eb0d1baab9a7678c00e8bc8dd99b6c59d7c7a Mon Sep 17 00:00:00 2001 From: Daniel Kao Date: Mon, 25 Nov 2024 00:26:59 +0800 Subject: [PATCH] refactor: make vertical digit conersion more robust --- app/src/main/assets/process_text_nodes.js | 35 ++++++++++++++--------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/app/src/main/assets/process_text_nodes.js b/app/src/main/assets/process_text_nodes.js index cdf28950..bb809e40 100644 --- a/app/src/main/assets/process_text_nodes.js +++ b/app/src/main/assets/process_text_nodes.js @@ -1,7 +1,8 @@ function convertToVerticalStyle(node) { if (node.nodeType === Node.TEXT_NODE) { - let text = node.nodeValue; - const regex = /(\d{1,4}\.?|[a-zA-Z]{1,50}\.?)/g; + let text = convertToFullWidth(node.nodeValue); + // 1.1 | 1. | 2024 | a. + const regex = /(\b\d\.\d\b|\d{1}\.(?=\s|\b)|\d{1,4}|\b[a-zA-Z]\.)/g; let match; let lastIndex = 0; const fragment = document.createDocumentFragment(); @@ -10,20 +11,22 @@ function convertToVerticalStyle(node) { // exclude english words longer than 2 characters, e.g. "Hello" but keep a. b. c. if (match[0].length > 1 && isLetter(match[0][0]) && isLetter(match[0][1])) { continue } - // digits longer than 4 characters are excluded, e.g. 12345, keep 2024 similar year numbers - if (match[0].length > 2) { - if (lastIndex < match.index) { - fragment.appendChild(document.createTextNode(text.slice(lastIndex, match.index))); - } + // digits longer than 3 characters , e.g. 12345, keep 2024 similar year numbers + if (match[0].length >= 3) { + if (match[0][1] != '.') { + if (lastIndex < match.index) { + fragment.appendChild(document.createTextNode(text.slice(lastIndex, match.index))); + } - // Create span element for the matched part - const span = document.createElement('span'); - span.className = 'verticalSingleChr'; - span.textContent = match[0]; - fragment.appendChild(span); + // Create span element for the matched part + const span = document.createElement('span'); + span.className = 'verticalSingleChr'; + span.textContent = match[0]; + fragment.appendChild(span); - lastIndex = regex.lastIndex; - continue; + lastIndex = regex.lastIndex; + continue; + } } // Create text node for the part before the match if (lastIndex < match.index) { @@ -52,6 +55,10 @@ function convertToVerticalStyle(node) { } } +function convertToFullWidth(str) { + return str.replace(/%/g, '%'); +} + function isLetter(char) { return /[a-zA-Z]/.test(char); // Returns true if the character is a letter }