all files / addon/utils/ make-svg.js

100% Statements 22/22
85.71% Branches 12/14
100% Functions 4/4
100% Lines 22/22
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          21× 46× 46×           17×   17×       16× 16×   16×     16×     14× 14×       14×      
import { copy } from '@ember/object/internals';
import { merge } from '@ember/polyfills';
import { isNone } from '@ember/utils';
import { htmlSafe } from '@ember/string';
 
export function formatAttrs(attrs) {
  return Object.keys(attrs)
    .map((key) => !isNone(attrs[key]) && `${key}="${attrs[key]}"`)
    .filter((attr) => attr)
    .join(' ');
}
 
export function symbolUseFor(assetId, attrs = {}) {
  return `<svg ${formatAttrs(attrs)}><use xlink:href="${assetId}" /></svg>`;
}
 
export function inlineSvgFor(assetId, getInlineAsset, attrs = {}) {
  const asset = getInlineAsset(assetId);
 
  if (!asset) {
    // eslint-disable-next-line no-console
    console.warn(`ember-svg-jar: Missing inline SVG for ${assetId}`);
    return;
  }
 
  const svgAttrs = asset.attrs ? merge(copy(asset.attrs), attrs) : attrs;
  const { size } = attrs;
 
  if (size) {
    svgAttrs.width = parseFloat(svgAttrs.width) * size || svgAttrs.width;
    svgAttrs.height = parseFloat(svgAttrs.height) * size || svgAttrs.height;
    delete svgAttrs.size;
  }
 
  return `<svg ${formatAttrs(svgAttrs)}>${asset.content}</svg>`;
}
 
export default function makeSvg(assetId, attrs = {}, getInlineAsset) {
  const isSymbol = assetId.lastIndexOf('#', 0) === 0;
  const svg = isSymbol
    ? symbolUseFor(assetId, attrs)
    : inlineSvgFor(assetId, getInlineAsset, attrs);
 
  return htmlSafe(svg);
}