summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/extensions/extension_error.js
blob: 7853a157dd597a86b929a5db218b6aa2d56a0296 (plain)
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
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('extensions', function() {
  'use strict';

  /**
   * Clone a template within the extension error template collection.
   * @param {string} templateName The class name of the template to clone.
   * @return {HTMLElement} The clone of the template.
   */
  function cloneTemplate(templateName) {
    return /** @type {HTMLElement} */($('template-collection-extension-error').
        querySelector('.' + templateName).cloneNode(true));
  }

  /**
   * Checks that an Extension ID follows the proper format (i.e., is 32
   * characters long, is lowercase, and contains letters in the range [a, p]).
   * @param {string} id The Extension ID to test.
   * @return {boolean} Whether or not the ID is valid.
   */
  function idIsValid(id) {
    return /^[a-p]{32}$/.test(id);
  }

  /**
   * @param {!Array<(ManifestError|RuntimeError)>} errors
   * @param {number} id
   * @return {number} The index of the error with |id|, or -1 if not found.
   */
  function findErrorById(errors, id) {
    for (var i = 0; i < errors.length; ++i) {
      if (errors[i].id == id)
        return i;
    }
    return -1;
  }

  /**
   * Creates a new ExtensionError HTMLElement; this is used to show a
   * notification to the user when an error is caused by an extension.
   * @param {(RuntimeError|ManifestError)} error The error the element should
   *     represent.
   * @constructor
   * @extends {HTMLElement}
   */
  function ExtensionError(error) {
    var div = cloneTemplate('extension-error-metadata');
    div.__proto__ = ExtensionError.prototype;
    div.decorate(error);
    return div;
  }

  ExtensionError.prototype = {
    __proto__: HTMLElement.prototype,

    /**
     * @param {(RuntimeError|ManifestError)} error The error the element should
     *     represent.
     * @private
     */
    decorate: function(error) {
      /**
       * The backing error.
       * @type {(ManifestError|RuntimeError)}
       */
      this.error = error;
      var iconAltTextKey = 'extensionLogLevelWarn';

      // Add an additional class for the severity level.
      if (error.type == chrome.developerPrivate.ErrorType.RUNTIME) {
        switch (error.severity) {
          case chrome.developerPrivate.ErrorLevel.LOG:
            this.classList.add('extension-error-severity-info');
            iconAltTextKey = 'extensionLogLevelInfo';
            break;
          case chrome.developerPrivate.ErrorLevel.WARN:
            this.classList.add('extension-error-severity-warning');
            break;
          case chrome.developerPrivate.ErrorLevel.ERROR:
            this.classList.add('extension-error-severity-fatal');
            iconAltTextKey = 'extensionLogLevelError';
            break;
          default:
            assertNotReached();
        }
      } else {
        // We classify manifest errors as "warnings".
        this.classList.add('extension-error-severity-warning');
      }

      var iconNode = document.createElement('img');
      iconNode.className = 'extension-error-icon';
      iconNode.alt = loadTimeData.getString(iconAltTextKey);
      this.insertBefore(iconNode, this.firstChild);

      var messageSpan = this.querySelector('.extension-error-message');
      messageSpan.textContent = error.message;

      var deleteButton = this.querySelector('.error-delete-button');
      deleteButton.addEventListener('click', function(e) {
        this.dispatchEvent(
            new CustomEvent('deleteExtensionError',
                            {bubbles: true, detail: this.error}));
      }.bind(this));

      this.addEventListener('click', function(e) {
        if (e.target != deleteButton)
          this.requestActive_();
      }.bind(this));

      this.addEventListener('keydown', function(e) {
        if (e.keyIdentifier == 'Enter' && e.target != deleteButton)
          this.requestActive_();
      });
    },

    /**
     * Bubble up an event to request to become active.
     * @private
     */
    requestActive_: function() {
      this.dispatchEvent(
          new CustomEvent('highlightExtensionError',
                          {bubbles: true, detail: this.error}));
    },
  };

  /**
   * A variable length list of runtime or manifest errors for a given extension.
   * @param {Array<(RuntimeError|ManifestError)>} errors The list of extension
   *     errors with which to populate the list.
   * @param {string} extensionId The id of the extension.
   * @constructor
   * @extends {HTMLDivElement}
   */
  function ExtensionErrorList(errors, extensionId) {
    var div = cloneTemplate('extension-error-list');
    div.__proto__ = ExtensionErrorList.prototype;
    div.extensionId_ = extensionId;
    div.decorate(errors);
    return div;
  }

  /**
   * @param {!Element} root
   * @param {?Node} boundary
   * @constructor
   * @extends {cr.ui.FocusRow}
   */
  ExtensionErrorList.FocusRow = function(root, boundary) {
    cr.ui.FocusRow.call(this, root, boundary);

    this.addItem('message', '.extension-error-message');
    this.addItem('delete', '.error-delete-button');
  };

  ExtensionErrorList.FocusRow.prototype = {
    __proto__: cr.ui.FocusRow.prototype,
  };

  ExtensionErrorList.prototype = {
    __proto__: HTMLDivElement.prototype,

    /**
     * Initializes the extension error list.
     * @param {Array<(RuntimeError|ManifestError)>} errors The list of errors.
     */
    decorate: function(errors) {
      /** @private {!Array<(ManifestError|RuntimeError)>} */
      this.errors_ = [];

      /** @private {!cr.ui.FocusGrid} */
      this.focusGrid_ = new cr.ui.FocusGrid();

      /** @private {Element} */
      this.listContents_ = this.querySelector('.extension-error-list-contents');

      errors.forEach(this.addError_, this);

      this.focusGrid_.ensureRowActive();

      this.addEventListener('highlightExtensionError', function(e) {
        this.setActiveErrorNode_(e.target);
      });
      this.addEventListener('deleteExtensionError', function(e) {
        this.removeError_(e.detail);
      });

      this.querySelector('#extension-error-list-clear').addEventListener(
          'click', function(e) {
        this.clear(true);
      }.bind(this));

      /**
       * The callback for the extension changed event.
       * @private {function(chrome.developerPrivate.EventData):void}
       */
      this.onItemStateChangedListener_ = function(data) {
        var type = chrome.developerPrivate.EventType;
        if ((data.event_type == type.ERRORS_REMOVED ||
             data.event_type == type.ERROR_ADDED) &&
            data.extensionInfo.id == this.extensionId_) {
          var newErrors = data.extensionInfo.runtimeErrors.concat(
              data.extensionInfo.manifestErrors);
          this.updateErrors_(newErrors);
        }
      }.bind(this);

      chrome.developerPrivate.onItemStateChanged.addListener(
          this.onItemStateChangedListener_);

      /**
       * The active error element in the list.
       * @private {?}
       */
      this.activeError_ = null;

      this.setActiveError(0);
    },

    /**
     * Adds an error to the list.
     * @param {(RuntimeError|ManifestError)} error The error to add.
     * @private
     */
    addError_: function(error) {
      this.querySelector('#no-errors-span').hidden = true;
      this.errors_.push(error);

      var extensionError = new ExtensionError(error);
      this.listContents_.appendChild(extensionError);

      this.focusGrid_.addRow(
          new ExtensionErrorList.FocusRow(extensionError, this.listContents_));
    },

    /**
     * Removes an error from the list.
     * @param {(RuntimeError|ManifestError)} error The error to remove.
     * @private
     */
    removeError_: function(error) {
      var index = 0;
      for (; index < this.errors_.length; ++index) {
        if (this.errors_[index].id == error.id)
          break;
      }
      assert(index != this.errors_.length);
      var errorList = this.querySelector('.extension-error-list-contents');

      var wasActive =
          this.activeError_ && this.activeError_.error.id == error.id;

      this.errors_.splice(index, 1);
      var listElement = errorList.children[index];

      var focusRow = this.focusGrid_.getRowForRoot(listElement);
      this.focusGrid_.removeRow(focusRow);
      this.focusGrid_.ensureRowActive();
      focusRow.destroy();

      // TODO(dbeam): in a world where this UI is actually used, we should
      // probably move the focus before removing |listElement|.
      listElement.parentNode.removeChild(listElement);

      if (wasActive) {
        index = Math.min(index, this.errors_.length - 1);
        this.setActiveError(index);  // Gracefully handles the -1 case.
      }

      chrome.developerPrivate.deleteExtensionErrors({
        extensionId: error.extensionId,
        errorIds: [error.id]
      });

      if (this.errors_.length == 0)
        this.querySelector('#no-errors-span').hidden = false;
    },

    /**
     * Updates the list of errors.
     * @param {!Array<(ManifestError|RuntimeError)>} newErrors The new list of
     *     errors.
     * @private
     */
    updateErrors_: function(newErrors) {
      this.errors_.forEach(function(error) {
        if (findErrorById(newErrors, error.id) == -1)
          this.removeError_(error);
      }, this);
      newErrors.forEach(function(error) {
        var index = findErrorById(this.errors_, error.id);
        if (index == -1)
          this.addError_(error);
        else
          this.errors_[index] = error;  // Update the existing reference.
      }, this);
    },

    /**
     * Called when the list is being removed.
     */
    onRemoved: function() {
      chrome.developerPrivate.onItemStateChanged.removeListener(
          this.onItemStateChangedListener_);
      this.clear(false);
    },

    /**
     * Sets the active error in the list.
     * @param {number} index The index to set to be active.
     */
    setActiveError: function(index) {
      var errorList = this.querySelector('.extension-error-list-contents');
      var item = errorList.children[index];
      this.setActiveErrorNode_(
          item ? item.querySelector('.extension-error-metadata') : null);
      var node = null;
      if (index >= 0 && index < errorList.children.length) {
        node = errorList.children[index].querySelector(
                   '.extension-error-metadata');
      }
      this.setActiveErrorNode_(node);
    },

    /**
     * Clears the list of all errors.
     * @param {boolean} deleteErrors Whether or not the errors should be deleted
     *     on the backend.
     */
    clear: function(deleteErrors) {
      if (this.errors_.length == 0)
        return;

      if (deleteErrors) {
        var ids = this.errors_.map(function(error) { return error.id; });
        chrome.developerPrivate.deleteExtensionErrors({
          extensionId: this.extensionId_,
          errorIds: ids
        });
      }

      this.setActiveErrorNode_(null);
      this.errors_.length = 0;
      var errorList = this.querySelector('.extension-error-list-contents');
      while (errorList.firstChild)
        errorList.removeChild(errorList.firstChild);
    },

    /**
     * Sets the active error in the list.
     * @param {?} node The error to make active.
     * @private
     */
    setActiveErrorNode_: function(node) {
      if (this.activeError_)
        this.activeError_.classList.remove('extension-error-active');

      if (node)
        node.classList.add('extension-error-active');

      this.activeError_ = node;

      this.dispatchEvent(
          new CustomEvent('activeExtensionErrorChanged',
                          {bubbles: true, detail: node ? node.error : null}));
    },
  };

  return {
    ExtensionErrorList: ExtensionErrorList
  };
});