import*as Formatter from"../formatter/formatter.js";import*as i18n from"../i18n/i18n.js";import*as Persistence from"../persistence/persistence.js";import*as UI from"../ui/ui.js";import{Events,registerEditorAction}from"./SourcesView.js";const UIStrings={formatS:"Format {PH1}",format:"Format"},str_=i18n.i18n.registerUIStrings("sources/InplaceFormatterEditorAction.js",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_);let inplaceFormatterEditorActionInstance;export class InplaceFormatterEditorAction{constructor(){this._button,this._sourcesView}static instance(t={forceNew:null}){const{forceNew:e}=t;return inplaceFormatterEditorActionInstance&&!e||(inplaceFormatterEditorActionInstance=new InplaceFormatterEditorAction),inplaceFormatterEditorActionInstance}_editorSelected(t){const e=t.data;this._updateButton(e)}_editorClosed(t){t.data.wasSelected&&this._updateButton(null)}_updateButton(t){const e=this._isFormattable(t);this._button.element.classList.toggle("hidden",!e),t&&e&&this._button.setTitle(i18nString(UIStrings.formatS,{PH1:t.name()}))}button(t){return this._button||(this._sourcesView=t,this._sourcesView.addEventListener(Events.EditorSelected,this._editorSelected.bind(this)),this._sourcesView.addEventListener(Events.EditorClosed,this._editorClosed.bind(this)),this._button=new UI.Toolbar.ToolbarButton(i18nString(UIStrings.format),"largeicon-pretty-print"),this._button.addEventListener(UI.Toolbar.ToolbarButton.Events.Click,this._formatSourceInPlace,this),this._updateButton(t.currentUISourceCode())),this._button}_isFormattable(t){return!!t&&(!!t.project().canSetFileContent()||(!!Persistence.Persistence.PersistenceImpl.instance().binding(t)||t.contentType().isStyleSheet()))}_formatSourceInPlace(t){const e=this._sourcesView.currentUISourceCode();e&&this._isFormattable(e)&&(e.isDirty()?this._contentLoaded(e,e.workingCopy()):e.requestContent().then((t=>{this._contentLoaded(e,t.content||"")})))}_contentLoaded(t,e){const o=t.mimeType();Formatter.ScriptFormatter.FormatterInterface.format(t.contentType(),o,e,(async(e,o)=>{this._formattingComplete(t,e,o)}))}_formattingComplete(t,e,o){if(t.workingCopy()===e)return;const r=this._sourcesView.viewForFile(t);let i=[0,0];if(r){const t=r.selection();i=o.originalToFormatted(t.startLine,t.startColumn)}t.setWorkingCopy(e),this._sourcesView.showSourceLocation(t,i[0],i[1])}}registerEditorAction(InplaceFormatterEditorAction.instance);