File size: 2,228 Bytes
04f98c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { SVGPathData } from "./SVGPathData";
import { SVGCommand } from "./types";

// Encode SVG PathData
// http://www.w3.org/TR/SVG/paths.html#PathDataBNF

// Private consts : Char groups
const WSP = " ";

export function encodeSVGPath(commands: SVGCommand | SVGCommand[]) {
  let str = "";

  if (!Array.isArray(commands)) {
    commands = [commands];
  }
  for (let i = 0; i < commands.length; i++) {
    const command = commands[i];
    if (command.type === SVGPathData.CLOSE_PATH) {
      str += "z";
    } else if (command.type === SVGPathData.HORIZ_LINE_TO) {
      str += (command.relative ? "h" : "H") +
        command.x;
    } else if (command.type === SVGPathData.VERT_LINE_TO) {
      str += (command.relative ? "v" : "V") +
        command.y;
    } else if (command.type === SVGPathData.MOVE_TO) {
      str += (command.relative ? "m" : "M") +
        command.x + WSP + command.y;
    } else if (command.type === SVGPathData.LINE_TO) {
      str += (command.relative ? "l" : "L") +
        command.x + WSP + command.y;
    } else if (command.type === SVGPathData.CURVE_TO) {
      str += (command.relative ? "c" : "C") +
        command.x1 + WSP + command.y1 +
        WSP + command.x2 + WSP + command.y2 +
        WSP + command.x + WSP + command.y;
    } else if (command.type === SVGPathData.SMOOTH_CURVE_TO) {
      str += (command.relative ? "s" : "S") +
        command.x2 + WSP + command.y2 +
        WSP + command.x + WSP + command.y;
    } else if (command.type === SVGPathData.QUAD_TO) {
      str += (command.relative ? "q" : "Q") +
        command.x1 + WSP + command.y1 +
        WSP + command.x + WSP + command.y;
    } else if (command.type === SVGPathData.SMOOTH_QUAD_TO) {
      str += (command.relative ? "t" : "T") +
        command.x + WSP + command.y;
    } else if (command.type === SVGPathData.ARC) {
      str += (command.relative ? "a" : "A") +
        command.rX + WSP + command.rY +
        WSP + command.xRot +
        WSP + (+command.lArcFlag) + WSP + (+command.sweepFlag) +
        WSP + command.x + WSP + command.y;
    } else {
      // Unknown command
      throw new Error(
        `Unexpected command type "${ (command as any).type}" at index ${i}.`);
    }
  }

  return str;
}