import { Plugin } from 'prosemirror-state'; import { docToText } from '../serializer'; function charCount(doc: import('prosemirror-model').Node): number { return docToText(doc).replace(/\n/g, '').length; } /** * Enforces a character limit by rejecting transactions that grow the * document past it. Shrinking edits are always allowed, even while over the * limit (e.g. after the limit was lowered), so users can recover. */ export function maxLengthPlugin(getMaxLength: () => number): Plugin { return new Plugin({ filterTransaction(tr, state) { if (!tr.docChanged) return true; const max = getMaxLength(); if (!max || max <= 0) return true; const after = charCount(tr.doc); if (after <= max) return true; return after < charCount(state.doc); }, }); }