All files / src index.js

95.74% Statements 180/188
93.79% Branches 151/161
93.75% Functions 30/32
96.24% Lines 179/186

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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          4x 4x 4x 4x 4x 4x       12x   23x     12x 1x 17x 2x   3x 3x                 12x 12x 23x         12x             761x 1612x       72x   1540x       2x   1538x       2x   1536x 757x 757x 4x     1532x               753x 753x   753x   753x     753x 27x   726x 76x     76x                     650x         55x     55x 55x   55x   55x 55x 55x 55x 55x 55x 55x   55x         234x 234x 234x   272x       234x     234x 234x   234x 234x   234x 1x                 234x     1697x     1x         234x         228x   232x     1x             6x 1x           234x     1697x     1x               234x       761x 761x 761x   761x 12x     12x   749x     761x 80x       681x 231x 230x 230x 230x 230x 230x     230x       230x         230x       1x     1x     1x   1x     1x     1x     450x   1x     449x 12x     437x 4x     4x     433x 4x     4x     429x 16x     413x       16x     397x         220x         680x 677x 677x 146x       1x                 234x 3x     234x 761x 761x     234x 233x     234x       48x 225x     48x 225x     48x 48x 48x 4x   13x     44x   3x     48x         48x         200x         5x         48x 37x                   48x                                                                   48x 225x     225x 225x 225x 225x   225x 23x   225x 225x               225x 17x   225x 264x         225x   225x 17x       225x 3x         225x 225x 226x   227x   226x   226x                               48x 48x 48x 6x   48x       4x  
/* eslint-disable complexity,prefer-reflect,max-len,newline-after-var */
/* eslint no-multi-str:0 */
 
'use strict';
 
const { ucs2 } = require('punycode');
const { Transform } = require('stream');
const Sax = require('sax');
const { SVGPathData } = require('svg-pathdata');
const svgShapesToPath = require('./svgshapes2svgpath');
const { Matrix } = require('./Matrix');
 
// Transform helpers (will move elsewhere later)
function parseTransforms(value) {
  return value
    .match(/(rotate|translate|scale|skewX|skewY|matrix)\s*\(([^)]*)\)\s*/g)
    .map((transform) => transform.match(/[\w.-]+/g));
}
function matrixFromTransformAttribute(transformAttributeString) {
  const transformations = {
    matrix: (result, ...args) => result.transform(...args),
    translate: (result, x, y = 0) => result.translate(x, y),
    scale: (result, x, y = x) => result.scale(x, y),
    rotate: (result, a, x = 0, y = 0) => {
      Eif (0 === x && 0 === y) {
        result.rotateDeg(a);
      } else {
        result.translate(x, y).rotateDeg(a).translate(-x, -y);
      }
    },
    skewX: (result, a) => result.skewX((a * Math.PI) / 180),
    skewY: (result, a) => result.skewY((a * Math.PI) / 180),
  };
 
  const result = new Matrix();
  for (const transform of parseTransforms(transformAttributeString)) {
    transformations[transform[0]](
      result,
      ...transform.slice(1).map(parseFloat)
    );
  }
  return result;
}
 
// Rendering
function tagShouldRender(curTag, parents) {
  let values;
 
  return !parents.some((tag) => {
    if (
      'undefined' !== typeof tag.attributes.display &&
      'none' === tag.attributes.display.toLowerCase()
    ) {
      return true;
    }
    if (
      'undefined' !== typeof tag.attributes.width &&
      0 === parseFloat(tag.attributes.width)
    ) {
      return true;
    }
    if (
      'undefined' !== typeof tag.attributes.height &&
      0 === parseFloat(tag.attributes.height)
    ) {
      return true;
    }
    if ('undefined' !== typeof tag.attributes.viewBox) {
      values = tag.attributes.viewBox.split(/\s*,*\s|\s,*\s*|,/);
      if (0 === parseFloat(values[2]) || 0 === parseFloat(values[3])) {
        return true;
      }
    }
    return false;
  });
}
 
// According to the document (http://www.w3.org/TR/SVG/painting.html#FillProperties)
// fill <paint> none|currentColor|inherit|<color>
//     [<icccolor>]|<funciri> (not support yet)
function getTagColor(currTag, parents) {
  const defaultColor = 'black';
  const fillVal = currTag.attributes.fill;
  let color;
  const parentsLength = parents.length;
 
  Iif ('none' === fillVal) {
    return color;
  }
  if ('currentColor' === fillVal) {
    return defaultColor;
  }
  if ('inherit' === fillVal) {
    Iif (0 === parentsLength) {
      return defaultColor;
    }
    return getTagColor(
      parents[parentsLength - 1],
      parents.slice(0, parentsLength - 1)
    );
    // this might be null.
    // For example: <svg ><path fill="inherit" /> </svg>
    // in this case getTagColor should return null
    // recursive call, the bottom element should be svg,
    // and svg didn't fill color, so just return null
  }
 
  return fillVal;
}
 
class SVGIcons2SVGFontStream extends Transform {
  constructor(options) {
    super({ objectMode: true });
 
    // Setting objectMode separately
    this._writableState.objectMode = true;
    this._readableState.objectMode = false;
 
    this.glyphs = [];
 
    this._options = options || {};
    this._options.fontName = this._options.fontName || 'iconfont';
    this._options.fontId = this._options.fontId || this._options.fontName;
    this._options.fixedWidth = this._options.fixedWidth || false;
    this._options.descent = this._options.descent || 0;
    this._options.round = this._options.round || 10e12;
    this._options.metadata = this._options.metadata || '';
 
    this.log = this._options.log || console.log.bind(console); // eslint-disable-line
  }
 
  _transform(svgIconStream, _unused, svgIconStreamCallback) {
    // Parsing each icons asynchronously
    const saxStream = Sax.createStream(true);
    const parents = [];
    const transformStack = [new Matrix()];
    function applyTransform(d) {
      return new SVGPathData(d).matrix(
        ...transformStack[transformStack.length - 1].toArray()
      );
    }
    const glyph = svgIconStream.metadata || {};
 
    // init width and height os they aren't undefined if <svg> isn't renderable
    glyph.width = 0;
    glyph.height = 1;
 
    glyph.paths = [];
    this.glyphs.push(glyph);
 
    if ('string' !== typeof glyph.name) {
      this.emit(
        'error',
        new Error(
          `Please provide a name for the glyph at index ${
            this.glyphs.length - 1
          }`
        )
      );
    }
    if (
      this.glyphs.some(
        (anotherGlyph) =>
          anotherGlyph !== glyph && anotherGlyph.name === glyph.name
      )
    ) {
      this.emit(
        'error',
        new Error(`The glyph name "${glyph.name}" must be unique.`)
      );
    }
    if (
      glyph.unicode &&
      glyph.unicode instanceof Array &&
      glyph.unicode.length
    ) {
      if (
        glyph.unicode.some((unicodeA, i) =>
          glyph.unicode.some((unicodeB, j) => i !== j && unicodeA === unicodeB)
        )
      ) {
        this.emit(
          'error',
          new Error(
            `Given codepoints for the glyph "${glyph.name}" contain duplicates.`
          )
        );
      }
    } else if ('string' !== typeof glyph.unicode) {
      this.emit(
        'error',
        new Error(`Please provide a codepoint for the glyph "${glyph.name}"`)
      );
    }
 
    if (
      this.glyphs.some(
        (anotherGlyph) =>
          anotherGlyph !== glyph && anotherGlyph.unicode === glyph.unicode
      )
    ) {
      this.emit(
        'error',
        new Error(
          `The glyph "${glyph.name}" codepoint seems to be used already elsewhere.`
        )
      );
    }
 
    saxStream.on('opentag', (tag) => {
      let values;
      let color;
 
      parents.push(tag);
      try {
        const currentTransform = transformStack[transformStack.length - 1];
 
        if ('undefined' !== typeof tag.attributes.transform) {
          const transform = matrixFromTransformAttribute(
            tag.attributes.transform
          );
          transformStack.push(currentTransform.clone().multiply(transform));
        } else {
          transformStack.push(currentTransform);
        }
        // Checking if any parent rendering is disabled and exit if so
        if (!tagShouldRender(tag, parents)) {
          return;
        }
 
        // Save the view size
        if ('svg' === tag.name) {
          if ('viewBox' in tag.attributes) {
            values = tag.attributes.viewBox.split(/\s*,*\s|\s,*\s*|,/);
            const dX = parseFloat(values[0]);
            const dY = parseFloat(values[1]);
            const width = parseFloat(values[2]);
            const height = parseFloat(values[3]);
 
            // use the viewBox width/height if not specified explictly
            glyph.width =
              'width' in tag.attributes
                ? parseFloat(tag.attributes.width)
                : width;
            glyph.height =
              'height' in tag.attributes
                ? parseFloat(tag.attributes.height)
                : height;
 
            transformStack[transformStack.length - 1]
              .translate(-dX, -dY)
              .scale(glyph.width / width, glyph.height / height);
          } else {
            Iif ('width' in tag.attributes) {
              glyph.width = parseFloat(tag.attributes.width);
            } else {
              this.log(
                `Glyph "${glyph.name}" has no width attribute, defaulting to 150.`
              );
              glyph.width = 150;
            }
            Iif ('height' in tag.attributes) {
              glyph.height = parseFloat(tag.attributes.height);
            } else {
              this.log(
                `Glyph "${glyph.name}" has no height attribute, defaulting to 150.`
              );
              glyph.height = 150;
            }
          }
        } else if ('clipPath' === tag.name) {
          // Clipping path unsupported
          this.log(
            `Found a clipPath element in the icon "${glyph.name}" the result may be different than expected.`
          );
        } else if ('rect' === tag.name && 'none' !== tag.attributes.fill) {
          glyph.paths.push(
            applyTransform(svgShapesToPath.rectToPath(tag.attributes))
          );
        } else if ('line' === tag.name && 'none' !== tag.attributes.fill) {
          this.log(
            `Found a line element in the icon "${glyph.name}" the result could be different than expected.`
          );
          glyph.paths.push(
            applyTransform(svgShapesToPath.lineToPath(tag.attributes))
          );
        } else if ('polyline' === tag.name && 'none' !== tag.attributes.fill) {
          this.log(
            `Found a polyline element in the icon "${glyph.name}" the result could be different than expected.`
          );
          glyph.paths.push(
            applyTransform(svgShapesToPath.polylineToPath(tag.attributes))
          );
        } else if ('polygon' === tag.name && 'none' !== tag.attributes.fill) {
          glyph.paths.push(
            applyTransform(svgShapesToPath.polygonToPath(tag.attributes))
          );
        } else if (
          ['circle', 'ellipse'].includes(tag.name) &&
          'none' !== tag.attributes.fill
        ) {
          glyph.paths.push(
            applyTransform(svgShapesToPath.circleToPath(tag.attributes))
          );
        } else if (
          'path' === tag.name &&
          tag.attributes.d &&
          'none' !== tag.attributes.fill
        ) {
          glyph.paths.push(applyTransform(tag.attributes.d));
        }
 
        // According to http://www.w3.org/TR/SVG/painting.html#SpecifyingPaint
        // Map attribute fill to color property
        if ('none' !== tag.attributes.fill) {
          color = getTagColor(tag, parents);
          if ('undefined' !== typeof color) {
            glyph.color = color;
          }
        }
      } catch (err) {
        this.emit(
          'error',
          new Error(
            `Got an error parsing the glyph "${glyph.name}": ${err.message}.`
          )
        );
      }
    });
 
    saxStream.on('error', (err) => {
      this.emit('error', err);
    });
 
    saxStream.on('closetag', () => {
      transformStack.pop();
      parents.pop();
    });
 
    saxStream.on('end', () => {
      svgIconStreamCallback();
    });
 
    svgIconStream.pipe(saxStream);
  }
 
  _flush(svgFontFlushCallback) {
    const maxGlyphHeight = this.glyphs.reduce(
      (curMax, glyph) => Math.max(curMax, glyph.height),
      0
    );
    const maxGlyphWidth = this.glyphs.reduce(
      (curMax, glyph) => Math.max(curMax, glyph.width),
      0
    );
    const fontHeight = this._options.fontHeight || maxGlyphHeight;
    let fontWidth = maxGlyphWidth;
    if (this._options.normalize) {
      fontWidth = this.glyphs.reduce(
        (curMax, glyph) =>
          Math.max(curMax, (fontHeight / glyph.height) * glyph.width),
        0
      );
    } else if (this._options.fontHeight) {
      // even if normalize is off, we need to scale the fontWidth if we have a custom fontHeight
      fontWidth *= fontHeight / maxGlyphHeight;
    }
 
    this._options.ascent =
      'undefined' !== typeof this._options.ascent
        ? this._options.ascent
        : fontHeight - this._options.descent;
 
    if (
      !this._options.normalize &&
      fontHeight >
        (1 < this.glyphs.length
          ? this.glyphs.reduce(
              (curMin, glyph) => Math.min(curMin, glyph.height),
              Infinity
            )
          : this.glyphs[0].height)
    ) {
      this.log(
        'The provided icons do not have the same heights. This could lead' +
          ' to unexpected results. Using the normalize option may help.'
      );
    }
    if (1000 > fontHeight) {
      this.log(
        'A fontHeight of at least than 1000 is recommended, otherwise ' +
          'further steps (rounding in svg2ttf) could lead to ugly results.' +
          ' Use the fontHeight option to scale icons.'
      );
    }
 
    // Output the SVG file
    // (find a SAX parser that allows modifying SVG on the fly)
    /* eslint-disable prefer-template */
    this.push(
      '<?xml version="1.0" standalone="no"?>\n' +
        '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >\n' +
        '<svg xmlns="http://www.w3.org/2000/svg">\n' +
        (this._options.metadata
          ? '<metadata>' + this._options.metadata + '</metadata>\n'
          : '') +
        '<defs>\n' +
        '  <font id="' +
        this._options.fontId +
        '" horiz-adv-x="' +
        fontWidth +
        '">\n' +
        '    <font-face font-family="' +
        this._options.fontName +
        '"\n' +
        '      units-per-em="' +
        fontHeight +
        '" ascent="' +
        this._options.ascent +
        '"\n' +
        '      descent="' +
        this._options.descent +
        '"' +
        (this._options.fontWeight
          ? '\n      font-weight="' + this._options.fontWeight + '"'
          : '') +
        (this._options.fontStyle
          ? '\n      font-style="' + this._options.fontStyle + '"'
          : '') +
        ' />\n' +
        '    <missing-glyph horiz-adv-x="0" />\n'
    );
 
    this.glyphs.forEach((glyph) => {
      const ratio = this._options.normalize
        ? fontHeight / glyph.height
        : fontHeight / maxGlyphHeight;
      Iif (!isFinite(ratio)) throw new Error('foo');
      glyph.width *= ratio;
      glyph.height *= ratio;
      const glyphPath = new SVGPathData('');
 
      if (this._options.fixedWidth) {
        glyph.width = fontWidth;
      }
      const yOffset = glyph.height - this._options.descent;
      const glyphPathTransform = new Matrix().transform(
        1,
        0,
        0,
        -1,
        0,
        yOffset
      ); // ySymmetry
      if (1 !== ratio) {
        glyphPathTransform.scale(ratio, ratio);
      }
      glyph.paths.forEach((path) => {
        glyphPath.commands.push(
          ...path.toAbs().matrix(...glyphPathTransform.toArray()).commands
        );
      });
      const bounds =
        (this._options.centerHorizontally || this._options.centerVertically) &&
        glyphPath.getBounds();
      if (this._options.centerHorizontally) {
        glyphPath.translate(
          (glyph.width - (bounds.maxX - bounds.minX)) / 2 - bounds.minX
        );
      }
      if (this._options.centerVertically) {
        glyphPath.translate(
          0,
          (fontHeight - (bounds.maxY - bounds.minY)) / 2 - bounds.minY
        );
      }
      delete glyph.paths;
      glyph.unicode.forEach((unicode, i) => {
        const unicodeStr = ucs2
          .decode(unicode)
          .map((point) => '&#x' + point.toString(16).toUpperCase() + ';')
          .join('');
        const d = glyphPath.round(this._options.round).encode();
 
        this.push(
          '    <glyph glyph-name="' +
            glyph.name +
            (0 === i ? '' : '-' + i) +
            '"\n' +
            '      unicode="' +
            unicodeStr +
            '"\n' +
            '      horiz-adv-x="' +
            glyph.width +
            '" d="' +
            d +
            '" />\n'
        );
      });
    });
    this.push('  </font>\n' + '</defs>\n' + '</svg>\n');
    this.log('Font created');
    if ('function' === typeof this._options.callback) {
      this._options.callback(this.glyphs);
    }
    svgFontFlushCallback();
  }
}
 
module.exports = SVGIcons2SVGFontStream;