Skip to content

Commit

Permalink
refactor: make vertical digit conersion more robust
Browse files Browse the repository at this point in the history
  • Loading branch information
plateaukao committed Nov 24, 2024
1 parent 007a6fe commit 489eb0d
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions app/src/main/assets/process_text_nodes.js
Original file line number Diff line number Diff line change
@@ -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();
Expand All @@ -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) {
Expand Down Expand Up @@ -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
}
Expand Down

0 comments on commit 489eb0d

Please sign in to comment.