Skip to content

Commit

Permalink
feat(character-count): add options for configuring counting (#5674)
Browse files Browse the repository at this point in the history
  • Loading branch information
ho991217 authored Sep 30, 2024
1 parent 45bac80 commit 93bc933
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/calm-bottles-shout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tiptap/extension-character-count": minor
---

Make counter function accessible from outside character-count extension
19 changes: 16 additions & 3 deletions packages/extension-character-count/src/character-count.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,18 @@ export interface CharacterCountOptions {
* @example 'textSize'
*/
mode: 'textSize' | 'nodeSize'
/**
* The text counter function to use. Defaults to a simple character count.
* @default (text) => text.length
* @example (text) => [...new Intl.Segmenter().segment(text)].length
*/
textCounter: (text: string) => number
/**
* The word counter function to use. Defaults to a simple word count.
* @default (text) => text.split(' ').filter(word => word !== '').length
* @example (text) => text.split(/\s+/).filter(word => word !== '').length
*/
wordCounter: (text: string) => number
}

export interface CharacterCountStorage {
Expand Down Expand Up @@ -46,6 +58,8 @@ export const CharacterCount = Extension.create<CharacterCountOptions, CharacterC
return {
limit: null,
mode: 'textSize',
textCounter: text => text.length,
wordCounter: text => text.split(' ').filter(word => word !== '').length,
}
},

Expand All @@ -64,7 +78,7 @@ export const CharacterCount = Extension.create<CharacterCountOptions, CharacterC
if (mode === 'textSize') {
const text = node.textBetween(0, node.content.size, undefined, ' ')

return text.length
return this.options.textCounter(text)
}

return node.nodeSize
Expand All @@ -73,9 +87,8 @@ export const CharacterCount = Extension.create<CharacterCountOptions, CharacterC
this.storage.words = options => {
const node = options?.node || this.editor.state.doc
const text = node.textBetween(0, node.content.size, ' ', ' ')
const words = text.split(' ').filter(word => word !== '')

return words.length
return this.options.wordCounter(text)
}
},

Expand Down

0 comments on commit 93bc933

Please sign in to comment.