import*as ARIAUtils from"./ARIAUtils.js";import{Keys}from"./KeyboardShortcut.js";import{ElementFocusRestorer,markBeingEdited}from"./UIUtils.js";let _defaultInstance=null;export class InplaceEditor{static startEditing(e,t){return _defaultInstance||(_defaultInstance=new InplaceEditor),_defaultInstance.startEditing(e,t)}editorContent(e){const t=e.element;return"INPUT"===t.tagName&&"text"===t.type?t.value:t.textContent||""}setUpEditor(e){const t=e.element;t.classList.add("editing"),t.setAttribute("contenteditable","plaintext-only");const n=t.getAttribute("role");ARIAUtils.markAsTextBox(t),e.oldRole=n;const o=t.tabIndex;("number"!==typeof o||o<0)&&(t.tabIndex=0),this._focusRestorer=new ElementFocusRestorer(t),e.oldTabIndex=o}closeEditor(e){const t=e.element;t.classList.remove("editing"),t.removeAttribute("contenteditable"),"string"!==typeof e.oldRole?t.removeAttribute("role"):t.setAttribute("role",e.oldRole),"number"!==typeof e.oldTabIndex?t.removeAttribute("tabIndex"):t.tabIndex=e.oldTabIndex,t.scrollTop=0,t.scrollLeft=0}cancelEditing(e){const t=e.element;"INPUT"===t.tagName&&"text"===t.type?t.value=e.oldText||"":t.textContent=e.oldText}startEditing(e,t){if(!markBeingEdited(e,!0))return null;const n=t||new Config((function(){}),(function(){})),o={element:e,config:n,oldRole:null,oldTabIndex:null,oldText:null},r=n.commitHandler,i=n.cancelHandler,s=n.pasteHandler,l=n.context;let d="";const a=this;function c(t){n.blurHandler&&!n.blurHandler(e,t)||f.call(e)}function u(){markBeingEdited(e,!1),e.removeEventListener("blur",c,!1),e.removeEventListener("keydown",x,!0),s&&e.removeEventListener("paste",p,!0),a._focusRestorer&&a._focusRestorer.restore(),a.closeEditor(o)}function m(){a.cancelEditing(o),u(),i(this,l)}function f(){u(),r(this,a.editorContent(o),o.oldText||"",l,d)}function b(t,n){"commit"===t?(f.call(e),n.consume(!0)):"cancel"===t?(m.call(e),n.consume(!0)):t&&t.startsWith("move-")&&(d=t.substring(5),"Tab"===n.key&&n.consume(!0),c())}function p(e){if(!s)return;b(s(e),e)}function x(e){let t=function(e){return"Enter"===e.key?"commit":e.keyCode===Keys.Esc.code||"Escape"===e.key?"cancel":"Tab"===e.key?"move-"+(e.shiftKey?"backward":"forward"):""}(e);if(!t&&n.postKeydownFinishHandler){const o=n.postKeydownFinishHandler(e);o&&(t=o)}b(t,e)}this.setUpEditor(o),o.oldText=this.editorContent(o),e.addEventListener("blur",c,!1),e.addEventListener("keydown",x,!0),void 0!==s&&e.addEventListener("paste",p,!0);return{cancel:m.bind(e),commit:f.bind(e)}}}export class Config{constructor(e,t,n,o){this.commitHandler=e,this.cancelHandler=t,this.context=n,this.blurHandler=o,this.pasteHandler,this.postKeydownFinishHandler}setPasteHandler(e){this.pasteHandler=e}setPostKeydownFinishHandler(e){this.postKeydownFinishHandler=e}}export let EventHandler;export let Controller;export let EditingContext;