Spaces:
Running

hugging-space / src /pathdata.ts
Chunte's picture
Chunte HF Staff
Hugging Partnership: v9 press arc test build
0a0ec90 verified
Raw History Blame Contribute Delete
9.95 kB
// SVG geometry → absolute cubic Béziers, so any logo shape can be warped smoothly.
export interface SubPath {
x0: number;
y0: number;
// Each segment: control 1, control 2, end point.
segs: [number, number, number, number, number, number][];
closed: boolean;
}
const CMD_RE = /[MmLlHhVvCcSsQqTtAaZz]/;
function tokenize(d: string): (string | number)[] {
const out: (string | number)[] = [];
const re = /([MmLlHhVvCcSsQqTtAaZz])|(-?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?)/g;
let m: RegExpExecArray | null;
while ((m = re.exec(d))) out.push(m[1] ? m[1] : parseFloat(m[2]));
return out;
}
/** Arc flags may be written without separators ("a1 1 0 01 5 5"); re-split those tokens. */
function tokenizeWithArcFlags(d: string): (string | number)[] {
if (!/[Aa]/.test(d)) return tokenize(d);
const out: (string | number)[] = [];
const re = /([MmLlHhVvCcSsQqTtAaZz])|([-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?)/g;
let cmd = '';
let argIndex = 0;
let m: RegExpExecArray | null;
let pos = 0;
while (pos < d.length) {
re.lastIndex = pos;
// Arc flag positions (4th and 5th args of each 7-arg group): a single 0/1 char.
if ((cmd === 'A' || cmd === 'a') && (argIndex % 7 === 3 || argIndex % 7 === 4)) {
const fm = /[\s,]*([01])/y;
fm.lastIndex = pos;
const f = fm.exec(d);
if (f) {
out.push(Number(f[1]));
argIndex++;
pos = fm.lastIndex;
continue;
}
}
m = re.exec(d);
if (!m) break;
pos = re.lastIndex;
if (m[1]) {
cmd = m[1];
argIndex = 0;
out.push(m[1]);
} else {
out.push(parseFloat(m[2]));
argIndex++;
}
}
return out;
}
function arcToCubics(
x1: number,
y1: number,
rx: number,
ry: number,
phiDeg: number,
fa: number,
fs: number,
x2: number,
y2: number,
): [number, number, number, number, number, number][] {
if (rx === 0 || ry === 0 || (x1 === x2 && y1 === y2)) return [[x1, y1, x2, y2, x2, y2]];
rx = Math.abs(rx);
ry = Math.abs(ry);
const phi = (phiDeg * Math.PI) / 180;
const cos = Math.cos(phi);
const sin = Math.sin(phi);
const dx = (x1 - x2) / 2;
const dy = (y1 - y2) / 2;
const x1p = cos * dx + sin * dy;
const y1p = -sin * dx + cos * dy;
const lam = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
if (lam > 1) {
rx *= Math.sqrt(lam);
ry *= Math.sqrt(lam);
}
const num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
const den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
let co = Math.sqrt(Math.max(0, num / den));
if (fa === fs) co = -co;
const cxp = (co * rx * y1p) / ry;
const cyp = (-co * ry * x1p) / rx;
const cx = cos * cxp - sin * cyp + (x1 + x2) / 2;
const cy = sin * cxp + cos * cyp + (y1 + y2) / 2;
const ang = (ux: number, uy: number, vx: number, vy: number) => {
const a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
return a;
};
const t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
let dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);
if (!fs && dt > 0) dt -= Math.PI * 2;
if (fs && dt < 0) dt += Math.PI * 2;
const n = Math.ceil(Math.abs(dt) / (Math.PI / 2) - 1e-9);
const out: [number, number, number, number, number, number][] = [];
const step = dt / n;
const k = (4 / 3) * Math.tan(step / 4);
let a = t1;
const pt = (t: number) => {
const ex = rx * Math.cos(t);
const ey = ry * Math.sin(t);
return [cx + cos * ex - sin * ey, cy + sin * ex + cos * ey];
};
const der = (t: number) => {
const ex = -rx * Math.sin(t);
const ey = ry * Math.cos(t);
return [cos * ex - sin * ey, sin * ex + cos * ey];
};
for (let i = 0; i < n; i++) {
const b = a + step;
const [ax, ay] = pt(a);
const [bx, by] = pt(b);
const [dax, day] = der(a);
const [dbx, dby] = der(b);
out.push([ax + k * dax, ay + k * day, bx - k * dbx, by - k * dby, bx, by]);
a = b;
}
return out;
}
export function parsePath(d: string): SubPath[] {
const t = tokenizeWithArcFlags(d);
const subs: SubPath[] = [];
let cur: SubPath | null = null;
let x = 0;
let y = 0;
let sx = 0;
let sy = 0;
let lastCtrl: [number, number] | null = null; // for S
let lastQ: [number, number] | null = null; // for T
let i = 0;
let cmd = '';
const num = () => {
const v = t[i++];
return typeof v === 'number' ? v : NaN;
};
const ensure = () => {
if (!cur) {
cur = { x0: x, y0: y, segs: [], closed: false };
subs.push(cur);
}
return cur;
};
const lineTo = (nx: number, ny: number) => {
ensure().segs.push([x + (nx - x) / 3, y + (ny - y) / 3, x + ((nx - x) * 2) / 3, y + ((ny - y) * 2) / 3, nx, ny]);
x = nx;
y = ny;
};
while (i < t.length) {
if (typeof t[i] === 'string') cmd = t[i++] as string;
else if (!cmd) {
i++;
continue;
}
const rel = cmd === cmd.toLowerCase();
const C = cmd.toUpperCase();
let ctrlSet = false;
let qSet = false;
switch (C) {
case 'M': {
const nx = num() + (rel ? x : 0);
const ny = num() + (rel ? y : 0);
x = sx = nx;
y = sy = ny;
cur = { x0: x, y0: y, segs: [], closed: false };
subs.push(cur);
cmd = rel ? 'l' : 'L'; // implicit lineto for further pairs
break;
}
case 'L':
lineTo(num() + (rel ? x : 0), num() + (rel ? y : 0));
break;
case 'H':
lineTo(num() + (rel ? x : 0), y);
break;
case 'V':
lineTo(x, num() + (rel ? y : 0));
break;
case 'C': {
const x1 = num() + (rel ? x : 0);
const y1 = num() + (rel ? y : 0);
const x2 = num() + (rel ? x : 0);
const y2 = num() + (rel ? y : 0);
const nx = num() + (rel ? x : 0);
const ny = num() + (rel ? y : 0);
ensure().segs.push([x1, y1, x2, y2, nx, ny]);
lastCtrl = [x2, y2];
ctrlSet = true;
x = nx;
y = ny;
break;
}
case 'S': {
const x1 = lastCtrl ? 2 * x - lastCtrl[0] : x;
const y1 = lastCtrl ? 2 * y - lastCtrl[1] : y;
const x2 = num() + (rel ? x : 0);
const y2 = num() + (rel ? y : 0);
const nx = num() + (rel ? x : 0);
const ny = num() + (rel ? y : 0);
ensure().segs.push([x1, y1, x2, y2, nx, ny]);
lastCtrl = [x2, y2];
ctrlSet = true;
x = nx;
y = ny;
break;
}
case 'Q':
case 'T': {
let qx: number;
let qy: number;
if (C === 'Q') {
qx = num() + (rel ? x : 0);
qy = num() + (rel ? y : 0);
} else {
qx = lastQ ? 2 * x - lastQ[0] : x;
qy = lastQ ? 2 * y - lastQ[1] : y;
}
const nx = num() + (rel ? x : 0);
const ny = num() + (rel ? y : 0);
ensure().segs.push([x + (2 / 3) * (qx - x), y + (2 / 3) * (qy - y), nx + (2 / 3) * (qx - nx), ny + (2 / 3) * (qy - ny), nx, ny]);
lastQ = [qx, qy];
qSet = true;
x = nx;
y = ny;
break;
}
case 'A': {
const rx = num();
const ry = num();
const rot = num();
const fa = num();
const fs = num();
const nx = num() + (rel ? x : 0);
const ny = num() + (rel ? y : 0);
const seg = ensure();
for (const c of arcToCubics(x, y, rx, ry, rot, fa, fs, nx, ny)) seg.segs.push(c);
x = nx;
y = ny;
break;
}
case 'Z': {
if (cur) {
if (x !== sx || y !== sy) lineTo(sx, sy);
(cur as SubPath).closed = true;
}
x = sx;
y = sy;
cur = null;
break;
}
default:
i++;
}
if (!ctrlSet) lastCtrl = null;
if (!qSet) lastQ = null;
if (Number.isNaN(x) || Number.isNaN(y)) break;
// Stop if we hit a command letter we don't understand.
if (i < t.length && typeof t[i] === 'string' && !CMD_RE.test(t[i] as string)) break;
}
return subs.filter((s) => s.segs.length > 0);
}
/** Geometry of basic shapes as path data (in the element's own coordinates). */
export function shapeToPath(el: Element): string | null {
const n = (a: string) => parseFloat(el.getAttribute(a) ?? '0') || 0;
switch (el.tagName.toLowerCase()) {
case 'path':
return el.getAttribute('d');
case 'rect': {
const x = n('x');
const y = n('y');
const w = n('width');
const h = n('height');
if (w <= 0 || h <= 0) return null;
let rx = el.hasAttribute('rx') ? n('rx') : el.hasAttribute('ry') ? n('ry') : 0;
let ry = el.hasAttribute('ry') ? n('ry') : rx;
rx = Math.min(rx, w / 2);
ry = Math.min(ry, h / 2);
if (!rx || !ry) return `M${x} ${y}H${x + w}V${y + h}H${x}Z`;
return (
`M${x + rx} ${y}H${x + w - rx}A${rx} ${ry} 0 0 1 ${x + w} ${y + ry}V${y + h - ry}` +
`A${rx} ${ry} 0 0 1 ${x + w - rx} ${y + h}H${x + rx}A${rx} ${ry} 0 0 1 ${x} ${y + h - ry}` +
`V${y + ry}A${rx} ${ry} 0 0 1 ${x + rx} ${y}Z`
);
}
case 'circle':
case 'ellipse': {
const cx = n('cx');
const cy = n('cy');
const rx = el.tagName.toLowerCase() === 'circle' ? n('r') : n('rx');
const ry = el.tagName.toLowerCase() === 'circle' ? n('r') : n('ry');
if (rx <= 0 || ry <= 0) return null;
return `M${cx - rx} ${cy}A${rx} ${ry} 0 1 0 ${cx + rx} ${cy}A${rx} ${ry} 0 1 0 ${cx - rx} ${cy}Z`;
}
case 'line':
return `M${n('x1')} ${n('y1')}L${n('x2')} ${n('y2')}`;
case 'polyline':
case 'polygon': {
const pts = (el.getAttribute('points') ?? '').trim().split(/[\s,]+/).map(Number);
if (pts.length < 4) return null;
let d = `M${pts[0]} ${pts[1]}`;
for (let i = 2; i + 1 < pts.length; i += 2) d += `L${pts[i]} ${pts[i + 1]}`;
return el.tagName.toLowerCase() === 'polygon' ? d + 'Z' : d;
}
}
return null;
}