Files
monkey-ai-web/src/components/common/ui/richTextLength.js
T
zhanjunhao cb9d836227 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

42 lines
1.2 KiB
JavaScript

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;
}