import { cleanSVG } from '../expansion/vector.js';
import { svgPathProperties } from 'svg-path-properties';
import { Delaunay, polygonHull } from 'd3';
import { text, num, choice, color, assert, parseJSON, numeric, points, svgDoc, svgResults, label, esc, json, plain, zip } from './common.js';
const NS = 'http://www.w3.org/2000/svg';
const serialize = (root) => new XMLSerializer().serializeToString(root);
async function readSVG(files) { assert(files[0], '请选择SVG文件。'); return cleanSVG(await files[0].text()); }
const output = (root, stem = 'result') => svgResults(serialize(root), stem);
function setBox(root, box) { assert(box.every(Number.isFinite) && box[2] > 0 && box[3] > 0, '画布边界无效。'); root.setAttribute('viewBox', box.join(' ')); const scale = Math.min(1, 2048 / box[2], 2048 / box[3]); root.setAttribute('width', String(box[2] * scale)); root.setAttribute('height', String(box[3] * scale)); }
function wrapContent(root, transform) { const group = root.ownerDocument.createElementNS(NS, 'g'); for (const child of [...root.childNodes]) if (!['defs', 'title', 'desc'].includes(child.nodeName)) group.append(child); group.setAttribute('transform', transform); root.append(group); }
export const svg_viewbox = (() => ({ fields: [choice('mode', '边界来源', [['content', '图形边界'], ['canvas', '现有画布']]), num('padding', '四边留白(坐标单位)', 10, 0, 500)], async run({ files, values: v }) {
const { root, box } = await readSVG(files); let bounds = box;
if (v.mode === 'content') { const holder = document.createElement('div'); holder.style.cssText = 'position:fixed;left:-10000px;top:0;visibility:hidden'; const mounted = document.importNode(root, true); holder.append(mounted); document.body.append(holder); try { const b = mounted.getBBox(); assert(b.width > 0 && b.height > 0, 'SVG没有可测量的二维图形。'); bounds = [b.x, b.y, b.width, b.height]; } finally { holder.remove(); } }
const next = [bounds[0] - v.padding, bounds[1] - v.padding, bounds[2] + v.padding * 2, bounds[3] + v.padding * 2]; setBox(root, next);
return [...await output(root, 'viewbox'), json({ before: box, after: next, note: '图形边界不包含描边外沿;请用留白覆盖描边。' }, 'viewbox.json')];
} }))();
function paints(root) { return [root, ...root.querySelectorAll('*')].flatMap((node) => ['fill', 'stroke', 'stop-color'].filter((attr) => node.hasAttribute(attr)).map((attr) => ({ node, attr, value: node.getAttribute(attr) }))); }
export const svg_colors = (() => ({ fields: [text('title', '色卡标题', 'SVG配色')], async run({ files, values: v }) {
const { root } = await readSVG(files), tally = new Map();
for (const p of paints(root)) if (CSS.supports('color', p.value) && !/^(currentcolor|inherit)$/i.test(p.value)) tally.set(p.value, (tally.get(p.value) || 0) + 1);
assert(tally.size && tally.size <= 100, '未找到明确颜色,或颜色超过100种。'); const entries = [...tally].map(([value, count]) => ({ value, count }));
const body = label(v.title, 24, 26) + entries.map((d, i) => `<rect x="24" y="${45 + i * 40}" width="52" height="28" fill="${esc(d.value)}" stroke="#bccbc4"/>${label(`${d.value} · ${d.count}处`, 90, 65 + i * 40)}`).join('');
return [...await svgResults(svgDoc(body, 620, 70 + entries.length * 40, v.title), 'colors'), json({ entries, scope: '只统计显式fill、stroke、stop-color;继承、默认值和渐变引用不计数。' }, 'colors.json')];
} }))();
export const svg_recolor = (() => ({ fields: [text('mapping', '颜色替换JSON(原属性值 → 新颜色)', '{"#ff0000":"#167d68","#0000ff":"#ffcc66"}', true)], async run({ files, values: v }) {
const { root } = await readSVG(files), mapping = parseJSON(v.mapping, 100); assert(mapping && !Array.isArray(mapping) && typeof mapping === 'object' && Object.keys(mapping).length, '请填写颜色映射对象。');
for (const value of Object.values(mapping)) assert(typeof value === 'string' && CSS.supports('color', value) && !/currentcolor|inherit|var\(/i.test(value), '替换值必须是固定CSS颜色。');
let replaced = 0; for (const p of paints(root)) if (Object.hasOwn(mapping, p.value)) { p.node.setAttribute(p.attr, mapping[p.value]); replaced++; } assert(replaced, '没有与映射键完全一致的颜色属性,请先提取配色。');
return [...await output(root, 'recolored'), json({ replaced, mapping }, 'recolor.json')];
} }))();
export const svg_transform = (() => ({ fields: [num('sx', 'X缩放', 1, .1, 5, .1), num('sy', 'Y缩放', 1, .1, 5, .1), num('x', 'X平移', 8, -1000, 1000), num('y', 'Y平移', 0, -1000, 1000), num('skew', 'X斜切角度', 0, -60, 60)], async run({ files, values: v }) {
const { root, box } = await readSVG(files), transform = `translate(${v.x} ${v.y}) skewX(${v.skew}) scale(${v.sx} ${v.sy})`; wrapContent(root, transform);
return [...await output(root, 'transformed'), json({ transform, viewBox: box, note: '保留画布;超出部分不可见,可随后用画布调整扩边。' }, 'transform.json')];
} }))();
export const svg_background = (() => ({ fields: [choice('repeat', '重复方式', [['repeat', '平铺'], ['no-repeat', '不重复'], ['repeat-x', '横向'], ['repeat-y', '纵向']]), num('size', '背景宽度(px)', 128, 8, 1024)], async run({ files, values: v }) {
const { value } = await readSVG(files), uri = 'data:image/svg+xml,' + encodeURIComponent(value).replaceAll("'", '%27'), css = `.svg-background { background-image: url("${uri}"); background-size: ${v.size}px auto; background-repeat: ${v.repeat}; min-height: 320px; }`;
return [plain(css, 'background.css', 'text/css'), plain(`<!doctype html><html lang="zh-CN"><meta charset="UTF-8"><title>SVG背景</title><link rel="stylesheet" href="background.css"><body><main class="svg-background"></main></body></html>`, 'example.html', 'text/html'), plain(value, 'background.svg', 'image/svg+xml')];
} }))();
export const svg_accessibility = (() => ({ fields: [text('title', '图形标题', '图片说明'), text('description', '详细描述', '图形内容与含义'), choice('mode', '用途', [['content', '有意义的图片'], ['decorative', '装饰图形']])], async run({ files, values: v }) {
const { root } = await readSVG(files); root.querySelectorAll('title,desc').forEach((n) => n.remove());
if (v.mode === 'decorative') { root.setAttribute('aria-hidden', 'true'); root.setAttribute('focusable', 'false'); }
else { const occupied = new Set([...root.querySelectorAll('[id]')].map((n) => n.id)); let suffix = 0; while (occupied.has(`a11y-title-${suffix}`) || occupied.has(`a11y-desc-${suffix}`)) suffix++;
for (const [tag, value] of [['title', v.title], ['desc', v.description]]) { const node = root.ownerDocument.createElementNS(NS, tag); node.setAttribute('id', `a11y-${tag}-${suffix}`); node.textContent = value; root.prepend(node); } root.setAttribute('role', 'img'); root.setAttribute('aria-labelledby', `a11y-title-${suffix} a11y-desc-${suffix}`);
}
return output(root, 'accessible');
} }))();
export const svg_optimize = (() => ({ fields: [num('precision', '小数精度', 3, 1, 6)], async run({ files, values: v }) {
const { optimize } = await import('svgo/browser'), original = await files[0].text(), { value } = cleanSVG(original), result = optimize(value, { multipass: true, floatPrecision: v.precision });
const safe = cleanSVG(result.data).value, size = (s) => new TextEncoder().encode(s).length;
return [...await svgResults(safe, 'optimized'), json({ originalBytes: size(original), sanitizedBytes: size(value), outputBytes: size(safe), reduction: 1 - size(safe) / size(original), precision: v.precision }, 'optimization.json')];
} }))();
const samplePoints = '[[60,60],[300,60],[300,260],[180,330],[60,260]]';
const pointField = (value = samplePoints) => text('points', '坐标JSON([x,y]数组)', value, true);
function geometry(value, min = 2) { const p = points(value, min); assert(p.every((v) => v.every((n) => Math.abs(n) <= 10000)), '几何坐标绝对值最多10000。'); assert(new Set(p.map((v) => v.join(','))).size === p.length, '坐标点不能重复。'); return p; }
const coords = (p) => p.map((v) => v.join(',')).join(' ');
function geomSVG(body, p) {
const xs = p.map((v) => v[0]), ys = p.map((v) => v[1]), x = Math.min(...xs) - 24, y = Math.min(...ys) - 24, w = Math.max(...xs) - x + 24, h = Math.max(...ys) - y + 24, s = Math.min(1, 1100 / w, 800 / h);
return `<svg xmlns="${NS}" width="${Math.ceil(w * s)}" height="${Math.ceil(h * s)}" viewBox="${x} ${y} ${w} ${h}"><rect x="${x}" y="${y}" width="${w}" height="${h}" fill="white"/>${body}</svg>`;
}
function pathProperties(value) { assert(value.length <= 8000 && /^[MmZzLlHhVvCcSsQqTtAa\s\d.,eE+-]+$/.test(value), 'SVG路径字符无效。'); let p; try { p = new svgPathProperties(value); } catch { throw new Error('SVG路径语法无效。'); } assert(p.getTotalLength() > 0 && p.getTotalLength() <= 100000, '路径长度无效或超过100000。'); return p; }
export const bezier_editor = (() => ({ fields: [pointField('[[40,280],[140,20],[460,20],[580,280]]'), num('samples', '采样数量', 32, 4, 200)], async run({ values: v }) {
const p = geometry(v.points, 4); assert(p.length === 4, '三次贝塞尔需要4个点:起点、两个控制点、终点。'); const d = `M${p[0]} C${p[1]} ${p[2]} ${p[3]}`, props = pathProperties(d), length = props.getTotalLength();
const samples = Array.from({ length: v.samples }, (_, i) => props.getPointAtLength(i / (v.samples - 1) * length));
const body = `<polyline points="${coords(p)}" fill="none" stroke="#b0bdb7" stroke-dasharray="5 5"/><path d="${d}" fill="none" stroke="#167d68" stroke-width="3"/>` + p.map(([x, y], i) => `<circle cx="${x}" cy="${y}" r="5" fill="#c75368"/>${label(`P${i}`, x + 7, y + 4)}`).join('');
return [...await svgResults(geomSVG(body, p), 'bezier'), json({ path: d, length, samples }, 'bezier.json')];
} }))();
export const path_morph = (() => ({ fields: [text('first', '起始路径d', 'M60 60 L300 60 L300 300 L60 300 Z', true), text('second', '结束路径d', 'M180 30 L330 180 L180 330 L30 180 Z', true), num('samples', '重采样点数', 64, 8, 200), num('frames', '输出帧数', 8, 2, 30)], async run({ values: v }) {
const a = pathProperties(v.first), b = pathProperties(v.second), closed = /[Zz]\s*$/.test(v.first); assert(closed === /[Zz]\s*$/.test(v.second), '两条路径需同为闭合或同为开放。');
assert((v.first.match(/[Mm]/g) || []).length === 1 && (v.second.match(/[Mm]/g) || []).length === 1, '形变仅支持单一连续子路径。');
const sample = (p) => Array.from({ length: v.samples }, (_, i) => { const q = p.getPointAtLength(p.getTotalLength() * i / (v.samples - (closed ? 0 : 1))); return [q.x, q.y]; }); const pa = sample(a), pb = sample(b), bounds = [...pa, ...pb]; assert(bounds.flat().every((n) => Number.isFinite(n) && Math.abs(n) <= 10000), '路径坐标无效或过大。');
const entries = []; for (let f = 0; f < v.frames; f++) { const t = f / (v.frames - 1), p = pa.map((q, i) => q.map((n, j) => n * (1 - t) + pb[i][j] * t)); entries.push(plain(geomSVG(`<path d="M${p.map((q) => q.join(',')).join(' L')}${closed ? ' Z' : ''}" fill="${closed ? '#b9ded0' : 'none'}" stroke="#167d68" stroke-width="3"/>`, bounds), `frame-${String(f + 1).padStart(3, '0')}.svg`, 'image/svg+xml')); }
return [entries[0], entries.at(-1), await zip([...entries, json({ frames: v.frames, samples: v.samples, closed, first: pa, last: pb }, 'morph.json')], 'morph-frames.zip')];
} }))();
const clipPoints = (p) => p.map(([x, y]) => ({ X: Math.round(x * 1000), Y: Math.round(y * 1000) }));
const unclip = (paths) => paths.map((path) => path.map((p) => [p.X / 1000, p.Y / 1000]));
function polygonOutput(paths, reference) { return geomSVG(`<path d="${paths.map((p) => 'M' + p.map((v) => v.join(',')).join(' L') + ' Z').join(' ')}" fill="#b9ded0" fill-rule="evenodd" stroke="#167d68" stroke-width="2"/>`, paths.length ? paths.flat() : reference); }
export const polygon_boolean = (() => ({ fields: [text('first', '多边形A坐标', '[[40,40],[250,40],[250,250],[40,250]]', true), text('second', '多边形B坐标', '[[150,150],[350,150],[350,350],[150,350]]', true), choice('operation', '运算', [['union', '并集'], ['intersection', '交集'], ['difference', '差集 A−B'], ['xor', '异或']])], async run({ values: v }) {
const { default: Clipper } = await import('clipper-lib'), a = geometry(v.first, 3), b = geometry(v.second, 3), engine = new Clipper.Clipper(), solution = new Clipper.Paths();
assert(Math.abs(Clipper.Clipper.Area(clipPoints(a))) > 0 && Math.abs(Clipper.Clipper.Area(clipPoints(b))) > 0, '多边形面积必须大于0。'); engine.AddPath(clipPoints(a), Clipper.PolyType.ptSubject, true); engine.AddPath(clipPoints(b), Clipper.PolyType.ptClip, true);
const types = { union: Clipper.ClipType.ctUnion, intersection: Clipper.ClipType.ctIntersection, difference: Clipper.ClipType.ctDifference, xor: Clipper.ClipType.ctXor }; engine.Execute(types[v.operation], solution, Clipper.PolyFillType.pftEvenOdd, Clipper.PolyFillType.pftEvenOdd);
const paths = unclip(solution); return [...await svgResults(polygonOutput(paths, [...a, ...b]), 'boolean'), json({ operation: v.operation, paths, area: Math.abs(solution.reduce((sum, p) => sum + Clipper.Clipper.Area(p), 0)) / 1e6, fillRule: 'evenodd' }, 'boolean.json')];
} }))();
export const stroke_outline = (() => ({ fields: [pointField('[[40,260],[150,60],[280,260],[430,90]]'), num('width', '线宽', 20, 1, 200), choice('join', '连接方式', [['round', '圆角'], ['miter', '尖角'], ['square', '切角']]), choice('cap', '端点', [['round', '圆头'], ['butt', '平头'], ['square', '方头']])], async run({ values: v }) {
const { default: Clipper } = await import('clipper-lib'), p = geometry(v.points), offset = new Clipper.ClipperOffset(2, 250), solution = new Clipper.Paths();
const joins = { round: Clipper.JoinType.jtRound, miter: Clipper.JoinType.jtMiter, square: Clipper.JoinType.jtSquare }, caps = { round: Clipper.EndType.etOpenRound, butt: Clipper.EndType.etOpenButt, square: Clipper.EndType.etOpenSquare };
offset.AddPath(clipPoints(p), joins[v.join], caps[v.cap]); offset.Execute(solution, v.width * 500); const paths = unclip(solution); assert(paths.length, '未生成轮廓。');
return [...await svgResults(polygonOutput(paths, p), 'stroke-outline'), json({ width: v.width, paths }, 'outline.json')];
} }))();
export const point_diagram = (() => ({ fields: [pointField('[[60,60],[300,60],[300,260],[180,330],[60,260],[150,150],[230,120]]'), choice('mode', '几何布局', [['triangles', 'Delaunay三角网'], ['voronoi', 'Voronoi分区'], ['hull', '凸包']])], async run({ values: v }) {
const p = geometry(v.points, 3), hull = polygonHull(p); assert(hull, '点集不能全部共线。'); const delaunay = Delaunay.from(p), xs = p.map((q) => q[0]), ys = p.map((q) => q[1]), bounds = [Math.min(...xs) - 10, Math.min(...ys) - 10, Math.max(...xs) + 10, Math.max(...ys) + 10];
let body, shapes; if (v.mode === 'hull') { shapes = [hull]; body = `<polygon points="${coords(hull)}" fill="#d8eee5" stroke="#167d68"/>`; }
else if (v.mode === 'triangles') { shapes = [...delaunay.trianglePolygons()].map((q) => [...q]); body = `<path d="${delaunay.render()}" fill="none" stroke="#167d68"/>`; }
else { const voronoi = delaunay.voronoi(bounds); shapes = [...voronoi.cellPolygons()].map((q) => [...q]); body = `<path d="${voronoi.render()}${voronoi.renderBounds()}" fill="none" stroke="#167d68"/>`; }
body += p.map(([x, y], i) => `<circle cx="${x}" cy="${y}" r="4" fill="#c75368"/>${label(i + 1, x + 5, y - 5)}`).join(''); return [...await svgResults(geomSVG(body, p), 'point-diagram'), json({ mode: v.mode, points: p, shapes, bounds }, 'geometry.json')];
} }))();
function segmentDistance(p, a, b) { const dx = b[0] - a[0], dy = b[1] - a[1], denom = dx * dx + dy * dy, t = denom ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / denom)) : 0; return Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dy); }
function simplify(p, tolerance) { let largest = 0, index = 0; for (let i = 1; i < p.length - 1; i++) { const distance = segmentDistance(p[i], p[0], p.at(-1)); if (distance > largest) { largest = distance; index = i; } } return largest > tolerance ? [...simplify(p.slice(0, index + 1), tolerance).slice(0, -1), ...simplify(p.slice(index), tolerance)] : [p[0], p.at(-1)]; }
export const polyline_simplify = (() => ({ fields: [pointField('[[30,200],[60,202],[100,198],[140,200],[180,100],[220,102],[260,100],[300,200],[350,202],[390,200]]'), num('tolerance', '允许偏差(坐标单位)', 5, .1, 500, .1)], async run({ values: v }) {
const p = geometry(v.points), reduced = simplify(p, v.tolerance), error = Math.max(...p.map((q) => Math.min(...reduced.slice(1).map((b, i) => segmentDistance(q, reduced[i], b)))));
const body = `<polyline points="${coords(p)}" fill="none" stroke="#b2c5bb" stroke-width="5"/><polyline points="${coords(reduced)}" fill="none" stroke="#167d68" stroke-width="2"/>`;
return [...await svgResults(geomSVG(body, p), 'simplified'), json({ before: p.length, after: reduced.length, tolerance: v.tolerance, maximumPointError: error, points: reduced }, 'simplified.json')];
} }))();
export const polygon_round = (() => ({ fields: [pointField(), num('radius', '沿每边切入距离', 25, 1, 300)], async run({ values: v }) {
const p = geometry(v.points, 3); const corners = p.map((b, i) => { const a = p[(i + p.length - 1) % p.length], c = p[(i + 1) % p.length], left = Math.hypot(a[0] - b[0], a[1] - b[1]), right = Math.hypot(c[0] - b[0], c[1] - b[1]), distance = Math.min(v.radius, left * .49, right * .49); return { b, start: b.map((n, j) => n + (a[j] - n) * distance / left), end: b.map((n, j) => n + (c[j] - n) * distance / right), distance }; });
const d = corners.map((c, i) => `${i ? 'L' : 'M'}${c.start} Q${c.b} ${c.end}`).join(' ') + ' Z';
return [...await svgResults(geomSVG(`<path d="${d}" fill="#d4eee1" stroke="#167d68" stroke-width="2"/>`, p), 'rounded'), json({ path: d, corners, note: '二次贝塞尔圆滑连接;切入距离受短边限制,不是固定半径圆弧。' }, 'rounded.json')];
} }))();