fix(telegram): clamp visible html characters

Telegram counts visible characters, not HTML source bytes.
Truncate without splitting tags, entities or surrogate pairs.
This commit is contained in:
翅膀 committed 2026-10-23 23:23:08 +08:00
1 parent 93650141f7
commit 7a76cac8a1
1 file changed
+34 -7
+34 -7
View File
@@ -40,13 +40,21 @@ function formatTimestamp(ts?: string): string {
* an incomplete trailing tag and closes every tag still open at the cut * an incomplete trailing tag and closes every tag still open at the cut
* point, so parse_mode HTML never rejects the message. * point, so parse_mode HTML never rejects the message.
*/ */
/**
* Clamp HTML to `max` characters as Telegram counts them — the text shown,
* tags left out and an entity (`&`) as one character — keeping tags and
* entities whole and closing the tags still open (an ellipsis marks the cut).
*/
function capHtml(text: string, max: number): string { function capHtml(text: string, max: number): string {
if (text.length <= max) return text;
let cut = text.slice(0, max).replace(/<[^>]*$/u, "");
const stack: string[] = []; const stack: string[] = [];
const re = /<(\/?)([a-z]+)(?:\s[^>]*)?>/g; let shown = 0;
let m: RegExpExecArray | null; let i = 0;
while ((m = re.exec(cut)) !== null) { while (i < text.length) {
if (text[i] === "<") {
const end = text.indexOf(">", i);
if (end < 0) break;
const m = /^<(\/?)([a-z]+)/.exec(text.slice(i, end + 1));
if (m) {
const tag = m[2]!; const tag = m[2]!;
if (m[1] === "/") { if (m[1] === "/") {
const open = stack.lastIndexOf(tag); const open = stack.lastIndexOf(tag);
@@ -55,11 +63,30 @@ function capHtml(text: string, max: number): string {
stack.push(tag); stack.push(tag);
} }
} }
const closers = stack i = end + 1;
continue;
}
const entity =
text[i] === "&" ? /^&(?:#\d+|#x[0-9a-f]+|[a-z]+);/i.exec(text.slice(i, i + 12)) : null;
const code = text.charCodeAt(i);
// A surrogate pair counts (and is cut) as the two code units it is.
const step = entity ? entity[0].length : code >= 0xd800 && code <= 0xdbff ? 2 : 1;
const weight = entity ? 1 : step;
// One character is kept for the ellipsis.
if (shown + weight > max - 1) {
const rest = text.slice(i).replace(/<[^>]*>/g, "");
// What is left fits after all (no ellipsis needed).
if (shown + rest.replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, "x").length <= max) return text;
const closers = [...stack]
.reverse() .reverse()
.map((tag) => `</${tag}>`) .map((tag) => `</${tag}>`)
.join(""); .join("");
return `${cut}…${closers}`; return `${text.slice(0, i)}…${closers}`;
}
shown += weight;
i += step;
}
return text;
} }
export function renderNeutralMessage(message: NeutralMessage): string { export function renderNeutralMessage(message: NeutralMessage): string {