cb9d836227
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
42 lines
1.2 KiB
JavaScript
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;
|
|
}
|