Skip to content

Commit

Permalink
fix: [Bug]: While setting content directly while using CharacterCou…
Browse files Browse the repository at this point in the history
…nt with limit is not obeyed #5851
  • Loading branch information
haris-conga committed Nov 21, 2024
1 parent 4b2de33 commit 304d187
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions packages/extension-character-count/src/character-count.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ export interface CharacterCountOptions {
* @example (text) => text.split(/\s+/).filter(word => word !== '').length
*/
wordCounter: (text: string) => number
/**
* Whether to trim initial content that exceeds the limit
* @default true
*/
trimInitialContent: boolean
}

export interface CharacterCountStorage {
Expand Down Expand Up @@ -60,6 +65,7 @@ export const CharacterCount = Extension.create<CharacterCountOptions, CharacterC
mode: 'textSize',
textCounter: text => text.length,
wordCounter: text => text.split(' ').filter(word => word !== '').length,
trimInitialContent: true,
}
},

Expand Down Expand Up @@ -92,6 +98,32 @@ export const CharacterCount = Extension.create<CharacterCountOptions, CharacterC
}
},

onCreate() {
const { editor, options } = this
const { limit, trimInitialContent } = options

// Only proceed if a limit is set and trimInitialContent is true
if (limit === null || limit === undefined || limit === 0 || !trimInitialContent) { return }

// Get the current document
const doc = editor.state.doc

// Calculate current character count
const currentCharCount = this.storage.characters()

// If content exceeds limit, trim it
if (currentCharCount > limit) {
const text = doc.textBetween(0, doc.content.size, undefined, ' ')
const trimmedContent = text.slice(0, limit)

// Replace the entire document content
editor.commands.setContent(trimmedContent)

// Add a console warning
console.warn(`[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.`)
}
},

addProseMirrorPlugins() {
return [
new Plugin({
Expand Down

0 comments on commit 304d187

Please sign in to comment.