Preserve rich formatting when restoring selected text

This commit is contained in:
muena
2026-09-27 10:23:37 +02:00
parent 94806aa049
commit ec1e2d27e0
6 changed files with 463 additions and 56 deletions

185
src/lib/rich-text.ts Normal file
View File

@@ -0,0 +1,185 @@
import type { PlaceholderMapping } from "../types";
import type { ProjectRun } from "./velum-project";
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function escapeHtml(value: string): string {
return value
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
function decodeEntities(value: string): string {
const named: Record<string, string> = {
amp: "&",
lt: "<",
gt: ">",
quot: '"',
apos: "'",
nbsp: " ",
ndash: "–",
mdash: "—",
hellip: "…",
rsquo: "’",
lsquo: "‘",
rdquo: "”",
ldquo: "“",
};
return value.replace(
/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]+);/gi,
(entity, code: string) => {
if (code.startsWith("#")) {
const point =
code[1].toLowerCase() === "x"
? Number.parseInt(code.slice(2), 16)
: Number.parseInt(code.slice(1), 10);
return Number.isInteger(point) && point >= 0 && point <= 0x10ffff
? String.fromCodePoint(point)
: entity;
}
return named[code.toLowerCase()] ?? entity;
},
);
}
function normalized(value: string): string {
return value
.replace(/\u00a0/g, " ")
.replace(/\s+/g, " ")
.trim();
}
type HtmlToken = { kind: "tag" | "text"; value: string };
function tokenizeHtml(html: string): HtmlToken[] | null {
const tokens: HtmlToken[] = [];
for (let start = 0; start < html.length; ) {
if (html[start] !== "<") {
const end = html.indexOf("<", start);
const next = end < 0 ? html.length : end;
tokens.push({ kind: "text", value: html.slice(start, next) });
start = next;
continue;
}
if (html.startsWith("<!--", start)) {
const end = html.indexOf("-->", start + 4);
if (end < 0) return null;
tokens.push({ kind: "tag", value: html.slice(start, end + 3) });
start = end + 3;
continue;
}
let quote = "";
let end = start + 1;
for (; end < html.length; end++) {
const character = html[end];
if (quote) {
if (character === quote) quote = "";
} else if (character === '"' || character === "'") quote = character;
else if (character === ">") break;
}
if (end === html.length) return null;
tokens.push({ kind: "tag", value: html.slice(start, end + 1) });
start = end + 1;
}
return tokens;
}
type Match = { start: number; end: number; replacement: string };
function replaceNode(
value: string,
mapping: PlaceholderMapping,
matchModes: ProjectRun["matchModes"],
session: boolean,
): { value: string; count: number } {
const candidates: Match[] = [];
for (const [key, entry] of Object.entries(mapping)) {
const stripped = key.replace(/[<>]/g, "");
const bare = session ? stripped : key;
const boundary =
matchModes?.[key] === "anywhere"
? escapeRegExp(bare)
: `(?<![\\p{L}\\p{N}])${escapeRegExp(bare)}(?![\\p{L}\\p{N}])`;
const patterns = [new RegExp(boundary, "gu")];
if (session) {
patterns.unshift(
new RegExp(
`(?:&lt;|&#0*60;|&#x0*3c;)${escapeRegExp(stripped)}(?:&gt;|&#0*62;|&#x0*3e;)`,
"giu",
),
);
}
for (const pattern of patterns) {
for (const match of value.matchAll(pattern)) {
candidates.push({
start: match.index,
end: match.index + match[0].length,
replacement: escapeHtml(entry.original),
});
}
}
}
candidates.sort((a, b) => a.start - b.start || b.end - a.end);
let output = "";
let cursor = 0;
let count = 0;
for (const match of candidates) {
if (match.start < cursor) continue;
output += value.slice(cursor, match.start) + match.replacement;
cursor = match.end;
count++;
}
return { value: output + value.slice(cursor), count };
}
/** Keep the source markup untouched except for verified placeholder text nodes. */
export function restoreRichHtml(
html: string,
sourceText: string,
restoredText: string,
mapping: PlaceholderMapping,
matchModes?: ProjectRun["matchModes"],
session = false,
): string | undefined {
const tokens = tokenizeHtml(html);
if (!tokens) return undefined;
const ignored = new Set(["head", "script", "style", "title", "noscript"]);
const blocks = new Set(["p", "div", "li", "tr", "h1", "h2", "h3", "br"]);
let ignoredDepth = 0;
let before = "";
let after = "";
let output = "";
for (const token of tokens) {
if (token.kind === "tag") {
const tag = /^<\s*(\/?)\s*([a-z][\w:-]*)/i.exec(token.value);
if (tag) {
const name = tag[2].toLowerCase();
if (ignored.has(name))
ignoredDepth = Math.max(0, ignoredDepth + (tag[1] ? -1 : 1));
if (!ignoredDepth && blocks.has(name) && (tag[1] || name === "br")) {
before += " ";
after += " ";
}
}
output += token.value;
continue;
}
if (ignoredDepth) {
output += token.value;
continue;
}
before += decodeEntities(token.value);
const replaced = replaceNode(token.value, mapping, matchModes, session);
after += decodeEntities(replaced.value);
output += replaced.value;
}
return normalized(before) === normalized(sourceText) &&
normalized(after) === normalized(restoredText)
? output
: undefined;
}