UNPKG

@react-native/debugger-frontend

Version:
2 lines (1 loc) 49.7 kB
import*as e from"../../../../models/text_utils/text_utils.js";import*as t from"../../../../core/common/common.js";import*as n from"../../../../core/i18n/i18n.js";import*as s from"../../legacy.js";import*as i from"../../../../core/host/host.js";import*as r from"../../../../core/platform/platform.js";import*as o from"../../../../core/root/root.js";import*as a from"../../../../models/formatter/formatter.js";import*as l from"../../../../third_party/codemirror.next/codemirror.next.js";import"../../../components/buttons/buttons.js";import*as c from"../../../components/code_highlighter/code_highlighter.js";import*as h from"../../../components/text_editor/text_editor.js";import*as d from"../../../visual_logging/visual_logging.js";import*as u from"../../../../models/workspace/workspace.js";import*as m from"../../../../core/sdk/sdk.js";import*as p from"../object_ui/object_ui.js";const g=["application/javascript","application/json","application/manifest+json","text/css","text/html","text/javascript"];var f={cssContent:".searchable-view{flex:1}.toolbar{background-color:var(--sys-color-cdt-base-container);border-top:1px solid var(--sys-color-divider)}\n/*# sourceURL=resourceSourceFrame.css */\n"},w={cssContent:".widget{padding:20px}.title{font-size:larger}.title,\n.message,\n.button,\n.text-input{margin:5px}.button{text-align:right;margin-top:10px;display:flex;justify-content:flex-end;gap:var(--sys-size-6)}.button button{min-width:80px}.dialog-close-button{position:absolute;right:9px;top:9px;z-index:1}\n/*# sourceURL=selfXssDialog.css */\n"};const S={source:"Source",prettyPrint:"Pretty print",loading:"Loading…",dSelectionRegions:"{PH1} selection regions",bytecodePositionXs:"Bytecode position `0x`{PH1}",lineSColumnS:"Line {PH1}, Column {PH2}",dCharactersSelected:"{PH1} characters selected",dLinesDCharactersSelected:"{PH1} lines, {PH2} characters selected",doYouTrustThisCode:"Do you trust this code?",doNotPaste:"Don't paste code you do not understand or have not reviewed yourself into DevTools. This could allow attackers to steal your identity or take control of your computer. Please type ''{PH1}'' below to allow pasting.",allowPasting:"allow pasting",cancel:"Cancel",allow:"Allow",typeAllowPasting:"Type ''{PH1}''"},x=n.i18n.registerUIStrings("ui/legacy/components/source_frame/SourceFrame.ts",S),b=n.i18n.getLocalizedString.bind(void 0,x),y=l.Facet.define({combine:e=>0===e.length?e=>e.toString():e[0]});class T extends(t.ObjectWrapper.eventMixin(s.View.SimpleView)){options;lazyContent;prettyInternal;rawContent;formattedMap;prettyToggle;shouldAutoPrettyPrint;progressToolbarItem;textEditorInternal;baseDoc;prettyBaseDoc=null;displayedSelection=null;searchConfig;delayedFindSearchMatches;currentSearchResultIndex;searchResults;searchRegex;loadError;muteChangeEventsForSetContent;sourcePosition;searchableView;editable;positionToReveal;lineToScrollTo;selectionToSet;loadedInternal;contentRequested;wasmDisassemblyInternal;contentSet;selfXssWarningDisabledSetting;constructor(e,n={}){super(b(S.source)),this.options=n,this.lazyContent=e,this.prettyInternal=!1,this.rawContent=null,this.formattedMap=null,this.prettyToggle=new s.Toolbar.ToolbarToggle(b(S.prettyPrint),"brackets",void 0,"pretty-print"),this.prettyToggle.addEventListener("Click",(()=>{this.setPretty(!this.prettyToggle.toggled())})),this.shouldAutoPrettyPrint=!1,this.prettyToggle.setVisible(!1),this.progressToolbarItem=new s.Toolbar.ToolbarItem(document.createElement("div")),this.textEditorInternal=new h.TextEditor.TextEditor(this.placeholderEditorState("")),this.textEditorInternal.style.flexGrow="1",this.element.appendChild(this.textEditorInternal),this.element.addEventListener("keydown",(e=>{e.defaultPrevented&&e.stopPropagation()})),this.baseDoc=this.textEditorInternal.state.doc,this.searchConfig=null,this.delayedFindSearchMatches=null,this.currentSearchResultIndex=-1,this.searchResults=[],this.searchRegex=null,this.loadError=!1,this.muteChangeEventsForSetContent=!1,this.sourcePosition=new s.Toolbar.ToolbarText,this.searchableView=null,this.editable=!1,this.positionToReveal=null,this.lineToScrollTo=null,this.selectionToSet=null,this.loadedInternal=!1,this.contentRequested=!1,this.wasmDisassemblyInternal=null,this.contentSet=!1,this.selfXssWarningDisabledSetting=t.Settings.Settings.instance().createSetting("disable-self-xss-warning",!1,"Synced"),t.Settings.Settings.instance().moduleSetting("text-editor-indent").addChangeListener(this.#e,this)}disposeView(){t.Settings.Settings.instance().moduleSetting("text-editor-indent").removeChangeListener(this.#e,this)}async#e(){this.prettyInternal&&(await this.setPretty(!1),await this.setPretty(!0))}placeholderEditorState(e){return l.EditorState.create({doc:e,extensions:[l.EditorState.readOnly.of(!0),!1!==this.options.lineNumbers?l.lineNumbers():[],h.Config.theme()]})}editorConfiguration(e){return[l.EditorView.updateListener.of((e=>this.dispatchEventToListeners("EditorUpdate",e))),h.Config.baseConfiguration(e),h.Config.closeBrackets.instance(),h.Config.autocompletion.instance(),h.Config.showWhitespace.instance(),h.Config.allowScrollPastEof.instance(),l.Prec.lowest(h.Config.codeFolding.instance()),h.Config.autoDetectIndent.instance(),U,l.EditorView.domEventHandlers({focus:()=>this.onFocus(),blur:()=>this.onBlur(),paste:()=>this.onPaste(),scroll:()=>this.dispatchEventToListeners("EditorScroll"),contextmenu:e=>this.onContextMenu(e)}),l.lineNumbers({domEventHandlers:{contextmenu:(e,t,n)=>this.onLineGutterContextMenu(t.from,n)}}),l.EditorView.updateListener.of((e=>{(e.selectionSet||e.docChanged)&&this.updateSourcePosition(),e.docChanged&&this.onTextChanged()})),R,l.Prec.lowest(V),E.language.of([]),this.wasmDisassemblyInternal?(t=this.wasmDisassemblyInternal,M.init((e=>{const n=[];for(const s of t.nonBreakableLineNumbers())s<e.doc.lines&&n.push(F.range(e.doc.line(s+1).from));return l.RangeSet.of(n)}))):M,this.options.lineWrapping?l.EditorView.lineWrapping:[],!1!==this.options.lineNumbers?l.lineNumbers():[],o.Runtime.experiments.isEnabled("sources-frame-indentation-markers-temporarily-disable")?[]:l.indentationMarkers({colors:{light:"var(--sys-color-divider)",activeLight:"var(--sys-color-divider-prominent)",dark:"var(--sys-color-divider)",activeDark:"var(--sys-color-divider-prominent)"}})];var t}onBlur(){}onFocus(){this.resetCurrentSearchResultIndex()}onPaste(){return!(o.Runtime.Runtime.queryParam("isChromeForTesting")||o.Runtime.Runtime.queryParam("disableSelfXssWarnings")||this.selfXssWarningDisabledSetting.get())&&(this.showSelfXssWarning(),!0)}async showSelfXssWarning(){await new Promise((e=>setTimeout(e,0)));await v.show()&&(this.selfXssWarningDisabledSetting.set(!0),i.userMetrics.actionTaken(i.UserMetrics.Action.SelfXssAllowPastingInDialog))}get wasmDisassembly(){return this.wasmDisassemblyInternal}editorLocationToUILocation(e,t){return this.wasmDisassemblyInternal?(t=this.wasmDisassemblyInternal.lineNumberToBytecodeOffset(e),e=0):this.prettyInternal&&([e,t]=this.prettyToRawLocation(e,t)),{lineNumber:e,columnNumber:t}}uiLocationToEditorLocation(e,t=0){return this.wasmDisassemblyInternal?(e=this.wasmDisassemblyInternal.bytecodeOffsetToLineNumber(t),t=0):this.prettyInternal&&([e,t]=this.rawToPrettyLocation(e,t)),{lineNumber:e,columnNumber:t}}setCanPrettyPrint(e,n){this.shouldAutoPrettyPrint=!0===n&&t.Settings.Settings.instance().moduleSetting("auto-pretty-print-minified").get(),this.prettyToggle.setVisible(e)}setEditable(e){this.editable=e,this.loaded&&e!==!this.textEditor.state.readOnly&&this.textEditor.dispatch({effects:E.editable.reconfigure(l.EditorState.readOnly.of(!e))})}async setPretty(e){this.prettyInternal=e,this.prettyToggle.setEnabled(!1);const t=this.loaded,{textEditor:n}=this,s=n.state.selection.main,i=n.toLineColumn(s.from),r=n.toLineColumn(s.to);let o;if(this.prettyInternal){const e=this.rawContent instanceof l.Text?this.rawContent.sliceString(0):this.rawContent||"",t=await a.ScriptFormatter.formatScriptContent(this.contentType,e);this.formattedMap=t.formattedMapping,await this.setContent(t.formattedContent),this.prettyBaseDoc=n.state.doc;const s=this.rawToPrettyLocation(i.lineNumber,i.columnNumber),c=this.rawToPrettyLocation(r.lineNumber,r.columnNumber);o=n.createSelection({lineNumber:s[0],columnNumber:s[1]},{lineNumber:c[0],columnNumber:c[1]})}else{await this.setContent(this.rawContent||""),this.baseDoc=n.state.doc;const e=this.prettyToRawLocation(i.lineNumber,i.columnNumber),t=this.prettyToRawLocation(r.lineNumber,r.columnNumber);o=n.createSelection({lineNumber:e[0],columnNumber:e[1]},{lineNumber:t[0],columnNumber:t[1]})}t&&n.revealPosition(o,!1),this.prettyToggle.setEnabled(!0),this.updatePrettyPrintState()}getLineNumberFormatter(){if(!1===this.options.lineNumbers)return[];let e;if(this.wasmDisassemblyInternal){const t=this.wasmDisassemblyInternal,n=t.lineNumberToBytecodeOffset(t.lineNumbers-1).toString(16).length+1;e=e=>`0x${t.lineNumberToBytecodeOffset(Math.min(t.lineNumbers,e)-1).toString(16).padStart(n,"0")}`}else this.prettyInternal&&(e=(e,t)=>{if(e<2||e>t.doc.lines)return String(e);const[n]=this.prettyToRawLocation(e-1),[s]=this.prettyToRawLocation(e-2);return n!==s?String(n+1):"-"});return e?[l.lineNumbers({formatNumber:e}),y.of(e)]:[]}updateLineNumberFormatter(){this.textEditor.dispatch({effects:E.lineNumbers.reconfigure(this.getLineNumberFormatter())}),this.textEditor.shadowRoot?.querySelector(".cm-lineNumbers")?.setAttribute("jslog",`${d.gutter("line-numbers").track({click:!0})}`)}updatePrettyPrintState(){this.prettyToggle.setToggled(this.prettyInternal),this.textEditorInternal.classList.toggle("pretty-printed",this.prettyInternal),this.updateLineNumberFormatter()}prettyToRawLocation(e,t=0){return this.formattedMap?this.formattedMap.formattedToOriginal(e,t):[e,t]}rawToPrettyLocation(e,t){return this.formattedMap?this.formattedMap.originalToFormatted(e,t):[e,t]}hasLoadError(){return this.loadError}wasShown(){this.ensureContentLoaded(),this.wasShownOrLoaded()}willHide(){super.willHide(),this.clearPositionToReveal()}async toolbarItems(){return[this.prettyToggle,this.sourcePosition,this.progressToolbarItem]}get loaded(){return this.loadedInternal}get textEditor(){return this.textEditorInternal}get pretty(){return this.prettyInternal}get contentType(){return this.loadError?"":this.getContentType()}getContentType(){return""}async ensureContentLoaded(){this.contentRequested||(this.contentRequested=!0,await this.setDeferredContent(this.lazyContent()),this.contentSet=!0)}async setDeferredContent(n){const i=new s.ProgressIndicator.ProgressIndicator;i.setTitle(b(S.loading)),i.setTotalWork(100),this.progressToolbarItem.element.appendChild(i.element),i.setWorked(1);const r=await n;let o,a;if(null===r.content)o=r.error,a=r.error;else if(r.isEncoded){const e=new DataView(t.Base64.decode(r.content));a=(new TextDecoder).decode(e,{stream:!0})}else if("wasmDisassemblyInfo"in r&&r.wasmDisassemblyInfo){const{wasmDisassemblyInfo:e}=r;a=l.Text.of(e.lines),this.wasmDisassemblyInternal=e}else a=r.content,this.wasmDisassemblyInternal=null;i.setWorked(100),i.done(),this.rawContent!==a&&(this.rawContent=a,this.formattedMap=null,this.prettyToggle.setEnabled(!0),o?(this.loadError=!0,this.textEditor.state=this.placeholderEditorState(o),this.prettyToggle.setEnabled(!1)):this.shouldAutoPrettyPrint&&e.TextUtils.isMinified(r.content||"")?await this.setPretty(!0):await this.setContent(this.rawContent||""))}revealPosition(e,t){if(this.lineToScrollTo=null,this.selectionToSet=null,"number"==typeof e){let n=0,s=0;const{doc:i}=this.textEditor.state;if(e>i.length)n=i.lines-1;else if(e>=0){const t=i.lineAt(e);n=t.number-1,s=e-t.from}this.positionToReveal={to:{lineNumber:n,columnNumber:s},shouldHighlight:t}}else if("lineNumber"in e){const{lineNumber:n,columnNumber:s}=e;this.positionToReveal={to:{lineNumber:n,columnNumber:s??0},shouldHighlight:t}}else this.positionToReveal={...e,shouldHighlight:t};this.innerRevealPositionIfNeeded()}innerRevealPositionIfNeeded(){if(!this.positionToReveal)return;if(!this.loaded||!this.isShowing())return;const{from:e,to:t,shouldHighlight:n}=this.positionToReveal,s=this.uiLocationToEditorLocation(t.lineNumber,t.columnNumber),i=e?this.uiLocationToEditorLocation(e.lineNumber,e.columnNumber):void 0,{textEditor:r}=this;r.revealPosition(r.createSelection(s,i),n),this.positionToReveal=null}clearPositionToReveal(){this.positionToReveal=null}scrollToLine(e){this.clearPositionToReveal(),this.lineToScrollTo=e,this.innerScrollToLineIfNeeded()}innerScrollToLineIfNeeded(){if(null!==this.lineToScrollTo&&this.loaded&&this.isShowing()){const{textEditor:e}=this,t=e.toOffset({lineNumber:this.lineToScrollTo,columnNumber:0});e.dispatch({effects:l.EditorView.scrollIntoView(t,{y:"start",yMargin:0})}),this.lineToScrollTo=null}}setSelection(e){this.selectionToSet=e,this.innerSetSelectionIfNeeded()}innerSetSelectionIfNeeded(){const e=this.selectionToSet;if(e&&this.loaded&&this.isShowing()){const{textEditor:t}=this;t.dispatch({selection:t.createSelection({lineNumber:e.startLine,columnNumber:e.startColumn},{lineNumber:e.endLine,columnNumber:e.endColumn})}),this.selectionToSet=null}}wasShownOrLoaded(){this.innerRevealPositionIfNeeded(),this.innerSetSelectionIfNeeded(),this.innerScrollToLineIfNeeded(),this.textEditor.shadowRoot?.querySelector(".cm-lineNumbers")?.setAttribute("jslog",`${d.gutter("line-numbers").track({click:!0})}`),this.textEditor.shadowRoot?.querySelector(".cm-foldGutter")?.setAttribute("jslog",`${d.gutter("fold")}`),this.textEditor.setAttribute("jslog",`${d.textField().track({change:!0})}`)}onTextChanged(){const e=this.pretty;this.prettyInternal=Boolean(this.prettyBaseDoc&&this.textEditor.state.doc.eq(this.prettyBaseDoc)),this.prettyInternal!==e&&this.updatePrettyPrintState(),this.prettyToggle.setEnabled(this.isClean()),this.searchConfig&&this.searchableView&&this.performSearch(this.searchConfig,!1,!1)}isClean(){return this.textEditor.state.doc.eq(this.baseDoc)||null!==this.prettyBaseDoc&&this.textEditor.state.doc.eq(this.prettyBaseDoc)}contentCommitted(){this.baseDoc=this.textEditorInternal.state.doc,this.prettyBaseDoc=null,this.rawContent=this.textEditor.state.doc.toString(),this.formattedMap=null,this.prettyInternal&&(this.prettyInternal=!1,this.updatePrettyPrintState()),this.prettyToggle.setEnabled(!0)}async getLanguageSupport(e){let{contentType:t}=this;"text/x.vue"===t&&((e="string"==typeof e?e:e.sliceString(0)).trimStart().startsWith("<")||(t="text/javascript"));const n=await c.CodeHighlighter.languageFromMIME(t);return n?[n,l.javascript.javascriptLanguage.data.of({autocomplete:l.completeAnyWord})]:[]}async updateLanguageMode(e){const t=await this.getLanguageSupport(e);this.textEditor.dispatch({effects:E.language.reconfigure(t)})}async setContent(e){this.muteChangeEventsForSetContent=!0;const{textEditor:t}=this,n=this.loadedInternal,s=t.editor.scrollDOM.scrollTop;this.loadedInternal=!0;const i=await this.getLanguageSupport(e),r=l.EditorState.create({doc:e,extensions:[this.editorConfiguration(e),i,E.lineNumbers.of(this.getLineNumberFormatter()),E.editable.of(this.editable?[]:l.EditorState.readOnly.of(!0))]});this.baseDoc=r.doc,t.state=r,n&&(t.editor.scrollDOM.scrollTop=s),this.wasShownOrLoaded(),this.delayedFindSearchMatches&&(this.delayedFindSearchMatches(),this.delayedFindSearchMatches=null),this.muteChangeEventsForSetContent=!1}setSearchableView(e){this.searchableView=e}doFindSearchMatches(e,t,n){this.currentSearchResultIndex=-1,this.searchRegex=e.toSearchRegex(!0),this.searchResults=this.collectRegexMatches(this.searchRegex),this.searchableView&&this.searchableView.updateSearchMatchesCount(this.searchResults.length);const s=this.textEditor;this.searchResults.length?t&&n?this.jumpToPreviousSearchResult():t?this.jumpToNextSearchResult():s.dispatch({effects:P.of(new I(this.searchRegex,null))}):s.state.field(R)&&s.dispatch({effects:P.of(null)})}performSearch(e,t,n){this.searchableView&&this.searchableView.updateSearchMatchesCount(0),this.resetSearch(),this.searchConfig=e,this.loaded?this.doFindSearchMatches(e,t,Boolean(n)):this.delayedFindSearchMatches=this.doFindSearchMatches.bind(this,e,t,Boolean(n)),this.ensureContentLoaded()}resetCurrentSearchResultIndex(){if(!this.searchResults.length)return;this.currentSearchResultIndex=-1,this.searchableView&&this.searchableView.updateCurrentMatchIndex(this.currentSearchResultIndex);const e=this.textEditor,t=e.state.field(R);t&&t.currentRange&&e.dispatch({effects:P.of(new I(t.regexp,null))})}resetSearch(){this.searchConfig=null,this.delayedFindSearchMatches=null,this.currentSearchResultIndex=-1,this.searchResults=[],this.searchRegex=null}onSearchCanceled(){const e=-1!==this.currentSearchResultIndex?this.searchResults[this.currentSearchResultIndex]:null;if(this.resetSearch(),!this.loaded)return;this.textEditor.dispatch({effects:P.of(null),selection:e?{anchor:e.from,head:e.to}:void 0,scrollIntoView:!0,userEvent:"select.search.cancel"})}jumpToLastSearchResult(){this.jumpToSearchResult(this.searchResults.length-1)}searchResultIndexForCurrentSelection(){return r.ArrayUtilities.lowerBound(this.searchResults,this.textEditor.state.selection.main,((e,t)=>e.to-t.to))}jumpToNextSearchResult(){const e=this.searchResultIndexForCurrentSelection(),t=-1===this.currentSearchResultIndex?e:e+1;this.jumpToSearchResult(t)}jumpToPreviousSearchResult(){const e=this.searchResultIndexForCurrentSelection();this.jumpToSearchResult(e-1)}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}jumpToSearchResult(e){if(!this.loaded||!this.searchResults.length||!this.searchRegex)return;this.currentSearchResultIndex=(e+this.searchResults.length)%this.searchResults.length,this.searchableView&&this.searchableView.updateCurrentMatchIndex(this.currentSearchResultIndex);const t=this.textEditor,n=this.searchResults[this.currentSearchResultIndex];t.dispatch({effects:P.of(new I(this.searchRegex,n)),selection:{anchor:n.from,head:n.to},scrollIntoView:!0,userEvent:"select.search"})}replaceSelectionWith(e,t){const n=this.searchResults[this.currentSearchResultIndex];if(!n)return;const s=this.searchRegex?.fromQuery?n.insertPlaceholders(t):t,i=this.textEditor,r=i.state.changes({from:n.from,to:n.to,insert:s});i.dispatch({changes:r,selection:{anchor:r.mapPos(i.state.selection.main.to,1)},userEvent:"input.replace"})}replaceAllWith(e,t){this.resetCurrentSearchResultIndex();const n=e.toSearchRegex(!0),s=this.collectRegexMatches(n);if(!s.length)return;const i=n.fromQuery,r=s.map((e=>({from:e.from,to:e.to,insert:i?e.insertPlaceholders(t):t})));this.textEditor.dispatch({changes:r,scrollIntoView:!0,userEvent:"input.replace.all"})}collectRegexMatches({regex:e}){const t=[];let n=0;for(const s of this.textEditor.state.doc.iterLines()){for(e.lastIndex=0;;){const i=e.exec(s);if(!i)break;if(i[0].length){const e=n+i.index;t.push(new C(e,e+i[0].length,i))}else e.lastIndex=i.index+1}n+=s.length+1}return t}canEditSource(){return this.editable}updateSourcePosition(){const{textEditor:e}=this,{state:t}=e,{selection:n}=t;if(this.displayedSelection?.eq(n))return;if(this.displayedSelection=n,n.ranges.length>1)return void this.sourcePosition.setText(b(S.dSelectionRegions,{PH1:n.ranges.length}));const{main:s}=t.selection;if(s.empty){const{lineNumber:t,columnNumber:n}=e.toLineColumn(s.head),i=this.prettyToRawLocation(t,n);if(this.wasmDisassemblyInternal){const e=this.wasmDisassemblyInternal,t=e.lineNumberToBytecodeOffset(e.lineNumbers-1).toString(16).length,n=e.lineNumberToBytecodeOffset(i[0]);this.sourcePosition.setText(b(S.bytecodePositionXs,{PH1:n.toString(16).padStart(t,"0")}))}else this.sourcePosition.setText(b(S.lineSColumnS,{PH1:i[0]+1,PH2:i[1]+1}))}else{const e=t.doc.lineAt(s.from),n=t.doc.lineAt(s.to);e.number===n.number?this.sourcePosition.setText(b(S.dCharactersSelected,{PH1:s.to-s.from})):this.sourcePosition.setText(b(S.dLinesDCharactersSelected,{PH1:n.number-e.number+1,PH2:s.to-s.from}))}}onContextMenu(e){e.consume(!0);const t=new s.ContextMenu.ContextMenu(e),{state:n}=this.textEditor,i=n.selection.main.from,r=n.doc.lineAt(i);return this.populateTextAreaContextMenu(t,r.number-1,i-r.from),t.appendApplicableItems(this),t.show(),!0}populateTextAreaContextMenu(e,t,n){}onLineGutterContextMenu(e,t){t.consume(!0);const n=new s.ContextMenu.ContextMenu(t),i=this.textEditor.state.doc.lineAt(e).number-1;return this.populateLineGutterContextMenu(n,i),n.appendApplicableItems(this),n.show(),!0}populateLineGutterContextMenu(e,t){}focus(){this.textEditor.focus()}}class C{from;to;match;constructor(e,t,n){this.from=e,this.to=t,this.match=n}insertPlaceholders(e){return e.replace(/\$(\$|&|\d+|<[^>]+>)/g,((e,t)=>"$"===t?"$":"&"===t?this.match[0]:"<"===t[0]?this.match.groups&&this.match.groups[t.slice(1,t.length-1)]||"":this.match[Number.parseInt(t,10)]||""))}}class v{static async show(){const e=new s.Dialog.Dialog("self-xss-warning");e.setMaxContentSize(new s.Geometry.Size(504,340)),e.setSizeBehavior("SetExactWidthMaxHeight"),e.setDimmed(!0);const t=s.UIUtils.createShadowRootWithCoreStyles(e.contentElement,{cssFile:w,delegatesFocus:void 0}).createChild("div","widget"),n=await new Promise((n=>{const r=t.createChild("div","dialog-close-button","dt-close-button");r.setTabbable(!0),self.onInvokeElement(r,(t=>{e.hide(),t.consume(!0),n(!1)})),t.createChild("div","title").textContent=b(S.doYouTrustThisCode),t.createChild("div","message").textContent=b(S.doNotPaste,{PH1:b(S.allowPasting)});const o=s.UIUtils.createInput("text-input","text","allow-pasting");o.placeholder=b(S.typeAllowPasting,{PH1:b(S.allowPasting)}),t.appendChild(o);const a=t.createChild("div","button"),l=s.UIUtils.createTextButton(b(S.cancel),(()=>n(!1)),{jslogContext:"cancel"});a.appendChild(l);const c=s.UIUtils.createTextButton(b(S.allow),(()=>{n(o.value===b(S.allowPasting))}),{jslogContext:"confirm",variant:"primary"});c.disabled=!0,a.appendChild(c),o.addEventListener("input",(()=>{c.disabled=!Boolean(o.value)}),!1),o.addEventListener("paste",(e=>e.preventDefault())),o.addEventListener("drop",(e=>e.preventDefault())),e.setOutsideClickCallback((e=>{e.consume(),n(!1)})),e.show(),i.userMetrics.actionTaken(i.UserMetrics.Action.SelfXssWarningDialogShown)}));return e.hide(),n}}const E={editable:new l.Compartment,language:new l.Compartment,lineNumbers:new l.Compartment};class I{regexp;currentRange;constructor(e,t){this.regexp=e,this.currentRange=t}map(e){return e.empty||!this.currentRange?this:new I(this.regexp,{from:e.mapPos(this.currentRange.from),to:e.mapPos(this.currentRange.to)})}static eq(e,t){return Boolean(e===t||e&&t&&e.currentRange?.from===t.currentRange?.from&&e.currentRange?.to===t.currentRange?.to&&e.regexp.regex.source===t.regexp.regex.source&&e.regexp.regex.flags===t.regexp.regex.flags)}}const P=l.StateEffect.define({map:(e,t)=>e&&e.map(t)}),R=l.StateField.define({create:()=>null,update:(e,t)=>t.effects.reduce(((e,t)=>t.is(P)?t.value:e),e&&e.map(t.changes))}),L=l.Decoration.mark({class:"cm-searchMatch"}),N=l.Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"}),V=l.ViewPlugin.fromClass(class{decorations;constructor(e){this.decorations=this.computeDecorations(e)}update(e){const t=e.state.field(R);(!I.eq(t,e.startState.field(R))||t&&(e.viewportChanged||e.docChanged))&&(this.decorations=this.computeDecorations(e.view))}computeDecorations(e){const t=e.state.field(R);if(!t)return l.Decoration.none;const n=new l.RangeSetBuilder,{doc:s}=e.state;for(const{from:i,to:r}of e.visibleRanges){let e=i;for(const o of s.iterRange(i,r)){if("\n"!==o)for(t.regexp.regex.lastIndex=0;;){const s=t.regexp.regex.exec(o);if(!s)break;if(s[0].length){const i=e+s.index,r=i+s[0].length,o=t.currentRange&&t.currentRange.from===i&&t.currentRange.to===r;n.add(i,r,o?N:L)}else t.regexp.regex.lastIndex=s.index+1}e+=o.length}}return n.finish()}},{decorations:e=>e.decorations}),F=new class extends l.GutterMarker{elementClass="cm-nonBreakableLine"},D=l.StateEffect.define(),M=l.StateField.define({create:()=>l.RangeSet.empty,update:(e,t)=>t.effects.reduce(((e,t)=>t.is(D)?e.update({add:t.value.map((e=>F.range(e)))}):e),e.map(t.changes)),provide:e=>l.lineNumberMarkers.from(e)});const U=l.EditorView.theme({"&.cm-editor":{height:"100%"},".cm-scroller":{overflow:"auto"},".cm-lineNumbers .cm-gutterElement.cm-nonBreakableLine":{color:"var(--sys-color-state-disabled) !important"},".cm-searchMatch":{border:"1px solid var(--sys-color-outline)",borderRadius:"3px",margin:"0 -1px","&.cm-searchMatch-selected":{borderRadius:"1px",backgroundColor:"var(--sys-color-yellow-container)",borderColor:"var(--sys-color-yellow-outline)","&, & *":{color:"var(--sys-color-on-surface) !important"}}},":host-context(.pretty-printed) & .cm-lineNumbers .cm-gutterElement":{color:"var(--sys-color-primary)"}});var j=Object.freeze({__proto__:null,LINE_NUMBER_FORMATTER:y,SourceFrameImpl:T,SelfXssWarningDialog:v,addNonBreakableLines:D,isBreakableLine:function(e,t){const n=e.field(M);if(!n.size)return!0;let s=!1;return n.between(t.from,t.from,(()=>{s=!0})),!s}});const O={find:"Find"},A=n.i18n.registerUIStrings("ui/legacy/components/source_frame/ResourceSourceFrame.ts",O),H=n.i18n.getLocalizedString.bind(void 0,A);class k extends T{resourceInternal;#t;constructor(t,n,s){const i=e.ContentProvider.isStreamingContentProvider(t);super(i?()=>t.requestStreamingContent().then(e.StreamingContentData.asDeferredContent.bind(null)):()=>t.requestContent(),s),this.#t=n,this.resourceInternal=t,i&&t.requestStreamingContent().then((t=>{e.StreamingContentData.isError(t)||t.addEventListener("ChunkAdded",(()=>{this.setDeferredContent(Promise.resolve(t.content().asDeferedContent()))}))}))}static createSearchableView(e,t){return new _(e,t)}getContentType(){return this.#t}get resource(){return this.resourceInternal}populateTextAreaContextMenu(e,t,n){super.populateTextAreaContextMenu(e,t,n),e.appendApplicableItems(this.resourceInternal)}}class _ extends s.Widget.VBox{sourceFrame;constructor(e,n){super(!0),this.registerRequiredCSS(f);const i=t.ResourceType.ResourceType.simplifyContentType(n),r=new k(e,i);this.sourceFrame=r;const o=g.includes(i);r.setCanPrettyPrint(o,!0);const a=new s.SearchableView.SearchableView(r,r);a.element.classList.add("searchable-view"),a.setPlaceholder(H(O.find)),r.show(a.element),r.setSearchableView(a),a.show(this.contentElement);const l=new s.Toolbar.Toolbar("toolbar",this.contentElement);r.toolbarItems().then((e=>{e.map((e=>l.appendToolbarItem(e)))}))}async revealPosition(e){this.sourceFrame.revealPosition(e,!0)}}var z=Object.freeze({__proto__:null,ResourceSourceFrame:k,SearchableContainer:_});class B{base64content;contentUrl;resourceType;arrayPromise;hexPromise;utf8Promise;constructor(e,t,n){this.base64content=e,this.contentUrl=t,this.resourceType=n,this.arrayPromise=null,this.hexPromise=null,this.utf8Promise=null}async fetchContentAsArray(){return this.arrayPromise||(this.arrayPromise=new Promise((async e=>{const t=await fetch("data:;base64,"+this.base64content);e(new Uint8Array(await t.arrayBuffer()))}))),await this.arrayPromise}async hex(){return this.hexPromise||(this.hexPromise=new Promise((async e=>{const t=await this.fetchContentAsArray();e(B.uint8ArrayToHexString(t))}))),this.hexPromise}base64(){return this.base64content}async utf8(){return this.utf8Promise||(this.utf8Promise=new Promise((async e=>{const t=await this.fetchContentAsArray();e(new TextDecoder("utf8").decode(t))}))),this.utf8Promise}createBase64View(){return new k(e.StaticContentProvider.StaticContentProvider.fromString(this.contentUrl,this.resourceType,this.base64content),this.resourceType.canonicalMimeType(),{lineNumbers:!1,lineWrapping:!0})}createHexView(){const t=new e.StaticContentProvider.StaticContentProvider(this.contentUrl,this.resourceType,(async()=>{const t=await this.fetchContentAsArray(),n=B.uint8ArrayToHexViewer(t);return new e.ContentData.ContentData(n,!1,"text/plain")}));return new k(t,this.resourceType.canonicalMimeType(),{lineNumbers:!1,lineWrapping:!1})}createUtf8View(){const t=new e.StaticContentProvider.StaticContentProvider(this.contentUrl,this.resourceType,(()=>this.utf8().then((t=>new e.ContentData.ContentData(t,!1,"text/plain")))));return new k(t,this.resourceType.canonicalMimeType(),{lineNumbers:!0,lineWrapping:!0})}static uint8ArrayToHexString(e){let t="";for(let n=0;n<e.length;n++)t+=B.numberToHex(e[n],2);return t}static numberToHex(e,t){let n=e.toString(16);for(;n.length<t;)n="0"+n;return n}static uint8ArrayToHexViewer(e){let t="",n=0;for(;16*n<e.length;){const s=e.slice(16*n,16*(n+1));t+=B.numberToHex(n,8)+":";let i=0;for(let e=0;e<s.length;e++)e%2==0&&(t+=" ",i++),t+=B.numberToHex(s[e],2),i+=2;for(;i<42;)t+=" ",i++;for(let e=0;e<s.length;e++){const n=s[e];t+=n>=32&&n<=126?String.fromCharCode(n):"."}t+="\n",n++}return t}}var W=Object.freeze({__proto__:null,BinaryResourceViewFactory:B}),q={cssContent:".font-view{font-size:60px;white-space:pre-wrap;word-wrap:break-word;text-align:center;padding:15px}\n/*# sourceURL=fontView.css */\n"};const X={font:"Font",previewOfFontFromS:"Preview of font from {PH1}"},J=n.i18n.registerUIStrings("ui/legacy/components/source_frame/FontView.ts",X),$=n.i18n.getLocalizedString.bind(void 0,J);class G extends s.View.SimpleView{url;mimeType;contentProvider;mimeTypeLabel;fontPreviewElement;dummyElement;fontStyleElement;inResize;constructor(e,t){super($(X.font)),this.registerRequiredCSS(q),this.element.classList.add("font-view"),this.element.setAttribute("jslog",`${d.pane("font-view")}`),this.url=t.contentURL(),s.ARIAUtils.setLabel(this.element,$(X.previewOfFontFromS,{PH1:this.url})),this.mimeType=e,this.contentProvider=t,this.mimeTypeLabel=new s.Toolbar.ToolbarText(e)}async toolbarItems(){return[this.mimeTypeLabel]}onFontContentLoaded(t,n){const{content:s}=n,i=s?e.ContentProvider.contentAsDataURL(s,this.mimeType,!0):this.url;this.fontStyleElement&&(this.fontStyleElement.textContent=r.StringUtilities.sprintf('@font-face { font-family: "%s"; src: url(%s); }',t,i),this.updateFontPreviewSize())}createContentIfNeeded(){if(this.fontPreviewElement)return;const e="WebInspectorFontPreview"+ ++Q;this.fontStyleElement=document.createElement("style"),this.contentProvider.requestContent().then((t=>{this.onFontContentLoaded(e,t)})),this.element.appendChild(this.fontStyleElement);const t=document.createElement("div");for(let e=0;e<Y.length;++e)e>0&&t.createChild("br"),s.UIUtils.createTextChild(t,Y[e]);this.fontPreviewElement=t.cloneNode(!0),this.fontPreviewElement&&(s.ARIAUtils.markAsHidden(this.fontPreviewElement),this.fontPreviewElement.style.overflow="hidden",this.fontPreviewElement.style.setProperty("font-family",e),this.fontPreviewElement.style.setProperty("visibility","hidden"),this.dummyElement=t,this.dummyElement.style.visibility="hidden",this.dummyElement.style.zIndex="-1",this.dummyElement.style.display="inline",this.dummyElement.style.position="absolute",this.dummyElement.style.setProperty("font-family",e),this.dummyElement.style.setProperty("font-size",K+"px"),this.element.appendChild(this.fontPreviewElement))}wasShown(){this.createContentIfNeeded(),this.updateFontPreviewSize()}onResize(){if(!this.inResize){this.inResize=!0;try{this.updateFontPreviewSize()}finally{this.inResize=null}}}measureElement(){if(!this.dummyElement)throw new Error("No font preview loaded");this.element.appendChild(this.dummyElement);const e={width:this.dummyElement.offsetWidth,height:this.dummyElement.offsetHeight};return this.element.removeChild(this.dummyElement),e}updateFontPreviewSize(){if(!this.fontPreviewElement||!this.isShowing())return;this.fontPreviewElement.style.removeProperty("visibility");const e=this.measureElement(),t=e.height,n=e.width,s=this.element.offsetWidth-50,i=this.element.offsetHeight-30;if(!(t&&n&&s&&i))return void this.fontPreviewElement.style.removeProperty("font-size");const r=s/n,o=i/t,a=Math.floor(K*Math.min(r,o))-2;this.fontPreviewElement.style.setProperty("font-size",a+"px",void 0)}}let Q=0;const Y=["ABCDEFGHIJKLM","NOPQRSTUVWXYZ","abcdefghijklm","nopqrstuvwxyz","1234567890"],K=50;var Z=Object.freeze({__proto__:null,FontView:G}),ee={cssContent:".image-view{overflow:auto}.image-view > .image{padding:20px 20px 10px;text-align:center}.image-view img.resource-image-view{max-width:100%;max-height:1000px;background-image:var(--image-file-checker);box-shadow:0 5px 10px var(--sys-color-outline);user-select:text;-webkit-user-drag:auto}\n/*# sourceURL=imageView.css */\n"};const te={image:"Image",dropImageFileHere:"Drop image file here",imageFromS:"Image from {PH1}",dD:"{PH1} × {PH2}",copyImageUrl:"Copy image URL",copyImageAsDataUri:"Copy image as data URI",openImageInNewTab:"Open image in new tab",saveImageAs:"Save image as...",download:"download"},ne=n.i18n.registerUIStrings("ui/legacy/components/source_frame/ImageView.ts",te),se=n.i18n.getLocalizedString.bind(void 0,ne);class ie extends s.View.SimpleView{url;parsedURL;mimeType;contentProvider;uiSourceCode;sizeLabel;dimensionsLabel;aspectRatioLabel;mimeTypeLabel;container;imagePreviewElement;cachedContent;constructor(e,n){super(se(te.image)),this.registerRequiredCSS(ee),this.element.tabIndex=-1,this.element.classList.add("image-view"),this.element.setAttribute("jslog",`${d.pane("image-view")}`),this.url=n.contentURL(),this.parsedURL=new t.ParsedURL.ParsedURL(this.url),this.mimeType=e,this.contentProvider=n,this.uiSourceCode=n instanceof u.UISourceCode.UISourceCode?n:null,this.uiSourceCode&&(this.uiSourceCode.addEventListener(u.UISourceCode.Events.WorkingCopyCommitted,this.workingCopyCommitted,this),new s.DropTarget.DropTarget(this.element,[s.DropTarget.Type.ImageFile,s.DropTarget.Type.URI],se(te.dropImageFileHere),this.handleDrop.bind(this))),this.sizeLabel=new s.Toolbar.ToolbarText,this.dimensionsLabel=new s.Toolbar.ToolbarText,this.aspectRatioLabel=new s.Toolbar.ToolbarText,this.mimeTypeLabel=new s.Toolbar.ToolbarText(e),this.container=this.element.createChild("div","image"),this.imagePreviewElement=this.container.createChild("img","resource-image-view"),this.imagePreviewElement.addEventListener("contextmenu",this.contextMenu.bind(this),!0)}async toolbarItems(){return await this.updateContentIfNeeded(),[this.sizeLabel,new s.Toolbar.ToolbarSeparator,this.dimensionsLabel,new s.Toolbar.ToolbarSeparator,this.aspectRatioLabel,new s.Toolbar.ToolbarSeparator,this.mimeTypeLabel]}wasShown(){this.updateContentIfNeeded()}disposeView(){this.uiSourceCode&&this.uiSourceCode.removeEventListener(u.UISourceCode.Events.WorkingCopyCommitted,this.workingCopyCommitted,this)}workingCopyCommitted(){this.updateContentIfNeeded()}async updateContentIfNeeded(){const t=await this.contentProvider.requestContent();if(this.cachedContent?.content===t.content)return;this.cachedContent=t;const n=e.ContentProvider.contentAsDataURL(t.content,this.mimeType,t.isEncoded)||this.url,s=new Promise((e=>{this.imagePreviewElement.onload=e}));this.imagePreviewElement.src=n,this.imagePreviewElement.alt=se(te.imageFromS,{PH1:this.url});const i=t.content&&!t.isEncoded?t.content.length:r.StringUtilities.base64ToSize(t.content);this.sizeLabel.setText(r.NumberUtilities.bytesToString(i)),await s,this.dimensionsLabel.setText(se(te.dD,{PH1:this.imagePreviewElement.naturalWidth,PH2:this.imagePreviewElement.naturalHeight})),this.aspectRatioLabel.setText(r.NumberUtilities.aspectRatio(this.imagePreviewElement.naturalWidth,this.imagePreviewElement.naturalHeight))}contextMenu(e){const n=new s.ContextMenu.ContextMenu(e),i=new t.ParsedURL.ParsedURL(this.imagePreviewElement.src);this.parsedURL.isDataURL()||n.clipboardSection().appendItem(se(te.copyImageUrl),this.copyImageURL.bind(this),{jslogContext:"image-view.copy-image-url"}),i.isDataURL()&&n.clipboardSection().appendItem(se(te.copyImageAsDataUri),this.copyImageAsDataURL.bind(this),{jslogContext:"image-view.copy-image-as-data-url"}),n.clipboardSection().appendItem(se(te.openImageInNewTab),this.openInNewTab.bind(this),{jslogContext:"image-view.open-in-new-tab"}),n.clipboardSection().appendItem(se(te.saveImageAs),this.saveImage.bind(this),{jslogContext:"image-view.save-image"}),n.show()}copyImageAsDataURL(){i.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this.imagePreviewElement.src)}copyImageURL(){i.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this.url)}async saveImage(){if(!this.cachedContent||!this.cachedContent.content)return;const t=e.ContentProvider.contentAsDataURL(this.cachedContent.content,this.mimeType,this.cachedContent.isEncoded,"",!1);if(!t)return;const n=document.createElement("a");n.href=t,n.download=this.parsedURL.isDataURL()?se(te.download):decodeURIComponent(this.parsedURL.displayName),n.click(),n.remove()}openInNewTab(){i.InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab(this.url)}async handleDrop(e){const t=e.items;if(!t.length||"file"!==t[0].kind)return;const n=t[0].getAsFile();if(!n)return;const s=!n.name.endsWith(".svg");(e=>{const t=new FileReader;t.onloadend=()=>{let e;try{e=t.result}catch(t){e=null,console.error("Can't read file: "+t)}"string"==typeof e&&this.uiSourceCode&&this.uiSourceCode.setContent(s?btoa(e):e,s)},s?t.readAsBinaryString(e):t.readAsText(e)})(n)}}var re=Object.freeze({__proto__:null,ImageView:ie}),oe={cssContent:".json-view{padding:2px 6px;overflow:auto}\n/*# sourceURL=jsonView.css */\n"};const ae={find:"Find"},le=n.i18n.registerUIStrings("ui/legacy/components/source_frame/JSONView.ts",ae),ce=n.i18n.getLocalizedString.bind(void 0,le);class he extends s.Widget.VBox{initialized;parsedJSON;startCollapsed;searchableView;treeOutline;currentSearchFocusIndex;currentSearchTreeElements;searchRegex;constructor(e,t){super(),this.initialized=!1,this.registerRequiredCSS(oe),this.parsedJSON=e,this.startCollapsed=Boolean(t),this.element.classList.add("json-view"),this.element.setAttribute("jslog",`${d.section("json-view")}`),this.currentSearchFocusIndex=0,this.currentSearchTreeElements=[],this.searchRegex=null}static async createView(e){const t=await he.parseJSON(e);if(!t||"object"!=typeof t.data)return null;const n=new he(t),i=new s.SearchableView.SearchableView(n,null);return i.setPlaceholder(ce(ae.find)),n.searchableView=i,n.show(i.element),i}static createViewSync(e){const t=new he(new de(e,"","")),n=new s.SearchableView.SearchableView(t,null);return n.setPlaceholder(ce(ae.find)),t.searchableView=n,t.show(n.element),t.element.tabIndex=0,n}static parseJSON(e){let t=null;if(e&&(t=he.extractJSON(e)),!t)return Promise.resolve(null);try{const e=JSON.parse(t.data);if(!e)return Promise.resolve(null);t.data=e}catch(e){t=null}return Promise.resolve(t)}static extractJSON(e){if(e.startsWith("<"))return null;let t=he.findBrackets(e,"{","}");const n=he.findBrackets(e,"[","]");if(t=n.length>t.length?n:t,-1===t.length||e.length-t.length>80)return null;const s=e.substring(0,t.start),i=e.substring(t.end+1);return e=e.substring(t.start,t.end+1),!i.trim().length||i.trim().startsWith(")")&&s.trim().endsWith("(")?new de(e,s,i):null}static findBrackets(e,t,n){const s=e.indexOf(t),i=e.lastIndexOf(n);let r=i-s-1;return(-1===s||-1===i||i<s)&&(r=-1),{start:s,end:i,length:r}}wasShown(){this.initialize()}initialize(){if(this.initialized)return;this.initialized=!0;const e=m.RemoteObject.RemoteObject.fromLocalObject(this.parsedJSON.data),t=this.parsedJSON.prefix+e.description+this.parsedJSON.suffix;this.treeOutline=new p.ObjectPropertiesSection.ObjectPropertiesSection(e,t,void 0,!0),this.treeOutline.enableContextMenu(),this.treeOutline.setEditable(!1),this.startCollapsed||this.treeOutline.expand(),this.element.appendChild(this.treeOutline.element);const n=this.treeOutline.firstChild();n&&n.select(!0,!1)}jumpToMatch(e){if(!this.searchRegex)return;const t=this.currentSearchTreeElements[this.currentSearchFocusIndex];t&&t.setSearchRegex(this.searchRegex);const n=this.currentSearchTreeElements[e];n?(this.updateSearchIndex(e),n.setSearchRegex(this.searchRegex,s.UIUtils.highlightedCurrentSearchResultClassName),n.reveal()):this.updateSearchIndex(0)}updateSearchCount(e){this.searchableView&&this.searchableView.updateSearchMatchesCount(e)}updateSearchIndex(e){this.currentSearchFocusIndex=e,this.searchableView&&this.searchableView.updateCurrentMatchIndex(e)}onSearchCanceled(){let e;for(this.searchRegex=null,this.currentSearchTreeElements=[],e=this.treeOutline.rootElement();e;e=e.traverseNextTreeElement(!1))e instanceof p.ObjectPropertiesSection.ObjectPropertyTreeElement&&e.revertHighlightChanges();this.updateSearchCount(0),this.updateSearchIndex(0)}performSearch(e,t,n){let s=this.currentSearchFocusIndex;const i=this.currentSearchTreeElements[s];let o;for(this.onSearchCanceled(),this.searchRegex=e.toSearchRegex(!0).regex,o=this.treeOutline.rootElement();o;o=o.traverseNextTreeElement(!1)){if(!(o instanceof p.ObjectPropertiesSection.ObjectPropertyTreeElement))continue;const e=o.setSearchRegex(this.searchRegex);if(e&&this.currentSearchTreeElements.push(o),i===o){const t=this.currentSearchTreeElements.length-1;s=e||n?t:t+1}}this.updateSearchCount(this.currentSearchTreeElements.length),this.currentSearchTreeElements.length?(s=r.NumberUtilities.mod(s,this.currentSearchTreeElements.length),this.jumpToMatch(s)):this.updateSearchIndex(-1)}jumpToNextSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=r.NumberUtilities.mod(this.currentSearchFocusIndex+1,this.currentSearchTreeElements.length);this.jumpToMatch(e)}jumpToPreviousSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=r.NumberUtilities.mod(this.currentSearchFocusIndex-1,this.currentSearchTreeElements.length);this.jumpToMatch(e)}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}}class de{data;prefix;suffix;constructor(e,t,n){this.data=e,this.prefix=t,this.suffix=n}}var ue=Object.freeze({__proto__:null,JSONView:he,ParsedJSON:de}),me={cssContent:".tree-outline ol{list-style:none;padding:0;margin:0;padding-inline-start:16px}ol.tree-outline{padding-inline-start:0}.tree-outline li{min-height:12px}.tree-outline li.shadow-xml-view-close-tag{margin-left:-16px}.shadow-xml-view-tag{color:var(--sys-color-purple)}.shadow-xml-view-comment{color:var(--sys-color-green)}.shadow-xml-view-processing-instruction{color:var(--sys-color-green)}.shadow-xml-view-attribute-name{color:var(--sys-color-orange)}.shadow-xml-view-attribute-value{color:var(--sys-color-blue)}.shadow-xml-view-text{color:var(--sys-color-on-surface);white-space:pre}.shadow-xml-view-cdata{color:var(--sys-color-on-surface)}\n/*# sourceURL=xmlTree.css */\n"},pe={cssContent:".shadow-xml-view{user-select:text;overflow:auto;padding:2px 4px}\n/*# sourceURL=xmlView.css */\n"};const ge={find:"Find"},fe=n.i18n.registerUIStrings("ui/legacy/components/source_frame/XMLView.ts",ge),we=n.i18n.getLocalizedString.bind(void 0,fe);class Se extends s.Widget.Widget{treeOutline;searchableView;currentSearchFocusIndex;currentSearchTreeElements;searchConfig;constructor(e){super(!0),this.registerRequiredCSS(pe),this.contentElement.classList.add("shadow-xml-view","source-code"),this.treeOutline=new s.TreeOutline.TreeOutlineInShadow,this.treeOutline.registerRequiredCSS(me),this.contentElement.appendChild(this.treeOutline.element),this.currentSearchFocusIndex=0,this.currentSearchTreeElements=[],xe.populate(this.treeOutline,e,this);const t=this.treeOutline.firstChild();t&&t.select(!0,!1)}static createSearchableView(e){const t=new Se(e),n=new s.SearchableView.SearchableView(t,null);return n.setPlaceholder(we(ge.find)),t.searchableView=n,t.show(n.element),n}static parseXML(e,t){let n;try{switch(t){case"application/xhtml+xml":case"application/xml":case"image/svg+xml":case"text/html":case"text/xml":n=(new DOMParser).parseFromString(e,t)}}catch(e){return null}return!n||n.body?null:n}jumpToMatch(e,t){if(!this.searchConfig)return;const{regex:n}=this.searchConfig.toSearchRegex(!0),i=this.currentSearchTreeElements[this.currentSearchFocusIndex];i&&i.setSearchRegex(n);const r=this.currentSearchTreeElements[e];r?(this.updateSearchIndex(e),t&&r.reveal(!0),r.setSearchRegex(n,s.UIUtils.highlightedCurrentSearchResultClassName)):this.updateSearchIndex(0)}updateSearchCount(e){this.searchableView&&this.searchableView.updateSearchMatchesCount(e)}updateSearchIndex(e){this.currentSearchFocusIndex=e,this.searchableView&&this.searchableView.updateCurrentMatchIndex(e)}innerPerformSearch(e,t){if(!this.searchConfig)return;let n=this.currentSearchFocusIndex;const s=this.currentSearchTreeElements[n];this.innerSearchCanceled(),this.currentSearchTreeElements=[];const{regex:i}=this.searchConfig.toSearchRegex(!0);for(let e=this.treeOutline.rootElement();e;e=e.traverseNextTreeElement(!1)){if(!(e instanceof xe))continue;const r=e.setSearchRegex(i);if(r&&this.currentSearchTreeElements.push(e),s===e){const e=this.currentSearchTreeElements.length-1;n=r||t?e:e+1}}this.updateSearchCount(this.currentSearchTreeElements.length),this.currentSearchTreeElements.length?(n=r.NumberUtilities.mod(n,this.currentSearchTreeElements.length),this.jumpToMatch(n,e)):this.updateSearchIndex(0)}innerSearchCanceled(){for(let e=this.treeOutline.rootElement();e;e=e.traverseNextTreeElement(!1))e instanceof xe&&e.revertHighlightChanges();this.updateSearchCount(0),this.updateSearchIndex(0)}onSearchCanceled(){this.searchConfig=null,this.currentSearchTreeElements=[],this.innerSearchCanceled()}performSearch(e,t,n){this.searchConfig=e,this.innerPerformSearch(t,n)}jumpToNextSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=r.NumberUtilities.mod(this.currentSearchFocusIndex+1,this.currentSearchTreeElements.length);this.jumpToMatch(e,!0)}jumpToPreviousSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=r.NumberUtilities.mod(this.currentSearchFocusIndex-1,this.currentSearchTreeElements.length);this.jumpToMatch(e,!0)}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}}class xe extends s.TreeOutline.TreeElement{node;closeTag;highlightChanges;xmlView;constructor(e,t,n){super("",!t&&"childElementCount"in e&&Boolean(e.childElementCount)),this.node=e,this.closeTag=t,this.selectable=!0,this.highlightChanges=[],this.xmlView=n,this.updateTitle()}static populate(e,t,n){if(!(t instanceof Node))return;let s=t.firstChild;for(;s;){const t=s;s=s.nextSibling;const i=t.nodeType;3===i&&t.nodeValue&&t.nodeValue.match(/\s+/)||(1!==i&&3!==i&&4!==i&&7!==i&&8!==i||e.appendChild(new xe(t,!1,n)))}}setSearchRegex(t,n){if(this.revertHighlightChanges(),!t)return!1;if(this.closeTag&&this.parent&&!this.parent.expanded)return!1;t.lastIndex=0;let i=s.UIUtils.highlightedSearchResultClassName;if(n&&(i+=" "+n),!this.listItemElement.textContent)return!1;const r=this.listItemElement.textContent.replace(/\xA0/g," ");let o=t.exec(r);const a=[];for(;o;)a.push(new e.TextRange.SourceRange(o.index,o[0].length)),o=t.exec(r);return a.length&&s.UIUtils.highlightRangesWithStyleClass(this.listItemElement,a,i,this.highlightChanges),Boolean(this.highlightChanges.length)}revertHighlightChanges(){s.UIUtils.revertDomChanges(this.highlightChanges),this.highlightChanges=[]}updateTitle(){const e=this.node;if("nodeType"in e)switch(e.nodeType){case 1:if(e instanceof Element){const t=e.tagName;if(this.closeTag)return void this.setTitle(["</"+t+">","shadow-xml-view-tag"]);const n=["<"+t,"shadow-xml-view-tag"],s=e.attributes;for(let e=0;e<s.length;++e){const t=s.item(e);if(!t)return;n.push(" ","shadow-xml-view-tag",t.name,"shadow-xml-view-attribute-name",'="',"shadow-xml-view-tag",t.value,"shadow-xml-view-attribute-value",'"',"shadow-xml-view-tag")}return this.expanded||(e.childElementCount?n.push(">","shadow-xml-view-tag","…","shadow-xml-view-comment","</"+t,"shadow-xml-view-tag"):e.textContent?n.push(">","shadow-xml-view-tag",e.textContent,"shadow-xml-view-text","</"+t,"shadow-xml-view-tag"):n.push(" /","shadow-xml-view-tag")),n.push(">","shadow-xml-view-tag"),void this.setTitle(n)}return;case 3:return void(e.nodeValue&&this.setTitle([e.nodeValue,"shadow-xml-view-text"]));case 4:return void(e.nodeValue&&this.setTitle(["<![CDATA[","shadow-xml-view-cdata",e.nodeValue,"shadow-xml-view-text","]]>","shadow-xml-view-cdata"]));case 7:return void(e.nodeValue&&this.setTitle(["<?"+e.nodeName+" "+e.nodeValue+"?>","shadow-xml-view-processing-instruction"]));case 8:return void this.setTitle(["\x3c!--"+e.nodeValue+"--\x3e","shadow-xml-view-comment"])}}setTitle(e){const t=document.createDocumentFragment();for(let n=0;n<e.length;n+=2)t.createChild("span",e[n+1]).textContent=e[n];this.title=t,this.xmlView.innerPerformSearch(!1,!1)}onattach(){this.listItemElement.classList.toggle("shadow-xml-view-close-tag",this.closeTag)}onexpand(){this.updateTitle()}oncollapse(){this.updateTitle()}async onpopulate(){xe.populate(this,this.node,this.xmlView),this.appendChild(new xe(this.node,!0,this.xmlView))}}var be=Object.freeze({__proto__:null,XMLView:Se,XMLViewNode:xe});const ye={nothingToPreview:"Nothing to preview"},Te=n.i18n.registerUIStrings("ui/legacy/components/source_frame/PreviewFactory.ts",ye),Ce=n.i18n.getLocalizedString.bind(void 0,Te);var ve=Object.freeze({__proto__:null,PreviewFactory:class{static async createPreview(e,n){let i=t.ResourceType.ResourceType.fromMimeType(n);switch(i===t.ResourceType.resourceTypes.Other&&(i=e.contentType()),i){case t.ResourceType.resourceTypes.Image:return new ie(n,e);case t.ResourceType.resourceTypes.Font:return new G(n,e)}const r=await e.requestContent();if(null===r.content)return new s.EmptyWidget.EmptyWidget(r.error);if(!r.content)return new s.EmptyWidget.EmptyWidget(Ce(ye.nothingToPreview));let o=r.content;r.isEncoded&&(o=window.atob(o));const a=Se.parseXML(o,n);if(a)return Se.createSearchableView(a);const l=await he.createView(o);if(l)return l;if(i.isTextType()){const t=n.replace(/;.*/,"")||e.contentType().canonicalMimeType();return k.createSearchableView(e,t)}return null}}});export{W as BinaryResourceViewFactory,Z as FontView,re as ImageView,ue as JSONView,ve as PreviewFactory,z as ResourceSourceFrame,j as SourceFrame,be as XMLView};