diff --git a/.changeset/calm-bottles-shout.md b/.changeset/calm-bottles-shout.md new file mode 100644 index 00000000000..6001c6919aa --- /dev/null +++ b/.changeset/calm-bottles-shout.md @@ -0,0 +1,5 @@ +--- +"@tiptap/extension-character-count": minor +--- + +Make counter function accessible from outside character-count extension diff --git a/packages/extension-character-count/src/character-count.ts b/packages/extension-character-count/src/character-count.ts index 1108f4ca013..16dcec0da11 100644 --- a/packages/extension-character-count/src/character-count.ts +++ b/packages/extension-character-count/src/character-count.ts @@ -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 { @@ -46,6 +58,8 @@ export const CharacterCount = Extension.create text.length, + wordCounter: text => text.split(' ').filter(word => word !== '').length, } }, @@ -64,7 +78,7 @@ export const CharacterCount = Extension.create { 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) } },