From 52b01e4c501984930a2077b6c33dd4fd309d9af1 Mon Sep 17 00:00:00 2001 From: Astrian Zheng Date: Wed, 17 Apr 2024 19:44:02 +1000 Subject: [PATCH] Control spacing adding --- src/index.ts | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++- tsconfig.json | 4 ++-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index ad21821..a1eefea 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1 +1,50 @@ -console.log("hello world") \ No newline at end of file +export default function (nodeClass: string) { + const nodes = document.querySelectorAll(`.${nodeClass}`) + for (let i in nodes) { + processText(nodes[i]) + } +} + +function processText(node: Node): void { + if (node.nodeType === Node.TEXT_NODE) { + // detect the characters includes chinese and english, or japanese (kanji or kana) and english + const reg = /[\u4e00-\u9fa5\u3040-\u30FF][a-zA-Z]|\w[\u4e00-\u9fa5\u3040-\u30FF]|\w[a-zA-Z]/ + const text = node.nodeValue || '' + if (reg.test(text)) { + // process the text char by char + const textArr = text.split('') + let newText = '' + for (let i = 0; i < textArr.length; i++) { + const cnchar_and_kanji = /[\u4e00-\u9fa5\u3040-\u30FF]/ + const kana = /[\u3040-\u30FF]/ + const english_and_number = /[a-zA-Z0-9]/ + // if the char is chinese or japanese (kanji or kana) + if (cnchar_and_kanji.test(textArr[i]) || kana.test(textArr[i])) { + console.log(`textArr[i]: ${textArr[i]}`) + // if next char is english + if (/[a-zA-Z]/.test(textArr[i + 1])) { + console.log(`textArr[i + 1]: ${textArr[i + 1]}`) + // 1/8 em space + newText += textArr[i] + '\u2009' + } else { + newText += textArr[i] + } + } else if (english_and_number.test(textArr[i])) { + if (cnchar_and_kanji.test(textArr[i + 1]) || kana.test(textArr[i + 1])) { + newText += textArr[i] + '\u2009' + } else { + newText += textArr[i] + } + } else { + newText += textArr[i] + + } + } + node.nodeValue = newText + } + } else { + if (!node.nodeName) return + console.log(node.nodeName) + for (let i = 0; i < node.childNodes.length; i++) processText(node.childNodes[i]) + } +} diff --git a/tsconfig.json b/tsconfig.json index 2414f2f..3fb76d6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { - "target": "es5", - "module": "commonjs", + "target": "es6", + "module": "es6", "declaration": true, "outDir": "./dist", "strict": true