All files / src/plugins convertPathData.ts

97.57% Statements 361/370
94.53% Branches 259/274
100% Functions 24/24
97.56% Lines 360/369
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 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 9471x       1x               1x                                                     129x         16x   113x 113x 113x 113x 113x 113x     113x 113x 1x     112x 112x 112x   112x 112x 112x   112x   112x                                   112x 112x     112x 341x 341x     341x     334x 68x 68x   68x 1x 1x 1x   266x 9x 257x 9x           334x 117x 5x     117x 117x   117x 117x   117x 217x     71x       71x 71x   71x 71x     146x 20x       20x 20x 20x 20x 20x 20x   20x 20x       126x 32x       32x 32x 32x 32x   32x 32x     94x 8x       8x 8x   8x 8x     86x               86x               334x 334x     334x 7x   7x 7x   7x 7x     341x     112x                           112x 112x 112x 112x   112x 328x 328x 328x   328x 321x 321x   321x 13x   13x 10x 10x     10x 10x         321x           19x 19x 19x 19x           19x   19x       19x 19x 19x 19x 19x   19x               3x 3x 3x 3x 3x 3x       3x 1x   3x       19x   19x 21x 21x 8x       8x 8x 8x   21x 14x 14x     14x 6x   14x 14x   12x 12x 12x     2x 2x 2x       2x                           2x 2x 2x   12x 12x   7x       19x 14x     14x 3x 3x 3x 3x 3x 3x 3x   14x 14x 6x 8x   7x           14x 2x   12x 12x 12x             319x 166x 536x   153x 9x 144x 9x 135x 23x 23x   319x   319x 9x 310x 9x   301x 301x   319x   319x 118x 118x       319x 319x       9x 4x   9x 9x 310x 7x 4x   7x 7x 303x         3x 3x 300x 2x 2x             319x 97x 36x 36x 61x 19x 19x           319x               18x 18x 2x   18x 18x 18x       301x   189x   23x         1x 1x 22x           1x 1x 21x           3x 3x   166x     22x         3x 3x 19x           1x 1x           301x   301x 11x 11x       290x 1x 1x       289x 289x   289x     7x 7x 7x 1x   6x     295x     112x                       112x   112x 295x 112x   183x 6x 6x     177x 177x 177x   177x 108x 350x   69x 29x 40x 20x 20x 20x 20x     177x   177x 177x           177x                     31x 31x   177x 177x     112x                     79x                   79x                                 114x 114x 114x   114x 114x 114x 114x   114x 11x     103x 103x           103x                             874x 2411x 110x 110x           874x                 72x 72x 72x 72x   72x   3x       69x 81x 53x       16x                   16x   12x 12x   4x 4x   16x       16x             197x                         197x 197x 197x 197x 197x                           35x 35x 35x 35x                   35x 35x   35x     54x             19x   16x                   26x       26x 108x                                     5x                                 36x 36x 36x 36x 36x                               46x 65x                             28x 113x   28x     1x                
import { applyTransforms, js2path, path2js } from './_path';
 
import { JsApi } from '../jsapi';
import { Plugin } from './_types';
import { cleanupOutData } from './_tools';
 
let roundData: (data: number[]) => number[];
let precision: number;
let error: number;
let arcThreshold: number;
let arcTolerance: number;
 
export const defaultParams = {
  applyTransforms: true,
  applyTransformsStroked: true,
  makeArcs: {
    threshold: 2.5, // Coefficient of rounding error.
    tolerance: 0.5, // Percentage of radius.
  },
  straightCurves: true,
  lineShorthands: true,
  curveSmoothShorthands: true,
  floatPrecision: 3,
  transformPrecision: 5,
  removeUseless: true,
  collapseRepeated: true,
  utilizeAbsolute: true,
  leadingZero: true,
  negativeExtraSpace: true,
};
 
export type Params = typeof defaultParams;
 
/**
 * Convert absolute Path to relative, collapse repeated instructions,
 * detect and convert Lineto shorthands, remove useless instructions like "l0,0",
 * trim useless delimiters and leading zeros, decrease accuracy of floating-point numbers.
 */
function fn(item: JsApi, params: Params) {
  if (
    !(item.isElem('path') || item.isElem('clip-path')) ||
    // TODO: properly reference the attribute using the correct namespace
    !item.hasAttr('android:pathData')
  ) {
    return item;
  }
  precision = params.floatPrecision;
  error = +Math.pow(0.1, precision).toFixed(precision);
  roundData = precision > 0 && precision < 20 ? strongRound : round;
  Eif (params.makeArcs) {
    arcThreshold = params.makeArcs.threshold;
    arcTolerance = params.makeArcs.tolerance;
  }
 
  let data = path2js(item);
  if (!data.length) {
    return item;
  }
 
  convertToRelative(data);
  Eif (params.applyTransforms) {
    data = applyTransforms(item, data, params);
  }
  data = filters(data, params);
  Eif (params.utilizeAbsolute) {
    data = convertToMixed(data, params);
  }
  js2path(item, data, params);
 
  return item;
}
 
/**
 * Convert absolute path data coordinates to relative.
 *
 * @param {Array} path input path data
 * @param {Object} params plugin params
 * @return {Array} output path data
 */
function convertToRelative(
  path: {
    instruction: string;
    coords?: number[];
    base?: number[];
    data?: number[];
  }[],
) {
  const point = [0, 0];
  const subpathPoint = [0, 0];
  let baseItem: { instruction: string; coords?: number[]; data?: number[] };
 
  path.forEach((item, index) => {
    let instruction = item.instruction;
    const data = item.data;
 
    // data !== !z
    if (data) {
      // already relative
      // recalculate current point
      if ('mcslqta'.indexOf(instruction) > -1) {
        point[0] += data[data.length - 2];
        point[1] += data[data.length - 1];
 
        if (instruction === 'm') {
          subpathPoint[0] = point[0];
          subpathPoint[1] = point[1];
          baseItem = item;
        }
      } else if (instruction === 'h') {
        point[0] += data[0];
      } else if (instruction === 'v') {
        point[1] += data[0];
      }
 
      // convert absolute path data coordinates to relative
      // if "M" was not transformed from "m"
      // M → m
      if (instruction === 'M') {
        if (index > 0) {
          instruction = 'm';
        }
 
        data[0] -= point[0];
        data[1] -= point[1];
 
        subpathPoint[0] = point[0] += data[0];
        subpathPoint[1] = point[1] += data[1];
 
        baseItem = item;
      } else if ('LT'.indexOf(instruction) > -1) {
        // L → l
        // T → t
        instruction = instruction.toLowerCase();
 
        // x y
        // 0 1
        data[0] -= point[0];
        data[1] -= point[1];
 
        point[0] += data[0];
        point[1] += data[1];
 
        // C → c
      } else if (instruction === 'C') {
        instruction = 'c';
 
        // x1 y1 x2 y2 x y
        // 0  1  2  3  4 5
        data[0] -= point[0];
        data[1] -= point[1];
        data[2] -= point[0];
        data[3] -= point[1];
        data[4] -= point[0];
        data[5] -= point[1];
 
        point[0] += data[4];
        point[1] += data[5];
 
        // S → s
        // Q → q
      } else if ('SQ'.indexOf(instruction) > -1) {
        instruction = instruction.toLowerCase();
 
        // x1 y1 x y
        // 0  1  2 3
        data[0] -= point[0];
        data[1] -= point[1];
        data[2] -= point[0];
        data[3] -= point[1];
 
        point[0] += data[2];
        point[1] += data[3];
 
        // A → a
      } else if (instruction === 'A') {
        instruction = 'a';
 
        // rx ry x-axis-rotation large-arc-flag sweep-flag x y
        // 0  1  2               3              4          5 6
        data[5] -= point[0];
        data[6] -= point[1];
 
        point[0] += data[5];
        point[1] += data[6];
 
        // H → h
      } else Iif (instruction === 'H') {
        instruction = 'h';
 
        data[0] -= point[0];
 
        point[0] += data[0];
 
        // V → v
      } else Iif (instruction === 'V') {
        instruction = 'v';
 
        data[0] -= point[1];
 
        point[1] += data[0];
      }
 
      item.instruction = instruction;
      item.data = data;
 
      // store absolute coordinates for later use
      item.coords = point.slice(-2);
    } else Eif (instruction === 'z') {
      // !data === z, reset current point
      Eif (baseItem) {
        item.coords = baseItem.coords;
      }
      point[0] = subpathPoint[0];
      point[1] = subpathPoint[1];
    }
 
    item.base = index > 0 ? path[index - 1].coords : [0, 0];
  });
 
  return path;
}
 
function filters(
  pathRes: {
    instruction: string;
    coords?: number[];
    base?: number[];
    data?: number[];
    // TODO: avoid this caching hackery?
    sdata?: number[];
  }[],
  params: Params,
) {
  const stringify = data2Path.bind(undefined, params);
  const relSubpoint = [0, 0];
  const pathBase = [0, 0];
  let prev: any = {};
 
  pathRes = pathRes.filter(function(item, index, path) {
    let instruction = item.instruction;
    let data = item.data;
    let next = path[index + 1];
 
    if (data) {
      let sdata = data;
      let circle;
 
      if (instruction === 's') {
        sdata = [0, 0].concat(data);
 
        if ('cs'.indexOf(prev.instruction) > -1) {
          const pdata = prev.data;
          const n = pdata.length;
 
          // (-x, -y) of the prev tangent point relative to the current point
          sdata[0] = pdata[n - 2] - pdata[n - 4];
          sdata[1] = pdata[n - 1] - pdata[n - 3];
        }
      }
 
      // convert curves to arcs if possible
      if (
        params.makeArcs &&
        (instruction === 'c' || instruction === 's') &&
        isConvex(sdata) &&
        (circle = findCircle(sdata))
      ) {
        const r = roundData([circle.radius])[0];
        let angle = findArcAngle(sdata, circle);
        const sweep = sdata[5] * sdata[0] - sdata[4] * sdata[1] > 0 ? 1 : 0;
        let arc = {
          instruction: 'a',
          data: [r, r, 0, 0, sweep, sdata[4], sdata[5]],
          coords: item.coords.slice(),
          base: item.base,
        };
        const output = [arc];
        // relative coordinates to adjust the found circle
        const relCenter = [
          circle.center[0] - sdata[4],
          circle.center[1] - sdata[5],
        ];
        const relCircle = { center: relCenter, radius: circle.radius };
        const arcCurves = [item];
        let hasPrev = 0;
        let suffix = '';
        let nextLonghand;
 
        if (
          (prev.instruction === 'c' &&
            isConvex(prev.data) &&
            isArcPrev(prev.data, circle)) ||
          (prev.instruction === 'a' &&
            prev.sdata &&
            isArcPrev(prev.sdata, circle))
        ) {
          arcCurves.unshift(prev);
          arc.base = prev.base;
          arc.data[5] = arc.coords[0] - arc.base[0];
          arc.data[6] = arc.coords[1] - arc.base[1];
          const prevData = prev.instruction === 'a' ? prev.sdata : prev.data;
          angle += findArcAngle(prevData, {
            center: [prevData[4] + relCenter[0], prevData[5] + relCenter[1]],
            radius: circle.radius,
          });
          if (angle > Math.PI) {
            arc.data[3] = 1;
          }
          hasPrev = 1;
        }
 
        // check if next curves are fitting the arc
        let j = index;
        // tslint:disable-next-line:no-bitwise
        for (; (next = path[++j]) && ~'cs'.indexOf(next.instruction); ) {
          let nextData = next.data;
          if (next.instruction === 's') {
            nextLonghand = makeLonghand(
              { instruction: 's', data: next.data.slice() },
              path[j - 1].data,
            );
            nextData = nextLonghand.data;
            nextLonghand.data = nextData.slice(0, 2);
            suffix = stringify([nextLonghand]);
          }
          if (isConvex(nextData) && isArc(nextData, relCircle)) {
            angle += findArcAngle(nextData, relCircle);
            Iif (angle - 2 * Math.PI > 1e-3) {
              break; // more than 360°
            }
            if (angle > Math.PI) {
              arc.data[3] = 1;
            }
            arcCurves.push(next);
            if (2 * Math.PI - angle > 1e-3) {
              // less than 360°
              arc.coords = next.coords;
              arc.data[5] = arc.coords[0] - arc.base[0];
              arc.data[6] = arc.coords[1] - arc.base[1];
            } else {
              // full circle, make a half-circle arc and add a second one
              arc.data[5] = 2 * (relCircle.center[0] - nextData[4]);
              arc.data[6] = 2 * (relCircle.center[1] - nextData[5]);
              arc.coords = [
                arc.base[0] + arc.data[5],
                arc.base[1] + arc.data[6],
              ];
              arc = {
                instruction: 'a',
                data: [
                  r,
                  r,
                  0,
                  0,
                  sweep,
                  next.coords[0] - arc.coords[0],
                  next.coords[1] - arc.coords[1],
                ],
                coords: next.coords,
                base: arc.coords,
              };
              output.push(arc);
              j++;
              break;
            }
            relCenter[0] -= nextData[4];
            relCenter[1] -= nextData[5];
          } else {
            break;
          }
        }
 
        if ((stringify(output) + suffix).length < stringify(arcCurves).length) {
          Iif (path[j] && path[j].instruction === 's') {
            makeLonghand(path[j], path[j - 1].data);
          }
          if (hasPrev) {
            const prevArc = output.shift();
            roundData(prevArc.data);
            relSubpoint[0] += prevArc.data[5] - prev.data[prev.data.length - 2];
            relSubpoint[1] += prevArc.data[6] - prev.data[prev.data.length - 1];
            prev.instruction = 'a';
            prev.data = prevArc.data;
            item.base = prev.coords = prevArc.coords;
          }
          arc = output.shift();
          if (arcCurves.length === 1) {
            item.sdata = sdata.slice(); // preserve curve data for future checks
          } else if (arcCurves.length - 1 - hasPrev > 0) {
            // filter out consumed next items
            path.splice.apply(path, [
              index + 1,
              arcCurves.length - 1 - hasPrev,
              ...output,
            ]);
          }
          if (!arc) {
            return false;
          }
          instruction = 'a';
          data = arc.data;
          item.coords = arc.coords;
        }
      }
 
      // Rounding relative coordinates, taking in account accummulating error
      // to get closer to absolute coordinates. Sum of rounded value remains same:
      // l .25 3 .25 2 .25 3 .25 2 -> l .3 3 .2 2 .3 3 .2 2
      if ('mltqsc'.indexOf(instruction) > -1) {
        for (let i = data.length; i--; ) {
          data[i] += item.base[i % 2] - relSubpoint[i % 2];
        }
      } else if (instruction === 'h') {
        data[0] += item.base[0] - relSubpoint[0];
      } else if (instruction === 'v') {
        data[0] += item.base[1] - relSubpoint[1];
      } else if (instruction === 'a') {
        data[5] += item.base[0] - relSubpoint[0];
        data[6] += item.base[1] - relSubpoint[1];
      }
      roundData(data);
 
      if (instruction === 'h') {
        relSubpoint[0] += data[0];
      } else if (instruction === 'v') {
        relSubpoint[1] += data[0];
      } else {
        relSubpoint[0] += data[data.length - 2];
        relSubpoint[1] += data[data.length - 1];
      }
      roundData(relSubpoint);
 
      if (instruction.toLowerCase() === 'm') {
        pathBase[0] = relSubpoint[0];
        pathBase[1] = relSubpoint[1];
      }
 
      // convert straight curves into lines segments
      Eif (params.straightCurves) {
        if (
          (instruction === 'c' && isCurveStraightLine(data)) ||
          (instruction === 's' && isCurveStraightLine(sdata))
        ) {
          if (next && next.instruction === 's') {
            makeLonghand(next, data); // fix up next curve
          }
          instruction = 'l';
          data = data.slice(-2);
        } else if (instruction === 'q' && isCurveStraightLine(data)) {
          if (next && next.instruction === 't') {
            makeLonghand(next, data); // fix up next curve
          }
          instruction = 'l';
          data = data.slice(-2);
        } else if (
          instruction === 't' &&
          prev.instruction !== 'q' &&
          prev.instruction !== 't'
        ) {
          instruction = 'l';
          data = data.slice(-2);
        } else if (instruction === 'a' && (data[0] === 0 || data[1] === 0)) {
          instruction = 'l';
          data = data.slice(-2);
        }
      }
 
      // horizontal and vertical line shorthands
      // l 50 0 → h 50
      // l 0 50 → v 50
      if (params.lineShorthands && instruction === 'l') {
        if (data[1] === 0) {
          instruction = 'h';
          data.pop();
        } else if (data[0] === 0) {
          instruction = 'v';
          data.shift();
        }
      }
 
      // collapse repeated commands
      // h 20 h 30 -> h 50
      if (
        params.collapseRepeated &&
        'mhv'.indexOf(instruction) > -1 &&
        prev.instruction &&
        instruction === prev.instruction.toLowerCase() &&
        ((instruction !== 'h' && instruction !== 'v') ||
          prev.data[0] >= 0 === item.data[0] >= 0)
      ) {
        prev.data[0] += data[0];
        if (instruction !== 'h' && instruction !== 'v') {
          prev.data[1] += data[1];
        }
        prev.coords = item.coords;
        path[index] = prev;
        return false;
      }
 
      // convert curves into smooth shorthands
      if (params.curveSmoothShorthands && prev.instruction) {
        // curveto
        if (instruction === 'c') {
          // c + c → c + s
          if (
            prev.instruction === 'c' &&
            data[0] === -(prev.data[2] - prev.data[4]) &&
            data[1] === -(prev.data[3] - prev.data[5])
          ) {
            instruction = 's';
            data = data.slice(2);
          } else if (
            prev.instruction === 's' &&
            data[0] === -(prev.data[0] - prev.data[2]) &&
            data[1] === -(prev.data[1] - prev.data[3])
          ) {
            // s + c → s + s
            instruction = 's';
            data = data.slice(2);
          } else if (
            'cs'.indexOf(prev.instruction) === -1 &&
            data[0] === 0 &&
            data[1] === 0
          ) {
            // [^cs] + c → [^cs] + s
            instruction = 's';
            data = data.slice(2);
          }
        } else if (instruction === 'q') {
          // quadratic Bézier curveto
          // q + q → q + t
          if (
            prev.instruction === 'q' &&
            data[0] === prev.data[2] - prev.data[0] &&
            data[1] === prev.data[3] - prev.data[1]
          ) {
            instruction = 't';
            data = data.slice(2);
          } else if (
            prev.instruction === 't' &&
            data[2] === prev.data[0] &&
            data[3] === prev.data[1]
          ) {
            // t + q → t + t
            instruction = 't';
            data = data.slice(2);
          }
        }
      }
 
      // remove useless non-first path segments
      Eif (params.removeUseless) {
        // l 0,0 / h 0 / v 0 / q 0,0 0,0 / t 0,0 / c 0,0 0,0 0,0 / s 0,0 0,0
        if ('lhvqtcs'.indexOf(instruction) > -1 && data.every(i => i === 0)) {
          path[index] = prev;
          return false;
        }
 
        // a 25,25 -30 0,1 0,0
        if (instruction === 'a' && data[5] === 0 && data[6] === 0) {
          path[index] = prev;
          return false;
        }
      }
 
      item.instruction = instruction;
      item.data = data;
 
      prev = item;
    } else {
      // z resets coordinates
      relSubpoint[0] = pathBase[0];
      relSubpoint[1] = pathBase[1];
      if (prev.instruction === 'z') {
        return false;
      }
      prev = item;
    }
 
    return true;
  });
 
  return pathRes;
}
 
/**
 * Writes data in shortest form using absolute or relative coordinates.
 * @param {Array} data input path data
 * @return {Boolean} output
 */
function convertToMixed(
  path: { instruction: string; data?: number[]; base?: number[] }[],
  params: Params,
) {
  let prev = path[0];
 
  path = path.filter(function(item, index) {
    if (index === 0) {
      return true;
    }
    if (!item.data) {
      prev = item;
      return true;
    }
 
    const instruction = item.instruction;
    const data = item.data;
    const adata = data && data.slice(0);
 
    if ('mltqsc'.indexOf(instruction) > -1) {
      for (let i = adata.length; i--; ) {
        adata[i] += item.base[i % 2];
      }
    } else if (instruction === 'h') {
      adata[0] += item.base[0];
    } else if (instruction === 'v') {
      adata[0] += item.base[1];
    } else Eif (instruction === 'a') {
      adata[5] += item.base[0];
      adata[6] += item.base[1];
    }
 
    roundData(adata);
 
    const absoluteDataStr = cleanupOutData(adata, params);
    const relativeDataStr = cleanupOutData(data, params);
 
    // Convert to absolute coordinates if it's shorter.
    // v-20 -> V0
    // Don't convert if it fits following previous instruction.
    // l20 30-10-50 instead of l20 30L20 30
    if (
      absoluteDataStr.length < relativeDataStr.length &&
      !(
        params.negativeExtraSpace &&
        instruction === prev.instruction &&
        prev.instruction.charCodeAt(0) > 96 &&
        absoluteDataStr.length === relativeDataStr.length - 1 &&
        (data[0] < 0 ||
          (/^0\./.test(String(data[0])) && prev.data[prev.data.length - 1] % 1))
      )
    ) {
      item.instruction = instruction.toUpperCase();
      item.data = adata;
    }
    prev = item;
    return true;
  });
 
  return path;
}
 
/**
 * Checks if curve is convex. Control points of such a curve must form
 * a convex quadrilateral with diagonals crosspoint inside of it.
 *
 * @param {Array} data input path data
 * @return {Boolean} output
 */
function isConvex(data: number[]) {
  const center = getIntersection([
    0,
    0,
    data[2],
    data[3],
    data[0],
    data[1],
    data[4],
    data[5],
  ]);
  return (
    center &&
    data[2] < center[0] === center[0] < 0 &&
    data[3] < center[1] === center[1] < 0 &&
    data[4] < center[0] === center[0] < data[0] &&
    data[5] < center[1] === center[1] < data[1]
  );
}
 
/**
 * Computes lines equations by two points and returns their intersection point.
 *
 * @param {Array} coords 8 numbers for 4 pairs of coordinates (x,y)
 * @return {Array|undefined} output coordinate of lines' crosspoint
 */
function getIntersection(coords: number[]) {
  // Prev line equation parameters.
  const a1 = coords[1] - coords[3]; // y1 - y2
  const b1 = coords[2] - coords[0]; // x2 - x1
  const c1 = coords[0] * coords[3] - coords[2] * coords[1]; // x1 * y2 - x2 * y1
  // Next line equation parameters
  const a2 = coords[5] - coords[7]; // y1 - y2
  const b2 = coords[6] - coords[4]; // x2 - x1
  const c2 = coords[4] * coords[7] - coords[5] * coords[6]; // x1 * y2 - x2 * y1
  const denom = a1 * b2 - a2 * b1;
 
  if (!denom) {
    return undefined; // parallel lines havn't an intersection
  }
 
  const cross = [(b1 * c2 - b2 * c1) / denom, (a1 * c2 - a2 * c1) / -denom];
  Eif (
    !isNaN(cross[0]) &&
    !isNaN(cross[1]) &&
    isFinite(cross[0]) &&
    isFinite(cross[1])
  ) {
    return cross;
  }
  return undefined;
}
 
/**
 * Decrease accuracy of floating-point numbers
 * in path data keeping a specified number of decimals.
 * Smart rounds values like 2.3491 to 2.35 instead of 2.349.
 * Doesn't apply "smartness" if the number precision fits already.
 *
 * @param {Array} data input data array
 * @return {Array} output data array
 */
function strongRound(data: number[]) {
  for (let i = data.length; i-- > 0; ) {
    if (+data[i].toFixed(precision) !== data[i]) {
      const rounded = +data[i].toFixed(precision - 1);
      data[i] =
        +Math.abs(rounded - data[i]).toFixed(precision + 1) >= error
          ? +data[i].toFixed(precision)
          : rounded;
    }
  }
  return data;
}
 
/**
 * Checks if a curve is a straight line by measuring distance
 * from middle points to the line formed by end points.
 */
function isCurveStraightLine(data: number[]) {
  // Get line equation a·x + b·y + c = 0 coefficients a, b (c = 0) by start and end points.
  let i = data.length - 2;
  const a = -data[i + 1]; // y1 − y2 (y1 = 0)
  const b = data[i]; // x2 − x1 (x1 = 0)
  const d = 1 / (a * a + b * b); // same part for all points
 
  if (i <= 1 || !isFinite(d)) {
    // Curve that ends at start point isn't the case.
    return false;
  }
 
  // Distance from point (x0, y0) to the line is sqrt((c − a·x0 − b·y0)² / (a² + b²))
  while ((i -= 2) >= 0) {
    if (Math.sqrt(Math.pow(a * data[i] + b * data[i + 1], 2) * d) > error) {
      return false;
    }
  }
 
  return true;
}
 
/**
 * Converts next curve from shorthand to full form using the current curve data.
 */
function makeLonghand<T extends { instruction: string; data?: number[] }>(
  item: T,
  data: number[],
) {
  switch (item.instruction) {
    case 's':
      item.instruction = 'c';
      break;
    case 't':
      item.instruction = 'q';
      break;
  }
  item.data.unshift(
    data[data.length - 2] - data[data.length - 4],
    data[data.length - 1] - data[data.length - 3],
  );
  return item;
}
 
/**
 * Returns distance between two points.
 */
function getDistance(p1: number[], p2: number[]) {
  return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2));
}
 
/**
 * Returns coordinates of the curve point corresponding to the certain t
 * a·(1 - t)³·p1 + b·(1 - t)²·t·p2 + c·(1 - t)·t²·p3 + d·t³·p4,
 * where pN are control points and p1 is zero due to relative coordinates.
 * @param {Array} curve array of curve points coordinates
 * @param {Number} t parametric position from 0 to 1
 * @return {Array} Point coordinates
 */
 
function getCubicBezierPoint(curve: number[], t: number): [number, number] {
  const sqrT = t * t;
  const cubT = sqrT * t;
  const mt = 1 - t;
  const sqrMt = mt * mt;
  return [
    3 * sqrMt * t * curve[0] + 3 * mt * sqrT * curve[2] + cubT * curve[4],
    3 * sqrMt * t * curve[1] + 3 * mt * sqrT * curve[3] + cubT * curve[5],
  ];
}
 
/**
 * Finds circle by 3 points of the curve and checks if the curve fits the found circle.
 *
 * @param {Array} curve
 * @return {Object|undefined} circle
 */
 
function findCircle(curve: number[]) {
  const midPoint = getCubicBezierPoint(curve, 1 / 2);
  const m1 = [midPoint[0] / 2, midPoint[1] / 2];
  const m2 = [(midPoint[0] + curve[4]) / 2, (midPoint[1] + curve[5]) / 2];
  const center = getIntersection([
    m1[0],
    m1[1],
    m1[0] + m1[1],
    m1[1] - m1[0],
    m2[0],
    m2[1],
    m2[0] + (m2[1] - midPoint[1]),
    m2[1] - (m2[0] - midPoint[0]),
  ]);
  const radius = center && getDistance([0, 0], center);
  const tolerance = Math.min(arcThreshold * error, arcTolerance * radius / 100);
 
  if (
    center &&
    [1 / 4, 3 / 4].every(point => {
      return (
        Math.abs(
          getDistance(getCubicBezierPoint(curve, point), center) - radius,
        ) <= tolerance
      );
    })
  ) {
    return { center: center, radius: radius };
  }
  return undefined;
}
 
/**
 * Checks if a curve fits the given circle.
 * @param {Object} circle
 * @param {Array} curve
 * @return {Boolean}
 */
function isArc(curve: number[], circle: { center: number[]; radius: number }) {
  const tolerance = Math.min(
    arcThreshold * error,
    arcTolerance * circle.radius / 100,
  );
  return [0, 1 / 4, 1 / 2, 3 / 4, 1].every(point => {
    return (
      Math.abs(
        getDistance(getCubicBezierPoint(curve, point), circle.center) -
          circle.radius,
      ) <= tolerance
    );
  });
}
 
/**
 * Checks if a previous curve fits the given circle.
 * @param {Object} circle
 * @param {Array} curve
 * @return {Boolean}
 */
function isArcPrev(
  curve: number[],
  circle: { center: number[]; radius: number },
) {
  return isArc(curve, {
    center: [circle.center[0] + curve[4], circle.center[1] + curve[5]],
    radius: circle.radius,
  });
}
 
/**
 * Finds angle of a curve fitting the given arc.
 * @param {Array} curve
 * @param {Object} relCircle
 * @return {Number} angle
 */
 
function findArcAngle(
  curve: number[],
  relCircle: { center: number[]; radius: number },
) {
  const x1 = -relCircle.center[0];
  const y1 = -relCircle.center[1];
  const x2 = curve[4] - relCircle.center[0];
  const y2 = curve[5] - relCircle.center[1];
  return Math.acos(
    (x1 * x2 + y1 * y2) / Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2)),
  );
}
 
/**
 * Converts given path data to string.
 *
 * @param {Object} params
 * @param {Array} pathData
 * @return {String}
 */
function data2Path(
  params: Params,
  pathData: { instruction: string; data?: number[] }[],
) {
  return pathData.reduce((pathString, item) => {
    return (
      pathString +
      item.instruction +
      (item.data ? cleanupOutData(roundData(item.data.slice()), params) : '')
    );
  }, '');
}
 
/**
 * Simple rounding function if precision is 0.
 *
 * @param {Array} data input data array
 * @return {Array} output data array
 */
function round(data: number[]) {
  for (let i = data.length; i-- > 0; ) {
    data[i] = Math.round(data[i]);
  }
  return data;
}
 
export const convertPathData: Plugin<Params> = {
  type: 'perItem',
  active: true,
  description:
    'optimizes path data: writes in shorter form, applies transformations',
  params: defaultParams,
  fn,
};