From 93bc93353b6bccce65c44bec41940e5cd11f419b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=B4=ED=98=B8=EC=97=B0?= Date: Mon, 30 Sep 2024 23:38:29 +0900 Subject: [PATCH] feat(character-count): add options for configuring counting (#5674) --- .changeset/calm-bottles-shout.md | 5 +++++ .../src/character-count.ts | 19 ++++++++++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 .changeset/calm-bottles-shout.md diff --git a/.changeset/calm-bottles-shout.md b/.changeset/calm-bottles-shout.md new file mode 100644 index 000000000..6001c6919 --- /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 1108f4ca0..16dcec0da 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) } },