All files / src/ui attribute-highlighter.ts

0% Statements 0/109
0% Branches 0/47
0% Functions 0/20
0% Lines 0/109

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import * as dom from '../dom/dom';
import {DomWatcher} from '../dom/dom-watcher';
import * as urlParams from '../dom/url-params';
import * as func from '../func/func';
import * as is from '../is/is';
import {Raf} from '../raf/raf';
 
export interface HighlightElementGroup {
  highlighterEl: HTMLElement;
  attributeEls: HTMLElement[];
}
 
export interface AttributeScopeConfig {
  attribute: string;
  querySelector: string;
}
 
export interface AttributeHighlighterConfig {
  /**
   * The name of the css class to attached to each generated aria highlighter item.
   */
  cssClassName: string;
 
  /**
   * A query selector to scope your scan to specific elements and its
   * children.
   */
  scopeQuerySelector: string;
 
  /**
   * A list of all attributes you want to highlight on the page.
   *
   * Typically this would be:
   *
   * ```
   * attributes: ['alt', 'aria-label']
   * ```
   *
   * You can also pass in a AttributeScopeConfig.
   * This is useful if you want to scope your search to specific elements.
   * For example, let's say you want to highlight, aria-labels ONLY on
   * video elements.
   *
   * You can do:
   *
   * attributes: [{
   *  attribute: 'aria-label',
   *  querySelector: 'video'
   * }]
   *
   * or perhaps you want to show aria-label only on buttons.
   *
   * attributes: [{
   *  attribute: 'aria-label',
   *  querySelector: '.button'
   * }]
   *
   *
   */
  attributes: (string | AttributeScopeConfig)[];
 
  /**
   * Allows you to search and highlight cases in which an attribute is missing
   * or empty.
   *
   *
   * Here is an example of where we would want to highlight a case in which
   * we scan for all <img> that are missing alts and any videos that
   * are missing the aria-label.
   * ```
   * warnMissingAttributes: [
   *  {
   *    attribute: 'alt',
   *    querySelector: 'img'
   *  },
   *  {
   *    attribute: 'aria-label',
   *    querySelector: 'video'
   *  },
   * ]
   * ```
   */
  warnMissingAttributes?: AttributeScopeConfig[];
 
  /**
   * Specify an option url to enable attribute specification via url params.
   */
  urlParamName?: string;
 
  /**
   * This classes uses Raf to continously update the attributes.
   * Set the raf FPS.
   */
  rafFps?: number;
}
 
/**
 * A class that will visibly highlight element attribute on your page.
 *
 *
 * Setup:
 *
 * 1) Create your highlighter css class.
 *.my-highlighter
 *  align-items: left
 *  color: #FFF
 *  background: rgba(#000, 0.8)
 *  border-radius: 3px
 *  box-shadow: none !important
 *  display: flex
 *  flex-direction: column
 *  font-size: 11px
 *  height: auto
 *  justify-content: center
 *  left: var(--left)
 *  margin: 0 !important
 *  max-width: var(--max-width)
 *  padding: 0px 8px
 *  position: fixed !important
 *  // Slight off center.
 *  top: calc(var(--center) + 10px)
 *  transform: translateX(-50%) translateY(0%)
 *  transition: transform 0.3s ease
 *  transform-origin: top center
 *  z-index: 9999
 *  cursor: pointer
 *  span
 *    display: block
 *  &.active,
 *   transform: translateX(-50%) translateY(0%) scale(1.2)
 *  &:hover,
 *    cursor: pointer
 *    z-index: 10000
 *  &:active
 *    z-index: 10000
 *    transform: translateX(-50%) translateY(10px) scale(1.2)
 *
 *  &.up
 *    top: calc(var(--center) - 10px + (var(--height)  * -1))
 *
 *
 *
 * // When clicking on a highlighter, it can highlight the associated
 * // element.  The element gets .attribute-highlighter-active
 * .attribute-highlighter-active
 *   border: 3px solid red !important
 *   transition: border 0s ease !important
 *
 * 2) Instantiate attributeHighlighter.
 *  const attributeHighlighter = new AttributeHighlighter({
 *    cssClassName: '.my-highlighter',
 *    scopeQuerySelector: '.my-module',
 *    attributes: [
 *       'alt',
 *       'aria-label'
 *    ]
 *  })
 *
 * Scoped Search:
 * Attributes accepts AttributeScopedConfig so you can do more complex
 * queries.
 *
 *
 * ```
 *    attributes: [
 *       'alt',
 *       {
 *          attribute: 'aria-label',
 *          querySelector: '.button'
 *       }
 *    ]
 * ```
 * Now all 'alt' and only aria-labels of classes with .button will be
 * highlighted on the page.
 *
 *
 * Optional url param:
 *
 * You can optionally, configure it so that a url param
 * populates the attributes list.
 *
 * ```
 *  const attributeHighlighter = new AttributeHighlighter({
 *    cssClassName: '.my-highlighter',
 *    scopeQuerySelector: '.my-module',
 *    attributes: [],
 *    urlParamName: 'attributeHighlight'
 *  })
 * ```
 *
 * Now you can do the following.  Use comma separation for multiple.
 * ```
 * xxx.com?attributeHightlight=alt
 * xxx.com?attributeHightlight=alt,aria-label
 * ```
 * If no url param is specified, it defaults to the attributes originally
 * specified in the config.
 *
 */
export class AttributeHighlighter {
  private watcher: DomWatcher;
  private attributeWatcher: DomWatcher;
 
  private config: AttributeHighlighterConfig;
 
  // A list of all highlighters on the page.
  private highlighters: HighlightElementGroup[] = [];
 
  private raf: Raf;
 
  constructor(config: AttributeHighlighterConfig) {
    this.config = config;
 
    if (!this.config.rafFps) {
      this.config.rafFps = 5;
    }
 
    // Allow url params to specify the attributes.
    if (this.config.urlParamName) {
      const paramValue = urlParams.getValue(this.config.urlParamName);
      if (paramValue) {
        this.config.attributes = paramValue.split(',');
      }
    }
 
    this.watcher = new DomWatcher();
    this.watcher.add({
      element: window,
      on: ['click', 'resize', 'scroll'],
      callback: func.debounce(this.refresh.bind(this), 1),
    });
 
    // Dedicated watcher for attributes.
    this.attributeWatcher = new DomWatcher();
 
    this.raf = new Raf(this.refresh.bind(this));
    this.raf.setFps(this.config.rafFps);
    this.raf.start();
  }
 
  public refresh() {
    this.removeHighlighters();
    this.createHighlighters();
  }
 
  /**
   * Creates a highlighter element.
   * @param el  The root scope element.
   * @param attributeEl  The element in which the attribute belongs to.
   * @param attribute  The attribute name.
   * @param isTypeMissing  Whether this is "missing" attribute.
   * @returns
   */
  private createHighlighter(
    el: HTMLDivElement,
    attributeEl: HTMLDivElement,
    attribute: string,
    isTypeMissing: boolean
  ) {
    // If this element is not visible on the page,
    // then skip.
    if (!dom.isVisibleOnScreen(attributeEl) && !isTypeMissing) {
      return;
    }
 
    let isMissingText = false;
    const text = attributeEl.getAttribute(attribute);
 
    if (text === 'None' || text === '' || !text) {
      isMissingText = true;
    }
 
    // We were looking to see if the attribute was missing or not, but this
    // one passed.
    if (isTypeMissing && attributeEl.hasAttribute(attribute)) {
      return;
    }
 
    // Search for an existing highlightEl containing this attribute.
    const spacerElGroup = this.highlighters.filter((h) => {
      return ~h.attributeEls.indexOf(attributeEl);
    })[0];
 
    let isNew = true;
    let spacerEl = document.createElement('div');
    if (spacerElGroup) {
      spacerEl = spacerElGroup.highlighterEl as HTMLDivElement;
      isNew = false;
    }
 
    spacerEl.classList.add(this.config.cssClassName);
    spacerEl.classList.add(attribute);
    if (isMissingText) {
      spacerEl.classList.add('missing-text');
    }
 
    if (isTypeMissing) {
      spacerEl.classList.add('missing');
    }
 
    const textEl = document.createElement('span');
    if (isTypeMissing) {
      textEl.innerText = `Missing: ${attribute}`;
    } else {
      textEl.innerText = `${attribute}: ${text}`;
    }
 
    spacerEl.appendChild(textEl);
 
    if (isNew) {
      const rect = attributeEl.getBoundingClientRect();
      const center = `${rect.top + rect.height / 2}px`;
      const bottom = `${rect.bottom}px`;
      const top = `${rect.top}px`;
      const left = (rect.left + rect.right) / 2;
 
      if (rect.width > 80) {
        spacerEl.style.setProperty('--max-width', `${rect.width * 1.5}px`);
      } else {
        spacerEl.style.setProperty('--max-width', '80px');
      }
      spacerEl.style.setProperty('--left', `${left}px`);
      spacerEl.style.setProperty('--center', center);
      spacerEl.style.setProperty('--top', top);
      spacerEl.style.setProperty('--bottom', bottom);
 
      // On hovering this spacerEl, we should highlight the associated
      // element.
      this.attributeWatcher.add({
        element: spacerEl,
        on: ['mousedown'],
        callback: (e: Event) => {
          e.preventDefault();
          e.stopPropagation();
          this.raf.stop();
          window.setTimeout(() => {
            attributeEl.classList.add('attribute-highlighter-active');
          });
        },
      });
 
      this.attributeWatcher.add({
        element: spacerEl,
        on: ['mouseup'],
        callback: (e: Event) => {
          e.preventDefault();
          e.stopPropagation();
          attributeEl.classList.remove('attribute-highlighter-active');
          window.setTimeout(() => {
            this.raf.start();
          }, 100);
        },
      });
 
      this.highlighters.push({
        highlighterEl: spacerEl,
        attributeEls: [attributeEl],
      });
 
      spacerEl.classList.remove('up');
      el.parentElement!.appendChild(spacerEl);
    } else {
      // Update.
      this.highlighters.forEach((h) => {
        if (~h.attributeEls.indexOf(attributeEl)) {
          h.attributeEls.push(attributeEl);
        }
      });
    }
 
    // Avoid overlap.
    this.highlighters.forEach((aHighlighter) => {
      const a = aHighlighter.highlighterEl;
      const isOverlapping = dom.isOverlapping(a, spacerEl);
      if (isOverlapping) {
        if (a.classList.contains('up')) {
          spacerEl.classList.add('up');
          spacerEl.style.setProperty('--height', spacerEl.offsetHeight + 'px');
          spacerEl.style.setProperty('--center', a.offsetTop + 'px');
        } else {
          spacerEl.classList.add('up');
          spacerEl.style.setProperty('--height', spacerEl.offsetHeight + 'px');
        }
      }
    });
  }
 
  private createHighlighters() {
    // // Flush attributeDom Watcher.
    this.attributeWatcher.removeAll();
 
    [].forEach.call(
      document.querySelectorAll(this.config.scopeQuerySelector),
      (el: HTMLDivElement) => {
        // Look for attributes.
        this.config.attributes.forEach((attribute) => {
          if (is.string(attribute)) {
            const attr = attribute as string;
            [].forEach.call(
              el.querySelectorAll(`[${attribute}]`),
              (attributeEl: HTMLDivElement) => {
                this.createHighlighter(el, attributeEl, attr, false);
              }
            );
          } else {
            // If this is a AttributeHighlighterConfig
            const attr = attribute as AttributeScopeConfig;
            const attrValue = attr.attribute;
            const query = attr.querySelector;
            [].forEach.call(
              el.querySelectorAll(`${query}`),
              (attributeEl: HTMLDivElement) => {
                this.createHighlighter(el, attributeEl, attrValue, false);
              }
            );
          }
        });
 
        if (this.config.warnMissingAttributes) {
          this.config.warnMissingAttributes.forEach((attribute) => {
            // Highlights missing attributes
            const attr = attribute as AttributeScopeConfig;
            const attrValue = attr.attribute;
            const query = attr.querySelector;
            [].forEach.call(
              el.querySelectorAll(`${query}`),
              (attributeEl: HTMLDivElement) => {
                this.createHighlighter(el, attributeEl, attrValue, true);
              }
            );
          });
        }
      }
    );
  }
 
  private removeHighlighters() {
    this.highlighters.forEach((highlighter) => {
      dom.removeElement(highlighter.highlighterEl);
    });
    this.highlighters = [];
  }
 
  public dispose() {
    this.removeHighlighters();
    this.watcher && this.watcher.dispose();
    this.attributeWatcher && this.attributeWatcher.dispose();
    this.raf && this.raf.dispose();
  }
}