Spaces:
Running

File size: 9,951 Bytes
0a0ec90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// 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;
}