@react-native/debugger-frontend
Version:
Debugger frontend for React Native based on Chrome DevTools
2 lines (1 loc) • 49.3 kB
JavaScript
import*as e from"../../../../models/text_utils/text_utils.js";import*as t from"../../legacy.js";import*as s from"../../../../core/common/common.js";import*as r from"../../../../core/i18n/i18n.js";import*as n from"../../../../core/host/host.js";import*as i from"../../../../core/platform/platform.js";import*as o from"../../../../core/root/root.js";import*as a from"../../../../core/sdk/sdk.js";import*as l from"../../../../models/formatter/formatter.js";import*as c from"../../../../panels/common/common.js";import*as h from"../../../../third_party/codemirror.next/codemirror.next.js";import*as d from"../../../components/code_highlighter/code_highlighter.js";import*as u from"../../../components/text_editor/text_editor.js";import*as m from"../../../visual_logging/visual_logging.js";import*as p from"../../../../panels/linear_memory_inspector/components/components.js";import*as g from"../../../../models/workspace/workspace.js";import*as f from"../object_ui/object_ui.js";const w=["application/javascript","application/json","application/manifest+json","text/css","text/html","text/javascript"];var S={cssText:`.searchable-view{flex:1}devtools-toolbar{background-color:var(--sys-color-cdt-base-container);border-top:1px solid var(--sys-color-divider)}\n/*# sourceURL=${import.meta.resolve("./resourceSourceFrame.css")} */\n`};const x={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",typeAllowPasting:"Type ''{PH1}''",binaryContentError:'Editor can\'t show binary data. Use the "Response" tab in the "Network" panel to inspect this resource.'},y=r.i18n.registerUIStrings("ui/legacy/components/source_frame/SourceFrame.ts",x),b=r.i18n.getLocalizedString.bind(void 0,y),T=h.Facet.define({combine:e=>0===e.length?e=>e.toString():e[0]});class C extends(s.ObjectWrapper.eventMixin(t.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,r={}){super(b(x.source)),this.options=r,this.lazyContent=e,this.prettyInternal=!1,this.rawContent=null,this.formattedMap=null,this.prettyToggle=new t.Toolbar.ToolbarToggle(b(x.prettyPrint),"brackets",void 0,"pretty-print"),this.prettyToggle.addEventListener("Click",(()=>{this.setPretty(this.prettyToggle.isToggled())})),this.shouldAutoPrettyPrint=!1,this.prettyToggle.setVisible(!1),this.progressToolbarItem=new t.Toolbar.ToolbarItem(document.createElement("div")),this.textEditorInternal=new u.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 t.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=s.Settings.Settings.instance().createSetting("disable-self-xss-warning",!1,"Synced"),s.Settings.Settings.instance().moduleSetting("text-editor-indent").addChangeListener(this.#e,this)}disposeView(){s.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 h.EditorState.create({doc:e,extensions:[h.EditorState.readOnly.of(!0),!1!==this.options.lineNumbers?h.lineNumbers():[],u.Config.theme()]})}editorConfiguration(e){return[h.EditorView.updateListener.of((e=>this.dispatchEventToListeners("EditorUpdate",e))),u.Config.baseConfiguration(e),u.Config.closeBrackets.instance(),u.Config.autocompletion.instance(),u.Config.showWhitespace.instance(),u.Config.allowScrollPastEof.instance(),h.Prec.lowest(u.Config.codeFolding.instance()),u.Config.autoDetectIndent.instance(),U,h.EditorView.domEventHandlers({focus:()=>this.onFocus(),blur:()=>this.onBlur(),paste:()=>this.onPaste(),scroll:()=>this.dispatchEventToListeners("EditorScroll"),contextmenu:e=>this.onContextMenu(e)}),h.lineNumbers({domEventHandlers:{contextmenu:(e,t,s)=>this.onLineGutterContextMenu(t.from,s)}}),h.EditorView.updateListener.of((e=>{(e.selectionSet||e.docChanged)&&this.updateSourcePosition(),e.docChanged&&this.onTextChanged()})),P,h.Prec.lowest(D),E.language.of([]),this.wasmDisassemblyInternal?(t=this.wasmDisassemblyInternal,F.init((e=>{const s=[];for(const r of t.nonBreakableLineNumbers())r<e.doc.lines&&s.push(M.range(e.doc.line(r+1).from));return h.RangeSet.of(s)}))):F,this.options.lineWrapping?h.EditorView.lineWrapping:[],!1!==this.options.lineNumbers?h.lineNumbers():[],h.indentationMarkers({colors:{light:"var(--sys-color-divider)",activeLight:"var(--sys-color-divider-prominent)",dark:"var(--sys-color-divider)",activeDark:"var(--sys-color-divider-prominent)"}}),A];var t}onBlur(){}onFocus(){}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 c.TypeToAllowDialog.show({jslogContext:{dialog:"self-xss-warning",input:"allow-pasting"},header:b(x.doYouTrustThisCode),message:b(x.doNotPaste,{PH1:b(x.allowPasting)}),typePhrase:b(x.allowPasting),inputPlaceholder:b(x.typeAllowPasting,{PH1:b(x.allowPasting)})})&&(this.selfXssWarningDisabledSetting.set(!0),n.userMetrics.actionTaken(n.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,t){this.shouldAutoPrettyPrint=!0===t&&s.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(h.EditorState.readOnly.of(!e))})}async setPretty(e){this.prettyInternal=e,this.prettyToggle.setEnabled(!1);const t=this.loaded,{textEditor:s}=this,r=s.state.selection.main,n=s.toLineColumn(r.from),i=s.toLineColumn(r.to);let o;if(this.prettyInternal){const e=this.rawContent instanceof h.Text?this.rawContent.sliceString(0):this.rawContent||"",t=await l.ScriptFormatter.formatScriptContent(this.contentType,e);this.formattedMap=t.formattedMapping,await this.setContent(t.formattedContent),this.prettyBaseDoc=s.state.doc;const r=this.rawToPrettyLocation(n.lineNumber,n.columnNumber),a=this.rawToPrettyLocation(i.lineNumber,i.columnNumber);o=s.createSelection({lineNumber:r[0],columnNumber:r[1]},{lineNumber:a[0],columnNumber:a[1]})}else{await this.setContent(this.rawContent||""),this.baseDoc=s.state.doc;const e=this.prettyToRawLocation(n.lineNumber,n.columnNumber),t=this.prettyToRawLocation(i.lineNumber,i.columnNumber);o=s.createSelection({lineNumber:e[0],columnNumber:e[1]},{lineNumber:t[0],columnNumber:t[1]})}t&&s.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,s=t.lineNumberToBytecodeOffset(t.lineNumbers-1).toString(16).length+1;e=e=>`0x${t.lineNumberToBytecodeOffset(Math.min(t.lineNumbers,e)-1).toString(16).padStart(s,"0")}`}else this.prettyInternal&&(e=(e,t)=>{if(e<2||e>t.doc.lines)return String(e);const[s]=this.prettyToRawLocation(e-1),[r]=this.prettyToRawLocation(e-2);return s!==r?String(s+1):"-"});return e?[h.lineNumbers({formatNumber:e}),T.of(e)]:[]}updateLineNumberFormatter(){this.textEditor.dispatch({effects:E.lineNumbers.reconfigure(this.getLineNumberFormatter())}),this.textEditor.shadowRoot?.querySelector(".cm-lineNumbers")?.setAttribute("jslog",`${m.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.setContentDataOrError(this.lazyContent()),this.contentSet=!0)}async setContentDataOrError(s){const r=new t.ProgressIndicator.ProgressIndicator;r.setTitle(b(x.loading)),r.setTotalWork(100),this.progressToolbarItem.element.appendChild(r.element),r.setWorked(1);const n=await s;let i,o,l=!1;e.ContentData.ContentData.isError(n)?(i=n.error,o=n.error):n instanceof e.WasmDisassembly.WasmDisassembly?(o=h.Text.of(n.lines),this.wasmDisassemblyInternal=n):n.isTextContent?(o=n.text,l=e.TextUtils.isMinified(n.text),this.wasmDisassemblyInternal=null):"application/wasm"===n.mimeType?(this.wasmDisassemblyInternal=await a.Script.disassembleWasm(n.base64),o=h.Text.of(this.wasmDisassemblyInternal.lines)):(i=b(x.binaryContentError),o=null,this.wasmDisassemblyInternal=null),r.setWorked(100),r.done(),this.rawContent===o&&void 0===i||(this.rawContent=o,this.formattedMap=null,this.prettyToggle.setEnabled(!0),i?(this.loadError=!0,this.textEditor.state=this.placeholderEditorState(i),this.prettyToggle.setEnabled(!1)):this.shouldAutoPrettyPrint&&l?await this.setPretty(!0):await this.setContent(this.rawContent||""))}revealPosition(e,t){if(this.lineToScrollTo=null,this.selectionToSet=null,"number"==typeof e){let s=0,r=0;const{doc:n}=this.textEditor.state;if(e>n.length)s=n.lines-1;else if(e>=0){const t=n.lineAt(e);s=t.number-1,r=e-t.from}this.positionToReveal={to:{lineNumber:s,columnNumber:r},shouldHighlight:t}}else if("lineNumber"in e){const{lineNumber:s,columnNumber:r}=e;this.positionToReveal={to:{lineNumber:s,columnNumber:r??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:s}=this.positionToReveal,r=this.uiLocationToEditorLocation(t.lineNumber,t.columnNumber),n=e?this.uiLocationToEditorLocation(e.lineNumber,e.columnNumber):void 0,{textEditor:i}=this;i.revealPosition(i.createSelection(r,n),s),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:h.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",`${m.gutter("line-numbers").track({click:!0})}`),this.textEditor.shadowRoot?.querySelector(".cm-foldGutter")?.setAttribute("jslog",`${m.gutter("fold")}`),this.textEditor.setAttribute("jslog",`${m.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 s=await d.CodeHighlighter.languageFromMIME(t);return s?[s,h.javascript.javascriptLanguage.data.of({autocomplete:h.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,s=this.loadedInternal,r=t.editor.scrollDOM.scrollTop;this.loadedInternal=!0;const n=await this.getLanguageSupport(e),i=h.EditorState.create({doc:e,extensions:[this.editorConfiguration(e),n,E.lineNumbers.of(this.getLineNumberFormatter()),E.editable.of(this.editable?[]:h.EditorState.readOnly.of(!0))]});this.baseDoc=i.doc,t.state=i,s&&(t.editor.scrollDOM.scrollTop=r),this.wasShownOrLoaded(),this.delayedFindSearchMatches&&(this.delayedFindSearchMatches(),this.delayedFindSearchMatches=null),this.muteChangeEventsForSetContent=!1}setSearchableView(e){this.searchableView=e}doFindSearchMatches(e,t,s){this.currentSearchResultIndex=-1,this.searchRegex=e.toSearchRegex(!0),this.searchResults=this.collectRegexMatches(this.searchRegex),this.searchableView&&this.searchableView.updateSearchMatchesCount(this.searchResults.length);const r=this.textEditor;this.searchResults.length?t&&s?this.jumpToPreviousSearchResult():t?this.jumpToNextSearchResult():r.dispatch({effects:R.of(new I(this.searchRegex,null))}):r.state.field(P)&&r.dispatch({effects:R.of(null)})}performSearch(e,t,s){this.searchableView&&this.searchableView.updateSearchMatchesCount(0),this.resetSearch(),this.searchConfig=e,this.loaded?this.doFindSearchMatches(e,t,Boolean(s)):this.delayedFindSearchMatches=this.doFindSearchMatches.bind(this,e,t,Boolean(s)),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(P);t?.currentRange&&e.dispatch({effects:R.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:R.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 i.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,s=this.searchResults[this.currentSearchResultIndex];t.dispatch({effects:R.of(new I(this.searchRegex,s)),selection:{anchor:s.from,head:s.to},scrollIntoView:!0,userEvent:"select.search"})}replaceSelectionWith(e,t){const s=this.searchResults[this.currentSearchResultIndex];if(!s)return;const r=this.searchRegex?.fromQuery?s.insertPlaceholders(t):t,n=this.textEditor,i=n.state.changes({from:s.from,to:s.to,insert:r});n.dispatch({changes:i,selection:{anchor:i.mapPos(n.state.selection.main.to,1)},userEvent:"input.replace"})}replaceAllWith(e,t){this.resetCurrentSearchResultIndex();const s=e.toSearchRegex(!0),r=this.collectRegexMatches(s);if(!r.length)return;const n=s.fromQuery,i=r.map((e=>({from:e.from,to:e.to,insert:n?e.insertPlaceholders(t):t})));this.textEditor.dispatch({changes:i,scrollIntoView:!0,userEvent:"input.replace.all"})}collectRegexMatches({regex:e}){const t=[];let s=0;for(const r of this.textEditor.state.doc.iterLines()){for(e.lastIndex=0;;){const n=e.exec(r);if(!n)break;if(n[0].length){const e=s+n.index;t.push(new v(e,e+n[0].length,n))}else e.lastIndex=n.index+1}s+=r.length+1}return t}canEditSource(){return this.editable}updateSourcePosition(){const{textEditor:e}=this,{state:t}=e,{selection:s}=t;if(this.displayedSelection?.eq(s))return;if(this.displayedSelection=s,s.ranges.length>1)return void this.sourcePosition.setText(b(x.dSelectionRegions,{PH1:s.ranges.length}));const{main:r}=t.selection;if(r.empty){const{lineNumber:t,columnNumber:s}=e.toLineColumn(r.head),n=this.prettyToRawLocation(t,s);if(this.wasmDisassemblyInternal){const e=this.wasmDisassemblyInternal,t=e.lineNumberToBytecodeOffset(e.lineNumbers-1).toString(16).length,s=e.lineNumberToBytecodeOffset(n[0]);this.sourcePosition.setText(b(x.bytecodePositionXs,{PH1:s.toString(16).padStart(t,"0")}))}else this.sourcePosition.setText(b(x.lineSColumnS,{PH1:n[0]+1,PH2:n[1]+1}))}else{const e=t.doc.lineAt(r.from),s=t.doc.lineAt(r.to);e.number===s.number?this.sourcePosition.setText(b(x.dCharactersSelected,{PH1:r.to-r.from})):this.sourcePosition.setText(b(x.dLinesDCharactersSelected,{PH1:s.number-e.number+1,PH2:r.to-r.from}))}}onContextMenu(e){e.consume(!0);const s=new t.ContextMenu.ContextMenu(e),{state:r}=this.textEditor,n=r.selection.main.from,i=r.doc.lineAt(n);return this.populateTextAreaContextMenu(s,i.number-1,n-i.from),s.appendApplicableItems(this),s.show(),!0}populateTextAreaContextMenu(e,t,s){}onLineGutterContextMenu(e,s){s.consume(!0);const r=new t.ContextMenu.ContextMenu(s),n=this.textEditor.state.doc.lineAt(e).number-1;return this.populateLineGutterContextMenu(r,n),r.appendApplicableItems(this),r.show(),!0}populateLineGutterContextMenu(e,t){}focus(){this.textEditor.focus()}}class v{from;to;match;constructor(e,t,s){this.from=e,this.to=t,this.match=s}insertPlaceholders(e){return e.replace(/\$(\$|&|\d+|<[^>]+>)/g,((e,t)=>"$"===t?"$":"&"===t?this.match[0]:"<"===t[0]?this.match.groups?.[t.slice(1,t.length-1)]||"":this.match[Number.parseInt(t,10)]||""))}}const E={editable:new h.Compartment,language:new h.Compartment,lineNumbers:new h.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 R=h.StateEffect.define({map:(e,t)=>e?.map(t)}),P=h.StateField.define({create:()=>null,update:(e,t)=>t.effects.reduce(((e,t)=>t.is(R)?t.value:e),e?.map(t.changes)??null)}),L=h.Decoration.mark({class:"cm-searchMatch"}),N=h.Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"}),D=h.ViewPlugin.fromClass(class{decorations;constructor(e){this.decorations=this.computeDecorations(e)}update(e){const t=e.state.field(P);(!I.eq(t,e.startState.field(P))||t&&(e.viewportChanged||e.docChanged))&&(this.decorations=this.computeDecorations(e.view))}computeDecorations(e){const t=e.state.field(P);if(!t)return h.Decoration.none;const s=new h.RangeSetBuilder,{doc:r}=e.state;for(const{from:n,to:i}of e.visibleRanges){let e=n;for(const o of r.iterRange(n,i)){if("\n"!==o)for(t.regexp.regex.lastIndex=0;;){const r=t.regexp.regex.exec(o);if(!r)break;if(r[0].length){const n=e+r.index,i=n+r[0].length,o=t.currentRange&&t.currentRange.from===n&&t.currentRange.to===i;s.add(n,i,o?N:L)}else t.regexp.regex.lastIndex=r.index+1}e+=o.length}}return s.finish()}},{decorations:e=>e.decorations}),M=new class extends h.GutterMarker{elementClass="cm-nonBreakableLine"},V=h.StateEffect.define(),F=h.StateField.define({create:()=>h.RangeSet.empty,update:(e,t)=>t.effects.reduce(((e,t)=>t.is(V)?e.update({add:t.value.map((e=>M.range(e)))}):e),e.map(t.changes)),provide:e=>h.lineNumberMarkers.from(e)});const U=h.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)"}}),j=h.StateEffect.define(),O=h.StateEffect.define(),A=h.StateField.define({create:()=>[],update(e,t){for(const s of t.effects)s.is(j)?e=e.concat(s.value):s.is(O)&&(e=e.filter((e=>e!==s.value)));return e},provide:e=>h.showPanel.computeN([e],(t=>t.field(e).map((e=>()=>({dom:e.element})))))});var H=Object.freeze({__proto__:null,LINE_NUMBER_FORMATTER:T,SourceFrameImpl:C,addInfobar:j,addNonBreakableLines:V,isBreakableLine:function(e,t){const s=e.field(F);if(!s.size)return!0;let r=!1;return s.between(t.from,t.from,(()=>{r=!0})),!r},removeInfobar:O});const _={find:"Find"},k=r.i18n.registerUIStrings("ui/legacy/components/source_frame/ResourceSourceFrame.ts",_),z=r.i18n.getLocalizedString.bind(void 0,k);class W extends C{resourceInternal;#t;constructor(t,s,r){const n=e.ContentProvider.isStreamingContentProvider(t);super(n?()=>t.requestStreamingContent().then(e.StreamingContentData.asContentDataOrError):()=>t.requestContentData(),r),this.#t=s,this.resourceInternal=t,n&&t.requestStreamingContent().then((t=>{e.StreamingContentData.isError(t)||t.addEventListener("ChunkAdded",(()=>{this.setContentDataOrError(Promise.resolve(t.content()))}))}))}static createSearchableView(e,t){return new B(e,t)}getContentType(){return this.#t}get resource(){return this.resourceInternal}populateTextAreaContextMenu(e,t,s){super.populateTextAreaContextMenu(e,t,s),e.appendApplicableItems(this.resourceInternal)}}class B extends t.Widget.VBox{sourceFrame;constructor(e,r){super(!0),this.registerRequiredCSS(S);const n=s.ResourceType.ResourceType.simplifyContentType(r),i=new W(e,n);this.sourceFrame=i;const o=w.includes(n);i.setCanPrettyPrint(o,!0);const a=new t.SearchableView.SearchableView(i,i);a.element.classList.add("searchable-view"),a.setPlaceholder(z(_.find)),i.show(a.element),i.setSearchableView(a),a.show(this.contentElement);const l=this.contentElement.createChild("devtools-toolbar","toolbar");i.toolbarItems().then((e=>{e.map((e=>l.appendToolbarItem(e)))}))}async revealPosition(e){this.sourceFrame.revealPosition(e,!0)}}var q=Object.freeze({__proto__:null,ResourceSourceFrame:W,SearchableContainer:B});const $=1e3;class X extends t.Widget.VBox{#s=new Uint8Array([0]);#r=0;#n=new p.LinearMemoryInspector.LinearMemoryInspector;constructor(){super(!1),this.#n.addEventListener(p.LinearMemoryInspector.MemoryRequestEvent.eventName,this.#i.bind(this)),this.#n.addEventListener(p.LinearMemoryInspector.AddressChangedEvent.eventName,(e=>{this.#r=e.data})),this.contentElement.appendChild(this.#n)}wasShown(){this.refreshData()}setMemory(e){this.#s=e,this.refreshData()}refreshData(){const e=Math.max(0,this.#r-500),t=e+$,s=this.#s.slice(e,t);this.#n.data={memory:s,address:this.#r,memoryOffset:e,outerMemoryLength:this.#s.length,hideValueInspector:!0}}#i(e){const{start:t,end:s,address:r}=e.data;if(r<t||r>=s)throw new Error("Requested address is out of bounds.");if(t<0||t>s||t>=this.#s.length)throw new Error("Requested range is out of bounds.");const n=Math.max(s,t+$),i=this.#s.slice(t,n);this.#n.data={memory:i,address:r,memoryOffset:t,outerMemoryLength:this.#s.length,hideValueInspector:!0}}}class J extends X{#o;constructor(e){super(),this.#o=e}wasShown(){this.#a(),this.#o.addEventListener("ChunkAdded",this.#a,this)}willHide(){super.willHide(),this.#o.removeEventListener("ChunkAdded",this.#a,this)}#a(){const e=window.atob(this.#o.content().base64),t=Uint8Array.from(e,(e=>e.codePointAt(0)));this.setMemory(t)}}var G=Object.freeze({__proto__:null,StreamingContentHexView:J});class Q{streamingContent;contentUrl;resourceType;constructor(e,t,s){this.streamingContent=e,this.contentUrl=t,this.resourceType=s}hex(){const e=window.atob(this.base64()),t=Uint8Array.from(e,(e=>e.codePointAt(0)));return Q.#l(t)}base64(){return this.streamingContent.content().base64}utf8(){return new e.ContentData.ContentData(this.base64(),!0,"text/plain","utf-8").text}createBase64View(){const t=new W(e.StaticContentProvider.StaticContentProvider.fromString(this.contentUrl,this.resourceType,this.streamingContent.content().base64),this.resourceType.canonicalMimeType(),{lineNumbers:!1,lineWrapping:!0});return this.streamingContent.addEventListener("ChunkAdded",(()=>{t.setContent(this.base64())})),t}createHexView(){return new J(this.streamingContent)}createUtf8View(){const t=new W(e.StaticContentProvider.StaticContentProvider.fromString(this.contentUrl,this.resourceType,this.utf8()),this.resourceType.canonicalMimeType(),{lineNumbers:!0,lineWrapping:!0});return this.streamingContent.addEventListener("ChunkAdded",(()=>{t.setContent(this.utf8())})),t}static#l(e){let t="";for(let s=0;s<e.length;s++)t+=Q.#c(e[s],2);return t}static#c(e,t){let s=e.toString(16);for(;s.length<t;)s="0"+s;return s}}var Y=Object.freeze({__proto__:null,BinaryResourceViewFactory:Q}),K={cssText:`.font-view{font-size:60px;white-space:pre-wrap;word-wrap:break-word;text-align:center;padding:15px}\n/*# sourceURL=${import.meta.resolve("./fontView.css")} */\n`};const Z={font:"Font",previewOfFontFromS:"Preview of font from {PH1}"},ee=r.i18n.registerUIStrings("ui/legacy/components/source_frame/FontView.ts",Z),te=r.i18n.getLocalizedString.bind(void 0,ee);class se extends t.View.SimpleView{url;contentProvider;mimeTypeLabel;fontPreviewElement;dummyElement;fontStyleElement;inResize;constructor(e,s){super(te(Z.font)),this.registerRequiredCSS(K),this.element.classList.add("font-view"),this.element.setAttribute("jslog",`${m.pane("font-view")}`),this.url=s.contentURL(),t.ARIAUtils.setLabel(this.element,te(Z.previewOfFontFromS,{PH1:this.url})),this.contentProvider=s,this.mimeTypeLabel=new t.Toolbar.ToolbarText(e)}async toolbarItems(){return[this.mimeTypeLabel]}onFontContentLoaded(t,s){const r=e.ContentData.ContentData.isError(s)?this.url:s.asDataUrl();this.fontStyleElement&&(this.fontStyleElement.textContent=i.StringUtilities.sprintf('@font-face { font-family: "%s"; src: url(%s); }',t,r),this.updateFontPreviewSize())}createContentIfNeeded(){if(this.fontPreviewElement)return;const e="WebInspectorFontPreview"+ ++re;this.fontStyleElement=document.createElement("style"),this.contentProvider.requestContentData().then((t=>{this.onFontContentLoaded(e,t)})),this.element.appendChild(this.fontStyleElement);const s=document.createElement("div");for(let e=0;e<ne.length;++e)e>0&&s.createChild("br"),t.UIUtils.createTextChild(s,ne[e]);this.fontPreviewElement=s.cloneNode(!0),this.fontPreviewElement&&(t.ARIAUtils.setHidden(this.fontPreviewElement,!0),this.fontPreviewElement.style.overflow="hidden",this.fontPreviewElement.style.setProperty("font-family",e),this.fontPreviewElement.style.setProperty("visibility","hidden"),this.dummyElement=s,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",ie+"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,s=e.width,r=this.element.offsetWidth-50,n=this.element.offsetHeight-30;if(!(t&&s&&r&&n))return void this.fontPreviewElement.style.removeProperty("font-size");const i=r/s,o=n/t,a=Math.floor(ie*Math.min(i,o))-2;this.fontPreviewElement.style.setProperty("font-size",a+"px",void 0)}}let re=0;const ne=["ABCDEFGHIJKLM","NOPQRSTUVWXYZ","abcdefghijklm","nopqrstuvwxyz","1234567890"],ie=50;var oe=Object.freeze({__proto__:null,FontView:se}),ae={cssText:`.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=${import.meta.resolve("./imageView.css")} */\n`};const le={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"},ce=r.i18n.registerUIStrings("ui/legacy/components/source_frame/ImageView.ts",le),he=r.i18n.getLocalizedString.bind(void 0,ce);class de extends t.View.SimpleView{url;parsedURL;mimeType;contentProvider;uiSourceCode;sizeLabel;dimensionsLabel;aspectRatioLabel;mimeTypeLabel;container;imagePreviewElement;cachedContent;constructor(e,r){super(he(le.image)),this.registerRequiredCSS(ae),this.element.tabIndex=-1,this.element.classList.add("image-view"),this.element.setAttribute("jslog",`${m.pane("image-view")}`),this.url=r.contentURL(),this.parsedURL=new s.ParsedURL.ParsedURL(this.url),this.mimeType=e,this.contentProvider=r,this.uiSourceCode=r instanceof g.UISourceCode.UISourceCode?r:null,this.uiSourceCode&&(this.uiSourceCode.addEventListener(g.UISourceCode.Events.WorkingCopyCommitted,this.workingCopyCommitted,this),new t.DropTarget.DropTarget(this.element,[t.DropTarget.Type.ImageFile,t.DropTarget.Type.URI],he(le.dropImageFileHere),this.handleDrop.bind(this))),this.sizeLabel=new t.Toolbar.ToolbarText,this.dimensionsLabel=new t.Toolbar.ToolbarText,this.aspectRatioLabel=new t.Toolbar.ToolbarText,this.mimeTypeLabel=new t.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 t.Toolbar.ToolbarSeparator,this.dimensionsLabel,new t.Toolbar.ToolbarSeparator,this.aspectRatioLabel,new t.Toolbar.ToolbarSeparator,this.mimeTypeLabel]}wasShown(){this.updateContentIfNeeded()}disposeView(){this.uiSourceCode&&this.uiSourceCode.removeEventListener(g.UISourceCode.Events.WorkingCopyCommitted,this.workingCopyCommitted,this)}workingCopyCommitted(){this.updateContentIfNeeded()}async updateContentIfNeeded(){const t=await this.contentProvider.requestContentData();if(e.ContentData.ContentData.isError(t)||this.cachedContent?.contentEqualTo(t))return;this.cachedContent=t;const s=t.asDataUrl()??this.url,n=new Promise((e=>{this.imagePreviewElement.onload=e}));this.imagePreviewElement.src=s,this.imagePreviewElement.alt=he(le.imageFromS,{PH1:this.url});const o=t.isTextContent?t.text.length:i.StringUtilities.base64ToSize(t.base64);this.sizeLabel.setText(r.ByteUtilities.bytesToString(o)),await n,this.dimensionsLabel.setText(he(le.dD,{PH1:this.imagePreviewElement.naturalWidth,PH2:this.imagePreviewElement.naturalHeight})),this.aspectRatioLabel.setText(i.NumberUtilities.aspectRatio(this.imagePreviewElement.naturalWidth,this.imagePreviewElement.naturalHeight))}contextMenu(e){const r=new t.ContextMenu.ContextMenu(e),n=new s.ParsedURL.ParsedURL(this.imagePreviewElement.src);this.parsedURL.isDataURL()||r.clipboardSection().appendItem(he(le.copyImageUrl),this.copyImageURL.bind(this),{jslogContext:"image-view.copy-image-url"}),n.isDataURL()&&r.clipboardSection().appendItem(he(le.copyImageAsDataUri),this.copyImageAsDataURL.bind(this),{jslogContext:"image-view.copy-image-as-data-url"}),r.clipboardSection().appendItem(he(le.openImageInNewTab),this.openInNewTab.bind(this),{jslogContext:"image-view.open-in-new-tab"}),r.clipboardSection().appendItem(he(le.saveImageAs),this.saveImage.bind(this),{jslogContext:"image-view.save-image"}),r.show()}copyImageAsDataURL(){n.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this.imagePreviewElement.src)}copyImageURL(){n.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this.url)}async saveImage(){const e=this.cachedContent?.asDataUrl();if(!e)return;let t="";if(this.parsedURL.isDataURL()){t=he(le.download);const{type:e,subtype:s}=this.parsedURL.extractDataUrlMimeType();"image"===e&&s&&(t+="."+s)}else t=decodeURIComponent(this.parsedURL.displayName);const s=await fetch(e).then((e=>e.blob()));try{const e=await window.showSaveFilePicker({suggestedName:t}),r=await e.createWritable();await r.write(s),await r.close()}catch(e){if("AbortError"===e.name)return;throw e}}openInNewTab(){n.InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab(this.url)}async handleDrop(e){const t=e.items;if(!t.length||"file"!==t[0].kind)return;const s=t[0].getAsFile();if(!s)return;const r=!s.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(r?btoa(e):e,r)},r?t.readAsBinaryString(e):t.readAsText(e)})(s)}}var ue=Object.freeze({__proto__:null,ImageView:de}),me={cssText:`.json-view{padding:2px 6px;overflow:auto}\n/*# sourceURL=${import.meta.resolve("./jsonView.css")} */\n`};const pe={find:"Find"},ge=r.i18n.registerUIStrings("ui/legacy/components/source_frame/JSONView.ts",pe),fe=r.i18n.getLocalizedString.bind(void 0,ge);class we extends t.Widget.VBox{initialized;parsedJSON;startCollapsed;searchableView;treeOutline;currentSearchFocusIndex;currentSearchTreeElements;searchRegex;constructor(e,t){super(),this.initialized=!1,this.registerRequiredCSS(me),this.parsedJSON=e,this.startCollapsed=Boolean(t),this.element.classList.add("json-view"),this.element.setAttribute("jslog",`${m.section("json-view")}`),this.currentSearchFocusIndex=0,this.currentSearchTreeElements=[],this.searchRegex=null}static async createView(e){const s=await we.parseJSON(e);if(!s||"object"!=typeof s.data)return null;const r=new we(s),n=new t.SearchableView.SearchableView(r,null);return n.setPlaceholder(fe(pe.find)),r.searchableView=n,r.show(n.element),n}static createViewSync(e){const s=new we(new Se(e,"","")),r=new t.SearchableView.SearchableView(s,null);return r.setPlaceholder(fe(pe.find)),s.searchableView=r,s.show(r.element),s.element.tabIndex=0,r}static parseJSON(e){let t=null;if(e&&(t=we.extractJSON(e)),!t)return Promise.resolve(null);try{const e=JSON.parse(t.data);if(!e)return Promise.resolve(null);t.data=e}catch{t=null}return Promise.resolve(t)}static extractJSON(e){if(e.startsWith("<"))return null;let t=we.findBrackets(e,"{","}");const s=we.findBrackets(e,"[","]");if(t=s.length>t.length?s:t,-1===t.length||e.length-t.length>80)return null;const r=e.substring(0,t.start),n=e.substring(t.end+1);return e=e.substring(t.start,t.end+1),!n.trim().length||n.trim().startsWith(")")&&r.trim().endsWith("(")?new Se(e,r,n):null}static findBrackets(e,t,s){const r=e.indexOf(t),n=e.lastIndexOf(s);let i=n-r-1;return(-1===r||-1===n||n<r)&&(i=-1),{start:r,end:n,length:i}}wasShown(){this.initialize()}initialize(){if(this.initialized)return;this.initialized=!0;const e=a.RemoteObject.RemoteObject.fromLocalObject(this.parsedJSON.data),t=this.parsedJSON.prefix+e.description+this.parsedJSON.suffix;this.treeOutline=new f.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 s=this.treeOutline.firstChild();s&&s.select(!0,!1)}jumpToMatch(e){if(!this.searchRegex)return;const s=this.currentSearchTreeElements[this.currentSearchFocusIndex];s&&s.setSearchRegex(this.searchRegex);const r=this.currentSearchTreeElements[e];r?(this.updateSearchIndex(e),r.setSearchRegex(this.searchRegex,t.UIUtils.highlightedCurrentSearchResultClassName),r.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 f.ObjectPropertiesSection.ObjectPropertyTreeElement&&e.revertHighlightChanges();this.updateSearchCount(0),this.updateSearchIndex(0)}performSearch(e,t,s){let r=this.currentSearchFocusIndex;const n=this.currentSearchTreeElements[r];let o;for(this.onSearchCanceled(),this.searchRegex=e.toSearchRegex(!0).regex,o=this.treeOutline.rootElement();o;o=o.traverseNextTreeElement(!1)){if(!(o instanceof f.ObjectPropertiesSection.ObjectPropertyTreeElement))continue;const e=o.setSearchRegex(this.searchRegex);if(e&&this.currentSearchTreeElements.push(o),n===o){const t=this.currentSearchTreeElements.length-1;r=e||s?t:t+1}}this.updateSearchCount(this.currentSearchTreeElements.length),this.currentSearchTreeElements.length?(r=i.NumberUtilities.mod(r,this.currentSearchTreeElements.length),this.jumpToMatch(r)):this.updateSearchIndex(-1)}jumpToNextSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=i.NumberUtilities.mod(this.currentSearchFocusIndex+1,this.currentSearchTreeElements.length);this.jumpToMatch(e)}jumpToPreviousSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=i.NumberUtilities.mod(this.currentSearchFocusIndex-1,this.currentSearchTreeElements.length);this.jumpToMatch(e)}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}}class Se{data;prefix;suffix;constructor(e,t,s){this.data=e,this.prefix=t,this.suffix=s}}var xe=Object.freeze({__proto__:null,JSONView:we,ParsedJSON:Se}),ye={cssText:`.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=${import.meta.resolve("./xmlTree.css")} */\n`},be={cssText:`.shadow-xml-view{user-select:text;overflow:auto;padding:2px 4px}\n/*# sourceURL=${import.meta.resolve("./xmlView.css")} */\n`};const Te={find:"Find"},Ce=r.i18n.registerUIStrings("ui/legacy/components/source_frame/XMLView.ts",Te),ve=r.i18n.getLocalizedString.bind(void 0,Ce);class Ee extends t.Widget.Widget{treeOutline=new t.TreeOutline.TreeOutlineInShadow;searchableView=null;currentSearchFocusIndex=0;currentSearchTreeElements=[];searchConfig=null;constructor(e){super(!0),this.registerRequiredCSS(be),this.contentElement.classList.add("shadow-xml-view","source-code"),this.treeOutline.registerRequiredCSS(ye),this.contentElement.appendChild(this.treeOutline.element),Ie.populate(this.treeOutline,e,this);const t=this.treeOutline.firstChild();t&&t.select(!0,!1)}static createSearchableView(e){const s=new Ee(e),r=new t.SearchableView.SearchableView(s,null);return r.setPlaceholder(ve(Te.find)),s.searchableView=r,s.show(r.element),r}static parseXML(e,t){let s;try{switch(t){case"application/xhtml+xml":case"application/xml":case"image/svg+xml":case"text/html":case"text/xml":s=(new DOMParser).parseFromString(e,t)}}catch{return null}return!s||s.body?null:s}jumpToMatch(e,s){if(!this.searchConfig)return;const{regex:r}=this.searchConfig.toSearchRegex(!0),n=this.currentSearchTreeElements[this.currentSearchFocusIndex];n&&n.setSearchRegex(r);const i=this.currentSearchTreeElements[e];i?(this.updateSearchIndex(e),s&&i.reveal(!0),i.setSearchRegex(r,t.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 s=this.currentSearchFocusIndex;const r=this.currentSearchTreeElements[s];this.innerSearchCanceled(),this.currentSearchTreeElements=[];const{regex:n}=this.searchConfig.toSearchRegex(!0);for(let e=this.treeOutline.rootElement();e;e=e.traverseNextTreeElement(!1)){if(!(e instanceof Ie))continue;const i=e.setSearchRegex(n);if(i&&this.currentSearchTreeElements.push(e),r===e){const e=this.currentSearchTreeElements.length-1;s=i||t?e:e+1}}this.updateSearchCount(this.currentSearchTreeElements.length),this.currentSearchTreeElements.length?(s=i.NumberUtilities.mod(s,this.currentSearchTreeElements.length),this.jumpToMatch(s,e)):this.updateSearchIndex(0)}innerSearchCanceled(){for(let e=this.treeOutline.rootElement();e;e=e.traverseNextTreeElement(!1))e instanceof Ie&&e.revertHighlightChanges();this.updateSearchCount(0),this.updateSearchIndex(0)}onSearchCanceled(){this.searchConfig=null,this.currentSearchTreeElements=[],this.innerSearchCanceled()}performSearch(e,t,s){this.searchConfig=e,this.innerPerformSearch(t,s)}jumpToNextSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=i.NumberUtilities.mod(this.currentSearchFocusIndex+1,this.currentSearchTreeElements.length);this.jumpToMatch(e,!0)}jumpToPreviousSearchResult(){if(!this.currentSearchTreeElements.length)return;const e=i.NumberUtilities.mod(this.currentSearchFocusIndex-1,this.currentSearchTreeElements.length);this.jumpToMatch(e,!0)}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}}class Ie extends t.TreeOutline.TreeElement{node;closeTag;highlightChanges;xmlView;constructor(e,t,s){super("",!t&&"childElementCount"in e&&Boolean(e.childElementCount)),this.node=e,this.closeTag=t,this.selectable=!0,this.highlightChanges=[],this.xmlView=s,this.updateTitle()}static populate(e,t,s){if(!(t instanceof Node))return;let r=t.firstChild;for(;r;){const t=r;r=r.nextSibling;const n=t.nodeType;3===n&&t.nodeValue?.match(/\s+/)||(1!==n&&3!==n&&4!==n&&7!==n&&8!==n||e.appendChild(new Ie(t,!1,s)))}}setSearchRegex(s,r){if(this.revertHighlightChanges(),!s)return!1;if(this.closeTag&&this.parent&&!this.parent.expanded)return!1;s.lastIndex=0;let n=t.UIUtils.highlightedSearchResultClassName;if(r&&(n+=" "+r),!this.listItemElement.textContent)return!1;const i=this.listItemElement.textContent.replace(/\xA0/g," ");let o=s.exec(i);const a=[];for(;o;)a.push(new e.TextRange.SourceRange(o.index,o[0].length)),o=s.exec(i);return a.length&&t.UIUtils.highlightRangesWithStyleClass(this.listItemElement,a,n,this.highlightChanges),Boolean(this.highlightChanges.length)}revertHighlightChanges(){t.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 s=["<"+t,"shadow-xml-view-tag"],r=e.attributes;for(let e=0;e<r.length;++e){const t=r.item(e);if(!t)return;s.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?s.push(">","shadow-xml-view-tag","…","shadow-xml-view-comment","</"+t,"shadow-xml-view-tag"):e.textContent?s.push(">","shadow-xml-view-tag",e.textContent,"shadow-xml-view-text","</"+t,"shadow-xml-view-tag"):s.push(" /","shadow-xml-view-tag")),s.push(">","shadow-xml-view-tag"),void this.setTitle(s)}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 s=0;s<e.length;s+=2)t.createChild("span",e[s+1]).textContent=e[s];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(){Ie.populate(this,this.node,this.xmlView),this.appendChild(new Ie(this.node,!0,this.xmlView))}}var Re=Object.freeze({__proto__:null,XMLView:Ee,XMLViewNode:Ie});const Pe={failedToLoadData:"Failed to load data",nothingToPreview:"Nothing to preview"},Le=r.i18n.registerUIStrings("ui/legacy/components/source_frame/PreviewFactory.ts",Pe),Ne=r.i18n.getLocalizedString.bind(void 0,Le);var De=Object.freeze({__proto__:null,PreviewFactory:class{static async createPreview(r,n){let i=s.ResourceType.ResourceType.fromMimeType(n);switch(i===s.ResourceType.resourceTypes.Other&&(i=r.contentType()),i){case s.ResourceType.resourceTypes.Image:return new de(n,r);case s.ResourceType.resourceTypes.Font:return new se(n,r)}const o=await r.requestContentData();if(e.ContentData.ContentData.isError(o))return new t.EmptyWidget.EmptyWidget(Ne(Pe.failedToLoadData),o.error);if(!o.isTextContent)return null;if(!o.text)return new t.EmptyWidget.EmptyWidget(Ne(Pe.nothingToPreview),"");const a=Ee.parseXML(o.text,o.mimeType);if(a)return Ee.createSearchableView(a);const l=await we.createView(o.text);if(l)return l;const c=n.replace(/;.*/,"")||r.contentType().canonicalMimeType();return W.createSearchableView(r,c)}}});export{Y as BinaryResourceViewFactory,oe as FontView,ue as ImageView,xe as JSONView,De as PreviewFactory,q as ResourceSourceFrame,H as SourceFrame,G as StreamingContentHexView,Re as XMLView};