diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index 978fa6a..918600d 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -33,6 +33,7 @@ import { layoutTabs } from './tabs' import { formatCount, formatNumber, useStrings } from '../strings' import { docxFonts, docxPageFonts } from '../../core/fonts' import { useDocFonts } from '../common/fonts' +import { countWords } from './count' const PX = 4 / 3 const GAP = 16 @@ -457,7 +458,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const id = setTimeout(() => { let n = 0 const count = (b: Block) => { - if (b.t === 'p') n += shownText(b).split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w)).length + if (b.t === 'p') n += countWords(shownText(b)) else if (b.t === 'tbl') for (const r of b.rows) for (const c of r.cells) c.blocks.forEach(count) } st.blocks.forEach(count) diff --git a/src/react/docx/count.ts b/src/react/docx/count.ts new file mode 100644 index 0000000..50e6ed4 --- /dev/null +++ b/src/react/docx/count.ts @@ -0,0 +1,22 @@ +/** Word counts CJK ideographs and kana as one word each; the rest is split on whitespace. */ +const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u +const WS = /\s/u +const WORD = /[\p{L}\p{N}]/u + +export function countWords(text: string): number { + let n = 0 + let letters = false + for (const ch of text) { + if (CJK.test(ch)) { + if (letters) n++ + n++ + letters = false + } else if (WS.test(ch)) { + if (letters) n++ + letters = false + } else if (WORD.test(ch)) { + letters = true + } + } + return n + (letters ? 1 : 0) +} diff --git a/test/docx-count.test.ts b/test/docx-count.test.ts new file mode 100644 index 0000000..254bdd3 --- /dev/null +++ b/test/docx-count.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, test } from 'bun:test' +import { countWords } from '../src/react/docx/count' + +describe('Word word count', () => { + test('each Chinese character counts as a word', () => { + expect(countWords('中文测试文档')).toBe(6) + }) + + test('Chinese separates Latin runs instead of merging them', () => { + expect(countWords('中文abc中文')).toBe(5) + expect(countWords('Revenue grew 24% 中文增长')).toBe(7) + }) + + test('punctuation and full-width spaces are not words', () => { + expect(countWords('中文,测试。 abc')).toBe(5) + expect(countWords('')).toBe(0) + expect(countWords('... ...')).toBe(0) + }) + + test('supplementary-plane ideographs count once each', () => { + expect(countWords('𠀀𠀁')).toBe(2) + }) + + test('non-CJK text keeps the old whitespace rule', () => { + expect(countWords('hello, world')).toBe(2) + expect(countWords('one\ttwo\nthree')).toBe(3) + }) +})