@react-native/debugger-frontend
Version:
Debugger frontend for React Native based on Chrome DevTools
2 lines (1 loc) • 40.2 kB
JavaScript
import*as t from"../../core/i18n/i18n.js";import*as e from"../../core/sdk/sdk.js";import*as i from"../../core/common/common.js";import*as n from"../../core/host/host.js";import*as o from"../../core/platform/platform.js";import*as r from"../../ui/components/icon_button/icon_button.js";import*as s from"../../ui/legacy/legacy.js";import*as a from"../../ui/visual_logging/visual_logging.js";import"../../ui/components/cards/cards.js";import*as l from"../../ui/components/buttons/buttons.js";const c={noThrottling:"No CPU and no network throttling",noInternetConnectivity:"No internet connectivity",lowTierMobile:"Low-tier mobile",slowGXCpuSlowdown:"Slow 3G & 6x CPU slowdown",slowGXCpuSlowdownCalibrated:"Slow 3G & {PH1}x CPU slowdown",midtierMobile:"Mid-tier mobile",fastGXCpuSlowdown:"Fast 3G & 4x CPU slowdown",fastGXCpuSlowdownCalibrated:"Fast 3G & {PH1}x CPU slowdown",custom:"Custom",checkNetworkAndPerformancePanels:"Check Network and Performance panels"},d=t.i18n.registerUIStrings("panels/mobile_throttling/ThrottlingPresets.ts",c),h=t.i18n.getLocalizedString.bind(void 0,d);class g{static getNoThrottlingConditions(){return{title:"function"==typeof e.NetworkManager.NoThrottlingConditions.title?e.NetworkManager.NoThrottlingConditions.title():e.NetworkManager.NoThrottlingConditions.title,description:h(c.noThrottling),network:e.NetworkManager.NoThrottlingConditions,cpuThrottlingOption:e.CPUThrottlingManager.NoThrottlingOption,jslogContext:"no-throttling"}}static getOfflineConditions(){return{title:"function"==typeof e.NetworkManager.OfflineConditions.title?e.NetworkManager.OfflineConditions.title():e.NetworkManager.OfflineConditions.title,description:h(c.noInternetConnectivity),network:e.NetworkManager.OfflineConditions,cpuThrottlingOption:e.CPUThrottlingManager.NoThrottlingOption,jslogContext:"offline"}}static getLowEndMobileConditions(){const t=0!==e.CPUThrottlingManager.CalibratedLowTierMobileThrottlingOption.rate(),i=t?e.CPUThrottlingManager.CalibratedLowTierMobileThrottlingOption:e.CPUThrottlingManager.LowTierThrottlingOption,n=t?h(c.slowGXCpuSlowdownCalibrated,{PH1:i.rate()}):h(c.slowGXCpuSlowdown);return{title:h(c.lowTierMobile),description:n,network:e.NetworkManager.Slow3GConditions,cpuThrottlingOption:i,jslogContext:"low-end-mobile"}}static getMidTierMobileConditions(){const t=0!==e.CPUThrottlingManager.CalibratedMidTierMobileThrottlingOption.rate(),i=t?e.CPUThrottlingManager.CalibratedMidTierMobileThrottlingOption:e.CPUThrottlingManager.MidTierThrottlingOption,n=t?h(c.fastGXCpuSlowdownCalibrated,{PH1:i.rate()}):h(c.fastGXCpuSlowdown);return{title:h(c.midtierMobile),description:n,network:e.NetworkManager.Slow4GConditions,cpuThrottlingOption:i,jslogContext:"mid-tier-mobile"}}static getCustomConditions(){return{title:h(c.custom),description:h(c.checkNetworkAndPerformancePanels),jslogContext:"custom"}}static getMobilePresets(){return[g.getMidTierMobileConditions(),g.getLowEndMobileConditions(),g.getCustomConditions()]}static getAdvancedMobilePresets(){return[g.getOfflineConditions()]}static getRecommendedNetworkPreset(t){if(!Number.isFinite(t))return null;if(t<60)return null;let e=null,i=1/0;for(const n of g.networkPresets){const{targetLatency:o}=n;if(!o)continue;const r=Math.abs(o-t);r>200||(i<r||(e=n,i=r))}return e}static networkPresets=[e.NetworkManager.Fast4GConditions,e.NetworkManager.Slow4GConditions,e.NetworkManager.Slow3GConditions,e.NetworkManager.OfflineConditions];static cpuThrottlingPresets=[e.CPUThrottlingManager.NoThrottlingOption,e.CPUThrottlingManager.MidTierThrottlingOption,e.CPUThrottlingManager.LowTierThrottlingOption,e.CPUThrottlingManager.ExtraSlowThrottlingOption,e.CPUThrottlingManager.CalibratedLowTierMobileThrottlingOption,e.CPUThrottlingManager.CalibratedMidTierMobileThrottlingOption]}globalThis.MobileThrottling=globalThis.MobileThrottling||{},globalThis.MobileThrottling.networkPresets=g.networkPresets;var u=Object.freeze({__proto__:null,ThrottlingPresets:g});const p={disabled:"Disabled",presets:"Presets",custom:"Custom"},C=t.i18n.registerUIStrings("panels/mobile_throttling/NetworkThrottlingSelector.ts",p),w=t.i18n.getLocalizedString.bind(void 0,C);class b{populateCallback;selectCallback;customNetworkConditionsSetting;options;constructor(t,i,n){this.populateCallback=t,this.selectCallback=i,this.customNetworkConditionsSetting=n,this.customNetworkConditionsSetting.addChangeListener(this.populateOptions,this),e.NetworkManager.MultitargetNetworkManager.instance().addEventListener("ConditionsChanged",(()=>{this.networkConditionsChanged()}),this),this.populateOptions()}revealAndUpdate(){i.Revealer.reveal(this.customNetworkConditionsSetting),this.networkConditionsChanged()}optionSelected(t){e.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(t)}populateOptions(){const t={title:w(p.disabled),items:[e.NetworkManager.NoThrottlingConditions]},i={title:w(p.presets),items:g.networkPresets},n={title:w(p.custom),items:this.customNetworkConditionsSetting.get()};if(this.options=this.populateCallback([t,i,n]),!this.networkConditionsChanged())for(let t=this.options.length-1;t>=0;t--)if(this.options[t]){this.optionSelected(this.options[t]);break}}networkConditionsChanged(){const t=e.NetworkManager.MultitargetNetworkManager.instance().networkConditions();for(let i=0;i<this.options.length;++i){const n=this.options[i];if(n&&e.NetworkManager.networkConditionsEqual(t,n))return this.selectCallback(i),!0}return!1}}var m=Object.freeze({__proto__:null,NetworkThrottlingSelector:b});const k={sS:"{PH1}: {PH2}",add:"Add…",addS:"Add {PH1}",offline:"Offline",forceDisconnectedFromNetwork:"Force disconnected from network",throttling:"Throttling",cpuThrottlingIsEnabled:"CPU throttling is enabled",cpuThrottling:"CPU throttling",excessConcurrency:"Exceeding the default value may degrade system performance.",resetConcurrency:"Reset to the default value",hardwareConcurrency:"Hardware concurrency",hardwareConcurrencySettingLabel:"Override the value reported by navigator.hardwareConcurrency",recommendedThrottling:"{PH1} – recommended",calibrate:"Calibrate…",recalibrate:"Recalibrate…"},v=t.i18n.registerUIStrings("panels/mobile_throttling/ThrottlingManager.ts",k),f=t.i18n.getLocalizedString.bind(void 0,v);let T;class M{cpuThrottlingControls;cpuThrottlingOptions;customNetworkConditionsSetting;currentNetworkThrottlingConditionsSetting;calibratedCpuThrottlingSetting;lastNetworkThrottlingConditions;cpuThrottlingManager;#t=!1;get hardwareConcurrencyOverrideEnabled(){return this.#t}constructor(){this.cpuThrottlingManager=e.CPUThrottlingManager.CPUThrottlingManager.instance(),this.cpuThrottlingManager.addEventListener("RateChanged",(t=>this.onCPUThrottlingRateChangedOnSDK(t.data))),this.cpuThrottlingControls=new Set,this.cpuThrottlingOptions=g.cpuThrottlingPresets,this.customNetworkConditionsSetting=i.Settings.Settings.instance().moduleSetting("custom-network-conditions"),this.currentNetworkThrottlingConditionsSetting=i.Settings.Settings.instance().createSetting("preferred-network-condition",e.NetworkManager.NoThrottlingConditions),this.calibratedCpuThrottlingSetting=i.Settings.Settings.instance().createSetting("calibrated-cpu-throttling",{},"Global"),this.currentNetworkThrottlingConditionsSetting.setSerializer(new e.NetworkManager.ConditionsSerializer),e.NetworkManager.MultitargetNetworkManager.instance().addEventListener("ConditionsChanged",(()=>{this.lastNetworkThrottlingConditions=this.currentNetworkThrottlingConditionsSetting.get(),this.currentNetworkThrottlingConditionsSetting.set(e.NetworkManager.MultitargetNetworkManager.instance().networkConditions())})),this.isDirty()&&e.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(this.currentNetworkThrottlingConditionsSetting.get())}static instance(t={forceNew:null}){const{forceNew:e}=t;return T&&!e||(T=new M),T}createOfflineToolbarCheckbox(){const t=new s.Toolbar.ToolbarCheckbox(f(k.offline),f(k.forceDisconnectedFromNetwork),function(){if(t.checked())e.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(e.NetworkManager.OfflineConditions);else{const t=this.lastNetworkThrottlingConditions.download||this.lastNetworkThrottlingConditions.upload?this.lastNetworkThrottlingConditions:e.NetworkManager.NoThrottlingConditions;e.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(t)}}.bind(this));return t.element.setAttribute("jslog",`${a.toggle("disconnect-from-network").track({click:!0})}`),e.NetworkManager.MultitargetNetworkManager.instance().addEventListener("ConditionsChanged",(function(){t.setChecked(e.NetworkManager.MultitargetNetworkManager.instance().isOffline())})),t.setChecked(e.NetworkManager.MultitargetNetworkManager.instance().isOffline()),t}createMobileThrottlingButton(){const t=new s.Toolbar.ToolbarMenuButton((function(t){for(let o=0;o<e.length;++o){const r=e[o];r&&(r.title===g.getCustomConditions().title&&r.description===g.getCustomConditions().description||t.defaultSection().appendCheckboxItem(r.title,n.optionSelected.bind(n,r),{checked:i===o,jslogContext:r.jslogContext}))}}),void 0,void 0,"mobile-throttling");t.setTitle(f(k.throttling)),t.setDarkText();let e=[],i=-1;const n=new O((function(t){e=[];for(const i of t){for(const t of i.items)e.push(t);e.push(null)}return e}),(function(n){i=n;const o=e[n];o&&(t.setText(o.title),t.setTitle(`${o.title}: ${o.description}`))}));return t}updatePanelIcon(){const t=[];this.cpuThrottlingManager.cpuThrottlingRate()!==e.CPUThrottlingManager.CPUThrottlingRates.NO_THROTTLING&&t.push(f(k.cpuThrottlingIsEnabled)),s.InspectorView.InspectorView.instance().setPanelWarnings("timeline",t)}setCPUThrottlingOption(t){this.cpuThrottlingManager.setCPUThrottlingOption(t)}onCPUThrottlingRateChangedOnSDK(t){t!==e.CPUThrottlingManager.CPUThrottlingRates.NO_THROTTLING&&n.userMetrics.actionTaken(n.UserMetrics.Action.CpuThrottlingEnabled);const i=this.cpuThrottlingOptions.indexOf(this.cpuThrottlingManager.cpuThrottlingOption());for(const t of this.cpuThrottlingControls)t.setSelectedIndex(i);this.updatePanelIcon()}createNetworkThrottlingSelector(t){let e=[],i=[],n=[];const r=new b((function(r){t.removeChildren(),e=[],i=[],n=[];for(let l=0;l<r.length;++l){const c=r[l],d=t.createChild("optgroup");d.label=c.title;for(const t of c.items){const h="function"==typeof t.title?t.title():t.title,g=new Option(h,h);s.ARIAUtils.setLabel(g,f(k.sS,{PH1:c.title,PH2:h}));const u=l===r.length-1?"custom-network-throttling-item":o.StringUtilities.toKebabCase(t.i18nTitleKey||h);g.setAttribute("jslog",`${a.item(u).track({click:!0})}`),d.appendChild(g),e.push(t),i.push(h),n.push(g)}if(l===r.length-1){const t=new Option(f(k.add),f(k.add));s.ARIAUtils.setLabel(t,f(k.addS,{PH1:c.title})),t.setAttribute("jslog",`${a.action("add").track({click:!0})}`),d.appendChild(t),e.push(null)}}return e}),(function(e){t.selectedIndex!==e&&(t.selectedIndex=e)}),this.customNetworkConditionsSetting);return t.setAttribute("jslog",`${a.dropDown().track({change:!0}).context(this.currentNetworkThrottlingConditionsSetting.name)}`),t.addEventListener("change",(function(){if(t.selectedIndex===t.options.length-1)r.revealAndUpdate();else{const i=e[t.selectedIndex];i&&r.optionSelected(i)}}),!1),{selector:r,updateRecommendedConditions(t){for(let o=0;o<n.length;o++){let r=i[o];e[o]===t&&(r=f(k.recommendedThrottling,{PH1:r})),n[o].text=r}}}}createCPUThrottlingSelector(){const t=()=>{const t=this.calibratedCpuThrottlingSetting.get(),e=t.low||t.mid;return f(e?k.recalibrate:k.calibrate)},e=new s.Toolbar.ToolbarComboBox((()=>{if(e.selectedIndex()===e.options().length-1){const t=this.cpuThrottlingOptions.indexOf(this.cpuThrottlingManager.cpuThrottlingOption());e.setSelectedIndex(t),i.Revealer.reveal(this.calibratedCpuThrottlingSetting)}else this.setCPUThrottlingOption(this.cpuThrottlingOptions[e.selectedIndex()])}),f(k.cpuThrottling),"","cpu-throttling");this.cpuThrottlingControls.add(e);const n=this.cpuThrottlingManager.cpuThrottlingOption(),o=[],r=this.cpuThrottlingOptions;for(let t=0;t<this.cpuThrottlingOptions.length;++t){const i=this.cpuThrottlingOptions[t],r=i.title(),s=i.jslogContext,a=e.createOption(r,s);e.addOption(a),n===i&&e.setSelectedIndex(t),o.push(a)}const a=e.createOption(t(),"");return e.addOption(a),o.push(a),{control:e,updateRecommendedOption(e){for(let t=0;t<o.length-1;t++){const i=r[t];o[t].text=i===e?f(k.recommendedThrottling,{PH1:i.title()}):i.title(),o[t].disabled=0===i.rate()}o[o.length-1].textContent=t()}}}createHardwareConcurrencySelector(){const t=new s.Toolbar.ToolbarItem(s.UIUtils.createInput("devtools-text-input","number","hardware-concurrency"));t.setTitle(f(k.hardwareConcurrencySettingLabel));const e=t.element;e.min="1",t.setEnabled(!1);const i=s.UIUtils.CheckboxLabel.create(f(k.hardwareConcurrency),!1,f(k.hardwareConcurrencySettingLabel),"hardware-concurrency"),n=new s.Toolbar.ToolbarButton("Reset concurrency","undo",void 0,"hardware-concurrency-reset");n.setTitle(f(k.resetConcurrency));const o=new r.Icon.Icon;o.data={iconName:"warning-filled",color:"var(--icon-warning)",width:"14px",height:"14px"};const a=new s.Toolbar.ToolbarItem(o);return a.setTitle(f(k.excessConcurrency)),i.checkboxElement.disabled=!0,n.element.classList.add("concurrency-hidden"),a.element.classList.add("concurrency-hidden"),this.cpuThrottlingManager.getHardwareConcurrency().then((o=>{if(void 0===o)return;const r=t=>{t>=1&&this.cpuThrottlingManager.setHardwareConcurrency(t),t>o?a.element.classList.remove("concurrency-hidden"):a.element.classList.add("concurrency-hidden"),t===o?n.element.classList.add("concurrency-hidden"):n.element.classList.remove("concurrency-hidden")};e.value=`${o}`,e.oninput=()=>r(Number(e.value)),i.checkboxElement.disabled=!1,i.checkboxElement.addEventListener("change",(()=>{this.#t=i.checkboxElement.checked,t.setEnabled(this.hardwareConcurrencyOverrideEnabled),r(this.hardwareConcurrencyOverrideEnabled?Number(e.value):o)})),n.addEventListener("Click",(()=>{e.value=`${o}`,r(o)}))})),{numericInput:t,reset:n,warning:a,checkbox:i}}setHardwareConcurrency(t){this.cpuThrottlingManager.setHardwareConcurrency(t)}isDirty(){const t=e.NetworkManager.MultitargetNetworkManager.instance().networkConditions(),i=this.currentNetworkThrottlingConditionsSetting.get();return!e.NetworkManager.networkConditionsEqual(t,i)}}function x(){return M.instance()}var y=Object.freeze({__proto__:null,ActionDelegate:class{handleAction(t,i){return"network-conditions.network-online"===i?(e.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(e.NetworkManager.NoThrottlingConditions),!0):"network-conditions.network-low-end-mobile"===i?(e.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(e.NetworkManager.Slow3GConditions),!0):"network-conditions.network-mid-tier-mobile"===i?(e.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(e.NetworkManager.Slow4GConditions),!0):"network-conditions.network-offline"===i&&(e.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(e.NetworkManager.OfflineConditions),!0)}},ThrottlingManager:M,throttlingManager:x});const N={disabled:"Disabled",presets:"Presets",advanced:"Advanced"},S=t.i18n.registerUIStrings("panels/mobile_throttling/MobileThrottlingSelector.ts",N),P=t.i18n.getLocalizedString.bind(void 0,S);class O{populateCallback;selectCallback;options;constructor(t,i){this.populateCallback=t,this.selectCallback=i,e.CPUThrottlingManager.CPUThrottlingManager.instance().addEventListener("RateChanged",this.conditionsChanged,this),e.NetworkManager.MultitargetNetworkManager.instance().addEventListener("ConditionsChanged",this.conditionsChanged,this),this.options=this.populateOptions(),this.conditionsChanged()}optionSelected(t){e.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(t.network),x().setCPUThrottlingOption(t.cpuThrottlingOption)}populateOptions(){const t={title:P(N.disabled),items:[g.getNoThrottlingConditions()]},e={title:P(N.presets),items:g.getMobilePresets()},i={title:P(N.advanced),items:g.getAdvancedMobilePresets()};return this.populateCallback([t,e,i])}conditionsChanged(){this.populateOptions();const t=e.NetworkManager.MultitargetNetworkManager.instance().networkConditions(),i=e.CPUThrottlingManager.CPUThrottlingManager.instance().cpuThrottlingOption();for(let e=0;e<this.options.length;++e){const n=this.options[e];if(n&&"network"in n&&n.network===t&&n.cpuThrottlingOption===i)return void this.selectCallback(e)}const n=g.getCustomConditions();for(let t=0;t<this.options.length;++t){const e=this.options[t];if(e&&e.title===n.title&&e.description===n.description)return void this.selectCallback(t)}}}var E=Object.freeze({__proto__:null,MobileThrottlingSelector:O});const L={networkThrottlingIsEnabled:"Network throttling is enabled",requestsMayBeOverridden:"Requests may be overridden locally, see the Sources panel",requestsMayBeBlocked:"Requests may be blocked, see the Network request blocking panel",acceptedEncodingOverrideSet:"The set of accepted `Content-Encoding` headers has been modified by DevTools, see the Network conditions panel"},I=t.i18n.registerUIStrings("panels/mobile_throttling/NetworkPanelIndicator.ts",L),U=t.i18n.getLocalizedString.bind(void 0,I);var B=Object.freeze({__proto__:null,NetworkPanelIndicator:class{constructor(){if(!s.InspectorView.InspectorView.instance().hasPanel("network"))return;const t=e.NetworkManager.MultitargetNetworkManager.instance();function n(){const i=[];t.isThrottling()&&i.push(U(L.networkThrottlingIsEnabled)),e.NetworkManager.MultitargetNetworkManager.instance().isIntercepting()&&i.push(U(L.requestsMayBeOverridden)),t.isBlocking()&&i.push(U(L.requestsMayBeBlocked)),t.isAcceptedEncodingOverrideSet()&&i.push(U(L.acceptedEncodingOverrideSet)),s.InspectorView.InspectorView.instance().setPanelWarnings("network",i)}t.addEventListener("ConditionsChanged",n),t.addEventListener("BlockedPatternsChanged",n),t.addEventListener("InterceptorsChanged",n),t.addEventListener("AcceptedEncodingsChanged",n),i.Settings.Settings.instance().moduleSetting("cache-disabled").addChangeListener(n,this),n()}}});const A={runningCalibration:"Running CPU calibration, please do not leave this tab or close DevTools."},R=t.i18n.registerUIStrings("panels/mobile_throttling/CalibrationController.ts",A),H=t.i18n.getLocalizedString.bind(void 0,R),_=1e3,D=264;function j(t){return Number(t.toFixed(2))}class W{#e;#i;#n;#o;#r="idle";async start(){const t=e.TargetManager.TargetManager.instance().primaryPageTarget();if(!t)return!1;const i=t.model(e.RuntimeModel.RuntimeModel),n=t.model(e.EmulationModel.EmulationModel);if(!i||!n)return!1;return this.#r="running",this.#e=i,this.#i=n,this.#n=t.inspectedURL(),await t.pageAgent().invoke_navigate({url:"about:blank"}),await i.agent.invoke_evaluate({expression:`\n (${function(t){const e=document.createElement("span");e.textContent=t,document.body.append(e),document.body.style.cssText="\n font-family: system-ui, sans-serif;\n height: 100vh;\n margin: 0;\n background-color: antiquewhite;\n font-size: 18px;\n text-align: center;\n\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n ";const i=document.createElement("span");document.body.append(i),i.id="moon",i.textContent="🌑",i.style.cssText="font-size: 5em"}})(${JSON.stringify(H(A.runningCalibration))});\n\n window.runBenchmark = () => {\n window.runs = window.runs ?? 0;\n moon.textContent = ['🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'][window.runs++ % 8];\n return (${z})(250);\n }`}),await this.#s(),!0}async#a(t){if("running"!==this.#r)throw this.#o=void 0,new Error("Calibration has been canceled");await this.#i.setCPUThrottlingRate(t)}async#s(){if("running"!==this.#r)throw this.#o=void 0,new Error("Calibration has been canceled");const{result:t}=await this.#e.agent.invoke_evaluate({expression:"runBenchmark()"});if(!Number.isFinite(t.value)){let e=`unexpected score from benchmark: ${t.value}`;throw t.description&&(e+=`\n${t.description}`),new Error(e)}return t.value}async*iterator(){const t=this;let i=!1;yield{progress:0};const n=new Map;async function o(e){const i=n.get(e);if(void 0!==i)return i;await t.#a(e);const o=await t.#s();return n.set(e,o),o}async function*r(t,e,n){const r={rate:e,score:await o(e)},s={rate:n,score:await o(n)};let a=0,l=0;for(;l++<8;){a=j((s.rate+r.rate)/2);const e=await o(a);if(Math.abs(t-e)<10)break;e<t?(s.rate=a,s.score=e):(r.rate=a,r.score=e),yield{progress:l/8/2+(i?.5:0)}}return j(a)}this.#o={};let s=await o(1);if(s<_&&(n.clear(),s=await o(1),s<_)){if(s<D)return void(this.#o={low:e.CPUThrottlingManager.CalibrationError.DEVICE_TOO_WEAK,mid:e.CPUThrottlingManager.CalibrationError.DEVICE_TOO_WEAK});this.#o={mid:e.CPUThrottlingManager.CalibrationError.DEVICE_TOO_WEAK},i=!0}const a=s/D*1.5,l=yield*r(D,1,a);if(this.#o.low=l,!this.#o.mid){i=!0,yield{progress:.5};const t=l/3.787878787878788,e=yield*r(_,t-t/4,t+t/4);this.#o.mid=e}yield{progress:1}}abort(){"running"===this.#r&&(this.#r="aborting")}result(){return this.#o}async end(){"idle"!==this.#r&&(this.#r="idle",this.#n.startsWith("chrome://")?await this.#e.agent.invoke_evaluate({expression:"history.back()"}):await this.#e.agent.invoke_evaluate({expression:`window.location.href = ${JSON.stringify(this.#n)}`}))}}function z(t=1e3){const e=t/2;return(function(){const t=Date.now();let i=0;for(;Date.now()-t<e;){let t="";for(let e=0;e<1e4;e++)t+="a";if(1===t.length)throw new Error("will never happen, but prevents compiler optimizations");i++}const n=(Date.now()-t)/1e3;return Math.round(i/10/n)}()+function(){const t=[],i=[];for(let e=0;e<1e5;e++)t[e]=i[e]=e;const n=Date.now();let o=0;for(;o%10!=0||Date.now()-n<e;){const e=o%2==0?t:i,n=o%2==0?i:t;for(let t=0;t<e.length;t++)n[t]=e[t];o++}const r=(Date.now()-n)/1e3;return Math.round(o/10/r)}())/2}var G={cssText:`.add-conditions-button{margin:var(--sys-size-5) 0;border:none}.conditions-list{flex:auto;&:has(.list-item){margin-top:var(--sys-size-3)}}.conditions-list-item{padding:3px 5px;height:30px;display:flex;align-items:center;position:relative;flex:auto 1 1}.conditions-list-text{text-overflow:ellipsis;overflow:hidden;flex:0 0 60px;user-select:none;color:var(--sys-color-on-surface);text-align:center;position:relative;& > input{scroll-margin-left:5px}}.conditions-list-text:last-child{flex-basis:100px;text-align:left}.conditions-list-title{text-align:start;display:flex;flex-grow:1;align-items:flex-start}.conditions-list-title-text{flex:auto;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.conditions-list-separator{flex:0 0 1px;background-color:var(--sys-color-divider);height:30px;margin:0 4px}.conditions-list-separator-invisible{visibility:hidden;height:100%!important}.conditions-edit-row{flex:none;display:flex;flex-direction:row;margin:6px 5px;.conditions-list-title-text{white-space:unset}}.conditions-edit-row input{&[type="checkbox"]{margin:auto;top:6px;position:relative;display:flex;align-items:center;justify-content:center}&:not([type="checkbox"]){width:100%;text-align:inherit}}.conditions-edit-optional{margin-top:var(--sys-size-5);color:var(--sys-color-on-surface-subtle)}.editor-buttons{margin-top:10px}.settings-card-container-wrapper{scrollbar-gutter:stable;padding:var(--sys-size-8) 0;overflow:auto;position:absolute;inset:var(--sys-size-8) 0 0}.settings-card-container{display:flex;flex-direction:column;align-items:center;gap:var(--sys-size-9)}.cpu-preset-section{padding:14px;display:flex;justify-content:space-between}.cpu-preset-result.not-calibrated{font-style:italic}.cpu-preset-calibrate{flex-direction:column;gap:14px}.cpu-preset-calibrate .button-container{display:flex;gap:10px}.cpu-preset-calibrate .text-container{display:flex;flex-direction:column;gap:10px}.text-with-icon{display:flex;align-items:center;gap:5px}\n/*# sourceURL=${import.meta.resolve("./throttlingSettingsTab.css")} */\n`};const q={networkThrottlingProfiles:"Network throttling profiles",addCustomProfile:"Add profile",dms:"{PH1} `ms`",profileName:"Profile Name",download:"Download",upload:"Upload",latency:"Latency",packetLoss:"Packet Loss",percent:"percent",packetQueueLength:"Packet Queue Length",packetReordering:"Packet Reordering",packet:"packet",optional:"optional",profileNameCharactersLengthMust:"Profile Name characters length must be between 1 to {PH1} inclusive",sMustBeANumberBetweenSkbsToSkbs:"{PH1} must be a number between {PH2} `kbit/s` to {PH3} `kbit/s` inclusive",latencyMustBeAnIntegerBetweenSms:"Latency must be an integer between {PH1} `ms` to {PH2} `ms` inclusive",packetLossMustBeAnIntegerBetweenSpct:"Packet Loss must be a number between {PH1} `%` to {PH2} `%` inclusive",packetQueueLengthMustBeAnIntegerGreaterOrEqualToZero:"Packet Queue Length must be greater or equal to 0",dskbits:"{PH1} `kbit/s`",fsmbits:"{PH1} `Mbit/s`",on:"On",off:"Off",cpuThrottlingPresets:"CPU throttling presets",calibrate:"Calibrate",recalibrate:"Recalibrate",continue:"Continue",cancel:"Cancel",needsCalibration:"Needs calibration",calibrationCTA:"To use the CPU throttling presets, run the calibration process to determine the ideal throttling rate for your device.",cpuCalibrationDescription:"These presets throttle your CPU to approximate the performance of typical low or mid-tier mobile devices.",calibrationConfirmationPrompt:"Calibration will take ~5 seconds, and temporarily navigate away from your current page. Do you wish to continue?",calibrationWarningHighCPU:"CPU utilization is too high",calibrationWarningRunningOnBattery:"Device is running on battery, please plug in charger for best results",calibrationWarningLowBattery:"Device battery is low (<20%), results may be impacted by CPU throttling",dSlowdown:"{PH1}× slowdown"},$=t.i18n.registerUIStrings("panels/mobile_throttling/ThrottlingSettingsTab.ts",q),F=t.i18n.getLocalizedString.bind(void 0,$);class Q{element;setting;computePressurePromise;controller;lowTierMobileDeviceEl;midTierMobileDeviceEl;calibrateEl;textEl;calibrateButton;cancelButton;progress;state="cta";warnings=[];constructor(){this.setting=i.Settings.Settings.instance().createSetting("calibrated-cpu-throttling",{},"Global"),this.element=document.createElement("devtools-card"),this.element.heading=F(q.cpuThrottlingPresets);this.element.createChild("span").textContent=F(q.cpuCalibrationDescription),this.lowTierMobileDeviceEl=this.element.createChild("div","cpu-preset-section"),this.lowTierMobileDeviceEl.append("Low-tier mobile device"),this.lowTierMobileDeviceEl.createChild("div","cpu-preset-result"),this.midTierMobileDeviceEl=this.element.createChild("div","cpu-preset-section"),this.midTierMobileDeviceEl.append("Mid-tier mobile device"),this.midTierMobileDeviceEl.createChild("div","cpu-preset-result"),this.calibrateEl=this.element.createChild("div","cpu-preset-section cpu-preset-calibrate");const t=this.calibrateEl.createChild("div","button-container");this.calibrateButton=new l.Button.Button,this.calibrateButton.classList.add("calibrate-button"),this.calibrateButton.data={variant:"primary",jslogContext:"throttling.calibrate"},this.calibrateButton.addEventListener("click",(()=>this.calibrateButtonClicked())),t.append(this.calibrateButton),this.cancelButton=new l.Button.Button,this.cancelButton.classList.add("cancel-button"),this.cancelButton.data={variant:"outlined",jslogContext:"throttling.calibrate-cancel"},this.cancelButton.textContent=F(q.cancel),this.cancelButton.addEventListener("click",(()=>this.cancelButtonClicked())),t.append(this.cancelButton),this.textEl=this.calibrateEl.createChild("div","text-container"),this.progress=new s.ProgressIndicator.ProgressIndicator({showStopButton:!1}),this.calibrateEl.append(this.progress.element),this.updateState()}wasShown(){this.computePressurePromise=function(){const t={state:""};return new Promise((e=>{new PressureObserver((i=>{t.state=i.at(-1).state,e(t)})).observe("cpu",{sampleInterval:1e3})}))}(),this.state="cta",this.updateState()}willHide(){this.computePressurePromise=void 0,this.controller&&this.controller.abort()}updateState(){"calibrating"!==this.state&&(this.controller=void 0);const t=this.setting.get(),i=t.low||t.mid;if(this.calibrateButton.style.display="none",this.textEl.style.display="none",this.cancelButton.style.display="none",this.progress.element.style.display="none","cta"===this.state)this.calibrateButton.style.display="",this.calibrateButton.textContent=F(i?q.recalibrate:q.calibrate),i||(this.textEl.style.display="",this.textEl.textContent="",this.textEl.append(this.createTextWithIcon(F(q.calibrationCTA),"info")));else if("prompting"===this.state){this.calibrateButton.style.display="",this.calibrateButton.textContent=F(q.continue),this.cancelButton.style.display="",this.textEl.style.display="",this.textEl.textContent="";for(const t of this.warnings)this.textEl.append(this.createTextWithIcon(t,"warning"));this.textEl.append(this.createTextWithIcon(F(q.calibrationConfirmationPrompt),"info"))}else"calibrating"===this.state&&(this.cancelButton.style.display="",this.progress.element.style.display="");const n=(t,i)=>{if(!t)throw new Error("expected HTMLElement");t.textContent=(t=>void 0===t?F(q.needsCalibration):"string"==typeof t?e.CPUThrottlingManager.calibrationErrorToString(t):"number"!=typeof t?`Invalid: ${t}`:F(q.dSlowdown,{PH1:t.toFixed(1)}))(i),t.classList.toggle("not-calibrated",void 0===i)};n(this.lowTierMobileDeviceEl.querySelector(".cpu-preset-result"),t.low),n(this.midTierMobileDeviceEl.querySelector(".cpu-preset-result"),t.mid)}createTextWithIcon(t,e){const i=document.createElement("div");return i.classList.add("text-with-icon"),i.append(r.Icon.create(e)),i.append(t),i}async getCalibrationWarnings(){const t=[];if(this.computePressurePromise){const e=await this.computePressurePromise;"critical"!==e.state&&"serious"!==e.state||t.push(F(q.calibrationWarningHighCPU))}const e=await navigator.getBattery();return e.charging?e.level<.2&&t.push(F(q.calibrationWarningLowBattery)):t.push(F(q.calibrationWarningRunningOnBattery)),t}async calibrateButtonClicked(){"cta"===this.state?(this.warnings=await this.getCalibrationWarnings(),this.state="prompting",this.updateState()):"prompting"===this.state&&(this.state="calibrating",this.updateState(),this.runCalibration())}cancelButtonClicked(){this.controller?this.controller.abort():(this.state="cta",this.updateState())}async runCalibration(){this.progress.setWorked(0),this.progress.setTotalWork(1),this.controller=new W;try{if(!await this.controller.start())return void console.error("Calibration failed to start");for await(const t of this.controller.iterator())this.progress.setWorked(t.progress)}catch(t){console.error(t)}finally{await this.controller.end()}const t=this.controller.result();t&&(t.low||t.mid)&&(this.setting.set(t),this.progress.setWorked(1),await new Promise((t=>setTimeout(t,200)))),this.state="cta",this.updateState()}}class V extends s.Widget.VBox{list;customSetting;editor;cpuThrottlingCard;constructor(){super(!0),this.registerRequiredCSS(G),this.element.setAttribute("jslog",`${a.pane("throttling-conditions")}`);const t=this.contentElement.createChild("div","settings-card-container-wrapper").createChild("div");t.classList.add("settings-card-container","throttling-conditions-settings"),this.cpuThrottlingCard=new Q,t.append(this.cpuThrottlingCard.element);const e=new l.Button.Button;e.classList.add("add-conditions-button"),e.data={variant:"outlined",iconName:"plus",jslogContext:"network.add-conditions"},e.textContent=F(q.addCustomProfile),e.addEventListener("click",(()=>this.addButtonClicked()));const n=t.createChild("devtools-card");n.heading=F(q.networkThrottlingProfiles);const o=n.createChild("div");this.list=new s.ListWidget.ListWidget(this),this.list.element.classList.add("conditions-list"),this.list.registerRequiredCSS(G),this.list.show(o),o.appendChild(e),this.customSetting=i.Settings.Settings.instance().moduleSetting("custom-network-conditions"),this.customSetting.addChangeListener(this.conditionsUpdated,this)}wasShown(){super.wasShown(),this.cpuThrottlingCard.wasShown(),this.conditionsUpdated()}willHide(){super.willHide(),this.cpuThrottlingCard.willHide()}conditionsUpdated(){this.list.clear();const t=this.customSetting.get();for(let e=0;e<t.length;++e)this.list.appendItem(t[e],!0);this.list.appendSeparator()}addButtonClicked(){this.list.addNewItem(this.customSetting.get().length,{title:()=>"",download:-1,upload:-1,latency:0,packetLoss:0,packetReordering:!1})}renderItem(t,e){const i=document.createElement("div");i.classList.add("conditions-list-item");const n=i.createChild("div","conditions-list-text conditions-list-title").createChild("div","conditions-list-title-text"),o=this.retrieveOptionsTitle(t);return n.textContent=o,s.Tooltip.Tooltip.install(n,o),i.createChild("div","conditions-list-separator"),i.createChild("div","conditions-list-text").textContent=X(t.download),i.createChild("div","conditions-list-separator"),i.createChild("div","conditions-list-text").textContent=X(t.upload),i.createChild("div","conditions-list-separator"),i.createChild("div","conditions-list-text").textContent=F(q.dms,{PH1:t.latency}),i.createChild("div","conditions-list-separator"),i.createChild("div","conditions-list-text").textContent=function(t){if(t<0)return"";return String(t)+"%"}(t.packetLoss??0),i.createChild("div","conditions-list-separator"),i.createChild("div","conditions-list-text").textContent=String(t.packetQueueLength??0),i.createChild("div","conditions-list-separator"),i.createChild("div","conditions-list-text").textContent=t.packetReordering?F(q.on):F(q.off),i}removeItemRequested(t,e){const i=this.customSetting.get();i.splice(e,1),this.customSetting.set(i)}retrieveOptionsTitle(t){return"function"==typeof t.title?t.title():t.title}commitEdit(t,e,i){t.title=e.control("title").value.trim();const n=e.control("download").value.trim();t.download=n?125*parseInt(n,10):-1;const o=e.control("upload").value.trim();t.upload=o?125*parseInt(o,10):-1;const r=e.control("latency").value.trim();t.latency=r?parseInt(r,10):0;const s=e.control("packetLoss").value.trim();t.packetLoss=s?parseFloat(s):0;const a=e.control("packetQueueLength").value.trim();t.packetQueueLength=a?parseFloat(a):0;const l=e.control("packetReordering").checked;t.packetReordering=l;const c=this.customSetting.get();i&&c.push(t),this.customSetting.set(c)}beginEdit(t){const e=this.createEditor();return e.control("title").value=this.retrieveOptionsTitle(t),e.control("download").value=t.download<=0?"":String(t.download/125),e.control("upload").value=t.upload<=0?"":String(t.upload/125),e.control("latency").value=t.latency?String(t.latency):"",e.control("packetLoss").value=t.packetLoss?String(t.packetLoss):"",e.control("packetQueueLength").value=t.packetQueueLength?String(t.packetQueueLength):"",e.control("packetReordering").checked=t.packetReordering??!1,e}createEditor(){if(this.editor)return this.editor;const e=new s.ListWidget.Editor;this.editor=e;const i=e.contentElement(),n=i.createChild("div","conditions-edit-row"),o=n.createChild("div","conditions-list-text conditions-list-title"),r=F(q.profileName);o.createChild("div","conditions-list-title-text").textContent=r,n.createChild("div","conditions-list-separator conditions-list-separator-invisible");const a=n.createChild("div","conditions-list-text"),l=F(q.download);a.createChild("div","conditions-list-title-text").textContent=l,n.createChild("div","conditions-list-separator conditions-list-separator-invisible");const c=n.createChild("div","conditions-list-text").createChild("div","conditions-list-title-text"),d=F(q.upload);c.textContent=d,n.createChild("div","conditions-list-separator conditions-list-separator-invisible");const h=n.createChild("div","conditions-list-text"),g=F(q.latency);h.createChild("div","conditions-list-title-text").textContent=g,n.createChild("div","conditions-list-separator conditions-list-separator-invisible");const u=n.createChild("div","conditions-list-text"),p=F(q.packetLoss);u.createChild("div","conditions-list-title-text").textContent=p,n.createChild("div","conditions-list-separator conditions-list-separator-invisible");const C=n.createChild("div","conditions-list-text"),w=F(q.packetQueueLength);C.createChild("div","conditions-list-title-text").textContent=w,n.createChild("div","conditions-list-separator conditions-list-separator-invisible");const b=n.createChild("div","conditions-list-text"),m=F(q.packetReordering);b.createChild("div","conditions-list-title-text").textContent=m;const k=i.createChild("div","conditions-edit-row"),v=e.createInput("title","text","",(function(t,e,i){const n=i.value.trim(),o=n.length>0&&n.length<=49;if(!o){return{valid:o,errorMessage:F(q.profileNameCharactersLengthMust,{PH1:49})}}return{valid:o,errorMessage:void 0}}));s.ARIAUtils.setLabel(v,r),k.createChild("div","conditions-list-text conditions-list-title").appendChild(v),k.createChild("div","conditions-list-separator conditions-list-separator-invisible");let f=k.createChild("div","conditions-list-text");const T=e.createInput("download","text",t.i18n.lockedString("kbit/s"),E);f.appendChild(T),s.ARIAUtils.setLabel(T,l);const M=f.createChild("div","conditions-edit-optional"),x=F(q.optional);M.textContent=x,s.ARIAUtils.setDescription(T,x),k.createChild("div","conditions-list-separator conditions-list-separator-invisible"),f=k.createChild("div","conditions-list-text");const y=e.createInput("upload","text",t.i18n.lockedString("kbit/s"),E);s.ARIAUtils.setLabel(y,d),f.appendChild(y);f.createChild("div","conditions-edit-optional").textContent=x,s.ARIAUtils.setDescription(y,x),k.createChild("div","conditions-list-separator conditions-list-separator-invisible"),f=k.createChild("div","conditions-list-text");const N=e.createInput("latency","text",t.i18n.lockedString("ms"),(function(t,e,i){const n=1e6,o=i.value.trim(),r=Number(o),s=Number.isInteger(r)&&r>=0&&r<=n;if(!s){return{valid:s,errorMessage:F(q.latencyMustBeAnIntegerBetweenSms,{PH1:0,PH2:n})}}return{valid:s,errorMessage:void 0}}));s.ARIAUtils.setLabel(N,g),f.appendChild(N);f.createChild("div","conditions-edit-optional").textContent=x,s.ARIAUtils.setDescription(N,x),k.createChild("div","conditions-list-separator conditions-list-separator-invisible"),f=k.createChild("div","conditions-list-text");const S=e.createInput("packetLoss","text",t.i18n.lockedString("percent"),(function(t,e,i){const n=i.value.trim(),o=Number(n),r=o>=0&&o<=100;if(!r){return{valid:r,errorMessage:F(q.packetLossMustBeAnIntegerBetweenSpct,{PH1:0,PH2:100})}}return{valid:r,errorMessage:void 0}}));s.ARIAUtils.setLabel(S,p),f.appendChild(S);f.createChild("div","conditions-edit-optional").textContent=x,s.ARIAUtils.setDescription(S,x),k.createChild("div","conditions-list-separator conditions-list-separator-invisible"),f=k.createChild("div","conditions-list-text");const P=e.createInput("packetQueueLength","text",F(q.packet),(function(t,e,i){const n=i.value.trim(),o=Number(n)>=0;if(!o){return{valid:o,errorMessage:F(q.packetQueueLengthMustBeAnIntegerGreaterOrEqualToZero)}}return{valid:o,errorMessage:void 0}}));s.ARIAUtils.setLabel(P,w),f.appendChild(P);f.createChild("div","conditions-edit-optional").textContent=x,s.ARIAUtils.setDescription(P,x),k.createChild("div","conditions-list-separator conditions-list-separator-invisible"),f=k.createChild("div","conditions-list-text");const O=e.createInput("packetReordering","checkbox",F(q.percent),(function(t,e,i){return{valid:!0,errorMessage:void 0}}));return s.ARIAUtils.setLabel(O,p),f.appendChild(O),e;function E(t,e,i){const n=1e7,o=i.value.trim(),r=Number(o),s=i.getAttribute("aria-label"),a=!Number.isNaN(r)&&r>=0&&r<=n;if(!a){return{valid:a,errorMessage:F(q.sMustBeANumberBetweenSkbsToSkbs,{PH1:String(s),PH2:0,PH3:n})}}return{valid:a,errorMessage:void 0}}}}function X(t){if(t<0)return"";const e=t/125;if(e<1e3)return F(q.dskbits,{PH1:e});if(e<1e4){const t=(e/1e3).toFixed(1);return F(q.fsmbits,{PH1:t})}return F(q.fsmbits,{PH1:e/1e3|0})}var K=Object.freeze({__proto__:null,CPUThrottlingCard:Q,ThrottlingSettingsTab:V});export{E as MobileThrottlingSelector,B as NetworkPanelIndicator,m as NetworkThrottlingSelector,y as ThrottlingManager,u as ThrottlingPresets,K as ThrottlingSettingsTab};