import { decodeHTML } from 'entities'; export const ARTICLE_BODY_LIMIT = 20000; export const countRichText = (text) => Array.from(text.replace(/\s/g, '')).length; export const countArticleHtml = (html) => countRichText(decodeHTML(String(html || '').replace(/<[^>]*>/g, ''))); const countDelta = (delta) => delta.ops.reduce( (total, op) => total + (typeof op.insert === 'string' ? countRichText(op.insert) : 0), 0, ); // Budget only newly inserted text, keeping the original text after the caret intact. export function limitRichTextChange(old, change, limit) { let oldIndex = 0; let remaining = limit - countDelta(old); for (const op of change.ops) { if (op.delete) remaining += countDelta(old.slice(oldIndex, oldIndex + op.delete)); oldIndex += op.retain || op.delete || 0; } remaining = Math.max(0, remaining); const ops = change.ops.flatMap((op) => { if (typeof op.insert !== 'string') return [op]; const text = Array.from(op.insert) .filter((char) => { if (/\s/.test(char)) return true; if (!remaining) return false; remaining--; return true; }) .join(''); return text ? [{ ...op, insert: text }] : []; }); return ops; }