summaryrefslogtreecommitdiffstats
path: root/chromium/chrome/browser/resources/discards/discards_tab.js
blob: 58cccce5e4e6da8361a818371886fd763948b1f3 (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
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// Copyright 2018 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('discards_tab', function() {
  'use strict';

  /**
   * @param {mojom.LifecycleUnitState} state The discard state.
   * @return {boolean} Whether the state is related to discarding.
   */
  function isDiscardRelatedState(state) {
    return state == mojom.LifecycleUnitState.PENDING_DISCARD ||
        state == mojom.LifecycleUnitState.DISCARDED;
  }

  /**
   * Compares two TabDiscardsInfos based on the data in the provided sort-key.
   * @param {string} sortKey The key of the sort. See the "data-sort-key"
   *     attribute of the table headers for valid sort-keys.
   * @param {boolean|number|string} a The first value being compared.
   * @param {boolean|number|string} b The second value being compared.
   * @return {number} A negative number if a < b, 0 if a == b, and a positive
   *     number if a > b.
   */
  function compareTabDiscardsInfos(sortKey, a, b) {
    let val1 = a[sortKey];
    let val2 = b[sortKey];

    // Compares strings.
    if (sortKey == 'title' || sortKey == 'tabUrl') {
      val1 = val1.toLowerCase();
      val2 = val2.toLowerCase();
      if (val1 == val2) {
        return 0;
      }
      return val1 > val2 ? 1 : -1;
    }

    // Compares boolean fields.
    if (['canFreeze', 'canDiscard', 'isAutoDiscardable'].includes(sortKey)) {
      if (val1 == val2) {
        return 0;
      }
      return val1 ? 1 : -1;
    }

    // Compare lifecycle state. This is actually a compound key.
    if (sortKey == 'state') {
      // If the keys are discarding state, then break ties using the discard
      // reason.
      if (val1 == val2 && isDiscardRelatedState(val1)) {
        val1 = a['discardReason'];
        val2 = b['discardReason'];
      }
      return val1 - val2;
    }

    // Compares numeric fields.
    // NOTE: visibility, loadingState and state are represented as a numeric
    // value.
    if ([
          'visibility',
          'loadingState',
          'discardCount',
          'utilityRank',
          'reactivationScore',
          'lastActiveSeconds',
          'siteEngagementScore',
        ].includes(sortKey)) {
      return val1 - val2;
    }

    assertNotReached('Unsupported sort key: ' + sortKey);
    return 0;
  }

  return {
    compareTabDiscardsInfos: compareTabDiscardsInfos,
  };
});


Polymer({
  is: 'discards-tab',

  behaviors: [SortedTableBehavior],

  properties: {
    /**
     * List of tabinfos.
     * @private {?Array<!discards.mojom.TabDiscardsInfo>}
     */
    tabInfos_: {
      type: Array,
    },
  },

  /** @private The current update timer if any. */
  updateTimer_: 0,

  /** @private {(discards.mojom.DetailsProviderRemote|null)} */
  discardsDetailsProvider_: null,

  /** @override */
  ready: function() {
    this.setSortKey('utilityRank');
    this.discardsDetailsProvider_ = discards.getOrCreateDetailsProvider();

    this.updateTable_();
  },

  /**
   * Returns a sort function to compare tab infos based on the provided sort key
   * and a boolean reverse flag.
   * @param {string} sortKey The sort key for the  returned function.
   * @param {boolean} sortReverse True if sorting is reversed.
   * @return {function({Object}, {Object}): number}
   *     A comparison function that compares two tab infos, returns
   *     negative number if a < b, 0 if a == b, and a positive
   *     number if a > b.
   * @private
   */
  computeSortFunction_: function(sortKey, sortReverse) {
    // Polymer 2.0 may invoke multi-property observers before all properties
    // are defined.
    if (!sortKey) {
      return (a, b) => 0;
    }

    return function(a, b) {
      const comp = discards_tab.compareTabDiscardsInfos(sortKey, a, b);
      return sortReverse ? -comp : comp;
    };
  },

  /**
   * Returns a string representation of a visibility enum value for display in
   * a table.
   * @param {discards.mojom.LifecycleUnitVisibility} visibility A visibility
   *     value.
   * @return {string} A string representation of the visibility.
   * @private
   */
  visibilityToString_: function(visibility) {
    switch (visibility) {
      case discards.mojom.LifecycleUnitVisibility.HIDDEN:
        return 'hidden';
      case discards.mojom.LifecycleUnitVisibility.OCCLUDED:
        return 'occluded';
      case discards.mojom.LifecycleUnitVisibility.VISIBLE:
        return 'visible';
    }
    assertNotReached('Unknown visibility: ' + visibility);
  },

  /**
   * Returns a string representation of a loading state enum value for display
   * in a table.
   * @param {mojom.LifecycleUnitLoadingState} loadingState A loading state
   *    value.
   * @return {string} A string representation of the loading state.
   * @private
   */
  loadingStateToString_: function(loadingState) {
    switch (loadingState) {
      case mojom.LifecycleUnitLoadingState.UNLOADED:
        return 'unloaded';
      case mojom.LifecycleUnitLoadingState.LOADING:
        return 'loading';
      case mojom.LifecycleUnitLoadingState.LOADED:
        return 'loaded';
    }
    assertNotReached('Unknown loadingState: ' + loadingState);
  },

  /**
   * Returns a string representation of a discard reason.
   * @param {mojom.LifecycleUnitDiscardReason} reason The discard reason.
   * @return {string} A string representation of the discarding reason.
   * @private
   */
  discardReasonToString_: function(reason) {
    switch (reason) {
      case mojom.LifecycleUnitDiscardReason.EXTERNAL:
        return 'external';
      case mojom.LifecycleUnitDiscardReason.PROACTIVE:
        return 'proactive';
      case mojom.LifecycleUnitDiscardReason.URGENT:
        return 'urgent';
    }
    assertNotReached('Unknown discard reason: ' + reason);
  },

  /**
   * Returns a string representation of a lifecycle state.
   * @param {mojom.LifecycleUnitState} state The lifecycle state.
   * @param {mojom.LifecycleUnitDiscardReason} reason The discard reason. This
   *     is only used if the state is discard related.
   * @param {discards.mojom.LifecycleUnitVisibility} visibility A visibility
   *     value.
   * @param {boolean} hasFocus Whether or not the tab has input focus.
   * @param {mojoBase.mojom.TimeDelta} stateChangeTime Delta between Unix Epoch
   *     and time at which the lifecycle state has changed.
   * @return {string} A string representation of the lifecycle state, augmented
   *     with the discard reason if appropriate.
   * @private
   */
  lifecycleStateToString_: function(
      state, reason, visibility, hasFocus, stateChangeTime) {
    const pageLifecycleStateFromVisibilityAndFocus = function() {
      switch (visibility) {
        case discards.mojom.LifecycleUnitVisibility.HIDDEN:
        case discards.mojom.LifecycleUnitVisibility.OCCLUDED:
          // An occluded page is also considered hidden.
          return 'hidden';
        case discards.mojom.LifecycleUnitVisibility.VISIBLE:
          return hasFocus ? 'active' : 'passive';
      }
      assertNotReached('Unknown visibility: ' + visibility);
    };

    switch (state) {
      case mojom.LifecycleUnitState.ACTIVE:
        return pageLifecycleStateFromVisibilityAndFocus();
      case mojom.LifecycleUnitState.THROTTLED:
        return pageLifecycleStateFromVisibilityAndFocus() + ' (throttled)';
      case mojom.LifecycleUnitState.PENDING_FREEZE:
        return pageLifecycleStateFromVisibilityAndFocus() + ' (pending frozen)';
      case mojom.LifecycleUnitState.FROZEN:
        return 'frozen';
      case mojom.LifecycleUnitState.PENDING_DISCARD:
        return pageLifecycleStateFromVisibilityAndFocus() +
            ' (pending discard (' + this.discardReasonToString_(reason) + '))';
      case mojom.LifecycleUnitState.DISCARDED:
        return 'discarded (' + this.discardReasonToString_(reason) + ')' +
            ((reason == mojom.LifecycleUnitDiscardReason.URGENT) ? ' at ' +
                     // Must convert since Date constructor takes milliseconds.
                     (new Date(stateChangeTime.microseconds / 1000))
                         .toLocaleString() :
                                                                   '');
      case mojom.LifecycleUnitState.PENDING_UNFREEZE:
        return 'frozen (pending unfreeze)';
    }
    assertNotReached('Unknown lifecycle state: ' + state);
  },

  /**
   * Dispatches a request to update tabInfos_.
   * @private
   */
  updateTableImpl_: function() {
    this.discardsDetailsProvider_.getTabDiscardsInfo().then(response => {
      this.tabInfos_ = response.infos;
    });
  },

  /**
   * A wrapper to updateTableImpl_ that is called due to user action and not
   * due to the automatic timer. Cancels the existing timer  and reschedules it
   * after rendering instantaneously.
   * @private
   */
  updateTable_: function() {
    if (this.updateTimer_) {
      clearInterval(this.updateTimer_);
    }
    this.updateTableImpl_();
    this.updateTimer_ = setInterval(this.updateTableImpl_.bind(this), 1000);
  },

  /**
   * Formats an items reactivation for display.
   * @param {discards.mojom.TabDiscardsInfo} item The item in question.
   * @return {string} The formatted reactivation score.
   * @private
   */
  getReactivationScore_: function(item) {
    return item.hasReactivationScore ? item.reactivationScore.toFixed(4) :
                                       'N/A';
  },

  /**
   * Formats an items site engagement score for display.
   * @param {discards.mojom.TabDiscardsInfo} item The item in question.
   * @return {string} The formatted site engagemetn score.
   * @private
   */
  getSiteEngagementScore_: function(item) {
    return item.siteEngagementScore.toFixed(1);
  },

  /**
   * Retrieves favicon style tag value for an item.
   * @param {discards.mojom.TabDiscardsInfo} item The item in question.
   * @return {string} A style to retrieve and display the item's favicon.
   * @private
   */
  getFavIconStyle_: function(item) {
    return 'background-image:' +
        cr.icon.getFaviconForPageURL(item.tabUrl, false);
  },

  /**
   * Formats an items lifecycle state for display.
   * @param {discards.mojom.TabDiscardsInfo} item The item in question.
   * @return {string} A human readable lifecycle state.
   * @private
   */
  getLifeCycleState_: function(item) {
    if (item.loadingState != mojom.LifecycleUnitLoadingState.UNLOADED ||
        item.discardCount > 0) {
      return this.lifecycleStateToString_(
          item.state, item.discardReason, item.visibility, item.hasFocus,
          item.stateChangeTime);
    } else {
      return '';
    }
  },

  /**
   * Returns a string representation of a boolean value for display in a table.
   * @param {boolean} value A boolean value.
   * @return {string} A string representing the bool.
   * @private
   */
  boolToString_: function(value) {
    return discards.boolToString(value);
  },

  /**
   * Converts a |secondsAgo| duration to a user friendly string.
   * @param {number} secondsAgo The duration to render.
   * @return {string} An English string representing the duration.
   * @private
   */
  durationToString_: function(secondsAgo) {
    return discards.durationToString(secondsAgo);
  },

  /**
   * Tests whether an item has reasons why it cannot be frozen.
   * @param {discards.mojom.TabDiscardsInfo} item The item in question.
   * @return {boolean} true iff there are reasons why the item cannot be frozen.
   * @private
   */
  hasCannotFreezeReasons_: function(item) {
    return item.cannotFreezeReasons.length != 0;
  },
  /**
   * Tests whether an item has reasons why it cannot be discarded.
   * @param {discards.mojom.TabDiscardsInfo} item The item in question.
   * @return {boolean} true iff there are reasons why the item cannot be
   *     discarded.
   * @private
   */
  hasCannotDiscardReasons_: function(item) {
    return item.cannotDiscardReasons.length != 0;
  },

  /**
   * Tests whether an item can be loaded.
   * @param {discards.mojom.TabDiscardsInfo} item The item in question.
   * @return {boolean} true iff the item can be loaded.
   * @private
   */
  canLoad_: function(item) {
    return item.loadingState == mojom.LifecycleUnitLoadingState.UNLOADED;
  },

  /**
   * Tests whether an item can be frozen.
   * @param {discards.mojom.TabDiscardsInfo} item The item in question.
   * @return {boolean} true iff the item can be frozen.
   * @private
   */
  canFreeze_: function(item) {
    if (item.visibility == discards.mojom.LifecycleUnitVisibility.HIDDEN ||
        item.visibility == discards.mojom.LifecycleUnitVisibility.OCCLUDED) {
      // Only tabs that aren't visible can be frozen for now.
      switch (item.state) {
        case mojom.LifecycleUnitState.DISCARDED:
        case mojom.LifecycleUnitState.PENDING_DISCARD:
        case mojom.LifecycleUnitState.FROZEN:
        case mojom.LifecycleUnitState.PENDING_FREEZE:
          return false;
      }
      return true;
    }
    return false;
  },

  /**
   * Tests whether an item can be discarded.
   * @param {discards.mojom.TabDiscardsInfo} item The item in question.
   * @return {boolean} true iff the item can be discarded.
   * @private
   */
  canDiscard_: function(item) {
    if (item.visibility == discards.mojom.LifecycleUnitVisibility.HIDDEN ||
        item.visibility == discards.mojom.LifecycleUnitVisibility.OCCLUDED) {
      // Only tabs that aren't visible can be discarded for now.
      switch (item.state) {
        case mojom.LifecycleUnitState.DISCARDED:
        case mojom.LifecycleUnitState.PENDING_DISCARD:
          return false;
      }
      return true;
    }
    return false;
  },

  /**
   * Event handler that toggles the auto discardable flag on an item.
   * @param {Event} e The event.
   * @private
   */
  toggleAutoDiscardable_: function(e) {
    const item = e.model.item;
    this.discardsDetailsProvider_
        .setAutoDiscardable(item.id, !item.isAutoDiscardable)
        .then(this.updateTable_.bind(this));
  },

  /**
   * Event handler that loads a tab.
   * @param {Event} e The event.
   * @private
   */
  loadTab_: function(e) {
    this.discardsDetailsProvider_.loadById(e.model.item.id);
  },

  /**
   * Event handler that freezes a tab.
   * @param {Event} e The event.
   * @private
   */
  freezeTab_: function(e) {
    this.discardsDetailsProvider_.freezeById(e.model.item.id);
  },

  /**
   * Implementation function for tab discarding.
   * @param {Event} e The event.
   * @param {boolean} urgent True if tab should be urgently discarded.
   * @private
   */
  discardTabImpl_: function(e, urgent) {
    this.discardsDetailsProvider_.discardById(e.model.item.id, urgent)
        .then(this.updateTable_.bind(this));
  },

  /**
   * Event handler that discards a given tab.
   * @param {Event} e The event.
   * @private
   */
  discardTab_: function(e) {
    this.discardTabImpl_(e, false);
  },

  /**
   * Event handler that discards a given tab urgently.
   * @param {Event} e The event.
   * @private
   */
  urgentDiscardTab_: function(e) {
    this.discardTabImpl_(e, true);
  },

  /**
   * Implementation function to discard the next discardable tab.
   * @param {boolean} urgent True if tab should be urgently discarded.
   * @private
   */
  discardImpl_: function(urgent) {
    this.discardsDetailsProvider_.discard(urgent).then(() => {
      this.updateTable_();
    });
  },

  /**
   * Event handler that discards the next discardable tab.
   * @param {Event} e The event.
   * @private
   */
  discardNow_: function(e) {
    this.discardImpl_(false);
  },

  /**
   * Event handler that discards the next discardable tab urgently.
   * @param {Event} e The event.
   * @private
   */
  discardUrgentNow_: function(e) {
    this.discardImpl_(true);
  },
});