Skip to content

Commit 960f4a6

Browse files
authored
Improve word counter using Intl.Segmenter when possible (#36)
1 parent 035e12f commit 960f4a6

1 file changed

Lines changed: 18 additions & 1 deletion

File tree

index.html

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,9 @@
160160
this.theme = localStorage.getItem(SHIRO_THEME) ||
161161
(window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
162162
this.countMode = localStorage.getItem(SHIRO_COUNT_MODE) || 'words';
163+
this.segmenter = typeof Intl.Segmenter === "function"
164+
? new Intl.Segmenter(navigator.language, { granularity: "word" })
165+
: null;
163166
this.visible = true;
164167

165168
this.init();
@@ -288,12 +291,26 @@
288291
}
289292
}
290293

294+
getWordsCount(content) {
295+
if (!content.trim()) return 0;
296+
297+
if (this.segmenter && content.length < 300_000) {
298+
let count = 0;
299+
for (const segment of this.segmenter.segment(content)) {
300+
if (segment.isWordLike) count++;
301+
}
302+
return count;
303+
}
304+
// Fallback for very old browsers or very large content
305+
return content.trim().split(/\s+/).filter(Boolean).length;
306+
}
307+
291308
updateCount() {
292309
const text = this.editor.value;
293310
let count, label;
294311

295312
if (this.countMode === 'words') {
296-
count = text.trim().split(/\s+/).filter(Boolean).length;
313+
count = this.getWordsCount(text);
297314
label = `word${count !== 1 ? 's' : ''}`;
298315
} else {
299316
count = text.length;

0 commit comments

Comments
 (0)