File
Blob: src/shared/editor/schema/metrics.ts
| 1 | import type { Node as ProseMirrorNode } from "@tiptap/pm/model"; |
| 2 | |
| 3 | const WORD_SPLIT = /\s+/; |
| 4 | |
| 5 | export interface EditorTextMetrics { |
| 6 | words: number; |
| 7 | characters: number; |
| 8 | } |
| 9 | |
| 10 | export const EMPTY_EDITOR_TEXT_METRICS: EditorTextMetrics = { |
| 11 | words: 0, |
| 12 | characters: 0, |
| 13 | }; |
| 14 | |
| 15 | export function countWords(text: string): number { |
| 16 | const trimmed = text.trim(); |
| 17 | return trimmed === "" ? 0 : trimmed.split(WORD_SPLIT).length; |
| 18 | } |
| 19 | |
| 20 | export function countCharacters(text: string): number { |
| 21 | return Array.from(text).length; |
| 22 | } |
| 23 | |
| 24 | export 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 | } |