import*as Common from"../common/common.js";import*as UI from"../ui/ui.js";import{ColorSwatch}from"./ColorSwatch.js";export class SwatchPopoverHelper extends Common.ObjectWrapper.ObjectWrapper{constructor(){super(),this._popover=new UI.GlassPane.GlassPane,this._popover.registerRequiredCSS("inline_editor/swatchPopover.css",{enableLegacyPatching:!1}),this._popover.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent),this._popover.setMarginBehavior(UI.GlassPane.MarginBehavior.Arrow),this._popover.element.addEventListener("mousedown",(e=>e.consume()),!1),this._hideProxy=this.hide.bind(this,!0),this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundFocusOut=this._onFocusOut.bind(this),this._isHidden=!0,this._anchorElement=null}_onFocusOut(e){const t=e.relatedTarget;!this._isHidden&&t&&this._view&&!t.isSelfOrDescendant(this._view.contentElement)&&this._hideProxy()}isShowing(){return this._popover.isShowing()}show(e,t,o){if(this._popover.isShowing()){if(this._anchorElement===t)return;this.hide(!0)}this.dispatchEventToListeners(Events.WillShowPopover),this._isHidden=!1,this._anchorElement=t,this._view=e,this._hiddenCallback=o,this.reposition(),e.focus();const i=this._popover.element.ownerDocument;i.addEventListener("mousedown",this._hideProxy,!1),i.defaultView&&i.defaultView.addEventListener("resize",this._hideProxy,!1),this._view.contentElement.addEventListener("keydown",this._boundOnKeyDown,!1)}reposition(){if(!this._isHidden&&this._view){if(this._view.contentElement.removeEventListener("focusout",this._boundFocusOut,!1),this._view.show(this._popover.contentElement),this._anchorElement){let e=this._anchorElement.boxInWindow();if(ColorSwatch.isColorSwatch(this._anchorElement)){const t=this._anchorElement;if(!t.anchorBox)return;e=t.anchorBox}this._popover.setContentAnchorBox(e),this._popover.show(this._anchorElement.ownerDocument)}this._view.contentElement.addEventListener("focusout",this._boundFocusOut,!1),this._focusRestorer||(this._focusRestorer=new UI.Widget.WidgetFocusRestorer(this._view))}}hide(e){if(this._isHidden)return;const t=this._popover.element.ownerDocument;this._isHidden=!0,this._popover.hide(),t.removeEventListener("mousedown",this._hideProxy,!1),t.defaultView&&t.defaultView.removeEventListener("resize",this._hideProxy,!1),this._hiddenCallback&&this._hiddenCallback.call(null,Boolean(e)),this._focusRestorer&&this._focusRestorer.restore(),this._anchorElement=null,this._view&&(this._view.detach(),this._view.contentElement.removeEventListener("keydown",this._boundOnKeyDown,!1),this._view.contentElement.removeEventListener("focusout",this._boundFocusOut,!1),delete this._view)}_onKeyDown(e){const t=e;if("Enter"===t.key)return this.hide(!0),void t.consume(!0);"Escape"===t.key&&(this.hide(!1),t.consume(!0))}}export const Events={WillShowPopover:Symbol("WillShowPopover")};