blob: cb1290f1d2b35a9d68e92ec1aba9f6855bbedf83 [file] [log] [blame]
Blink Reformat4c46d092018-04-07 15:32:371// Copyright 2017 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5MobileThrottling.NetworkThrottlingSelector = class {
6 /**
7 * @param {function(!Array<!MobileThrottling.NetworkThrottlingConditionsGroup>):!Array<?SDK.NetworkManager.Conditions>} populateCallback
8 * @param {function(number)} selectCallback
9 * @param {!Common.Setting<!Array<!SDK.NetworkManager.Conditions>>} customNetworkConditionsSetting
10 */
11 constructor(populateCallback, selectCallback, customNetworkConditionsSetting) {
12 this._populateCallback = populateCallback;
13 this._selectCallback = selectCallback;
14 this._customNetworkConditionsSetting = customNetworkConditionsSetting;
15 this._customNetworkConditionsSetting.addChangeListener(this._populateOptions, this);
16 SDK.multitargetNetworkManager.addEventListener(
17 SDK.MultitargetNetworkManager.Events.ConditionsChanged, this._networkConditionsChanged, this);
18 /** @type {!Array<?SDK.NetworkManager.Conditions>} */
19 this._options;
20 this._populateOptions();
21 }
22
23 revealAndUpdate() {
24 Common.Revealer.reveal(this._customNetworkConditionsSetting);
25 this._networkConditionsChanged();
26 }
27
28 /**
29 * @param {!SDK.NetworkManager.Conditions} conditions
30 */
31 optionSelected(conditions) {
32 SDK.multitargetNetworkManager.setNetworkConditions(conditions);
33 }
34
35 _populateOptions() {
36 const disabledGroup = {title: Common.UIString('Disabled'), items: [SDK.NetworkManager.NoThrottlingConditions]};
37 const presetsGroup = {title: Common.UIString('Presets'), items: MobileThrottling.networkPresets};
38 const customGroup = {title: Common.UIString('Custom'), items: this._customNetworkConditionsSetting.get()};
39 this._options = this._populateCallback([disabledGroup, presetsGroup, customGroup]);
40 if (!this._networkConditionsChanged()) {
41 for (let i = this._options.length - 1; i >= 0; i--) {
42 if (this._options[i]) {
43 this.optionSelected(/** @type {!SDK.NetworkManager.Conditions} */ (this._options[i]));
44 break;
45 }
46 }
47 }
48 }
49
50 /**
51 * @return {boolean} returns false if selected condition no longer exists
52 */
53 _networkConditionsChanged() {
54 const value = SDK.multitargetNetworkManager.networkConditions();
55 for (let index = 0; index < this._options.length; ++index) {
56 const option = this._options[index];
57 if (option && option.download === value.download && option.upload === value.upload &&
58 option.latency === value.latency && option.title === value.title) {
59 this._selectCallback(index);
60 return true;
61 }
62 }
63 return false;
64 }
65};