Skip to content
File

Blob: src/shared/editor/schema/metrics.ts

typescript30 lines
1import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
2 
3const WORD_SPLIT = /\s+/;
4 
5export interface EditorTextMetrics {
6 words: number;
7 characters: number;
8}
9 
10export const EMPTY_EDITOR_TEXT_METRICS: EditorTextMetrics = {
11 words: 0,
12 characters: 0,
13};
14 
15export function countWords(text: string): number {
16 const trimmed = text.trim();
17 return trimmed === "" ? 0 : trimmed.split(WORD_SPLIT).length;
18}
19 
20export function countCharacters(text: string): number {
21 return Array.from(text).length;
22}
23 
24export function collectEditorTextMetrics(node: ProseMirrorNode): EditorTextMetrics {
25 return {
26 words: countWords(node.textBetween(0, node.content.size, " ", " ")),
27 characters: countCharacters(node.textBetween(0, node.content.size, undefined, " ")),
28 };
29}