text: /**
   * @license Copyright 2017 Google Inc. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
   * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
   */
  'use strict';
  
  /**
   * @fileoverview Adds export button, print, and other dynamic functionality to
   * the report.
   */
  
  /* globals self URL Blob CustomEvent getFilenamePrefix window */
  
  class ReportUIFeatures {
  
    /**
     * @param {!DOM} dom
     */
    constructor(dom) {
      /** @type {!ReportRenderer.ReportJSON} */
      this.json; // eslint-disable-line no-unused-expressions
      /** @protected {!DOM} */
      this._dom = dom;
      /** @protected {!Document} */
      this._document = this._dom.document();
      /** @private {boolean} */
      this._copyAttempt = false;
      /** @type {!Element} **/
      this.exportButton; // eslint-disable-line no-unused-expressions
  
      this.onMediaQueryChange = this.onMediaQueryChange.bind(this);
      this.onCopy = this.onCopy.bind(this);
      this.onExportButtonClick = this.onExportButtonClick.bind(this);
      this.onExport = this.onExport.bind(this);
      this.onKeyDown = this.onKeyDown.bind(this);
      this.printShortCutDetect = this.printShortCutDetect.bind(this);
    }
  
    /**
     * Adds export button, print, and other functionality to the report. The method
     * should be called whenever the report needs to be re-rendered.
     * @param {!ReportRenderer.ReportJSON} report
     */
    initFeatures(report) {
      this.json = report;
      this._setupMediaQueryListeners();
      this._setupExportButton();
      this._setUpCollapseDetailsAfterPrinting();
      this._resetUIState();
      this._document.addEventListener('keydown', this.printShortCutDetect);
      this._document.addEventListener('copy', this.onCopy);
    }
  
    /**
     * Fires a custom DOM event on target.
     * @param {string} name Name of the event.
     * @param {!Node=} target DOM node to fire the event on.
     * @param {*=} detail Custom data to include.
     */
    _fireEventOn(name, target = this._document, detail) {
      const event = new CustomEvent(name, detail ? {detail} : null);
      this._document.dispatchEvent(event);
    }
  
    _setupMediaQueryListeners() {
      const mediaQuery = self.matchMedia('(max-width: 600px)');
      mediaQuery.addListener(this.onMediaQueryChange);
      // Ensure the handler is called on init
      this.onMediaQueryChange(mediaQuery);
    }
  
    /**
     * Handle media query change events.
     * @param {!MediaQueryList} mql
     */
    onMediaQueryChange(mql) {
      const root = this._dom.find('.lh-root', this._document);
      root.classList.toggle('lh-narrow', mql.matches);
    }
  
    _setupExportButton() {
      this.exportButton = this._dom.find('.lh-export__button', this._document);
      this.exportButton.addEventListener('click', this.onExportButtonClick);
  
      const dropdown = this._dom.find('.lh-export__dropdown', this._document);
      dropdown.addEventListener('click', this.onExport);
    }
  
    /**
     * Handle copy events.
     * @param {!Event} e
     */
    onCopy(e) {
      // Only handle copy button presses (e.g. ignore the user copying page text).
      if (this._copyAttempt) {
        // We want to write our own data to the clipboard, not the user's text selection.
        e.preventDefault();
        e.clipboardData.setData('text/plain', JSON.stringify(this.json, null, 2));
  
        this._fireEventOn('lh-log', this._document, {
          cmd: 'log', msg: 'Report JSON copied to clipboard'
        });
      }
  
      this._copyAttempt = false;
    }
  
    /**
     * Copies the report JSON to the clipboard (if supported by the browser).
     * @suppress {reportUnknownTypes}
     */
    onCopyButtonClick() {
      this._fireEventOn('lh-analytics', this._document, {
        cmd: 'send',
        fields: {hitType: 'event', eventCategory: 'report', eventAction: 'copy'}
      });
  
      try {
        if (this._document.queryCommandSupported('copy')) {
          this._copyAttempt = true;
  
          // Note: In Safari 10.0.1, execCommand('copy') returns true if there's
          // a valid text selection on the page. See http://caniuse.com/#feat=clipboard.
          if (!this._document.execCommand('copy')) {
            this._copyAttempt = false; // Prevent event handler from seeing this as a copy attempt.
  
            this._fireEventOn('lh-log', this._document, {
              cmd: 'warn', msg: 'Your browser does not support copy to clipboard.'
            });
          }
        }
      } catch (/** @type {!Error} */ e) {
        this._copyAttempt = false;
        this._fireEventOn('lh-log', this._document, {cmd: 'log', msg: e.message});
      }
    }
  
    closeExportDropdown() {
      this.exportButton.classList.remove('active');
    }
  
    /**
     * Click handler for export button.
     * @param {!Event} e
     */
    onExportButtonClick(e) {
      e.preventDefault();
      const el = /** @type {!Element} */ (e.target);
      el.classList.toggle('active');
      this._document.addEventListener('keydown', this.onKeyDown);
    }
  
    /**
     * Resets the state of page before capturing the page for export.
     * When the user opens the exported HTML page, certain UI elements should
     * be in their closed state (not opened) and the templates should be unstamped.
     */
    _resetUIState() {
      this.closeExportDropdown();
      this._dom.resetTemplates();
    }
  
    /**
     * Handler for "export as" button.
     * @param {!Event} e
     */
    onExport(e) {
      e.preventDefault();
  
      const el = /** @type {!Element} */ (e.target);
  
      if (!el.hasAttribute('data-action')) {
        return;
      }
  
      switch (el.getAttribute('data-action')) {
        case 'copy':
          this.onCopyButtonClick();
          break;
        case 'print':
          this.expandAllDetails();
          this.closeExportDropdown();
          self.print();
          break;
        case 'save-json': {
          const jsonStr = JSON.stringify(this.json, null, 2);
          this._saveFile(new Blob([jsonStr], {type: 'application/json'}));
          break;
        }
        case 'save-html': {
          const htmlStr = this.getReportHtml();
          try {
            this._saveFile(new Blob([htmlStr], {type: 'text/html'}));
          } catch (/** @type {!Error} */ e) {
            this._fireEventOn('lh-log', this._document, {
              cmd: 'error', msg: 'Could not export as HTML. ' + e.message
            });
          }
          break;
        }
        case 'open-viewer': {
          this.sendJsonReport();
          break;
        }
        case 'save-gist': {
          this.saveAsGist();
          break;
        }
      }
  
      this.closeExportDropdown();
      this._document.removeEventListener('keydown', this.onKeyDown);
    }
  
    /**
     * Keydown handler for the document.
     * @param {!Event} e
     */
    onKeyDown(e) {
      if (e.keyCode === 27) { // ESC
        this.closeExportDropdown();
      }
    }
  
    /**
     * Opens a new tab to the online viewer and sends the local page's JSON results
     * to the online viewer using postMessage.
     * @protected
     */
    sendJsonReport() {
      const VIEWER_ORIGIN = 'https://googlechrome.github.io';
      const VIEWER_URL = `${VIEWER_ORIGIN}/lighthouse/viewer/`;
  
      // Chrome doesn't allow us to immediately postMessage to a popup right
      // after it's created. Normally, we could also listen for the popup window's
      // load event, however it is cross-domain and won't fire. Instead, listen
      // for a message from the target app saying "I'm open".
      const json = this.json;
      window.addEventListener('message', function msgHandler(/** @type {!Event} */ e) {
        const messageEvent = /** @type {!MessageEvent<{opened: boolean}>} */ (e);
        if (messageEvent.origin !== VIEWER_ORIGIN) {
          return;
        }
  
        if (messageEvent.data.opened) {
          popup.postMessage({lhresults: json}, VIEWER_ORIGIN);
          window.removeEventListener('message', msgHandler);
        }
      });
  
      const popup = /** @type {!Window} */ (window.open(VIEWER_URL, '_blank'));
    }
  
    /**
     * Expands audit details when user prints via keyboard shortcut.
     * @param {!Event} e
     */
    printShortCutDetect(e) {
      if ((e.ctrlKey || e.metaKey) && e.keyCode === 80) { // Ctrl+P
        this.expandAllDetails();
        this.closeExportDropdown();
      }
    }
  
    /**
     * Expands all audit `<details>`.
     * Ideally, a print stylesheet could take care of this, but CSS has no way to
     * open a `<details>` element.
     */
    expandAllDetails() {
      const details = this._dom.findAll('.lh-categories details', this._document);
      details.map(detail => detail.open = true);
    }
  
    /**
     * Collapses all audit `<details>`.
     * open a `<details>` element.
     */
    collapseAllDetails() {
      const details = this._dom.findAll('.lh-categories details', this._document);
      details.map(detail => detail.open = false);
    }
  
    /**
     * Sets up listeners to collapse audit `<details>` when the user closes the
     * print dialog, all `<details>` are collapsed.
     */
    _setUpCollapseDetailsAfterPrinting() {
      // FF and IE implement these old events.
      if ('onbeforeprint' in self) {
        self.addEventListener('afterprint', this.collapseAllDetails);
      } else {
        // Note: FF implements both window.onbeforeprint and media listeners. However,
        // it doesn't matchMedia doesn't fire when matching 'print'.
        self.matchMedia('print').addListener(mql => {
          if (mql.matches) {
            this.expandAllDetails();
          } else {
            this.collapseAllDetails();
          }
        });
      }
    }
  
    /**
     * Returns the html that recreates this report.
     * @return {string}
     * @protected
     */
    getReportHtml() {
      this._resetUIState();
      return this._document.documentElement.outerHTML;
    }
  
    /**
     * Save json as a gist. Unimplemented in base UI features.
     * @protected
     */
    saveAsGist() {
      throw new Error('Cannot save as gist from base report');
    }
  
    /**
     * Downloads a file (blob) using a[download].
     * @param {!Blob|!File} blob The file to save.
     * @private
     */
    _saveFile(blob) {
      const filename = getFilenamePrefix({
        url: this.json.url,
        generatedTime: this.json.generatedTime
      });
  
      const ext = blob.type.match('json') ? '.json' : '.html';
      const href = URL.createObjectURL(blob);
  
      const a = /** @type {!HTMLAnchorElement} */ (this._dom.createElement('a'));
      a.download = `${filename}${ext}`;
      a.href = href;
      this._document.body.appendChild(a); // Firefox requires anchor to be in the DOM.
      a.click();
  
      // cleanup.
      this._document.body.removeChild(a);
      setTimeout(_ => URL.revokeObjectURL(href), 500);
    }
  }
  
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = ReportUIFeatures;
  } else {
    self.ReportUIFeatures = ReportUIFeatures;
  }
  