Skip to content

Commit

Permalink
fix(character-count): setting content larger than limit should trun…
Browse files Browse the repository at this point in the history
  • Loading branch information
gethari authored Nov 25, 2024
1 parent f8961a9 commit 14681a1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilled-pigs-drum.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tiptap/extension-character-count": major
---

fix: #5851 - While setting `content` directly while using character-count
30 changes: 30 additions & 0 deletions packages/extension-character-count/src/character-count.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,39 @@ export const CharacterCount = Extension.create<CharacterCountOptions, CharacterC
},

addProseMirrorPlugins() {
let initialEvaluationDone = false

return [
new Plugin({
key: new PluginKey('characterCount'),
appendTransaction: (transactions, oldState, newState) => {
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

Expand Down

0 comments on commit 14681a1

Please sign in to comment.