text: import*as Common from"../common/common.js";import*as Host from"../host/host.js";import*as ObjectUI from"../object_ui/object_ui.js";import*as SDK from"../sdk/sdk.js";import*as TextUtils from"../text_utils/text_utils.js";import*as UI from"../ui/ui.js";import{ConsolePanel}from"./ConsolePanel.js";export class ConsolePrompt extends UI.Widget.Widget{constructor(){super(),this.registerRequiredCSS("console/consolePrompt.css"),this._addCompletionsFromHistory=!0,this._history=new ConsoleHistoryManager,this._initialText="",this._editor=null,this._eagerPreviewElement=createElementWithClass("div","console-eager-preview"),this._textChangeThrottler=new Common.Throttler.Throttler(150),this._formatter=new ObjectUI.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter,this._requestPreviewBound=this._requestPreview.bind(this),this._innerPreviewElement=this._eagerPreviewElement.createChild("div","console-eager-inner-preview"),this._eagerPreviewElement.appendChild(UI.Icon.Icon.create("smallicon-command-result","preview-result-icon"));const t=this.element.createChild("div","console-prompt-editor-container");this.element.appendChild(this._eagerPreviewElement),this._promptIcon=UI.Icon.Icon.create("smallicon-text-prompt","console-prompt-icon"),this.element.appendChild(this._promptIcon),this._iconThrottler=new Common.Throttler.Throttler(0),this._eagerEvalSetting=Common.Settings.Settings.instance().moduleSetting("consoleEagerEval"),this._eagerEvalSetting.addChangeListener(this._eagerSettingChanged.bind(this)),this._eagerPreviewElement.classList.toggle("hidden",!this._eagerEvalSetting.get()),this.element.tabIndex=0,this._previewRequestForTest=null,this._defaultAutocompleteConfig=null,this._highlightingNode=!1,self.runtime.extension(UI.TextEditor.TextEditorFactory).instance().then(function(e){this._editor=e.createEditor({devtoolsAccessibleName:ls`Console prompt`,lineNumbers:!1,lineWrapping:!0,mimeType:"javascript",autoHeight:!0}),this._defaultAutocompleteConfig=ObjectUI.JavaScriptAutocomplete.JavaScriptAutocompleteConfig.createConfigForEditor(this._editor),this._editor.configureAutocomplete(Object.assign({},this._defaultAutocompleteConfig,{suggestionsCallback:this._wordsWithQuery.bind(this),anchorBehavior:UI.GlassPane.AnchorBehavior.PreferTop})),this._editor.widget().element.addEventListener("keydown",this._editorKeyDown.bind(this),!0),this._editor.widget().show(t),this._editor.addEventListener(UI.TextEditor.Events.CursorChanged,this._updatePromptIcon,this),this._editor.addEventListener(UI.TextEditor.Events.TextChanged,this._onTextChanged,this),this._editor.addEventListener(UI.TextEditor.Events.SuggestionChanged,this._onTextChanged,this),this.setText(this._initialText),delete this._initialText,this.hasFocus()&&this.focus();this.element.removeAttribute("tabindex"),this._editor.widget().element.tabIndex=-1,this._editorSetForTest(),Host.userMetrics.panelLoaded("console","DevTools.Launch.Console")}.bind(this))}_eagerSettingChanged(){const t=this._eagerEvalSetting.get();this._eagerPreviewElement.classList.toggle("hidden",!t),t&&this._requestPreview()}belowEditorElement(){return this._eagerPreviewElement}_onTextChanged(){if(this._eagerEvalSetting.get()){const t=!this._editor.textWithCurrentSuggestion();this._previewRequestForTest=this._textChangeThrottler.schedule(this._requestPreviewBound,t)}this._updatePromptIcon(),this.dispatchEventToListeners(Events.TextChanged)}async _requestPreview(){const t=this._editor.textWithCurrentSuggestion().trim(),e=self.UI.context.flavor(SDK.RuntimeModel.ExecutionContext),{preview:i,result:s}=await ObjectUI.JavaScriptREPL.JavaScriptREPL.evaluateAndBuildPreview(t,!0,500);this._innerPreviewElement.removeChildren(),i.deepTextContent()!==this._editor.textWithCurrentSuggestion().trim()&&this._innerPreviewElement.appendChild(i),s&&s.object&&"node"===s.object.subtype?(this._highlightingNode=!0,SDK.OverlayModel.OverlayModel.highlightObjectAsDOMNode(s.object)):this._highlightingNode&&(this._highlightingNode=!1,SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight()),s&&e.runtimeModel.releaseEvaluationResult(s)}willHide(){this._highlightingNode&&(this._highlightingNode=!1,SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight())}history(){return this._history}clearAutocomplete(){this._editor&&this._editor.clearAutocomplete()}_isCaretAtEndOfPrompt(){return!!this._editor&&this._editor.selection().collapseToEnd().equal(this._editor.fullRange().collapseToEnd())}moveCaretToEndOfPrompt(){this._editor&&this._editor.setSelection(TextUtils.TextRange.TextRange.createFromLocation(1/0,1/0))}setText(t){this._editor?this._editor.setText(t):this._initialText=t,this.dispatchEventToListeners(Events.TextChanged)}text(){return this._editor?this._editor.text():this._initialText}setAddCompletionsFromHistory(t){this._addCompletionsFromHistory=t}_editorKeyDown(t){const e=t;let i,s;const o=this._editor.selection(),r=this._editor.visualCoordinates(o.endLine,o.endColumn).y;switch(e.keyCode){case UI.KeyboardShortcut.Keys.Up.code:{const t=this._editor.visualCoordinates(0,0).y;if(e.shiftKey||!o.isEmpty()||r!==t)break;i=this._history.previous(this.text()),s=!0;break}case UI.KeyboardShortcut.Keys.Down.code:{const t=this._editor.fullRange(),s=this._editor.visualCoordinates(t.endLine,t.endColumn).y;if(e.shiftKey||!o.isEmpty()||r!==s)break;i=this._history.next();break}case UI.KeyboardShortcut.Keys.P.code:!Host.Platform.isMac()||!e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||(i=this._history.previous(this.text()),s=!0);break;case UI.KeyboardShortcut.Keys.N.code:!Host.Platform.isMac()||!e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||(i=this._history.next());break;case UI.KeyboardShortcut.Keys.Enter.code:this._enterKeyPressed(e);break;case UI.KeyboardShortcut.Keys.Tab.code:this.text()||e.consume()}void 0!==i&&(e.consume(!0),this.setText(i),s?this._editor.setSelection(TextUtils.TextRange.TextRange.createFromLocation(0,1/0)):this.moveCaretToEndOfPrompt())}async _enterWillEvaluate(){return!this._isCaretAtEndOfPrompt()||await ObjectUI.JavaScriptAutocomplete.JavaScriptAutocomplete.isExpressionComplete(this.text())}_updatePromptIcon(){this._iconThrottler.schedule(async()=>{const t=await this._enterWillEvaluate();this._promptIcon.classList.toggle("console-prompt-incomplete",!t)})}async _enterKeyPressed(t){if(t.altKey||t.ctrlKey||t.shiftKey)return;t.consume(!0),this.element.scrollIntoView(),this.clearAutocomplete();const e=this.text();e.length&&(await this._enterWillEvaluate()?await this._appendCommand(e,!0):this._editor.newlineAndIndent(),this._enterProcessedForTest())}async _appendCommand(t,e){this.setText("");const i=self.UI.context.flavor(SDK.RuntimeModel.ExecutionContext);if(i){const s=i,o=SDK.ConsoleModel.ConsoleModel.instance().addCommandMessage(s,t),r=ObjectUI.JavaScriptREPL.JavaScriptREPL.preprocessExpression(t);SDK.ConsoleModel.ConsoleModel.instance().evaluateCommandInConsole(s,o,r,e),ConsolePanel.instance().isShowing()&&Host.userMetrics.actionTaken(Host.UserMetrics.Action.CommandEvaluatedInConsolePanel)}}_enterProcessedForTest(){}_historyCompletions(t,e){const i=this.text();if(!this._addCompletionsFromHistory||!this._isCaretAtEndOfPrompt()||!i&&!e)return[];const s=[],o=new Set,r=this._history.historyData();for(let e=r.length-1;e>=0&&s.length<50;--e){const n=r[e];n.startsWith(i)&&(o.has(n)||(o.add(n),s.push({text:n.substring(i.length-t.length),iconType:"smallicon-text-prompt",isSecondary:!0})))}return s}focus(){this._editor?this._editor.widget().focus():this.element.focus()}async _wordsWithQuery(t,e,i){const s=this._editor.text(t),o=await this._defaultAutocompleteConfig.suggestionsCallback(t,e,i),r=this._historyCompletions(s,i);return o.concat(r)}_editorSetForTest(){}}export class ConsoleHistoryManager{constructor(){this._data=[],this._historyOffset=1}historyData(){return this._data}setHistoryData(t){this._data=t.slice(),this._historyOffset=1}pushHistoryItem(t){this._uncommittedIsTop&&(this._data.pop(),delete this._uncommittedIsTop),this._historyOffset=1,t!==this._currentHistoryItem()&&this._data.push(t)}_pushCurrentText(t){this._uncommittedIsTop&&this._data.pop(),this._uncommittedIsTop=!0,this._data.push(t)}previous(t){if(!(this._historyOffset>this._data.length))return 1===this._historyOffset&&this._pushCurrentText(t),++this._historyOffset,this._currentHistoryItem()}next(){if(1!==this._historyOffset)return--this._historyOffset,this._currentHistoryItem()}_currentHistoryItem(){return this._data[this._data.length-this._historyOffset]}}export const Events={TextChanged:Symbol("TextChanged")};