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

96.25% Statements 77/80
97.67% Branches 42/43
100% Functions 28/28
96.2% Lines 76/79

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          7x         82x 82x 82x 82x 82x 82x               11x     23x                 166x     78x 78x                 86x     20x 20x                 1x     3x                 86x     8x 8x                     86x     10x                 1x 1x                                     82x                             22x                   22x 19x                   22x 22x 22x                       38x                   21x 21x                   14x                     3x 3x       18x 1x         17x 15x 14x         13x 13x   13x       13x 13x   1x 1x         17x     17x 13x                   3x     7x   2x     3x                   15x 15x 14x 14x 14x 11x       10x 2x   10x     10x     4x                         49x 49x                   11x 2x 2x         1x                   14x       38x       7x                          
import { LightningElement, api } from 'lwc';
import { reflectAttribute } from 'sds/utils';
import 'sds/privateThemeProvider';
 
const sdsIconParser = new DOMParser();
const sdsIconRequests = new Map();
 
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
   *
   * @param {string} symbol
   */
  getSymbolParams(symbol) {
    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);
  }
 
  /**
   * Validates if the provided URL is an SVG file.
   *
   * @param {string} url
   * @returns {boolean}
   */
  isValidSvgUrl(url) {
    const svgUrlPattern = /\.svg$/i;
    return svgUrlPattern.test(url);
  }
 
  /**
   * Validates if the provided content type is an SVG.
   *
   * @param {string} contentType
   * @returns {boolean}
   */
  isValidContentType(contentType) {
    return contentType && contentType.includes('image/svg+xml');
  }
 
  /**
   * Fetch SVG asset from url, run optional mutations, and return it.
   *
   * @param {string} url
   */
  async fetchIcon(url) {
    // Validate the URL
    if (!this.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) {
        if (!this.isValidContentType(response.headers.get('content-type'))) {
          console.error(`Invalid content type: ${contentType}. Only SVG files are allowed.`);
          sdsIconRequests.delete(url);
          return;
        }
        const div = document.createElement('div');
        div.innerHTML = await response.text();
        const svg = div.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);
  }
}