/**
 * Copyright 2019 Penn State University
 * @license Apache-2.0, see License.md for full text.
 */
import{LitElement as t,html as e,css as r}from"../../../../lit/index.js";import{SimpleToolbarBehaviors as i}from"../../../simple-toolbar/simple-toolbar.js";import{SimpleToolbarButtonBehaviors as o}from"../../../simple-toolbar/lib/simple-toolbar-button.js";import{RichTextStyles as s,RichTextToolbarStyles as n}from"../buttons/rich-text-editor-button.js";import{RichTextEditorRangeBehaviors as a}from"../singletons/rich-text-editor-range-behaviors.js";import"../singletons/rich-text-editor-prompt.js";import"../../../absolute-position-behavior/absolute-position-behavior.js";import*as u from"../../../../shadow-selection-polyfill/shadow.js";import{normalizeEventPath as d}from"../../../utils/utils.js";import"../buttons/rich-text-editor-source-code.js";import"../buttons/rich-text-editor-heading-picker.js";import"../buttons/rich-text-editor-symbol-picker.js";import"../buttons/rich-text-editor-emoji-picker.js";import"../buttons/rich-text-editor-underline.js";import"../buttons/rich-text-editor-image.js";import"../buttons/rich-text-editor-link.js";import"../buttons/rich-text-editor-unlink.js";globalThis.RichTextEditorToolbars=globalThis.RichTextEditorToolbars||[];const RichTextEditorToolbarBehaviors=function(t){return class extends(a(i(t))){static get tag(){return"rich-text-editor-toolbar"}static get miniStyles(){return[r`
          :host {
            position: relative;
            height: 0;
            margin: 0 auto;
            padding: 0;
            border: none;
            background-color: none;
          }
          #container {
            display: flex;
            position: absolute;
            bottom: 0;
            margin: 0 auto;
            padding: 0;
            border: var(--rich-text-editor-border-width, 1px) solid
              var(--rich-text-editor-border-color, #ddd);
            background-color: var(
              --rich-text-editor-bg,
              var(--rich-text-editor-bg, #ffffff)
            );
          }
        `]}static get baseStyles(){return[...super.baseStyles,...s,r`
          :host {
            border: var(--rich-text-editor-border-width, 1px) solid
              var(--rich-text-editor-border-color, #ddd);
            background-color: var(--rich-text-editor-bg, #ffffff);
          }
          #morebutton::part(button) {
            border-radius: var(
              --rich-text-editor-button-disabled-border-radius,
              0px
            );
          }
        `]}static get styles(){return[...this.baseStyles,...super.stickyStyles]}get undoButton(){return{command:"undo",icon:"undo",label:"Undo",shortcutKeys:"ctrl+z",type:"rich-text-editor-button"}}get redoButton(){return{command:"redo",icon:"redo",label:"Redo",shortcutKeys:"ctrl+shift+z",type:"rich-text-editor-button"}}get historyButtonGroup(){return{type:"button-group",subtype:"history-button-group",buttons:[this.undoButton,this.redoButton]}}get formatButton(){return{label:"Format",type:"rich-text-editor-heading-picker"}}get boldButton(){return{command:"bold",icon:"editor:format-bold",label:"Bold",shortcutKeys:"ctrl+b",toggles:!0,type:"rich-text-editor-button"}}get italicButton(){return{command:"italic",icon:"editor:format-italic",label:"Italics",shortcutKeys:"ctrl+i",toggles:!0,type:"rich-text-editor-button"}}get underlineButton(){return{type:"rich-text-editor-underline"}}get strikethroughButton(){return{command:"strikeThrough",icon:"editor:format-strikethrough",label:"Strike Through",type:"rich-text-editor-button"}}get removeFormatButton(){return{command:"removeFormat",icon:"editor:format-clear",label:"Erase Format",type:"rich-text-editor-button"}}get codeButton(){return{command:"wrapRange",commandVal:"CODE",toggles:!0,label:"Code",type:"rich-text-editor-button"}}get markButton(){return{command:"wrapRange",commandVal:"MARK",toggles:!0,label:"Mark",type:"rich-text-editor-button"}}get abbrButton(){return{command:"wrapRange",commandVal:"ABBR",toggles:!0,label:"Abbr",type:"rich-text-editor-button"}}get basicInlineButtonGroup(){return{type:"button-group",subtype:"basic-inline-button-group",buttons:[this.formatButton,this.boldButton,this.italicButton,this.removeFormatButton]}}get linkButton(){return{icon:"link",label:"Link",shortcutKeys:"ctrl+k",type:"rich-text-editor-link"}}get unlinkButton(){return{icon:"mdextra:unlink",label:"Remove Link",type:"rich-text-editor-unlink"}}get linkButtonGroup(){return{type:"button-group",subtype:"link-button-group",buttons:[this.linkButton,this.unlinkButton]}}get cutButton(){return{command:"cut",icon:"content-cut",label:"Cut",shortcutKeys:"ctrl+x",type:"rich-text-editor-button"}}get copyButton(){return{command:"copy",icon:"content-copy",label:"Copy",shortcutKeys:"ctrl+c",type:"rich-text-editor-button"}}get pasteButton(){return{command:"paste",icon:"content-paste",label:"Paste",shortcutKeys:"ctrl+v",type:"rich-text-editor-button"}}get clipboardButtonGroup(){return{type:"button-group",subtype:"clipboard-button-group",buttons:[this.cutButton,this.copyButton,this.pasteButton]}}get subscriptButton(){return{command:"subscript",icon:"mdextra:subscript",label:"Subscript",radio:!0,type:"rich-text-editor-button"}}get superscriptButton(){return{command:"superscript",icon:"mdextra:superscript",label:"Superscript",radio:!0,type:"rich-text-editor-button"}}get scriptButtonGroup(){return{type:"simple-toolbar-button-group",subtype:"script-button-group","aria-label":"Subscript and Superscript",buttons:[this.subscriptButton,this.superscriptButton]}}get symbolButton(){return{symbolTypes:["symbols"],type:"rich-text-editor-symbol-picker"}}get iconButton(){return{type:"rich-text-editor-icon-picker"}}get emojiButton(){return{type:"rich-text-editor-emoji-picker"}}get imageButton(){return{type:"rich-text-editor-image"}}get insertButtonGroup(){return{type:"button-group",subtype:"insert-button-group",buttons:[this.imageButton,this.symbolButton]}}get advancedInsertButtonGroup(){return{type:"button-group",subtype:"advanced-insert-button-group",buttons:[this.emojiButton]}}get justifyLeftButton(){return{command:"justifyLeft",icon:"editor:format-align-left",label:"Align Left",radio:!0,type:"rich-text-editor-button"}}get justifyCenterButton(){return{command:"justifyCenter",icon:"editor:format-align-center",label:"Align Center",radio:!0,type:"rich-text-editor-button"}}get justifyRightButton(){return{command:"justifyRight",icon:"editor:format-align-right",label:"Align Right",radio:!0,type:"rich-text-editor-button"}}get justifyFullButton(){return{command:"justifyFull",icon:"editor:format-align-justify",label:"Justify",radio:!0,type:"rich-text-editor-button"}}get justifyButtonGroup(){return{type:"simple-toolbar-button-group",subtype:"advanced-insert-button-group","aria-label":"Text Alignment",required:!0,buttons:[this.justifyLeftButton,this.justifyCenterButton,this.justifyRightButton,this.justifyFullButton]}}get orderedListButton(){return{command:"insertOrderedList",icon:"editor:format-list-numbered",label:"Ordered List",radio:!0,type:"rich-text-editor-button"}}get unorderedListButton(){return{command:"insertUnorderedList",icon:"editor:format-list-bulleted",label:"Unordered List",radio:!0,type:"rich-text-editor-button"}}get blockquoteButton(){return{command:"formatBlock",commandVal:"blockquote",label:"Blockquote",icon:"editor:format-quote",shortcutKeys:"ctrl+'",toggles:!0,type:"rich-text-editor-button"}}get indentButton(){return{command:"indent",icon:"editor:format-indent-increase",label:"Increase Indent",shortcutKeys:"ctrl+]",type:"rich-text-editor-button"}}get outdentButton(){return{command:"outdent",icon:"editor:format-indent-decrease",label:"Decrease Indent",shortcutKeys:"ctrl+[",type:"rich-text-editor-button"}}get listButtonGroup(){return{type:"simple-toolbar-button-group",subtype:"list-button-group","aria-label":"List Type",buttons:[this.orderedListButton,this.unorderedListButton]}}get listIndentButtonGroup(){return{type:"button-group",subtype:"list-indent-button-group",buttons:[this.listButtonGroup,this.blockquoteButton,this.indentButton,this.outdentButton]}}get saveButton(){return{command:"save",icon:"save",label:"Save",type:"rich-text-editor-button"}}get closeButton(){return{command:"cancel",icon:"close",label:"Cancel",type:"rich-text-editor-button"}}get saveCloseButtonGroup(){return{type:"button-group",subtype:"save-close-button-group",buttons:[this.saveButton]}}get sourceButton(){return{type:"rich-text-editor-source-code"}}get sourceButtonGroup(){return{type:"button-group",subtype:"source-button-group",buttons:[this.sourceButton]}}get defaultConfig(){return[this.historyButtonGroup,this.basicInlineButtonGroup,this.linkButtonGroup,this.clipboardButtonGroup,this.scriptButtonGroup,this.insertButtonGroup,this.listIndentButtonGroup]}get miniConfig(){return[{type:"button-group",buttons:[this.boldButton,this.italicButton,this.removeFormatButton]},this.linkButtonGroup,this.scriptButtonGroup,{type:"button-group",buttons:[this.orderedListButton,this.unorderedListButton]}]}get miniTemplate(){return e` <div id="container">${super.toolbarTemplate}</div> `}get toolbarTemplate(){return super.toolbarTemplate}render(){return this.toolbarTemplate}static get properties(){return{...super.properties,breadcrumbsLabel:{name:"breadcrumbsLabel",type:String,attribute:"breadcrumbs-label"},breadcrumbsSelectAllLabel:{name:"breadcrumbsSelectAllLabel",type:String,attribute:"breadcrumbs-select-all-label"},target:{name:"target",type:Object},id:{name:"id",type:String,attribute:"id",reflect:!0},savedSelection:{name:"savedSelection",type:Object},registered:{type:Boolean},selectedNode:{type:Object},selectionAncestors:{type:Array},show:{type:String,attribute:"show",reflect:!0},clickableElements:{name:"clickableElements",type:Object},__canceledEdits:{type:Object},__pasteDisabled:{name:"__pasteDisabled",type:Boolean,attribute:"paste-disabled",reflect:!0},__prompt:{type:Object},__promptOpen:{name:"__promptOpen",type:Boolean}}}constructor(){super(),this.windowControllers=new AbortController,this.config=this.defaultConfig,this.clickableElements={},this.breadcrumbsLabel="Select",this.breadcrumbsSelectAllLabel="All",this.__toolbar=this,globalThis.document.addEventListener(u.eventName,this._handleTargetSelection.bind(this.__toolbar),{signal:this.windowControllers.signal}),this.addEventListener("mousedown",(t=>t.stopImmediatePropagation()))}connectedCallback(){super.connectedCallback(),globalThis.RichTextEditorToolbars.push(this)}disconnectedCallback(){this.windowControllers.abort(),globalThis.RichTextEditorToolbars=globalThis.RichTextEditorToolbars.filter((t=>t!==this)),super.disconnectedCallback()}firstUpdated(t){this.id||(this.id=this._generateUUID()),super.firstUpdated(t),this.hasBreadcrumbs&&this.editor&&this.positionByTarget(this.editor),this.__prompt=globalThis.RichTextEditorPrompt.requestAvailability(),this.__prompt.addEventListener("open",(t=>{this.__promptOpen=!0})),this.__prompt.addEventListener("close",(t=>{this.__promptOpen=!1})),this.onmousedown=this._addHighlight,this.onkeydown=this._addHighlight}updated(t){super.updated(t),t.forEach(((t,e)=>{"range"===e&&this._rangeChanged(this.range,t),"config"===e&&this.updateToolbar(),"editor"===e&&this._editorChange(),["editor","show","range"].includes(e)&&(this.hidden=this.disconnected),["breadcrumbs","sticky"].includes(e)&&this.breadcrumbs&&(this.breadcrumbs.sticky=this.sticky)}))}get controls(){let t=this.target?this.target.getAttribute("id"):void 0;return this.target&&this.setAttribute("controls",t),t}get disconnected(){return"always"!=this.show&&("selection"!=this.show?!this.target:this.noSelection)}get noSelection(){return!this.range||this.range.collapsed}get observer(){return new MutationObserver(this._handleTargetMutation.bind(this))}get isRangeInScope(){return this.range&&this.target&&this.rangeNodeOrParentNode(this.range)&&this.target.contains(this.rangeNodeOrParentNode(this.range))}cancel(){this.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,cancelable:!0,composed:!0,detail:this}))}close(){this.target=void 0,this.positionByTarget(!1),this.dispatchEvent(new CustomEvent("close",{bubbles:!0,cancelable:!0,composed:!0,detail:this}))}_editorChanged(){this.dispatchEvent(new CustomEvent("editor-change",{bubbles:!0,cancelable:!0,composed:!0,detail:this}))}getRange(){let shadowRoot=t=>{let e=t.parentNode;return e?shadowRoot(e):t};try{this.range=shadowRoot(this.target)?u.getRange(shadowRoot(this.target)):void 0}catch(t){this.range=void 0}return this.range}getSelection(){return window,getSelection()}updateRange(t,e=this.range){t&&(t.range||(t.range=e))}_rangeChanged(t,e){this._updateButtonRanges(),this.dispatchEvent(new CustomEvent("range-changed",{bubbles:!0,composed:!0,cancelable:!0,detail:this}))}clearToolbar(){super.clearToolbar&&super.clearToolbar(),this.clickableElements={}}deregisterButton(t){super.deregisterButton&&super.deregisterButton(t),(t.tagsArray||[]).forEach((t=>delete this.clickableElements[t]))}registerButton(t){super.registerButton&&super.registerButton(t),"paste"!==t.command||navigator.clipboard?(t.__toolbar=this,t.disabled=!this.target,(t.tagsArray||[]).forEach((e=>{t.tagClickCallback&&(this.clickableElements[e]=t)}))):t.remove()}_addBreadcrumbs(){return this.breadcrumbs||(this.breadcrumbs=globalThis.document.createElement("rich-text-editor-breadcrumbs"),globalThis.document.body.appendChild(this.breadcrumbs)),this.breadcrumbs.label=this.breadcrumbsLabel,this.breadcrumbs}_generateUUID(){let t=Math.floor(65536*(1+Math.random())).toString(16).substring(1);return"rte-"+"ss-s-s-s-sss".replace(/s/g,t)}_handleButtonUpdate(t){super._handleButtonUpdate&&super._handleButtonUpdate(t)}_renderButtonGroup(t){let e=super._renderButtonGroup(t);return t.subtype&&e.classList.add(t.subtype),e}_updateButtonRanges(){if(this.isRangeInScope){let t=[],getParentNode=e=>{"rich-text-editor-highlight"!==(e.tagName||"").toLowerCase()&&t.push(e),e.parentNode&&e.parentNode!==this.target&&getParentNode(e.parentNode)};this.rangeNodeOrParentNode(this.range)!==this.target&&getParentNode(this.rangeNodeOrParentNode(this.range)),t.push({nodeName:this.breadcrumbsSelectAllLabel,selectAll:this.target}),this.selectedNode=t[0],this.selectionAncestors=t.reverse(),(this.buttons||[]).forEach((t=>{t.range=void 0,t.range=this.range,t.selectedNode=this.selectedNode,t.selectionAncestors=this.selectionAncestors})),this.breadcrumbs&&(this.breadcrumbs.selectionAncestors=this.selectionAncestors,this.breadcrumbs.hidden=this.disconnected,this.breadcrumbs.editor=this.editor)}}cancelEdits(t=this.target){this.revertTarget(t),this.target(editor,!1)}get enabledTargetHandlers(){return{keydown:this._removeHighlight.bind(this),keypress:this._handleTargetKeypress.bind(this),mousedown:this._removeHighlight.bind(this),mouseup:this._addHighlight.bind(this)}}positionByTarget(t){t?(t.parentNode.insertBefore(this,t),this.slot=t.slot,this.hasBreadcrumbs&&(this.breadcrumbs=this.breadcrumbs||this._addBreadcrumbs(),this.target.parentNode.insertBefore(this.breadcrumbs,this.target.nextSibling),this.breadcrumbs.slot=t.slot)):(globalThis.document.body.append(this),this.slot=void 0,this.breadcrumbs&&(globalThis.document.body.append(this.breadcrumbs),this.breadcrumbs.slot=void 0))}enableEditing(t=this.editor){let e=this.enabledTargetHandlers;!t||t.hidden||t.disabled||(t.makeSticky&&t.makeSticky(this.sticky),this.positionByTarget(t),t&&t.setAttribute&&t.setAttribute("contenteditable","true"),Object.keys(e).forEach((r=>t.removeEventListener(r,e[r]))),this.setCanceledEdits(),this.updateRange(t),this.observeChanges(!0),this.getRoot(t).onselectionchange=e=>{this.__promptOpen||this.updateRange(t,this.getRange())},this.dispatchEvent(new CustomEvent("enabled",{bubbles:!0,composed:!0,cancelable:!0,detail:(this.target.innerHTML||"").replace(/<!--[^(-->)]*-->/g,"").trim()})))}disableEditing(t=this.target){let e=this.enabledTargetHandlers,r=this.getRange();t&&(r&&r.collapse(!1),this.__highlight.emptyContents(),this.getRoot(t).onselectionchange=void 0,this.observeChanges(!1),this.__source&&this.__source.toggle(!1),t&&t.removeAttribute&&t.removeAttribute("contenteditable"),Object.keys(e).forEach((r=>t.removeEventListener(r,e[r]))),t.makeSticky&&t.makeSticky(!1),this.dispatchEvent(new CustomEvent("disabled",{bubbles:!0,composed:!0,cancelable:!0,detail:(this.target.innerHTML||"").replace(/<!--[^(-->)]*-->/g,"").trim()})))}insertNew(t){let e=globalThis.document.createElement("rich-text-editor");t.parentNode.insertBefore(e,t),e.appendChild(t)}observeChanges(t=!0){t?this.observer.observe(this.target,{attributes:!1,childList:!0,subtree:!0,characterData:!1}):this.observer&&this.observer.disconnect}revertTarget(t=this.target){this.target&&(this.target.innerHTML=this.__canceledEdits)}sanitizeHTML(t=""){let e="<body(.*\n)*>(.*\n)*</body>";return t.match(e)&&t.match(e).length>0&&(t=t.match(e)[0].replace(/<\?body(.*\n)*\>/i)),t}setCanceledEdits(t){this.__canceledEdits=t||(this.target&&this.target.innerHTML?this.target.innerHTML:"")}setTarget(t){let e=this.targetHandlers(t),r=this.target;t&&(r&&r.getAttribute&&"textbox"==r.getAttribute("role")&&r.removeAttribute("role"),t&&t.setAttribute&&t.setAttribute("role","textbox"),r!==t&&(r&&this.unsetTarget(r),Object.keys(e).forEach((r=>t.addEventListener(r,e[r]))),this.getRoot(t).onselectionchange=e=>{this.__promptOpen||this.updateRange(t,this.getRange())},this.target=t,this.enableEditing(t))),this.updateRange(this.target),this.breadcrumbs&&(this.breadcrumbs.controls=this.controls),this.buttons.forEach((t=>{"close"!==t.command&&(t.disabled=!this.target)})),t!==r&&(this.range=void 0,this._rangeChanged())}unsetTarget(t=this.target){let e=this.targetHandlers(t);this.disableEditing(t),Object.keys(e).forEach((r=>t.removeEventListener(r,e[r]))),this.target=void 0}targetEmpty(){return!this.target||!this.target.innerHTML||""==this.trimHTML(this.target)}targetHandlers(t){return{dblclick:e=>this._handleTargetClick(t,e),focus:e=>this._handleTargetFocus(t,e),keydown:t=>this._handleShortcutKeys(t),paste:t=>this._handlePaste(t)}}get targetHTML(){return this.target?this.outdentHTML(this.target.innerHTML):void 0}htmlMatchesTarget(t){let e=t?this.outdentHTML(t):void 0,r=e?e.replace(/\s+/gm,""):void 0,i=this.targetHTML?this.targetHTML.replace(/\s+/gm,""):void 0;return r&&i&&i.localeCompare(r)}_handleTargetClick(t,e){let r=d(e);if(t&&!t.disabled){if(this.target!==t)e.preventDefault(),this.setTarget(t);else{let t=Object.keys(this.clickableElements||{}),i=!1;r.forEach((o=>{if(i)return;let s=(o.tagName||"").toLowerCase();s&&t.includes(s)&&(i=!0,e.preventDefault(),this.clickableElements[s].tagClickCallback({...e,detail:o,eventPath:r}))}))}this.range=this.getRange(),this.updateRange()}}_handleTargetFocus(t,e){this.__promptOpen||t.disabled||this.setTarget(t)}_handleTargetKeypress(t){this.targetEmpty()&&t.key&&(this.innerHTML=t.key.replace(">","&gt;").replace("<","&lt;").replace("&","&amp;"),this.range=this.getRange(),this.range.selectNodeContents(this),this.range.collapse())}_handleTargetMutation(t=[]){this._handleTargetSelection(),(t||[]).forEach((t=>{"attributes"==t.type&&((target.disabled||target.hidden)&&target.conteneditable?(this.disableEditing(target),target.tabindex=-1):target.disabled||target.hidden||!target.conteneditable||(this.enableEditing(target),target.tabindex=0))}))}_handleTargetSelection(t){this.__promptOpen||(this.range=this.getRange())}_handlePaste(t){t.stopImmediatePropagation(),this.pasteFromClipboard()}_addHighlight(){this.__highlight.hidden&&(this.range=this.getRange(),this.target&&"true"!=!this.target.getAttribute("contenteditable")&&this.__highlight.wrap(this.range||this.getRange()))}_removeHighlight(){this.__highlight.unwrap(this.range||this.getRange())}}};class RichTextEditorToolbar extends(RichTextEditorToolbarBehaviors(t)){}customElements.define(RichTextEditorToolbar.tag,RichTextEditorToolbar);export{RichTextEditorToolbar,RichTextEditorToolbarBehaviors};