All files / packages/sds-components/src/sds/icon icon.js

97.97% Statements 97/99
98.21% Branches 55/56
100% Functions 35/35
97.91% Lines 94/96

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          7x 7x     7x                   32x 32x                     20x       97x 97x 97x 97x 97x 97x 97x               11x     38x                 181x     92x 92x                 101x     35x 35x                 1x     4x                 101x     8x 8x                     101x     10x                 1x 1x                           3x         97x                             32x                   32x 29x                     38x 6x   32x 32x 32x                       53x                   32x 9x 9x       23x           23x 21x 20x 20x 2x 2x 2x     18x 18x       20x 20x   1x 1x         23x     23x 20x                 9x 4x     9x 9x 2x     4x                   29x 29x 23x 23x 23x 22x 22x     22x 2x   14x     14x 23x   10x     6x                   64x 64x                   11x 2x 2x       11x 1x                 53x 28x       53x       7x 7x                              
import { LightningElement, api } from 'lwc';
import { reflectAttribute } from 'sds/utils';
import 'sds/privateThemeProvider';
 
const sdsIconParser = new DOMParser();
const sdsIconRequests = new Map();
 
// Names only allow letters, digits, _ and -, so they can't change the path of the resolved URL
const VALID_SYMBOL = /^[a-zA-Z][A-Za-z0-9_-]*$/;
 
/**
 * Validates if the provided URL is an SVG file.
 * The path must end in .svg, optionally followed by a query string, and must not contain ".." or an encoded dot (%2e).
 *
 * @param {string} url
 * @returns {boolean}
 */
function isValidSvgUrl(url) {
  const svgUrlPattern = /^[^?#]*\.svg(\?[^#]*)?$/i;
  return typeof url === 'string' && !/\.\.|%2e/i.test(url) && svgUrlPattern.test(url);
}
 
/**
 * Validates if the provided content type is an SVG.
 * The media type must be exactly image/svg+xml; parameters such as charset are ignored.
 *
 * @param {string} contentType
 * @returns {boolean}
 */
function isValidContentType(contentType) {
  return (
    typeof contentType === 'string' && contentType.split(';')[0].trim().toLowerCase() === 'image/svg+xml'
  );
}
 
export default class Icon extends LightningElement {
  static shadowSupportMode = 'native';
 
  _symbol;
  _set;
  _ariaLabel;
  _prefetch;
  _generatedIcon = false;
  _iconSets = [];
 
  /**
   * An array of icon sets to use when resolving the icon.
   *
   * @type {Array}
   */
  @api
  get iconSets() {
    return this._iconSets;
  }
  set iconSets(value) {
    this._iconSets = value ?? [];
  }
 
  /**
   * The name of the icon to resolve.
   *
   * @type {string}
   */
  @api
  get symbol() {
    return this._symbol;
  }
  set symbol(value) {
    this._symbol = value;
    reflectAttribute(this, 'symbol', this._symbol);
  }
 
  /**
   * The name of the icon set to use when resolving the icon.
   *
   * @type {string}
   */
  @api
  get set() {
    return this._set;
  }
  set set(value) {
    this._set = value;
    reflectAttribute(this, 'set', this._set);
  }
 
  /**
   * Which icons to prefetch from the set.
   *
   * @type {string}
   */
  @api
  get prefetch() {
    return this._prefetch;
  }
  set prefetch(value) {
    this._prefetch = value;
  }
 
  /**
   * Defines a string value that labels an interactive element.
   *
   * @type {string}
   */
  @api
  get ariaLabel() {
    return this._ariaLabel;
  }
  set ariaLabel(value) {
    this._ariaLabel = value;
    this.role = 'img';
  }
 
  /**
   * Provides semantic meaning to content, allowing screen readers and other
   * tools to present and support interaction with object in a way that is
   * consistent with user expectations of that type of object.
   *
   * @type {string}
   */
  @api
  get role() {
    return this._role;
  }
  set role(value) {
    this._role = value;
  }
 
  /**
   * Register new icon sets programmatically
   *
   * @param {array} set
   */
  @api
  registerIconSet(set) {
    set.forEach((set) => {
      this._iconSets.push({
        name: set.name,
        resolver: set.resolver,
        mutator: set.mutator,
      });
    });
  }
 
  /**
   * Unregister a custom icon set
   *
   * @param {string} name
   */
  @api
  unregisterIconSet(name) {
    this._iconSets = this._iconSets.filter((lib) => lib.name !== name);
  }
 
  connectedCallback() {
    // Dispatch custom event for parent
    // Used to imperatively set an iconSet
    this.dispatchEvent(
      new CustomEvent('iconregister', {
        bubbles: true,
        cancelable: true,
        detail: {
          name: 'sds-icon',
        },
      }),
    );
  }
 
  /**
   * Retrieve an icon set
   *
   * @param {string} name
   */
  getIconSet(name) {
    return this._iconSets && this._iconSets.filter((set) => set.name === name)[0];
  }
 
  /**
   * Return the resolver (url) for an icon set
   *
   * @param {string} set
   * @param {string} symbol
   */
  getIconUrl(set, symbol) {
    if (set && symbol) {
      return set.resolver(symbol);
    }
  }
 
  /**
   * Return the parameters of a symbol in an object for easier reference.
   * Returns an empty object if symbol is not a valid name.
   *
   * @param {string} symbol
   */
  getSymbolParams(symbol) {
    if (typeof symbol !== 'string' || !VALID_SYMBOL.test(symbol)) {
      return {};
    }
 
    const set = this.getIconSet(this._set);
    const url = this.getIconUrl(set, symbol);
    return {
      set,
      url,
    };
  }
 
  /**
   * Check if the icon set and symbol are set.
   *
   * @returns {boolean}
   */
  hasIconsConfigured() {
    return Boolean(this._set && this._symbol);
  }
I
  /**
   * Fetch SVG asset from url, run optional mutations, and return it.
   *
   * @param {string} url
   */
  async fetchIcon(url) {
    // Validate the URL
    if (!isValidSvgUrl(url)) {
      console.error(`Invalid URL: ${url}. Only SVG files are allowed.`);
      return;
    }
 
    // If there's an ongoing request for the same URL, return the stored Promise
    if (sdsIconRequests.has(url)) {
      const result = await sdsIconRequests.get(url);
      return result;
    }
 
    // If there's no ongoing request, create a new Promise for the fetch request
    const requestPromise = fetch(url).then(async (response) => {
      if (response.ok) {
        const contentType = response.headers.get('content-type');
        if (!isValidContentType(contentType)) {
          console.error(`Invalid content type: ${contentType}. Only SVG files are allowed.`);
          sdsIconRequests.delete(url);
          return;
        }
        // DOMParser documents are inert: no scripts, event handlers or resource loads
        const svg = sdsIconParser.parseFromString(await response.text(), 'text/html').body.firstElementChild;
        const result = {
          url: url,
          svg: svg && svg.tagName.toLowerCase() === 'svg' ? svg.outerHTML : '',
        };
 
        sdsIconRequests.delete(url);
        return result;
      } else {
        sdsIconRequests.delete(url);
        throw Error();
      }
    });
 
    // Store the Promise in the sdsIconRequests cache
    sdsIconRequests.set(url, requestPromise);
 
    // Wait for the Promise to resolve and return the icon
    const request = await requestPromise;
    return request;
  }
 
  /**
   * Prefetch icons before they are drawn
   *
   * @param {string} icons
   */
  async prefetchIcons(icons) {
    const iconsToFetch = icons.split(',').map((icon) => icon.trim());
    const fetchedIcons = await Promise.all(
      iconsToFetch.map((symbol) => {
        const { url } = this.getSymbolParams(symbol);
        return this.fetchIcon(url).catch(() => {
          console.error(
            `Unable to prefetch the symbol "${symbol}". Double check your symbol exists and use comma separated values.`,
          );
        });
      }),
    );
    return fetchedIcons;
  }
 
  /**
   * Create the icon (entry point)
   */
  async createIcon() {
    const { set, url } = this.getSymbolParams(this._symbol);
    if (url && set) {
      const slotContainer = !this._generatedIcon
        ? this.template.querySelector("[part~='icon']")
        : this.template.querySelector('svg');
 
      try {
        const svg = await this.fetchIcon(url);
        const doc = sdsIconParser.parseFromString(svg.svg, 'text/html');
        let svgEl = doc.body.querySelector('svg');
 
        // Run any optional mutations
        if (set && set.mutator) {
          svgEl = set.mutator(svgEl);
        }
        svgEl.setAttribute('aria-hidden', 'true');
 
        // Add the SVG as the fallback content of the slot
        !this._generatedIcon ? slotContainer.appendChild(svgEl) : slotContainer.replaceWith(svgEl);
        this._generatedIcon = true;
      } catch {
        console.error(`Error creating icon using ${url}`);
      }
    } else {
      console.error(
        `Unable to create an icon using set ${this._set} and URL ${url}. Double check your registered set names and paths.`,
      );
    }
  }
 
  /**
   * Check if the slot has slotted content
   *
   * @returns {boolean}
   */
  hasSlottedChildren() {
    const slot = this.template.querySelector('slot');
    return slot.assignedNodes({ flatten: true }).length !== 0;
  }
 
  /**
   * Handle slotchange event
   */
  handleSlotChange() {
    // Remove icon generated by API to make room for slotted content
    if (this._generatedIcon) {
      this.template.querySelector('svg').remove();
      this._generatedIcon = false;
    }
 
    // Recreate icon if slot is emptied and icons are configured
    if (!this.hasSlottedChildren() && !this._generatedIcon && this.hasIconsConfigured) {
      this.createIcon();
    }
  }
 
  /**
   * RenderedCallback LWC lifecycle
   */
  renderedCallback() {
    // Create icon if slot is empty and icons have been configured
    if (!this.hasSlottedChildren() && this.hasIconsConfigured()) {
      this.createIcon();
    }
 
    // Check if we need to prefetch icons
    this._prefetch && this.prefetchIcons(this._prefetch);
  }
}