import*as Common from"../common/common.js";import*as i18n from"../i18n/i18n.js";import*as UI from"../ui/ui.js";import{Events,RuntimeSettings}from"./LighthouseController.js";const UIStrings={cancel:"Cancel",loading:"Loading\u2026",auditingS:"Auditing {PH1}",auditingYourWebPage:"Auditing your web page",cancelling:"Cancelling\u2026",lighthouseIsWarmingUp:"`Lighthouse` is warming up\u2026",lighthouseIsLoadingYourPage:"`Lighthouse` is loading your page",fastFactMessageWithPlaceholder:"\ud83d\udca1 {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("lighthouse/LighthouseStatusView.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_),i18nLazyString=i18n.i18n.getLazilyComputedLocalizedString.bind(void 0,str_);export class StatusView{constructor(e){this._controller=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._scheduledTextChangeTimeout=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:"lighthouse/lighthouseDialog.css",enableLegacyPatching:!1,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(UI.GlassPane.SizeBehavior.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._scheduledTextChangeTimeout=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}\u2026`)}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),s=StatusPhases.indexOf(t),i=StatusPhases.indexOf(this._currentPhase);if(t||this._currentPhase){if(t&&(!this._currentPhase||i<s)){this._currentPhase=t;const e=this._getMessageForPhase(t);this._scheduleTextChange(e),this._scheduleFastFactCheck(),this._resetProgressBarClasses(),this._progressBar&&(this._progressBar.classList.add(t.progressBarClass),UI.ARIAUtils.setProgressBarValue(this._progressBar,s,e))}}else this._commitTextChange(i18nString(UIStrings.lighthouseIsWarmingUp)),clearTimeout(this._scheduledFastFactTimeout)}_cancel(){this._controller.dispatchEventToListeners(Events.RequestLighthouseCancel)}_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():"",n=LoadingMessages.find((e=>e.deviceType===i&&e.throttling===a));return n?n.message():i18nString(UIStrings.lighthouseIsLoadingYourPage)}_getPhaseForMessage(e){return StatusPhases.find((t=>e.startsWith(t.statusMessagePrefix)))||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._scheduleTextChange(i18nString(UIStrings.fastFactMessageWithPlaceholder,{PH1:this._fastFactsQueued[e]})),this._fastFactsQueued.splice(e,1)}_commitTextChange(e){this._statusText&&(this._textChangedAt=performance.now(),this._statusText.textContent=e)}_scheduleTextChange(e){this._scheduledTextChangeTimeout&&clearTimeout(this._scheduledTextChangeTimeout);const t=performance.now()-this._textChangedAt,s=minimumTextVisibilityDuration-t;this._scheduledTextChangeTimeout=window.setTimeout((()=>{this._commitTextChange(e)}),Math.max(s,0))}renderBugReport(e){if(console.error(e),this._scheduledFastFactTimeout&&window.clearTimeout(this._scheduledFastFactTimeout),this._scheduledTextChangeTimeout&&window.clearTimeout(this._scheduledTextChangeTimeout),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),statusMessagePrefix:"Loading page"},{id:"gathering",progressBarClass:"gathering",message:i18nLazyString(UIStrings.lighthouseIsGatheringInformation),statusMessagePrefix:"Gathering"},{id:"auditing",progressBarClass:"auditing",message:i18nLazyString(UIStrings.almostThereLighthouseIsNow),statusMessagePrefix:"Auditing"}];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)];