fix: AI 配图 SVG 属性重复时整张图无法显示

模型画折线时把 <line> 写成重复的 x2/y2 属性,XML 不合法,<img> 加载失败。
净化与显示时把这类 <line> 改为 <polyline>,其他重复属性只保留第一个;
显示时也修复,已保存的旧配图无需重新生成。提示词补充合法 XML 要求。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
margrop
2026-11-11 19:24:43 +08:00
parent e7664b1956
commit 5ff2a675cb
3 changed files with 68 additions and 3 deletions

View File

@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { figureSvgToDataUri, MAX_FIGURE_SVG_LENGTH, sanitizeFigureSvg } from '@/lib/figure-svg';
import { figureSvgToDataUri, MAX_FIGURE_SVG_LENGTH, repairDuplicateSvgAttributes, sanitizeFigureSvg } from '@/lib/figure-svg';
import { parseFigure } from '@/lib/ai/schema';
const triangle = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200"><polygon points="10,190 190,190 100,10" fill="none" stroke="#000"/><text x="5" y="198">A</text></svg>';
@@ -70,3 +70,32 @@ describe('parseFigure', () => {
expect(parseFigure(null, null)).toEqual({ hasFigure: false, figureSvg: null });
});
});
describe('repairDuplicateSvgAttributes', () => {
const isValidXml = (svg: string) => new DOMParser().parseFromString(svg, 'image/svg+xml').getElementsByTagName('parsererror').length === 0;
it('把重复写了 x2/y2 的 <line> 改成折线,箭头与描边属性保留', () => {
const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 350"><g fill="none" stroke="#000">'
+ '<line x1="95" y1="95" x2="95" y2="60" x2="270" y2="60"/>'
+ '<line x1="430" y1="176" x2="430" y2="202" x2="225" y2="202" marker-end="url(#arrowhead)"/>'
+ '<line x1="0" y1="0" x2="10" y2="10"/></g></svg>';
expect(isValidXml(svg)).toBe(false);
const repaired = repairDuplicateSvgAttributes(svg);
expect(isValidXml(repaired)).toBe(true);
expect(repaired).toContain('<polyline points="95,95 95,60 270,60" fill="none"/>');
expect(repaired).toContain('<polyline points="430,176 430,202 225,202" fill="none" marker-end="url(#arrowhead)"/>');
expect(repaired).toContain('<line x1="0" y1="0" x2="10" y2="10"/>');
});
it('其他元素的重复属性只保留第一个,正常 SVG 原样返回', () => {
expect(repairDuplicateSvgAttributes('<rect x="1" width="5" x="2" height="5">')).toBe('<rect x="1" width="5" height="5">');
expect(repairDuplicateSvgAttributes(triangle)).toBe(triangle);
});
it('净化与显示时都会修复,已保存的旧配图也能显示', () => {
const broken = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><line x1="0" y1="0" x2="5" y2="0" x2="5" y2="5" stroke="#000"/></svg>';
expect(sanitizeFigureSvg(broken)).toContain('<polyline points="0,0 5,0 5,5" fill="none" stroke="#000"/>');
expect(decodeURIComponent(figureSvgToDataUri(broken))).toContain('<polyline points="0,0 5,0 5,5"');
});
});

View File

@@ -222,6 +222,7 @@ export const FIGURE_SVG_RULES = `- 输出一个完整的 <svg> 元素,包含 x
- 白色背景、黑色线条(stroke="#000",线宽 1.5~2),需要区分的区域可用浅灰填充;不要使用彩色装饰。
- 按原图比例和相对位置绘制,保留原题印刷标注:顶点字母、数字、长度、角度、单位、箭头和虚线等,文字用 <text>(font-size 14~18);必须过滤掉人在图上手写的草稿、演算、思考批注、圈画和涂改痕迹。
- 只使用基本图形元素:line、polyline、polygon、rect、circle、ellipse、path、text、g、defs、marker。
- 必须是合法 XML:同一元素的属性不能重复;<line> 只画一条线段,折线用 <polyline points="...">。
- 严禁使用 <image>、<script>、<foreignObject>、外部链接、外部字体或事件属性。`;
/**

View File

@@ -16,6 +16,40 @@ const DANGEROUS_OPEN_TAGS = /<\/?(script|foreignObject|iframe|object|embed|audio
const MAX_SANITIZE_PASSES = 10;
// 属性值都带引号的开始标签;不带引号的写法不处理,原样保留
const START_TAG = /<([a-zA-Z][\w:.-]*)((?:\s+[^\s=>/"']+\s*=\s*(?:"[^"]*"|'[^']*'))+)\s*(\/?)>/g;
const ATTRIBUTE = /([^\s=>/"']+)\s*=\s*("[^"]*"|'[^']*')/g;
/**
* 修复同一元素中重复出现的属性。XML 不允许重复属性,<img> 加载这样的 SVG 时整张图都不显示。
* 模型画折线时常把 <line> 写成 x1 y1 x2 y2 x2 y2…,此时按原意改成 <polyline>;其他重复属性只保留第一个。
*/
export function repairDuplicateSvgAttributes(svg: string): string {
return svg.replace(START_TAG, (tag: string, name: string, attrText: string, selfClosing: string) => {
const attributes = [...attrText.matchAll(ATTRIBUTE)].map(([, key, value]) => ({ key, value }));
const counts = new Map<string, number>();
for (const { key } of attributes) counts.set(key, (counts.get(key) ?? 0) + 1);
if (![...counts.values()].some((count) => count > 1)) return tag;
const close = selfClosing ? '/>' : '>';
const kept = new Map<string, string>();
for (const { key, value } of attributes) {
if (!kept.has(key)) kept.set(key, value);
}
const unquote = (value: string) => value.slice(1, -1).trim();
const xs = attributes.filter((attr) => attr.key === 'x2').map((attr) => unquote(attr.value));
const ys = attributes.filter((attr) => attr.key === 'y2').map((attr) => unquote(attr.value));
if (name.toLowerCase() === 'line' && xs.length > 1 && xs.length === ys.length && kept.has('x1') && kept.has('y1')) {
const points = [`${unquote(kept.get('x1')!)},${unquote(kept.get('y1')!)}`, ...xs.map((x, i) => `${x},${ys[i]}`)];
const rest = [...kept].filter(([key]) => !['x1', 'y1', 'x2', 'y2', 'fill'].includes(key));
// line 本身没有填充,改成折线后要显式不填充,否则默认填成黑色
const attrs = [`points="${points.join(' ')}"`, 'fill="none"', ...rest.map(([key, value]) => `${key}=${value}`)];
return `<polyline ${attrs.join(' ')}${close}`;
}
return `<${name} ${[...kept].map(([key, value]) => `${key}=${value}`).join(' ')}${close}`;
});
}
/**
* 从 AI 回复中取出 <svg>…</svg> 并净化;没有有效 SVG、超长或净化后为空时返回 null
*/
@@ -49,6 +83,7 @@ export function sanitizeFigureSvg(raw: unknown, maxLength: number = MAX_FIGURE_S
svg = svg.replace(/(?:javascript|vbscript|data)\s*:/gi, '');
} while (svg !== previous);
svg = repairDuplicateSvgAttributes(svg);
if (!/<svg[^>]*\sxmlns\s*=/i.test(svg)) {
svg = svg.replace(/<svg/i, `<svg xmlns="${SVG_NS}"`);
}
@@ -57,7 +92,7 @@ export function sanitizeFigureSvg(raw: unknown, maxLength: number = MAX_FIGURE_S
return svg;
}
/** 用于 <img src> 的 data URI */
/** 用于 <img src> 的 data URI;同时修复已保存配图中的重复属性,旧数据不必重新生成 */
export function figureSvgToDataUri(svg: string): string {
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(repairDuplicateSvgAttributes(svg))}`;
}