From 14681a19068447779fa112dd96a0200a1fc40b63 Mon Sep 17 00:00:00 2001 From: Hari Haran Date: Mon, 25 Nov 2024 15:03:52 +0530 Subject: [PATCH] fix(character-count): setting `content` larger than limit should truncate #5851 (#5862) --- .changeset/chilled-pigs-drum.md | 5 ++++ .../src/character-count.ts | 30 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 .changeset/chilled-pigs-drum.md diff --git a/.changeset/chilled-pigs-drum.md b/.changeset/chilled-pigs-drum.md new file mode 100644 index 0000000000..154f90a1b5 --- /dev/null +++ b/.changeset/chilled-pigs-drum.md @@ -0,0 +1,5 @@ +--- +"@tiptap/extension-character-count": major +--- + +fix: #5851 - While setting `content` directly while using character-count diff --git a/packages/extension-character-count/src/character-count.ts b/packages/extension-character-count/src/character-count.ts index 16dcec0da1..006bb157ca 100644 --- a/packages/extension-character-count/src/character-count.ts +++ b/packages/extension-character-count/src/character-count.ts @@ -93,9 +93,39 @@ export const CharacterCount = Extension.create { + if (initialEvaluationDone) { + return + } + + const limit = this.options.limit + + if (limit === null || limit === undefined || limit === 0) { + initialEvaluationDone = true + return + } + + const initialContentSize = this.storage.characters({ node: newState.doc }) + + if (initialContentSize > limit) { + const over = initialContentSize - limit + const from = 0 + const to = over + + console.warn(`[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.`) + const tr = newState.tr.deleteRange(from, to) + + initialEvaluationDone = true + return tr + } + + initialEvaluationDone = true + }, filterTransaction: (transaction, state) => { const limit = this.options.limit