import*as Common from"../../core/common/common.js";import*as i18n from"../../core/i18n/i18n.js";import*as UI from"../../ui/legacy/legacy.js";import{RuntimeSettings}from"./LighthouseController.js";import lighthouseDialogStyles from"./lighthouseDialog.css.js";const UIStrings={cancel:"Cancel",loading:"Loading…",auditingS:"Auditing {PH1}",auditingYourWebPage:"Auditing your web page",cancelling:"Cancelling…",lighthouseIsWarmingUp:"`Lighthouse` is warming up…",lighthouseIsLoadingYourPage:"`Lighthouse` is loading your page",fastFactMessageWithPlaceholder:"💡 {PH1}",ahSorryWeRanIntoAnError:"Ah, sorry! We ran into an error.",tryToNavigateToTheUrlInAFresh:"Try to navigate to the URL in a fresh `Chrome` profile without any other tabs or extensions open and try again.",ifThisIssueIsReproduciblePlease:"If this issue is reproducible, please report it at the `Lighthouse` `GitHub` repo.",lighthouseIsLoadingThePage:"Lighthouse is loading the page.",lighthouseIsGatheringInformation:"`Lighthouse` is gathering information about the page to compute your score.",almostThereLighthouseIsNow:"Almost there! `Lighthouse` is now generating your report.",lighthouseIsLoadingYourPageWith:"`Lighthouse` is loading your page with throttling to measure performance on a mobile device on 3G.",lighthouseIsLoadingYourPageWithThrottling:"`Lighthouse` is loading your page with throttling to measure performance on a slow desktop on 3G.",lighthouseIsLoadingYourPageWithMobile:"`Lighthouse` is loading your page with mobile emulation.",mbTakesAMinimumOfSecondsTo:"1MB takes a minimum of 5 seconds to download on a typical 3G connection [Source: `WebPageTest` and `DevTools` 3G definition].",rebuildingPinterestPagesFor:"Rebuilding Pinterest pages for performance increased conversion rates by 15% [Source: `WPO Stats`]",byReducingTheResponseSizeOfJson:"By reducing the response size of JSON needed for displaying comments, Instagram saw increased impressions [Source: `WPO Stats`]",walmartSawAIncreaseInRevenueFor:"Walmart saw a 1% increase in revenue for every 100ms improvement in page load [Source: `WPO Stats`]",ifASiteTakesSecondToBecome:"If a site takes >1 second to become interactive, users lose attention, and their perception of completing the page task is broken [Source: `Google Developers Blog`]",OfGlobalMobileUsersInWereOnGOrG:"75% of global mobile users in 2016 were on 2G or 3G [Source: `GSMA Mobile`]",theAverageUserDeviceCostsLess:"The average user device costs less than 200 USD. [Source: `International Data Corporation`]",SecondsIsTheAverageTimeAMobile:"19 seconds is the average time a mobile web page takes to load on a 3G connection [Source: `Google DoubleClick blog`]",OfMobilePagesTakeNearlySeconds:"70% of mobile pages take nearly 7 seconds for the visual content above the fold to display on the screen. [Source: `Think with Google`]",asPageLoadTimeIncreasesFromOne:"As page load time increases from one second to seven seconds, the probability of a mobile site visitor bouncing increases 113%. [Source: `Think with Google`]",asTheNumberOfElementsOnAPage:"As the number of elements on a page increases from 400 to 6,000, the probability of conversion drops 95%. [Source: `Think with Google`]",lighthouseOnlySimulatesMobile:"`Lighthouse` only simulates mobile performance; to measure performance on a real device, try WebPageTest.org [Source: `Lighthouse` team]"},str_=i18n.i18n.registerUIStrings("panels/lighthouse/LighthouseStatusView.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_),i18nLazyString=i18n.i18n.getLazilyComputedLocalizedString.bind(void 0,str_);export class StatusView{panel;statusView;statusHeader;progressWrapper;progressBar;statusText;cancelButton;inspectedURL;textChangedAt;fastFactsQueued;currentPhase;scheduledFastFactTimeout;dialog;constructor(e){this.panel=e,this.statusView=null,this.statusHeader=null,this.progressWrapper=null,this.progressBar=null,this.statusText=null,this.cancelButton=null,this.inspectedURL="",this.textChangedAt=0,this.fastFactsQueued=FastFacts.map((e=>e())),this.currentPhase=null,this.scheduledFastFactTimeout=null,this.dialog=new UI.Dialog.Dialog,this.dialog.setDimmed(!0),this.dialog.setCloseOnEscape(!1),this.dialog.setOutsideClickCallback((e=>e.consume(!0))),this.render()}render(){const e=UI.Utils.createShadowRootWithCoreStyles(this.dialog.contentElement,{cssFile:[lighthouseDialogStyles],delegatesFocus:void 0}).createChild("div","lighthouse-view vbox"),t=UI.UIUtils.createTextButton(i18nString(UIStrings.cancel),this.cancel.bind(this)),s=UI.Fragment.Fragment.build`
  <div class="lighthouse-view vbox">
  <h2 $="status-header">Auditing your web page…</h2>
  <div class="lighthouse-status vbox" $="status-view">
  <div class="lighthouse-progress-wrapper" $="progress-wrapper">
  <div class="lighthouse-progress-bar" $="progress-bar"></div>
  </div>
  <div class="lighthouse-status-text" $="status-text"></div>
  </div>
  ${t}
  </div>
  `;e.appendChild(s.element()),this.statusView=s.$("status-view"),this.statusHeader=s.$("status-header"),this.progressWrapper=s.$("progress-wrapper"),this.progressBar=s.$("progress-bar"),this.statusText=s.$("status-text"),UI.ARIAUtils.markAsProgressBar(this.progressBar,0,StatusPhases.length-1),this.cancelButton=t,UI.ARIAUtils.markAsStatus(this.statusText),this.dialog.setDefaultFocusedElement(t),this.dialog.setSizeBehavior("SetExactWidthMaxHeight"),this.dialog.setMaxContentSize(new UI.Geometry.Size(500,400))}reset(){this.resetProgressBarClasses(),clearTimeout(this.scheduledFastFactTimeout),this.textChangedAt=0,this.fastFactsQueued=FastFacts.map((e=>e())),this.currentPhase=null,this.scheduledFastFactTimeout=null}show(e){this.reset(),this.updateStatus(i18nString(UIStrings.loading));const t=Common.ParsedURL.ParsedURL.fromString(this.inspectedURL),s=t&&t.host,i=s?i18nString(UIStrings.auditingS,{PH1:s}):i18nString(UIStrings.auditingYourWebPage);this.renderStatusHeader(i),this.dialog.show(e)}renderStatusHeader(e){this.statusHeader&&(this.statusHeader.textContent=`${e}…`)}hide(){this.dialog.isShowing()&&this.dialog.hide()}setInspectedURL(e=""){this.inspectedURL=e}updateStatus(e){if(!e||!this.statusText)return;if(e.startsWith("Cancel"))return this.commitTextChange(i18nString(UIStrings.cancelling)),void clearTimeout(this.scheduledFastFactTimeout);const t=this.getPhaseForMessage(e);if(t||this.currentPhase){if(t){this.currentPhase=t;const e=this.getMessageForPhase(t);if(this.commitTextChange(e),this.scheduleFastFactCheck(),this.resetProgressBarClasses(),this.progressBar){this.progressBar.classList.add(t.progressBarClass);const s=StatusPhases.indexOf(t);UI.ARIAUtils.setProgressBarValue(this.progressBar,s,e)}}}else this.commitTextChange(i18nString(UIStrings.lighthouseIsWarmingUp)),clearTimeout(this.scheduledFastFactTimeout)}cancel(){this.panel.handleRunCancel()}getMessageForPhase(e){if(e.message())return e.message();const t=RuntimeSettings.find((e=>"lighthouse.device_type"===e.setting.name)),s=RuntimeSettings.find((e=>"lighthouse.throttling"===e.setting.name)),i=t?t.setting.get():"",a=s?s.setting.get():"",o=LoadingMessages.find((e=>e.deviceType===i&&e.throttling===a));return o?o.message():i18nString(UIStrings.lighthouseIsLoadingYourPage)}getPhaseForMessage(e){return StatusPhases.find((t=>t.statusMessageRegex.test(e)))||null}resetProgressBarClasses(){this.progressBar&&(this.progressBar.className="lighthouse-progress-bar")}scheduleFastFactCheck(){this.currentPhase&&!this.scheduledFastFactTimeout&&(this.scheduledFastFactTimeout=window.setTimeout((()=>{this.updateFastFactIfNecessary(),this.scheduledFastFactTimeout=null,this.scheduleFastFactCheck()}),100))}updateFastFactIfNecessary(){if(performance.now()-this.textChangedAt<fastFactRotationInterval)return;if(!this.fastFactsQueued.length)return;const e=Math.floor(Math.random()*this.fastFactsQueued.length);this.commitTextChange(i18nString(UIStrings.fastFactMessageWithPlaceholder,{PH1:this.fastFactsQueued[e]})),this.fastFactsQueued.splice(e,1)}commitTextChange(e){this.statusText&&(this.textChangedAt=performance.now(),this.statusText.textContent=e)}renderBugReport(e){if(console.error(e),this.scheduledFastFactTimeout&&window.clearTimeout(this.scheduledFastFactTimeout),this.resetProgressBarClasses(),this.progressBar&&this.progressBar.classList.add("errored"),this.statusText)if(this.commitTextChange(""),UI.UIUtils.createTextChild(this.statusText.createChild("p"),i18nString(UIStrings.ahSorryWeRanIntoAnError)),KnownBugPatterns.some((t=>t.test(e.message)))){const e=i18nString(UIStrings.tryToNavigateToTheUrlInAFresh);UI.UIUtils.createTextChild(this.statusText.createChild("p"),e)}else this.renderBugReportBody(e,this.inspectedURL)}renderText(e,t){this.renderStatusHeader(e),this.commitTextChange(t)}toggleCancelButton(e){this.cancelButton&&(this.cancelButton.style.visibility=e?"visible":"hidden")}renderBugReportBody(e,t){const s=navigator.userAgent.match(/Chrome\/(\S+)/)||["","Unknown"],i=`\n${e.friendlyMessage||e.message}\n\`\`\`\nChannel: DevTools\nInitial URL: ${t}\nChrome Version: ${s[1]}\nStack Trace: ${e.stack}\n\`\`\`\n`;this.statusText&&(UI.UIUtils.createTextChild(this.statusText.createChild("p"),i18nString(UIStrings.ifThisIssueIsReproduciblePlease)),UI.UIUtils.createTextChild(this.statusText.createChild("code","monospace"),i.trim()))}}export const fastFactRotationInterval=6e3;export const minimumTextVisibilityDuration=3e3;const KnownBugPatterns=[/PARSING_PROBLEM/,/DOCUMENT_REQUEST/,/READ_FAILED/,/TRACING_ALREADY_STARTED/,/^You must provide a url to the runner/,/^You probably have multiple tabs open/];export const StatusPhases=[{id:"loading",progressBarClass:"loading",message:i18nLazyString(UIStrings.lighthouseIsLoadingThePage),statusMessageRegex:/^(Navigating to)/},{id:"gathering",progressBarClass:"gathering",message:i18nLazyString(UIStrings.lighthouseIsGatheringInformation),statusMessageRegex:/(Gather|artifact)/i},{id:"auditing",progressBarClass:"auditing",message:i18nLazyString(UIStrings.almostThereLighthouseIsNow),statusMessageRegex:/^Audit/}];const LoadingMessages=[{deviceType:"mobile",throttling:"on",message:i18nLazyString(UIStrings.lighthouseIsLoadingYourPageWith)},{deviceType:"desktop",throttling:"on",message:i18nLazyString(UIStrings.lighthouseIsLoadingYourPageWithThrottling)},{deviceType:"mobile",throttling:"off",message:i18nLazyString(UIStrings.lighthouseIsLoadingYourPageWithMobile)},{deviceType:"desktop",throttling:"off",message:i18nLazyString(UIStrings.lighthouseIsLoadingThePage)}],FastFacts=[i18nLazyString(UIStrings.mbTakesAMinimumOfSecondsTo),i18nLazyString(UIStrings.rebuildingPinterestPagesFor),i18nLazyString(UIStrings.byReducingTheResponseSizeOfJson),i18nLazyString(UIStrings.walmartSawAIncreaseInRevenueFor),i18nLazyString(UIStrings.ifASiteTakesSecondToBecome),i18nLazyString(UIStrings.OfGlobalMobileUsersInWereOnGOrG),i18nLazyString(UIStrings.theAverageUserDeviceCostsLess),i18nLazyString(UIStrings.SecondsIsTheAverageTimeAMobile),i18nLazyString(UIStrings.OfMobilePagesTakeNearlySeconds),i18nLazyString(UIStrings.asPageLoadTimeIncreasesFromOne),i18nLazyString(UIStrings.asTheNumberOfElementsOnAPage),i18nLazyString(UIStrings.OfMobilePagesTakeNearlySeconds),i18nLazyString(UIStrings.lighthouseOnlySimulatesMobile)];