Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/react/docx/DocxView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
22 changes: 22 additions & 0 deletions src/react/docx/count.ts
Original file line number Diff line number Diff line change
@@ -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)
}
28 changes: 28 additions & 0 deletions test/docx-count.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})