CVE-2023-2817 (published 2023-05-26T17:15Z)

A post-authentication stored cross-site scripting vulnerability exists in Craft CMS versions <= 4.4.11. HTML, including script tags can be injected into field names which, when the field is added to a category or section, will trigger when users visit the Categories or Entries pages respectively.

CVSS v3 base score: 5.4, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/craftcms/cms
commit_details: repo_url: https://github.com/craftcms/cms
author: brandonkelly
author_date: 2023-05-18 12:31:35-07:00
msg: Fixed XSS vulnerabilities
repository: repo_url: https://github.com/craftcms/cms
repo_name: craftcms/cms
description: Build bespoke content experiences with Craft.
repo_language: PHP
owner: craftcms
file_changes: filename: CHANGELOG.md
change_type: ModificationType.MODIFY
diff: @@ -6,6 +6,7 @@
 - Fixed a bug where reverting an entry’s content from a revision could omit some Matrix blocks.
 - Fixed an error that could occur when adding a new site to an entry which contained Matrix blocks, if the same site had been added and removed previously.
 - Fixed a bug where Matrix blocks nested within Neo or Super Table fields could be omitted when propagating an entry to a new site. ([#13207](https://github.com/craftcms/cms/issues/13207))
+- Fixed two XSS vulnerabilities.
 
 ## 4.4.11 - 2023-05-15
 

programming_language: Markdown
filename: cp.js
change_type: ModificationType.MODIFY
diff: @@ -1,2 +1,2 @@
-(function(){var __webpack_modules__={463:function(){Craft.Accordion=Garnish.Base.extend({$trigger:null,targetSelector:null,_$target:null,init:function(t){var e=this;this.$trigger=$(t),this.$trigger.data("accordion")&&(console.warn("Double-instantiating an accordion trigger on an element"),this.$trigger.data("accordion").destroy()),this.$trigger.data("accordion",this),this.targetSelector=this.$trigger.attr("aria-controls")?"#".concat(this.$trigger.attr("aria-controls")):null,this.targetSelector&&(this._$target=$(this.targetSelector)),this.addListener(this.$trigger,"click","onTriggerClick"),this.addListener(this.$trigger,"keypress",(function(t){var i=t.keyCode;i!==Garnish.SPACE_KEY&&i!==Garnish.RETURN_KEY||(t.preventDefault(),e.onTriggerClick())}))},onTriggerClick:function(){"true"===this.$trigger.attr("aria-expanded")?this.hideTarget(this._$target):this.showTarget(this._$target)},showTarget:function(t){var e=this;if(t&&t.length){this.showTarget._currentHeight=t.height(),t.removeClass("hidden"),this.$trigger.removeClass("collapsed").addClass("expanded").attr("aria-expanded","true");for(var i=0;i<t.length;i++)!function(t){"SPAN"!==t.prop("nodeName")&&(t.height("auto"),e.showTarget._targetHeight=t.height(),t.css({height:e.showTarget._currentHeight,overflow:"hidden"}),t.velocity("stop"),t.velocity({height:e.showTarget._targetHeight},Garnish.getUserPreferredAnimationDuration("fast"),(function(){t.css({height:"",overflow:""})})))}(t.eq(i));delete this.showTarget._targetHeight,delete this.showTarget._currentHeight,Garnish.$win.trigger("resize")}},hideTarget:function(t){if(t&&t.length){this.$trigger.removeClass("expanded").addClass("collapsed").attr("aria-expanded","false");for(var e=0;e<t.length;e++)!function(t){t.hasClass("hidden")||("SPAN"===t.prop("nodeName")?t.addClass("hidden"):(t.css("overflow","hidden"),t.velocity("stop"),t.velocity({height:0},Garnish.getUserPreferredAnimationDuration("fast"),(function(){t.addClass("hidden")}))))}(t.eq(e))}},destroy:function(){this.$trigger.removeData("accordion"),this.base()}})},3839:function(){Craft.AddressesInput=Garnish.Base.extend({$container:null,$addBtn:null,$addBtnItem:null,$cards:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.AddressesInput.defaults),this.$container.data("addresses")&&(console.warn("Double-instantiating an address input on an element"),this.$container.data("addresses").destroy()),this.$container.data("addresses",this),this.$addBtn=this.$container.find(".address-cards__add-btn"),this.$addBtnItem=this.$addBtn.closest("li"),this.$cards=this.$container.find("> .address-card");for(var s=0;s<this.$cards.length;s++)this.initCard(this.$cards.eq(s));this.updateAddButton(),this.addListener(this.$addBtn,"click",(function(){i.createAddress()}))},initCard:function(t){var e=this;this.addListener(t,"click",(function(i){$(i.target).closest(".menubtn").length||e.editAddress(t)}));var i=t.find(".menubtn").disclosureMenu();if(i.length){var s=i.data("trigger"),n=s.$container,a=n.find('[data-action="edit"]');this.addListener(a,"click",(function(i){i.stopPropagation(),e.editAddress(t)}));var r=n.find('[data-action="delete"]');this.addListener(r,"click",(function(i){if(i.preventDefault(),i.stopPropagation(),confirm(Craft.t("app","Are you sure you want to delete this address?"))){e.$addBtn.addClass("loading");var a=t.data("id"),r=t.data("draft-id");Craft.sendActionRequest("POST","elements/delete",{data:{elementId:a,draftId:r}}).then((function(){t.remove(),n.remove(),s.destroy(),e.$cards=e.$cards.not(t),e.updateAddButton(),e.trigger("deleteAddress",{addressId:a,draftId:r})})).finally((function(){e.$addBtn.removeClass("loading")}))}}))}},editAddress:function(t,e){var i=this;Craft.createElementEditor("craft\\elements\\Address",t,e).on("submit",(function(e){i.trigger("saveAddress",{data:e.data}),Craft.sendActionRequest("POST","addresses/card-html",{data:{addressId:e.data.id}}).then((function(e){var s=$(e.data.html);t?(t.replaceWith(s),i.$cards=i.$cards.not(t)):s.insertBefore(i.$addBtnItem),Craft.initUiElements(s),i.initCard(s),i.$cards=i.$cards.add(s),i.updateAddButton()}))}))},updateAddButton:function(){this.canCreateAddress()?this.$addBtn.removeClass("hidden"):this.$addBtn.addClass("hidden")},canCreateAddress:function(){return!this.settings.maxAddresses||this.$cards.length<this.settings.maxAddresses},createAddress:function(){var t=this;if(!this.canCreateAddress())throw"No more addresses can be created.";this.$addBtn.addClass("loading"),Craft.sendActionRequest("POST","elements/create",{data:{elementType:"craft\\elements\\Address",ownerId:this.settings.ownerId}}).then((function(e){t.editAddress(null,{elementId:e.data.element.id,draftId:e.data.element.draftId})})).finally((function(){t.$addBtn.removeClass("loading")}))},destroy:function(){this.$container.removeData("addresses"),this.base()}},{ownerId:null,defaults:{maxAddresses:null}})},7452:function(){Craft.AdminTable=Garnish.Base.extend({settings:null,totalItems:null,sorter:null,$noItems:null,$table:null,$tbody:null,$deleteBtns:null,init:function(t){var e=this;this.setSettings(t,Craft.AdminTable.defaults),this.settings.allowDeleteAll||(this.settings.minItems=1),this.$noItems=$(this.settings.noItemsSelector),this.$table=$(this.settings.tableSelector),this.$tbody=this.$table.children("tbody"),this.totalItems=this.$tbody.children().length,this.settings.sortable&&(this.sorter=new Craft.DataTableSorter(this.$table,{onSortChange:this.reorderItems.bind(this)})),this.$deleteBtns=this.$table.find(".delete:not(.disabled)"),this.addListener(this.$deleteBtns,"click","handleDeleteBtnClick"),this.addListener(this.$deleteBtns,"keydown",(function(t){t.keyCode!==Garnish.SPACE_KEY&&t.keyCode!==Garnish.RETURN_KEY||(t.preventDefault(),e.handleDeleteBtnClick(t))})),this.updateUI()},addRow:function(t){if(!(this.settings.maxItems&&this.totalItems>=this.settings.maxItems)){var e=$(t).appendTo(this.$tbody),i=e.find(".delete");this.settings.sortable&&this.sorter.addItems(e),this.$deleteBtns=this.$deleteBtns.add(i),this.addListener(i,"click","handleDeleteBtnClick"),this.totalItems++,this.updateUI()}},reorderItems:function(){var t=this;if(this.settings.sortable){for(var e=[],i=0;i<this.sorter.$items.length;i++){var s=$(this.sorter.$items[i]).attr(this.settings.idAttribute);e.push(s)}var n={ids:JSON.stringify(e)};Craft.sendActionRequest("POST",this.settings.reorderAction,{data:n}).then((function(i){t.onReorderItems(e),Craft.cp.displaySuccess(Craft.t("app",t.settings.reorderSuccessMessage))})).catch((function(e){e.response,Craft.cp.displayError(Craft.t("app",t.settings.reorderFailMessage))}))}},handleDeleteBtnClick:function(t){if(!(this.settings.minItems&&this.totalItems<=this.settings.minItems)){var e=$(t.target).closest("tr");this.confirmDeleteItem(e)&&this.deleteItem(e)}},confirmDeleteItem:function(t){if(!this.settings.confirmDeleteMessage)return!0;var e=this.getItemName(t);return confirm(Craft.t("app",this.settings.confirmDeleteMessage,{name:e}))},deleteItem:function(t){var e=this,i={id:this.getItemId(t)};Craft.sendActionRequest("POST",this.settings.deleteAction,{data:i}).then((function(i){return e.handleDeleteItemSuccess(i.data,t)})).catch((function(i){var s=i.response;return e.handleDeleteItemFailure(s.data,t)}))},handleDeleteItemFailure:function(t,e){this.getItemId(e);var i=this.getItemName(e);Craft.cp.displayError(Craft.t("app",this.settings.deleteFailMessage,{name:i}))},handleDeleteItemSuccess:function(t,e){var i=this.getItemId(e),s=this.getItemName(e);this.sorter&&this.sorter.removeItems(e),e.remove(),this.totalItems--,this.updateUI(),this.onDeleteItem(i),this.settings.deleteSuccessMessage&&Craft.cp.displaySuccess(Craft.t("app",this.settings.deleteSuccessMessage,{name:s}))},onReorderItems:function(t){this.settings.onReorderItems(t)},onDeleteItem:function(t){this.settings.onDeleteItem(t)},getItemId:function(t){return t.attr(this.settings.idAttribute)},getItemName:function(t){return Craft.escapeHtml(t.attr(this.settings.nameAttribute))},updateUI:function(){if(0===this.totalItems?(this.$table.hide(),this.$noItems.removeClass("hidden")):(this.$table.show(),this.$noItems.addClass("hidden")),this.settings.sortable){var t=this.$table.find(".move");1===this.totalItems?t.addClass("disabled"):t.removeClass("disabled")}this.settings.minItems&&this.totalItems<=this.settings.minItems?this.$deleteBtns.addClass("disabled"):this.$deleteBtns.removeClass("disabled"),this.settings.newItemBtnSelector&&(this.settings.maxItems&&this.totalItems>=this.settings.maxItems?$(this.settings.newItemBtnSelector).addClass("hidden"):$(this.settings.newItemBtnSelector).removeClass("hidden"))}},{defaults:{tableSelector:null,noItemsSelector:null,newItemBtnSelector:null,idAttribute:"data-id",nameAttribute:"data-name",sortable:!1,allowDeleteAll:!0,minItems:0,maxItems:null,reorderAction:null,deleteAction:null,reorderSuccessMessage:Craft.t("app","New order saved."),reorderFailMessage:Craft.t("app","Couldn’t save new order."),confirmDeleteMessage:Craft.t("app","Are you sure you want to delete “{name}”?"),deleteSuccessMessage:Craft.t("app","“{name}” deleted."),deleteFailMessage:Craft.t("app","Couldn’t delete “{name}”."),onReorderItems:$.noop,onDeleteItem:$.noop}})},6872:function(){Craft.AssetImageEditor=Garnish.Modal.extend({$body:null,$footer:null,$imageTools:null,$buttons:null,$cancelBtn:null,$replaceBtn:null,$saveBtn:null,$focalPointBtn:null,$editorContainer:null,$straighten:null,$croppingCanvas:null,$spinner:null,$constraintContainer:null,$constraintRadioInputs:null,$customConstraints:null,canvas:null,image:null,viewport:null,focalPoint:null,grid:null,croppingCanvas:null,clipper:null,croppingRectangle:null,cropperHandles:null,cropperGrid:null,croppingShade:null,imageStraightenAngle:0,viewportRotation:0,originalWidth:0,originalHeight:0,imageVerticeCoords:null,zoomRatio:1,animationInProgress:!1,currentView:"",assetId:null,cacheBust:null,draggingCropper:!1,scalingCropper:!1,draggingFocal:!1,previousMouseX:0,previousMouseY:0,shiftKeyHeld:!1,editorHeight:0,editorWidth:0,cropperState:!1,scaleFactor:1,flipData:{},focalPointState:!1,maxImageSize:null,lastLoadedDimensions:null,imageIsLoading:!1,mouseMoveEvent:null,croppingConstraint:!1,constraintOrientation:"landscape",showingCustomConstraint:!1,saving:!1,renderImage:null,renderCropper:null,_queue:null,init:function(t,e){var i=this;this._queue=new Craft.Queue,this.cacheBust=Date.now(),this.setSettings(e,Craft.AssetImageEditor.defaults),null===this.settings.allowDegreeFractions&&(this.settings.allowDegreeFractions=Craft.isImagick),Garnish.prefersReducedMotion()&&(this.settings.animationDuration=1),this.assetId=t,this.flipData={x:0,y:0},this.$container=$('<form class="modal fitted imageeditor"></form>').appendTo(Garnish.$bod),this.$body=$('<div class="body"></div>').appendTo(this.$container),this.$footer=$('<div class="footer"/>').appendTo(this.$container),this.base(this.$container,this.settings),this.$buttons=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn cancel",text:Craft.t("app","Cancel")}).appendTo(this.$buttons),this.settings.allowSavingAsNew&&(this.$saveBtn=Craft.ui.createButton({class:"save copy",label:Craft.t("app","Save as a new asset"),spinner:!0}).appendTo(this.$buttons),this.addListener(this.$saveBtn,"activate",this.saveImage)),this.$replaceBtn=Craft.ui.createSubmitButton({class:"save replace",label:Craft.t("app","Save"),spinner:!0}).appendTo(this.$buttons),this.addListener(this.$replaceBtn,"activate",this.saveImage),this.addListener(this.$cancelBtn,"activate",this.hide),this.removeListener(this.$shade,"click"),this.maxImageSize=this.getMaxImageSize(),Craft.sendActionRequest("POST","assets/image-editor",{data:{assetId:t}}).then((function(t){return i.loadEditor(t.data)}))},getMaxImageSize:function(){var t=Garnish.$doc.get(0).documentElement.clientWidth,e=Garnish.$doc.get(0).documentElement.clientHeight;return Math.max(e,t)*(window.devicePixelRatio>1?2:1)},loadEditor:function(t){var e=this;t.html||Craft.cp.displayError(Craft.t("app","Could not load the image editor.")),this.$body.html(t.html),this.$tabs=$(".tabs li",this.$body),this.$viewsContainer=$(".views",this.$body),this.$views=$("> div",this.$viewsContainer),this.$imageTools=$(".image-container .image-tools",this.$body),this.$editorContainer=$(".image-container .image",this.$body),this.$constraintContainer=$(".constraint-group",this.$body),this.$constraintRadioInputs=$('[name="constraint"]',this.$constraintContainer),this.$focalPointBtn=$(".focal-point",this.$body),this.editorHeight=this.$editorContainer.innerHeight(),this.editorWidth=this.$editorContainer.innerWidth(),this._showSpinner(),this.updateSizeAndPosition(),$customConstraintWrapper=this.$constraintRadioInputs.filter('[value="custom"]').parent(),this.$customConstraints=$("<div/>",{class:"constraint custom hidden","data-constraint":"custom"}).append($("<input/>",{type:"text",class:"custom-constraint-w",size:3,value:1,"aria-label":Craft.t("app","Width unit")})).append($("<span/>",{class:"custom-constraint-spacer",text:"x","aria-hidden":"true"})).append($("<input/>",{type:"text",class:"custom-constraint-h",size:3,value:1,"aria-label":Craft.t("app","Height unit")})).appendTo($customConstraintWrapper),this.$constraintRadioInputs.filter((function(){var t=$(this).val();return/^\d*\.\d+$/.test(t)})).addClass("flip"),this.canvas=new fabric.StaticCanvas("image-canvas"),this.$croppingCanvas=$("#cropping-canvas",this.$editorContainer),this.$croppingCanvas.width(this.editorWidth),this.$croppingCanvas.height(this.editorHeight),this.canvas.enableRetinaScaling=!0,this.renderImage=function(){Garnish.requestAnimationFrame(e.canvas.renderAll.bind(e.canvas))};var i=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});fabric.Image.fromURL(i,(function(i){e.image=i,e.image.set({originX:"center",originY:"center",left:e.editorWidth/2,top:e.editorHeight/2}),e.canvas.add(e.image),e.originalHeight=e.image.getHeight(),e.originalWidth=e.image.getWidth(),e.zoomRatio=1,e.lastLoadedDimensions=e.getScaledImageDimensions(),e._setFittedImageVerticeCoordinates(),e._repositionEditorElements();var s={imageDimensions:e.getScaledImageDimensions(),offsetX:0,offsetY:0},n=!1;if(t.focalPoint){var a=t.focalPoint,r=s.imageDimensions.width*a.x,o=s.imageDimensions.height*a.y;s.offsetX=r-s.imageDimensions.width/2,s.offsetY=o-s.imageDimensions.height/2,n=!0}e.storeFocalPointState(s),n&&e._createFocalPoint(),e._createViewport(),e.storeCropperState(),e._addControlListeners(),e.addListener(e.$croppingCanvas,"mousemove,touchmove",e._handleMouseMove),e.addListener(e.$croppingCanvas,"mousedown,touchstart",e._handleMouseDown),e.addListener(e.$croppingCanvas,"mouseup,touchend",e._handleMouseUp),e.addListener(e.$croppingCanvas,"mouseout,touchcancel",e._handleMouseOut),e._hideSpinner(),e.renderImage(),e.$tabs.first().trigger("click")}))},_reloadImage:function(){var t=this;if(!this.imageIsLoading){this.imageIsLoading=!0,this.maxImageSize=this.getMaxImageSize();var e=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});this.image.setSrc(e,(function(e){t.originalHeight=e.getHeight(),t.originalWidth=e.getWidth(),t.lastLoadedDimensions={width:t.originalHeight,height:t.originalWidth},t.updateSizeAndPosition(),t.renderImage(),t.imageIsLoading=!1}))}},updateSizeAndPosition:function(){if(this.$container){var t=window.innerWidth,e=window.innerHeight;this.$container.css({width:t,"min-width":t,left:0,height:e,"min-height":e,top:0}),this.$body.css({height:e-(this.$footer.outerHeight()-1)}),t<e?this.$container.addClass("vertical"):this.$container.removeClass("vertical"),this.$editorContainer&&this.image&&this._repositionEditorElements()}},_repositionEditorElements:function(){var t={width:this.editorWidth,height:this.editorHeight};this.editorHeight=this.$editorContainer.innerHeight(),this.editorWidth=this.$editorContainer.innerWidth(),this.canvas.setDimensions({width:this.editorWidth,height:this.editorHeight});var e=this.getScaledImageDimensions();if("crop"===this.currentView){this.zoomRatio=this.getZoomToFitRatio(this.getScaledImageDimensions());var i=this._getBoundingRectangle(this.imageVerticeCoords);this._setFittedImageVerticeCoordinates(),this._repositionCropper(i)}else this.zoomRatio=this.getZoomToCoverRatio(this.getScaledImageDimensions())*this.scaleFactor;this._repositionImage(t),this._repositionViewport(),this._repositionFocalPoint(t),this._zoomImage(),this.renderImage(),(e.width/this.lastLoadedDimensions.width>1.5||e.height/this.lastLoadedDimensions.height>1.5)&&this._reloadImage()},_repositionImage:function(t){this.image.set({left:this.image.left-(t.width-this.editorWidth)/2,top:this.image.top-(t.height-this.editorHeight)/2})},_createViewport:function(){this.viewport=new fabric.Rect({width:this.image.width,height:this.image.height,fill:"rgba(127,0,0,1)",originX:"center",originY:"center",globalCompositeOperation:"destination-in",left:this.image.left,top:this.image.top}),this.canvas.add(this.viewport),this.renderImage()},_createFocalPoint:function(){var t=this.focalPointState,e=this.getScaledImageDimensions().width/t.imageDimensions.width,i=t.offsetX*e*this.zoomRatio*this.scaleFactor,s=t.offsetY*e*this.zoomRatio*this.scaleFactor;i+=this.image.left,s+=this.image.top;var n=0,a=0;this.viewport&&0===t.offsetX&&0===t.offsetY&&("crop"!==this.currentView?(n=this.viewport.left-this.image.left,a=this.viewport.top-this.image.top):(n=this.clipper.left-this.image.left,a=this.clipper.top-this.image.top),i+=n,s+=a,t.offsetX+=n/(e*this.zoomRatio*this.scaleFactor),t.offsetY+=a/(e*this.zoomRatio*this.scaleFactor)),this.focalPoint=new fabric.Group([new fabric.Circle({radius:8,fill:"rgba(0,0,0,0.5)",strokeWidth:2,stroke:"rgba(255,255,255,0.8)",left:0,top:0,originX:"center",originY:"center"}),new fabric.Circle({radius:1,fill:"rgba(255,255,255,0)",strokeWidth:2,stroke:"rgba(255,255,255,0.8)",left:0,top:0,originX:"center",originY:"center"})],{originX:"center",originY:"center",left:i,top:s}),this.storeFocalPointState(t),this.canvas.add(this.focalPoint)},toggleFocalPoint:function(){this.focalPoint?(this.canvas.remove(this.focalPoint),this.focalPoint=null,this.$focalPointBtn.attr("aria-pressed","false")):(this._createFocalPoint(),this.$focalPointBtn.attr("aria-pressed","true")),this.renderImage()},_repositionViewport:function(){if(this.viewport){var t={left:this.editorWidth/2,top:this.editorHeight/2};if("crop"===this.currentView)t.width=this.editorWidth,t.height=this.editorHeight;else if(this.cropperState){var e=this.cropperState,i=this.getScaledImageDimensions().width/e.imageDimensions.width;t.width=e.width*i*this.zoomRatio,t.height=e.height*i*this.zoomRatio,this.image.set({left:this.editorWidth/2-e.offsetX*i,top:this.editorHeight/2-e.offsetY*i})}else $.extend(t,this.getScaledImageDimensions());this.viewport.set(t)}},_repositionFocalPoint:function(t){if(this.focalPoint){var e=this.focalPoint.left-this.editorWidth/2,i=this.focalPoint.top-this.editorHeight/2,s=this.image.width,n=this.getScaledImageDimensions().width*this.zoomRatio/s/this.scaleFactor;e-=(t.width-this.editorWidth)/2,i-=(t.height-this.editorHeight)/2,e*=n,i*=n,this.focalPoint.set({left:this.editorWidth/2+e,top:this.editorHeight/2+i})}},hasOrientationChanged:function(){return this.viewportRotation%180!=0},getScaledImageDimensions:function(){return void 0===this.getScaledImageDimensions._&&(this.getScaledImageDimensions._={}),this.getScaledImageDimensions._.imageRatio=this.originalHeight/this.originalWidth,this.getScaledImageDimensions._.editorRatio=this.editorHeight/this.editorWidth,this.getScaledImageDimensions._.dimensions={},this.getScaledImageDimensions._.imageRatio>this.getScaledImageDimensions._.editorRatio?(this.getScaledImageDimensions._.dimensions.height=Math.min(this.editorHeight,this.originalHeight),this.getScaledImageDimensions._.dimensions.width=Math.round(this.originalWidth/(this.originalHeight/this.getScaledImageDimensions._.dimensions.height))):(this.getScaledImageDimensions._.dimensions.width=Math.min(this.editorWidth,this.originalWidth),this.getScaledImageDimensions._.dimensions.height=Math.round(this.originalHeight*(this.getScaledImageDimensions._.dimensions.width/this.originalWidth))),this.getScaledImageDimensions._.dimensions},_zoomImage:function(){void 0===this._zoomImage._&&(this._zoomImage._={}),this._zoomImage._.imageDimensions=this.getScaledImageDimensions(),this.image.set({width:this._zoomImage._.imageDimensions.width*this.zoomRatio,height:this._zoomImage._.imageDimensions.height*this.zoomRatio})},_getPrevTab:function(){var t,e=this._getActiveTabIndex();if(!(e<0))return t=e>0?e-1:this.$tabs.length-1,this.$tabs.eq(t)},_getNextTab:function(){var t,e=this._getActiveTabIndex();if(!(e<0))return t=e<this.$tabs.length-1?e+1:0,this.$tabs.eq(t)},_getActiveTab:function(){return this.$tabs.filter('[aria-selected="true"]')},_getActiveTabIndex:function(){var t=this._getActiveTab();if(t.length)return t.index()},_addControlListeners:function(){var t=this;this.addListener(this.$tabs,"click",this._handleTabClick),this.addListener(this.$tabs,"keydown",(function(e){switch(e.keyCode){case Garnish.LEFT_KEY:case Garnish.UP_KEY:e.preventDefault();var i=t._getPrevTab();t.activateTab(i);break;case Garnish.RIGHT_KEY:case Garnish.DOWN_KEY:e.preventDefault();var s=t._getNextTab();t.activateTab(s)}})),this.addListener(this.$focalPointBtn,"click",this.toggleFocalPoint),this.addListener($(".rotate-left"),"click",(function(){this.rotateImage(-90)})),this.addListener($(".rotate-right"),"click",(function(){this.rotateImage(90)})),this.addListener($(".flip-vertical"),"click",(function(){this.flipImage("y")})),this.addListener($(".flip-horizontal"),"click",(function(){this.flipImage("x")})),this.straighteningInput=new Craft.SlideRuleInput("slide-rule",{onStart:function(){t._showGrid()},onChange:function(e){t.straighten(e)},onEnd:function(){t._hideGrid(),t._cleanupFocalPointAfterStraighten()}}),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.SHIFT_KEY&&(this.shiftKeyHeld=!0)})),this.addListener(Garnish.$doc,"keyup",(function(t){t.keyCode===Garnish.SHIFT_KEY&&(this.shiftKeyHeld=!1)})),this.addListener(this.$constraintRadioInputs,"change",this._handleConstraintChange),this.addListener($(".orientation input",this.$container),"click",this._handleOrientationClick),this.addListener($(".constraint-group .custom input",this.$container),"keyup",this._applyCustomConstraint)},_handleConstraintClick:function(t){var e=$(t.currentTarget).data("constraint"),i=$(t.currentTarget);if(i.siblings().removeClass("active"),i.addClass("active"),"custom"==e)return this._showCustomConstraint(),void this._applyCustomConstraint();this._hideCustomConstraint(),this.setCroppingConstraint(e),this.enforceCroppingConstraint()},_handleConstraintChange:function(t){var e=$(t.target).val();if("custom"==e)return this._showCustomConstraint(),void this._applyCustomConstraint();this._hideCustomConstraint(),this.setCroppingConstraint(e),this.enforceCroppingConstraint()},_handleOrientationClick:function(t){if(t.currentTarget.value!==this.constraintOrientation){this.constraintOrientation=t.currentTarget.value;for(var e=$(".flip",this.$constraintContainer),i=0;i<e.length;i++){var s=$(e[i]),n='label[for="'+s.attr("id")+'"]',a=$(n,this.$constraintContainer);s.val(1/s.val()),a.html(a.text().split(":").reverse().join(":").replace(/\s/g,""))}e.filter(":checked").trigger("change")}},_applyCustomConstraint:function(){var t=this._getCustomConstraint();t.w>0&&t.h>0&&(this.setCroppingConstraint(t.w/t.h),this.enforceCroppingConstraint())},_getCustomConstraint:function(){var t=parseFloat($(".custom-constraint-w").val()),e=parseFloat($(".custom-constraint-h").val());return{w:isNaN(t)?0:t,h:isNaN(e)?0:e}},_setCustomConstraint:function(t,e){$(".custom-constraint-w").val(parseFloat(t)),$(".custom-constraint-h").val(parseFloat(e))},_hideCustomConstraint:function(){this.showingCustomConstraint=!1,this.$customConstraints.addClass("hidden"),$(".orientation",this.$container).removeClass("hidden")},_showCustomConstraint:function(){this.showingCustomConstraint||(this.showingCustomConstraint=!0,this.$customConstraints.removeClass("hidden"),$(".orientation",this.$container).addClass("hidden"))},_handleTabClick:function(t){if(!this.animationInProgress){var e=$(t.currentTarget);this.activateTab(e)}},activateTab:function(t){var e=$(t).data("view");this.$tabs.removeClass("selected").attr({"aria-selected":"false",tabindex:"-1"}),$(t).addClass("selected").attr({"aria-selected":"true",tabindex:"0"}).trigger("focus"),this.showView(e)},showView:function(t){var e=this;this.currentView!==t&&(this.$views.addClass("hidden"),this.$views.filter('[data-view="'+t+'"]').removeClass("hidden"),"rotate"===t?this.enableSlider():this.disableSlider(),this.updateSizeAndPosition(),"crop"===this.currentView&&"crop"!==t?this._queue.push((function(){return new Promise((function(t,i){e.disableCropMode(),t()}))})):"crop"!==this.currentView&&"crop"===t&&this._queue.push((function(){return new Promise((function(t,i){e.enableCropMode(),t()}))})),this.currentView=t)},storeCropperState:function(t){void 0===this.storeCropperState._&&(this.storeCropperState._={}),t?this.cropperState=t:this.clipper?(this.storeCropperState._.zoomFactor=1/this.zoomRatio,this.cropperState={offsetX:(this.clipper.left-this.image.left)*this.storeCropperState._.zoomFactor,offsetY:(this.clipper.top-this.image.top)*this.storeCropperState._.zoomFactor,height:this.clipper.height*this.storeCropperState._.zoomFactor,width:this.clipper.width*this.storeCropperState._.zoomFactor,imageDimensions:this.getScaledImageDimensions()}):(this.storeCropperState._.dimensions=this.getScaledImageDimensions(),this.cropperState={offsetX:0,offsetY:0,height:this.storeCropperState._.dimensions.height,width:this.storeCropperState._.dimensions.width,imageDimensions:this.storeCropperState._.dimensions})},storeFocalPointState:function(t){void 0===this.storeFocalPointState._&&(this.storeFocalPointState._={}),t?this.focalPointState=t:this.focalPoint&&(this.storeFocalPointState._.zoomFactor=1/this.zoomRatio,this.focalPointState={offsetX:(this.focalPoint.left-this.image.left)*this.storeFocalPointState._.zoomFactor/this.scaleFactor,offsetY:(this.focalPoint.top-this.image.top)*this.storeFocalPointState._.zoomFactor/this.scaleFactor,imageDimensions:this.getScaledImageDimensions()})},rotateImage:function(t){var e=this;if(!this.animationInProgress){if(90!==t&&-90!==t)return!1;this.animationInProgress=!0,this.viewportRotation+=t,this.viewportRotation=parseInt((this.viewportRotation+360)%360,10);var i,s=this.image.angle+t,n=this.getScaledImageDimensions();i=this.hasOrientationChanged()?this.getZoomToCoverRatio({height:n.width,width:n.height}):this.getZoomToCoverRatio(n),this.zoomRatio>i&&(i=this.zoomRatio);var a={angle:90===t?"+=90":"-=90"},r={angle:s,width:n.width*i,height:n.height*i},o=1;this.scaleFactor<1?(o=1/this.scaleFactor,this.scaleFactor=1):(this.viewport.width>this.editorHeight?o=this.editorHeight/this.viewport.width:this.viewport.height>this.editorWidth&&(o=this.editorWidth/this.viewport.height),this.scaleFactor=o),o<1&&(r.width*=o,r.height*=o);var l=this.cropperState,h=l.offsetX,d=l.offsetY,c=t*(Math.PI/180),u=h*Math.cos(c)-d*Math.sin(c),p=h*Math.sin(c)+d*Math.cos(c),f=n.width/l.imageDimensions.width,g=u*f*this.zoomRatio*this.scaleFactor,m=p*f*this.zoomRatio*this.scaleFactor;r.left=this.editorWidth/2-g,r.top=this.editorHeight/2-m,l.offsetX=u,l.offsetY=p;var v=l.width;l.width=l.height,l.height=v,this.storeCropperState(l),this.focalPoint&&this.canvas.remove(this.focalPoint),this.viewport.animate(a,{duration:this.settings.animationDuration,onComplete:function(){var t=e.viewport.height*o;e.viewport.height=e.viewport.width*o,e.viewport.width=t,e.viewport.set({angle:0})}}),this.image.animate(r,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){var i=parseFloat((e.image.angle+360)%360);e.image.set({angle:i}),e.animationInProgress=!1,e.focalPoint?(e._adjustFocalPointByAngle(t),e.straighten(e.straighteningInput),e.canvas.add(e.focalPoint)):e._resetFocalPointPosition()}})}},flipImage:function(t){var e=this;if(!this.animationInProgress){this.animationInProgress=!0,this.hasOrientationChanged()&&(t="y"===t?"x":"y"),this.focalPoint?this.canvas.remove(this.focalPoint):this._resetFocalPointPosition();var i={x:this.editorWidth/2,y:this.editorHeight/2};this.straighteningInput.setValue(-this.imageStraightenAngle),this.imageStraightenAngle=-this.imageStraightenAngle;var s,n,a={angle:this.viewportRotation+this.imageStraightenAngle},r=this.cropperState,o=this.focalPointState;"y"===t&&this.hasOrientationChanged()||"y"!==t&&!this.hasOrientationChanged()?(r.offsetX=-r.offsetX,o.offsetX=-o.offsetX,n=this.image.left-i.x,a.left=i.x-n):(r.offsetY=-r.offsetY,o.offsetY=-o.offsetY,s=this.image.top-i.y,a.top=i.y-s),"y"===t?(a.scaleY=-1*this.image.scaleY,this.flipData.y=1-this.flipData.y):(a.scaleX=-1*this.image.scaleX,this.flipData.x=1-this.flipData.x),this.storeCropperState(r),this.storeFocalPointState(o),this.image.animate(a,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){e.animationInProgress=!1,e.focalPoint&&(e._adjustFocalPointByAngle(0),e.canvas.add(e.focalPoint))}})}},straighten:function(t){if(!this.animationInProgress){this.animationInProgress=!0;var e=this.image.angle;this.imageStraightenAngle=(this.settings.allowDegreeFractions?parseFloat(t.value):Math.round(parseFloat(t.value)))%360,this.image.set({angle:this.viewportRotation+this.imageStraightenAngle}),this.zoomRatio=this.getZoomToCoverRatio(this.getScaledImageDimensions())*this.scaleFactor,this._zoomImage(),this.cropperState&&this._adjustEditorElementsOnStraighten(e),this.renderImage(),this.animationInProgress=!1}},_adjustEditorElementsOnStraighten:function(t){var e,i,s,n,a,r=this.getScaledImageDimensions(),o=this.image.angle-t,l=this.cropperState,h=this.zoomRatio,d=1;do{var c=l.offsetX,u=l.offsetY,p=o*(Math.PI/180);s=c*Math.cos(p)-u*Math.sin(p),n=c*Math.sin(p)+u*Math.cos(p),e=s*h*(a=r.width/l.imageDimensions.width),i=n*h*a;var f=this.getImageVerticeCoords(h),g={width:this.viewport.width,height:this.viewport.height,left:this.editorWidth/2-this.viewport.width/2+e,top:this.editorHeight/2-this.viewport.height/2+i};h*=d=this._getZoomRatioToFitRectangle(g,f)}while(1!==d);this.image.set({left:this.editorWidth/2-e,top:this.editorHeight/2-i}),l.offsetX=s,l.offsetY=n,l.width=this.viewport.width/h/a,l.height=this.viewport.height/h/a,this.storeCropperState(l),this.zoomRatio=h,this.focalPoint?(this._adjustFocalPointByAngle(o),this._isCenterInside(this.focalPoint,this.viewport)?this.focalPoint.set({opacity:1}):this.focalPoint.set({opacity:0})):0!==o&&this._resetFocalPointPosition(),this._zoomImage()},_cleanupFocalPointAfterStraighten:function(){if(this.focalPoint&&!this._isCenterInside(this.focalPoint,this.viewport)){this.focalPoint.set({opacity:1});var t=this.focalPointState;t.offsetX=0,t.offsetY=0,this.storeFocalPointState(t),this.toggleFocalPoint()}},_resetFocalPointPosition:function(){var t=this.focalPointState;t.offsetX=0,t.offsetY=0,this.storeFocalPointState(t)},_isCenterInside:function(t,e){return t.left>e.left-e.width/2&&t.top>e.top-e.height/2&&t.left<e.left+e.width/2&&t.top<e.top+e.height/2},_adjustFocalPointByAngle:function(t){var e=t*(Math.PI/180),i=this.focalPointState,s=i.offsetX,n=i.offsetY,a=s*Math.cos(e)-n*Math.sin(e),r=s*Math.sin(e)+n*Math.cos(e),o=this.getScaledImageDimensions().width/i.imageDimensions.width,l=a*o*this.zoomRatio,h=r*o*this.zoomRatio;this.focalPoint.left=this.image.left+l,this.focalPoint.top=this.image.top+h,i.offsetX=a,i.offsetY=r,this.storeFocalPointState(i)},_getZoomRatioToFitRectangle:function(t,e){for(var i,s,n=this._getRectangleVertices(t),a=0;a<n.length&&(i=n[a],this.arePointsInsideRectangle([i],e));a++)i=!1;if(i){var r=this._getEdgeCrossed(e,i),o={x:t.left+t.width/2,y:t.top+t.height/2},l=Math.abs((r[1].y-r[0].y)*i.x-(r[1].x-r[0].x)*i.y+r[1].x*r[0].y-r[1].y*r[0].x)/Math.sqrt(Math.pow(r[1].y-r[0].y,2)+Math.pow(r[1].x-r[0].x,2)),h=Math.abs((r[1].y-r[0].y)*o.x-(r[1].x-r[0].x)*o.y+r[1].x*r[0].y-r[1].y*r[0].x)/Math.sqrt(Math.pow(r[1].y-r[0].y,2)+Math.pow(r[1].x-r[0].x,2));s=(l+h)/h}else s=1;return s},saveImage:function(t){var e=this,i=$(t.currentTarget);if(this.saving)return!1;this.saving=!0,i.addClass("loading");var s=i.hasClass("replace"),n={assetId:this.assetId,viewportRotation:this.viewportRotation,imageRotation:this.imageStraightenAngle,replace:s?1:0};if(this.cropperState){var a={};a.height=this.cropperState.height,a.width=this.cropperState.width,a.offsetX=this.cropperState.offsetX,a.offsetY=this.cropperState.offsetY,n.imageDimensions=this.cropperState.imageDimensions,n.cropData=a}else n.imageDimensions=this.getScaledImageDimensions();this.focalPoint&&(n.focalPoint=this.focalPointState),n.flipData=this.flipData,n.zoom=this.zoomRatio,Craft.sendActionRequest("POST","assets/save-image",{data:n}).then((function(t){var i=t.data;e.onSave(i),s&&Craft.broadcaster&&Craft.broadcaster.postMessage({event:"saveElement",id:e.assetId}),e.hide(),Craft.cp.runQueue(),Craft.Preview.refresh()})).catch((function(t){var e=t.response;Craft.cp.displayError(e.data.message)})).finally((function(){e.$buttons.find(".btn").removeClass("loading"),e.saving=!1}))},getZoomToCoverRatio:function(t){var e=Math.abs(this.imageStraightenAngle)*(Math.PI/180),i=Math.sin(e)*t.height+Math.cos(e)*t.width,s=Math.sin(e)*t.width+Math.cos(e)*t.height;return Math.max(i/t.width,s/t.height)},getZoomToFitRatio:function(t){var e=this._getImageBoundingBox(t),i=1;if(e.height>this.editorHeight||e.width>this.editorWidth){var s=this.editorHeight/e.height,n=this.editorWidth/e.width;i=Math.min(n,s)}return i},getCombinedZoomRatio:function(t){return this.getZoomToCoverRatio(t)/this.getZoomToFitRatio(t)},_showGrid:function(){if(!this.grid){var t,e={strokeWidth:1,stroke:"rgba(255,255,255,0.5)"},i=this.viewport.width,s=this.viewport.height,n=i/9,a=s/9,r=[new fabric.Rect({strokeWidth:2,stroke:"rgba(255,255,255,1)",originX:"center",originY:"center",width:i,height:s,left:i/2,top:s/2,fill:"rgba(255,255,255,0)"})];for(t=1;t<=8;t++)r.push(new fabric.Line([t*n,0,t*n,s],e));for(t=1;t<=8;t++)r.push(new fabric.Line([0,t*a,i,t*a],e));this.grid=new fabric.Group(r,{left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",angle:this.viewport.angle}),this.canvas.add(this.grid),this.renderImage()}},_hideGrid:function(){this.canvas.remove(this.grid),this.grid=null,this.renderImage()},onFadeOut:function(){this.destroy()},show:function(){this.base(),Garnish.$bod.addClass("no-scroll")},hide:function(){this.removeAllListeners(),this.straighteningInput.removeAllListeners(),Garnish.$bod.removeClass("no-scroll"),this.base()},onSave:function(t){this.settings.onSave(t),this.trigger("save")},enableSlider:function(){this.$imageTools.removeClass("hidden")},disableSlider:function(){this.$imageTools.addClass("hidden")},enableCropMode:function(){var t=this,e=this.getScaledImageDimensions();this.zoomRatio=this.getZoomToFitRatio(e);var i={width:this.editorWidth,height:this.editorHeight},s={width:e.width*this.zoomRatio,height:e.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2};this._editorModeTransition((function(){t._setFittedImageVerticeCoordinates();var e=t.cropperState,i=t.getScaledImageDimensions(),s=i.width/e.imageDimensions.width,n={left:t.image.left+e.offsetX*s*t.zoomRatio,top:t.image.top+e.offsetY*s*t.zoomRatio,width:e.width*s*t.zoomRatio,height:e.height*s*t.zoomRatio};t._showCropper(n),t.focalPoint&&(s=i.width/t.focalPointState.imageDimensions.width,t.focalPoint.left=t.image.left+t.focalPointState.offsetX*s*t.zoomRatio,t.focalPoint.top=t.image.top+t.focalPointState.offsetY*s*t.zoomRatio,t.canvas.add(t.focalPoint))}),s,i)},disableCropMode:function(){var t=this,e={};this._hideCropper();var i=this.getScaledImageDimensions(),s=this.getZoomToCoverRatio(i)*this.scaleFactor,n=s/this.zoomRatio;this.zoomRatio=s;var a={width:i.width*this.zoomRatio,height:i.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2},r=(this.clipper.left-this.image.left)*n,o=(this.clipper.top-this.image.top)*n;a.left=this.editorWidth/2-r,a.top=this.editorHeight/2-o,e.height=this.clipper.height*n,e.width=this.clipper.width*n,(!this.focalPoint||this.focalPoint&&!this._isCenterInside(this.focalPoint,this.clipper))&&(this.focalPoint&&this.toggleFocalPoint(),this._resetFocalPointPosition()),this._editorModeTransition((function(){if(t.focalPoint){var e=t.getScaledImageDimensions().width/t.focalPointState.imageDimensions.width;t.focalPoint.left=t.image.left+t.focalPointState.offsetX*e*t.zoomRatio,t.focalPoint.top=t.image.top+t.focalPointState.offsetY*e*t.zoomRatio,t.canvas.add(t.focalPoint)}}),a,e)},_editorModeTransition:function(t,e,i){var s=this;this._queue.pause(),this.animationInProgress||(this.animationInProgress=!0,this.focalPoint&&(this.canvas.remove(this.focalPoint),this.renderImage()),this.image.animate(e,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){t(),s.animationInProgress=!1,s.renderImage(),s._queue.resume()}}),this.viewport.animate(i,{duration:this.settings.animationDuration}))},_showSpinner:function(){this.$spinner||(this.$spinner=$('<div class="spinner big spinner-absolute"/>')),this.$spinner.appendTo(this.$container.find(".image"))},_hideSpinner:function(){this.$spinner.remove()},_showCropper:function(t){this._setupCropperLayer(t),this._redrawCropperElements(),this.renderCropper()},_hideCropper:function(){this.clipper&&(this.croppingCanvas.remove(this.clipper),this.croppingCanvas.remove(this.croppingShade),this.croppingCanvas.remove(this.cropperHandles),this.croppingCanvas.remove(this.cropperGrid),this.croppingCanvas.remove(this.croppingRectangle),this.croppingCanvas=null,this.renderCropper=null)},_setupCropperLayer:function(t){var e=this;this.croppingCanvas=new fabric.StaticCanvas("cropping-canvas",{backgroundColor:"rgba(0,0,0,0)",hoverCursor:"default",selection:!1}),this.croppingCanvas.setDimensions({width:this.editorWidth,height:this.editorHeight}),this.renderCropper=function(){return Garnish.requestAnimationFrame(e.croppingCanvas.renderAll.bind(e.croppingCanvas))},$("#cropping-canvas",this.$editorContainer).css({position:"absolute",top:0,left:0}),this.croppingShade=new fabric.Rect({left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",width:this.editorWidth,height:this.editorHeight,fill:"rgba(0,0,0,0.7)"});var i=this.getScaledImageDimensions(),s=0===this.imageStraightenAngle?1:1.2*this.getCombinedZoomRatio(i),n=i.width/s,a=i.height/s;if(this.hasOrientationChanged()){var r=a;a=n,n=r}this.clipper=new fabric.Rect({left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",width:n,height:a,stroke:"black",fill:"rgba(128,0,0,1)",strokeWidth:0}),t&&this.clipper.set(t),this.clipper.globalCompositeOperation="destination-out",this.croppingCanvas.add(this.croppingShade),this.croppingCanvas.add(this.clipper)},_redrawCropperElements:function(){void 0===this._redrawCropperElements._&&(this._redrawCropperElements._={}),this.cropperHandles&&(this.croppingCanvas.remove(this.cropperHandles),this.croppingCanvas.remove(this.cropperGrid),this.croppingCanvas.remove(this.croppingRectangle)),this._redrawCropperElements._.lineOptions={strokeWidth:4,stroke:"rgb(255,255,255)",fill:!1},this._redrawCropperElements._.gridOptions={strokeWidth:2,stroke:"rgba(255,255,255,0.5)"},this._redrawCropperElements._.pathGroup=[new fabric.Path("M 0,10 L 0,0 L 10,0",this._redrawCropperElements._.lineOptions),new fabric.Path("M "+(this.clipper.width-8)+",0 L "+(this.clipper.width+4)+",0 L "+(this.clipper.width+4)+",10",this._redrawCropperElements._.lineOptions),new fabric.Path("M "+(this.clipper.width+4)+","+(this.clipper.height-8)+" L"+(this.clipper.width+4)+","+(this.clipper.height+4)+" L "+(this.clipper.width-8)+","+(this.clipper.height+4),this._redrawCropperElements._.lineOptions),new fabric.Path("M 10,"+(this.clipper.height+4)+" L 0,"+(this.clipper.height+4)+" L 0,"+(this.clipper.height-8),this._redrawCropperElements._.lineOptions)],this.cropperHandles=new fabric.Group(this._redrawCropperElements._.pathGroup,{left:this.clipper.left,top:this.clipper.top,originX:"center",originY:"center"}),this.croppingRectangle=new fabric.Rect({left:this.clipper.left,top:this.clipper.top,width:this.clipper.width,height:this.clipper.height,fill:"rgba(0,0,0,0)",stroke:"rgba(255,255,255,0.8)",strokeWidth:2,originX:"center",originY:"center"}),this.cropperGrid=new fabric.Group([new fabric.Line([.33*this.clipper.width,0,.33*this.clipper.width,this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([.66*this.clipper.width,0,.66*this.clipper.width,this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([0,.33*this.clipper.height,this.clipper.width,.33*this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([0,.66*this.clipper.height,this.clipper.width,.66*this.clipper.height],this._redrawCropperElements._.gridOptions)],{left:this.clipper.left,top:this.clipper.top,originX:"center",originY:"center"}),this._redrawCropperElements._.cropTextTop=this.croppingRectangle.top+this.clipper.height/2+12,this._redrawCropperElements._.cropTextBackgroundColor="rgba(0,0,0,0)",this._redrawCropperElements._.cropTextTop+12>this.editorHeight-2&&(this._redrawCropperElements._.cropTextTop-=24,this._redrawCropperElements._.cropTextBackgroundColor="rgba(0,0,0,0.5)"),this.croppingCanvas.add(this.cropperHandles),this.croppingCanvas.add(this.cropperGrid),this.croppingCanvas.add(this.croppingRectangle)},_repositionCropper:function(t){if(this.croppingCanvas){var e=this.clipper.left-this.croppingCanvas.width/2,i=this.clipper.top-this.croppingCanvas.height/2;this.croppingCanvas.setDimensions({width:this.editorWidth,height:this.editorHeight});var s=this._getBoundingRectangle(this.imageVerticeCoords).width/t.width;this.clipper.width=Math.round(this.clipper.width*s),this.clipper.height=Math.round(this.clipper.height*s),this.clipper.left=this.editorWidth/2+e*s,this.clipper.top=this.editorHeight/2+i*s,this.croppingShade.set({width:this.editorWidth,height:this.editorHeight,left:this.editorWidth/2,top:this.editorHeight/2}),this._redrawCropperElements(),this.renderCropper()}},_getBoundingRectangle:function(t){return{width:Math.max(t.a.x,t.b.x,t.c.x,t.d.x)-Math.min(t.a.x,t.b.x,t.c.x,t.d.x),height:Math.max(t.a.y,t.b.y,t.c.y,t.d.y)-Math.min(t.a.y,t.b.y,t.c.y,t.d.y)}},_handleMouseDown:function(t){var e=this.focalPoint&&this._isMouseOver(t,this.focalPoint),i=this.croppingCanvas&&this._isMouseOver(t,this.clipper),s=this.croppingCanvas&&this._cropperHandleHitTest(t);(s||i||e)&&(this.previousMouseX=t.pageX,this.previousMouseY=t.pageY,e?this.draggingFocal=!0:s?this.scalingCropper=s:i&&(this.draggingCropper=!0))},_handleMouseMove:function(t){null!==this.mouseMoveEvent&&Garnish.requestAnimationFrame(this._handleMouseMoveInternal.bind(this)),this.mouseMoveEvent=t},_handleMouseMoveInternal:function(){null!==this.mouseMoveEvent&&(this.focalPoint&&this.draggingFocal?(this._handleFocalDrag(this.mouseMoveEvent),this.storeFocalPointState(),this.renderImage()):this.draggingCropper||this.scalingCropper?(this.draggingCropper?this._handleCropperDrag(this.mouseMoveEvent):this._handleCropperResize(this.mouseMoveEvent),this._redrawCropperElements(),this.storeCropperState(),this.renderCropper()):this._setMouseCursor(this.mouseMoveEvent),this.previousMouseX=this.mouseMoveEvent.pageX,this.previousMouseY=this.mouseMoveEvent.pageY,this.mouseMoveEvent=null)},_handleMouseUp:function(){this.draggingCropper=!1,this.scalingCropper=!1,this.draggingFocal=!1},_handleMouseOut:function(t){this._handleMouseUp(t),this.mouseMoveEvent=t,this._handleMouseMoveInternal()},_handleCropperDrag:function(t){if(void 0===this._handleCropperDrag._&&(this._handleCropperDrag._={}),this._handleCropperDrag._.deltaX=t.pageX-this.previousMouseX,this._handleCropperDrag._.deltaY=t.pageY-this.previousMouseY,0===this._handleCropperDrag._.deltaX&&0===this._handleCropperDrag._.deltaY)return!1;if(this._handleCropperDrag._.rectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this._handleCropperDrag._.vertices=this._getRectangleVertices(this._handleCropperDrag._.rectangle,this._handleCropperDrag._.deltaX,this._handleCropperDrag._.deltaY),!this.arePointsInsideRectangle(this._handleCropperDrag._.vertices,this.imageVerticeCoords)){for(this._handleCropperDrag._.dxi=0,this._handleCropperDrag._.dyi=0,this._handleCropperDrag._.xStep=this._handleCropperDrag._.deltaX>0?-1:1,this._handleCropperDrag._.yStep=this._handleCropperDrag._.deltaY>0?-1:1,this._handleCropperDrag._.furthest=0,this._handleCropperDrag._.furthestDeltas={},this._handleCropperDrag._.dxi=Math.min(Math.abs(this._handleCropperDrag._.deltaX),10);this._handleCropperDrag._.dxi>=0;this._handleCropperDrag._.dxi--)for(this._handleCropperDrag._.dyi=Math.min(Math.abs(this._handleCropperDrag._.deltaY),10);this._handleCropperDrag._.dyi>=0;this._handleCropperDrag._.dyi--)this._handleCropperDrag._.vertices=this._getRectangleVertices(this._handleCropperDrag._.rectangle,this._handleCropperDrag._.dxi*(this._handleCropperDrag._.deltaX>0?1:-1),this._handleCropperDrag._.dyi*(this._handleCropperDrag._.deltaY>0?1:-1)),this.arePointsInsideRectangle(this._handleCropperDrag._.vertices,this.imageVerticeCoords)&&this._handleCropperDrag._.dxi+this._handleCropperDrag._.dyi>this._handleCropperDrag._.furthest&&(this._handleCropperDrag._.furthest=this._handleCropperDrag._.dxi+this._handleCropperDrag._.dyi,this._handleCropperDrag._.furthestDeltas={x:this._handleCropperDrag._.dxi*(this._handleCropperDrag._.deltaX>0?1:-1),y:this._handleCropperDrag._.dyi*(this._handleCropperDrag._.deltaY>0?1:-1)});if(0==this._handleCropperDrag._.furthest)return;this._handleCropperDrag._.deltaX=this._handleCropperDrag._.furthestDeltas.x,this._handleCropperDrag._.deltaY=this._handleCropperDrag._.furthestDeltas.y}this.clipper.set({left:this.clipper.left+this._handleCropperDrag._.deltaX,top:this.clipper.top+this._handleCropperDrag._.deltaY})},_handleFocalDrag:function(t){if(void 0===this._handleFocalDrag._&&(this._handleFocalDrag._={}),this.focalPoint){if(this._handleFocalDrag._.deltaX=t.pageX-this.previousMouseX,this._handleFocalDrag._.deltaY=t.pageY-this.previousMouseY,0===this._handleFocalDrag._.deltaX&&0===this._handleFocalDrag._.deltaY)return;if(this._handleFocalDrag._.newX=this.focalPoint.left+this._handleFocalDrag._.deltaX,this._handleFocalDrag._.newY=this.focalPoint.top+this._handleFocalDrag._.deltaY,"crop"===this.currentView){if(!this.arePointsInsideRectangle([{x:this._handleFocalDrag._.newX,y:this._handleFocalDrag._.newY}],this.imageVerticeCoords))return}else if(!(this.viewport.left-this.viewport.width/2-this._handleFocalDrag._.newX<0&&this.viewport.left+this.viewport.width/2-this._handleFocalDrag._.newX>0&&this.viewport.top-this.viewport.height/2-this._handleFocalDrag._.newY<0&&this.viewport.top+this.viewport.height/2-this._handleFocalDrag._.newY>0))return;this.focalPoint.set({left:this.focalPoint.left+this._handleFocalDrag._.deltaX,top:this.focalPoint.top+this._handleFocalDrag._.deltaY})}},setCroppingConstraint:function(t){switch(this.updateSizeAndPosition(),t){case"none":this.croppingConstraint=!1;break;case"original":this.croppingConstraint=this.originalWidth/this.originalHeight;break;case"current":this.croppingConstraint=this.clipper.width/this.clipper.height;break;case"custom":break;default:this.croppingConstraint=parseFloat(t)}},enforceCroppingConstraint:function(){var t=this;void 0===this.enforceCroppingConstraint._&&(this.enforceCroppingConstraint._={}),!this.animationInProgress&&this.croppingConstraint&&(this.animationInProgress=!0,this.enforceCroppingConstraint._.rectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this.clipper.width>this.clipper.height*this.croppingConstraint?(this.enforceCroppingConstraint._.previousHeight=this.enforceCroppingConstraint._.rectangle.height,this.enforceCroppingConstraint._.rectangle.height=this.clipper.width/this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.top-=(this.enforceCroppingConstraint._.rectangle.height-this.enforceCroppingConstraint._.previousHeight)/2,this.arePointsInsideRectangle(this._getRectangleVertices(this.enforceCroppingConstraint._.rectangle),this.imageVerticeCoords)||(this.enforceCroppingConstraint._.rectangle.width=this.clipper.height*this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.height=this.enforceCroppingConstraint._.rectangle.width/this.croppingConstraint)):(this.enforceCroppingConstraint._.previousWidth=this.enforceCroppingConstraint._.rectangle.width,this.enforceCroppingConstraint._.rectangle.width=this.clipper.height*this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.left-=(this.enforceCroppingConstraint._.rectangle.width-this.enforceCroppingConstraint._.previousWidth)/2,this.arePointsInsideRectangle(this._getRectangleVertices(this.enforceCroppingConstraint._.rectangle),this.imageVerticeCoords)||(this.enforceCroppingConstraint._.rectangle.height=this.clipper.width/this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.width=this.enforceCroppingConstraint._.rectangle.height*this.croppingConstraint)),this.enforceCroppingConstraint._.properties={height:this.enforceCroppingConstraint._.rectangle.height,width:this.enforceCroppingConstraint._.rectangle.width},this.clipper.animate(this.enforceCroppingConstraint._.properties,{onChange:function(){t._redrawCropperElements(),t.croppingCanvas.renderAll()},duration:this.settings.animationDuration,onComplete:function(){t._redrawCropperElements(),t.animationInProgress=!1,t.renderCropper(),t.storeCropperState()}}))},_handleCropperResize:function(t){void 0===this._handleCropperResize._&&(this._handleCropperResize._={}),this._handleCropperResize._.deltaX=t.pageX-this.previousMouseX,this._handleCropperResize._.deltaY=t.pageY-this.previousMouseY,"b"!==this.scalingCropper&&"t"!==this.scalingCropper||(this._handleCropperResize._.deltaX=0),"l"!==this.scalingCropper&&"r"!==this.scalingCropper||(this._handleCropperResize._.deltaY=0),0===this._handleCropperResize._.deltaX&&0===this._handleCropperResize._.deltaY||(this._handleCropperResize._.startingRectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this._handleCropperResize._.rectangle=this._calculateNewCropperSizeByDeltas(this._handleCropperResize._.startingRectangle,this._handleCropperResize._.deltaX,this._handleCropperResize._.deltaY,this.scalingCropper),this._handleCropperResize._.rectangle.height<30||this._handleCropperResize._.rectangle.width<30||this.arePointsInsideRectangle(this._getRectangleVertices(this._handleCropperResize._.rectangle),this.imageVerticeCoords)&&(this.clipper.set({top:this._handleCropperResize._.rectangle.top+this._handleCropperResize._.rectangle.height/2,left:this._handleCropperResize._.rectangle.left+this._handleCropperResize._.rectangle.width/2,width:this._handleCropperResize._.rectangle.width,height:this._handleCropperResize._.rectangle.height}),this._redrawCropperElements()))},_calculateNewCropperSizeByDeltas:function(t,e,i,s){if(void 0===this._calculateNewCropperSizeByDeltas._&&(this._calculateNewCropperSizeByDeltas._={}),this._calculateNewCropperSizeByDeltas._.topDelta=0,this._calculateNewCropperSizeByDeltas._.leftDelta=0,this._calculateNewCropperSizeByDeltas._.rectangle=t,this._calculateNewCropperSizeByDeltas._.deltaX=e,this._calculateNewCropperSizeByDeltas._.deltaY=i,this.croppingConstraint){switch(this._calculateNewCropperSizeByDeltas._.change=0,s){case"t":this._calculateNewCropperSizeByDeltas._.change=-this._calculateNewCropperSizeByDeltas._.deltaY;break;case"b":this._calculateNewCropperSizeByDeltas._.change=this._calculateNewCropperSizeByDeltas._.deltaY;break;case"r":this._calculateNewCropperSizeByDeltas._.change=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"l":this._calculateNewCropperSizeByDeltas._.change=-this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tr":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?-this._calculateNewCropperSizeByDeltas._.deltaY:this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tl":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?-this._calculateNewCropperSizeByDeltas._.deltaY:-this._calculateNewCropperSizeByDeltas._.deltaX;break;case"br":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?this._calculateNewCropperSizeByDeltas._.deltaY:this._calculateNewCropperSizeByDeltas._.deltaX;break;case"bl":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?this._calculateNewCropperSizeByDeltas._.deltaY:-this._calculateNewCropperSizeByDeltas._.deltaX}switch(this.croppingConstraint>1?(this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.change,this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.deltaX/this.croppingConstraint):(this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.change,this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.deltaY*this.croppingConstraint),this._calculateNewCropperSizeByDeltas._.rectangle.height+=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.width+=this._calculateNewCropperSizeByDeltas._.deltaX,s){case"t":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX/2;break;case"b":this._calculateNewCropperSizeByDeltas._.rectangle.left+=-this._calculateNewCropperSizeByDeltas._.deltaX/2;break;case"r":this._calculateNewCropperSizeByDeltas._.rectangle.top+=-this._calculateNewCropperSizeByDeltas._.deltaY/2;break;case"l":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY/2,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tr":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY;break;case"tl":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"bl":this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX}}else!this.shiftKeyHeld||"tl"!==s&&"tr"!==s&&"bl"!==s&&"br"!==s||(this._calculateNewCropperSizeByDeltas._.ratio,Math.abs(e)>Math.abs(i)?(this._calculateNewCropperSizeByDeltas._.ratio=t.width/t.height,this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.deltaX/this._calculateNewCropperSizeByDeltas._.ratio,this._calculateNewCropperSizeByDeltas._.deltaY*="tr"===s||"bl"===s?-1:1):(this._calculateNewCropperSizeByDeltas._.ratio=t.width/t.height,this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.deltaY*this._calculateNewCropperSizeByDeltas._.ratio,this._calculateNewCropperSizeByDeltas._.deltaX*="tr"===s||"bl"===s?-1:1)),s.match(/t/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.top+=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.height-=this._calculateNewCropperSizeByDeltas._.deltaY),s.match(/b/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.height+=this._calculateNewCropperSizeByDeltas._.deltaY),s.match(/r/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.width+=this._calculateNewCropperSizeByDeltas._.deltaX),s.match(/l/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.left+=this._calculateNewCropperSizeByDeltas._.deltaX,this._calculateNewCropperSizeByDeltas._.rectangle.width-=this._calculateNewCropperSizeByDeltas._.deltaX);return this._calculateNewCropperSizeByDeltas._.rectangle.top=this._calculateNewCropperSizeByDeltas._.rectangle.top,this._calculateNewCropperSizeByDeltas._.rectangle.left=this._calculateNewCropperSizeByDeltas._.rectangle.left,this._calculateNewCropperSizeByDeltas._.rectangle.width=this._calculateNewCropperSizeByDeltas._.rectangle.width,this._calculateNewCropperSizeByDeltas._.rectangle.height=this._calculateNewCropperSizeByDeltas._.rectangle.height,this._calculateNewCropperSizeByDeltas._.rectangle},_setMouseCursor:function(t){void 0===this._setMouseCursor._&&(this._setMouseCursor._={}),Garnish.isMobileBrowser(!0)||(this._setMouseCursor._.cursor="default",this._setMouseCursor._.handle=this.croppingCanvas&&this._cropperHandleHitTest(t),this.focalPoint&&this._isMouseOver(t,this.focalPoint)?this._setMouseCursor._.cursor="pointer":this._setMouseCursor._.handle?"t"===this._setMouseCursor._.handle||"b"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="ns-resize":"l"===this._setMouseCursor._.handle||"r"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="ew-resize":"tl"===this._setMouseCursor._.handle||"br"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="nwse-resize":"bl"!==this._setMouseCursor._.handle&&"tr"!==this._setMouseCursor._.handle||(this._setMouseCursor._.cursor="nesw-resize"):this.croppingCanvas&&this._isMouseOver(t,this.clipper)&&(this._setMouseCursor._.cursor="move"),$(".body").css("cursor",this._setMouseCursor._.cursor))},_cropperHandleHitTest:function(t){if(void 0===this._cropperHandleHitTest._&&(this._cropperHandleHitTest._={}),this._cropperHandleHitTest._.parentOffset=this.$croppingCanvas.offset(),this._cropperHandleHitTest._.mouseX=t.pageX-this._cropperHandleHitTest._.parentOffset.left,this._cropperHandleHitTest._.mouseY=t.pageY-this._cropperHandleHitTest._.parentOffset.top,this._cropperHandleHitTest._.lb=this.clipper.left-this.clipper.width/2,this._cropperHandleHitTest._.rb=this._cropperHandleHitTest._.lb+this.clipper.width,this._cropperHandleHitTest._.tb=this.clipper.top-this.clipper.height/2,this._cropperHandleHitTest._.bb=this._cropperHandleHitTest._.tb+this.clipper.height,this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb-3){if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-3)return"tl";if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+3&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-10)return"bl"}if(this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.rb-13&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb+3){if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-3)return"tr";if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+2&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-10)return"br"}return this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.lb+3&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb-3&&this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb-10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb+10?"l":this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb+1&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.rb-5&&this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb-10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb+10?"r":this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+4&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-2&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb-10?"t":this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+2&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-4&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb-10&&"b"},_isMouseOver:function(t,e){return void 0===this._isMouseOver._&&(this._isMouseOver._={}),this._isMouseOver._.parentOffset=this.$croppingCanvas.offset(),this._isMouseOver._.mouseX=t.pageX-this._isMouseOver._.parentOffset.left,this._isMouseOver._.mouseY=t.pageY-this._isMouseOver._.parentOffset.top,this._isMouseOver._.lb=e.left-e.width/2,this._isMouseOver._.rb=this._isMouseOver._.lb+e.width,this._isMouseOver._.tb=e.top-e.height/2,this._isMouseOver._.bb=this._isMouseOver._.tb+e.height,this._isMouseOver._.mouseX>=this._isMouseOver._.lb&&this._isMouseOver._.mouseX<=this._isMouseOver._.rb&&this._isMouseOver._.mouseY>=this._isMouseOver._.tb&&this._isMouseOver._.mouseY<=this._isMouseOver._.bb},_getRectangleVertices:function(t,e,i){return void 0===this._getRectangleVertices._&&(this._getRectangleVertices._={}),void 0===e&&(e=0),void 0===i&&(i=0),this._getRectangleVertices._.topLeft={x:t.left+e,y:t.top+i},this._getRectangleVertices._.topRight={x:this._getRectangleVertices._.topLeft.x+t.width,y:this._getRectangleVertices._.topLeft.y},this._getRectangleVertices._.bottomRight={x:this._getRectangleVertices._.topRight.x,y:this._getRectangleVertices._.topRight.y+t.height},this._getRectangleVertices._.bottomLeft={x:this._getRectangleVertices._.topLeft.x,y:this._getRectangleVertices._.bottomRight.y},[this._getRectangleVertices._.topLeft,this._getRectangleVertices._.topRight,this._getRectangleVertices._.bottomRight,this._getRectangleVertices._.bottomLeft]},_setFittedImageVerticeCoordinates:function(){this.imageVerticeCoords=this.getImageVerticeCoords("fit")},getImageVerticeCoords:function(t){var e,i=-1*((this.hasOrientationChanged()?90:0)+this.imageStraightenAngle)*(Math.PI/180),s=this.getScaledImageDimensions();e="number"==typeof t?t:"cover"===t?this.getZoomToCoverRatio(s):this.getZoomToFitRatio(s);var n=s.height*e,a=s.width*e,r=Math.cos(i)*n,o=Math.sin(i)*a,l=Math.cos(i)*a,h=Math.sin(i)*n,d=(this.editorHeight-(r+o))/2,c=(this.editorWidth-(h+l))/2;return{a:{x:c+l,y:d},b:{x:this.editorWidth-c,y:d+r},c:{x:c+h,y:this.editorHeight-d},d:{x:c,y:d+o}}},_debug:function(t){this.canvas.remove(this.debugger),this.debugger=t,this.canvas.add(this.debugger)},arePointsInsideRectangle:function(t,e){for(void 0===this.arePointsInsideRectangle._&&(this.arePointsInsideRectangle._={}),this.arePointsInsideRectangle._.ab=this._getVector(e.a,e.b),this.arePointsInsideRectangle._.bc=this._getVector(e.b,e.c),this.arePointsInsideRectangle._.scalarAbAb=this._getScalarProduct(this.arePointsInsideRectangle._.ab,this.arePointsInsideRectangle._.ab),this.arePointsInsideRectangle._.scalarBcBc=this._getScalarProduct(this.arePointsInsideRectangle._.bc,this.arePointsInsideRectangle._.bc),this.arePointsInsideRectangle._.i=0;this.arePointsInsideRectangle._.i<t.length;this.arePointsInsideRectangle._.i++)if(this.arePointsInsideRectangle._.point=t[this.arePointsInsideRectangle._.i],this.arePointsInsideRectangle._.ap=this._getVector(e.a,this.arePointsInsideRectangle._.point),this.arePointsInsideRectangle._.bp=this._getVector(e.b,this.arePointsInsideRectangle._.point),this.arePointsInsideRectangle._.scalarAbAp=this._getScalarProduct(this.arePointsInsideRectangle._.ab,this.arePointsInsideRectangle._.ap),this.arePointsInsideRectangle._.scalarBcBp=this._getScalarProduct(this.arePointsInsideRectangle._.bc,this.arePointsInsideRectangle._.bp),this.arePointsInsideRectangle._.projectsOnAB=0<=this.arePointsInsideRectangle._.scalarAbAp&&this.arePointsInsideRectangle._.scalarAbAp<=this.arePointsInsideRectangle._.scalarAbAb,this.arePointsInsideRectangle._.projectsOnBC=0<=this.arePointsInsideRectangle._.scalarBcBp&&this.arePointsInsideRectangle._.scalarBcBp<=this.arePointsInsideRectangle._.scalarBcBc,!this.arePointsInsideRectangle._.projectsOnAB||!this.arePointsInsideRectangle._.projectsOnBC)return!1;return!0},_getVector:function(t,e){return{x:e.x-t.x,y:e.y-t.y}},_getScalarProduct:function(t,e){return t.x*e.x+t.y*e.y},_getVectorMagnitude:function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},_getAngleBetweenVectors:function(t,e){return Math.round(180*Math.acos(Math.min(1,this._getScalarProduct(t,e)/(this._getVectorMagnitude(t)*this._getVectorMagnitude(e))))/Math.PI*100)/100},_getEdgeCrossed:function(t,e){for(var i=[[t.a,t.b],[t.b,t.c],[t.c,t.d],[t.d,t.a]],s={x:this.editorWidth/2,y:this.editorHeight/2},n=180,a=null,r=0;r<i.length;r++){var o=i[r],l=this._getVector(o[0],s),h=this._getVector(o[0],o[1]),d=this._getVector(o[0],e),c=Math.abs(this._getAngleBetweenVectors(l,d)-(this._getAngleBetweenVectors(l,h)+this._getAngleBetweenVectors(h,d)));c<n&&(n=c,a=o)}return a},_getImageBoundingBox:function(t){var e={},i=Math.abs(this.imageStraightenAngle)*(Math.PI/180),s=t.height/t.width;if(e.height=t.width*(Math.sin(i)+Math.cos(i)*s),e.width=t.width*(Math.cos(i)+Math.sin(i)*s),this.hasOrientationChanged()){var n=e.width;e.width=e.height,e.height=n}return e}},{defaults:{animationDuration:100,allowSavingAsNew:!0,onSave:$.noop,allowDegreeFractions:null}})},2495:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function e(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Craft.AssetIndex=Craft.BaseElementIndex.extend({$includeSubfoldersContainer:null,$includeSubfoldersCheckbox:null,showingIncludeSubfoldersCheckbox:!1,$uploadButton:null,$uploadInput:null,$progressBar:null,uploader:null,promptHandler:null,progressBar:null,$listedFolders:null,itemDrag:null,_uploadTotalFiles:0,_uploadFileProgress:{},_currentUploaderSettings:{},init:function(t,i,s){var n,a=this;s=Object.assign({},Craft.AssetIndex.defaults,s),this.base(t,i,s),"index"===this.settings.context?(this.itemDrag=new Garnish.DragDrop((e(n={activeDropTargetClass:"sel",minMouseDist:10,hideDraggee:!1,moveHelperToCursor:!0},"activeDropTargetClass","active-drop-target"),e(n,"handle",(function(t){return $(t).closest("tr,li")})),e(n,"filter",(function(){var t=a.itemDrag.$targetItem.closest("tr,li");return a.view.elementSelect.selectItem(t),a._findDraggableItems(a.view.getSelectedElements())})),e(n,"helper",(function(t,e){return $('<div class="offset-drag-helper"/>').append(t).css({opacity:Math.max(.9-.05*e,0),width:"",height:""})})),e(n,"dropTargets",(function(){var t=$(a.$visibleSources.toArray().filter((function(t){return Garnish.hasAttr(t,"data-folder-id")&&Garnish.hasAttr(t,"data-can-move-peer-files-to")})));if(a.sourcePath.length<=1)t=t.not(a.$source);else for(var e=0;e<a.sourcePath.length-1;e++){var i=a.sourcePath[e];i.folderId&&(t=t.add(i.$btn))}return a.$listedFolders&&(t=t.add(a.$listedFolders.filter("[data-folder-id]").closest("tr,li")).not(a.view.getSelectedElements())),t})),e(n,"onDragStart",(function(){Garnish.$bod.addClass("dragging"),a.itemDrag.$draggee.closest("tr,li").addClass("draggee")})),e(n,"onDragStop",(function(){Garnish.$bod.removeClass("dragging");var t=a.itemDrag.$draggee,e=a._targetFolderId(a.itemDrag.$activeDropTarget);if(!e)return t.closest("tr,li").removeClass("draggee"),void a.itemDrag.returnHelpersToDraggees();a.itemDrag.fadeOutHelpers();var i=t.filter("[data-is-folder]"),s=t.not(i),n=i.toArray().map((function(t){return parseInt($(t).data("folder-id"))})),r=s.toArray().map((function(t){return parseInt($(t).data("id"))})),o=new Craft.AssetMover;o.moveFolders(n,e).then((function(i){o.moveAssets(r,e).then((function(e){var s=i+e;s?(Craft.cp.displayNotice(Craft.t("app","{totalItems, plural, =1{Item} other{Items}} moved.",{totalItems:s})),Craft.elementIndex.updateElements(!0)):t.closest("tr,li").removeClass("draggee")}))}))})),n)),this.addListener(Garnish.$win,"resize,scroll","_positionProgressBar")):(this.addListener(this.$main,"scroll","_positionProgressBar"),this.settings.modal&&this.settings.modal.on("updateSizeAndPosition",this._positionProgressBar.bind(this)))},_findDraggableItems:function(t){return $(t.toArray().map((function(t){return $(t).find(".element:first")[0]})).filter((function(t){return t&&Garnish.hasAttr(t,"data-movable")})))},_targetFolderId:function(t){if(!t||!t.length)return!1;if(t.is(this.$visibleSources))return t.data("folder-id");for(var e=0;e<this.sourcePath.length-1;e++){var i=this.sourcePath[e];if(t.is(i.$btn))return i.folderId}return t.find(".element:first").data("folder-id")||!1},afterInit:function(){this.settings.foldersOnly||this.initForFiles(),this.base()},initForFiles:function(){var t=this;this.$uploadButton||(this.$uploadButton=$("<button/>",{type:"button",class:"btn submit","data-icon":"upload",style:"position: relative; overflow: hidden;",text:Craft.t("app","Upload files")}),this.addButton(this.$uploadButton),this.$uploadInput=$('<input type="file" multiple="multiple" name="assets-upload" />').hide().insertBefore(this.$uploadButton)),this.promptHandler=new Craft.PromptHandler,this.progressBar=new Craft.ProgressBar(this.$main,!1);var e={url:Craft.getActionUrl("assets/upload"),fileInput:this.$uploadInput,dropZone:this.$container};e.events={fileuploadstart:this._onUploadStart.bind(this),fileuploadprogressall:this._onUploadProgress.bind(this),fileuploaddone:this._onUploadSuccess.bind(this),fileuploadalways:this._onUploadAlways.bind(this),fileuploadfail:this._onUploadFailure.bind(this)},this.settings.criteria&&void 0!==this.settings.criteria.kind&&(e.allowedKinds=this.settings.criteria.kind),this._currentUploaderSettings=e,this.uploader=new Craft.Uploader(this.$uploadButton,e),this.$uploadButton.on("click",(function(){t.$uploadButton.hasClass("disabled")||t.isIndexBusy||t.$uploadButton.parent().find("input[name=assets-upload]").trigger("click")}))},onSelectSource:function(){this.settings.foldersOnly||(this.$source.data("folder-id")&&Garnish.hasAttr(this.$source,"data-can-upload")?(this.uploader.setParams({folderId:this.$source.attr("data-folder-id")}),this.$uploadButton.removeClass("disabled")):this.$uploadButton.addClass("disabled")),this.base()},onSourcePathChange:function(){if(!this.settings.foldersOnly&&this.sourcePath.length){var t=this.sourcePath[this.sourcePath.length-1];if(t.folderId){this.uploader&&this.uploader.setParams({folderId:t.folderId});var e=!!t.canMoveSubItems;this.settings.selectable=this.settings.selectable||e,this.settings.multiSelect=this.settings.multiSelect||e}}this.base()},startSearching:function(){if(!this.settings.hideSidebar&&this.sourcePath[this.sourcePath.length-1].hasChildren){if(null===this.$includeSubfoldersContainer){var t="includeSubfolders-"+Math.floor(1e9*Math.random());this.$includeSubfoldersContainer=$('<div style="margin-bottom: -25px; opacity: 0;"/>').insertAfter(this.$search);var e=$('<div style="padding-top: 5px;"/>').appendTo(this.$includeSubfoldersContainer);this.$includeSubfoldersCheckbox=$('<input type="checkbox" id="'+t+'" class="checkbox"/>').appendTo(e),$('<label class="light smalltext" for="'+t+'"/>').text(" "+Craft.t("app","Search in subfolders")).appendTo(e),this.addListener(this.$includeSubfoldersCheckbox,"change",(function(){this.setSelecetedSourceState("includeSubfolders",this.$includeSubfoldersCheckbox.prop("checked")),this.updateElements()}))}else this.$includeSubfoldersContainer.velocity("stop").removeClass("hidden");var i=this.getSelectedSourceState("includeSubfolders",!1);this.$includeSubfoldersCheckbox.prop("checked",i),this.$includeSubfoldersContainer.velocity({marginBottom:0,opacity:1},"fast"),this.showingIncludeSubfoldersCheckbox=!0}this.base()},stopSearching:function(){var t=this;this.showingIncludeSubfoldersCheckbox&&(this.$includeSubfoldersContainer.velocity("stop"),this.$includeSubfoldersContainer.velocity({marginBottom:-25,opacity:0},{duration:"fast",complete:function(){t.$includeSubfoldersContainer.addClass("hidden")}}),this.showingIncludeSubfoldersCheckbox=!1),this.base()},getViewSettings:function(){var t={};return"index"===this.settings.context&&(t.canSelectElement=function(){return!0}),t},getViewParams:function(){var t=Object.assign(this.base(),{showFolders:this.settings.showFolders&&!this.trashed,foldersOnly:this.settings.foldersOnly});return this.showingIncludeSubfoldersCheckbox&&this.$includeSubfoldersCheckbox.prop("checked")&&(t.criteria.includeSubfolders=!0),t},_onUploadStart:function(){this.setIndexBusy(),this._positionProgressBar(),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar(),this.promptHandler.resetPrompts()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadSuccess:function(t,e){var i=e.result;this.selectElementAfterUpdate(i.assetId),i.conflict&&(i.prompt={message:Craft.t("app",i.conflict,{file:i.filename}),choices:[{value:"keepBoth",title:Craft.t("app","Keep both")},{value:"replace",title:Craft.t("app","Replace it")}]},this.promptHandler.addPrompt(i)),Craft.cp.runQueue()},_onUploadAlways:function(){this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.setIndexAvailable(),this.promptHandler.getPromptCount()?this.promptHandler.showBatchPrompts(this._uploadFollowup.bind(this)):this._updateAfterUpload())},_onUploadFailure:function(t,e){var i,s=e.response(),n=(null==s||null===(i=s.jqXHR)||void 0===i?void 0:i.responseJSON)||{},a=n.message,r=n.filename;a||(a=r?Craft.t("app","Upload failed for “{filename}”.",{filename:r}):Craft.t("app","Upload failed.")),Craft.cp.displayError(a)},_updateAfterUpload:function(){"index"!==this.settings.context&&(this.clearSearch(),this.setSelectedSortAttribute("dateCreated","desc")),this.updateElements()},_uploadFollowup:function(t){var e=this;this.setIndexBusy(),this.progressBar.resetProgressBar(),this.promptHandler.resetPrompts(),this.progressBar.setItemCount(t.length),this.progressBar.showProgressBar(),function t(i,s,n){var a={},r=null,o=function(){s++,e.progressBar.incrementProcessedItemCount(1),e.progressBar.updateProgressBar(),s===i.length?n():t(i,s,n)},l=function(t){t.assetId&&e.selectElementAfterUpdate(t.assetId),o()};"replace"===i[s].choice?(r="assets/replace-file",a.sourceAssetId=i[s].assetId,i[s].conflictingAssetId?a.assetId=i[s].conflictingAssetId:a.targetFilename=i[s].filename):"cancel"===i[s].choice&&(r="assets/delete-asset",a.assetId=i[s].assetId),r?Craft.sendActionRequest("POST",r,{data:a}).then((function(t){return l(t.data)})).catch((function(t){return function(t){Craft.cp.displayError(t.message),o()}(t.response.data)})):l({assetId:i[s].assetId})}(t,0,(function(){e.progressBar.hideProgressBar(),e.setIndexAvailable(),e._updateAfterUpload()}))},onUpdateElements:function(){var t=this;this._onUpdateElements(!1,this.view.getAllElements()),this.view.on("appendElements",(function(e){t._onUpdateElements(!0,e.newElements)})),this.base()},_onUpdateElements:function(t,e){var i=this;this.removeListener(this.$elements,"keydown"),this.addListener(this.$elements,"keydown",this._onKeyDown.bind(this)),this.view.elementSelect.on("focusItem",this._onElementFocus.bind(this)),this.$listedFolders=e.find(".element[data-is-folder][data-folder-name]");for(var s=function(t){var s=i.$listedFolders.eq(t),n=s.find(".label"),a=n.find(".title"),r=parseInt(s.data("folder-id")),o=s.data("folder-name"),l=Craft.t("app","{name} folder",{name:o});if(i.settings.disabledFolderIds.includes(r))return n.attr("aria-label",l),e.has(s).addClass("disabled"),"continue";var h=s.data("source-path");if(h){var d=$("<a/>",{href:Craft.getCpUrl(h[h.length-1].uri),html:a.html(),role:"button","aria-label":l});n.empty().append(d),i.addListener(d,"activate",(function(t){i.sourcePath=h,i.clearSearch(!1),i.updateElements().then((function(){var t=i.$elements.find(":focusable:not(.selectallcontainer)")[0];t&&t.focus()}))}))}},n=0;n<this.$listedFolders.length;n++)s(n);if(this.itemDrag){var a=this.sourcePath[this.sourcePath.length-1],r=!!(a&&a.folderId&&a.canMoveSubItems);r&&t||this.itemDrag.removeAllItems(),r&&this.itemDrag.addItems(this._findDraggableItems(e))}},_onKeyDown:function(t){if(t.keyCode===Garnish.SPACE_KEY&&t.shiftKey){if(Craft.PreviewFileModal.openInstance)Craft.PreviewFileModal.openInstance.selfDestruct();else{var e=this.view.elementSelect.$focusedItem.find(".element");e.length&&this._loadPreview(e)}return t.stopPropagation(),!1}},_onElementFocus:function(t){var e=$(t.item).find(".element");Craft.PreviewFileModal.openInstance&&e.length&&this._loadPreview(e)},_loadPreview:function(t){var e={};t.data("image-width")&&(e.startingWidth=t.data("image-width"),e.startingHeight=t.data("image-height")),new Craft.PreviewFileModal(t.data("id"),this.view.elementSelect,e)},getSourcePathLabel:function(){return Craft.t("app","Volume path")},getSourcePathActionLabel:function(){return Craft.t("app","Folder actions")},getSourcePathActions:function(){var t=this,e=[],i=this.sourcePath[this.sourcePath.length-1];return i.canCreate&&e.push({label:Craft.t("app","New subfolder"),onSelect:function(){t._createSubfolder()}}),"index"===this.settings.context&&i.canRename&&(e.push({label:Craft.t("app","Rename folder"),onSelect:function(){t._renameFolder()}}),i.canMove&&this.getMoveTargetSourceKeys(!0).length&&e.push({label:Craft.t("app","Move folder"),onSelect:function(){t._moveFolder()}}),i.canDelete&&e.push({label:Craft.t("app","Delete folder"),destructive:!0,onSelect:function(){t._deleteFolder()}})),e},_createSubfolder:function(){var t=this,e=this.sourcePath[this.sourcePath.length-1],i=prompt(Craft.t("app","Enter the name of the folder"));if(i){var s={parentId:e.folderId,folderName:i};this.setIndexBusy(),Craft.sendActionRequest("POST","assets/create-folder",{data:s}).then((function(e){t.setIndexAvailable(),Craft.cp.displayNotice(Craft.t("app","Folder created.")),t.updateElements(!0)})).catch((function(e){var i=e.response;t.setIndexAvailable(),Craft.cp.displayError(i.data.message)}))}},_deleteFolder:function(){var t=this,e=this.sourcePath[this.sourcePath.length-1];if(confirm(Craft.t("app","Really delete folder “{folder}”?",{folder:e.label}))){var i={folderId:e.folderId};this.setIndexBusy(),Craft.sendActionRequest("POST","assets/delete-folder",{data:i}).then((function(e){t.setIndexAvailable(),Craft.cp.displayNotice(Craft.t("app","Folder deleted.")),t.sourcePath=t.sourcePath.slice(0,t.sourcePath.length-1),t.updateElements()})).catch((function(e){var i=e.response;t.setIndexAvailable(),Craft.cp.displayError(i.data.message)}))}},_renameFolder:function(){var t=this,e=this.sourcePath[this.sourcePath.length-1],i=prompt(Craft.t("app","Rename folder"),e.label);i&&i!==e.label&&(this.setIndexBusy(),Craft.sendActionRequest("POST","assets/rename-folder",{data:{folderId:e.folderId,newName:i}}).then((function(e){Craft.cp.displayNotice(Craft.t("app","Folder renamed."));var i=t.sourcePath.slice();i[i.length-1].label=e.data.newName,i[i.length-1].uri=i[i.length-2].uri+"/".concat(e.data.newName),t.sourcePath=i})).catch((function(t){var e=t.response;Craft.cp.displayError(e.data.message)})).finally((function(){t.setIndexAvailable()})))},getMoveTargetSourceKeys:function(t){var e=t?"data-can-move-peer-files-to":"data-can-move-to";return this.$sources.toArray().filter((function(t){var i=$(t).data("volume-handle");return i&&"temp"!==i&&Garnish.hasAttr(t,e)})).map((function(t){return $(t).data("key")}))},_moveFolder:function(){var e=this,i=this.sourcePath[this.sourcePath.length-1],s=this.sourcePath[this.sourcePath.length-2],n=[i.folderId];s&&n.push(s.folderId),new Craft.VolumeFolderSelectorModal({sources:this.getMoveTargetSourceKeys(!0),showTitle:!0,modalTitle:Craft.t("app","Move to"),selectBtnLabel:Craft.t("app","Move"),disabledFolderIds:n,indexSettings:{defaultSource:this.sourceKey,defaultSourcePath:this.sourcePath.slice(0,this.sourcePath.length-1)},onSelect:function(s){var n,a,r=(n=s,a=1,function(t){if(Array.isArray(t))return t}(n)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(n,a)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(n,a)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())[0];e.$sourcePathActionsBtn.focus(),(new Craft.AssetMover).moveFolders([i.folderId],r.folderId).then((function(t){t&&(Craft.cp.displayNotice(Craft.t("app","{totalItems, plural, =1{Item} other{Items}} moved.",{totalItems:t})),e.sourcePath=e.sourcePath.slice(0,e.sourcePath.length-1),e.clearSearch(!1),e.updateElements())}))}})},_positionProgressBar:function(){this.progressBar||(this.progressBar=new Craft.ProgressBar(this.$main,!0));var t=$(),e=0,i=0;"index"===this.settings.context?(t=this.progressBar.$progressBar.closest("#content"),e=Garnish.$win.scrollTop()):(t=this.progressBar.$progressBar.closest(".main"),e=this.$main.scrollTop());var s=e-t.offset().top,n=Garnish.$win.height();i=t.height()>n?n/2-6+s:t.height()/2-6,"index"!==this.settings.context&&(i=e+(t.height()/2-6)),this.progressBar.$progressBar.css({top:i})}},{defaults:{showFolders:!0,foldersOnly:!1,disabledFolderIds:[]}}),Craft.registerElementIndexClass("craft\\elements\\Asset",Craft.AssetIndex)},1016:function(){function t(t,i){var s="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!s){if(Array.isArray(t)||(s=e(t))||i&&t&&"number"==typeof t.length){s&&(t=s);var n=0,a=function(){};return{s:a,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){s=s.call(t)},n:function(){var t=s.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==s.return||s.return()}finally{if(l)throw r}}}}function e(t,e){if(t){if("string"==typeof t)return i(t,e);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?i(t,e):void 0}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.AssetMover=Garnish.Base.extend({moveAssets:function(t,e){var i=t.map((function(t){return{for:"asset",action:"assets/move-asset",params:{assetId:t,folderId:e}}}));return this._batchMoveRequests(i,{conflictChoices:[{value:"keepBoth",title:Craft.t("app","Keep both")},{value:"replace",title:Craft.t("app","Replace it")}],handleConflictChoice:function(t){var e={folderId:t.request.params.folderId,assetId:t.assetId};switch(t.choice){case"replace":e.force=!0;break;case"keepBoth":e.filename=t.suggestedFilename}return{action:"assets/move-asset",params:e}}})},moveFolders:function(t,s){var n=this;return new Promise((function(a,r){var o=[],l=[],h=t.map((function(t){return{for:"folder",action:"assets/move-folder",params:{folderId:t,parentId:s},onSuccess:function(s){var n;s.transferList.length&&o.push.apply(o,function(t){if(Array.isArray(t))return i(t)}(n=s.transferList)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(n)||e(n)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),l.push(t)}}}));n._batchMoveRequests(h,{conflictChoices:[{value:"replace",title:Craft.t("app","Replace the folder (all existing files will be deleted)")},{value:"merge",title:Craft.t("app","Merge the folder (any conflicting files will be replaced)")}],handleConflictChoice:function(t){var e={folderId:t.folderId,parentId:t.parentId};switch(t.choice){case"replace":e.force=!0;break;case"merge":e.merge=!0}return{action:"assets/move-folder",params:e}}}).then((function(t){n._processTransferList(o).then((function(){n._deleteFolders(l).then((function(){a(t)}))}))})).catch(r)}))},_processTransferList:function(t){return this._batchRequests(t.map((function(t){return{action:"assets/move-asset",params:t}})))},_deleteFolders:function(t){return this._batchRequests(t.map((function(t){return{action:"assets/delete-folder",params:{folderId:t}}})))},_batchMoveRequests:function(e,i){var s=this;return new Promise((function(n){var a=0;s._batchRequests(e).then((function(e){Craft.elementIndex.promptHandler.resetPrompts();var r,o=t(e);try{for(o.s();!(r=o.n()).done;){var l=r.value;l.success&&a++,l.conflict&&Craft.elementIndex.promptHandler.addPrompt(Object.assign({},l,{prompt:{message:l.conflict,choices:i.conflictChoices}})),l.error&&Craft.cp.displayError(l.error)}}catch(t){o.e(t)}finally{o.f()}Craft.elementIndex.promptHandler.getPromptCount()?Craft.elementIndex.promptHandler.showBatchPrompts((function(e){Craft.elementIndex.promptHandler.resetPrompts();var r,o=[],l=t(e);try{for(l.s();!(r=l.n()).done;){var h=r.value;if("cancel"!==h.choice&&i.handleConflictChoice){var d=i.handleConflictChoice(h);h.request&&h.request.onSuccess&&(d.onSuccess=h.request.onSuccess),o.push(d)}}}catch(t){l.e(t)}finally{l.f()}s._batchMoveRequests(o,i).then((function(t){n(a+t)}))})):n(a)}))}))},_batchRequests:function(e){return new Promise((function(i){if(e.length){Craft.elementIndex.setIndexBusy(),Craft.elementIndex._positionProgressBar(),Craft.elementIndex.progressBar.resetProgressBar(),Craft.elementIndex.progressBar.setItemCount(e.length),Craft.elementIndex.progressBar.showProgressBar();var s,n=[],a=e.length,r=t(e);try{var o=function(){var t=s.value;Craft.sendActionRequest("POST",t.action,{data:t.params}).then((function(e){n.push(Object.assign({},e.data,{request:t})),e.data.success&&t.onSuccess&&t.onSuccess(e.data)})).catch((function(e){e.response&&e.response.data&&n.push(Object.assign({},e.response.data,{request:t}))})).finally((function(){0==--a?(Craft.elementIndex.setIndexAvailable(),Craft.elementIndex.progressBar.hideProgressBar(),Craft.cp.runQueue(),i(n)):(Craft.elementIndex.progressBar.incrementProcessedItemCount(1),Craft.elementIndex.progressBar.updateProgressBar())}))};for(r.s();!(s=r.n()).done;)o()}catch(t){r.e(t)}finally{r.f()}}else i([])}))}})},5077:function(){Craft.AssetSelectInput=Craft.BaseElementSelectInput.extend({$uploadBtn:null,uploader:null,progressBar:null,openPreviewTimeout:null,init:function(){this.base.apply(this,arguments),this.settings.canUpload&&this._attachUploader(),this.updateAddElementsBtn(),this.addListener(this.$elementsContainer,"keydown",this._onKeyDown.bind(this)),this.elementSelect.on("focusItem",this._onElementFocus.bind(this))},_onKeyDown:function(t){if(t.keyCode===Garnish.SPACE_KEY&&t.shiftKey)return this.openPreview(),t.stopPropagation(),!1},onAddElements:function(){var t=this;this.$elements.find(".elementthumb").addClass("open-preview").on("click",(function(e){t.clearOpenPreviewTimeout(),t.openPreviewTimeout=setTimeout((function(){t.openPreview(),t.openPreviewTimeout=null}),500)})).on("dblclick",(function(e){t.clearOpenPreviewTimeout()})),this.base()},clearOpenPreviewTimeout:function(){this.openPreviewTimeout&&(clearTimeout(this.openPreviewTimeout),this.openPreviewTimeout=null)},openPreview:function(){if(Craft.PreviewFileModal.openInstance)Craft.PreviewFileModal.openInstance.selfDestruct();else{var t=this.elementSelect.$focusedItem;t.length&&this._loadPreview(t)}},_onElementFocus:function(t){var e=$(t.item);Craft.PreviewFileModal.openInstance&&e.length&&this._loadPreview(e)},_loadPreview:function(t){var e={minGutter:50};t.data("image-width")&&(e.startingWidth=t.data("image-width"),e.startingHeight=t.data("image-height")),new Craft.PreviewFileModal(t.data("id"),this.elementSelect,e)},_attachUploader:function(){var t=this;this.progressBar=new Craft.ProgressBar($('<div class="progress-shade"></div>').appendTo(this.$container));var e={url:Craft.getActionUrl("assets/upload"),dropZone:this.$container,formData:{fieldId:this.settings.fieldId}};this.settings.sourceElementId&&(e.formData.elementId=this.settings.sourceElementId),this.settings.criteria.siteId&&(e.formData.siteId=this.settings.criteria.siteId),this.$addElementBtn&&(this.$uploadBtn=$("<button/>",{type:"button",class:"btn dashed","data-icon":"upload","aria-label":1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files"),"aria-describedby":this.settings.describedBy,text:1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files")}).insertAfter(this.$addElementBtn),e.fileInput=$("<input/>",{type:"file",class:"hidden",multiple:1!=this.settings.limit}).insertAfter(this.$uploadBtn),Garnish.$win.trigger("resize")),void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(e.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),void 0!==this.settings.criteria.kind&&(e.allowedKinds=this.settings.criteria.kind),e.canAddMoreFiles=this.canAddMoreFiles.bind(this),e.events={},e.events.fileuploadstart=this._onUploadStart.bind(this),e.events.fileuploadprogressall=this._onUploadProgress.bind(this),e.events.fileuploaddone=this._onUploadComplete.bind(this),e.events.fileuploadfail=this._onUploadFailure.bind(this),this.uploader=new Craft.Uploader(this.$container,e),this.$uploadBtn&&this.$uploadBtn.on("click",(function(e){t.$uploadBtn.next("input[type=file]").trigger("click")}))},enableAddElementsBtn:function(){this.$uploadBtn&&this.$uploadBtn.removeClass("hidden"),this.base()},disableAddElementsBtn:function(){this.$uploadBtn&&this.$uploadBtn.addClass("hidden"),this.base()},selectUploadedFile:function(t){if(this.canAddMoreElements()){var e=t.$element;e.addClass("removable"),e.prepend('<input type="hidden" name="'+this.settings.name+'[]" value="'+t.id+'"><a class="delete icon" title="'+Craft.t("app","Remove")+'"></a>'),e.appendTo(this.$elementsContainer);var i=-(e.outerWidth()+10);this.$addElementBtn.css("margin-"+Craft.left,i+"px");var s={};s["margin-"+Craft.left]=0,this.$addElementBtn.velocity(s,"fast"),this.addElements(e),delete this.modal}},_onUploadStart:function(){this.progressBar.$progressBar.css({top:Math.round(this.$container.outerHeight()/2)-6}),this.$container.addClass("uploading"),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){var i=this;if(e.result.error)Craft.cp.displayError(e.result.error),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading");else{var s={elementId:e.result.assetId,siteId:this.settings.criteria.siteId,thumbSize:this.settings.viewMode};Craft.sendActionRequest("POST","elements/get-element-html",{data:s}).then((function(t){var e=$(t.data.html);Craft.appendHeadHtml(t.data.headHtml),i.selectUploadedFile(Craft.getElementInfo(e)),i.uploader.isLastUpload()&&(i.progressBar.hideProgressBar(),i.$container.removeClass("uploading"),i.$container.trigger("change"))})).catch((function(t){var e=t.response;Craft.cp.displayError(e.data.message)})),Craft.cp.runQueue()}},_onUploadFailure:function(t,e){var i,s=e.response(),n=(null==s||null===(i=s.jqXHR)||void 0===i?void 0:i.responseJSON)||{},a=n.message,r=n.filename;a||(a=r?Craft.t("app","Upload failed for “{filename}”.",{filename:r}):Craft.t("app","Upload failed.")),Craft.cp.displayError(a),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading")},canAddMoreFiles:function(t){return!this.settings.limit||this.$elements.length+t<this.settings.limit}})},4606:function(){Craft.AssetSelectorModal=Craft.BaseElementSelectorModal.extend({$selectTransformBtn:null,_selectedTransform:null,init:function(t,e){e=$.extend({},Craft.AssetSelectorModal.defaults,e),this.base(t,e),e.transforms.length&&this.createSelectTransformButton(e.transforms)},createSelectTransformButton:function(t){if(t&&t.length){var e=$('<div class="btngroup"/>').appendTo(this.$primaryButtons);this.$selectBtn.appendTo(e),this.$selectTransformBtn=$("<button/>",{type:"button",class:"btn menubtn disabled",text:Craft.t("app","Select transform")}).appendTo(e);for(var i=$('<div class="menu" data-align="right"></div>').insertAfter(this.$selectTransformBtn),s=$("<ul></ul>").appendTo(i),n=0;n<t.length;n++)$('<li><a data-transform="'+t[n].handle+'">'+t[n].name+"</a></li>").appendTo(s);var a=new Garnish.MenuBtn(this.$selectTransformBtn,{onOptionSelect:this.onSelectTransform.bind(this)});a.disable(),this.$selectTransformBtn.data("menuButton",a)}},onSelectionChange:function(t){var e=this.elementIndex.getSelectedElements(),i=!1;if(e.length&&this.settings.transforms.length){i=!0;for(var s=0;s<e.length&&$(".element.hasthumb:first",e[s]).length;s++);}var n=null;this.$selectTransformBtn&&(n=this.$selectTransformBtn.data("menuButton")),i?(n&&n.enable(),this.$selectTransformBtn.removeClass("disabled")):this.$selectTransformBtn&&(n&&n.disable(),this.$selectTransformBtn.addClass("disabled")),this.base()},onSelectTransform:function(t){var e=$(t).data("transform");this.selectImagesWithTransform(e)},selectImagesWithTransform:function(t){var e=this;void 0===Craft.AssetSelectorModal.transformUrls[t]&&(Craft.AssetSelectorModal.transformUrls[t]={});for(var i=this.elementIndex.getSelectedElements(),s=[],n=0;n<i.length;n++){var a=$(i[n]),r=Craft.getElementInfo(a).id;void 0===Craft.AssetSelectorModal.transformUrls[t][r]&&s.push(r)}s.length?(this.showFooterSpinner(),this.fetchMissingTransformUrls(s,t,(function(){e.hideFooterSpinner(),e.selectImagesWithTransform(t)}))):(this._selectedTransform=t,this.selectElements(),this._selectedTransform=null)},fetchMissingTransformUrls:function(t,e,i){var s=this,n=t.pop(),a={assetId:n,handle:e};Craft.sendActionRequest("POST","assets/generate-transform",{data:a}).then((function(t){Craft.AssetSelectorModal.transformUrls[e][n]=t.data.url||!1})).catch((function(){Craft.AssetSelectorModal.transformUrls[e][n]=!1})).finally((function(){t.length?s.fetchMissingTransformUrls(t,e,i):i()}))},getElementInfo:function(t){var e=this.base(t);if(this._selectedTransform)for(var i=0;i<e.length;i++){var s=e[i].id;void 0!==Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s]&&!1!==Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s]&&(e[i].url=Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s])}return e},onSelect:function(t){this.settings.onSelect(t,this._selectedTransform)}},{defaults:{canSelectImageTransforms:!1,transforms:[]},transformUrls:{}}),Craft.registerElementSelectorModalClass("craft\\elements\\Asset",Craft.AssetSelectorModal)},8391:function(){Craft.AssetsFieldSettings=Garnish.Base.extend({$useSingleFolderInput:null,$sourceInputs:null,$defaultUploadLocationSelect:null,$defaultUploadLocationOptions:null,init:function(t,e,i){var s=this;this.$useSingleFolderInput=$("#".concat(t)),this.$sourceInputs=$("#".concat(e," input")),this.$defaultUploadLocationSelect=$("#".concat(i)),this.$defaultUploadLocationOptions=this.$defaultUploadLocationSelect.children("option"),this.updateDefaultUploadLocationSelect(),Garnish.requestAnimationFrame((function(){s.addListener(s.$useSingleFolderInput,"change","updateDefaultUploadLocationSelect"),s.addListener(s.$sourceInputs,"change","updateDefaultUploadLocationSelect")}))},updateDefaultUploadLocationSelect:function(){if(!this.$useSingleFolderInput.prop("checked")){for(var t,e=this.$defaultUploadLocationSelect.val(),i=0;i<this.$sourceInputs.length;i++){var s=this.$sourceInputs.eq(i),n=s.val(),a=s.prop("checked");if("*"===n){if(a)return void this.$defaultUploadLocationOptions.prop("disabled",!1)}else this.getOption(n).prop("disabled",!a),a&&!t&&(t=n)}var r=this.getOption(e);(!r.length||r.prop("disabled")&&t)&&this.$defaultUploadLocationSelect.val(t)}},getOption:function(t){return this.$defaultUploadLocationOptions.filter('[value="'.concat(t,'"]'))}})},9222:function(){Craft.AuthManager=Garnish.Base.extend({remainingSessionTime:null,checkRemainingSessionTimer:null,showLoginModalTimer:null,decrementLogoutWarningInterval:null,showingLogoutWarningModal:!1,showingLoginModal:!1,logoutWarningModal:null,loginModal:null,$logoutWarningPara:null,$passwordInput:null,$loginBtn:null,$loginErrorPara:null,submitLoginIfLoggedOut:!1,init:function(){Craft.username&&this.updateRemainingSessionTime(Craft.remainingSessionTime)},setCheckRemainingSessionTimer:function(t){this.checkRemainingSessionTimer&&clearTimeout(this.checkRemainingSessionTimer),this.checkRemainingSessionTimer=setTimeout(this.checkRemainingSessionTime.bind(this),1e3*t)},checkRemainingSessionTime:function(t){var e=this;$.ajax({url:Craft.getActionUrl("users/session-info",t?null:"dontExtendSession=1"),type:"GET",dataType:"json",complete:function(t,i){"success"===i?(void 0!==t.responseJSON.csrfTokenValue&&void 0!==Craft.csrfTokenValue&&(Craft.csrfTokenValue=t.responseJSON.csrfTokenValue),e.updateRemainingSessionTime(t.responseJSON.timeout),e.submitLoginIfLoggedOut=!1):e.updateRemainingSessionTime(-1)}})},updateRemainingSessionTime:function(t){this.remainingSessionTime=parseInt(t),-1!==this.remainingSessionTime&&this.remainingSessionTime<Craft.AuthManager.minSafeSessionTime?(this.remainingSessionTime?(this.showingLogoutWarningModal||this.showLogoutWarningModal(),this.remainingSessionTime<Craft.AuthManager.checkInterval&&(this.showLoginModalTimer&&clearTimeout(this.showLoginModalTimer),this.showLoginModalTimer=setTimeout(this.showLoginModal.bind(this),1e3*this.remainingSessionTime))):this.showingLoginModal?this.submitLoginIfLoggedOut&&this.submitLogin():this.showLoginModal(),this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval)):(this.hideLogoutWarningModal(),this.hideLoginModal(),-1!==this.remainingSessionTime&&this.remainingSessionTime<Craft.AuthManager.minSafeSessionTime+Craft.AuthManager.checkInterval?this.setCheckRemainingSessionTimer(this.remainingSessionTime-Craft.AuthManager.minSafeSessionTime+1):this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval))},showLogoutWarningModal:function(){var t;if(this.showingLoginModal?(this.hideLoginModal(!0),t=!0):t=!1,this.showingLogoutWarningModal=!0,!this.logoutWarningModal){var e=$('<form id="logoutwarningmodal" class="modal alert fitted"/>'),i=$('<div class="body"/>').appendTo(e),s=$('<div class="buttons right"/>').appendTo(i),n=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Sign out now")}).appendTo(s),a=$("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Keep me signed in")}).appendTo(s);this.$logoutWarningPara=$("<p/>").prependTo(i),this.logoutWarningModal=new Garnish.Modal(e,{autoShow:!1,closeOtherModals:!1,hideOnEsc:!1,hideOnShadeClick:!1,shadeClass:"modal-shade dark logoutwarningmodalshade",onFadeIn:function(){Garnish.isMobileBrowser(!0)||setTimeout((function(){a.trigger("focus")}),100)}}),this.addListener(n,"activate","logout"),this.addListener(e,"submit","renewSession")}t?this.logoutWarningModal.quickShow():this.logoutWarningModal.show(),this.updateLogoutWarningMessage(),this.decrementLogoutWarningInterval=setInterval(this.decrementLogoutWarning.bind(this),1e3)},updateLogoutWarningMessage:function(){this.$logoutWarningPara.text(Craft.t("app","Your session will expire in {time}.",{time:Craft.secondsToHumanTimeDuration(this.remainingSessionTime)})),this.logoutWarningModal.updateSizeAndPosition()},decrementLogoutWarning:function(){this.remainingSessionTime>0&&(this.remainingSessionTime--,this.updateLogoutWarningMessage()),0===this.remainingSessionTime&&clearInterval(this.decrementLogoutWarningInterval)},hideLogoutWarningModal:function(t){this.showingLogoutWarningModal=!1,this.logoutWarningModal&&(t?this.logoutWarningModal.quickHide():this.logoutWarningModal.hide(),this.decrementLogoutWarningInterval&&clearInterval(this.decrementLogoutWarningInterval))},showLoginModal:function(){var t,e=this;if(this.showingLogoutWarningModal?(this.hideLogoutWarningModal(!0),t=!0):t=!1,this.showingLoginModal=!0,!this.loginModal){var i=$('<form id="loginmodal" class="modal alert fitted"/>'),s=$('<div class="body"><h2>'+Craft.t("app","Your session has ended.")+"</h2><p>"+Craft.t("app","Enter your password to log back in.")+"</p></div>").appendTo(i),n=$('<div class="inputcontainer">').appendTo(s),a=$('<div class="flex"/>').appendTo(n),r=$('<div class="flex-grow"/>').appendTo(a),o=$("<div/>").appendTo(a),l=$('<div class="passwordwrapper"/>').appendTo(r);this.$passwordInput=$('<input type="password" class="text password fullwidth" autocomplete="current-password" placeholder="'+Craft.t("app","Password")+'"/>').appendTo(l),this.$loginBtn=Craft.ui.createSubmitButton({class:"disabled",label:Craft.t("app","Sign in"),spinner:!0}).attr("aria-disabled","true").appendTo(o),this.$loginErrorPara=$('<p class="error"/>').appendTo(s),this.loginModal=new Garnish.Modal(i,{autoShow:!1,closeOtherModals:!1,hideOnEsc:!1,hideOnShadeClick:!1,shadeClass:"modal-shade dark loginmodalshade",onFadeIn:function(){Garnish.isMobileBrowser(!0)||setTimeout((function(){e.$passwordInput.trigger("focus")}),100)},onFadeOut:function(){e.$passwordInput.val("")}}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:function(t){e.$passwordInput=t}}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(i,"submit","login")}t?this.loginModal.quickShow():this.loginModal.show()},hideLoginModal:function(t){this.showingLoginModal=!1,this.loginModal&&(t?this.loginModal.quickHide():this.loginModal.hide())},logout:function(){$.get({url:Craft.getActionUrl("users/logout"),dataType:"json",success:function(){Craft.redirectTo("")}})},renewSession:function(t){t&&t.preventDefault(),this.hideLogoutWarningModal(),this.checkRemainingSessionTime(!0)},validatePassword:function(){return this.$passwordInput.val().length>=6?(this.$loginBtn.removeClass("disabled"),this.$loginBtn.removeAttr("aria-disabled"),!0):(this.$loginBtn.addClass("disabled"),this.$loginBtn.attr("aria-disabled","true"),!1)},login:function(t){t&&t.preventDefault(),this.validatePassword()&&(this.$loginBtn.addClass("loading"),this.clearLoginError(),void 0!==Craft.csrfTokenValue?(this.submitLoginIfLoggedOut=!0,this.checkRemainingSessionTime()):this.submitLogin())},submitLogin:function(){var t=this,e={loginName:Craft.username,password:this.$passwordInput.val()};Craft.sendActionRequest("POST","users/login",{data:e}).then((function(e){t.$loginBtn.removeClass("loading"),t.hideLoginModal(),t.checkRemainingSessionTime()})).catch((function(e){var i=e.response;t.$loginBtn.removeClass("loading"),t.showLoginError(i.data.message||null),Garnish.shake(t.loginModal.$container),Garnish.isMobileBrowser(!0)||t.$passwordInput.trigger("focus")}))},showLoginError:function(t){null==t&&(t=Craft.t("app","A server error occurred.")),this.$loginErrorPara.text(t),this.loginModal.updateSizeAndPosition()},clearLoginError:function(){this.showLoginError("")}},{checkInterval:60,minSafeSessionTime:120})},5774:function(){function t(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,s)}return i}function e(e){for(var s=1;s<arguments.length;s++){var n=null!=arguments[s]?arguments[s]:{};s%2?t(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function s(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(t,e)||r(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(t){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n(t)}function a(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=r(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var s=0,n=function(){};return{s:n,n:function(){return s>=t.length?{done:!0}:{done:!1,value:t[s++]}},e:function(t){throw t},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,o=!0,l=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return o=t.done,t},e:function(t){l=!0,a=t},f:function(){try{o||null==i.return||i.return()}finally{if(l)throw a}}}}function r(t,e){if(t){if("string"==typeof t)return o(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?o(t,e):void 0}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.BaseElementIndex=Garnish.Base.extend({initialized:!1,elementType:null,idPrefix:null,instanceState:null,sourceStates:null,sourceStatesStorageKey:null,searchTimeout:null,sourceSelect:null,$container:null,$main:null,isIndexBusy:!1,$sidebar:null,showingSidebar:null,sourceKey:null,rootSourceKey:null,sourceViewModes:null,$source:null,$rootSource:null,sourcesByKey:null,$visibleSources:null,$sourceActionsContainer:null,$sourceActionsBtn:null,$toolbar:null,toolbarOffset:null,$searchContainer:null,$search:null,$filterBtn:null,searching:!1,searchText:null,sortByScore:null,trashed:!1,drafts:!1,$clearSearchBtn:null,$statusMenuBtn:null,$statusMenuContainer:null,statusMenu:null,status:null,$siteMenuBtn:null,siteMenu:null,siteId:null,_sourcePath:null,$sourcePathOuterContainer:null,$sourcePathInnerContainer:null,$sourcePathOverflowBtnContainer:null,$sourcePathActionsBtn:null,$elements:null,$updateSpinner:null,$viewModeBtnContainer:null,viewModeBtns:null,_viewMode:null,view:null,_autoSelectElements:null,$countSpinner:null,$countContainer:null,$actionsContainer:null,page:1,resultSet:null,totalResults:null,$exportBtn:null,actions:null,actionsHeadHtml:null,actionsBodyHtml:null,$selectAllContainer:null,$selectAllCheckbox:null,showingActionTriggers:!1,exporters:null,exportersByType:null,_$triggers:null,_cancelToken:null,viewMenus:null,activeViewMenu:null,filterHuds:null,_activeElement:null,get viewMode(){return"structure"!==this._viewMode||this.canSortByStructure()?this._viewMode:"table"},set viewMode(t){this._viewMode=t},init:function(t,e,i){var s=this;if(this.elementType=t,this.$container=e,this.setSettings(i,Craft.BaseElementIndex.defaults),this.idPrefix=Craft.randomString(10),this.instanceState=this.getDefaultInstanceState(),this.sourceStates={},this.settings.storageKey&&$.extend(this.instanceState,Craft.getLocalStorage(this.settings.storageKey),{}),this.sourceStatesStorageKey="BaseElementIndex."+this.elementType+"."+this.settings.context,$.extend(this.sourceStates,Craft.getLocalStorage(this.sourceStatesStorageKey,{})),this.$main=this.$container.find(".main"),this.$toolbar=this.$container.find(this.settings.toolbarSelector),this.$statusMenuBtn=this.$toolbar.find(".statusmenubtn:first"),this.$statusMenuContainer=this.$statusMenuBtn.parent(),this.$siteMenuBtn=this.$container.find(".sitemenubtn:first"),this.$searchContainer=this.$toolbar.find(".search-container:first"),this.$search=this.$searchContainer.children("input:first"),this.$filterBtn=this.$searchContainer.children(".filter-btn:first"),this.$clearSearchBtn=this.$searchContainer.children(".clear-btn:first"),this.$sidebar=this.$container.find(".sidebar:first"),this.$sourceActionsContainer=this.$sidebar.find("#source-actions"),this.$elements=this.$container.find(".elements:first"),this.$updateSpinner=this.$elements.find(".spinner"),this.$updateSpinner.length||(this.$updateSpinner=$("<div/>",{class:"update-spinner spinner spinner-absolute"}).appendTo(this.$elements)),this.$countSpinner=this.$container.find("#count-spinner"),this.$countContainer=this.$container.find("#count-container"),this.$actionsContainer=this.$container.find("#actions-container"),this.$exportBtn=this.$container.find("#export-btn"),this.settings.hideSidebar&&(this.$sidebar.hide(),$(".body, .content",this.$container).removeClass("has-sidebar")),this.initSources()){if(this.$statusMenuBtn.length&&(this.statusMenu=this.$statusMenuBtn.menubtn().data("menubtn").menu,this.statusMenu.on("optionselect",this._handleStatusChange.bind(this))),this.$siteMenuBtn.length){this.siteMenu=this.$siteMenuBtn.menubtn().data("menubtn").menu;var n=this.siteMenu.$options.filter(".sel:first");if(n.length||(n=this.siteMenu.$options.first()),n.length?this._setSite(n.data("site-id")):this.settings.criteria={id:"0"},this.siteMenu.on("optionselect",this._handleSiteChange.bind(this)),this.siteId){var a=this.settings.defaultSiteId||Craft.cp.getSiteId();if(a&&a!=this.siteId){var r=this.siteMenu.$options.filter('[data-site-id="'+a+'"]:first');r.length&&r.trigger("click")}}}else this.settings.criteria&&this.settings.criteria.siteId&&"*"!==this.settings.criteria.siteId?this._setSite(this.settings.criteria.siteId):this._setSite(Craft.siteId);this.settings.criteria&&this.settings.criteria.siteId&&delete this.settings.criteria.siteId,this.addListener(this.$search,"input",(function(){!s.searching&&s.$search.val()?s.startSearching():s.searching&&!s.$search.val()&&s.stopSearching(),s.searchTimeout&&clearTimeout(s.searchTimeout),s.searchTimeout=setTimeout(s.updateElementsIfSearchTextChanged.bind(s),500)})),this.addListener(this.$search,"keypress",(function(t){t.keyCode===Garnish.RETURN_KEY&&(t.preventDefault(),s.searchTimeout&&clearTimeout(s.searchTimeout),s.updateElementsIfSearchTextChanged())})),this.addListener(this.$clearSearchBtn,"click",(function(){s.clearSearch(!0),Garnish.isMobileBrowser(!0)||s.$search.trigger("focus")})),Garnish.isMobileBrowser(!0)||this.$search.trigger("focus"),this.viewMenus={},this.filterHuds={},this.addListener(this.$filterBtn,"click","showFilterHud");var o="index"===this.settings.context?Craft.getQueryParams():{};if(o.status){var l;switch(o.status){case"trashed":l="[data-trashed]";break;case"drafts":l="[data-drafts]";break;default:l='[data-status="'.concat(o.status,'"]')}var h=this.statusMenu.$options.filter(l);h.length?this.statusMenu.selectOption(h[0]):Craft.setQueryParam("status",null)}this.addListener(this.$exportBtn,"click","_showExportHud"),this.initialized=!0,this.afterInit(),this.selectDefaultSource();var d=this.getDefaultSourcePath();if(null!==d&&(this.sourcePath=d),"index"===this.settings.context&&this.addListener(Garnish.$win,"resize","handleResize"),this.handleResize(),o.search&&(this.startSearching(),this.searchText=o.search),o.sort){var c=o.sort.lastIndexOf("-");if(-1!==c){var u=o.sort.substring(0,c),p=o.sort.substring(c+1);this.setSelectedSortAttribute(u,p)}}this.setPage(Craft.pageNum),this.updateElements(!0)}},afterInit:function(){this.onAfterInit()},handleResize:function(){this.sourcePath.length&&this.settings.showSourcePath&&this._updateSourcePathVisibility()},_createCancelToken:function(){return this._cancelToken=axios.CancelToken.source(),this._cancelToken.token},_cancelRequests:function(){this._cancelToken&&this._cancelToken.cancel()},getSourceContainer:function(){return this.$sidebar.find("nav > ul")},get $sources(){if(this.sourceSelect)return this.sourceSelect.$items},getSite:function(){var t=this;if(this.siteId)return Craft.sites.find((function(e){return e.id==t.siteId}))},initSources:function(){var t=this._getSourcesInList(this.getSourceContainer(),!0);if(0===t.length)return!1;this.sourceSelect||(this.sourceSelect=new Garnish.Select(this.$sidebar.find("nav"),{multi:!1,allowEmpty:!1,vertical:!0,onSelectionChange:this._handleSourceSelectionChange.bind(this)})),this.sourcesByKey={};for(var e=0;e<t.length;e++)this.initSource($(t[e]));return!0},selectDefaultSource:function(){var t,e;return"index"===this.settings.context&&(t=Craft.getQueryParam("source")),t||(t=this.getDefaultSourceKey()),t&&(e=this.getSourceByKey(t),-1===this.$visibleSources.index(e)&&(e=null)),t&&e||(e=this.$visibleSources.first()),this.selectSource(e)},refreshSources:function(){var t=this;this.sourceSelect.removeAllItems(),this.setIndexBusy(),Craft.sendActionRequest("POST",this.settings.refreshSourcesAction,{data:{context:this.settings.context,elementType:this.elementType}}).then((function(e){t.setIndexAvailable(),t.getSourceContainer().replaceWith(e.data.html),t.initSources(),t.selectDefaultSource()})).catch((function(e){axios.isCancel(e)||(t.setIndexAvailable(),Craft.cp.displayError(Craft.t("app","A server error occurred.")))}))},initSource:function(t){this.sourceSelect.addItems(t),this.initSourceToggle(t),this.sourcesByKey[t.data("key")]=t,t.data("hasNestedSources")&&-1!==this.instanceState.expandedSources.indexOf(t.data("key"))&&this._expandSource(t)},initSourceToggle:function(t){this.deinitSourceToggle(t);var e=this._getSourceToggle(t);e.length?(this.addListener(t,"dblclick","_handleSourceDblClick"),this.addListener(e,"click","_handleSourceToggleClick"),t.data("hasNestedSources",!0)):t.data("hasNestedSources",!1)},deinitSource:function(t){this.sourceSelect.removeItems(t),this.deinitSourceToggle(t),delete this.sourcesByKey[t.data("key")]},deinitSourceToggle:function(t){t.data("hasNestedSources")&&(this.removeListener(t,"dblclick"),this.removeListener(this._getSourceToggle(t),"click")),t.removeData("hasNestedSources")},getDefaultInstanceState:function(){return{selectedSource:null,expandedSources:[]}},getDefaultSourceKey:function(){var t,e=null;if(this.settings.defaultSource){var i,s=null,n=!1,r=a(this.settings.defaultSource.split("/"));try{for(r.s();!(i=r.n()).done;){var o=i.value;s&&(this._expandSource(s),n=!0);var l=(null!==e?"".concat(e,"/"):"")+o,h=this.getSourceByKey(l);if(!h){s&&this._collapseSource(s);break}s=h,e=l}}catch(t){r.e(t)}finally{r.f()}n&&this._setSite(this.siteId)}return null!==(t=e)&&void 0!==t?t:this.instanceState.selectedSource},getDefaultSourcePath:function(){return null!==this.settings.defaultSourcePath&&void 0!==this.settings.defaultSourcePath[0]&&!0===this.settings.defaultSourcePath[0].canView&&(this.sourcePath.length>0&&this.sourcePath[0].handle===this.settings.defaultSourcePath[0].handle||0===this.sourcePath.length)?this.settings.defaultSourcePath:null},getDefaultExpandedSources:function(){return this.instanceState.expandedSources},get sourcePath(){return this._sourcePath||[]},set sourcePath(t){var e=this;this._sourcePath=t&&t.length?t:null,this.$sourcePathOuterContainer&&(this.$sourcePathOuterContainer.remove(),this.$sourcePathOuterContainer=null,this.$sourcePathInnerContainer=null,this.$sourcePathOverflowBtnContainer=null,this.$sourcePathActionsBtn=null),this._sourcePath&&this.settings.showSourcePath&&function(){var i=e.getSourcePathActions();e.$sourcePathOuterContainer=$("<div/>",{class:"source-path"}).insertBefore(e.$elements),e.$sourcePathInnerContainer=$("<div/>",{class:"chevron-btns"}).appendTo(e.$sourcePathOuterContainer);var s,n,a,r=$("<nav/>",{"aria-label":e.getSourcePathLabel()}).appendTo(e.$sourcePathInnerContainer),o=$("<ol/>").appendTo(r);if(t.length>1){e.$sourcePathOverflowBtnContainer=$("<li/>",{class:"first-step hidden"}).appendTo(o),n="menu"+Math.floor(1e6*Math.random()),s=$("<button/>",{type:"button",class:"btn",title:Craft.t("app","More items"),"aria-label":Craft.t("app","More items"),"data-disclosure-trigger":!0,"aria-controls":n}).append($("<span/>",{class:"btn-body"}).append($("<span/>",{class:"label"}).append($("<span/>",{"data-icon":"ellipsis","aria-hidden":"true"})))).append($("<span/>",{class:"chevron-right"})).appendTo(e.$sourcePathOverflowBtnContainer);var l=$("<div/>",{id:n,class:"menu menu--disclosure"}).appendTo(e.$sourcePathOverflowBtnContainer);a=$("<ul/>").appendTo(l),s.disclosureMenu()}for(var h=0;h<t.length;h++)!function(n){var r=t[n];a&&n<t.length-1&&(r.$overflowLi=$("<li/>",{class:"hidden"}).appendTo(a),$("<a/>",{class:"flex flex-nowrap",href:"#",type:"button",role:"button",html:r.icon?'<span data-icon="'.concat(r.icon,'" aria-hidden="true"></span><span>').concat(r.label,"</span>"):r.label}).appendTo(r.$overflowLi).on("click",(function(t){t.preventDefault(),s.data("trigger").hide(),e.selectSourcePathStep(n)})));var l=0===n,h=n===t.length-1;r.$li=$("<li/>").appendTo(o),l&&r.$li.addClass("first-step"),r.$btn=$("<a/>",{href:r.uri?Craft.getCpUrl(r.uri):"#",class:"btn",role:"button"}),r.icon&&r.$btn.attr("aria-label",r.label);var d=$("<span/>",{class:"btn-body"}).appendTo(r.$btn);r.$label=$("<span/>",{class:"label",html:r.icon?'<span data-icon="'.concat(r.icon,'" aria-hidden="true"></span>'):r.label}).appendTo(d),r.$btn.append($('<span class="chevron-left"/>')),h&&i.length?r.$btn.addClass("has-action-menu"):r.$btn.append($('<span class="chevron-right"/>')),h&&r.$btn.addClass("current-step").attr("aria-current","page"),r.$btn.appendTo(r.$li),e.addListener(r.$btn,"activate",(function(){e.selectSourcePathStep(n)}))}(h);if(i&&i.length){var d=e.getSourcePathActionLabel(),c="menu"+Math.floor(1e6*Math.random());e.$sourcePathActionsBtn=$("<button/>",{type:"button",class:"btn current-step",title:d,"aria-label":d,"data-disclosure-trigger":!0,"aria-controls":c}).append($("<span/>",{class:"btn-body"}).append($("<span/>",{class:"label"}))).append($("<span/>",{class:"chevron-right"})).appendTo(e.$sourcePathInnerContainer);var u=[i.filter((function(t){return!t.destructive&&!t.administrative})),i.filter((function(t){return t.destructive&&!t.administrative})),i.filter((function(t){return t.administrative}))].filter((function(t){return t.length})),p=$("<div/>",{id:c,class:"menu menu--disclosure"}).appendTo(e.$sourcePathInnerContainer);u.forEach((function(t,i){0!==i&&$("<hr/>").appendTo(p),e._buildSourcePathActionList(t).appendTo(p)})),e.$sourcePathActionsBtn.disclosureMenu(),e._updateSourcePathVisibility()}"index"===e.settings.context&&void 0!==t[t.length-1].uri&&"undefined"!=typeof history&&history.replaceState({},"",Craft.getCpUrl(t[t.length-1].uri))}(),this.onSourcePathChange()},getSourcePathLabel:function(){return""},getSourcePathActions:function(){return[]},getSourcePathActionLabel:function(){return""},_updateSourcePathVisibility:function(){var t=this.sourcePath[0],e=this.sourcePath[this.sourcePath.length-1];this.$sourcePathOverflowBtnContainer&&(this.$sourcePathOverflowBtnContainer.addClass("hidden"),t.$li.addClass("first-step"));var i,s=a(this.sourcePath);try{for(s.s();!(i=s.n()).done;){var n=i.value;n.$overflowLi&&n.$overflowLi.addClass("hidden"),n.$li.removeClass("hidden")}}catch(t){s.e(t)}finally{s.f()}e.$label.css("width",""),e.$btn.removeAttr("title");var r=this._checkSourcePathOverage();if(r){if(this.$sourcePathOverflowBtnContainer){this.$sourcePathOverflowBtnContainer.removeClass("hidden"),t.$li.removeClass("first-step");for(var o=0;o<this.sourcePath.length-1;o++){var l=this.sourcePath[o];if(l.$overflowLi.removeClass("hidden"),l.$li.addClass("hidden"),!(r=this._checkSourcePathOverage()))return}}if(!e.icon){var h=e.$label[0].getBoundingClientRect().width;e.$label.width(Math.floor(h-r)),e.$btn.attr("title",e.label)}}},_checkSourcePathOverage:function(){var t=this.$sourcePathOuterContainer[0].getBoundingClientRect().width,e=this.$sourcePathInnerContainer[0].getBoundingClientRect().width;return Math.max(e-t,0)},_buildSourcePathActionList:function(t){var e=this,i=$("<ul/>");return t.forEach((function(t){var s=$("<a/>",{href:"#",type:"button",role:"button","aria-label":t.label,text:t.label}).on("click",(function(i){i.preventDefault(),e.$sourcePathActionsBtn.data("trigger").hide(),t.onSelect&&t.onSelect()}));t.destructive&&s.addClass("error"),$("<li/>").append(s).appendTo(i)})),i},onSourcePathChange:function(){this.settings.onSourcePathChange(),this.trigger("sourcePathChange")},selectSourcePathStep:function(t){this.sourcePath=this.sourcePath.slice(0,t+1),this.sourcePath[t].$btn.focus(),this.clearSearch(!1),this.updateElements()},startSearching:function(){this.$clearSearchBtn.removeClass("hidden"),this.searching=!0,this.sortByScore=!0,this.activeViewMenu&&this.activeViewMenu.updateSortField()},clearSearch:function(t){this.searching&&(this.$search.val(""),this.searchTimeout&&clearTimeout(this.searchTimeout),this.stopSearching(),t?this.updateElementsIfSearchTextChanged():this.searchText=null)},stopSearching:function(){this.$clearSearchBtn.addClass("hidden"),this.searching=!1,this.sortByScore=!1,this.activeViewMenu&&this.activeViewMenu.updateSortField()},setInstanceState:function(t,e){"object"===n(t)?$.extend(this.instanceState,t):this.instanceState[t]=e,this.storeInstanceState()},storeInstanceState:function(){this.settings.storageKey&&Craft.setLocalStorage(this.settings.storageKey,this.instanceState)},getSourceState:function(t,e,i){return null==t?null:(t=t.replace(/\/.*/,""),void 0===this.sourceStates[t]&&(this.sourceStates[t]={}),void 0===e?this.sourceStates[t]:void 0!==this.sourceStates[t][e]?this.sourceStates[t][e]:void 0!==i?i:null)},getSelectedSourceState:function(t,e){return this.getSourceState(this.instanceState.selectedSource,t,e)},setSelecetedSourceState:function(t,e){var i=this.getSelectedSourceState();if(null==i&&(i=[]),"object"===n(t))for(var s in t)t.hasOwnProperty(s)&&(null!==t[s]?i[s]=t[s]:delete i[s]);else null!==e?i[t]=e:delete i[t];var a="*";for(var r in null!=this.instanceState.selectedSource&&(a=this.instanceState.selectedSource.replace(/\/.*/,"")),this.sourceStates[a]=i,this.sourceStates)this.sourceStates.hasOwnProperty(r)&&r.includes("/")&&delete this.sourceStates[r];Craft.setLocalStorage(this.sourceStatesStorageKey,this.sourceStates)},storeSortAttributeAndDirection:function(){},setPage:function(t){if("index"===this.settings.context){t=Math.max(t,1),this.page=t;var e=Craft.getPageUrl(this.page);history.replaceState({},"",e)}},_resetCount:function(){this.resultSet=null,this.totalResults=null},updateSourceMenu:function(){var t=this;if(this.$sourceActionsContainer.length){this.$sourceActionsBtn&&(this.$sourceActionsBtn.data("trigger").destroy(),this.$sourceActionsContainer.empty(),$("#source-actions-menu").remove(),this.$sourceActionsBtn=null);var e=this.getSourceActions();if(e.length){var i=[e.filter((function(t){return!t.destructive&&!t.administrative})),e.filter((function(t){return t.destructive&&!t.administrative})),e.filter((function(t){return t.administrative}))].filter((function(t){return t.length}));this.$sourceActionsBtn=$("<button/>",{type:"button",class:"btn settings icon menubtn",title:Craft.t("app","Source settings"),"aria-label":Craft.t("app","Source settings"),"aria-controls":"source-actions-menu"}).appendTo(this.$sourceActionsContainer);var s=$("<div/>",{id:"source-actions-menu",class:"menu menu--disclosure"}).appendTo(this.$sourceActionsContainer);i.forEach((function(e,i){0!==i&&$("<hr/>").appendTo(s),t._buildActionList(e).appendTo(s)})),this.$sourceActionsBtn.disclosureMenu()}}},_buildActionList:function(t){var e=this,i=$("<ul/>");return t.forEach((function(t){var s=$("<button/>",{type:"button",class:"menu-option",text:t.label}).on("click",(function(){e.$sourceActionsBtn.data("trigger").hide(),t.onSelect&&t.onSelect()}));t.destructive&&s.addClass("error"),$("<li/>").append(s).appendTo(i)})),i},getSourceActions:function(){var t=this,e=[];return Craft.userIsAdmin&&Craft.allowAdminChanges&&e.push({label:Craft.t("app","Customize sources"),administrative:!0,onSelect:function(){t.createCustomizeSourcesModal()}}),e},updateViewMenu:function(){this.activeViewMenu&&this.activeViewMenu===this.viewMenus[this.rootSourceKey]||(this.activeViewMenu&&this.activeViewMenu.hideTrigger(),this.viewMenus[this.rootSourceKey]||(this.viewMenus[this.rootSourceKey]=new l(this,this.$rootSource)),this.activeViewMenu=this.viewMenus[this.rootSourceKey],this.activeViewMenu.showTrigger())},getViewSettings:function(){return{}},getViewParams:function(){var t={siteId:this.siteId,search:this.searchText,offset:this.settings.batchSize*(this.page-1),limit:this.settings.batchSize};if(this.settings.canHaveDrafts&&(this.drafts||"index"===this.settings.context&&!this.status)&&(t.drafts=this.drafts||null,t.savedDraftsOnly=!0,this.drafts||(t.draftOf=!1)),this.trashed&&(t.trashed=!0),Garnish.hasAttr(this.$source,"data-override-status")||(t.status=this.status),$.extend(t,this.settings.criteria),this.sourcePath.length){var e=this.sourcePath[this.sourcePath.length-1];void 0!==e.criteria&&$.extend(t,e.criteria)}var i={context:this.settings.context,elementType:this.elementType,source:this.instanceState.selectedSource,condition:this.settings.condition,referenceElementId:this.settings.referenceElementId,referenceElementSiteId:this.settings.referenceElementSiteId,criteria:t,disabledElementIds:this.settings.disabledElementIds,viewState:$.extend({},this.getSelectedSourceState()),paginated:this._isViewPaginated()?1:0};if(i.viewState.mode=this.viewMode,"structure"===this.viewMode)i.viewState.mode="table",i.viewState.order="structure",i.viewState.sort="asc",void 0===this.instanceState.collapsedElementIds&&(this.instanceState.collapsedElementIds=[]),i.collapsedElementIds=this.instanceState.collapsedElementIds;else{var n=s(this.getSortAttributeAndDirection(),2),a=n[0],r=n[1];i.viewState.order=a,i.viewState.sort=r}return this.filterHuds[this.siteId]&&this.filterHuds[this.siteId][this.sourceKey]&&this.filterHuds[this.siteId][this.sourceKey].serialized&&(i.filters=this.filterHuds[this.siteId][this.sourceKey].serialized),this.trigger("registerViewParams",{params:i}),i},updateElements:function(t,e){var i=this;return new Promise((function(s,n){if(i.initialized){i._cancelRequests(),i.setIndexBusy(),i.view&&(i.view.destroy(),delete i.view),!0!==t&&(i.setPage(1),i._resetCount());var a=i.getViewParams();Craft.sendActionRequest("POST",i.settings.updateElementsAction,{data:a,cancelToken:i._createCancelToken()}).then((function(t){if(i.setIndexAvailable(),"index"===i.settings.context){if(Craft.cp.fixedHeader){var n=Craft.cp.$headerContainer.height(),r=i.$main.offset().top-n;r<Garnish.$scrollContainer.scrollTop()&&Garnish.$scrollContainer.scrollTop(r)}}else i.$main.scrollTop(0);if(i._updateView(a,t.data),e){var o=i.view.getElementContainer();Garnish.firstFocusableElement(o).trigger("focus")}s()})).catch((function(t){axios.isCancel(t)||(i.setIndexAvailable(),Craft.cp.displayError(Craft.t("app","A server error occurred."))),n(t)}))}else n("The element index isn’t initialized yet.")}))},updateElementsIfSearchTextChanged:function(){this.searchText!==(this.searchText=this.searching?this.$search.val():null)&&("index"===this.settings.context&&Craft.setQueryParam("search",this.$search.val()),this.updateElements())},showActionTriggers:function(){this.showingActionTriggers||(this._$triggers?this._$triggers.appendTo(this.$actionsContainer):this._createTriggers(),this.showingActionTriggers=!0)},submitAction:function(t,e){var i=this,s=this.view.getSelectedElementIds();if(0!==s.length&&("string"==typeof t&&(t=this._findAction(t)),!t.confirm||confirm(t.confirm))){this._cancelRequests();var n=this.getViewParams();e=e?Craft.expandPostArray(e):{};var a=$.extend(n,t.settings||{},e,{elementAction:t.type,elementIds:s});this.setIndexBusy(),this._autoSelectElements=s,t.download?(Craft.csrfTokenName&&(a[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl(this.settings.submitActionsAction),a).then((function(t){i.setIndexAvailable()})).catch((function(t){i.setIndexAvailable()}))):Craft.sendActionRequest("POST",this.settings.submitActionsAction,{data:a,cancelToken:this._createCancelToken()}).then((function(e){i._resetCount(),i._updateView(n,e.data),void 0!==e.data.badgeCounts&&i._updateBadgeCounts(e.data.badgeCounts),e.data.message&&Craft.cp.displaySuccess(e.data.message),i.afterAction(t,a)})).catch((function(t){var e=t.response;Craft.cp.displayError(e.data.message)})).finally((function(){i.setIndexAvailable()}))}},_findAction:function(t){for(var e=0;e<this.actions.length;e++)if(this.actions[e].type===t)return this.actions[e];throw"Invalid element action: ".concat(t)},afterAction:function(t,e){Craft.cp.runQueue(),this.onAfterAction(t,e)},hideActionTriggers:function(){this.showingActionTriggers&&(this._$triggers.detach(),this.showingActionTriggers=!1)},updateActionTriggers:function(){if(this.actions){var t=this.view.getSelectedElements().length;0!==t?(t===this.view.getEnabledElements().length?(this.$selectAllCheckbox.removeClass("indeterminate"),this.$selectAllCheckbox.addClass("checked"),this.$selectAllCheckbox.attr("aria-checked","true")):(this.$selectAllCheckbox.addClass("indeterminate"),this.$selectAllCheckbox.removeClass("checked"),this.$selectAllCheckbox.attr("aria-checked","mixed")),this.showActionTriggers()):(this.$selectAllCheckbox.removeClass("indeterminate checked"),this.$selectAllCheckbox.attr("aria-checked","false"),this.hideActionTriggers())}},getSelectedElements:function(){return this.view?this.view.getSelectedElements():$()},getSelectedElementIds:function(){return this.view?this.view.getSelectedElementIds():[]},setStatus:function(t){var e=this.statusMenu.$options.filter('a[data-status="'+t+'"]:first');e.length&&this.statusMenu.selectOption(e[0])},getSelectedSortAttribute:function(t){if(t=t?this.getRootSource(t):this.$rootSource){var e=this.getSourceState(t.data("key"),"order");if(this.getSortOption(e,t))return e}return this.getDefaultSort()[0]},getSelectedSortDirection:function(t){if(t=t||this.$source){var e=this.getSourceState(t.data("key"),"sort");if(["asc","desc"].includes(e))return e}return this.getDefaultSort()[1]},setSortAttribute:function(t){this.setSelectedSortAttribute(t)},setSelectedSortAttribute:function(t,e){if("score"===t)return this.sortByScore=!0,void(this.activeViewMenu&&this.activeViewMenu.updateSortField());this.sortByScore=!1;var i=this.getSortOption(t);if(i){e||(e=i.defaultDir);var n=[],a=[t],r=this.getSelectedSourceState("order");r&&r!==t&&(n.push([r,this.getSelectedSourceState("sort")]),a.push(r));for(var o=this.getSelectedSourceState("orderHistory",[]),l=0;l<o.length;l++){var h=s(o[l],1)[0];if(!h||a.includes(h))break;n.push(o[l]),a.push(h)}this.setSelecetedSourceState({order:t,sort:e,orderHistory:n}),this.activeViewMenu&&this.activeViewMenu.updateSortField(),"index"===this.settings.context&&Craft.setQueryParam("sort","".concat(t,"-").concat(e))}else console.warn("Invalid sort option: ".concat(t))},setSortDirection:function(t){this.setSelectedSortDirection(t)},setSelectedSortDirection:function(t){this.setSelectedSortAttribute(this.getSelectedSortAttribute(),t)},canSortByStructure:function(){return!this.trashed&&!this.drafts&&!this.searching},getSortAttributeAndDirection:function(){return this.searching&&this.sortByScore?["score","desc"]:[this.getSelectedSortAttribute(),this.getSelectedSortDirection()]},getSortLabel:function(t){var e=this.getSortOption(t);return e?e.label:null},getSelectedViewMode:function(){return this.getSelectedSourceState("mode")||"table"},getSourceLevel:function(t){return t.parentsUntil("nav","ul.nested").length+1},getParentSource:function(t){var e=t.parent().parent().siblings("a");return e.length?e:null},getRootSource:function(t){for(var e;e=this.getParentSource(t);)t=e;return t},getSourceByKey:function(t){return this.sourcesByKey[t]||null},selectSource:function(t){var e=$(t);if(!this.sourcesByKey||!Object.keys(this.sourcesByKey).length)return!1;if(this.$source&&this.$source[0]&&this.$source[0]===e[0]&&e.data("key")===this.sourceKey)return!1;if(this.hideActionTriggers(),this.$source=e,this.$rootSource=this.getRootSource(e),this.sourceKey=e.data("key"),this.rootSourceKey=this.$rootSource.data("key"),this.setInstanceState("selectedSource",this.sourceKey),this.sourceSelect.selectItem(e),Craft.cp.updateContentHeading(),this.searching&&(this.searchText=null,this.$search.val(""),"index"===this.settings.context&&Craft.setQueryParam("search",null),this.stopSearching()),this.$statusMenuBtn.length&&(Garnish.hasAttr(this.$source,"data-override-status")?this.$statusMenuContainer.addClass("hidden"):this.$statusMenuContainer.removeClass("hidden"),this.trashed)){var i=this.statusMenu.$options.first();this.setStatus(i.data("status"))}if(this.$viewModeBtnContainer&&this.$viewModeBtnContainer.remove(),this.viewModeBtns={},this.viewMode=null,this.sourceViewModes=this.getViewModesForSource(),this.sourceViewModes.length>1){this.$viewModeBtnContainer=$('<section class="btngroup btngroup--exclusive"/>').attr("aria-label",Craft.t("app","View")).insertAfter(this.$searchContainer);for(var s=0;s<this.sourceViewModes.length;s++){var n=this.sourceViewModes[s],a=$("<button/>",{type:"button",class:"btn"+(void 0!==n.className?" ".concat(n.className):""),"data-view":n.mode,"data-icon":n.icon,"aria-label":n.title,"aria-pressed":"false",title:n.title}).appendTo(this.$viewModeBtnContainer);this.viewModeBtns[n.mode]=a,this.addListener(a,"click",{mode:n.mode},(function(t){this.selectViewMode(t.data.mode),this.updateElements()}))}}var r=this.getSelectedSourceState("mode");if("table"===r&&"structure"===this.getSourceState(e.data("key"),"order")&&(r="structure"),r&&this.doesSourceHaveViewMode(r)||(r=this.viewMode&&this.doesSourceHaveViewMode(this.viewMode)?this.viewMode:this.sourceViewModes[0].mode),this.selectViewMode(r),this.updateSourceMenu(),this.updateViewMenu(),this.updateFilterBtn(),this.sourcePath=this.$source.data("default-source-path"),this.onSelectSource(),"index"===this.settings.context){var o=Craft.getQueryParams();o.source=this.sourceKey,Craft.setUrl(Craft.getUrl(Craft.path,o))}return!0},selectSourceByKey:function(t){var e=this.getSourceByKey(t);return!!e&&this.selectSource(e)},getSortOptions:function(t){var e=((t=t?this.getRootSource(t):this.$rootSource)?t.data("sort-opts"):null)||[];return e.length||e.push({label:Craft.t("app","Title"),attr:"title",defaultDir:"asc"}),e},getSortOption:function(t,e){return this.getSortOptions(e).find((function(e){return e.attr===t}))||null},getDefaultSort:function(t){if(t=t?this.getRootSource(t):this.$rootSource){var e=t.data("default-sort");if(e){"string"==typeof e&&(e=[e]);var i=this.getSortOption(e[0],t);if(i)return e[1]||(e[1]=i.defaultDir),e}}var s=this.getSortOptions(t);return[s[0].attr,s[0].defaultDir]},getTableColumnOptions:function(t){return((t=t?this.getRootSource(t):this.$rootSource)?t.data("table-col-opts"):null)||[]},getTableColumnOption:function(t,e){return this.getTableColumnOptions(e).find((function(e){return e.attr===t}))||null},getDefaultTableColumns:function(t){return((t=t?this.getRootSource(t):this.$rootSource)?t.data("default-table-cols"):null)||[]},getSelectedTableColumns:function(t){var e=this;if(t=t?this.getRootSource(t):this.$rootSource){var i=this.getSourceState(t.data("key"),"tableColumns");if(i)return i.filter((function(i){return!!e.getTableColumnOption(i,t)}))}return this.getDefaultTableColumns(t)},setSelectedTableColumns:function(t){this.setSelecetedSourceState({tableColumns:t}),this.activeViewMenu&&this.activeViewMenu.updateTableColumnField()},getViewModesForSource:function(){var t=[];return Garnish.hasAttr(this.$source,"data-has-structure")&&t.push({mode:"structure",title:Craft.t("app","Display in a structured table"),icon:"rtl"===Craft.orientation?"structurertl":"structure"}),t.push({mode:"table",title:Craft.t("app","Display in a table"),icon:"list"}),this.$source&&Garnish.hasAttr(this.$source,"data-has-thumbs")&&t.push({mode:"thumbs",title:Craft.t("app","Display as thumbnails"),icon:"grid"}),t},doesSourceHaveViewMode:function(t){for(var e=0;e<this.sourceViewModes.length;e++)if(this.sourceViewModes[e].mode===t)return!0;return!1},selectViewMode:function(t,e){e||this.doesSourceHaveViewMode(t)||(t=this.sourceViewModes[0].mode),t!==this._viewMode&&(this._viewMode&&void 0!==this.viewModeBtns[this._viewMode]&&this.viewModeBtns[this._viewMode].removeClass("active").attr("aria-pressed","false"),this._viewMode=t,this.setSelecetedSourceState("mode",this._viewMode),void 0!==this.viewModeBtns[this._viewMode]&&this.viewModeBtns[this._viewMode].addClass("active").attr("aria-pressed","true"),this.activeViewMenu&&this.activeViewMenu.updateSortField())},createView:function(t,e){return new(this.getViewClass(t))(this,this.$elements,e)},getViewClass:function(t){switch(t){case"table":case"structure":return Craft.TableElementIndexView;case"thumbs":return Craft.ThumbsElementIndexView;default:throw'View mode "'.concat(t,'" not supported.')}},rememberDisabledElementId:function(t){-1===$.inArray(t,this.settings.disabledElementIds)&&this.settings.disabledElementIds.push(t)},forgetDisabledElementId:function(t){var e=$.inArray(t,this.settings.disabledElementIds);-1!==e&&this.settings.disabledElementIds.splice(e,1)},enableElements:function(t){t.removeClass("disabled").parents(".disabled").removeClass("disabled");for(var e=0;e<t.length;e++){var i=$(t[e]).data("id");this.forgetDisabledElementId(i)}this.onEnableElements(t)},disableElements:function(t){t.removeClass("sel").addClass("disabled");for(var e=0;e<t.length;e++){var i=$(t[e]).data("id");this.rememberDisabledElementId(i)}this.onDisableElements(t)},getElementById:function(t){return this.view.getElementById(t)},enableElementsById:function(t){t=$.makeArray(t);for(var e=0;e<t.length;e++){var i=t[e],s=this.getElementById(i);s&&s.length?this.enableElements(s):this.forgetDisabledElementId(i)}},disableElementsById:function(t){t=$.makeArray(t);for(var e=0;e<t.length;e++){var i=t[e],s=this.getElementById(i);s&&s.length?this.disableElements(s):this.rememberDisabledElementId(i)}},selectElementAfterUpdate:function(t){null===this._autoSelectElements&&(this._autoSelectElements=[]),this._autoSelectElements.push(t)},addButton:function(t){this.getButtonContainer().append(t)},isShowingSidebar:function(){return null===this.showingSidebar&&(this.showingSidebar=this.$sidebar.length&&!this.$sidebar.hasClass("hidden")),this.showingSidebar},getButtonContainer:function(){if(this.settings.buttonContainer)return $(this.settings.buttonContainer);var t=$("#action-buttons");return t.length||(t=$('<div id="action-buttons"/>').appendTo($("#header"))),t},setIndexBusy:function(){this.$elements.addClass("busy"),this.$updateSpinner.appendTo(this.$elements),this.isIndexBusy=!0,document.activeElement&&this.$elements[0].contains(document.activeElement)&&(this._activeElement=document.activeElement,document.activeElement.blur());var t=this.$elements.height(),e=window.innerHeight,i=$(document).scrollTop();if("modal"==this.settings.context&&(e=this.$elements.parents(".modal").height(),i=this.$elements.scrollParent().scrollTop()),t>e){var s=Math.floor(i+e/2)-100;s=Math.floor(s/t*100),document.documentElement.style.setProperty("--elements-busy-top-position",s+"%")}},setIndexAvailable:function(){this.$elements.removeClass("busy"),this.$updateSpinner.remove(),this.isIndexBusy=!1,this._activeElement&&(document.activeElement&&document.activeElement!==document.body||(document.body.contains(this._activeElement)?this._activeElement.focus():this._activeElement.id&&$("#".concat(this._activeElement.id)).focus()),this._activeElement=null)},createCustomizeSourcesModal:function(){var t=new Craft.CustomizeSourcesModal(this,{hideOnEsc:!1,hideOnShadeClick:!1,onHide:function(){t.destroy()}});return t},disable:function(){this.sourceSelect&&this.sourceSelect.disable(),this.view&&this.view.disable(),this.base()},enable:function(){this.sourceSelect&&this.sourceSelect.enable(),this.view&&this.view.enable(),this.base()},onAfterInit:function(){this.settings.onAfterInit(),this.trigger("afterInit")},onSelectSource:function(){this.settings.onSelectSource(this.sourceKey),this.trigger("selectSource",{sourceKey:this.sourceKey})},onSelectSite:function(){this.settings.onSelectSite(this.siteId),this.trigger("selectSite",{siteId:this.siteId})},onUpdateElements:function(){this.settings.onUpdateElements(),this.trigger("updateElements")},onSelectionChange:function(){this.settings.onSelectionChange(),this.trigger("selectionChange")},onEnableElements:function(t){this.settings.onEnableElements(t),this.trigger("enableElements",{elements:t})},onDisableElements:function(t){this.settings.onDisableElements(t),this.trigger("disableElements",{elements:t})},onAfterAction:function(t,e){this.settings.onAfterAction(t,e),this.trigger("afterAction",{action:t,params:e})},_handleSourceSelectionChange:function(){this.sourceSelect.totalSelected?this.selectSource(this.sourceSelect.$selectedItems)&&this.updateElements():this.sourceSelect.selectItem(this.$visibleSources.first())},_handleActionTriggerSubmit:function(t){t.preventDefault();var e=$(t.currentTarget);e.hasClass("disabled")||e.data("custom-handler")||this.submitAction(e.data("action"),Garnish.getPostData(e))},_handleMenuActionTriggerSubmit:function(t){var e=$(t.option);e.hasClass("disabled")||e.data("custom-handler")||this.submitAction(e.data("action"))},_handleStatusChange:function(t){this.statusMenu.$options.removeClass("sel");var e=$(t.selectedOption).addClass("sel");this.$statusMenuBtn.html(e.html()),this.trashed=!1,this.drafts=!1,this.status=null;var i=null;Garnish.hasAttr(e,"data-trashed")?(this.trashed=!0,i="trashed"):Garnish.hasAttr(e,"data-drafts")?(this.drafts=!0,i="drafts"):this.status=i=e.data("status")||null,this.activeViewMenu&&this.activeViewMenu.updateSortField(),"index"===this.settings.context&&Craft.setQueryParam("status",i),this.updateElements()},_handleSiteChange:function(t){this.siteMenu.$options.removeClass("sel");var e=$(t.selectedOption).addClass("sel");this.$siteMenuBtn.html(e.html()),this._setSite(e.data("site-id")),this.initialized&&this.updateElements(),this.onSelectSite()},_setSite:function(t){var e=null===this.siteId;this.siteId=t,this.updateSourceVisibility(),!this.initialized||e||this.$source&&this.$source.length||!this.$visibleSources.length||this.selectSource(this.$visibleSources[0]);for(var i,s=this.getSourceContainer().children(".heading"),n=0;n<s.length;n++)0!==(i=s.eq(n)).has("> ul > li:not(.hidden)").length?i.removeClass("hidden"):i.addClass("hidden");this.initialized&&("index"===this.settings.context&&Craft.cp.setSiteId(t),this.updateFilterBtn())},updateSourceVisibility:function(){this.$visibleSources=$();for(var t=0;t<this.$sources.length;t++){var e=this.$sources.eq(t);Garnish.hasAttr(e,"data-disabled")||void 0!==e.data("sites")&&-1===e.data("sites").toString().split(",").indexOf(this.siteId.toString())?(e.parent().addClass("hidden"),this.$source&&this.$source.get(0)===e.get(0)&&(this.$source=null,this.$rootSource=null,this.sourceKey=null,this.rootSourceKey=null)):(e.parent().removeClass("hidden"),this.$visibleSources=this.$visibleSources.add(e))}},_handleSelectionChange:function(){this.updateActionTriggers(),this.onSelectionChange()},_handleSourceDblClick:function(t){this._toggleSource($(t.currentTarget)),t.stopPropagation()},_handleSourceToggleClick:function(t){this._toggleSource($(t.currentTarget).prev("a")),t.stopPropagation()},_getSourcesInList:function(t,e){var i=t.find("> li:not(.heading) > a");return e&&(i=i.add(t.find("> li.heading > ul > li > a"))),i},_getChildSources:function(t){var e=t.siblings("ul");return this._getSourcesInList(e)},_getSourceToggle:function(t){return t.siblings(".toggle")},_toggleSource:function(t){t.parent("li").hasClass("expanded")?this._collapseSource(t):this._expandSource(t)},_expandSource:function(t){t.next(".toggle").attr({"aria-expanded":"true","aria-label":Craft.t("app","Hide nested sources")}),t.parent("li").addClass("expanded");for(var e=this._getChildSources(t),i=0;i<e.length;i++)this.initSource($(e[i])),this.$visibleSources&&(this.$visibleSources=this.$visibleSources.add(e[i]));var s=t.data("key");-1===this.instanceState.expandedSources.indexOf(s)&&(this.instanceState.expandedSources.push(s),this.storeInstanceState())},_collapseSource:function(t){t.next(".toggle").attr({"aria-expanded":"false","aria-label":Craft.t("app","Show nested sources")}),t.parent("li").removeClass("expanded");for(var e=this._getChildSources(t),i=0;i<e.length;i++)this.deinitSource($(e[i])),this.$visibleSources=this.$visibleSources.not(e[i]);var s=this.instanceState.expandedSources.indexOf(t.data("key"));-1!==s&&(this.instanceState.expandedSources.splice(s,1),this.storeInstanceState())},_isViewPaginated:function(){return"index"===this.settings.context&&"structure"!==this.viewMode},_updateView:function(t,e){var i=this;this.actions&&(this.hideActionTriggers(),this.actions=this.actionsHeadHtml=this.actionsBodyHtml=this._$triggers=null),this.$countContainer.length&&(this.$countSpinner.removeClass("hidden"),this.$countContainer.html(""),this._countResults().then((function(t){i.$countSpinner.addClass("hidden");var e=Craft.elementTypeNames[i.elementType]?Craft.elementTypeNames[i.elementType][2]:i.settings.elementTypeName.toLowerCase(),s=Craft.elementTypeNames[i.elementType]?Craft.elementTypeNames[i.elementType][3]:i.settings.elementTypePluralName.toLowerCase();if(i._isViewPaginated()){var n=Math.min(i.settings.batchSize*(i.page-1)+1,t),a=Math.min(n+(i.settings.batchSize-1),t),r=Craft.t("app","{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}",{first:n,last:a,total:t,item:e,items:s}),o=$('<div class="flex pagination"/>').appendTo(i.$countContainer),l=Math.max(Math.ceil(t/i.settings.batchSize),1),h=$("<nav/>",{class:"flex","aria-label":Craft.t("app","{element} pagination",{element:e})}).appendTo(o),d=$("<button/>",{role:"button",class:"page-link prev-page"+(i.page>1?"":" disabled"),disabled:1===i.page,title:Craft.t("app","Previous Page")}).appendTo(h),c=$("<button/>",{role:"button",class:"page-link next-page"+(i.page<l?"":" disabled"),disabled:i.page===l,title:Craft.t("app","Next Page")}).appendTo(h);$("<div/>",{class:"page-info",text:r}).appendTo(o),i.page>1&&i.addListener(d,"click",(function(){this.removeListener(d,"click"),this.removeListener(c,"click"),this.setPage(this.page-1),this.updateElements(!0,!0)})),i.page<l&&i.addListener(c,"click",(function(){this.removeListener(d,"click"),this.removeListener(c,"click"),this.setPage(this.page+1),this.updateElements(!0,!0)}))}else{var u=Craft.t("app","{total, number} {total, plural, =1{{item}} other{{items}}}",{total:t,item:e,items:s});i.$countContainer.text(u)}})).catch((function(){i.$countSpinner.addClass("hidden")}))),this.$elements.html(e.html),Craft.appendHeadHtml(e.headHtml),Craft.appendBodyHtml(e.bodyHtml),this.$selectAllContainer=this.$elements.find(".selectallcontainer:first"),e.actions&&e.actions.length?this.$selectAllContainer.length&&(this.actions=e.actions,this.actionsHeadHtml=e.actionsHeadHtml,this.actionsBodyHtml=e.actionsBodyHtml,this.$selectAllCheckbox=$('<div class="checkbox"/>').prependTo(this.$selectAllContainer).attr({role:"checkbox",tabindex:"0","aria-checked":"false","aria-label":Craft.t("app","Select all")}),this.addListener(this.$selectAllCheckbox,"click",(function(){0===this.view.getSelectedElements().length?this.view.selectAllElements():this.view.deselectAllElements()})),this.addListener(this.$selectAllCheckbox,"keydown",(function(t){t.keyCode===Garnish.SPACE_KEY&&(t.preventDefault(),$(t.currentTarget).trigger("click"))}))):(this.$selectAllContainer.siblings().length||this.$selectAllContainer.parent(".header").remove(),this.$selectAllContainer.remove()),this.exporters=e.exporters,this.exportersByType=Craft.index(this.exporters||[],(function(t){return t.type})),this.exporters&&this.exporters.length?this.$exportBtn.removeClass("hidden"):this.$exportBtn.addClass("hidden");var s=this.actions||this.settings.selectable,n=Object.assign({context:this.settings.context,batchSize:"index"!==this.settings.context||"structure"===this.viewMode?this.settings.batchSize:null,params:t,selectable:s,multiSelect:this.actions||this.settings.multiSelect,canSelectElement:this.settings.canSelectElement,checkboxMode:!!this.actions,onSelectionChange:this._handleSelectionChange.bind(this)},this.getViewSettings());if(this.view=this.createView(this.getSelectedViewMode(),n),this._autoSelectElements){if(s)for(var a=0;a<this._autoSelectElements.length;a++)this.view.selectElementById(this._autoSelectElements[a]);this._autoSelectElements=null}this.onUpdateElements()},_updateBadgeCounts:function(t){for(var e in t)if(t.hasOwnProperty(e)){var i=this.getSourceByKey(e);if(i){var s=i.children(".badge");null!==t[e]?(s.length||(s=$('<span class="badge"/>').appendTo(i)),s.text(t[e])):s&&s.remove()}}},_countResults:function(){var t=this;return new Promise((function(e,i){if(null!==t.totalResults)e(t.totalResults);else{var s=t.getViewParams();delete s.criteria.offset,delete s.criteria.limit,null===t.resultSet&&(t.resultSet=Math.floor(1e8*Math.random())),s.resultSet=t.resultSet,Craft.sendActionRequest("POST",t.settings.countElementsAction,{data:s,cancelToken:t._createCancelToken()}).then((function(s){s.data.resultSet==t.resultSet?(t.totalResults=s.data.count,e(s.data.count)):i()})).catch(i)}}))},_createTriggers:function(){var t,e,i=[],s=[],n=[];for(t=0;t<this.actions.length;t++){var a=this.actions[t];if(a.trigger){var r=$('<form id="'+Craft.formatInputId(a.type)+'-actiontrigger"/>').data("action",a).append(a.trigger);r.find(".btn").addClass("secondary"),this.addListener(r,"submit","_handleActionTriggerSubmit"),i.push(r)}else a.destructive?n.push(a):s.push(a)}if(s.length||n.length){var o=$("<form/>");e=$("<button/>",{type:"button",class:"btn secondary menubtn","data-icon":"settings",title:Craft.t("app","Actions")}).appendTo(o);var l=$('<ul class="menu"/>').appendTo(o),h=this._createMenuTriggerList(s,!1),d=this._createMenuTriggerList(n,!0);h&&h.appendTo(l),h&&d&&$("<hr/>").appendTo(l),d&&d.appendTo(l),i.push(o)}for(this._$triggers=$(),t=0;t<i.length;t++){var c=$("<div/>").append(i[t]);this._$triggers=this._$triggers.add(c)}this._$triggers.appendTo(this.$actionsContainer),Craft.appendHeadHtml(this.actionsHeadHtml),Craft.appendBodyHtml(this.actionsBodyHtml),Craft.initUiElements(this._$triggers),e&&e.data("menubtn").on("optionSelect",this._handleMenuActionTriggerSubmit.bind(this))},_showExportHud:function(){var t=this;this.$exportBtn.addClass("active"),this.$exportBtn.attr("aria-expanded","true");for(var e=$("<form/>",{class:"export-form"}),i=[],s=0;s<this.exporters.length;s++)i.push({label:this.exporters[s].name,value:this.exporters[s].type});var n=Craft.ui.createSelectField({label:Craft.t("app","Export Type"),options:i,class:"fullwidth"}).appendTo(e),a=Craft.ui.createSelectField({label:Craft.t("app","Format"),options:[{label:"CSV",value:"csv"},{label:"JSON",value:"json"},{label:"XML",value:"xml"}],class:"fullwidth"}).appendTo(e),r=n.find("select");this.addListener(r,"change",(function(){var e=r.val();t.exportersByType[e].formattable?a.removeClass("hidden"):a.addClass("hidden")})),r.trigger("change");var o=this.view.getSelectedElementIds();if(!o.length)var l=Craft.ui.createTextField({label:Craft.t("app","Limit"),placeholder:Craft.t("app","No limit"),type:"number",min:1}).appendTo(e);var h=Craft.ui.createSubmitButton({class:"fullwidth",label:Craft.t("app","Export"),spinner:!0}).appendTo(e),d=new Garnish.MultiFunctionBtn(h);new Garnish.HUD(this.$exportBtn,e).on("hide",(function(){t.$exportBtn.removeClass("active"),t.$exportBtn.attr("aria-expanded","false")}));var c=!1;this.addListener(e,"submit",(function(t){if(t.preventDefault(),!c){c=!0,d.busyEvent();var e=this.getViewParams();if(delete e.criteria.offset,delete e.criteria.limit,delete e.collapsedElementIds,e.type=n.find("select").val(),e.format=a.find("select").val(),o.length)e.criteria.id=o;else{var i=parseInt(l.find("input").val());i&&!isNaN(i)&&(e.criteria.limit=i)}Craft.csrfTokenValue&&(e[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl("element-indexes/export"),e).catch((function(t){axios.isCancel(t)||Craft.cp.displayError(Craft.t("app","A server error occurred."))})).finally((function(){c=!1,d.successEvent()}))}}))},_createMenuTriggerList:function(t,e){if(t&&t.length){for(var i=$("<ul/>"),s=0;s<t.length;s++)$("<li/>").append($("<a/>",{id:Craft.formatInputId(t[s].type)+"-actiontrigger",class:e?"error":null,data:{action:t[s]},text:t[s].name})).appendTo(i);return i}},showFilterHud:function(){this.filterHuds[this.siteId]||(this.filterHuds[this.siteId]={}),this.filterHuds[this.siteId][this.sourceKey]?this.filterHuds[this.siteId][this.sourceKey].show():(this.filterHuds[this.siteId][this.sourceKey]=new h(this,this.sourceKey,this.siteId),this.updateFilterBtn())},updateFilterBtn:function(){this.$filterBtn.removeClass("active"),this.filterHuds[this.siteId]&&this.filterHuds[this.siteId][this.sourceKey]?(this.$filterBtn.attr("aria-controls",this.filterHuds[this.siteId][this.sourceKey].id).attr("aria-expanded",this.filterHuds[this.siteId][this.sourceKey].showing?"true":"false"),(this.filterHuds[this.siteId][this.sourceKey].showing||this.filterHuds[this.siteId][this.sourceKey].hasRules())&&this.$filterBtn.addClass("active")):this.$filterBtn.attr("aria-controls",null)}},{defaults:{context:"index",modal:null,storageKey:null,condition:null,referenceElementId:null,referenceElementSiteId:null,criteria:null,batchSize:100,disabledElementIds:[],selectable:!1,multiSelect:!1,canSelectElement:null,buttonContainer:null,hideSidebar:!1,toolbarSelector:".toolbar:first",refreshSourcesAction:"element-indexes/get-source-tree-html",updateElementsAction:"element-indexes/get-elements",countElementsAction:"element-indexes/count-elements",submitActionsAction:"element-indexes/perform-action",defaultSiteId:null,defaultSource:null,defaultSourcePath:null,showSourcePath:!0,canHaveDrafts:!1,elementTypeName:Craft.t("app","Element"),elementTypePluralName:Craft.t("app","Elements"),onAfterInit:$.noop,onSelectSource:$.noop,onSelectSite:$.noop,onUpdateElements:$.noop,onSelectionChange:$.noop,onSourcePathChange:$.noop,onEnableElements:$.noop,onDisableElements:$.noop,onAfterAction:$.noop}});var l=Garnish.Base.extend({elementIndex:null,$source:null,sourceKey:null,menu:null,id:null,$trigger:null,$container:null,$sortField:null,$sortAttributeSelect:null,$sortDirectionPicker:null,sortDirectionListbox:null,$tableColumnsField:null,$tableColumnsContainer:null,$revertContainer:null,$revertBtn:null,$closeBtn:null,init:function(t,e){var i=this;this.elementIndex=t,this.$source=e,this.sourceKey=e.data("key"),this.id="view-menu-".concat(Math.floor(1e9*Math.random())),this.$trigger=$("<button/>",{type:"button",class:"btn menubtn hidden",text:Craft.t("app","View"),"aria-label":Craft.t("app","View settings"),"aria-controls":this.id,"data-icon":"sliders"}).appendTo(this.elementIndex.$toolbar),this.$container=$("<div/>",{id:this.id,class:"menu menu--disclosure element-index-view-menu","data-align":"right"}).appendTo(Garnish.$bod),this._buildMenu(),this.addListener(this.$container,"mousedown",(function(t){t.stopPropagation()})),this.menu=new Garnish.DisclosureMenu(this.$trigger),this.menu.on("show",(function(){i.$trigger.addClass("active")})),this.menu.on("hide",(function(){i.$trigger.removeClass("active"),setTimeout((function(){i.tidyTableColumnField()}),Garnish.FX_DURATION)}))},showTrigger:function(){this.$trigger.removeClass("hidden")},hideTrigger:function(){this.$trigger.data("trigger").hide(),this.$trigger.addClass("hidden"),this.menu.hide()},updateSortField:function(){this.$sortField&&("structure"===this.elementIndex.viewMode?(this.$sortField.addClass("hidden"),this.$tableColumnsField.addClass("first-child")):(this.$sortField.removeClass("hidden"),this.$tableColumnsField.removeClass("first-child")));var t=s(this.elementIndex.getSortAttributeAndDirection(),2),e=t[0],i=t[1],n=this.$sortAttributeSelect.children('option[value="score"]');this.elementIndex.searching?n.length||this.$sortAttributeSelect.prepend($("<option/>",{value:"score",text:Craft.t("app","Score")})):n.length&&n.remove(),this.$sortAttributeSelect.val(e),this.sortDirectionListbox.select("asc"===i?0:1),"score"===e?(this.sortDirectionListbox.disable(),this.$sortDirectionPicker.addClass("disabled")):(this.sortDirectionListbox.enable(),this.$sortDirectionPicker.removeClass("disabled"))},updateTableColumnField:function(){var t,e,i=this,s=this.elementIndex.getSelectedTableColumns();s.forEach((function(s){var n=i.$tableColumnsContainer.find('input[value="'.concat(s,'"]'));n.prop("checked")||n.prop("checked",!0);var a=n.parent();t&&a.index()<e&&a.insertAfter(t),t=a,e=a.index()}));for(var n=this._getTableColumnCheckboxes(),a=0;a<n.length;a++){var r=n.eq(a);r.prop("checked")&&!s.includes(r.val())&&r.prop("checked",!1)}},tidyTableColumnField:function(){var t=this.elementIndex.getTableColumnOptions(this.$source).map((function(t){return t.attr})).reduce((function(t,s,n){return e(e({},t),{},i({},s,n))}),{});this.$tableColumnsContainer.children().sort((function(e,i){var s=$(e).children('input[type="checkbox"]')[0],n=$(i).children('input[type="checkbox"]')[0];return s.checked&&n.checked?0:s.checked||n.checked?s.checked?-1:1:t[s.value]<t[n.value]?-1:1})).appendTo(this.$tableColumnsContainer)},revert:function(){this.elementIndex.setSelecetedSourceState({order:null,sort:null,tableColumns:null}),this.updateSortField(),this.updateTableColumnField(),this.tidyTableColumnField(),this.$revertBtn.remove(),this.$revertBtn=null,this.$closeBtn.focus(),this.elementIndex.updateElements()},_buildMenu:function(){var t=this,e=$('<div class="meta"/>').appendTo(this.$container);this.$sortField=this._createSortField().appendTo(e),this.$tableColumnsField=this._createTableColumnsField().appendTo(e),this.updateSortField(),this.$sortAttributeSelect.focus();var i=$("<div/>",{class:"flex menu-footer"}).appendTo(this.$container);this.$revertContainer=$("<div/>",{class:"flex-grow"}).appendTo(i),(this.elementIndex.getSelectedSourceState("order")||this.elementIndex.getSelectedSourceState("sort")||this.elementIndex.getSelectedSourceState("tableColumns"))&&this._createRevertBtn(),this.$closeBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close")}).appendTo(i).on("click",(function(){t.menu.hide()}))},_createSortField:function(){var t=this,e=$('<div class="flex"/>'),i=Craft.ui.createSelect({options:this.elementIndex.getSortOptions(this.$source).map((function(t){return{label:t.label,value:t.attr}}))}).addClass("fullwidth").appendTo($('<div class="flex-grow"/>').appendTo(e));this.$sortAttributeSelect=i.children("select").attr({"aria-label":Craft.t("app","Sort attribute")}),this.$sortDirectionPicker=$("<section/>",{class:"btngroup btngroup--exclusive","aria-label":Craft.t("app","Sort direction")}).append($("<button/>",{type:"button",class:"btn",title:Craft.t("app","Sort ascending"),"aria-label":Craft.t("app","Sort ascending"),"aria-pressed":"false","data-icon":"asc","data-dir":"asc"})).append($("<button/>",{type:"button",class:"btn",title:Craft.t("app","Sort descending"),"aria-label":Craft.t("app","Sort descending"),"aria-pressed":"false","data-icon":"desc","data-dir":"desc"})).appendTo(e),this.sortDirectionListbox=new Craft.Listbox(this.$sortDirectionPicker,{onChange:function(e){e.data("dir")!==t.elementIndex.getSelectedSortDirection()&&(t.elementIndex.setSelectedSortAttribute(t.$sortAttributeSelect.val(),e.data("dir")),t.elementIndex.sortByScore||t.elementIndex.selectViewMode(t.elementIndex.viewMode),t.elementIndex.updateElements(),t._createRevertBtn())}}),this.$sortAttributeSelect.on("change",(function(){t.elementIndex.setSelectedSortAttribute(t.$sortAttributeSelect.val(),null,!1),t.elementIndex.selectViewMode(t.elementIndex.viewMode),t.elementIndex.updateElements(),t._createRevertBtn()}));var s=Craft.ui.createField(e,{label:Craft.t("app","Sort by"),fieldset:!0});return s.addClass("sort-field"),s},_getTableColumnCheckboxes:function(){return this.$tableColumnsContainer.find('input[type="checkbox"]')},_createTableColumnsField:function(){var t=this,e=this.elementIndex.getTableColumnOptions(this.$source);if(!e.length)return $();this.$tableColumnsContainer=$("<div/>"),e.forEach((function(e){$('<div class="element-index-view-menu-table-column"/>').append('<div class="icon move"/>').append(Craft.ui.createCheckbox({label:Craft.escapeHtml(e.label),value:e.attr})).appendTo(t.$tableColumnsContainer)})),this.updateTableColumnField(),this.tidyTableColumnField(),new Garnish.DragSort(this.$tableColumnsContainer.children(),{handle:".move",axis:"y",onSortChange:function(){t._onTableColumnChange()}}),this._getTableColumnCheckboxes().on("change",(function(e){t._onTableColumnChange()}));var i=Craft.ui.createField(this.$tableColumnsContainer,{label:Craft.t("app","Table Columns"),fieldset:!0});return i.addClass("table-columns-field"),i},_onTableColumnChange:function(){for(var t=[],e=this._getTableColumnCheckboxes().filter(":checked"),i=0;i<e.length;i++)t.push(e.eq(i).val());Craft.compare(t,this.elementIndex.getSelectedTableColumns(this.$source))||(this.elementIndex.setSelectedTableColumns(t,!1),this.elementIndex.updateElements(),this._createRevertBtn())},_createRevertBtn:function(){var t=this;this.$revertBtn||(this.$revertBtn=$("<button/>",{type:"button",class:"light",text:Craft.t("app","Use defaults")}).appendTo(this.$revertContainer).on("click",(function(){t.revert()})))},destroy:function(){this.menu.destroy(),delete this.menu,this.base()}}),h=Garnish.HUD.extend({elementIndex:null,sourceKey:null,siteId:null,id:null,loading:!0,serialized:null,$clearBtn:null,cleared:!1,init:function(t,e,i){var s=this;this.elementIndex=t,this.sourceKey=e,this.siteId=i,this.id="filter-".concat(Math.floor(1e9*Math.random()));var n=$("<div/>").append($("<div/>",{class:"spinner"})).append($("<div/>",{text:Craft.t("app","Loading"),class:"visually-hidden","aria-role":"alert"}));this.base(this.elementIndex.$filterBtn,n,{hudClass:"hud element-filter-hud loading"}),this.$hud.attr({id:this.id,"aria-live":"polite","aria-busy":"false"}),this.$tip.remove(),this.$tip=null,this.$body.on("submit",(function(t){t.preventDefault(),s.hide()})),Craft.sendActionRequest("POST","element-indexes/filter-hud",{data:{elementType:this.elementIndex.elementType,source:this.sourceKey,condition:this.elementIndex.settings.condition,id:"".concat(this.id,"-filters")}}).then((function(t){s.loading=!1,s.$hud.removeClass("loading"),n.remove(),s.$main.append(t.data.hudHtml),Craft.appendHeadHtml(t.data.headHtml),Craft.appendBodyHtml(t.data.bodyHtml);var e=$("<div/>",{class:"flex flex-nowrap"}).appendTo(s.$main);$("<div/>",{class:"flex-grow"}).appendTo(e),s.$clearBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(e),$("<button/>",{type:"submit",class:"btn secondary",text:Craft.t("app","Apply")}).appendTo(e),s.$clearBtn.on("click",(function(){s.clear()})),s.$hud.find(".condition-container").on("htmx:beforeRequest",(function(){s.setBusy()})),s.$hud.find(".condition-container").on("htmx:load",(function(){s.setReady(),s.updateSizeAndPosition(!0)})),s.setFocus()})).catch((function(){Craft.cp.displayError(Craft.t("app","A server error occurred."))})),this.$hud.css("position","fixed"),this.addListener(Garnish.$win,"scroll,resize",(function(){s.updateSizeAndPosition(!0)}))},addListener:function(t,e,i,s){t===this.$main&&"resize"===e||this.base(t,e,i,s)},setBusy:function(){this.$hud.attr("aria-busy","true"),$("<div/>",{class:"visually-hidden",text:Craft.t("app","Loading")}).insertAfter(this.$main.find(".htmx-indicator"))},setReady:function(){this.$hud.attr("aria-busy","false")},setFocus:function(){Garnish.setFocusWithin(this.$main)},clear:function(){this.cleared=!0,this.hide()},updateSizeAndPositionInternal:function(){var t,e=this.elementIndex.$searchContainer[0].getBoundingClientRect(),i=Garnish.$win.height(),s=i-e.bottom;this.$body.height()>s&&(t=i-e.bottom-10),this.$hud.css({width:this.elementIndex.$searchContainer.outerWidth()-2,top:e.top+this.elementIndex.$searchContainer.outerHeight(),left:e.left+1,height:t?"".concat(t,"px"):"unset",overflowY:t?"scroll":"unset"})},onShow:function(){this.base(),this.$clearBtn&&this.$clearBtn.text(Craft.t("app","Clear")),this.elementIndex.updateFilterBtn(),this.setFocus()},onHide:function(){this.base(),this.serialized!==(this.serialized=this.serialize())&&this.elementIndex.updateElements(),this.cleared?this.destroy():(this.$hud.detach(),this.$shade.detach()),this.elementIndex.updateFilterBtn(),this.elementIndex.$filterBtn.focus()},hasRules:function(){return 0!==this.$main.has(".condition-rule").length},serialize:function(){return!this.cleared&&this.hasRules()?this.$body.serialize():null},destroy:function(){this.base(),delete this.elementIndex.filterHuds[this.siteId][this.sourceKey]}})},8495:function(){Craft.BaseElementIndexView=Garnish.Base.extend({$container:null,$loadingMoreSpinner:null,$elementContainer:null,$scroller:null,elementIndex:null,elementSelect:null,loadingMore:!1,_totalVisible:null,_morePending:null,_handleEnableElements:null,_handleDisableElements:null,get thumbLoader(){return console.warn("Craft.BaseElementIndexView::thumbLoader is deprecated. Craft.cp.elementThumbLoader should be used instead."),Craft.cp.elementThumbLoader},init:function(t,e,i){var s=this;this.elementIndex=t,this.$container=$(e),this.setSettings(i,Craft.BaseElementIndexView.defaults),this.$loadingMoreSpinner=$('<div class="centeralign hidden"><div class="spinner loadingmore"></div></div>').insertAfter(this.$container),this.$elementContainer=this.getElementContainer();var n=this.$elementContainer.children();this.setTotalVisible(n.length),this.setMorePending(this.settings.batchSize&&n.length==this.settings.batchSize),Craft.cp.elementThumbLoader.load(n),this.settings.selectable&&(this.elementSelect=new Garnish.Select(this.$elementContainer,$(n.toArray().filter((function(t){return s.canSelectElement($(t))}))),{multi:this.settings.multiSelect,vertical:this.isVerticalList(),handle:"index"===this.settings.context?".checkbox, .element:first":null,filter:":not(a):not(.toggle)",checkboxMode:this.settings.checkboxMode,onSelectionChange:this.onSelectionChange.bind(this)}),this._handleEnableElements=function(t){s.elementSelect.addItems(t.elements)},this._handleDisableElements=function(t){s.elementSelect.removeItems(t.elements)},this.elementIndex.on("enableElements",this._handleEnableElements),this.elementIndex.on("disableElements",this._handleDisableElements)),"index"===this.settings.context&&(this._handleElementEditing=function(t){var e=$(t.target);if("A"!==e.prop("nodeName")){var i;if(e.hasClass("element"))i=e;else if(!(i=e.closest(".element")).length)return;Garnish.hasAttr(i,"data-editable")&&Craft.createElementEditor(i.data("type"),i)}},this.elementIndex.trashed||this.addListener(this.$elementContainer,"dblclick,taphold",this._handleElementEditing)),this.afterInit(),this.settings.batchSize&&("index"===this.settings.context?this.$scroller=Garnish.$scrollContainer:this.$scroller=this.elementIndex.$main,this.$scroller.scrollTop(0),this.addListener(this.$scroller,"scroll","maybeLoadMore"),this.maybeLoadMore())},canSelectElement:function(t){return!t.hasClass("disabled")&&(this.settings.canSelectElement?this.settings.canSelectElement(t):!!t.data("id"))},getElementContainer:function(){throw"Classes that extend Craft.BaseElementIndexView must supply a getElementContainer() method."},afterInit:function(){},getAllElements:function(){return this.$elementContainer.children()},getEnabledElements:function(){return this.$elementContainer.children(":not(.disabled)")},getElementById:function(t){var e=this.$elementContainer.children('[data-id="'+t+'"]:first');return e.length?e:null},getSelectedElements:function(){if(!this.elementSelect)throw"This view is not selectable.";return this.elementSelect.$selectedItems},getSelectedElementIds:function(){var t;try{t=this.getSelectedElements()}catch(t){}var e=[];if(t)for(var i=0;i<t.length;i++)e.push(t.eq(i).data("id"));return e},selectElement:function(t){if(!this.elementSelect)throw"This view is not selectable.";return this.elementSelect.selectItem(t,!0),!0},selectElementById:function(t){if(!this.elementSelect)throw"This view is not selectable.";var e=this.getElementById(t);return!!e&&(this.elementSelect.selectItem(e,!0),!0)},selectAllElements:function(){this.elementSelect.selectAll()},deselectAllElements:function(){this.elementSelect.deselectAll()},getElementCheckbox:function(t){return $(t).find('[role="checkbox"]')},isVerticalList:function(){return!1},getTotalVisible:function(){return this._totalVisible},setTotalVisible:function(t){this._totalVisible=t},getMorePending:function(){return this._morePending},setMorePending:function(t){this._morePending=t},maybeLoadMore:function(){this.canLoadMore()&&this.loadMore()},canLoadMore:function(){return!(!this.getMorePending()||!this.settings.batchSize)&&(this.$scroller[0]===Garnish.$win[0]?Garnish.$win.innerHeight()+Garnish.$win.scrollTop()>=this.$container.offset().top+this.$container.height():this.$scroller.prop("scrollHeight")-this.$scroller.scrollTop()<=this.$scroller.outerHeight()+15)},loadMore:function(){var t=this;this.getMorePending()&&!this.loadingMore&&this.settings.batchSize&&(this.loadingMore=!0,this.$loadingMoreSpinner.removeClass("hidden"),this.removeListener(this.$scroller,"scroll"),Craft.sendActionRequest("POST",this.settings.loadMoreElementsAction,{data:this.getLoadMoreParams()}).then((function(e){t.loadingMore=!1,t.$loadingMoreSpinner.addClass("hidden");var i=$(e.data.html);t.appendElements(i),Craft.appendHeadHtml(e.data.headHtml),Craft.appendBodyHtml(e.data.bodyHtml),t.elementSelect&&(t.elementSelect.addItems(i.filter(":not(.disabled)")),t.elementIndex.updateActionTriggers()),t.setTotalVisible(t.getTotalVisible()+i.length),t.setMorePending(i.length==t.settings.batchSize),t.addListener(t.$scroller,"scroll","maybeLoadMore"),t.maybeLoadMore()})).catch((function(e){t.loadingMore=!1,t.$loadingMoreSpinner.addClass("hidden")})))},getLoadMoreParams:function(){var t=$.extend(!0,{},this.settings.params);return t.criteria.offset=this.getTotalVisible(),t},appendElements:function(t){t.appendTo(this.$elementContainer),Craft.cp.elementThumbLoader.load(t),this.onAppendElements(t)},onAppendElements:function(t){this.settings.onAppendElements(t),this.trigger("appendElements",{newElements:t})},onSelectionChange:function(){var t=this;this.settings.onSelectionChange(),this.trigger("selectionChange"),this.settings.checkboxMode&&this.elementSelect.$items.each((function(e,i){t.elementSelect.isSelected(i)?t.getElementCheckbox(i).attr("aria-checked","true"):t.getElementCheckbox(i).attr("aria-checked","false")}))},disable:function(){this.elementSelect&&this.elementSelect.disable()},enable:function(){this.elementSelect&&this.elementSelect.enable()},destroy:function(){this.$loadingMoreSpinner.remove(),this.elementSelect&&(this.elementIndex.off("enableElements",this._handleEnableElements),this.elementIndex.off("disableElements",this._handleDisableElements),this.elementSelect.destroy(),delete this.elementSelect),this.base()}},{defaults:{context:"index",batchSize:null,params:null,selectable:!1,multiSelect:!1,canSelectElement:null,checkboxMode:!1,loadMoreElementsAction:"element-indexes/get-more-elements",onAppendElements:$.noop,onSelectionChange:$.noop}})},5970:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.BaseElementSelectInput=Garnish.Base.extend({elementSelect:null,elementSort:null,modal:null,elementEditor:null,$container:null,$form:null,$elementsContainer:null,$elements:null,$addElementBtn:null,$spinner:null,_initialized:!1,get thumbLoader(){return console.warn("Craft.BaseElementSelectInput::thumbLoader is deprecated. Craft.cp.elementThumbLoader should be used instead."),Craft.cp.elementThumbLoader},init:function(t){var e=this;if(!$.isPlainObject(t)){for(var i={},s=["id","name","elementType","sources","criteria","sourceElementId","limit","modalStorageKey","fieldId"],n=0;n<s.length&&void 0!==arguments[n];n++)i[s[n]]=arguments[n];t=i}this.setSettings(t,Craft.BaseElementSelectInput.defaults),this.settings.modalStorageKey&&(this.modalStorageKey="BaseElementSelectInput."+this.settings.modalStorageKey),(1==this.settings.limit||this.settings.maintainHierarchy)&&(this.settings.sortable=!1),this.$container=this.getContainer(),this.$form=this.$container.closest("form"),this.$container.data("elementSelect",this),this.$elementsContainer=this.getElementsContainer(),this.$addElementBtn=this.getAddElementsBtn(),this.$spinner=this.getSpinner(),this.initElementSelect(),this.initElementSort(),this.resetElements(),this.$addElementBtn&&this.addListener(this.$addElementBtn,"activate","showModal"),Garnish.requestAnimationFrame((function(){e._initialized=!0}))},get totalSelected(){return this.$elements.length},getContainer:function(){return $("#"+this.settings.id)},getElementsContainer:function(){return this.$container.children(".elements")},getElements:function(){return this.$elementsContainer.find(".element")},getAddElementsBtn:function(){return this.$container.find(".btn.add:first")},getSpinner:function(){return this.$container.find(".spinner")},initElementSelect:function(){this.settings.selectable&&(this.elementSelect=new Garnish.Select({multi:this.settings.sortable,filter:":not(.delete)"}))},initElementSort:function(){var t=this;this.settings.sortable&&(this.elementSort=new Garnish.DragSort({container:this.$elementsContainer,filter:this.settings.selectable?function(){return t.elementSort.$targetItem.hasClass("sel")?t.elementSelect.getSelectedItems():t.elementSort.$targetItem}:null,ignoreHandleSelector:".delete",axis:this.getElementSortAxis(),collapseDraggees:!0,magnetStrength:4,helperLagBase:1.5,onSortChange:this.settings.selectable?function(){t.elementSelect.resetItemOrder()}:null}))},getElementSortAxis:function(){return"list"===this.settings.viewMode?"y":null},canAddMoreElements:function(){return!this.settings.limit||this.$elements.length<this.settings.limit},updateAddElementsBtn:function(){this.canAddMoreElements()?this.enableAddElementsBtn():this.disableAddElementsBtn()},enableAddElementsBtn:function(){this.$addElementBtn&&this.$addElementBtn.removeClass("hidden"),this.updateButtonContainer()},disableAddElementsBtn:function(){this.$addElementBtn&&this.$addElementBtn.addClass("hidden"),this.updateButtonContainer()},showSpinner:function(){this.$spinner&&this.$spinner.removeClass("hidden"),this.updateButtonContainer()},hideSpinner:function(){this.$spinner&&this.$spinner.addClass("hidden"),this.updateButtonContainer()},updateButtonContainer:function(){var t=this.$addElementBtn&&this.$addElementBtn.parent(".flex");t&&t.length&&(t.children(":not(.hidden)").length?t.removeClass("hidden"):t.addClass("hidden"))},focusNextLogicalElement:function(){if(this.canAddMoreElements()){var t=this.$addElementBtn;t&&t.get(0).focus()}else this.focusLastRemoveBtn()},focusLastRemoveBtn:function(){var t=this.$container.find(".delete");t.length&&t.last()[0].focus()},resetElements:function(){null!==this.$elements?this.removeElements(this.$elements):this.$elements=$(),this.addElements(this.getElements())},addElements:function(t){var e=this;Craft.cp.elementThumbLoader.load(t),this.settings.selectable&&this.elementSelect.addItems(t),this.settings.sortable&&this.elementSort.addItems(t),this.settings.editable&&(this._handleShowElementEditor=function(t){var i=$(t.currentTarget);!Garnish.hasAttr(i,"data-editable")||i.hasClass("disabled")||i.hasClass("loading")||(e.elementEditor=e.createElementEditor(i))},this.addListener(t,"dblclick",this._handleShowElementEditor),$.isTouchCapable()&&this.addListener(t,"taphold",this._handleShowElementEditor)),t.find(".delete").on("click dblclick",(function(t){e.removeElement($(t.currentTarget).closest(".element")),t.stopPropagation()})),t.on("keydown",(function(t){if([Garnish.BACKSPACE_KEY,Garnish.DELETE_KEY].includes(t.keyCode)){t.stopPropagation(),t.preventDefault();for(var i=e.elementSelect.getSelectedItems(),s=0;s<i.length;s++)e.removeElement(i.eq(s))}})),this.$elements=this.$elements.add(t),this.updateAddElementsBtn(),this.onAddElements()},createElementEditor:function(t,e){return e=Object.assign({elementSelectInput:this,prevalidate:this.settings.prevalidate},e),Craft.createElementEditor(this.settings.elementType,t,e)},replaceElement:function(t,e){var i=this;return new Promise((function(s,n){var a=i.$elements.filter('[data-id="'.concat(t,'"]'));if(a.length){i.showSpinner();var r={elementId:e,siteId:i.settings.criteria.siteId,thumbSize:i.settings.viewMode};Craft.sendActionRequest("POST","elements/get-element-html",{data:r}).then((function(t){i.removeElement(a);var e=Craft.getElementInfo(t.data.html);i.selectElements([e]),s()})).catch((function(t){var e=t.response;e&&e.data&&e.data.message?Craft.cp.displayError(e.data.message):Craft.cp.displayError(),n(e.data.message)})).finally((function(){i.hideSpinner()}))}else n("No element selected with an ID of ".concat(t,"."))}))},removeElements:function(t){if(this.settings.selectable&&this.elementSelect.removeItems(t),this.modal){for(var e=[],i=0;i<t.length;i++){var s=t.eq(i).data("id");s&&e.push(s)}e.length&&this.modal.elementIndex.enableElementsById(e)}var n;if(t.children("input").prop("disabled",!0),this.settings.selectable){var a=this.$elements.index(t.last());n=this.$elements.eq(a+1).find(".delete")}n.length?n.focus():this.focusNextLogicalElement(),this.$elements=this.$elements.not(t),this.updateAddElementsBtn(),this.onRemoveElements()},removeElement:function(t){if(this.settings.maintainHierarchy){var e=t.add(t.parent().siblings("ul").find(".element"));$("[name]",e).removeAttr("name"),this.removeElements(e);for(var i=0;i<e.length;i++)this._animateStructureElementAway(e,i)}else $("[name]",t).removeAttr("name"),this.removeElements(t),this.animateElementAway(t,(function(){t.remove()}))},animateElementAway:function(t,e){t.css("z-index",0);var i={opacity:-1};i["margin-"+Craft.left]=-(t.outerWidth()+parseInt(t.css("margin-"+Craft.right))),"list"!==this.settings.viewMode&&0!==this.$elements.length||(i["margin-bottom"]=-(t.outerHeight()+parseInt(t.css("margin-bottom")))),t.velocity(i,Craft.BaseElementSelectInput.REMOVE_FX_DURATION,(function(){e&&e()}))},showModal:function(){this.canAddMoreElements()&&(this.modal?this.modal.show():this.modal=this.createModal())},createModal:function(){return Craft.createElementSelectorModal(this.settings.elementType,this.getModalSettings())},getModalSettings:function(){return $.extend({closeOtherModals:!1,storageKey:this.modalStorageKey,sources:this.settings.sources,condition:this.settings.condition,referenceElementId:this.settings.referenceElementId,referenceElementSiteId:this.settings.referenceElementSiteId,criteria:this.settings.criteria,multiSelect:1!=this.settings.limit,hideOnSelect:!this.settings.maintainHierarchy,showSiteMenu:this.settings.showSiteMenu,disabledElementIds:this.getDisabledElementIds(),onSelect:this.onModalSelect.bind(this),onHide:this.onModalHide.bind(this),triggerElement:this.$addElementBtn,modalTitle:Craft.t("app","Choose")},this.settings.modalSettings)},getSelectedElementIds:function(){for(var t=[],e=0;e<this.$elements.length;e++)t.push(this.$elements.eq(e).data("id"));return t},getDisabledElementIds:function(){var e,i=this.getSelectedElementIds();return!this.settings.allowSelfRelations&&this.settings.sourceElementId&&i.push(this.settings.sourceElementId),this.settings.disabledElementIds&&i.push.apply(i,function(e){if(Array.isArray(e))return t(e)}(e=this.settings.disabledElementIds)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(e)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),i},onModalSelect:function(t){if(this.settings.maintainHierarchy)this.selectStructuredElements(t);else{if(this.settings.limit){var e=this.settings.limit-this.$elements.length;t.length>e&&(t=t.slice(0,e))}this.selectElements(t),this.updateDisabledElementsInModal()}},onModalHide:function(){var t=this;this.modal&&this.settings.condition&&this.settings.referenceElementId&&(this.modal.destroy(),this.modal=null),this.canAddMoreElements()||setTimeout((function(){t.focusNextLogicalElement()}),200)},selectElements:function(t){for(var e=0;e<t.length;e++){var i=t[e],s=this.createNewElement(i);this.appendElement(s),this.addElements(s),this.animateElementIntoPlace(i.$element,s),i.$element=s}this.onSelectElements(t)},selectStructuredElements:function(t){var e=this;this.modal.disable(),this.modal.disableCancelBtn(),this.modal.disableSelectBtn(),this.modal.showFooterSpinner();for(var i=this.getSelectedElementIds(),s=0;s<t.length;s++)i.push(t[s].id);var n={elementIds:i,siteId:t[0].siteId,containerId:this.settings.id,name:this.settings.name,branchLimit:this.settings.branchLimit,selectionLabel:this.settings.selectionLabel,elementType:this.settings.elementType},a=function(){e.modal.enable(),e.modal.enableCancelBtn(),e.modal.enableSelectBtn(),e.modal.hideFooterSpinner()};Craft.sendActionRequest("POST","relational-fields/structured-input-html",{data:n}).then((function(i){a();var s=$(i.data.html).children(".elements");e.$elementsContainer.replaceWith(s),e.$elementsContainer=s,e.resetElements();for(var n=[],r=0;r<t.length;r++){var o=t[r],l=e.getElementById(o.id);l&&(e.animateElementIntoPlace(o.$element,l),n.push(o))}e.updateDisabledElementsInModal(),e.modal.hide(),e.onSelectElements(n)})).catch((function(t){t.response,a()}))},createNewElement:function(t){var e=t.$element.clone(),i=Craft.t("app","Remove {label}",{label:Craft.escapeHtml(t.label)});return Craft.setElementSize(e,"large"===this.settings.viewMode?"large":"small"),e.addClass("removable").prepend($("<input/>",{type:"hidden",name:this.settings.name+(this.settings.single?"":"[]"),value:t.id})).prepend($("<button/>",{type:"button",class:"delete icon",title:Craft.t("app","Remove"),"aria-label":i})),e},appendElement:function(t){t.appendTo(this.$elementsContainer)},animateElementIntoPlace:function(t,e){var i=t.offset(),s=e.offset(),n=e.clone().appendTo(Garnish.$bod);e.css("visibility","hidden"),n.css({position:"absolute",zIndex:1e4,top:i.top,left:i.left});var a={top:s.top,left:s.left};n.velocity(a,Craft.BaseElementSelectInput.ADD_FX_DURATION,(function(){n.remove(),e.css("visibility","visible")}))},updateDisabledElementsInModal:function(){this.modal.elementIndex&&this.modal.elementIndex.disableElementsById(this.getDisabledElementIds())},getElementById:function(t){for(var e=0;e<this.$elements.length;e++){var i=this.$elements.eq(e);if(i.data("id")==t)return i}},onSelectElements:function(t){this.trigger("selectElements",{elements:t}),this.settings.onSelectElements(t),this.$container.trigger("change")},onAddElements:function(){this.trigger("addElements"),this.settings.onAddElements(),this.$container.trigger("change")},onRemoveElements:function(){this.trigger("removeElements"),this.settings.onRemoveElements(),this.$container.trigger("change")},_animateStructureElementAway:function(t,e){var i,s=this;e===t.length-1&&(i=function(){var e=t.first().parent().parent(),i=e.parent();i[0]===s.$elementsContainer[0]||e.siblings().length?e.remove():i.remove()});var n=function(){s.animateElementAway(t.eq(e),i)};0===e?n():setTimeout(n,100*e)}},{ADD_FX_DURATION:200,REMOVE_FX_DURATION:200,defaults:{id:null,name:null,fieldId:null,elementType:null,sources:null,condition:null,referenceElementId:null,referenceElementSiteId:null,criteria:{},allowSelfRelations:!1,sourceElementId:null,disabledElementIds:null,viewMode:"list",single:!1,maintainHierarchy:!1,branchLimit:null,limit:null,showSiteMenu:!1,modalStorageKey:null,modalSettings:{},onAddElements:$.noop,onSelectElements:$.noop,onRemoveElements:$.noop,sortable:!0,selectable:!0,editable:!0,prevalidate:!1,editorSettings:{}}})},4993:function(){Craft.BaseElementSelectorModal=Garnish.Modal.extend({elementType:null,elementIndex:null,supportSidebarToggleView:!1,$body:null,$content:null,$footer:null,$selectBtn:null,$sidebar:null,$sources:null,$sourceToggles:null,$sidebarToggleBtn:null,$sidebarCloseBtn:null,$mainHeading:null,$main:null,$search:null,$elements:null,$tbody:null,$primaryButtons:null,$secondaryButtons:null,$cancelBtn:null,init:function(t,e){this.elementType=t,this.setSettings(e,Craft.BaseElementSelectorModal.defaults);var i="elementSelectorModalHeading-"+Date.now(),s=$("<div/>",{class:"modal elementselectormodal","aria-labelledby":i}).appendTo(Garnish.$bod),n=$("<div/>",{class:this.settings.showTitle?"header":"visually-hidden"}).appendTo(s);$("<h1/>",{id:i,text:this.settings.modalTitle}).appendTo(n);var a=$("<div/>",{class:"body"}).append($("<div/>",{class:"spinner big"})).appendTo(s);this.$footer=$("<div/>",{class:"footer"}).appendTo(s),this.settings.fullscreen&&(s.addClass("fullscreen"),this.settings.minGutter=0),this.base(s,this.settings),this.$secondaryButtons=$('<div class="buttons left secondary-buttons"/>').appendTo(this.$footer),this.$primaryButtons=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$primaryButtons),this.$selectBtn=Craft.ui.createSubmitButton({class:"disabled",label:this.settings.selectBtnLabel,spinner:!0}).attr("aria-disabled","true").appendTo(this.$primaryButtons),this.$body=a,this.addListener(this.$cancelBtn,"activate","cancel"),this.addListener(this.$selectBtn,"activate","selectElements")},updateModalBottomPadding:function(){var t=this.$footer.outerHeight();t!==parseInt(this.$container.css("padding-bottom"))&&this.$container.css("padding-bottom",t)},updateSidebarView:function(){this.supportSidebarToggleView&&(this.sidebarShouldBeHidden()?this.$sidebarToggleBtn||this.buildSidebarToggleView():this.$sidebarToggleBtn&&this.resetView())},sidebarShouldBeHidden:function(){return this.$container.outerWidth()<550},resetView:function(){this.$mainHeader&&this.$mainHeader.remove(),this.$sidebarHeader&&this.$sidebarHeader.remove(),this.$sidebarToggleBtn=null,this.$body.addClass("has-sidebar"),this.$content.addClass("has-sidebar"),this.$sidebar.removeClass("hidden")},buildSidebarToggleView:function(){var t=this;!this.$sidebarToggleBtn&&this.sidebarShouldBeHidden()&&(this.$sidebarHeader=$('<div class="sidebar-header"/>').prependTo(this.$sidebar),this.$sidebarCloseBtn=Craft.ui.createButton({class:"nav-close close-btn"}).attr("aria-label",Craft.t("app","Close")).removeClass("btn").appendTo(this.$sidebarHeader),this.$mainHeader=$('<div class="main-header"/>').prependTo(this.$main),this.$mainHeading=$('<h2 class="main-heading">'.concat(this.getActiveSourceName(),"</h2>")).appendTo(this.$mainHeader),this.$sidebarToggleBtn=Craft.ui.createButton({toggle:!0,controls:"modal-sidebar",class:"nav-toggle"}).removeClass("btn").attr("aria-label",Craft.t("app","Show sidebar")).appendTo(this.$mainHeader),this.$sidebar.attr("id","modal-sidebar"),this.closeSidebar(),this.addListener(this.$sidebarToggleBtn,"click",(function(){t.toggleSidebar()})),this.addListener(this.$sidebarCloseBtn,"click",(function(){t.toggleSidebar()})))},sidebarIsOpen:function(){return"true"===this.$sidebarToggleBtn.attr("aria-expanded")},toggleSidebar:function(){this.sidebarIsOpen()?this.closeSidebar():this.openSidebar()},openSidebar:function(){var t=this;this.$body.addClass("has-sidebar"),this.$content.addClass("has-sidebar"),this.$sidebar.removeClass("hidden"),this.$sidebarToggleBtn.attr("aria-expanded","true"),this.$sidebar.find(":focusable").first().focus(),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.closeSidebar();var e=Garnish.getFocusedElement();$.contains(t.$sidebar.get(0),e.get(0))&&t.$sidebarToggleBtn.focus()}))},closeSidebar:function(){this.$sidebarToggleBtn&&(this.sidebarIsOpen()&&(Garnish.uiLayerManager.removeLayer(),this.$sidebar.addClass("hidden"),this.$sidebarToggleBtn.attr("aria-expanded","false")),this.$body.removeClass("has-sidebar"),this.$content.removeClass("has-sidebar"))},getActiveSourceName:function(){return this.$sidebar.find(".sel").text()},onFadeIn:function(){this.elementIndex?(this.updateModalBottomPadding(),Garnish.isMobileBrowser(!0)||this.elementIndex.$search.trigger("focus")):this._createElementIndex(),this.base()},onSelectionChange:function(){this.updateSelectBtnState()},onSelectSource:function(){this.updateHeading(),this.updateModalBottomPadding()},updateHeading:function(){this.$mainHeading&&this.$mainHeading.text(this.getActiveSourceName())},updateSelectBtnState:function(){this.$selectBtn&&(this.hasSelection()?this.enableSelectBtn():this.disableSelectBtn())},hasSelection:function(){return this.elementIndex&&this.elementIndex.getSelectedElements().length},enableSelectBtn:function(){this.$selectBtn.removeClass("disabled").attr("aria-disabled","false")},disableSelectBtn:function(){this.$selectBtn.addClass("disabled").attr("aria-disabled","true")},enableCancelBtn:function(){this.$cancelBtn.removeClass("disabled")},disableCancelBtn:function(){this.$cancelBtn.addClass("disabled")},showFooterSpinner:function(){this.$selectBtn.addClass("loading")},hideFooterSpinner:function(){this.$selectBtn.removeClass("loading")},cancel:function(){this.$cancelBtn.hasClass("disabled")||this.hide()},selectElements:function(){if(this.hasSelection()){this.elementIndex.view&&this.elementIndex.view.elementSelect&&this.elementIndex.view.elementSelect.clearMouseUpTimeout();var t=this.elementIndex.getSelectedElements(),e=this.getElementInfo(t);this.onSelect(e),this.settings.disableElementsOnSelect&&this.elementIndex.disableElements(this.elementIndex.getSelectedElements()),this.settings.hideOnSelect&&this.hide()}},getElementInfo:function(t){for(var e=[],i=0;i<t.length;i++){var s=$(t[i]),n=Craft.getElementInfo(s);e.push(n)}return e},onShow:function(){this.updateSelectBtnState(),this.addListener(Garnish.$win,"resize",this.updateSidebarView),this.addListener(Garnish.$win,"resize",this.updateModalBottomPadding),this.updateModalBottomPadding(),this.updateSidebarView(),this.base()},onHide:function(){this.closeSidebar(),this.base()},onSelect:function(t){this.settings.onSelect(t)},disable:function(){this.elementIndex&&this.elementIndex.disable(),this.base()},enable:function(){this.elementIndex&&this.elementIndex.enable(),this.base()},getElementIndexParams:function(){var t={context:"modal",elementType:this.elementType,sources:this.settings.sources};return null!==this.settings.showSiteMenu&&"auto"!==this.settings.showSiteMenu&&(t.showSiteMenu=this.settings.showSiteMenu?"1":"0"),t},_createElementIndex:function(){var t=this;Craft.sendActionRequest("POST",this.settings.bodyAction,{data:this.getElementIndexParams()}).then((function(e){t.$body.html(e.data.html),t.$body.has(".sidebar:not(.hidden)").length&&(t.$body.addClass("has-sidebar"),t.supportSidebarToggleView=!0),t.elementIndex=Craft.createElementIndex(t.elementType,t.$body,t.getIndexSettings()),t.$main=t.elementIndex.$main,t.$sidebar=t.elementIndex.$sidebar,t.$content=t.$body.find(".content"),t.updateSidebarView(),t.updateModalBottomPadding(),t.addListener(t.elementIndex.$elements,"doubletap",(function(t,e){e.firstTap.target===e.secondTap.target&&-1!=this.elementIndex.view.elementSelect.getItemIndex(e.firstTap.target)&&this.selectElements()})),t.on("updateSizeAndPosition",(function(){t.elementIndex.handleResize()})),t.updateSelectBtnState()}))},getIndexSettings:function(){var t=this;return Object.assign({context:"modal",modal:this,storageKey:this.settings.storageKey,condition:this.settings.condition,referenceElementId:this.settings.referenceElementId,referenceElementSiteId:this.settings.referenceElementSiteId,criteria:this.settings.criteria,disabledElementIds:this.settings.disabledElementIds,selectable:!0,multiSelect:this.settings.multiSelect,buttonContainer:this.$secondaryButtons,onSelectionChange:function(){t.elementIndex&&t.onSelectionChange()},onSourcePathChange:function(){t.elementIndex&&t.onSelectionChange()},onSelectSource:this.onSelectSource.bind(this),hideSidebar:this.settings.hideSidebar,defaultSiteId:this.settings.defaultSiteId,defaultSource:this.settings.defaultSource,defaultSourcePath:this.settings.defaultSourcePath,showSourcePath:this.settings.showSourcePath},this.settings.indexSettings)}},{defaults:{fullscreen:!1,resizable:!0,storageKey:null,sources:null,condition:null,referenceElementId:null,referenceElementSiteId:null,criteria:null,multiSelect:!1,showSiteMenu:null,disabledElementIds:[],disableElementsOnSelect:!1,hideOnSelect:!0,modalTitle:Craft.t("app","Select element"),showTitle:!1,selectBtnLabel:Craft.t("app","Select"),onCancel:$.noop,onSelect:$.noop,hideSidebar:!1,defaultSiteId:null,defaultSource:null,defaultSourcePath:null,showSourcePath:!0,bodyAction:"element-selector-modals/body",indexSettings:{}}})},8843:function(){Craft.BaseInputGenerator=Garnish.Base.extend({$source:null,$target:null,$form:null,settings:null,listening:null,timeout:null,init:function(t,e,i){this.$source=$(t),this.$target=$(e),this.$form=this.$source.closest("form"),this.setSettings(i),this.startListening()},setNewSource:function(t){var e=this.listening;this.stopListening(),this.$source=$(t),e&&this.startListening()},startListening:function(){this.listening||(this.listening=!0,this.addListener(this.$source,"input","onSourceTextChange"),this.addListener(this.$target,"input","onTargetTextChange"),this.addListener(this.$form,"submit","onFormSubmit"))},stopListening:function(){this.listening&&(this.listening=!1,this.timeout&&clearTimeout(this.timeout),this.removeAllListeners(this.$source),this.removeAllListeners(this.$target),this.removeAllListeners(this.$form))},onSourceTextChange:function(){this.timeout&&clearTimeout(this.timeout),this.timeout=setTimeout(this.updateTarget.bind(this),250)},onTargetTextChange:function(){this.$target.get(0)===document.activeElement&&this.stopListening()},onFormSubmit:function(){this.timeout&&clearTimeout(this.timeout),this.updateTarget()},updateTarget:function(){if(this.$target.is(":visible")){var t=this.$source.val();if(void 0!==t){var e=this.generateTargetValue(t);this.$target.val(e);for(var i=0;i<this.$target.length;i++)this.$target[i].dispatchEvent(new InputEvent("input",{inputType:"insertText"})),this.$target[i].dispatchEvent(new Event("input"));this.$target.is(":focus")&&Craft.selectFullValue(this.$target)}}},generateTargetValue:function(t){return t}})},3778:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CategoryIndex=Craft.BaseElementIndex.extend({editableGroups:null,$newCategoryBtnGroup:null,$newCategoryBtn:null,init:function(t,e,i){this.editableGroups=[],this.on("selectSource",this.updateButton.bind(this)),this.on("selectSite",this.updateButton.bind(this)),this.base(t,e,i)},afterInit:function(){var t=this;this.editableGroups=Craft.editableCategoryGroups.filter((function(e){return!!t.getSourceByKey("group:".concat(e.uid))})),this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultGroupHandle)for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("handle")===defaultGroupHandle)return e.data("key")}return this.base()},updateButton:function(){var e=this;if(this.$source){var i=this.$source.data("handle");if(this.editableGroups.length&&function(){e.$newCategoryBtnGroup&&e.$newCategoryBtnGroup.remove();var s,n=e.editableGroups.find((function(t){return t.handle===i}));e.$newCategoryBtnGroup=$('<div class="btngroup submit" data-wrapper/>');var a="new-category-menu-"+Craft.randomString(10);if(n){var r="index"===e.settings.context?Craft.t("app","New category"):Craft.t("app","New {group} category",{group:n.name}),o="index"===e.settings.context?Craft.t("app","New category in the {group} category group",{group:n.name}):r,l="index"===e.settings.context?"link":null;e.$newCategoryBtn=Craft.ui.createButton({label:r,ariaLabel:o,spinner:!0,role:l}).addClass("submit add icon").appendTo(e.$newCategoryBtnGroup),e.addListener(e.$newCategoryBtn,"click mousedown",(function(t){"index"===e.settings.context&&("click"===t.type&&Garnish.isCtrlKeyPressed(t)||"mousedown"===t.type&&1===t.originalEvent.button)?window.open(Craft.getUrl("categories/".concat(n.handle,"/new"))):"click"===t.type&&e._createCategory(n.id)})),e.editableGroups.length>1&&(s=$("<button/>",{type:"button",class:"btn submit menubtn btngroup-btn-last","aria-controls":a,"data-disclosure-trigger":"","aria-label":Craft.t("app","New category, choose a category group")}).appendTo(e.$newCategoryBtnGroup))}else e.$newCategoryBtn=s=Craft.ui.createButton({label:Craft.t("app","New category"),ariaLabel:Craft.t("app","New category, choose a category group"),spinner:!0}).addClass("submit add icon menubtn btngroup-btn-last").attr("aria-controls",a).attr("data-disclosure-trigger","").appendTo(e.$newCategoryBtnGroup);if(e.addButton(e.$newCategoryBtnGroup),s){var h,d=$("<div/>",{id:a,class:"menu menu--disclosure"}).appendTo(e.$newCategoryBtnGroup),c=$("<ul/>").appendTo(d),u=function(e,i){var s="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!s){if(Array.isArray(e)||(s=function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(e))||i&&e&&"number"==typeof e.length){s&&(e=s);var n=0,a=function(){};return{s:a,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){s=s.call(e)},n:function(){var t=s.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==s.return||s.return()}finally{if(l)throw r}}}}(e.editableGroups);try{var p=function(){var t=h.value,i="index"===e.settings.context?"link":"button";if("index"===e.settings.context||t!==n){var a=$("<li/>").appendTo(c),r=$("<a/>",{role:"button"===i?"button":null,href:"#",type:"button"===i?"button":null,text:Craft.t("app","New {group} category",{group:t.name})}).appendTo(a);e.addListener(r,"click",(function(){s.data("trigger").hide(),e._createCategory(t.id)})),"button"===i&&e.addListener(r,"keydown",(function(i){i.keyCode===Garnish.SPACE_KEY&&(i.preventDefault(),s.data("trigger").hide(),e._createCategory(t.id))}))}};for(u.s();!(h=u.n()).done;)p()}catch(t){u.e(t)}finally{u.f()}new Garnish.DisclosureMenu(s)}}(),"index"===this.settings.context){var s="categories";i&&(s+="/"+i),Craft.setPath(s)}}},_createCategory:function(t){var e=this;if(this.$newCategoryBtn.hasClass("loading"))console.warn("New category creation already in progress.");else{var i=this.editableGroups.find((function(e){return e.id===t}));if(!i)throw"Invalid category group ID: ".concat(t);this.$newCategoryBtn.addClass("loading"),Craft.sendActionRequest("POST","elements/create",{data:{elementType:this.elementType,siteId:this.siteId,groupId:t}}).then((function(t){"index"===e.settings.context?document.location.href=Craft.getUrl(t.data.cpEditUrl,{fresh:1}):Craft.createElementEditor(e.elementType,{siteId:e.siteId,elementId:t.data.element.id,draftId:t.data.element.draftId,params:{fresh:1}}).on("submit",(function(){var s="group:".concat(i.uid);e.sourceKey!==s&&e.selectSourceByKey(s),e.clearSearch(),e.selectElementAfterUpdate(t.data.element.id),e.updateElements()}))})).finally((function(){e.$newCategoryBtn.removeClass("loading")}))}}}),Craft.registerElementIndexClass("craft\\elements\\Category",Craft.CategoryIndex)},6617:function(){Craft.CategorySelectInput=Craft.BaseElementSelectInput.extend({setSettings:function(){this.base.apply(this,arguments),this.settings.sortable=!1},getModalSettings:function(){var t=this.base();return t.hideOnSelect=!1,t},getElements:function(){return this.$elementsContainer.find(".element")},onModalSelect:function(t){var e=this;this.modal.disable(),this.modal.disableCancelBtn(),this.modal.disableSelectBtn(),this.modal.showFooterSpinner();for(var i=this.getSelectedElementIds(),s=0;s<t.length;s++)i.push(t[s].id);var n={categoryIds:i,siteId:t[0].siteId,id:this.settings.id,name:this.settings.name,branchLimit:this.settings.branchLimit,selectionLabel:this.settings.selectionLabel},a=function(){e.modal.enable(),e.modal.enableCancelBtn(),e.modal.enableSelectBtn(),e.modal.hideFooterSpinner()};Craft.sendActionRequest("POST","categories/input-html",{data:n}).then((function(i){a();var s=$(i.data.html).children(".elements");e.$elementsContainer.replaceWith(s),e.$elementsContainer=s,e.resetElements();for(var n=[],r=0;r<t.length;r++){var o=t[r],l=e.getElementById(o.id);l&&(e.animateElementIntoPlace(o.$element,l),n.push(o))}e.updateDisabledElementsInModal(),e.modal.hide(),e.onSelectElements(n)})).catch((function(t){t.response,a()}))},removeElement:function(t){var e=t.add(t.parent().siblings("ul").find(".element"));this.removeElements(e);for(var i=0;i<e.length;i++)this._animateCategoryAway(e,i)},_animateCategoryAway:function(t,e){var i,s=this;e===t.length-1&&(i=function(){var e=t.first().parent().parent(),i=e.parent();i[0]===s.$elementsContainer[0]||e.siblings().length?e.remove():i.remove()});var n=function(){s.animateElementAway(t.eq(e),i)};0===e?n():setTimeout(n,100*e)}})},9482:function(){Craft.charts={},Craft.charts.DataTable=Garnish.Base.extend({columns:null,rows:null,init:function(t){var e=t.columns,i=t.rows;i.forEach((function(t){$.each(t,(function(i){var s;switch(e[i].type){case"date":s=d3.timeParse("%Y-%m-%d"),t[i]=s(t[i]);break;case"datetime":s=d3.timeParse("%Y-%m-%d %H:00:00"),t[i]=s(t[i]);break;case"percent":t[i]=t[i]/100;break;case"number":t[i]=+t[i]}}))})),this.columns=e,this.rows=i}}),Craft.charts.Tip=Garnish.Base.extend({$container:null,$tip:null,init:function(t){this.$container=t,this.$tip=$('<div class="tooltip"></div>').appendTo(this.$container),this.hide()},setContent:function(t){this.$tip.html(t)},setPosition:function(t){this.$tip.css("left","".concat(t.left,"px")),this.$tip.css("top","".concat(t.top,"px"))},show:function(){this.$tip.css("display","block")},hide:function(){this.$tip.css("display","none")}}),Craft.charts.BaseChart=Garnish.Base.extend({$container:null,$chart:null,chartBaseClass:"cp-chart",dataTable:null,formatLocale:null,timeFormatLocale:null,orientation:null,svg:null,width:null,height:null,init:function(t,e){var i=this;this.$container=t,this.setSettings(Craft.charts.BaseChart.defaults),this.setSettings(e);var s={formats:window.d3Formats,formatLocaleDefinition:window.d3FormatLocaleDefinition,timeFormatLocaleDefinition:window.d3TimeFormatLocaleDefinition};this.setSettings(s),d3.select(window).on("resize",(function(){i.resize()}))},setSettings:function(t,e){var i=void 0===this.settings?{}:this.settings;this.settings=$.extend(!0,{},i,e,t)},draw:function(t,e){this.setSettings(e),this.dataTable=t,this.formatLocale=d3.formatLocale(this.settings.formatLocaleDefinition),this.timeFormatLocale=d3.timeFormatLocale(this.settings.timeFormatLocaleDefinition),this.orientation=this.settings.orientation,this.$chart&&this.$chart.remove();var i=this.chartBaseClass;this.settings.chartClass&&(i+=" "+this.settings.chartClass),this.$chart=$('<div class="'.concat(i,'" />')).appendTo(this.$container)},resize:function(){this.draw(this.dataTable,this.settings)},onAfterDrawTicks:function(){$(".tick",this.$chart).each((function(t,e){var i=$("text",e);i.clone().appendTo(e),i.attr("stroke","#ffffff"),i.attr("stroke-width",3)}))}},{defaults:{formatLocaleDefinition:null,timeFormatLocaleDefinition:null,formats:{numberFormat:",.2f",percentFormat:",.2%",currencyFormat:"$,.2f",shortDateFormats:{day:"%-m/%-d",month:"%-m/%y",year:"%Y"}},margin:{top:0,right:0,bottom:0,left:0},chartClass:null,colors:["#0594D1","#DE3800","#FF9A00","#009802","#9B009B"]}}),Craft.charts.Area=Craft.charts.BaseChart.extend({tip:null,drawingArea:null,init:function(t,e){this.base(t,Craft.charts.Area.defaults),this.setSettings(e)},draw:function(t,e){this.base(t,e),this.tip&&(this.tip=null);var i=this.getChartMargin();this.width=this.$chart.width()-i.left-i.right,this.height=this.$chart.height()-i.top-i.bottom;var s={width:this.width+(i.left+i.right),height:this.height+(i.top+i.bottom),translateX:"rtl"!==this.orientation?i.left:i.right,translateY:i.top};this.svg=d3.select(this.$chart.get(0)).append("svg").attr("width",s.width).attr("height",s.height),this.drawingArea=this.svg.append("g").attr("transform","translate(".concat(s.translateX,",").concat(s.translateY,")")),this.drawTicks(),this.drawAxes(),this.drawChart(),this.drawTipTriggers()},drawTicks:function(){var t=this.getX(!0),e=d3.axisBottom(t).tickFormat(this.getXFormatter()).ticks(3);this.drawingArea.append("g").attr("class","x ticks-axis").attr("transform","translate(0, ".concat(this.height,")")).call(e);var i,s=this.getY();"rtl"!==this.orientation?(i=d3.axisLeft(s).tickFormat(this.getYFormatter()).tickValues(this.getYTickValues()).ticks(2),this.drawingArea.append("g").attr("class","y ticks-axis").call(i)):(i=d3.axisRight(s).tickFormat(this.getYFormatter()).tickValues(this.getYTickValues()).ticks(2),this.drawingArea.append("g").attr("class","y ticks-axis").attr("transform","translate(".concat(this.width,",0)")).call(i)),this.onAfterDrawTicks()},drawAxes:function(){if(this.settings.xAxis.showAxis){var t=this.getX(),e=d3.axisBottom(t).ticks(0).tickSizeOuter(0);this.drawingArea.append("g").attr("class","x axis").attr("transform","translate(0, ".concat(this.height,")")).call(e)}if(this.settings.yAxis.showAxis){var i,s=this.getY();"rtl"===this.orientation?(i=d3.axisLeft(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(".concat(this.width-0,", 0)")).call(i)):(i=d3.axisRight(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(".concat(0,", 0)")).call(i))}},drawChart:function(){var t=this.getX(!0),e=this.getY();if(this.settings.xAxis.gridlines){var i=d3.axisBottom(t);this.drawingArea.append("g").attr("class","x grid-line").attr("transform","translate(0,".concat(this.height,")")).call(i.tickSize(-this.height,0,0).tickFormat(""))}if(this.settings.yAxis.gridlines){var s=d3.axisLeft(e);this.drawingArea.append("g").attr("class","y grid-line").attr("transform","translate(0 , 0)").call(s.tickSize(-this.width,0).tickFormat("").tickValues(this.getYTickValues()).ticks(2))}var n=d3.line().x((function(e){return t(e[0])})).y((function(t){return e(t[1])}));this.drawingArea.append("g").attr("class","chart-line").append("path").datum(this.dataTable.rows).style("fill","none").style("stroke",this.settings.colors[0]).style("stroke-width","3px").attr("d",n);var a=d3.area().x((function(e){return t(e[0])})).y0(this.height).y1((function(t){return e(t[1])}));this.drawingArea.append("g").attr("class","chart-area").append("path").datum(this.dataTable.rows).style("fill",this.settings.colors[0]).style("fill-opacity","0.3").attr("d",a),this.settings.plots&&this.drawingArea.append("g").attr("class","plots").selectAll("circle").data(this.dataTable.rows).enter().append("circle").style("fill",this.settings.colors[0]).attr("class",(function(t,e){return"plot plot-".concat(e)})).attr("r",4).attr("cx",(function(e){return t(e[0])})).attr("cy",(function(t){return e(t[1])}))},drawTipTriggers:function(){var t=this;if(this.settings.tips){this.tip||(this.tip=new Craft.charts.Tip(this.$chart));var e=this.getChartMargin(),i=(this.drawingArea.select(".x path.domain").node().getTotalLength()-e.left-e.right-12)/(this.dataTable.rows.length-1),s=Math.max(0,i),n=this.getX(!0),a=this.getY();this.drawingArea.append("g").attr("class","tip-triggers").selectAll("rect").data(this.dataTable.rows).enter().append("rect").attr("class","tip-trigger").style("fill","transparent").style("fill-opacity","1").attr("width",s).attr("height",this.height).attr("x",(function(t){return n(t[0])-s/2})).on("mouseover",(function(e,i){t.drawingArea.select(".plot-"+i).attr("r",5);var s=$("<div />"),r=$('<div class="x-value" />').appendTo(s),o=$('<div class="y-value" />').appendTo(s);r.html(t.getXFormatter()(e[0])),o.html(t.getYFormatter()(e[1]));var l=s.get(0);t.tip.setContent(l);var h,d=t.getChartMargin(),c=24,u=a(e[1])+c;"rtl"!==t.orientation?(h=n(e[0])+d.left+c,t.$chart.offset().left+h+t.tip.$tip.width()>t.$chart.offset().left+t.$chart.width()-c&&(h=n(e[0])-(t.tip.$tip.width()+c))):h=n(e[0])-(t.tip.$tip.width()+d.left+c),h<0&&(h=n(e[0])+d.left+c);var p={top:u,left:h};t.tip.setPosition(p),t.tip.show()})).on("mouseout",(function(e,i){t.drawingArea.select(".plot-"+i).attr("r",4),t.tip.hide()}))}},getChartMargin:function(){var t=this,e=this.settings.margin,i=this.getYTickValues(),s=0;return $.each(i,(function(e,i){var n=8*t.getYFormatter()(i).length;n>s&&(s=n)})),s+=10,e.left=s,e},getX:function(t){var e=d3.min(this.dataTable.rows,(function(t){return t[0]})),i=d3.max(this.dataTable.rows,(function(t){return t[0]})),s=[e,i];"rtl"===this.orientation&&(s=[i,e]);var n=0,a=0;t&&(n=0,a=0);var r=d3.scaleTime().range([n,this.width-a]);return r.domain(s),r},getY:function(){var t=[0,this.getYMaxValue()],e=d3.scaleLinear().range([this.height,0]);return e.domain(t),e},getXFormatter:function(){return this.settings.xAxis.formatter!==$.noop?this.settings.xAxis.formatter(this):Craft.charts.utils.getTimeFormatter(this.timeFormatLocale,this.settings)},getYFormatter:function(){return this.settings.yAxis.formatter!==$.noop?this.settings.yAxis.formatter(this):Craft.charts.utils.getNumberFormatter(this.formatLocale,this.dataTable.columns[1].type,this.settings)},getYMaxValue:function(){return d3.max(this.dataTable.rows,(function(t){return t[1]}))},getYTickValues:function(){var t=this.getYMaxValue();return t>1?[t/2,t]:[0,t]}},{defaults:{chartClass:"area",margin:{top:25,right:5,bottom:25,left:0},plots:!0,tips:!0,xAxis:{gridlines:!1,showAxis:!0,formatter:$.noop},yAxis:{gridlines:!0,showAxis:!1,formatter:$.noop}}}),Craft.charts.utils={getDuration:function(t){var e=parseInt(t,10),i={hours:Math.floor(e/3600),minutes:Math.floor((e-3600*i.hours)/60),seconds:e-3600*i.hours-60*i.minutes};return i.hours<10&&(i.hours="0".concat(i.hours)),i.minutes<10&&(i.minutes="0".concat(i.minutes)),i.seconds<10&&(i.seconds="0".concat(i.seconds)),"".concat(i.hours,":").concat(i.minutes,":").concat(i.seconds)},getTimeFormatter:function(t,e){switch(e.dataScale){case"year":return t.format("%Y");case"month":return t.format(e.formats.shortDateFormats.month);case"hour":return t.format("".concat(e.formats.shortDateFormats.day," %H:00:00"));default:return t.format(e.formats.shortDateFormats.day)}},getNumberFormatter:function(t,e,i){switch(e){case"currency":return t.format(i.formats.currencyFormat);case"percent":return t.format(i.formats.percentFormat);case"time":return Craft.charts.utils.getDuration;case"number":return t.format(i.formats.numberFormat)}}}},3352:function(){Craft.ColorInput=Garnish.Base.extend({$container:null,$input:null,$colorContainer:null,$colorPreview:null,$colorInput:null,init:function(t){this.$container=$(t),this.$input=this.$container.find(".color-input"),this.$colorContainer=this.$container.children(".color"),this.$colorPreview=this.$colorContainer.children(".color-preview"),this.createColorInput(),this.handleTextChange(),this.addListener(this.$input,"input","handleTextChange")},createColorInput:function(){var t=document.createElement("input");t.setAttribute("type","color"),"color"===t.type&&(this.$colorContainer.removeClass("static"),this.$colorInput=$(t).addClass("color-preview-input").attr({"aria-controls":this.$input.attr("id"),"aria-label":Craft.t("app","Color picker")}).appendTo(this.$colorPreview),this.addListener(this.$colorInput,"click",(function(t){t.stopPropagation()})),this.addListener(this.$colorContainer,"click",(function(){this.$colorInput.trigger("click")})),this.addListener(this.$colorInput,"input","updateColor"))},updateColor:function(){this.$input.val(this.$colorInput.val()),this.handleTextChange()},handleTextChange:function(){var t=this.$input.val();t!==(t=Craft.trim(t))&&this.$input.val(t),t.length&&"#"===t[0]&&(t=t.substring(1),this.$input.val(t)),t.length?(3===t.length&&(t=t[0].repeat(2)+t[1].repeat(2)+t[2].repeat(2)),t.match(/^[0-9a-f]{6}$/i)?(this.$colorPreview.css("background-color","#".concat(t)),this.$colorInput&&this.$colorInput.val("#".concat(t))):this.$colorPreview.css("background-color","")):this.$colorPreview.css("background-color","")}},{_browserSupportsColorInputs:null,doesBrowserSupportColorInputs:function(){return Craft.ColorInput._browserSupportsColorInputs,Craft.ColorInput._browserSupportsColorInputs}})},8167:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function e(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Craft.CpScreenSlideout=Craft.Slideout.extend({action:null,namespace:null,showingLoadSpinner:!1,hasTabs:!1,hasCpLink:!1,hasSidebar:!1,$header:null,$toolbar:null,$tabContainer:null,$loadSpinner:null,$editLink:null,$sidebarBtn:null,$body:null,$content:null,$sidebar:null,$footer:null,$noticeContainer:null,$cancelBtn:null,$saveBtn:null,tabManager:null,showingSidebar:!1,cancelToken:null,ignoreFailedRequest:!1,fieldsWithErrors:null,init:function(t,e){var i=this;this.action=t,this.setSettings(e,Craft.CpScreenSlideout.defaults),this.fieldsWithErrors=[],this.$header=$("<header/>",{class:"pane-header"}),this.$toolbar=$("<div/>",{class:"so-toolbar"}).appendTo(this.$header),this.$tabContainer=$("<div/>",{class:"pane-tabs"}).appendTo(this.$toolbar),this.$loadSpinner=$("<div/>",{class:"spinner",title:Craft.t("app","Loading"),"aria-label":Craft.t("app","Loading")}).appendTo(this.$toolbar),this.$editLink=$("<a/>",{target:"_blank",class:"btn header-btn hidden",title:Craft.t("app","Open the full edit page in a new tab"),"aria-label":Craft.t("app","Open the full edit page in a new tab"),"data-icon":"external"}).appendTo(this.$toolbar),this.$sidebarBtn=$("<button/>",{type:"button",class:"btn header-btn hidden sidebar-btn",title:Craft.t("app","Show sidebar"),"aria-label":Craft.t("app","Show sidebar"),"data-icon":"sidebar-".concat(Garnish.ltr?"right":"left"),"aria-expanded":"false"}).appendTo(this.$toolbar),this.addListener(this.$sidebarBtn,"click",(function(t){t.preventDefault(),i.showingSidebar?i.hideSidebar():i.showSidebar()})),this.$body=$("<div/>",{class:"so-body"}),this.$content=$("<div/>",{class:"so-content"}).appendTo(this.$body),this.$sidebar=$("<div/>",{class:"so-sidebar details hidden"}).appendTo(this.$body),this.$footer=$("<div/>",{class:"so-footer hidden"}),this.$noticeContainer=$("<div/>",{class:"so-notice"}).appendTo(this.$footer),$("<div/>",{class:"flex-grow"}).appendTo(this.$footer);var s=$("<div/>",{class:"flex flex-nowrap"}).appendTo(this.$footer);this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(s),this.$saveBtn=Craft.ui.createSubmitButton({label:Craft.t("app","Save"),spinner:!0}).appendTo(s);var n=this.$header.add(this.$body).add(this.$footer);this.base(n,{containerElement:"form",containerAttributes:{id:"cp-screen-".concat(Math.floor(1e8*Math.random())),action:"",method:"post",novalidate:"",class:"cp-screen"},closeOnEsc:!1,closeOnShadeClick:!1}),this.$container.data("cpScreen",this),this.on("beforeClose",(function(){i.hideSidebar()})),Garnish.uiLayerManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0},(function(t){i.handleSubmit(t)})),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){i.closeMeMaybe()})),this.addListener(this.$cancelBtn,"click",(function(){i.closeMeMaybe()})),this.addListener(this.$shade,"click",(function(){i.closeMeMaybe()})),this.addListener(this.$container,"click",(function(t){var e=$(event.target);!i.showingSidebar||e.closest(i.$sidebarBtn).length||e.closest(i.$sidebar).length||i.hideSidebar()})),this.addListener(this.$container,"submit","handleSubmit"),this.load()},load:function(t,e){var i=this;return new Promise((function(t,s){i.trigger("beforeLoad"),i.showLoadSpinner(),i.cancelToken&&(i.ignoreFailedRequest=!0,i.cancelToken.cancel()),i.cancelToken=axios.CancelToken.source(),Craft.sendActionRequest("GET",i.action,$.extend({params:Object.assign({},i.getParams(),i.settings.params),cancelToken:i.cancelToken.token,headers:{"X-Craft-Container-Id":i.$container.attr("id")}},i.settings.requestOptions)).then((function(n){i.update(n.data).then((function(){!1!==e&&(i.$container.data("delta-names",n.data.deltaNames),i.$container.data("initial-delta-values",n.data.initialDeltaValues),i.$container.data("initialSerializedValue",i.$container.serialize())),t()})).catch((function(t){s(t)}))})).catch((function(t){i.ignoreFailedRequest||(Craft.cp.displayError(),s(t)),i.ignoreFailedRequest=!1})).finally((function(){i.hideLoadSpinner(),i.cancelToken=null}))}))},getParams:function(){return{}},updateHeaderVisibility:function(){var t=this.settings.showHeader||this.hasTabs||this.hasCpLink||this.showingLoadSpinner;t||this.hasSidebar?this.$header.removeClass("hidden"):this.$header.addClass("hidden"),t?this.$header.addClass("so-visible"):this.$header.removeClass("so-visible")},showLoadSpinner:function(){this.$loadSpinner.removeClass("hidden"),this.showingLoadSpinner=!0,this.updateHeaderVisibility()},hideLoadSpinner:function(){this.$loadSpinner.addClass("hidden"),this.showingLoadSpinner=!1,this.updateHeaderVisibility()},update:function(t){var e=this;return new Promise((function(i){e.namespace=t.namespace,e.$content.html(t.content),t.submitButtonLabel&&e.$saveBtn.text(t.submitButtonLabel),e.updateTabs(t.tabs),t.formAttributes&&Craft.setElementAttributes(e.$container,t.formAttributes),t.editUrl?(e.$editLink.removeClass("hidden").attr("href",t.editUrl),e.hasCpLink=!0):(e.$editLink.addClass("hidden"),e.hasCpLink=!1),t.sidebar?(e.$container.addClass("has-sidebar"),e.$sidebarBtn.removeClass("hidden"),e.$sidebar.html(t.sidebar),e.$sidebar.find("a").each((function(){this.hostname.length&&void 0===$(this).attr("target")&&$(this).attr("target","_blank")})),e.hasSidebar=!0):(e.$container.removeClass("has-sidebar"),e.$sidebarBtn.addClass("hidden"),e.$sidebar.addClass("hidden").html(""),e.hasSidebar=!1),t.notice?e.$noticeContainer.html(t.notice):e.$noticeContainer.empty(),e.updateHeaderVisibility(),e.$footer.removeClass("hidden"),Garnish.requestAnimationFrame((function(){Craft.appendHeadHtml(t.headHtml),Craft.appendBodyHtml(t.bodyHtml),Craft.initUiElements(e.$content),Craft.cp.elementThumbLoader.load($(e.$content)),t.sidebar&&(Craft.initUiElements(e.$sidebar),Craft.cp.elementThumbLoader.load(e.$sidebar)),Garnish.isMobileBrowser()||Craft.setFocusWithin(e.$content),i(),e.trigger("load")}))}))},updateTabs:function(t){var e=this;if(this.tabManager&&(this.tabManager.destroy(),this.tabManager=null,this.$tabContainer.html("")),this.hasTabs=!!t,this.hasTabs){var i=$(t);this.$tabContainer.replaceWith(i),this.$tabContainer=i,this.tabManager=new Craft.Tabs(this.$tabContainer),this.tabManager.on("deselectTab",(function(t){$(t.$tab.attr("href")).addClass("hidden")})),this.tabManager.on("selectTab",(function(t){$(t.$tab.attr("href")).removeClass("hidden"),Garnish.$win.trigger("resize"),e.$body.trigger("scroll")}))}},showSidebar:function(){var t=this;this.showingSidebar||(this.$body.scrollTop(0).addClass("no-scroll"),this.$sidebar.off("transitionend.so").css(this._closedSidebarStyles()).removeClass("hidden"),this.$sidebar[0].offsetWidth,this.$sidebar.css(this._openedSidebarStyles()),Garnish.isMobileBrowser()||this.$sidebar.one("transitionend.so",(function(){Craft.setFocusWithin(t.$sidebar)})),Craft.trapFocusWithin(this.$sidebar),this.$sidebarBtn.addClass("active").attr({"aria-expanded":"true"}),Garnish.$win.trigger("resize"),this.$sidebar.trigger("scroll"),Garnish.uiLayerManager.addLayer(),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.hideSidebar()})),this.showingSidebar=!0)},hideSidebar:function(){var t=this;this.showingSidebar&&(this.$body.removeClass("no-scroll"),this.$sidebar.off("transitionend.so").css(this._closedSidebarStyles()).one("transitionend.so",(function(){t.$sidebar.addClass("hidden"),t.$sidebarBtn.focus()})),this.$sidebarBtn.removeClass("active").attr({"aria-expanded":"false"}),Garnish.uiLayerManager.removeLayer(),this.showingSidebar=!1)},_openedSidebarStyles:function(){return e({},Garnish.ltr?"right":"left","0")},_closedSidebarStyles:function(){return e({},Garnish.ltr?"right":"left","-350px")},showSubmitSpinner:function(){this.$saveBtn.addClass("loading")},hideSubmitSpinner:function(){this.$saveBtn.removeClass("loading")},handleSubmit:function(t){t.preventDefault(),this.submit()},submit:function(){var t=this;this.showSubmitSpinner();var e=Craft.findDeltaData(this.$container.data("initialSerializedValue"),this.$container.serialize(),this.$container.data("delta-names"),null,this.$container.data("initial-delta-values"));Craft.sendActionRequest("POST",null,{data:e,headers:{"X-Craft-Namespace":this.namespace}}).then((function(e){t.handleSubmitResponse(e)})).catch((function(e){t.handleSubmitError(e)})).finally((function(){t.hideSubmitSpinner()}))},handleSubmitResponse:function(t){this.clearErrors();var e=t.data||{};e.message&&Craft.cp.displaySuccess(e.message,e.notificationSettings),this.trigger("submit",{response:t,data:e.modelName&&e[e.modelName]||{}}),this.settings.closeOnSubmit&&this.close()},handleSubmitError:function(t){if(!t.isAxiosError||!t.response||400===!t.response.status)throw Craft.cp.displayError(),t;var e=t.response.data||{};Craft.cp.displayError(e.message),e.errors&&this.showErrors(e.errors)},showErrors:function(e){var i=this;this.clearErrors(),Object.entries(e).forEach((function(e){var s,n,a=(n=2,function(t){if(Array.isArray(t))return t}(s=e)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(s,n)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(s,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),r=a[0],o=a[1],l=i.$container.find('[data-attribute="'.concat(r,'"]'));l&&(Craft.ui.addErrorsToField(l,o),i.fieldsWithErrors.push(l))}))},clearErrors:function(){this.fieldsWithErrors.forEach((function(t){Craft.ui.clearErrorsFromField(t)}))},isDirty:function(){return void 0!==this.$container.data("initialSerializedValue")&&this.$container.serialize()!==this.$container.data("initialSerializedValue")},closeMeMaybe:function(){this.isOpen&&(this.isDirty()&&!confirm(Craft.t("app","Are you sure you want to close this screen? Any changes will be lost."))||this.close())},close:function(){this.base(),this.cancelToken&&(this.ignoreFailedRequest=!0,this.cancelToken.cancel())}},{defaults:{params:{},requestOptions:{},showHeader:null,closeOnSubmit:!0}})},587:function(){function t(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=s(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var n=0,a=function(){};return{s:a,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}((function(t){throw t})),f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return o=t.done,t},e:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}((function(t){l=!0,r=t})),f:function(){try{o||null==i.return||i.return()}finally{if(l)throw r}}}}function i(t){return function(t){if(Array.isArray(t))return n(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||s(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(t,e){if(t){if("string"==typeof t)return n(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?n(t,e):void 0}}function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function a(t){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a(t)}var r=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi;if(jQuery.htmlPrefilter=function(t){return t.replace(r,"<$1></$2>")},$.extend(Craft,{navHeight:48,index:function(t,e){if(!$.isArray(t))throw"The first argument passed to Craft.index() must be an array.";return t.reduce((function(t,i,s){return t["string"==typeof e?i[e]:e(i,s)]=i,t}),{})},group:function(t,e){if(!$.isArray(t))throw"The first argument passed to Craft.group() must be an array.";var i={};return t.reduce((function(t,s,n){var a="string"==typeof e?s[e]:e(s,n);return i.hasOwnProperty(a)||(i[a]=[[],a],t.push(i[a])),i[a][0].push(s),t}),[])},t:function(t,e,i){return void 0!==Craft.translations[t]&&void 0!==Craft.translations[t][e]&&(e=Craft.translations[t][e]),i?this.formatMessage(e,i):e},formatMessage:function(t,e){var i;if(!1===(i=this._tokenizePattern(t)))throw"Message pattern is invalid.";for(var s=0;s<i.length;s++){var n=i[s];if("object"===a(n)&&!1===(i[s]=this._parseToken(n,e)))throw"Message pattern is invalid."}return i.join("")},_tokenizePattern:function(t){var e,s,n=1,a=i(t);if(-1===(e=s=a.indexOf("{")))return[t];for(var r=[a.slice(0,s).join("")];;){var o=a.indexOf("{",s+1),l=a.indexOf("}",s+1);if(-1===o&&(o=!1),-1===l&&(l=!1),!1===o&&!1===l)break;if(!1===o&&(o=a.length),l>o?(n++,s=o):(n--,s=l),0===n&&(r.push(a.slice(e+1,s).join("").split(",",3)),e=s+1,r.push(a.slice(e,o).join("")),e=o),0!==n&&(!1===o||!1===l))break}return 0===n&&r},_parseToken:function(t,e){var s=this,n=Craft.trim(t[0]);if(void 0===e[n])return"{".concat(t.join(","),"}");var r=e[n],o=void 0!==t[1]?Craft.trim(t[1]):"none";switch(o){case"number":return function(){var e=void 0!==t[2]?Craft.trim(t[2]):null;if(null!==e&&"integer"!==e)throw"Message format 'number' is only supported for integer values.";var i,s=Craft.formatNumber(r);return null===e&&-1!==(i="".concat(r).indexOf("."))&&(s+=".".concat(r.substring(i+1))),s}();case"none":return r;case"select":return function(){if(void 0===t[2])return!1;for(var i=s._tokenizePattern(t[2]),n=i.length,a=!1,o=0;o+1<n;o++){if(Garnish.isArray(i[o])||!Garnish.isArray(i[o+1]))return!1;var l=Craft.trim(i[o++]);(!1===a&&"other"===l||l==r)&&(a=i[o].join(","))}return!1!==a&&s.formatMessage(a,e)}();case"plural":return function(){if(void 0===t[2])return!1;for(var n=s._tokenizePattern(t[2]),o=n.length,l=!1,h=0,d=0;d+1<o;d++){if("object"===a(n[d])||"object"!==a(n[d+1]))return!1;var c=Craft.trim(n[d++]),u=i(c);if(1===d&&"offset:"===c.substring(0,7)){var p=i(c.replace(/[\n\r\t]/g," ")).indexOf(" ",7);if(-1===p)throw"Message pattern is invalid.";h=parseInt(Craft.trim(u.slice(7,p).join(""))),c=Craft.trim(u.slice(p+1,p+1+u.length).join(""))}(!1===l&&"other"===c||"="===c[0]&&parseInt(u.slice(1,1+u.length).join(""))===r||"one"===c&&r-h==1)&&(l=("string"==typeof n[d]?[n[d]]:n[d]).map((function(t){return t.replace("#",r-h)})).join(","))}return!1!==l&&s.formatMessage(l,e)}();default:throw"Message format '".concat(o,"' is not supported.")}},formatDate:function(t){return"object"!==a(t)&&(t=new Date(t)),$.datepicker.formatDate(Craft.datepickerOptions.dateFormat,t)},formatNumber:function(t,e){return void 0===e&&(e=",.0f"),d3.formatLocale(d3FormatLocaleDefinition).format(e)(t)},shortcutText:function(t,e,i){return"Mac"===Craft.clientOs?(i?"⌥":"")+(e?"⇧":"")+"⌘"+t:"Ctrl+"+(i?"Alt+":"")+(e?"Shift+":"")+t},escapeHtml:function(t){return $("<div/>").text(t).html()},escapeRegex:function(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},getText:function(t){return $("<div/>").html(t).text()},encodeUriComponent:function(t){t=encodeURIComponent(t);var e={"!":"%21","*":"%2A","'":"%27","(":"%28",")":"%29"};for(var i in e){var s=new RegExp("\\"+i,"g");t=t.replace(s,e[i])}return t},selectFullValue:function(t){var e=$(t),i=e.val();if(void 0!==e[0].setSelectionRange){var s=2*i.length;e[0].setSelectionRange(0,s)}else e.val(i)},formatInputId:function(t){return this.rtrim(t.replace(/[^\w\-]+/g,"-"),"-")},getUrl:function(t,e,i){"string"!=typeof t&&(t="");var s=null;if($.isPlainObject(e))void 0!==e["#"]&&(s=e["#"],delete e["#"]);else if("string"==typeof e){var n=e.indexOf("#");-1!==n&&(s=e.substring(n+1),e=e.substring(0,n)),e=Object.fromEntries(new URLSearchParams(e).entries())}else e={};var a=t.indexOf("#");-1!==a&&(s||(s=t.substring(a+1)),t=t.substring(0,a));var r,o=t.indexOf("?");if(-1!==o&&(e=$.extend(Object.fromEntries(new URLSearchParams(t.substring(o+1)).entries()),e),t=t.substring(0,o)),-1!==t.search("://")||"/"===t[0])return t+($.isEmptyObject(e)?"":"?".concat($.param(e)))+(s?"#".concat(s):"");if(t=Craft.trim(t,"/"),i){if(r=i,t&&Craft.pathParam){var l=r.match(new RegExp("[&?]"+Craft.escapeRegex(Craft.pathParam)+"=[^&]+"));l&&(r=r.replace(l[0],Craft.rtrim(l[0],"/")+"/"+t),t="")}}else r=Craft.baseUrl;return-1!==(o=r.indexOf("?"))&&(e=$.extend(Object.fromEntries(new URLSearchParams(r.substring(o+1)).entries()),e),r=r.substring(0,o)),!Craft.omitScriptNameInUrls&&t&&(Craft.usePathInfo||!Craft.pathParam?-1===r.search(Craft.scriptName)&&(r=Craft.rtrim(r,"/")+"/"+Craft.scriptName):(void 0!==e[Craft.pathParam]&&(t=Craft.rtrim(e[Craft.pathParam])+(t?"/"+t:"")),e[Craft.pathParam]=t,t=null)),t&&(r=Craft.rtrim(r,"/")+"/"+t),$.isEmptyObject(e)||(r+="?".concat($.param(e))),s&&(r+="#".concat(s)),r},getCpUrl:function(t,e){return this.getUrl(t,e,Craft.baseCpUrl)},getSiteUrl:function(t,e){return this.getUrl(t,e,Craft.baseSiteUrl)},getActionUrl:function(t,e){return Craft.getUrl(t,e,Craft.actionUrl)},redirectTo:function(t){document.location.href=this.getUrl(t)},setUrl:function(t){"undefined"!=typeof history&&(t.match(/#/)||(t+=document.location.hash),history.replaceState({},"",t))},setPath:function(t){this.path=t,this.setUrl(Craft.getUrl(t,document.location.search))},setQueryParam:function(t,e){var i=document.location.origin+document.location.pathname,s=this.getQueryParams();null!=e&&!1!==e?s[t]=e:delete s[t],this.setUrl(Craft.getUrl(i,s))},getPageUrl:function(t){var e=document.location.origin+document.location.pathname;e=Craft.rtrim(e,"/");var i=document.location.search?document.location.search.substring(1):"";if("?"===Craft.pageTrigger[0]){var s=Craft.pageTrigger.substring(1);if(document.location.search){var n=Object.fromEntries(new URLSearchParams(i).entries());delete n[s],i=$.param(n)}1!==t&&(i+=(""!==i?"&":"")+"".concat(s,"=").concat(t))}else e=e.replace(new RegExp("/"+Craft.escapeRegex(Craft.pageTrigger)+"\\d+$"),""),1!==t&&(e+="/".concat(Craft.pageTrigger).concat(t));return e+(i?"?".concat(i):"")+document.location.hash},getCsrfInput:function(){return Craft.csrfTokenName?'<input type="hidden" name="'+Craft.csrfTokenName+'" value="'+Craft.csrfTokenValue+'"/>':""},postActionRequest:function(t,e,i,s){"function"==typeof e&&(s=i,i=e,e={}),(s=s||{}).contentType&&s.contentType.match(/\bjson\b/)&&("object"===a(e)&&(e=JSON.stringify(e)),s.contentType="application/json; charset=utf-8");var n=$.ajax($.extend({url:Craft.getActionUrl(t),type:"POST",dataType:"json",headers:this._actionHeaders(),data:e,success:i,error:function(t,e,s){4===t.readyState&&(400!==t.status&&(void 0!==Craft.cp?Craft.cp.displayError():alert(Craft.t("app","A server error occurred."))),i&&i(400===t.status?t.responseJSON:null,e,t))}},s));return"function"==typeof s.send&&s.send(n),n},_actionHeaders:function(){var t={"X-Registered-Asset-Bundles":Object.keys(Craft.registeredAssetBundles).join(","),"X-Registered-Js-Files":Object.keys(Craft.registeredJsFiles).join(",")};return Craft.csrfTokenValue&&(t["X-CSRF-Token"]=Craft.csrfTokenValue),t},sendActionRequest:function(t,e){var i=this,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if($.isPlainObject(e)&&(s=e,e=null),"POST"===t.toUpperCase()&&e&&s.data)if("string"==typeof s.data){var n=s&&s.headers&&s.headers["X-Craft-Namespace"],a=this.namespaceInputName("action",n);s.data+="&".concat(a,"=").concat(e)}else delete s.data.action;return new Promise((function(n,a){(s=s?$.extend({},s):{}).method=t,s.url=e?Craft.getActionUrl(e):Craft.getCpUrl(),s.headers=$.extend({"X-Requested-With":"XMLHttpRequest"},s.headers||{},i._actionHeaders()),s.params=$.extend({},s.params||{},{v:(new Date).getTime()}),axios.request(s).then(n).catch(a)}))},sendApiRequest:function(t,e,i){var s=this;return new Promise((function(n,a){var r=(i=i?$.extend({},i):{}).cancelToken||null;s._getApiHeaders(r).then((function(o){i.method=t,i.baseURL=Craft.baseApiUrl,i.url=e,i.headers=$.extend(o,i.headers||{}),i.params=$.extend(Craft.apiParams||{},i.params||{},{v:(new Date).getTime()}),s._apiHeaders||(i.params.processCraftHeaders=1),Craft.httpProxy&&(i.proxy=Craft.httpProxy),axios.request(i).then((function(t){s._processApiHeaders(t.headers,r).then((function(){n(t.data)})).catch(a)})).catch(a)})).catch(a)}))},_loadingApiHeaders:!1,_apiHeaders:null,_apiHeaderWaitlist:[],_getApiHeaders:function(t){var i=this;return new Promise((function(s,n){i._loadingApiHeaders?i._apiHeaderWaitlist.push([s,n]):i._apiHeaders?s(i._apiHeaders):(i._loadingApiHeaders=!0,i.sendActionRequest("POST","app/api-headers",{cancelToken:t}).then((function(t){i._loadingApiHeaders?s(t.data):n(e)})).catch((function(t){i._rejectApiRequests(n,t)})))}))},_processApiHeaders:function(t,i){var s=this;return new Promise((function(n,a){s._apiHeaders?n():s.sendActionRequest("POST","app/process-api-response-headers",{data:{headers:t},cancelToken:i}).then((function(t){if(s._loadingApiHeaders)for(s._apiHeaders=t.data,s._loadingApiHeaders=!1,n();s._apiHeaderWaitlist.length;)s._apiHeaderWaitlist.shift()[0](s._apiHeaders);else a(e)})).catch((function(t){s._rejectApiRequests(a,t)}))}))},_rejectApiRequests:function(t,e){for(this._loadingApiHeaders=!1,t(e);this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[1](e)},clearCachedApiHeaders:function(){for(this._apiHeaders=null,this._loadingApiHeaders=!1;this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[1]()},downloadFromUrl:function(t,e,i){return new Promise((function(s,n){var r=new XMLHttpRequest;r.open(t,e,!0),"object"===a(i)?(r.setRequestHeader("Content-Type","application/json; charset=UTF-8"),i=JSON.stringify(i)):r.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),r.responseType="blob",r.onload=function(){if(200===r.status){var t=r.getResponseHeader("content-disposition"),e=/"([^"]*)"/.exec(t),i=null!=e&&e[1]?e[1]:"Download",a=r.getResponseHeader("content-type"),o=new Blob([r.response],{type:a}),l=document.createElement("a");l.href=window.URL.createObjectURL(o),l.download=i,document.body.appendChild(l),l.click(),document.body.removeChild(l),s()}else n()},r.send(i)}))},stringToArray:function(t){if("string"!=typeof t)return t;for(var e=t.split(","),i=0;i<e.length;i++)e[i]=$.trim(e[i]);return e},findDeltaData:function(t,e,i,s,n,r){t="string"==typeof t?t:"",e="string"==typeof e?e:"",i=$.isArray(i)?i:[],n=$.isPlainObject(n)?n:{},r=$.isArray(r)?r:[],i.sort((function(t,e){return t.length===e.length?0:t.length>e.length?1:-1}));for(var o=this._groupParamsByDeltaNames(t.split("&"),i,!1,n),l=this._groupParamsByDeltaNames(e.split("&"),i,!0,!1),h=l.__root__,d=0;d<i.length;d++)(Craft.inArray(i[d],r)||"object"===a(l[i[d]])&&("object"!==a(o[i[d]])||JSON.stringify(o[i[d]])!==JSON.stringify(l[i[d]])))&&((h=h.concat(l[i[d]])).push("modifiedDeltaNames[]="+i[d]),s&&s(i[d],l[i[d]]));return h.join("&")},_groupParamsByDeltaNames:function(t,e,i,s){var n={};i&&(n.__root__=[]);var a=function(t){return encodeURIComponent(t).replace("%3D","=")};t=t.map((function(t){return decodeURIComponent(t)}));t:for(var r=0;r<t.length;r++){for(var o=e.length-1;o>=0;o--){var l=t[r].substring(0,e[o].length+1);if(l===e[o]+"="||l===e[o]+"["){void 0===n[e[o]]&&(n[e[o]]=[]),n[e[o]].push(a(t[r]));continue t}}i&&n.__root__.push(a(t[r]))}if(s){var h=function(t,e){return $.isArray(e)||$.isPlainObject(e)?e=$.param(e):"string"==typeof e?e=encodeURIComponent(e):null===e&&(e=""),"".concat(encodeURIComponent(t),"=").concat(e)};for(var d in s)if(s.hasOwnProperty(d))if($.isPlainObject(s[d]))for(var c in n[d]=[],s[d])s[d].hasOwnProperty(c)&&n[d].push(h("".concat(d,"[").concat(c,"]"),s[d][c]));else n[d]=[h(d,s[d])]}return n},expandPostArray:function(t){var e,i={};for(var s in t)if(t.hasOwnProperty(s)){var n,r=t[s],o=s.match(/^(\w+)(\[.*)?/);if(o[2])for(n=o[2].match(/\[[^\[\]]*\]/g),e=0;e<n.length;e++)n[e]=n[e].substring(1,n[e].length-1);else n=[];n.unshift(o[1]);var l=i;for(e=0;e<n.length;e++)e<n.length-1?("object"!==a(l[n[e]])&&(n[e+1]&&parseInt(n[e+1])!=n[e+1]?l[n[e]]={}:l[n[e]]=[]),l=l[n[e]]):(n[e]||(n[e]=l.length),l[n[e]]=r)}return i},createForm:function(t){var e=$("<form/>",{attr:{method:"post",action:"","accept-charset":"UTF-8"}});if("string"==typeof t)for(var i,s=t.split("&"),n=0;n<s.length;n++)i=s[n].split("=",2),$("<input/>",{type:"hidden",name:decodeURIComponent(i[0]),value:decodeURIComponent(i[1]||"")}).appendTo(e);return e},compare:function(t,e,i){if(a(t)!==a(e))return!1;if("object"===a(t)&&null!==t&&null!==e){if(t.length!==e.length)return!1;if(t instanceof Array!=e instanceof Array)return!1;if(!(t instanceof Array))if(void 0===i||!0===i){if(!Craft.compare(Craft.getObjectKeys(t).sort(),Craft.getObjectKeys(e).sort()))return!1}else if(!Craft.compare(Craft.getObjectKeys(t),Craft.getObjectKeys(e)))return!1;for(var s in t)if(t.hasOwnProperty(s)&&!Craft.compare(t[s],e[s]))return!1;return!0}return t===e},getObjectKeys:function(t){var e=[];for(var i in t)t.hasOwnProperty(i)&&e.push(i);return e},escapeChars:function(t){Garnish.isArray(t)||(t=t.split());for(var e="",i=0;i<t.length;i++)e+="\\"+t[i];return e},ltrim:function(t,e){if(!t)return t;void 0===e&&(e=" \t\n\r\0\v");var i=new RegExp("^["+Craft.escapeChars(e)+"]+");return t.replace(i,"")},rtrim:function(t,e){if(!t)return t;void 0===e&&(e=" \t\n\r\0\v");var i=new RegExp("["+Craft.escapeChars(e)+"]+$");return t.replace(i,"")},trim:function(t,e){return t=Craft.ltrim(t,e),Craft.rtrim(t,e)},startsWith:function(t,e){return t.substring(0,e.length)===e},filterArray:function(t,e){for(var i=[],s=0;s<t.length;s++)("function"==typeof e?e(t[s],s):t[s])&&i.push(t[s]);return i},inArray:function(t,e){return $.isPlainObject(e)&&(e=Object.values(e)),e.includes(t)},removeFromArray:function(t,e){var i=$.inArray(t,e);return-1!==i&&(e.splice(i,1),!0)},getLast:function(t){return t.length?t[t.length-1]:null},uppercaseFirst:function(t){return t.charAt(0).toUpperCase()+t.slice(1)},lowercaseFirst:function(t){return t.charAt(0).toLowerCase()+t.slice(1)},parseUrl:function(t){var e=t.match(/^(?:(https?):\/\/|\/\/)([^\/\:]*)(?:\:(\d+))?(\/[^\?]*)?(?:\?([^#]*))?(#.*)?/);return e?{scheme:e[1],host:e[2]+(e[3]?":"+e[3]:""),hostname:e[2],port:e[3]||null,path:e[4]||"/",query:e[5]||null,hash:e[6]||null}:{}},getQueryParams:function(){return Object.fromEntries(new URLSearchParams(window.location.search).entries())},getQueryParam:function(t){return new Proxy(new URLSearchParams(window.location.search),{get:function(t,e){return t.get(e)}})[t]},isSameHost:function(t){var e=this.parseUrl(document.location.href);if(!e)return!1;var i=this.parseUrl(t);return!!i&&e.host===i.host},secondsToHumanTimeDuration:function(t,e){void 0===e&&(e=!0);var i=604800,s=Math.floor(t/i);t%=i;var n=Math.floor(t/86400);t%=86400;var a,r=Math.floor(t/3600);t%=3600,e?(a=Math.floor(t/60),t%=60):(a=Math.round(t/60),t=0);var o=[];return s&&o.push(s+" "+(1===s?Craft.t("app","week"):Craft.t("app","weeks"))),n&&o.push(n+" "+(1===n?Craft.t("app","day"):Craft.t("app","days"))),r&&o.push(r+" "+(1===r?Craft.t("app","hour"):Craft.t("app","hours"))),!a&&(e||s||n||r)||o.push(a+" "+(1===a?Craft.t("app","minute"):Craft.t("app","minutes"))),!t&&(!e||s||n||r||a)||o.push(t+" "+(1===t?Craft.t("app","second"):Craft.t("app","seconds"))),o.join(", ")},asciiString:function(t,e){t=t.normalize("NFC");for(var i,s="",n=0;n<t.length;n++)i=t.charAt(n),s+="string"==typeof(e||Craft.asciiCharMap)[i]?(e||Craft.asciiCharMap)[i]:i;return s},uuid:function(){return"function"==typeof crypto.randomUUID?crypto.randomUUID():([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(t){return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}))},namespaceInputName:function(t,e){return e?t.replace(/([^'"\[\]]+)([^'"]*)/,"".concat(e,"[$1]$2")):t},namespaceId:function(t,e){return Craft.formatInputId(e?"".concat(e,"-").concat(t):t)},randomString:function(t){for(var e="",i=0;i<t;i++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()));return e},createErrorList:function(t){for(var e=$(document.createElement("ul")).addClass("errors"),i=0;i<t.length;i++){var s=$(document.createElement("li"));s.appendTo(e),s.html(t[i])}return e},appendHeadHtml:function(t){if(t){var e=$("link[href]");if(e.length){for(var i,s=[],n=0;n<e.length;n++)i=e.eq(n).attr("href").replace(/&/g,"&amp;"),s.push(Craft.escapeRegex(i));var a=new RegExp('<link\\s[^>]*href="(?:'+s.join("|")+')".*?></link>',"g");t=t.replace(a,"")}$("head").append(t)}},appendBodyHtml:function(t){if(t){var e=$("script[src]");if(e.length){for(var i,s=[],n=0;n<e.length;n++)i=e.eq(n).attr("src").replace(/&/g,"&amp;"),s.push(Craft.escapeRegex(i));var a=new RegExp('<script\\s[^>]*src="(?:'+s.join("|")+')".*?><\/script>',"g");t=t.replace(a,"")}Garnish.$bod.append(t)}},appendFootHtml:function(t){console.warn("Craft.appendFootHtml() is deprecated. Craft.appendBodyHtml() should be used instead."),this.appendBodyHtml(t)},initUiElements:function(t){$(".grid",t).grid(),$(".info",t).infoicon(),$(".checkbox-select",t).checkboxselect(),$(".fieldtoggle",t).fieldtoggle(),$(".lightswitch",t).lightswitch(),$(".nicetext",t).nicetext(),$(".formsubmit",t).formsubmit(),$(".menubtn:not([data-disclosure-trigger])",t).menubtn(),$("[data-disclosure-trigger]",t).disclosureMenu(),$(".datetimewrapper",t).datetime(),$('.datewrapper > input[type="date"], .timewrapper > input[type="time"]',t).datetimeinput(),$("a",t).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===$(this).attr("target")&&$(this).attr("rel","noopener").attr("target","_blank")}))},_elementIndexClasses:{},_elementSelectorModalClasses:{},_elementEditorClasses:{},registerElementIndexClass:function(t,e){if(void 0!==this._elementIndexClasses[t])throw"An element index class has already been registered for the element type “"+t+"”.";this._elementIndexClasses[t]=e},registerElementSelectorModalClass:function(t,e){if(void 0!==this._elementSelectorModalClasses[t])throw"An element selector modal class has already been registered for the element type “"+t+"”.";this._elementSelectorModalClasses[t]=e},registerElementEditorClass:function(t,e){if(void 0!==this._elementEditorClasses[t])throw"An element editor class has already been registered for the element type “"+t+"”.";this._elementEditorClasses[t]=e},createElementIndex:function(t,e,i){return new(void 0!==this._elementIndexClasses[t]?this._elementIndexClasses[t]:Craft.BaseElementIndex)(t,e,i)},createElementSelectorModal:function(t,e){return new(void 0!==this._elementSelectorModalClasses[t]?this._elementSelectorModalClasses[t]:Craft.BaseElementSelectorModal)(t,e)},createElementEditor:function(t,e,i){return void 0===i&&$.isPlainObject(e)?(i=e,e=null):"object"!==a(i)&&(i={}),i.elementType||(i.elementType=t),new Craft.ElementEditorSlideout(e,i)},getLocalStorage:function(t,e){return t="Craft-"+Craft.systemUid+"."+t,"undefined"!=typeof localStorage&&void 0!==localStorage[t]?JSON.parse(localStorage[t]):e},setLocalStorage:function(t,e){if("undefined"!=typeof localStorage){t="Craft-"+Craft.systemUid+"."+t;try{localStorage[t]=JSON.stringify(e)}catch(t){}}},removeLocalStorage:function(t){"undefined"!=typeof localStorage&&localStorage.removeItem("Craft-".concat(Craft.systemUid,".").concat(t))},getCookie:function(t){return document.cookie.replace(new RegExp("(?:(?:^|.*;\\s*)Craft-".concat(Craft.systemUid,":").concat(t,"\\s*\\=\\s*([^;]*).*$)|^.*$")),"$1")},setCookie:function(t,e,i){i=$.extend({},this.defaultCookieOptions,i);var s="Craft-".concat(Craft.systemUid,":").concat(t,"=").concat(encodeURIComponent(e));i.path&&(s+=";path=".concat(i.path)),i.domain&&(s+=";domain=".concat(i.domain)),i.maxAge?s+=";max-age-in-seconds=".concat(i.maxAge):i.expires&&(s+=";expires=".concat(i.expires.toUTCString())),i.secure&&(s+=";secure"),document.cookie=s},removeCookie:function(t){this.setCookie(t,"",new Date("1970-01-01T00:00:00"))},getElementInfo:function(t){var e=$(t);return e.hasClass("element")||(e=e.find(".element:first")),{id:e.data("id"),siteId:e.data("site-id"),label:e.data("label"),status:e.data("status"),url:e.data("url"),hasThumb:e.hasClass("hasthumb"),$element:e}},setElementSize:function(t,e){var i=$(t);if("small"!==e&&"large"!==e&&(e="small"),!i.hasClass(e)){var s="small"===e?"large":"small";if(i.addClass(e).removeClass(s),i.hasClass("hasthumb")){var n=i.find("> .elementthumb > img"),a=$("<img/>",{sizes:("small"===e?"30":"100")+"px",srcset:n.attr("srcset")||n.attr("data-pfsrcset")});n.replaceWith(a),picturefill({elements:[a[0]]})}}},submitForm:function(t,e){if(void 0===e&&(e={}),!e.confirm||confirm(e.confirm)){if(e.action&&$("<input/>",{type:"hidden",name:"action",val:e.action}).appendTo(t),e.redirect&&$("<input/>",{type:"hidden",name:"redirect",val:e.redirect}).appendTo(t),e.params)for(var i in e.params){var s=e.params[i];$("<input/>",{type:"hidden",name:i,val:s}).appendTo(t)}e.retainScroll&&this.setLocalStorage("scrollY",window.scrollY),t.trigger($.extend({type:"submit"},e.data))}},trapFocusWithin:function(t){Garnish.trapFocusWithin(t)},setFocusWithin:function(t){Garnish.setFocusWithin(t)},filterInputVal:function(t,e){for(var i=$(t),s=i.val(),n=i[0].selectionStart,a="",r=0;r<s.length;r++)s[r].match(e)?a+=s[r]:r<n&&n--;a!==s&&(i.val(a),i[0].setSelectionRange(n,n))},filterNumberInputVal:function(t){this.filterInputVal(t,/[0-9.,\-]/)},setElementAttributes:function(e,i){var s=$(e);for(var n in i)if(i.hasOwnProperty(n)){var a=i[n];if(null===a||!1===a)s.removeAttr(n);else if(!0===a)s.attr(n,"");else if($.isArray(a)||$.isPlainObject(a))if(Craft.dataAttributes.includes(n)){for(var r in a=Object.assign({},a))if(a.hasOwnProperty(r)){var o=a[r];null!==o&&!1!==o&&(o=$.isPlainObject(o)||$.isArray(o)?JSON.stringify(o):!0===o?"":this.escapeHtml(o),s.attr("".concat(n,"-").concat(r),o))}}else if("class"===n){$.isPlainObject(a)&&(a=Object.values(a));var l,h=t(a);try{for(h.s();!(l=h.n()).done;){var d=l.value;s.addClass(d)}}catch(t){h.e(t)}finally{h.f()}}else"style"===n?s.css(a):s.attr(n,JSON.stringify(a));else s.attr(n,this.escapeHtml(a))}},isVisible:function(){return void 0===document.visibilityState||"visible"===document.visibilityState},useMobileStyles:function(){return Garnish.isMobileBrowser()||document.body.clientWidth<600}}),Craft.pageId=Craft.uuid(),"undefined"!=typeof BroadcastChannel){var o="CraftCMS:".concat(Craft.appId);Craft.broadcaster=new BroadcastChannel(o),Craft.messageReceiver=new BroadcastChannel(o),Craft.messageReceiver.addEventListener("message",(function(e){if("saveElement"===e.data.event){var i=$('div.element[data-id="'.concat(e.data.id,'"][data-settings]'));if(!i.length)return;for(var s={type:i.data("type"),id:e.data.id,instances:[]},n=0;n<i.length;n++){var a=i.eq(n);s.instances.push(Object.assign({siteId:a.data("site-id")},a.data("settings")))}Craft.sendActionRequest("POST","app/render-element",{data:s}).then((function(e){for(var s=e.data,n=0;n<i.length;n++){var a=i.eq(n);if(s.elementHtml[n]){var r,o=$(s.elementHtml[n]),l=t(o[0].attributes);try{for(l.s();!(r=l.n()).done;){var h=r.value;"class"===h.name?a.addClass(h.value):a.attr(h.name,h.value)}}catch(t){l.e(t)}finally{l.f()}var d=a.find("input,button").detach();a.html(o.html()),d.length&&d.prependTo(a)}}Craft.cp.elementThumbLoader.load(i)}))}}))}$.extend($.fn,{animateLeft:function(t,e,i,s){return"ltr"===Craft.orientation?this.velocity({left:t},e,i,s):this.velocity({right:t},e,i,s)},animateRight:function(t,e,i,s){return"ltr"===Craft.orientation?this.velocity({right:t},e,i,s):this.velocity({left:t},e,i,s)},disable:function(){return this.each((function(){var t=$(this);t.addClass("disabled"),t.data("activatable")&&t.removeAttr("tabindex")}))},enable:function(){return this.each((function(){var t=$(this);t.removeClass("disabled"),t.data("activatable")&&t.attr("tabindex","0")}))},grid:function(){return this.each((function(){var t=$(this),e={};t.data("item-selector")&&(e.itemSelector=t.data("item-selector")),t.data("cols")&&(e.cols=parseInt(t.data("cols"))),t.data("max-cols")&&(e.maxCols=parseInt(t.data("max-cols"))),t.data("min-col-width")&&(e.minColWidth=parseInt(t.data("min-col-width"))),t.data("mode")&&(e.mode=t.data("mode")),t.data("fill-mode")&&(e.fillMode=t.data("fill-mode")),t.data("col-class")&&(e.colClass=t.data("col-class")),t.data("snap-to-grid")&&(e.snapToGrid=!!t.data("snap-to-grid")),new Craft.Grid(this,e)}))},infoicon:function(){return this.each((function(){new Craft.InfoIcon(this)}))},checkboxselect:function(){return this.each((function(){$.data(this,"checkboxselect")||new Garnish.CheckboxSelect(this)}))},fieldtoggle:function(){return this.each((function(){$.data(this,"fieldtoggle")||new Craft.FieldToggle(this)}))},lightswitch:function(t,e,i){return"settings"===t?("string"==typeof e?(t={})[e]=i:t=e,this.each((function(){var e=$.data(this,"lightswitch");e&&e.setSettings(t)}))):($.isPlainObject(t)||(t={}),this.each((function(){var e=$.extend({},t);Garnish.hasAttr(this,"data-value")&&(e.value=$(this).attr("data-value")),Garnish.hasAttr(this,"data-indeterminate-value")&&(e.indeterminateValue=$(this).attr("data-indeterminate-value")),$.data(this,"lightswitch")||new Craft.LightSwitch(this,e)})))},nicetext:function(){return this.each((function(){$.data(this,"nicetext")||new Garnish.NiceText(this)}))},formsubmit:function(){return this.on("click",(function(t){var e=$(t.currentTarget),i=e.data("params")||{};e.data("param")&&(i[e.data("param")]=e.data("value"));var s=e.data("menu")?e.data("menu").$anchor:e,n=s.attr("data-form")?$("#"+s.attr("data-form")):s.closest("form");Craft.submitForm(n,{confirm:e.data("confirm"),action:e.data("action"),redirect:e.data("redirect"),params:i,data:$.extend({customTrigger:e},e.data("event-data"))})}))},menubtn:function(){return this.each((function(){var t=$(this);if(!t.data("menubtn")&&t.next().hasClass("menu")){var e={};t.data("menu-anchor")&&(e.menuAnchor=t.data("menu-anchor")),new Garnish.MenuBtn(t,e)}}))},disclosureMenu:function(){return this.each((function(){var t=$(this);!t.data("trigger")&&t.attr("aria-controls")&&new Garnish.DisclosureMenu(t)}))},datetime:function(){return this.each((function(){var t=$(this),e=t.find('input:not([name$="[timezone]"])'),i=function(){for(var i=!1,s=0;s<e.length;s++)if(e.eq(s).val()){i=!0;break}if(i){if(!t.children(".clear-btn").length)var n=$("<button/>",{type:"button",class:"clear-btn",title:Craft.t("app","Clear"),"aria-label":Craft.t("app","Clear")}).appendTo(t).on("click",(function(){for(var t=0;t<e.length;t++)e.eq(t).val("").trigger("input").trigger("change");n.remove(),e.first().filter('[type="text"]').focus()}))}else t.children(".clear-btn").remove()};e.on("change",i),i()}))},datetimeinput:function(){return this.each((function(){var t=$(this),e=function(){""===t.val()?t.addClass("empty-value"):t.removeClass("empty-value")};t.on("input",e),e()}))}}),Garnish.NiceText.charsLeftHtml=function(t){return Craft.t("app",'<span class="visually-hidden">Characters left:</span> {chars, number}',{chars:t})},Garnish.$doc.ready((function(){Craft.initUiElements()}))},691:function(){function t(t){return function(t){if(Array.isArray(t))return s(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||i(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function e(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(t,e)||i(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(t,e){if(t){if("string"==typeof t)return s(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?s(t,e):void 0}}function s(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CustomizeSourcesModal=Garnish.Modal.extend({elementIndex:null,$elementIndexSourcesContainer:null,$sidebar:null,$sidebarToggleBtn:null,$sourcesContainer:null,$sourcesHeader:null,$sourcesHeading:null,$sourceSettingsContainer:null,$sourceSettingsHeader:null,$addSourceMenu:null,addSourceMenu:null,$footer:null,$footerBtnContainer:null,$saveBtn:null,$cancelBtn:null,$loadingSpinner:null,sourceSort:null,sources:null,selectedSource:null,elementTypeName:null,baseSortOptions:null,availableTableAttributes:null,customFieldAttributes:null,conditionBuilderHtml:null,conditionBuilderJs:null,userGroups:null,init:function(t,e){var i=this;this.base(),this.setSettings(e,{resizable:!0}),this.elementIndex=t,this.$elementIndexSourcesContainer=this.elementIndex.$sidebar.children("nav").children("ul");var s=$('<form class="modal customize-sources-modal"/>').appendTo(Garnish.$bod);this.$sidebar=$('<div class="cs-sidebar block-types"/>').appendTo(s).attr({role:"navigation","aria-label":Craft.t("app","Source")}),this.$sourcesContainer=$('<div class="sources">').appendTo(this.$sidebar),this.$sourceSettingsContainer=$('<div class="source-settings">').appendTo(s),this.$footer=$('<div class="footer"/>').appendTo(s),this.$footerBtnContainer=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$footerBtnContainer),this.$saveBtn=Craft.ui.createSubmitButton({class:"disabled",label:Craft.t("app","Save"),spinner:!0}).appendTo(this.$footerBtnContainer),this.$loadingSpinner=$('<div class="spinner"/>').appendTo(this.$sourceSettingsContainer),this.setContainer(s),this.show(),Craft.sendActionRequest("POST","element-index-settings/get-customize-sources-modal-data",{data:{elementType:this.elementIndex.elementType}}).then((function(t){i.$saveBtn.removeClass("disabled"),i.buildModal(t.data)})).finally((function(){i.$loadingSpinner.remove(),Garnish.setFocusWithin(i.$sidebar)})),this.addListener(this.$cancelBtn,"click","hide"),this.addListener(this.$saveBtn,"click","save"),this.addListener(this.$container,"submit","save")},buildModal:function(t){var e=this;this.baseSortOptions=t.baseSortOptions,this.defaultSortOptions=t.defaultSortOptions,this.availableTableAttributes=t.availableTableAttributes,this.customFieldAttributes=t.customFieldAttributes,this.elementTypeName=t.elementTypeName,this.conditionBuilderHtml=t.conditionBuilderHtml,this.conditionBuilderJs=t.conditionBuilderJs,this.userGroups=t.userGroups,t.headHtml&&Craft.appendHeadHtml(t.headHtml),t.bodyHtml&&Craft.appendBodyHtml(t.bodyHtml),this.sourceSort=new Garnish.DragSort({handle:".move",axis:"y"}),this.sources=[];for(var i=0;i<t.sources.length;i++)this.sources.push(this.addSource(t.sources[i]));this.selectedSource||void 0===this.sources[0]||this.sources[0].select();var s=$('<div class="buttons left" data-wrapper/>').appendTo(this.$footer),n=$("<button/>",{type:"button",class:"btn menubtn add icon","aria-label":Craft.t("app","Add…"),"aria-controls":"add-source-menu",title:Craft.t("app","Add…"),"data-disclosure-trigger":""}).appendTo(s);this.$addSourceMenu=$("<div/>",{id:"add-source-menu",class:"menu menu--disclosure"}).appendTo(s);var a=function(t){var i=e.addSource(t,!0);Garnish.scrollContainerToElement(e.$sidebar,i.$item),i.select(),e.addSourceMenu.hide()},r=$("<button/>",{type:"button",class:"menu-option",text:Craft.t("app","New heading")}).on("click",(function(){a({type:"heading"}),e.focusLabelInput()})),o=$("<button/>",{type:"button",class:"menu-option",text:Craft.t("app","New custom source"),"data-type":"custom"}).on("click",(function(){var t=e.baseSortOptions.slice(0);t.push(e.defaultSortOptions),a({type:"custom",key:"custom:".concat(Craft.uuid()),sortOptions:t,defaultSort:[t[0].attr,t[1].defaultDir],tableAttributes:[],availableTableAttributes:[]}),e.focusLabelInput()})),l=$("<ul/>").append($("<li/>").append(r)).appendTo(this.$addSourceMenu);t.conditionBuilderHtml&&$("<li/>").append(o).appendTo(l),Craft.useMobileStyles()&&this.buildSidebarToggleView(),this.addListener(Garnish.$win,"resize",this.updateSidebarView),this.addSourceMenu=new Garnish.DisclosureMenu(n)},focusLabelInput:function(){this.selectedSource.$labelInput.trigger("focus")},getSourceName:function(){return this.selectedSource?this.selectedSource.sourceData.label:this.sources[0].sourceData.label},updateSidebarView:function(){Craft.useMobileStyles()?this.$sidebarToggleBtn||this.buildSidebarToggleView():this.$sidebarToggleBtn&&this.resetView()},resetView:function(){this.$sourceSettingsHeader&&this.$sourceSettingsHeader.remove(),this.$sourcesHeader&&this.$sourcesHeader.remove(),this.$sidebarToggleBtn=null,this.$container.removeClass("sidebar-hidden")},updateHeading:function(){this.$sourcesHeading&&this.$sourcesHeading.text(this.getSourceName())},buildSidebarToggleView:function(){var t=this;this.$sourcesHeader=$('<div class="sources-header"/>').addClass("sidebar-header").prependTo(this.$sourcesContainer),this.$sidebarCloseBtn=Craft.ui.createButton({class:"nav-close close-btn"}).attr("aria-label",Craft.t("app","Close")).removeClass("btn").appendTo(this.$sourcesHeader),this.$sourcesHeading=$('<h1 class="main-heading"/>').text(this.getSourceName()),this.$sourceSettingsHeader=$('<div class="source-settings-header"/>').addClass("main-header").append(this.$sourcesHeading).prependTo(this.$sourceSettingsContainer),this.$sidebarToggleBtn=Craft.ui.createButton({toggle:!0,controls:"modal-sidebar",class:"nav-toggle"}).removeClass("btn").attr("aria-label",Craft.t("app","Show sidebar")).appendTo(this.$sourceSettingsHeader),this.closeSidebar(),this.addListener(this.$sidebarToggleBtn,"click",(function(){t.toggleSidebar()})),this.addListener(this.$sidebarCloseBtn,"click",(function(){t.toggleSidebar(),t.$sidebarToggleBtn.trigger("focus")}))},toggleSidebar:function(){this.sidebarIsOpen()?this.closeSidebar():this.openSidebar()},openSidebar:function(){var t=this;this.$container.removeClass("sidebar-hidden"),this.$sidebarToggleBtn.attr("aria-expanded","true"),this.$sidebar.find(":focusable").first().focus(),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.closeSidebar(),Garnish.focusIsInside(t.$sidebar)&&t.$sidebarToggleBtn.focus()}))},closeSidebar:function(){this.$container.addClass("sidebar-hidden"),this.$sidebarToggleBtn&&this.$sidebarToggleBtn.attr("aria-expanded","false"),Garnish.uiLayerManager.currentLayer.$container.hasClass("cs-sidebar")&&Garnish.uiLayerManager.removeLayer()},sidebarIsOpen:function(){return"true"===this.$sidebarToggleBtn.attr("aria-expanded")},addSource:function(t,e){var i,s=$('<div class="customize-sources-item"/>').appendTo(this.$sourcesContainer),n=$('<div class="label customize-sources-item__btn"/>').attr({tabindex:"0",role:"button"}).appendTo(s),a=$('<input type="hidden"/>').appendTo(s);return $('<a class="move icon customize-sources-item__move" title="'.concat(Craft.t("app","Reorder"),'" role="button"></a>')).appendTo(s),"heading"===t.type?(s.addClass("heading"),a.attr("name","sourceOrder[][heading]"),(i=new Craft.CustomizeSourcesModal.Heading(this,s,n,a,t,e)).updateItemLabel(t.heading)):(a.attr("name","sourceOrder[][key]").val(t.key),(i="native"===t.type?new Craft.CustomizeSourcesModal.Source(this,s,n,a,t,e):new Craft.CustomizeSourcesModal.CustomSource(this,s,n,a,t,e)).updateItemLabel(t.label),t.key===this.elementIndex.rootSourceKey&&i.select()),this.sourceSort.addItems(s),i},save:function(t){var e=this;t&&t.preventDefault(),this.$saveBtn.hasClass("disabled")||this.$saveBtn.hasClass("loading")||(this.$saveBtn.addClass("loading"),Craft.sendActionRequest("POST","element-index-settings/save-customize-sources-modal-settings",{data:this.$container.serialize()+"&elementType=".concat(this.elementIndex.elementType)}).then((function(t){var i=t.data,s=null;e.selectedSource&&e.selectedSource.sourceData.key&&!i.disabledSourceKeys.includes(e.selectedSource.sourceData.key)?s=e.selectedSource.sourceData.key:e.elementIndex.sourceKey||(s=e.elementIndex.$visibleSources.first().data("key")),s&&e.elementIndex.selectSourceByKey(s),window.location.reload()})).catch((function(){Craft.cp.displayError(Craft.t("app","A server error occurred."))})).finally((function(){e.$saveBtn.removeClass("loading")})))},appendIndexSourceItem:function(t,e){if(e){var i=t.hasClass("heading");if(e.hasClass("heading")&&!i)t.appendTo(e.children("ul"));else{if(i){var s=e.parentsUntil(this.$elementIndexSourcesContainer,"li").last();s.length&&(e=s)}t.insertAfter(e)}}else t.prependTo(this.$elementIndexSourcesContainer)},destroy:function(){for(var t=0;t<this.sources.length;t++)this.sources[t].destroy();this.addSourceMenu&&(this.addSourceMenu.destroy(),this.$addSourceMenu.remove()),delete this.sources,this.base()}}),Craft.CustomizeSourcesModal.BaseSource=Garnish.Base.extend({modal:null,$item:null,$itemLabel:null,$itemInput:null,$settingsContainer:null,sourceData:null,isNew:null,init:function(t,e,i,s,n,a){var r=this;this.modal=t,this.$item=e,this.$itemLabel=i,this.$itemInput=s,this.sourceData=n,this.isNew=a,this.$item.data("source",this),this.addListener(this.$itemLabel,"click","select"),this.addListener(this.$itemLabel,"keypress",(function(t){return Garnish.handleActivatingKeypress(t,r.select.bind(r))}))},isHeading:function(){return!1},isNative:function(){return!1},isSelected:function(){return this.modal.selectedSource===this},select:function(){this.isSelected()||(this.modal.selectedSource&&this.modal.selectedSource.deselect(),this.$item.addClass("sel"),this.$itemLabel.attr({"aria-current":"true"}),this.modal.selectedSource=this,this.modal.updateHeading(),this.$settingsContainer?this.$settingsContainer.removeClass("hidden"):(this.$settingsContainer=$("<div/>").appendTo(this.modal.$sourceSettingsContainer),this.createSettings(this.$settingsContainer)),this.modal.$sourceSettingsContainer.scrollTop(0))},createSettings:function(){},getIndexSourceItem:function(){},deselect:function(){this.$item.removeClass("sel"),this.$itemLabel.attr({"aria-current":"false"}),this.modal.selectedSource=null,this.$settingsContainer.addClass("hidden")},updateItemLabel:function(t){t?this.$itemLabel.text(t):this.$itemLabel.html("&nbsp;")},destroy:function(){this.modal.sourceSort.removeItems(this.$item),this.modal.sources.splice($.inArray(this,this.modal.sources),1),this.isSelected()&&(this.deselect(),this.modal.sources.length&&this.modal.sources[0].select(),Garnish.setFocusWithin(this.modal.$sourceSettingsContainer)),this.$item.data("source",null),this.$item.remove(),this.$settingsContainer&&this.$settingsContainer.remove(),this.base()}}),Craft.CustomizeSourcesModal.Source=Craft.CustomizeSourcesModal.BaseSource.extend({$sortAttributeSelect:null,$sortDirectionPicker:null,$sortDirectionInput:null,sortDirectionListbox:null,isNative:function(){return!0},createSettings:function(t){Craft.ui.createLightswitchField({label:Craft.t("app","Enabled"),name:"sources[".concat(this.sourceData.key,"][enabled]"),on:!this.sourceData.disabled}).appendTo(t),this.createSortField(t),this.createTableAttributesField(t)},createSortField:function(t){var e=this,i=$('<div class="flex"/>'),s=Craft.ui.createSelect({name:"sources[".concat(this.sourceData.key,"][defaultSort][0]"),options:this.sourceData.sortOptions.map((function(t){return{label:t.label,value:t.attr}})),value:this.sourceData.defaultSort[0]}).addClass("fullwidth").appendTo($("<div/>").appendTo(i));this.$sortAttributeSelect=s.children("select").attr("aria-label",Craft.t("app","Sort attribute")),this.$sortDirectionPicker=$("<section/>",{class:"btngroup btngroup--exclusive","aria-label":Craft.t("app","Sort direction")}).append($("<button/>",{type:"button",class:"btn",title:Craft.t("app","Sort ascending"),"aria-label":Craft.t("app","Sort ascending"),"aria-pressed":"false","data-icon":"asc","data-dir":"asc"})).append($("<button/>",{type:"button",class:"btn",title:Craft.t("app","Sort descending"),"aria-label":Craft.t("app","Sort descending"),"aria-pressed":"false","data-icon":"desc","data-dir":"desc"})).appendTo(i),this.$sortDirectionInput=$("<input/>",{type:"hidden",name:"sources[".concat(this.sourceData.key,"][defaultSort][1]")}).appendTo(i),this.sortDirectionListbox=new Craft.Listbox(this.$sortDirectionPicker,{onChange:function(t){e.$sortDirectionInput.val(t.data("dir"))}}),this.$sortAttributeSelect.on("change",(function(){e.handleSortAttributeChange()})),this.handleSortAttributeChange(!0),Craft.ui.createField(i,{label:Craft.t("app","Default Sort"),fieldset:!0}).appendTo(t).addClass("sort-field")},handleSortAttributeChange:function(t){var e=this.$sortAttributeSelect.val();if("structure"===e)this.sortDirectionListbox.select(0),this.sortDirectionListbox.disable(),this.$sortDirectionPicker.addClass("disabled");else{this.sortDirectionListbox.enable(),this.$sortDirectionPicker.removeClass("disabled");var i=t?this.sourceData.defaultSort[1]:this.sourceData.sortOptions.find((function(t){return t.attr===e})).defaultDir;this.sortDirectionListbox.select("asc"===i?0:1)}},createTableAttributesField:function(t){var i=this.availableTableAttributes();if(this.sourceData.tableAttributes.length||i.length){var s=$("<div/>"),n=[];$('<input type="hidden" name="sources['.concat(this.sourceData.key,'][tableAttributes][]" value=""/>')).appendTo(s);for(var a=0;a<this.sourceData.tableAttributes.length;a++){var r=e(this.sourceData.tableAttributes[a],2),o=r[0],l=r[1];s.append(this.createTableColumnOption(o,l,!0)),n.push(o)}for(var h=0;h<i.length;h++){var d=e(i[h],2),c=d[0],u=d[1];Craft.inArray(c,n)||s.append(this.createTableColumnOption(c,u,!1))}new Garnish.DragSort(s.children(),{handle:".move",axis:"y"}),Craft.ui.createField(s,{label:Craft.t("app","Default Table Columns"),instructions:Craft.t("app","Choose which table columns should be visible for this source by default.")}).appendTo(t)}},availableTableAttributes:function(){var e=this.modal.availableTableAttributes.slice(0);return e.push.apply(e,t(this.sourceData.availableTableAttributes)),e},createTableColumnOption:function(t,e,i){return $('<div class="customize-sources-table-column"/>').append('<div class="icon move"/>').append(Craft.ui.createCheckbox({label:Craft.escapeHtml(e),name:"sources[".concat(this.sourceData.key,"][tableAttributes][]"),value:t,checked:i}))},getIndexSourceItem:function(){var t=this.modal.elementIndex.getSourceByKey(this.sourceData.key);if(t)return t.closest("li")}}),Craft.CustomizeSourcesModal.CustomSource=Craft.CustomizeSourcesModal.Source.extend({$labelInput:null,createSettings:function(t){var e=this,i=Craft.ui.createTextField({label:Craft.t("app","Label"),name:"sources[".concat(this.sourceData.key,"][label]"),value:this.sourceData.label}).appendTo(t);this.$labelInput=i.find(".text");var s="condition".concat(Math.floor(1e6*Math.random())),n=function(t){return t.replace(/__ID__/g,s).replace(/__SOURCE_KEY__(?=-)/g,Craft.formatInputId(e.sourceData.key)).replace(/__SOURCE_KEY__/g,e.sourceData.key)},a=this.sourceData.conditionBuilderHtml||n(this.modal.conditionBuilderHtml),r=this.sourceData.conditionBuilderJs||n(this.modal.conditionBuilderJs);Craft.ui.createField($("<div/>").append(a),{id:"criteria",label:Craft.t("app","{type} Criteria",{type:this.modal.elementTypeName})}).appendTo(t),Craft.appendBodyHtml(r),this.createSortField(t),this.createTableAttributesField(t),this.modal.userGroups.length&&Craft.ui.createCheckboxSelectField({label:Craft.t("app","User Groups"),instructions:Craft.t("app","Choose which user groups should have access to this source."),name:"sources[".concat(this.sourceData.key,"][userGroups]"),options:this.modal.userGroups,values:this.sourceData.userGroups||"*",showAllOption:!0}).appendTo(t),t.append("<hr/>"),this.$deleteBtn=$('<a class="error delete"/>').attr({role:"button",tabindex:"0"}).text(Craft.t("app","Delete custom source")).appendTo(t),this.addListener(this.$labelInput,"input","handleLabelInputChange"),this.addListener(this.$deleteBtn,"click","destroy"),this.addListener(this.$deleteBtn,"keypress",(function(t){Garnish.handleActivatingKeypress(t,e.destroy.bind(e))}))},availableTableAttributes:function(){var e=this.base();return this.isNew&&e.push.apply(e,t(this.modal.customFieldAttributes)),e},handleLabelInputChange:function(){this.updateItemLabel(this.$labelInput.val())},getIndexSourceItem:function(){var t,e=this.base();if(e?t=e.find(".label"):(t=$("<span/>",{class:"label"}),e=$("<li/>").append($("<a/>",{"data-key":this.sourceData.key}).append(t))),this.$labelInput){var i=Craft.trim(this.$labelInput.val());""===i&&(i=Craft.t("app","(blank)")),t.text(i)}return e}}),Craft.CustomizeSourcesModal.Heading=Craft.CustomizeSourcesModal.BaseSource.extend({$labelInput:null,$deleteBtn:null,isHeading:function(){return!0},createSettings:function(t){var e=this,i=Craft.ui.createTextField({label:Craft.t("app","Heading"),instructions:Craft.t("app","This can be left blank if you just want an unlabeled separator."),value:this.sourceData.heading||""}).appendTo(t);this.$labelInput=i.find(".text"),t.append("<hr/>"),this.$deleteBtn=$('<a class="error delete"/>').text(Craft.t("app","Delete heading")).attr({role:"button",tabindex:"0"}).appendTo(t),this.addListener(this.$labelInput,"input","handleLabelInputChange"),this.addListener(this.$deleteBtn,"click","destroy"),this.addListener(this.$deleteBtn,"keypress",(function(t){Garnish.handleActivatingKeypress(t,e.destroy.bind(e))}))},handleLabelInputChange:function(){this.updateItemLabel(this.$labelInput.val())},updateItemLabel:function(t){this.$itemLabel.html((t?Craft.escapeHtml(t):"<em>".concat(Craft.t("app","(blank)"),"</em>"))+"&nbsp;"),this.$itemInput.val(t)},getIndexSourceItem:function(){var t=(this.$labelInput?this.$labelInput.val():null)||this.sourceData.heading||"";return $('<li class="heading"/>').append($("<span/>").text(t)).append("<ul/>")}})},1519:function(){Craft.DataTableSorter=Garnish.DragSort.extend({$table:null,init:function(t,e){this.$table=$(t);var i=this.$table.children("tbody").children(":not(.filler)");(e=$.extend({},Craft.DataTableSorter.defaults,e)).container=this.$table.children("tbody"),e.helper=this.getHelper.bind(this),e.caboose="<tr/>",e.axis=Garnish.Y_AXIS,e.magnetStrength=4,e.helperLagBase=1.5,this.base(i,e)},getHelper:function(t){var e=$('<div class="'+this.settings.helperClass+'"/>').appendTo(Garnish.$bod),i=$("<table/>").appendTo(e),s=$("<tbody/>").appendTo(i);t.appendTo(s),i.width(this.$table.width()),i.prop("className",this.$table.prop("className"));for(var n=this.$table.find("tr:first").children(),a=t.children(),r=0;r<a.length;r++)$(a[r]).width($(n[r]).width());return e}},{defaults:{handle:".move",helperClass:"datatablesorthelper"}})},501:function(){Craft.DeleteUserModal=Garnish.Modal.extend({id:null,userId:null,$deleteActionRadios:null,$deleteSubmitBtn:null,userSelect:null,_deleting:!1,init:function(t,e){var i=this;this.id=Math.floor(1e9*Math.random()),this.userId=t,e=$.extend(Craft.DeleteUserModal.defaults,e);var s,n=$('<form class="modal fitted deleteusermodal" method="post" accept-charset="UTF-8">'+Craft.getCsrfInput()+'<input type="hidden" name="action" value="users/delete-user"/>'+(Garnish.isArray(this.userId)?"":'<input type="hidden" name="userId" value="'+this.userId+'"/>')+(e.redirect?'<input type="hidden" name="redirect" value="'+e.redirect+'"/>':"")+"</form>").appendTo(Garnish.$bod),a=$('<div class="body"><div class="content-summary"><p>'+Craft.t("app","What do you want to do with their content?")+'</p><ul class="bullets"></ul></div><div class="options"><label><input type="radio" name="contentAction" value="transfer"/> '+Craft.t("app","Transfer it to:")+'</label><div id="transferselect'+this.id+'" class="elementselect"><div class="elements"></div><button type="button" class="btn add icon dashed">'+Craft.t("app","Choose a user")+'</button></div></div><div><label class="error"><input type="radio" name="contentAction" value="delete"/> '+Craft.t("app","Delete their content")+"</label></div></div>").appendTo(n),r=$('<div class="buttons right"/>').appendTo(a),o=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(r);if(e.contentSummary.length)for(var l=0;l<e.contentSummary.length;l++)a.find("ul").append($("<li/>",{text:e.contentSummary[l]}));else a.find("ul").remove();if(this.$deleteActionRadios=a.find("input[type=radio]"),this.$deleteSubmitBtn=Craft.ui.createSubmitButton({class:"disabled",label:this._submitBtnLabel(!1),spinner:!0}).appendTo(r),Garnish.isArray(this.userId)){s=["and"];for(var h=0;h<this.userId.length;h++)s.push("not "+this.userId[h])}else s="not "+this.userId;this.userSelect=new Craft.BaseElementSelectInput({id:"transferselect"+this.id,name:"transferContentTo",elementType:"craft\\elements\\User",criteria:{id:s},limit:1,modalSettings:{closeOtherModals:!1},onSelectElements:function(){i.updateSizeAndPosition(),i.$deleteActionRadios.first().prop("checked")?i.validateDeleteInputs():i.$deleteActionRadios.first().trigger("click")},onRemoveElements:this.validateDeleteInputs.bind(this),selectable:!1,editable:!1}),this.addListener(o,"click","hide"),this.addListener(this.$deleteActionRadios,"change","validateDeleteInputs"),this.addListener(n,"submit","handleSubmit"),this.base(n,e)},_submitBtnLabel:function(t){var e=t?"Delete {num, plural, =1{user} other{users}} and content":"Delete {num, plural, =1{user} other{users}}";return Craft.t("app",e,{num:Garnish.isArray(this.userId)?this.userId.length:1})},validateDeleteInputs:function(){var t=!1;return this.$deleteActionRadios.eq(1).prop("checked")?(t=!0,this.$deleteSubmitBtn.find(".label").text(this._submitBtnLabel(!0))):(this.$deleteSubmitBtn.find(".label").text(this._submitBtnLabel(!1)),this.$deleteActionRadios.eq(0).prop("checked")&&(t=!!this.userSelect.totalSelected)),this.updateSizeAndPosition(),t?this.$deleteSubmitBtn.removeClass("disabled"):this.$deleteSubmitBtn.addClass("disabled"),t},handleSubmit:function(t){if(!this._deleting&&this.validateDeleteInputs()){this.$deleteSubmitBtn.addClass("loading"),this.disable(),this.userSelect.disable(),this._deleting=!0;try{!1===this.settings.onSubmit()&&t.preventDefault()}catch(e){throw t.preventDefault(),this.$deleteSubmitBtn.removeClass("loading"),e}}else t.preventDefault()},onFadeIn:function(){Garnish.isMobileBrowser(!0)||this.$deleteActionRadios.first().trigger("focus"),this.base()}},{defaults:{contentSummary:[],onSubmit:$.noop,redirect:null}})},2318:function(){Craft.DynamicGenerator=Craft.BaseInputGenerator.extend({callback:$.noop,init:function(t,e,i){this.callback=i,this.base(t,e)},generateTargetValue:function(t){return this.callback(t)}})},4755:function(){Craft.EditableTable=Garnish.Base.extend({initialized:!1,id:null,baseName:null,columns:null,sorter:null,biggestId:-1,$table:null,$tbody:null,$addRowBtn:null,$tableParent:null,$statusMessage:null,rowCount:0,hasMaxRows:!1,hasMinRows:!1,radioCheckboxes:null,init:function(t,e,i,s){var n=this;if(this.id=t,this.baseName=e,this.columns=i,this.setSettings(s,Craft.EditableTable.defaults),this.radioCheckboxes={},this.$table=$("#"+t),this.$tbody=this.$table.children("tbody"),this.$tableParent=this.$table.parent(),this.$statusMessage=this.$tableParent.find("[data-status-message]"),this.rowCount=this.$tbody.find("tr").length,this.$table.data("editable-table")&&(console.warn("Double-instantiating an editable table on an element"),this.$table.data("editable-table").destroy()),this.$table.data("editable-table",this),this.sorter=new Craft.DataTableSorter(this.$table,{helperClass:"editabletablesorthelper",copyDraggeeInputValuesToHelper:!0,onSortChange:function(){n.updateAllRows()}}),this.isVisible()?this.initialize():window.setTimeout(this.initializeIfVisible.bind(this),500),this.settings.minRows&&this.rowCount<this.settings.minRows)for(var a=this.rowCount;a<this.settings.minRows;a++)this.addRow()},isVisible:function(){return this.$table.parent().height()>0},initialize:function(){if(this.initialized)return!1;this.initialized=!0,this.removeListener(Garnish.$win,"resize");for(var t=this.$tbody.children(),e=0;e<t.length;e++)this.createRowObj(t[e]);var i=this.$table.parent(".input");return i.length&&this.$table.width()>i.width()&&i.css("overflow-x","auto"),this.$addRowBtn=this.$table.next(".add"),this.updateAddRowButton(),this.addListener(this.$addRowBtn,"activate","addRow"),!0},initializeIfVisible:function(){this.removeListener(Garnish.$win,"resize"),this.isVisible()?this.initialize():this.addListener(Garnish.$win,"resize","initializeIfVisible")},updateAddRowButton:function(){this.canAddRow()?(this.$addRowBtn.css("opacity","1"),this.$addRowBtn.css("pointer-events","auto"),this.$addRowBtn.attr("aria-disabled","false")):(this.$addRowBtn.css("opacity","0.2"),this.$addRowBtn.css("pointer-events","none"),this.$addRowBtn.attr("aria-disabled","true"))},updateAllRows:function(){if(!this.settings.staticRows)for(var t=this.$table.find("> tbody > tr"),e=0;e<t.length;e++)this.updateRow(t.eq(e))},updateRow:function(t){if(!this.settings.staticRows){var e=t.find("button.delete");e.length&&(e.attr("aria-label",Craft.t("app","Delete row {index}",{index:t.index()+1})),this.canDeleteRow()?e.removeAttr("disabled").removeClass("disabled"):e.attr("disabled","disabled").addClass("disabled"))}},updateDeleteRowButton:function(t){this.updateRow(this.$table.find('tr[data-id="'.concat(t,'"]')))},updateStatusMessage:function(){var t,e=this;this.$statusMessage.empty(),t=this.canAddRow()?Craft.t("app","Row could not be deleted. Minimum number of rows reached."):Craft.t("app","Row could not be added. Maximum number of rows reached."),setTimeout((function(){e.$statusMessage.text(t)}),250)},canDeleteRow:function(){return!!this.settings.allowDelete&&this.rowCount>this.settings.minRows},deleteRow:function(t){this.canDeleteRow()?(this.sorter.removeItems(t.$tr),t.$tr.remove(),this.rowCount--,this.updateAllRows(),this.updateAddRowButton(),0===this.rowCount?(this.$table.addClass("hidden"),this.$addRowBtn.trigger("focus")):this.$tbody.find(":focusable").last().trigger("focus"),this.settings.onDeleteRow(t.$tr),t.destroy()):this.updateStatusMessage()},canAddRow:function(){return!!this.settings.allowAdd&&(!this.settings.maxRows||this.rowCount<this.settings.maxRows)},addRow:function(t,e){if(this.canAddRow()){var i=this.settings.rowIdPrefix+(this.biggestId+1),s=this.createRow(i,this.columns,this.baseName,$.extend({},this.settings.defaultValues));e?s.prependTo(this.$tbody):s.appendTo(this.$tbody);var n=this.createRowObj(s);return this.sorter.addItems(s),!1!==t&&s.find("input:visible,textarea:visible,select:visible").first().trigger("focus"),this.rowCount++,this.updateAllRows(),this.updateAddRowButton(),this.$table.removeClass("hidden"),this.settings.onAddRow(s),n}this.updateStatusMessage()},createRow:function(t,e,i,s){return Craft.EditableTable.createRow(t,e,i,s,this.settings.allowReorder,this.settings.allowDelete)},createRowObj:function(t){return new Craft.EditableTable.Row(this,t)},focusOnPrevRow:function(t,e,i){var s,n=t.prev("tr");if((s=n.length?n.data("editable-table-row"):this.addRow(!1,!0))&&s.$tds[e])if($(s.$tds[e]).hasClass("disabled"))n&&this.focusOnPrevRow(n,e,i);else{var a=$("textarea,input.text",s.$tds[e]);a.length&&($(i).trigger("blur"),a.trigger("focus"))}},focusOnNextRow:function(t,e,i){var s,n=t.next("tr");if((s=n.length?n.data("editable-table-row"):this.addRow(!1))&&s.$tds[e])if($(s.$tds[e]).hasClass("disabled"))n&&this.focusOnNextRow(n,e,i);else{var a=$("textarea,input.text",s.$tds[e]);a.length&&($(i).trigger("blur"),a.trigger("focus"))}},importData:function(t,e,i){for(var s=t.split(/\r?\n|\r/),n=0;n<s.length;n++){for(var a=s[n].split("\t"),r=0;r<a.length;r++){var o=a[r];e.$tds.eq(i+r).find("textarea,input[type!=hidden]").val(o).trigger("input")}var l=e.$tr.next("tr");e=l.length?l.data("editable-table-row"):this.addRow(!1)}},destroy:function(){this.$table.removeData("editable-table"),this.base()}},{textualColTypes:["autosuggest","color","date","email","multiline","number","singleline","template","time","url"],defaults:{rowIdPrefix:"",defaultValues:{},allowAdd:!1,allowReorder:!1,allowDelete:!1,minRows:null,maxRows:null,onAddRow:$.noop,onDeleteRow:$.noop},createRow:function(t,e,i,s,n,a){var r=$("<tr/>",{"data-id":t});for(var o in e)if(e.hasOwnProperty(o)){var l,h=e[o],d=void 0!==s[o]?s[o]:"";if("heading"===h.type)l=$("<th/>",{scope:"row",class:h.class,html:d});else{var c=i+"["+t+"]["+o+"]";switch(l=$("<td/>",{class:"".concat(h.class," ").concat(h.type,"-cell"),width:h.width}),Craft.inArray(h.type,Craft.EditableTable.textualColTypes)&&l.addClass("textual"),h.code&&l.addClass("code"),h.type){case"checkbox":$('<div class="checkbox-wrapper"/>').append(Craft.ui.createCheckbox({name:c,value:h.value||"1",checked:!!d})).appendTo(l);break;case"color":Craft.ui.createColorInput({name:c,value:d,small:!0}).appendTo(l);break;case"date":Craft.ui.createDateInput({name:c,value:d}).appendTo(l);break;case"lightswitch":Craft.ui.createLightswitch({name:c,value:h.value||"1",on:!!d,small:!0}).appendTo(l);break;case"select":Craft.ui.createSelect({name:c,options:h.options,value:d||function(){for(var t in h.options)if(h.options.hasOwnProperty(t)&&h.options[t].default)return void 0!==h.options[t].value?h.options[t].value:t;return null}(),class:"small"}).appendTo(l);break;case"time":Craft.ui.createTimeInput({name:c,value:d}).appendTo(l);break;case"email":case"url":Craft.ui.createTextInput({name:c,value:d,type:h.type,placeholder:h.placeholder||null}).appendTo(l);break;default:$("<textarea/>",{name:c,rows:h.rows||1,val:d,placeholder:h.placeholder}).appendTo(l)}}l.appendTo(r)}return n&&$("<td/>",{class:"thin action"}).append($("<a/>",{class:"move icon",title:Craft.t("app","Reorder"),role:"button",type:"button"})).appendTo(r),a&&$("<td/>",{class:"thin action"}).append($("<button/>",{class:"delete icon",title:Craft.t("app","Delete"),type:"button"})).appendTo(r),r}}),Craft.EditableTable.Row=Garnish.Base.extend({table:null,id:null,niceTexts:null,$tr:null,$tds:null,tds:null,$textareas:null,$deleteBtn:null,init:function(t,e){this.table=t,this.$tr=$(e),this.$tds=this.$tr.children(),this.tds=[],this.id=this.$tr.attr("data-id"),this.$tr.data("editable-table-row",this);var i=parseInt(this.id.substring(this.table.settings.rowIdPrefix.length));i>this.table.biggestId&&(this.table.biggestId=i),this.$textareas=$(),this.niceTexts=[];var s,n,a,r,o,l={},h=0;for(s in this.table.columns)this.table.columns.hasOwnProperty(s)&&(n=this.table.columns[s],a=this.tds[s]=this.$tds[h],Craft.inArray(n.type,Craft.EditableTable.textualColTypes)?(r=$("textarea",a),this.$textareas=this.$textareas.add(r),this.addListener(r,"focus","onTextareaFocus"),this.addListener(r,"mousedown","ignoreNextTextareaFocus"),this.niceTexts.push(new Garnish.NiceText(r,{onHeightChange:this.onTextareaHeightChange.bind(this)})),this.addListener(r,"keypress",{tdIndex:h,type:n.type},"handleKeypress"),this.addListener(r,"input",{type:n.type},"validateValue"),r.trigger("input"),"multiline"!==n.type&&this.addListener(r,"paste",{tdIndex:h,type:n.type},"handlePaste"),l[s]=r):"checkbox"===n.type&&(o=$('input[type="checkbox"]',a),n.radioMode&&(void 0===this.table.radioCheckboxes[s]&&(this.table.radioCheckboxes[s]=[]),this.table.radioCheckboxes[s].push(o[0]),this.addListener(o,"change",{colId:s},"onRadioCheckboxChange")),n.toggle&&this.addListener(o,"change",{colId:s},(function(t){this.applyToggleCheckbox(t.data.colId)}))),$(a).hasClass("disabled")||this.addListener(a,"click",{td:a},(function(t){t.target===t.data.td&&$(t.data.td).find("textarea,input,select,.lightswitch").focus()})),h++);for(s in this.onTextareaHeightChange(),this.table.columns)this.table.columns.hasOwnProperty(s)&&"checkbox"===(n=this.table.columns[s]).type&&n.toggle&&this.applyToggleCheckbox(s);for(s in this.table.columns)this.table.columns.hasOwnProperty(s)&&(n=this.table.columns[s]).autopopulate&&void 0!==l[n.autopopulate]&&!l[s].val()&&new Craft.HandleGenerator(l[s],l[n.autopopulate],{allowNonAlphaStart:!0});var d=this.$tr.children().last().find(".delete");this.addListener(d,"click","deleteRow");var c=this.$tr.find("input,textarea,select,.lightswitch");this.addListener(c,"focus",(function(t){$(t.currentTarget).closest("td:not(.disabled)").addClass("focus")})),this.addListener(c,"blur",(function(t){$(t.currentTarget).closest("td").removeClass("focus")}))},onTextareaFocus:function(t){this.onTextareaHeightChange();var e=$(t.currentTarget);e.data("ignoreNextFocus")?e.data("ignoreNextFocus",!1):window.setTimeout((function(){Craft.selectFullValue(e)}),0)},onRadioCheckboxChange:function(t){if(t.currentTarget.checked)for(var e=0;e<this.table.radioCheckboxes[t.data.colId].length;e++){var i=this.table.radioCheckboxes[t.data.colId][e];i.checked=i===t.currentTarget}},applyToggleCheckbox:function(t){for(var e,i,s=this.table.columns[t],n=$('input[type="checkbox"]',this.tds[t]).prop("checked"),a=0;a<s.toggle.length;a++)e=s.toggle[a],this.table.colum,(i="!"===e[0])&&(e=e.substring(1)),n&&!i||!n&&i?$(this.tds[e]).removeClass("disabled").find("textarea, input").prop("disabled",!1):$(this.tds[e]).addClass("disabled").find("textarea, input").prop("disabled",!0)},ignoreNextTextareaFocus:function(t){$.data(t.currentTarget,"ignoreNextFocus",!0)},handleKeypress:function(t){var e=t.keyCode?t.keyCode:t.charCode,i=Garnish.isCtrlKeyPressed(t);if(e===Garnish.RETURN_KEY&&("multiline"!==t.data.type||i))return t.preventDefault(),void(t.shiftKey?this.table.focusOnPrevRow(this.$tr,t.data.tdIndex,t.currentTarget):this.table.focusOnNextRow(this.$tr,t.data.tdIndex,t.currentTarget))},handlePaste:function(t){var e=Craft.trim(t.originalEvent.clipboardData.getData("Text")," \n\r");e.match(/[\t\r\n]/)&&(t.preventDefault(),this.table.importData(e,this,t.data.tdIndex))},validateValue:function(t){if("multiline"!==t.data.type)if("number"!==t.data.type){var e=t.currentTarget.value.replace(/[\r\n]/g,"");e!==t.currentTarget.value&&(t.currentTarget.value=e)}else Craft.filterNumberInputVal(t.currentTarget)},onTextareaHeightChange:function(){for(var t=-1,e=0;e<this.niceTexts.length;e++)this.niceTexts[e].height>t&&(t=this.niceTexts[e].height);this.$textareas.css("min-height",t);var i=this.$textareas.filter(":visible").first().parent().height();i>t&&this.$textareas.css("min-height",i)},deleteRow:function(){this.table.deleteRow(this)}},{numericKeyCodes:[9,8,37,38,39,40,45,91,46,190,48,49,50,51,52,53,54,55,56,57]})},8468:function(){Craft.ElementActionTrigger=Garnish.Base.extend({maxLevels:null,newChildUrl:null,$trigger:null,$selectedItems:null,triggerEnabled:!0,init:function(t){$.isPlainObject(t)||(t={}),void 0!==t.batch&&(t.bulk=t.batch,delete t.batch),Object.defineProperty(t,"batch",{get:function(){return this.bulk},set:function(t){this.bulk=t}}),this.setSettings(t,Craft.ElementActionTrigger.defaults),this.$trigger=$("#"+t.type.replace(/[\[\]\\]+/g,"-")+"-actiontrigger"),this.settings.activate&&(this.$trigger.data("custom-handler",!0),"FORM"===this.$trigger.prop("nodeName")?this.addListener(this.$trigger,"submit","handleTriggerActivation"):this.addListener(this.$trigger,"activate","handleTriggerActivation")),this.updateTrigger(),Craft.elementIndex.on("selectionChange",this.updateTrigger.bind(this))},updateTrigger:function(){0!==Craft.elementIndex.getSelectedElements().length&&(this.validateSelection()?this.enableTrigger():this.disableTrigger())},validateSelection:function(){return this.$selectedItems=Craft.elementIndex.getSelectedElements(),!(!this.settings.bulk&&this.$selectedItems.length>1)&&(!this.settings.requireId||!this.$selectedItems.is('[data-id=""]'))&&("function"!=typeof this.settings.validateSelection||this.settings.validateSelection(this.$selectedItems))},enableTrigger:function(){this.triggerEnabled||(this.$trigger.removeClass("disabled").removeAttr("aria-disabled"),this.triggerEnabled=!0)},disableTrigger:function(){this.triggerEnabled&&(this.$trigger.addClass("disabled").attr("aria-disabled","true"),this.triggerEnabled=!1)},handleTriggerActivation:function(){this.triggerEnabled&&this.settings.activate(this.$selectedItems)}},{defaults:{type:null,bulk:!0,requireId:!0,validateSelection:null,activate:null}})},5049:function(){function t(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.ElementEditor=Garnish.Base.extend({isFullPage:null,$container:null,$tabContainer:null,$contentContainer:null,$revisionBtn:null,$revisionLabel:null,$spinner:null,$expandSiteStatusesBtn:null,$statusIcon:null,$previewBtn:null,$editMetaBtn:null,metaHud:null,$nameTextInput:null,$saveMetaBtn:null,$siteStatusPane:null,$globalLightswitch:null,$siteLightswitches:null,$additionalSiteField:null,siteIds:null,newSiteIds:null,enableAutosave:null,lastSerializedValue:null,listeningForChanges:!1,pauseLevel:0,timeout:null,cancelToken:null,ignoreFailedRequest:!1,queue:null,submittingForm:!1,duplicatedElements:null,failed:!1,httpStatus:null,httpError:null,openingPreview:!1,preview:null,activatedPreviewToken:!1,previewTokenQueue:null,previewLinks:null,scrollY:null,hiddenTipsStorageKey:"Craft-"+Craft.systemUid+".TipField.hiddenTips",get tipDismissBtn(){return this.$container.find(".tip-dismiss-btn")},get slideout(){return this.$container.data("slideout")},init:function(e,i){var s=this;if(this.$container=$(e),"FORM"!==this.$container.prop("tagName"))throw"Element editors may only be used with forms.";this.$container.data("elementEditor")&&(console.warn("Double-instantiating an element editor on an element."),this.$container.data("elementEditor").destroy()),this.$container.data("elementEditor",this),this.$container.attr("data-element-editor",""),this.setSettings(i,Craft.ElementEditor.defaults),this.isFullPage=this.$container[0]===Craft.cp.$primaryForm[0],this.isFullPage?(this.$tabContainer=$("#tabs"),this.$contentContainer=$("#content")):(this.$tabContainer=this.slideout.$tabContainer,this.$contentContainer=this.slideout.$content),this.queue=this._createQueue(),this.previewTokenQueue=this._createQueue(),this.duplicatedElements={},this.enableAutosave=Craft.autosaveDrafts,this.previewLinks=[],this.siteIds=Object.keys(this.settings.siteStatuses).map((function(t){return parseInt(t)})),this.$revisionBtn=this.$container.find(".context-btn"),this.$revisionLabel=this.$container.find(".revision-label"),this.$previewBtn=this.$container.find(".preview-btn");var n,a,r=this.isFullPage?$("#page-title"):this.slideout.$toolbar;if(this.$spinner=$("<div/>",{class:"revision-spinner spinner hidden",title:Craft.t("app","Saving")}).appendTo(r),this.$statusIcon=$("<div/>",{class:"revision-status ".concat(this.isFullPage?"invisible":"hidden")}).appendTo(r),this.$statusMessage=$("<div/>",{class:"revision-status-message visually-hidden","aria-live":"polite"}).appendTo(r),this.$expandSiteStatusesBtn=$(".expand-status-btn"),this.settings.canEditMultipleSites&&this.addListener(this.$expandSiteStatusesBtn,"click","expandSiteStatuses"),this.settings.previewTargets.length&&this.isFullPage){this.settings.enablePreview&&this.addListener(this.$previewBtn,"click","openPreview");var o=this.$container.find(".preview-btn-container");if(1===this.settings.previewTargets.length){var l=(n=this.settings.previewTargets,a=1,function(t){if(Array.isArray(t))return t}(n)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(n,a)||t(n,a)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())[0];this.createPreviewLink(l).addClass("view-btn btn").attr("aria-label",Craft.t("app","View")).appendTo(o)}else this.createShareMenu(o)}this.settings.revisionId||(this.$container.data("serializer",(function(){return s.serializeForm(!0)})),this.$container.data("initialSerializedValue",this.serializeForm(!0)),this.isFullPage&&this.addListener(this.$container,"submit","handleSubmit"),this.settings.isProvisionalDraft?this.initForProvisionalDraft():this.settings.draftId&&!this.settings.isUnpublishedDraft?this.initForDraft():this.settings.canSaveCanonical||this.addListener(this.$container,"submit.saveShortcut",(function(t){t.saveShortcut&&(t.preventDefault(),s.createDraft(),s.removeListener(s.$container,"submit.saveShortcut"))})),this.listenForChanges(),this.addListener(this.$statusIcon,"click",(function(){s.showStatusHud(s.$statusIcon)})),this.handleDismissibleTips(),this.isFullPage&&Craft.messageReceiver&&Craft.broadcaster.addEventListener("message",(function(t){if("saveDraft"===t.data.event&&t.data.canonicalId===s.settings.canonicalId&&(t.data.draftId===s.settings.draftId||t.data.isProvisionalDraft&&!s.settings.draftId)||"saveElement"===t.data.event&&t.data.id===s.settings.canonicalId&&!s.settings.draftId)Craft.setLocalStorage("scrollY",window.scrollY),window.location.reload();else if("deleteDraft"===t.data.event&&t.data.canonicalId===s.settings.canonicalId&&t.data.draftId===s.settings.draftId){var e=new URL(window.location.href);e.searchParams.delete("draftId"),e.href!==document.location.href?window.location.href=e:(Craft.setLocalStorage("scrollY",window.scrollY),window.location.reload())}})))},_createQueue:function(){var t=this,e=new Craft.Queue;return e.on("beforeRun",(function(){t.showSpinner()})),e.on("afterRun",(function(){t.hideSpinner()})),e},get namespace(){return this.isFullPage?null:this.slideout.namespace},namespaceInputName:function(t){return Craft.namespaceInputName(t,this.namespace)},namespaceId:function(t){return Craft.namespaceId(t,this.namespace)},listenForChanges:function(){var t=this;if(!(this.listeningForChanges||this.pauseLevel>0)&&this.enableAutosave&&this.settings.canCreateDrafts){this.listeningForChanges=!0;var e=this.isFullPage?Garnish.$bod:this.$container;this.addListener(e,"keypress,keyup,change,focus,blur,click,mousedown,mouseup",(function(e){$(e.target).is(t.statusIcons())||(clearTimeout(t.timeout),["keypress","keyup","change"].includes(e.type)?t.timeout=setTimeout(t.checkForm.bind(t),500):t.checkForm())}))}},stopListeningForChanges:function(){this.listeningForChanges&&(this.removeListener(Garnish.$bod,"keypress,keyup,change,focus,blur,click,mousedown,mouseup"),clearTimeout(this.timeout),this.listeningForChanges=!1)},pause:function(){this.pauseLevel++,this.stopListeningForChanges()},resume:function(){if(0===this.pauseLevel)throw"Craft.ElementEditor::resume() should only be called after pause().";this.pauseLevel--,0===this.pauseLevel&&this.enableAutosave&&(this.checkForm(),this.listenForChanges())},initForProvisionalDraft:function(){var t=this,e=this.$container.find(".discard-changes-btn");if(!e.length){var i,s,n;this.isFullPage?(i=$("#content").height(),s=Garnish.$win.scrollTop(),n=Craft.cp.$noticeContainer):n=this.$container.find(".so-notice");var a=$("<div/>",{class:"draft-notice"}).append($("<div/>",{class:"draft-icon","aria-hidden":"true","data-icon":"edit"})).append($("<p/>",{text:Craft.t("app","Showing your unsaved changes.")})).appendTo(n);if(e=$("<button/>",{type:"button",class:"discard-changes-btn btn",text:Craft.t("app","Discard")}).appendTo(a),this.isFullPage){var r=$("#content").height()-i;if(Garnish.$win.scrollTop(s+r),Garnish.$win.scrollTop()===s){Craft.cp.$contentContainer.css("pointer-events","none"),$("#content-header").css("min-height","auto");var o=n.height();n.css({height:o-r,overflow:"hidden"}).velocity({height:o},"fast",(function(){$("#content-header").css("min-height",""),n.css({height:"",overflow:""}),setTimeout((function(){Craft.cp.$contentContainer.css("pointer-events","")}),300)}))}}}this.addListener(e,"keypress,keyup,change,focus,blur,click,mousedown,mouseup",(function(t){t.stopPropagation()})),this.addListener(e,"click",(function(){confirm(Craft.t("app","Are you sure you want to discard your changes?"))&&t.queue.unshift((function(){return new Promise((function(e,i){t.isFullPage?Craft.submitForm(t.$container,{action:"elements/delete-draft",redirect:t.settings.hashedCpEditUrl,params:{draftId:t.settings.draftId,provisional:1}}):Craft.sendActionRequest("POST","elements/delete-draft",{data:{elementId:t.settings.canonicalId,draftId:t.settings.draftId,provisional:1}}).then((function(e){Craft.cp.displaySuccess(e.data.message),t.slideout.close()})).catch(i)}))}))}))},initForDraft:function(){var t=this;this.createEditMetaBtn(),this.settings.canSaveCanonical&&Garnish.uiLayerManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0,alt:!0},(function(){Craft.submitForm(t.$container,{action:"elements/apply-draft",redirect:t.settings.hashedCpEditUrl})}),0)},expandSiteStatuses:function(){var t=this;this.removeListener(this.$expandSiteStatusesBtn,"click"),this.$expandSiteStatusesBtn.velocity({opacity:0},"fast",(function(){t.$expandSiteStatusesBtn.remove()}));var e=this.$container.find(".enabled-for-site-".concat(this.settings.siteId,"-field"));if(this.$siteStatusPane=e.parent(),this.settings.revisionId)this._getOtherSupportedSites().forEach((function(e){return t._createSiteStatusField(e)}));else{e.addClass("nested");var i=Craft.ui.createLightswitchField({label:Craft.t("app","Enabled for all sites"),name:this.namespaceInputName("enabled")}).insertBefore(e);i.find("label").css("font-weight","bold"),this.$globalLightswitch=i.find(".lightswitch"),this.settings.revisionId||this._showField(i);var s=Object.values(this.settings.siteStatuses),n=s.includes(!0),a=s.includes(!1),r=n&&a?"-":n?"1":"",o=encodeURIComponent(this.namespaceInputName("enabledForSite[".concat(this.settings.siteId,"]")))+"="+(this.settings.enabledForSite?"1":"");this.$siteLightswitches=e.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this)),this._getOtherSupportedSites().forEach((function(e){return t._createSiteStatusField(e)}));for(var l=encodeURIComponent(this.namespaceInputName("enabled"))+"=".concat(r),h=0;h<this.$siteLightswitches.length;h++){var d=this.$siteLightswitches.eq(h).data("lightswitch").$input;l+="&"+encodeURIComponent(d.attr("name"))+"="+d.val()}this.$container.data("initialSerializedValue",this.$container.data("initialSerializedValue").replace(o,l)),this.lastSerializedValue&&(this.lastSerializedValue=this.lastSerializedValue.replace(o,l)),this.settings.additionalSites&&this.settings.additionalSites.length&&this.isFullPage&&this._createAddlSiteField(),this.$globalLightswitch.focus(),this.$globalLightswitch.on("change",this._updateSiteStatuses.bind(this)),this._updateGlobalStatus()}},_getOtherSupportedSites:function(){var t=this;return Craft.sites.filter((function(e){return e.id!=t.settings.siteId&&t.siteIds.includes(e.id)}))},_showField:function(t){var e=t.height();t.css({overflow:"hidden","min-height":"auto"}).height(0).velocity({height:e},"fast",(function(){t.css({overflow:"",height:"","min-height":""})}))},_removeField:function(t){t.css({overflow:"hidden","min-height":"auto"}).velocity({height:0},"fast",(function(){t.remove()}))},_updateGlobalStatus:function(){var t=!0,e=!0;this.$siteLightswitches.each((function(){if($(this).data("lightswitch").on?e=!1:t=!1,!t&&!e)return!1})),t?this.$globalLightswitch.data("lightswitch").turnOn(!0):e?this.$globalLightswitch.data("lightswitch").turnOff(!0):this.$globalLightswitch.data("lightswitch").turnIndeterminate(!0)},_updateSiteStatuses:function(){var t=this.$globalLightswitch.data("lightswitch").on;this.$siteLightswitches.each((function(){t?$(this).data("lightswitch").turnOn(!0):$(this).data("lightswitch").turnOff(!0)}))},_createSiteStatusField:function(t,e){var i=Craft.ui.createLightswitchField({fieldClass:"enabled-for-site-".concat(t.id,"-field"),label:t.name,name:this.namespaceInputName("enabledForSite[".concat(t.id,"]")),on:void 0!==e?e:!this.settings.siteStatuses.hasOwnProperty(t.id)||this.settings.siteStatuses[t.id],disabled:!!this.settings.revisionId});if(this.$additionalSiteField?i.insertBefore(this.$additionalSiteField):i.appendTo(this.$siteStatusPane),!this.settings.revisionId){i.addClass("nested");var s=i.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this));this.$siteLightswitches=this.$siteLightswitches.add(s)}return this._showField(i),i},_createAddlSiteField:function(){var i,s=this,n=Craft.sites.filter((function(t){return!s.siteIds.includes(t.id)&&s.settings.additionalSites.some((function(e){return e.siteId==t.id}))}));if(n.length){var a="add-site-label",r=$("<span/>",{text:Craft.t("app","Add a site..."),class:"visually-hidden",id:a}),o=Craft.ui.createSelect({options:[{label:Craft.t("app","Add a site…")}].concat((i=n.map((function(t){return{label:t.name,value:t.id}})),function(t){if(Array.isArray(t))return e(t)}(i)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(i)||t(i)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())),labelledBy:a}).addClass("fullwidth");this.$additionalSiteField=Craft.ui.createField(o,{}).addClass("nested add").appendTo(this.$siteStatusPane),r.prependTo(this.$additionalSiteField);var l=o.find("select");l.on("change",(function(){var t=parseInt(l.val()),e=Craft.sites.find((function(e){return e.id===t}));if(e){var i=s.settings.additionalSites.find((function(t){return t.siteId==e.id}));s._createSiteStatusField(e,i.enabledByDefault),s._updateGlobalStatus(),l.val("").find('option[value="'.concat(t,'"]')).remove(),null===s.newSiteIds&&(s.newSiteIds=[]),s.siteIds.push(t),s.newSiteIds.push(t),1===l.find("option").length&&s._removeField(s.$additionalSiteField)}})),this._showField(this.$additionalSiteField)}},showStatusHud:function(t){var e;this.failed?(e='<p class="error"><strong>'.concat(this._saveFailMessage(),"</strong></p>"),this.httpError&&(e+='<p class="http-error code">'.concat(Craft.escapeHtml(this.httpError),"</p>")),400===this.httpStatus&&(e+='<button class="btn refresh-btn">'.concat(Craft.t("app","Refresh"),"</button>"))):e="<p>".concat(this._saveSuccessMessage(),"</p>");var i=new Garnish.HUD(t,e,{hudClass:"hud revision-status-hud",onHide:function(){i.destroy()}});i.$mainContainer.find(".refresh-btn").on("click",(function(){window.location.reload()}))},_saveSuccessMessage:function(){return this.settings.isProvisionalDraft||this.settings.isUnpublishedDraft?Craft.t("app","Your changes have been stored."):Craft.t("app","The draft has been saved.")},_saveFailMessage:function(){return this.settings.isProvisionalDraft||this.settings.isUnpublishedDraft?Craft.t("app","Your changes could not be stored."):Craft.t("app","The draft could not be saved.")},spinners:function(){return this.preview?this.$spinner.add(this.preview.$spinner):this.$spinner},showSpinner:function(){this.spinners().removeClass("hidden")},hideSpinner:function(){this.spinners().addClass("hidden")},statusIcons:function(){return this.preview?this.$statusIcon.add(this.preview.$statusIcon):this.$statusIcon},statusMessage:function(){return this.preview?this.$statusMessage.add(this.preview.$statusMessage):this.$statusMessage},createEditMetaBtn:function(){var t=this.$container.find(".context-btngroup");this.$editMetaBtn=$("<button/>",{type:"button",class:"btn edit icon","aria-expanded":"false","aria-label":Craft.t("app","Edit draft settings"),title:Craft.t("app","Edit draft settings")}).appendTo(t),t.find(".btngroup-btn-last").removeClass("btngroup-btn-last"),this.addListener(this.$editMetaBtn,"click","showMetaHud")},createPreviewLink:function(t,e){var i=this,s=$("<a/>",{href:this.getTokenizedPreviewUrl(t.url,null,!1),text:e||Craft.t("app","View"),target:"_blank",data:{targetUrl:t.url,targetLabel:t.label}});return this.addListener(s,"click",(function(){setTimeout((function(){i.activatePreviewToken()}),1)})),this.previewLinks.push(s),s},updatePreviewLinks:function(){var t=this;this.previewLinks.forEach((function(e){t.updatePreviewLinkHref(e),t.activatedPreviewToken&&t.removeListener(e,"click")}))},updatePreviewLinkHref:function(t){t.attr("href",this.getTokenizedPreviewUrl(t.data("targetUrl"),null,!1))},activatePreviewToken:function(){this.settings.isLive||(this.activatedPreviewToken=!0,this.updatePreviewLinks())},createShareMenu:function(t){var e=this,i=$("<button/>",{type:"button",class:"view-btn btn menubtn",text:Craft.t("app","View")}).appendTo(t),s=$("<div/>",{class:"menu"}).appendTo(t),n=$("<ul/>").appendTo(s);this.settings.previewTargets.forEach((function(t){$("<li/>").append(e.createPreviewLink(t,t.label)).appendTo(n)})),new Garnish.MenuBtn(i)},getPreviewTokenParams:function(){var t={elementType:this.settings.elementType,canonicalId:this.settings.canonicalId,siteId:this.settings.siteId,revisionId:this.settings.revisionId,previewToken:this.settings.previewToken};return this.settings.draftId&&!this.settings.isProvisionalDraft&&(t.draftId=this.settings.draftId),t},getPreviewToken:function(){var t=this;return this.previewTokenQueue.push((function(){return new Promise((function(e,i){t.activatedPreviewToken?e(t.settings.previewToken):Craft.sendActionRequest("POST","preview/create-token",{data:t.getPreviewTokenParams()}).then((function(){t.activatePreviewToken(),e(t.settings.previewToken)})).catch(i)}))}))},getTokenizedPreviewUrl:function(t,e,i){var s=this;void 0===i&&(i=!0);var n={};if(!e&&this.settings.isLive||(n[e||"x-craft-preview"]=Craft.randomString(10)),this.settings.siteToken&&(n[Craft.siteToken]=this.settings.siteToken),this.settings.isLive){var a=Craft.getUrl(t,n);return i?new Promise((function(t){t(a)})):a}if(!this.settings.previewToken)throw"Missing preview token";n[Craft.tokenParam]=this.settings.previewToken;var r=Craft.getUrl(t,n);if(this.activatedPreviewToken)return i?new Promise((function(t){t(r)})):r;if(i)return new Promise((function(t,e){s.getPreviewToken().then((function(){t(r)})).catch(e)}));var o=this.getPreviewTokenParams();return o.redirect=r,Craft.getActionUrl("preview/create-token",o)},getPreview:function(){var t=this;return this.preview||(this.preview=new Craft.Preview(this),this.enableAutosave||(this.preview.on("open",(function(){t.enableAutosave=!0,t.listenForChanges()})),this.preview.on("close",(function(){t.enableAutosave=!1,t.stopListeningForChanges();var e=t.statusIcons();e.hasClass("checkmark-icon")&&e.addClass("hidden")}))),this.preview.on("close",(function(){t.scrollY&&(window.scrollTo(0,t.scrollY),t.scrollY=null)}))),this.preview},openPreview:function(){var t=this;Garnish.hasAttr(this.$previewBtn,"aria-disabled")||(this.$previewBtn.attr("aria-disabled",!0),this.$previewBtn.addClass("loading"),this.queue.push((function(){return new Promise((function(e,i){t.openingPreview=!0,t.ensureIsDraftOrRevision(!0).then((function(){t.scrollY=window.scrollY,t.$previewBtn.removeAttr("aria-disabled"),t.$previewBtn.removeClass("loading"),t.getPreview().open(),t.openingPreview=!1,e()})).catch(i)}))})))},ensureIsDraftOrRevision:function(t){var e=this;return new Promise((function(i,s){if(e.settings.draftId||e.settings.revisionId)i();else{if(t&&e.serializeForm(!0)===e.$container.data("initialSerializedValue"))return void i();e.createDraft().then(i).catch(s)}}))},serializeForm:function(t){var e=this.$container.serialize();if(this.isPreviewActive()&&(e=e.replace("__PREVIEW_FIELDS__=1",this.preview.$editor.serialize())),t&&!this.settings.isUnpublishedDraft){var i=this.namespaceInputName("action"),s=this.namespaceInputName("redirect");e=(e=e.replace(new RegExp("&".concat(Craft.escapeRegex(i),"=[^&]*")),"")).replace(new RegExp("&".concat(Craft.escapeRegex(s),"=[^&]*")),"")}return e},checkForm:function(t){var e=this;return this.queue.push((function(){return new Promise((function(i,s){if(e.settings.revisionId||e.pauseLevel>0||!e.enableAutosave||!e.settings.canCreateDrafts)i();else if(clearTimeout(e.timeout),e.timeout=null,void 0!==e.$container.data("initialSerializedValue")){var n=e.serializeForm(!0);t||n!==(e.lastSerializedValue||e.$container.data("initialSerializedValue"))?e.saveDraft(n).then(i).catch((function(t){console.warn("Couldn’t save draft:",t),s(t)})):i()}else e.timeout=setTimeout(e.checkForm.bind(e),500)}))}))},isPreviewActive:function(){return this.preview&&this.preview.isActive},createDraft:function(){var t=this;return this.queue.push((function(){return new Promise((function(e,i){t.saveDraft(t.serializeForm(!0)).then(e).catch(i)}))}))},saveDraft:function(t){var e=this;return new Promise((function(i,s){if(e.submittingForm)s("Form already being submitted.");else{e.lastSerializedValue=t,e.failed=!1,e.httpStatus=null,e.httpError=null,e.cancelToken=axios.CancelToken.source(),e.statusIcons().velocity("stop").css("opacity","").removeClass("hidden invisible checkmark-icon alert-icon fade-out").addClass("hidden"),e.statusMessage().empty(),e.$saveMetaBtn&&e.$saveMetaBtn.addClass("active");var n,a,r,o=[],l=e.prepareData(t,e.settings.isUnpublishedDraft?null:function(t,e){e.length&&o.push(decodeURIComponent(e[0].split("=")[0]))}),h=(n={},a=e.namespaceInputName("visibleLayoutElements"),r=e.settings.visibleLayoutElements,a in n?Object.defineProperty(n,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):n[a]=r,n);!e.settings.isProvisionalDraft&&e.settings.draftId||(h[e.namespaceInputName("provisional")]=1);var d=e.$contentContainer.children("[data-layout-tab]:not(.hidden)").data("id");d&&(h[e.namespaceInputName("selectedTab")]=d),l+="&".concat($.param(h)),Craft.sendActionRequest("POST","elements/save-draft",{cancelToken:e.cancelToken.token,headers:e._saveHeaders,data:l}).then((function(s){var n=e.$contentContainer.children("[data-layout-tab]:not(.hidden)").data("id");e._afterSaveDraft();var a=!e.settings.draftId;a&&(e.settings.isProvisionalDraft=!0,e.$revisionLabel.append($("<span/>",{text:" — ".concat(Craft.t("app","Edited"))}))),e.isFullPage&&(s.data.title&&e.$container.find(".screen-title").text(s.data.title),s.data.docTitle&&(document.title=s.data.docTitle)),e.settings.isProvisionalDraft||(e.$revisionLabel.text(s.data.draftName),e.settings.draftName=s.data.draftName);var r=e.$revisionBtn.data("menubtn")?e.$revisionBtn.data("menubtn").menu:null;for(var l in e.newSiteIds&&(r||(e.$revisionBtn.removeClass("disabled").addClass("menubtn"),new Garnish.MenuBtn(e.$revisionBtn),(r=e.$revisionBtn.data("menubtn").menu).$container.removeClass("hidden")),e.newSiteIds.forEach((function(t){var i=r.$options.filter("[data-site-id=".concat(t,"]")),s=e.settings.additionalSites.find((function(e){return e.siteId==t}));s&&void 0!==s.enabledByDefault&&!s.enabledByDefault||i.find(".status").removeClass("disabled").addClass("enabled"),i.parent().removeClass("hidden").closest(".site-group").removeClass("hidden")})),r.$container.find(".revision-hr").removeClass("hidden"),e.newSiteIds=null),e.settings.isProvisionalDraft?a&&(e.$container.find("input.action-input").attr("value","elements/apply-draft"),e.settings.draftId=s.data.draftId,e.settings.isLive=!1,e.previewToken=null,e.initForProvisionalDraft()):r&&(r.$options.filter(".sel").find(".draft-name").text(s.data.draftName),r.$options.filter(".sel").find(".draft-meta").text(s.data.creator?Craft.t("app","Saved {timestamp} by {creator}",{timestamp:s.data.timestamp,creator:s.data.creator}):Craft.t("app","Saved {timestamp}",{timestamp:s.data.timestamp}))),s.data.previewTargets&&JSON.stringify(s.data.previewTargets)!==JSON.stringify(e.settings.previewTargets)&&e.updatePreviewTargets(s.data.previewTargets),a&&(e.updatePreviewLinks(),e.trigger("createProvisionalDraft")),e.$nameTextInput&&e.checkMetaValues(),s.data.duplicatedElements)l!=e.settings.canonicalId&&s.data.duplicatedElements.hasOwnProperty(l)&&(e.duplicatedElements[l]=s.data.duplicatedElements[l]);for(var h=s.data.modifiedAttributes.map((function(t){return t=e.namespaceInputName(t),'[name="'.concat(t,'"],[name^="').concat(t,'["]')})).concat(o.map((function(t){return'[name="'.concat(t,'"]')}))),c=$(h.join(",")).parents().filter(".flex-fields > .field:not(:has(> .status-badge))"),u=0;u<c.length;u++)c.eq(u).prepend($("<div/>",{class:"status-badge modified",title:Craft.t("app","This field has been modified.")}).append($("<span/>",{class:"visually-hidden",html:Craft.t("app","This field has been modified.")})));for(var p=e.serializeForm(!0)===t,f=$(),g={},m=!1,v=0;v<s.data.missingElements.length;v++){var b=s.data.missingElements[v],C=e.$contentContainer.children('[data-layout-tab="'.concat(b.uid,'"]'));C.length||(C=$("<div/>",{id:e.namespaceId(b.id),class:"flex-fields","data-id":b.id,"data-layout-tab":b.uid}),b.id!==d&&C.addClass("hidden"),C.appendTo(e.$contentContainer)),f=f.add(C);for(var _=0;_<b.elements.length;_++){var w=b.elements[_];if(!1!==w.html){if(g[b.uid]||(g[b.uid]=[]),g[b.uid].push(w.uid),"string"==typeof w.html){var S=C.children('[data-layout-element="'.concat(w.uid,'"]')),y=$(w.html);S.length?S.replaceWith(y):y.appendTo(C),Craft.initUiElements(y),m=!0}}else{var I=C.children('[data-layout-element="'.concat(w.uid,'"]'));if(!I.length||!Garnish.hasAttr(I,"data-layout-element-placeholder")){var T=$("<div/>",{class:"hidden","data-layout-element":w.uid,"data-layout-element-placeholder":""});I.length?I.replaceWith(T):T.appendTo(C),m=!0}}}}var x,P=e.$contentContainer.children("[data-layout-tab]").not(f).not('[data-layout-tab=""]');if(P.length&&(P.remove(),m=!0),f.filter(":not(.hidden)").length||f.first().removeClass("hidden"),e.settings.visibleLayoutElements=g,e.isFullPage?(Craft.cp.updateTabs(s.data.tabs),x=Craft.cp.tabManager):(e.slideout.updateTabs(s.data.tabs),x=e.slideout.tabManager),d&&n&&d!==n){var B=x.$tabs.filter('[data-id="'.concat(n,'"]'));B.length?x.selectTab(B):x.selectTab(x.$tabs.first())}Craft.appendHeadHtml(s.data.headHtml),Craft.appendBodyHtml(s.data.bodyHtml),m&&(s.data.initialDeltaValues&&Object.assign(e.$container.data("initial-delta-values"),s.data.initialDeltaValues),p&&(e.lastSerializedValue=e.serializeForm(!0))),e.handleDismissibleTips(),e.afterUpdate(t),Craft.broadcaster&&Craft.broadcaster.postMessage({pageId:Craft.pageId,event:"saveDraft",canonicalId:e.settings.canonicalId,draftId:e.settings.draftId,isProvisionalDraft:e.settings.isProvisionalDraft}),i()})).catch((function(t){e._afterSaveDraft(),e.ignoreFailedRequest||(e.failed=!0,t&&t.response&&(e.httpStatus=t.response.status,e.httpError=t.response.data?t.response.data.message:null),e._showFailStatus(),s(t)),e.ignoreFailedRequest=!1}))}}))},_afterSaveDraft:function(){this.$saveMetaBtn&&this.$saveMetaBtn.removeClass("active")},_showFailStatus:function(){this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden checkmark-icon").addClass("alert-icon"),this.setStatusMessage(this._saveFailMessage())},prepareData:function(t,e){t=Craft.findDeltaData(this.$container.data("initialSerializedValue"),t,this.$container.data("delta-names"),e,this.$container.data("initial-delta-values"),this.$container.data("modified-delta-names")),t=this.swapDuplicatedElementIds(t);var i={};return this.settings.draftId&&(i[this.namespaceInputName("draftId")]=this.settings.draftId,this.settings.isProvisionalDraft&&(i[this.namespaceInputName("provisional")]=1)),null!==this.settings.draftName&&(i[this.namespaceInputName("draftName")]=this.settings.draftName),$.isEmptyObject(i)||(t+="&".concat($.param(i))),t},get _saveHeaders(){var t={"content-type":"application/x-www-form-urlencoded"};return this.namespace&&(t["X-Craft-Namespace"]=this.namespace),t},swapDuplicatedElementIds:function(t){var e=this,i=Object.keys(this.duplicatedElements).join("|");if(""===i)return t;var s=encodeURIComponent("["),n=encodeURIComponent("]"),a=this.namespaceInputName("fields");for(a=this.isFullPage?Craft.escapeRegex(a):encodeURIComponent(a);t!==(t=t.replace(new RegExp("(&".concat(a).concat(s,"[^=]+").concat(n).concat(s,")(").concat(i,")(").concat(n,")"),"g"),(function(t,i,s,n){return e._filterFieldInputName(i)?i+e.duplicatedElements[s]+n:t})).replace(new RegExp("&(".concat(a).concat(s,"[^=]+)=(").concat(i,")\\b"),"g"),(function(t,i,a){return!e._filterFieldInputName(i)||i.match(new RegExp("".concat(s,"(enabled|sortOrder|type|typeId)").concat(n,"$")))?t:"&".concat(i,"=").concat(e.duplicatedElements[a])}))););return t},_filterFieldInputName:function(t){var e=encodeURIComponent("["),i=encodeURIComponent("]"),s=t.match(new RegExp("(\\bfields|".concat(e,"fields").concat(i,")").concat(e,".+?").concat(i),"g"));if(!s)throw"Unexpected input name: ".concat(t);var n=s[s.length-1].match(new RegExp("(?:\\bfields|".concat(e,"fields").concat(i,")").concat(e,"(.+?)").concat(i)))[1];return Craft.fieldsWithoutContent.includes(n)},updatePreviewTargets:function(t){var e=this;t.forEach((function(t){var i=e.settings.previewTargets.find((function(e){return e.label===t.label}));i&&(i.url=t.url);var s=e.previewLinks.find((function(e){return e.data("targetLabel")===t.label}));s&&(s.data("targetUrl",t.url),e.updatePreviewLinkHref(s))}))},afterUpdate:function(t){this.$container.data("initialSerializedValue",t),this.$container.data("initial-delta-values",{});var e=this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden").addClass("checkmark-icon");this.setStatusMessage(this._saveSuccessMessage()),Craft.autosaveDrafts||e.velocity("stop").velocity({opacity:0},{delay:2e3,complete:function(){e.addClass("hidden")}}),this.trigger("update")},setStatusMessage:function(t){this.statusIcons().attr("title",t),this.statusMessage().empty().append($("<span/>",{class:"visually-hidden",text:t}))},showMetaHud:function(){this.metaHud?this.metaHud.show():(this.createMetaHud(),this.onMetaHudShow()),Garnish.isMobileBrowser(!0)||this.$nameTextInput.trigger("focus")},createMetaHud:function(){var t=$("<div/>"),e=$('<div class="field"><div class="heading"><label for="draft-name">'+Craft.t("app","Draft Name")+"</label></div></div>").appendTo(t),i=$('<div class="input"/>').appendTo(e);this.$nameTextInput=$('<input type="text" class="text fullwidth" id="draft-name"/>').appendTo(i).val(this.settings.draftName);var s=$('<div class="hud-footer flex flex-center"/>').appendTo(t);$('<div class="flex-grow"></div>').appendTo(s),this.$saveMetaBtn=$("<button/>",{type:"submit",class:"btn submit disabled","aria-disabled":"true",text:Craft.t("app","Save")}).appendTo(s),this.metaHud=new Garnish.HUD(this.$editMetaBtn,t,{onSubmit:this.saveMeta.bind(this)}),this.addListener(this.$nameTextInput,"input","checkMetaValues"),this.metaHud.on("show",this.onMetaHudShow.bind(this)),this.metaHud.on("hide",this.onMetaHudHide.bind(this)),this.metaHud.on("escape",this.onMetaHudEscape.bind(this))},onMetaHudShow:function(){this.$editMetaBtn.addClass("active"),this.$editMetaBtn.attr("aria-expanded","true")},onMetaHudHide:function(){this.$editMetaBtn.removeClass("active"),this.$editMetaBtn.attr("aria-expanded","false"),Garnish.focusIsInside(this.metaHud.$body)&&this.$editMetaBtn.trigger("focus")},onMetaHudEscape:function(){this.$nameTextInput.val(this.settings.draftName)},checkMetaValues:function(){return this.$nameTextInput.val()&&this.$nameTextInput.val()!==this.settings.draftName?(this.$saveMetaBtn.removeClass("disabled"),this.$saveMetaBtn.removeAttr("aria-disabled"),!0):(this.$saveMetaBtn.addClass("disabled"),this.$saveMetaBtn.attr("aria-disabled","true"),!1)},shakeMetaHud:function(){Garnish.shake(this.metaHud.$hud)},saveMeta:function(){var t=this;return new Promise((function(e,i){if(!t.checkMetaValues())return t.shakeMetaHud(),void i();t.settings.draftName=t.$nameTextInput.val(),t.metaHud.hide(),t.checkForm(!0).then(e).catch(i)}))},handleSubmit:function(t){var e=this;if(t.preventDefault(),t.stopPropagation(),!this.submittingForm)if(!this.settings.draftId||this.settings.isUnpublishedDraft||this.settings.isProvisionalDraft||void 0!==t.autosave&&!t.autosave||!(t.saveShortcut||t.customTrigger&&"elements/save-draft"===t.customTrigger.data("action"))||!this.enableAutosave){this.submittingForm=!0,Craft.cp.$confirmUnloadForms=Craft.cp.$confirmUnloadForms.not(this.$container),this.cancelToken&&(this.ignoreFailedRequest=!0,this.cancelToken.cancel()),this.trigger("beforeSubmit");var i=this.prepareData(this.serializeForm(!1));if(this.isFullPage){this.stopListeningForChanges();var s=Craft.createForm(i);s.appendTo(Garnish.$bod),s.submit()}else this.slideout.showSubmitSpinner(),Craft.sendActionRequest("POST",null,{headers:this._saveHeaders,data:i}).then((function(t){e.slideout.handleSubmitResponse(t)})).catch((function(t){e.slideout.handleSubmitError(t)})).finally((function(){e.submittingForm=!1,e.slideout.hideSubmitSpinner()}))}else this.checkForm(!0)},handleDismissibleTips:function(){var t=this;this.addListener(this.tipDismissBtn,"click",(function(e){t.hideTip(e)}))},getHiddenTipsUids:function(){return Craft.getLocalStorage("dismissedTips",[])},setHiddenTipsUids:function(t){Craft.setLocalStorage("dismissedTips",t)},hideTip:function(t){var e=t.target;if(e){var i=$(e).closest(".readable");if(i.length){var s=i.data("layout-element");if(i.remove(),"undefined"!=typeof Storage){var n=this.getHiddenTipsUids();n.includes(s)||(n.push(s),this.setHiddenTipsUids(n))}}}}},{defaults:{additionalSites:[],canCreateDrafts:!1,canEditMultipleSites:!1,canSaveCanonical:!1,canonicalId:null,draftId:null,draftName:null,elementType:null,enablePreview:!1,enabled:!1,enabledForSite:!1,hashedCpEditUrl:null,isLive:!1,isProvisionalDraft:!1,isUnpublishedDraft:!1,previewTargets:[],previewToken:null,revisionId:null,siteId:null,siteStatuses:null,siteToken:null,visibleLayoutElements:{}}})},4211:function(){Craft.ElementEditorSlideout=Craft.CpScreenSlideout.extend({$element:null,init:function(t,e){var i=this;this.$element=$(t),e=Object.assign({},Craft.ElementEditorSlideout.defaults,e,{showHeader:!0}),this.base("elements/edit",e),this.on("load",(function(){var t=i.$container.data("elementEditor");t&&t.on("beforeSubmit",(function(){Object.keys(i.settings.saveParams).forEach((function(e){$("<input/>",{class:"hidden",name:t.namespaceInputName(e),value:i.settings.saveParams[e]}).appendTo(i.$container)}))}))})),this.on("submit",(function(t){if(Craft.broadcaster&&Craft.broadcaster.postMessage({event:"saveElement",id:t.response.data.element.id}),i.settings.onSaveElement){var e=Object.assign({},t.response.data,t.response.data.element);delete e.element,delete e.modelName,delete e.message,i.settings.onSaveElement(e)}Craft.Preview.refresh()}))},getParams:function(){var t={};return this.settings.elementType&&(t.elementType=this.settings.elementType),this.settings.elementId?t.elementId=this.settings.elementId:this.$element&&this.$element.data("id")&&(t.elementId=this.$element.data("id")),this.settings.draftId?t.draftId=this.settings.draftId:this.$element&&this.$element.data("draft-id")?t.draftId=this.$element.data("draft-id"):this.settings.revisionId?t.revisionId=this.settings.revisionId:this.$element&&this.$element.data("revision-id")&&(t.revisionId=this.$element.data("revision-id")),this.settings.siteId?t.siteId=this.settings.siteId:this.$element&&this.$element.data("site-id")&&(t.siteId=this.$element.data("site-id")),this.settings.prevalidate&&(t.prevalidate=1),t},handleSubmit:function(t){this.$container.data("elementEditor").handleSubmit(t)}},{defaults:{elementId:null,draftId:null,revisionId:null,elementType:null,siteId:null,prevalidate:!1,saveParams:{},onSaveElement:null,validators:[]}})},7998:function(){Craft.ElementFieldSettings=Garnish.Base.extend({allowMultipleSources:null,$maintainHierarchyField:null,$maintainHierarchyInput:null,$sourcesField:null,$sourceSelect:null,$branchLimitField:null,$maxRelationsField:null,$minRelationsField:null,init:function(t,e,i,s,n,a){this.allowMultipleSources=t,this.$maintainHierarchyField=$("#".concat(e)),this.$maintainHierarchyInput=this.$maintainHierarchyField.find('input[type="checkbox"]'),this.$sourcesField=$("#".concat(i)),this.allowMultipleSources||(this.$sourceSelect=this.$sourcesField.find("select")),this.$branchLimitField=$("#".concat(s)),this.$minRelationsField=$("#".concat(n)),this.$maxRelationsField=$("#".concat(a)),this.updateLimitFields(),this.addListener(this.$maintainHierarchyInput,"change","updateLimitFields"),this.allowMultipleSources?this.$sourcesField.find("[type=checkbox]").each(function(t,e){this.addListener($(e),"change","updateMaintainHierarchyField")}.bind(this)):this.addListener(this.$sourceSelect,"change","updateMaintainHierarchyField"),this.updateMaintainHierarchyField()},updateLimitFields:function(){!this.$maintainHierarchyField.hasClass("hidden")&&this.$maintainHierarchyInput.is(":checked")?(this.$minRelationsField.addClass("hidden"),this.$maxRelationsField.addClass("hidden"),this.$branchLimitField.removeClass("hidden")):(this.$branchLimitField.addClass("hidden"),this.$minRelationsField.removeClass("hidden"),this.$maxRelationsField.removeClass("hidden"))},updateMaintainHierarchyField:function(){var t;if(this.allowMultipleSources){var e=this.$sourcesField.find('[type="checkbox"]:checked');t=1===e.length&&e.data("structure-id")}else t=this.$sourceSelect.children("option:selected").data("structure-id");t?this.$maintainHierarchyField.removeClass("hidden"):this.$maintainHierarchyField.addClass("hidden"),this.updateLimitFields()}})},8895:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.ElementThumbLoader=Garnish.Base.extend({queue:null,workers:[],init:function(){this.queue=[];for(var t=0;t<3;t++)this.workers.push(new Craft.ElementThumbLoader.Worker(this))},load:function(t){for(var e=this,i=t.find(".elementthumb"),s=function(t){var s=i.eq(t),n=s.scrollParent();if("FIELDSET"===n.prop("nodeName")&&(n=n.scrollParent()),n[0]===document.body&&(n=Garnish.$doc),e.isVisible(s,n))e.addToQueue(s[0]);else{var a="thumb"+Math.floor(1e6*Math.random());Craft.ElementThumbLoader.invisibleThumbs[a]=[e,s,n],n.on("scroll.".concat(a),{$thumb:s,$scrollParent:n,key:a},(function(t){e.isVisible(t.data.$thumb,t.data.$scrollParent)&&(delete Craft.ElementThumbLoader.invisibleThumbs[t.data.key],n.off("scroll.".concat(t.data.key)),e.addToQueue(t.data.$thumb[0]))}))}},n=0;n<i.length;n++)s(n)},addToQueue:function(t){this.queue.push(t);for(var e=0;e<this.workers.length;e++)this.workers[e].active||this.workers[e].loadNext()},isVisible:function(t,e){var i,s,n=t.offset().top;return e[0]===document?(i=e.scrollTop(),s=Garnish.$win.height()):(i=e.offset().top,s=e.height()),n>i&&n<i+s+1e3},destroy:function(){for(var t=0;t<this.workers.length;t++)this.workers[t].destroy();this.base()}},{invisibleThumbs:{},retryAll:function(){for(var e in Craft.ElementThumbLoader.invisibleThumbs){var i=(r=Craft.ElementThumbLoader.invisibleThumbs[e],o=3,function(t){if(Array.isArray(t))return t}(r)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(r,o)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(r,o)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),s=i[0],n=i[1],a=i[2];delete Craft.ElementThumbLoader.invisibleThumbs[e],a.off("scroll.".concat(e)),s.load(n.parent())}var r,o}}),Craft.ElementThumbLoader.Worker=Garnish.Base.extend({loader:null,active:!1,init:function(t){this.loader=t},loadNext:function(){var t=this.loader.queue.shift();if(void 0!==t){this.active=!0;var e=$(t);if(e.find("img").length)this.loadNext();else{var i=$("<img/>",{sizes:e.attr("data-sizes"),srcset:e.attr("data-srcset"),alt:e.attr("data-alt")||""});this.addListener(i,"load,error","loadNext"),i.appendTo(e),picturefill({elements:[i[0]]})}}else this.active=!1}})},4233:function(){Craft.ElevatedSessionForm=Garnish.Base.extend({$form:null,inputs:null,init:function(t,e){if(this.$form=$(t),void 0!==e){this.inputs=[],e=$.makeArray(e);for(var i=0;i<e.length;i++)for(var s=$(e[i]),n=0;n<s.length;n++){var a=s.eq(n);this.inputs.push({input:a,val:Garnish.getInputPostVal(a)})}}this.addListener(this.$form,"submit","handleFormSubmit")},handleFormSubmit:function(t){if(Craft.elevatedSessionManager.fetchingTimeout)return t.preventDefault(),void t.stopImmediatePropagation();if(this.inputs){for(var e,i=!1,s=0;s<this.inputs.length;s++)if((e=this.inputs[s].input).data("passwordInput")&&(e=e.data("passwordInput").$currentInput),Garnish.getInputPostVal(e)!==this.inputs[s].val){i=!0;break}if(!i)return}t.preventDefault(),t.stopImmediatePropagation(),Craft.elevatedSessionManager.requireElevatedSession(this.submitForm.bind(this))},submitForm:function(){this.disable(),this.$form.trigger("submit"),this.enable()}})},9699:function(){Craft.ElevatedSessionManager=Garnish.Base.extend({fetchingTimeout:!1,passwordModal:null,$passwordInput:null,$submitBtn:null,$errorPara:null,callback:null,requireElevatedSession:function(t){var e=this;this.callback=t,this.fetchingTimeout=!0,Craft.sendActionRequest("POST","users/get-elevated-session-timeout").then((function(t){e.fetchingTimeout=!1,!1===t.data.timeout||t.data.timeout>=Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout?e.callback():e.showPasswordModal()})).catch((function(){e.fetchingTimeout=!1}))},showPasswordModal:function(){var t=this;if(this.passwordModal)this.passwordModal.show();else{var e=$('<form id="elevatedsessionmodal" class="modal secure fitted"/>'),i=$('<div class="body"><p>'+Craft.t("app","Enter your password to continue.")+"</p></div>").appendTo(e),s=$('<div class="inputcontainer">').appendTo(i),n=$('<div class="flex"/>').appendTo(s),a=$('<div class="flex-grow"/>').appendTo(n),r=$("<td/>").appendTo(n),o=$('<div class="passwordwrapper"/>').appendTo(a);this.$passwordInput=$('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'" autocomplete="current-password"/>').appendTo(o),this.$submitBtn=Craft.ui.createSubmitButton({class:"disabled",label:Craft.t("app","Submit"),spinner:!0}).appendTo(r),this.$errorPara=$('<p class="error"/>').appendTo(i),this.passwordModal=new Garnish.Modal(e,{closeOtherModals:!1,onFadeIn:function(){setTimeout(t.focusPasswordInput.bind(t),100)},onFadeOut:function(){t.$passwordInput.val("")}}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:function(e){t.$passwordInput=e}}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(e,"submit","submitPassword")}},focusPasswordInput:function(){Garnish.isMobileBrowser(!0)||this.$passwordInput.trigger("focus")},validatePassword:function(){return this.$passwordInput.val().length>=6?(this.$submitBtn.removeClass("disabled"),!0):(this.$submitBtn.addClass("disabled"),!1)},submitPassword:function(t){var e=this;if(t&&t.preventDefault(),this.validatePassword()){this.$submitBtn.addClass("loading"),this.clearLoginError();var i={currentPassword:this.$passwordInput.val()};Craft.sendActionRequest("POST","users/start-elevated-session",{data:i}).then((function(t){e.$submitBtn.removeClass("loading"),e.passwordModal.hide(),e.callback()})).catch((function(t){var i=t.response;e.$submitBtn.removeClass("loading"),e.showPasswordError(i.data.message||Craft.t("app","Incorrect password.")),Garnish.shake(e.passwordModal.$container),e.focusPasswordInput()}))}},showPasswordError:function(t){null==t&&(t=Craft.t("app","A server error occurred.")),this.$errorPara.text(t),this.passwordModal.updateSizeAndPosition()},clearLoginError:function(){this.showPasswordError("")}},{minSafeElevatedSessionTimeout:5}),Craft.elevatedSessionManager=new Craft.ElevatedSessionManager},1402:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.EntryIndex=Craft.BaseElementIndex.extend({publishableSections:null,$newEntryBtnGroup:null,$newEntryBtn:null,init:function(t,e,i){this.publishableSections=[],this.on("selectSource",this.updateButton.bind(this)),this.on("selectSite",this.updateButton.bind(this)),this.base(t,e,i)},afterInit:function(){var t=this;this.publishableSections=Craft.publishableSections.filter((function(e){return!!t.getSourceByKey("section:".concat(e.uid))})),this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultSectionHandle){if("singles"===defaultSectionHandle)return"singles";for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("handle")===defaultSectionHandle)return e.data("key")}}return this.base()},updateButton:function(){var e,i=this;if(this.$source&&(e="singles"===this.$source.data("key")?"singles":this.$source.data("handle"),this.publishableSections.length&&function(){i.$newEntryBtnGroup&&i.$newEntryBtnGroup.remove();var s,n=i.publishableSections.find((function(t){return t.handle===e}));i.$newEntryBtnGroup=$('<div class="btngroup submit" data-wrapper/>');var a="new-entry-menu-"+Craft.randomString(10);if(n){var r="index"===i.settings.context?Craft.t("app","New entry"):Craft.t("app","New {section} entry",{section:n.name}),o="index"===i.settings.context?Craft.t("app","New entry in the {section} section",{section:n.name}):r,l="index"===i.settings.context?"link":null;i.$newEntryBtn=Craft.ui.createButton({label:r,ariaLabel:o,spinner:!0,role:l}).addClass("submit add icon").appendTo(i.$newEntryBtnGroup),i.addListener(i.$newEntryBtn,"click mousedown",(function(t){"index"===i.settings.context&&("click"===t.type&&Garnish.isCtrlKeyPressed(t)||"mousedown"===t.type&&1===t.originalEvent.button)?window.open(Craft.getUrl("entries/".concat(n.handle,"/new"))):"click"===t.type&&i._createEntry(n.id)})),i.publishableSections.length>1&&(s=$("<button/>",{type:"button",class:"btn submit menubtn btngroup-btn-last","aria-controls":a,"data-disclosure-trigger":"","aria-label":Craft.t("app","New entry, choose a section")}).appendTo(i.$newEntryBtnGroup))}else i.$newEntryBtn=s=Craft.ui.createButton({label:Craft.t("app","New entry"),ariaLabel:Craft.t("app","New entry, choose a section"),spinner:!0}).addClass("submit add icon menubtn btngroup-btn-last").attr("aria-controls",a).attr("data-disclosure-trigger","").appendTo(i.$newEntryBtnGroup);if(i.addButton(i.$newEntryBtnGroup),s){var h,d=$("<div/>",{id:a,class:"menu menu--disclosure"}).appendTo(i.$newEntryBtnGroup),c=$("<ul/>").appendTo(d),u=function(e,i){var s="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!s){if(Array.isArray(e)||(s=function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(e))||i&&e&&"number"==typeof e.length){s&&(e=s);var n=0,a=function(){};return{s:a,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){s=s.call(e)},n:function(){var t=s.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==s.return||s.return()}finally{if(l)throw r}}}}(i.publishableSections);try{var p=function(){var t=h.value,e="index"===i.settings.context?"link":"button";if("index"===i.settings.context&&-1!==$.inArray(i.siteId,t.sites)||"index"!==i.settings.context&&t!==n){var a=$("<li/>").appendTo(c),r=$("<a/>",{role:"button"===e?"button":null,href:"#",type:"button"===e?"button":null,text:Craft.t("app","New {section} entry",{section:t.name})}).appendTo(a);i.addListener(r,"click",(function(){s.data("trigger").hide(),i._createEntry(t.id)})),"button"===e&&i.addListener(r,"keydown",(function(e){e.keyCode===Garnish.SPACE_KEY&&(e.preventDefault(),s.data("trigger").hide(),i._createEntry(t.id))}))}};for(u.s();!(h=u.n()).done;)p()}catch(t){u.e(t)}finally{u.f()}new Garnish.DisclosureMenu(s)}}(),"index"===this.settings.context)){var s="entries";e&&(s+="/"+e),Craft.setPath(s)}},_createEntry:function(t){var e=this;if(this.$newEntryBtn.hasClass("loading"))console.warn("New entry creation already in progress.");else{var i=this.publishableSections.find((function(e){return e.id===t}));if(!i)throw"Invalid section ID: ".concat(t);this.$newEntryBtn.addClass("loading"),Craft.sendActionRequest("POST","entries/create",{data:{siteId:this.siteId,section:i.handle}}).then((function(t){var s=t.data;"index"===e.settings.context?document.location.href=Craft.getUrl(s.cpEditUrl,{fresh:1}):Craft.createElementEditor(e.elementType,{siteId:e.siteId,elementId:s.entry.id,draftId:s.entry.draftId,params:{fresh:1}}).on("submit",(function(){var t="section:".concat(i.uid);e.sourceKey!==t&&e.selectSourceByKey(t),e.clearSearch(),e.setSelectedSortAttribute("dateCreated","desc"),e.selectElementAfterUpdate(s.entry.id),e.updateElements()}))})).finally((function(){e.$newEntryBtn.removeClass("loading")}))}}}),Craft.registerElementIndexClass("craft\\elements\\Entry",Craft.EntryIndex)},8201:function(){Craft.FieldLayoutDesigner=Garnish.Base.extend({$container:null,$configInput:null,$tabContainer:null,$newTabBtn:null,$sidebar:null,$libraryToggle:null,$selectedLibrary:null,$fieldLibrary:null,$uiLibrary:null,$uiLibraryElements:null,$fieldSearch:null,$clearFieldSearchBtn:null,$fieldGroups:null,$fields:null,tabGrid:null,elementDrag:null,_config:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.FieldLayoutDesigner.defaults),this.$configInput=this.$container.children("input[data-config-input]"),this._config=JSON.parse(this.$configInput.val()),this._config.tabs||(this._config.tabs=[]);var s=this.$container.children(".fld-workspace");this.$tabContainer=s.children(".fld-tabs"),this.$newTabBtn=s.children(".fld-new-tab-btn"),this.$sidebar=this.$container.children(".fld-sidebar"),this.$fieldLibrary=this.$selectedLibrary=this.$sidebar.children(".fld-field-library");var n=this.$fieldLibrary.children(".search");this.$fieldSearch=n.children("input"),this.$clearFieldSearchBtn=n.children(".clear"),this.$fieldGroups=this.$sidebar.find(".fld-field-group"),this.$fields=this.$fieldGroups.children(".fld-element"),this.$uiLibrary=this.$sidebar.children(".fld-ui-library"),this.$uiLibraryElements=this.$uiLibrary.children(),this.tabGrid=new Craft.Grid(this.$tabContainer,{itemSelector:".fld-tab",minColWidth:264,fillMode:"grid",snapToGrid:24});for(var a=this.$tabContainer.children(),r=0;r<a.length;r++)this.initTab($(a[r]));if(this.elementDrag=new Craft.FieldLayoutDesigner.ElementDrag(this),this.settings.customizableTabs&&(this.tabDrag=new Craft.FieldLayoutDesigner.TabDrag(this),this.addListener(this.$newTabBtn,"activate","addTab")),this.settings.customizableUi){var o=this.$sidebar.children(".btngroup");new Craft.Listbox(o,{onChange:function(t){i.$selectedLibrary.addClass("hidden"),i.$selectedLibrary=i["$".concat(t.data("library"),"Library")].removeClass("hidden")}})}this.addListener(this.$fieldSearch,"input",(function(){var t=i.$fieldSearch.val().toLowerCase().replace(/['"]/g,"");if(!t)return i.$fieldLibrary.find(".filtered").removeClass("filtered"),void i.$clearFieldSearchBtn.addClass("hidden");i.$clearFieldSearchBtn.removeClass("hidden");var e=i.$fields.filter('[data-keywords*="'.concat(t,'"]')).add(i.$fieldGroups.filter('[data-name*="'.concat(t,'"]')).children(".fld-element")).removeClass("filtered");i.$fields.not(e).addClass("filtered");for(var s=0;s<i.$fieldGroups.length;s++){var n=i.$fieldGroups.eq(s);n.find(".fld-element:not(.hidden):not(.filtered)").length?n.removeClass("filtered"):n.addClass("filtered")}})),this.addListener(this.$fieldSearch,"keydown",(function(t){switch(t.keyCode){case Garnish.ESC_KEY:i.$fieldSearch.val("").trigger("input");break;case Garnish.RETURN_KEY:t.preventDefault()}})),this.addListener(this.$clearFieldSearchBtn,"click",(function(){i.$fieldSearch.val("").trigger("input")}))},initTab:function(t){return new Craft.FieldLayoutDesigner.Tab(this,t)},removeFieldByHandle:function(t){this.$fields.filter('[data-attribute="'.concat(t,'"]:first')).removeClass("hidden").closest(".fld-field-group").removeClass("hidden")},addTab:function(){if(this.settings.customizableTabs){var t=Craft.escapeHtml(prompt(Craft.t("app","Give your tab a name.")));if(t){var e=$('\n<div class="fld-tab">\n  <div class="tabs">\n    <div class="tab sel draggable">\n      <span>'.concat(t,'</span>\n      <a class="settings icon" title="').concat(Craft.t("app","Settings"),'"></a>\n    </div>\n  </div>\n  <div class="fld-tabcontent"></div>\n</div>\n')).appendTo(this.$tabContainer);this.tabGrid.addItems(e),this.tabDrag.addItems(e),this.initTab(e).updatePositionInConfig()}}},get config(){return this._config},set config(t){this._config=t,this.$configInput.val(JSON.stringify(t))},updateConfig:function(t){var e=t(this.config);!1!==e&&(this.config=e)}},{defaults:{customizableTabs:!0,customizableUi:!0},createSlideout:function createSlideout(contents,js){var $body=$("<div/>",{class:"fld-element-settings-body"});$("<div/>",{class:"fields",html:contents}).appendTo($body);var $footer=$("<div/>",{class:"fld-element-settings-footer"});$("<div/>",{class:"flex-grow"}).appendTo($footer);var $cancelBtn=Craft.ui.createButton({label:Craft.t("app","Close"),spinner:!0}).appendTo($footer);Craft.ui.createSubmitButton({class:"secondary",label:Craft.t("app","Apply"),spinner:!0}).appendTo($footer);var $contents=$body.add($footer),slideout=new Craft.Slideout($contents,{containerElement:"form",containerAttributes:{action:"",method:"post",novalidate:"",class:"fld-element-settings"}});return slideout.on("open",(function(){Garnish.requestAnimationFrame((function(){slideout.$container.find(".text:first").trigger("focus")}))})),$cancelBtn.on("click",(function(){slideout.close()})),js&&eval(js),Craft.initUiElements(slideout.$container),slideout}}),Craft.FieldLayoutDesigner.Tab=Garnish.Base.extend({designer:null,uid:null,$container:null,slideout:null,destroyed:!1,init:function(t,e){this.designer=t,this.$container=e,this.$container.data("fld-tab",this),this.uid=this.$container.data("uid"),this.uid||(this.uid=Craft.uuid(),this.config={uid:this.uid,name:this.$container.find(".tabs .tab span").text(),elements:[]},this.$container.data("settings-namespace",this.designer.$container.data("new-tab-settings-namespace").replace(/\bTAB_UID\b/g,this.uid)),this.$container.data("settings-html",this.designer.$container.data("new-tab-settings-html").replace(/\bTAB_UID\b/g,this.uid).replace(/\bTAB_NAME\b/g,this.config.name)),this.$container.data("settings-js",this.designer.$container.data("new-tab-settings-js").replace(/\bTAB_UID\b/g,this.uid))),this.designer.settings.customizableTabs&&(this.settingsNamespace=this.$container.data("settings-namespace"),this.createMenu());for(var i=this.$container.children(".fld-tabcontent").children(),s=0;s<i.length;s++)this.initElement($(i[s]))},createMenu:function(){var t=this,e=this.$container.find(".tabs .settings");$('<div class="menu" data-align="center"/>').insertAfter(e).append($("<ul/>").append($("<li/>").append($("<a/>",{"data-action":"settings",text:Craft.t("app","Settings")}))).append($("<li/>").append($("<a/>",{"data-action":"remove",text:Craft.t("app","Remove")})))).append($("<hr/>")).append($("<ul/>").append($("<li/>").append($("<a/>",{"data-action":"moveLeft",text:Craft.t("app","Move to the left")}))).append($("<li/>").append($("<a/>",{"data-action":"moveRight",text:Craft.t("app","Move to the right")}))));var i=new Garnish.MenuBtn(e,{onOptionSelect:this.onTabOptionSelect.bind(this)});i.menu.on("show",(function(){t.$container.prev(".fld-tab").length?i.menu.$container.find("[data-action=moveLeft]").removeClass("disabled"):i.menu.$container.find("[data-action=moveLeft]").addClass("disabled"),t.$container.next(".fld-tab").length?i.menu.$container.find("[data-action=moveRight]").removeClass("disabled"):i.menu.$container.find("[data-action=moveRight]").addClass("disabled")}))},onTabOptionSelect:function(t){if(this.designer.settings.customizableTabs)switch($(t).data("action")){case"settings":this.slideout?this.slideout.open():this.createSettings();break;case"remove":this.destroy();break;case"moveLeft":var e=this.$container.prev(".fld-tab");e.length&&(this.$container.insertBefore(e),this.updatePositionInConfig());break;case"moveRight":var i=this.$container.next(".fld-tab");i.length&&(this.$container.insertAfter(i),this.updatePositionInConfig())}},createSettings:function(){var t=this,e=this.$container.data("settings-html"),i=this.$container.data("settings-js");this.slideout=Craft.FieldLayoutDesigner.createSlideout(e,i),this.slideout.$container.on("submit",(function(e){e.preventDefault(),t.applySettings()}))},applySettings:function(){var t=this;if(this.slideout.$container.find('[name$="[name]"]').val()){var e=this.slideout.$container.find("button[type=submit]").addClass("loading"),i=$.extend({},this.config);delete i.elements,Craft.sendActionRequest("POST","fields/apply-layout-tab-settings",{data:{config:i,settingsNamespace:this.settingsNamespace,settings:this.slideout.$container.serialize()}}).then((function(e){t.updateConfig((function(t){return $.extend(e.data.config,{elements:t.elements})}));var i=t.$container.find(".tabs .tab span"),s=i.children(".fld-indicator");e.data.hasConditions?s.length||i.append($("<div/>",{class:"fld-indicator",title:Craft.t("app","This tab is conditional"),"aria-label":Craft.t("app","This tab is conditional"),"data-icon":"condition",role:"img"})):s.length&&s.remove(),t.slideout.close()})).catch((function(t){Craft.cp.displayError(),console.error(t)})).finally((function(){e.removeClass("loading"),t.slideout.close()}))}else Craft.cp.displayError(Craft.t("app","You must specify a tab name."))},initElement:function(t){return new Craft.FieldLayoutDesigner.Element(this,t)},get index(){var t=this;return this.designer.config.tabs.findIndex((function(e){return e.uid===t.uid}))},get config(){var t=this;if(!this.uid)throw"Tab is missing its UID";var e=this.designer.config.tabs.find((function(e){return e.uid===t.uid}));return e||(e={uid:this.uid,elements:[]},this.config=e),e},set config(t){if(!this.destroyed){t.name&&t.name!==this.config.name&&this.$container.find(".tabs .tab span").text(t.name);var e=this.designer.config,i=this.index;if(-1!==i)e.tabs[i]=t;else{var s=$.inArray(this.$container[0],this.$container.parent().children(".fld-tab"));e.tabs.splice(s,0,t)}this.designer.config=e}},updateConfig:function(t){if(!this.destroyed){var e=t(this.config);!1!==e&&(this.config=e)}},updatePositionInConfig:function(){var t=this;this.destroyed||this.designer.updateConfig((function(e){var i=t.config,s=t.index,n=$.inArray(t.$container[0],t.$container.parent().children(".fld-tab"));return-1!==s&&e.tabs.splice(s,1),e.tabs.splice(n,0,i),e}))},destroy:function(){var t=this;if(!this.destroyed){this.destroyed=!0,this.designer.updateConfig((function(e){var i=t.index;return-1!==i&&(e.tabs.splice(i,1),e)}));for(var e=this.$container.find(".fld-element"),i=0;i<e.length;i++)e.eq(i).data("fld-element").destroy();this.designer.tabGrid.removeItems(this.$container),this.designer.tabDrag.removeItems(this.$container),this.$container.remove(),this.base()}}}),Craft.FieldLayoutDesigner.Element=Garnish.Base.extend({tab:null,$container:null,$settingsContainer:null,$editBtn:null,uid:null,isField:!1,attribute:null,requirable:!1,hasCustomWidth:!1,hasSettings:!1,settingsNamespace:null,slideout:null,init:function(t,e){var i=this;this.tab=t,this.$container=e,this.$container.data("fld-element",this),this.uid=this.$container.data("uid"),this.uid||(this.uid=Craft.uuid(),this.config=$.extend(this.$container.data("config"),{uid:this.uid})),this.isField=this.$container.hasClass("fld-field"),this.requirable=this.isField&&Garnish.hasAttr(this.$container,"data-requirable"),this.isField&&(this.attribute=this.$container.data("attribute")),this.settingsNamespace=this.$container.data("settings-namespace").replace(/\bELEMENT_UID\b/g,this.uid);var s=(this.$container.data("settings-html")||"").replace(/\bELEMENT_UID\b/g,this.uid),n=this.requirable&&this.$container.hasClass("fld-required");if(this.hasCustomWidth=this.tab.designer.settings.customizableUi&&Garnish.hasAttr(this.$container,"data-has-custom-width"),this.hasSettings=s||this.requirable,this.hasSettings){this.$settingsContainer=$("<div/>",{class:"hidden"}),this.$editBtn=$("<a/>",{role:"button",tabindex:0,class:"settings icon",title:Craft.t("app","Edit")});var a=function(){i.slideout?i.slideout.open():i.createSettings(s,n)};this.$editBtn.on("click",a),this.$container.on("dblclick",a)}this.initUi(),this.$container.attr("data-keywords",null),this.$container.attr("data-settings-html",null)},initUi:function(){var t=this;this.hasCustomWidth&&new Craft.SlidePicker(this.config.width||100,{min:25,max:100,step:25,valueLabel:function(t){return Craft.t("app","{pct} width",{pct:"".concat(t,"%")})},onChange:function(e){t.updateConfig((function(t){return t.width=e,t}))}}).$container.appendTo(this.$container),this.hasSettings&&this.$editBtn.appendTo(this.$container)},createSettings:function(t,e){var i=this,s=(this.$container.data("settings-js")||"").replace(/\bELEMENT_UID\b/g,this.uid);if(this.slideout=Craft.FieldLayoutDesigner.createSlideout(t,s),this.slideout.$container.on("submit",(function(t){t.preventDefault(),i.applySettings()})),this.requirable){var n=this.slideout.$container.find(".fields:first");Craft.ui.createLightswitchField({label:Craft.t("app","Required"),name:"".concat(this.settingsNamespace,"[required]"),on:e}).prependTo(n)}this.trigger("createSettings")},applySettings:function(){var t=this,e=this.slideout.$container.find("button[type=submit]").addClass("loading");Craft.sendActionRequest("POST","fields/apply-layout-element-settings",{data:{config:this.config,settingsNamespace:this.settingsNamespace,settings:this.slideout.$container.serialize()}}).then((function(e){t.config=e.data.config,t.$editBtn.detach(),t.$container.html($(e.data.selectorHtml).html()),t.initUi()})).catch((function(t){Craft.cp.displayError(),console.error(t)})).finally((function(){e.removeClass("loading"),t.updateRequiredClass(),t.slideout.close()}))},updateRequiredClass:function(){this.requirable&&(this.config.required?this.$container.addClass("fld-required"):this.$container.removeClass("fld-required"))},get index(){var t=this,e=this.tab.config;return void 0===e?-1:e.elements.findIndex((function(e){return e.uid===t.uid}))},get config(){var t=this;if(!this.uid)throw"Tab is missing its UID";var e=this.tab.config.elements.find((function(e){return e.uid===t.uid}));return e||(e={uid:this.uid},this.config=e),e},set config(t){var e=this.tab.config,i=this.index;if(-1!==i)e.elements[i]=t;else{var s=$.inArray(this.$container[0],this.$container.parent().children(".fld-element"));e.elements.splice(s,0,t)}this.tab.config=e},updateConfig:function(t){var e=t(this.config);!1!==e&&(this.config=e)},updatePositionInConfig:function(){var t=this;this.tab.updateConfig((function(e){var i=t.config,s=t.index,n=$.inArray(t.$container[0],t.$container.parent().children(".fld-element"));return-1!==s&&e.elements.splice(s,1),e.elements.splice(n,0,i),e}))},destroy:function(){var t=this;this.tab.updateConfig((function(e){var i=t.index;return-1!==i&&(e.elements.splice(i,1),e)})),this.tab.designer.elementDrag.removeItems(this.$container),this.$container.remove(),this.isField&&this.tab.designer.removeFieldByHandle(this.attribute),this.base()}}),Craft.FieldLayoutDesigner.BaseDrag=Garnish.Drag.extend({designer:null,$insertion:null,showingInsertion:!1,$caboose:null,init:function(t,e){this.designer=t,this.base(this.findItems(),e)},onDragStart:function(){this.base(),this.$insertion=this.createInsertion(),this.$caboose=this.createCaboose(),this.$items=$().add(this.$items.add(this.$caboose)),Garnish.$bod.addClass("dragging")},removeCaboose:function(){this.$items=this.$items.not(this.$caboose),this.$caboose.remove()},swapDraggeeWithInsertion:function(){this.$insertion.insertBefore(this.$draggee),this.$draggee.detach(),this.$items=$().add(this.$items.not(this.$draggee).add(this.$insertion)),this.showingInsertion=!0},swapInsertionWithDraggee:function(){this.$insertion.replaceWith(this.$draggee),this.$items=$().add(this.$items.not(this.$insertion).add(this.$draggee)),this.showingInsertion=!1},setMidpoints:function(){for(var t=0;t<this.$items.length;t++){var e=$(this.$items[t]),i=e.offset();e.hasClass("unused")||e.data("midpoint",{left:i.left+e.outerWidth()/2,top:i.top+e.outerHeight()/2})}},getClosestItem:function(){for(this.getClosestItem._closestItem=null,this.getClosestItem._closestItemMouseDiff=null,this.getClosestItem._i=0;this.getClosestItem._i<this.$items.length;this.getClosestItem._i++)this.getClosestItem._$item=$(this.$items[this.getClosestItem._i]),this.getClosestItem._midpoint=this.getClosestItem._$item.data("midpoint"),this.getClosestItem._midpoint&&(this.getClosestItem._mouseDiff=Garnish.getDist(this.getClosestItem._midpoint.left,this.getClosestItem._midpoint.top,this.mouseX,this.mouseY),(null===this.getClosestItem._closestItem||this.getClosestItem._mouseDiff<this.getClosestItem._closestItemMouseDiff)&&(this.getClosestItem._closestItem=this.getClosestItem._$item[0],this.getClosestItem._closestItemMouseDiff=this.getClosestItem._mouseDiff));return this.getClosestItem._closestItem},checkForNewClosestItem:function(){this.checkForNewClosestItem._closestItem=this.getClosestItem(),this.checkForNewClosestItem._closestItem!==this.$insertion[0]&&(this.showingInsertion&&$.inArray(this.$insertion[0],this.$items)<$.inArray(this.checkForNewClosestItem._closestItem,this.$items)&&-1===$.inArray(this.checkForNewClosestItem._closestItem,this.$caboose)?this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem):this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem),this.$items=$().add(this.$items.add(this.$insertion)),this.showingInsertion=!0,this.designer.tabGrid.refreshCols(!0),this.setMidpoints())},onDragStop:function(){var t=this;this.showingInsertion&&this.swapInsertionWithDraggee(),this.removeCaboose(),this.designer.tabGrid.refreshCols(!0);var e=this.$draggee.offset();!e||0===e.top&&0===e.left?(this.$draggee.css({display:this.draggeeDisplay,visibility:"visible",opacity:0}).velocity({opacity:1},Garnish.FX_DURATION),this.helpers[0].velocity({opacity:0},Garnish.FX_DURATION,(function(){t._showDraggee()}))):this.returnHelpersToDraggees(),this.base(),Garnish.$bod.removeClass("dragging")}}),Craft.FieldLayoutDesigner.TabDrag=Craft.FieldLayoutDesigner.BaseDrag.extend({init:function(t){this.base(t,{handle:".tab"})},findItems:function(){return this.designer.$tabContainer.find("> div.fld-tab")},onDragStart:function(){this.base(),this.swapDraggeeWithInsertion(),this.setMidpoints()},swapDraggeeWithInsertion:function(){this.base(),this.designer.tabGrid.removeItems(this.$draggee),this.designer.tabGrid.addItems(this.$insertion)},swapInsertionWithDraggee:function(){this.base(),this.designer.tabGrid.removeItems(this.$insertion),this.designer.tabGrid.addItems(this.$draggee)},onDrag:function(){this.checkForNewClosestItem(),this.base()},onDragStop:function(){this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:"hidden"}),this.$draggee.data("fld-tab").updatePositionInConfig()},createCaboose:function(){var t=$('<div class="fld-tab fld-tab-caboose"/>').appendTo(this.designer.$tabContainer);return this.designer.tabGrid.addItems(t),t},removeCaboose:function(){this.base(),this.designer.tabGrid.removeItems(this.$caboose)},createInsertion:function(){var t=this.$draggee.find(".tab");return $('\n<div class="fld-tab fld-insertion" style="height: '.concat(this.$draggee.height(),'px;">\n  <div class="tabs"><div class="tab sel draggable" style="width: ').concat(t.outerWidth(),"px; height: ").concat(t.outerHeight()+2,'px;"></div></div>\n  <div class="fld-tabcontent" style="height: ').concat(this.$draggee.find(".fld-tabcontent").height()-2,'px;"></div>\n</div>\n'))}}),Craft.FieldLayoutDesigner.ElementDrag=Craft.FieldLayoutDesigner.BaseDrag.extend({draggingLibraryElement:!1,draggingField:!1,originalTab:null,onDragStart:function(){this.base(),this.draggingLibraryElement=this.$draggee.hasClass("unused"),this.draggingField=this.$draggee.hasClass("fld-field"),this.draggingLibraryElement&&!this.draggingField&&this.$draggee.css({display:this.draggeeDisplay,visibility:"visible"}),this.draggingLibraryElement?this.originalTab=null:(this.originalTab=this.$draggee.closest(".fld-tab").data("fld-tab"),this.swapDraggeeWithInsertion()),this.setMidpoints()},onDrag:function(){this.isDraggeeMandatory()||this.isHoveringOverTab()?this.checkForNewClosestItem():this.showingInsertion&&(this.$insertion.remove(),this.$items=$().add(this.$items.not(this.$insertion)),this.showingInsertion=!1,this.designer.tabGrid.refreshCols(!0),this.setMidpoints()),this.base()},isDraggeeMandatory:function(){return Garnish.hasAttr(this.$draggee,"data-mandatory")},isHoveringOverTab:function(){for(var t=0;t<this.designer.tabGrid.$items.length;t++)if(Garnish.hitTest(this.mouseX,this.mouseY,this.designer.tabGrid.$items.eq(t)))return!0;return!1},findItems:function(){return this.designer.$tabContainer.find(".fld-element").add(this.designer.$sidebar.find(".fld-element"))},createCaboose:function(){for(var t=$(),e=this.designer.$tabContainer.find("> .fld-tab > .fld-tabcontent"),i=0;i<e.length;i++)t=t.add($("<div/>").appendTo(e[i]));return t},createInsertion:function(){return $('<div class="fld-element fld-insertion" style="height: '.concat(this.$draggee.outerHeight(),'px;"/>'))},onDragStop:function(){var t=this.showingInsertion;if(t){if(this.draggingLibraryElement){var e=this.$draggee.clone().removeClass("unused");this.draggingField&&(this.$draggee.css({visibility:"inherit",display:"field"}).addClass("hidden"),0===this.$draggee.siblings(".fld-field:not(.hidden)").length&&this.$draggee.closest(".fld-field-group").addClass("hidden")),this.$draggee=e,this.addItems(e)}}else if(!this.draggingLibraryElement){var i=this.draggingField?this.designer.$fields.filter('[data-attribute="'.concat(this.$draggee.data("attribute"),'"]:first')):this.designer.$uiLibraryElements.filter('[data-type="'.concat(this.$draggee.data("type"),'"]:first'));this.draggingField&&(i.removeClass("hidden"),i.closest(".fld-field-group").removeClass("hidden")),this.$draggee.data("fld-element").destroy(),this.$draggee=i}if(this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:this.draggingField||t?"hidden":"visible"}),t){var s,n=this.$draggee.closest(".fld-tab").data("fld-tab");if(this.draggingLibraryElement)s=n.initElement(this.$draggee);else if(s=this.$draggee.data("fld-element"),n!==this.originalTab){var a=s.config;this.originalTab.updateConfig((function(t){var e=s.index;return-1!==e&&(t.elements.splice(e,1),t)})),this.$draggee.data("fld-element").tab=n,s.config=a}s.updatePositionInConfig()}}})},3347:function(){Craft.FieldToggle=Garnish.Base.extend({$toggle:null,targetPrefix:null,targetSelector:null,reverseTargetSelector:null,_$target:null,_$reverseTarget:null,type:null,init:function(t){switch(this.$toggle=$(t),this.$toggle.data("fieldtoggle")&&(console.warn("Double-instantiating a field toggle on an element"),this.$toggle.data("fieldtoggle").destroy()),this.$toggle.data("fieldtoggle",this),this.type=this.getType(),"select"===this.type||"fieldset"===this.type?this.targetPrefix=this.$toggle.attr("data-target-prefix")||"":(this.targetSelector=this.normalizeTargetSelector(this.$toggle.data("target")),this.reverseTargetSelector=this.normalizeTargetSelector(this.$toggle.data("reverse-target"))),this.findTargets(),this.type){case"link":this.addListener(this.$toggle,"click","onToggleChange");break;case"fieldset":this.addListener(this.$toggle.find("input"),"change","onToggleChange");break;default:this.addListener(this.$toggle,"change","onToggleChange"),this.onToggleChange()}},normalizeTargetSelector:function(t){return t&&!t.match(/^[#\.]/)&&(t="#"+t),t},getType:function(){var t=this.$toggle.prop("nodeName");if("INPUT"===t&&"checkbox"===this.$toggle.attr("type")||"checkbox"===this.$toggle.attr("role")||"switch"===this.$toggle.attr("role"))return"checkbox";switch(t){case"SELECT":return Garnish.hasAttr(this.$toggle,"data-boolean-menu")?"booleanMenu":"select";case"A":return"link";default:return"fieldset"}},findTargets:function(){"select"===this.type||"fieldset"===this.type?(this.getToggleVal(),this._$target=$(this.normalizeTargetSelector(this.targetPrefix+this.getToggleVal()))):(this.targetSelector&&(this._$target=$(this.targetSelector)),this.reverseTargetSelector&&(this._$reverseTarget=$(this.reverseTargetSelector)))},getToggleVal:function(){switch(this.type){case"checkbox":return void 0!==this.$toggle.prop("checked")?this.$toggle.prop("checked"):"true"===this.$toggle.attr("aria-checked");case"booleanMenu":var t=this.$toggle.data("boolean");if(void 0!==t)return t;var e=this.$toggle.val();return e&&"0"!==e;default:var i;return null==(i="fieldset"===this.type?this.$toggle.find("input:checked:first").val():Garnish.getInputPostVal(this.$toggle))?null:i.replace(/[^\w]+/g,"-")}},onToggleChange:function(){"select"===this.type||"fieldset"===this.type?(this.hideTarget(this._$target),this.findTargets(),this.showTarget(this._$target)):(this.findTargets(),"link"===this.type?this.onToggleChange._show=this.$toggle.hasClass("collapsed")||!this.$toggle.hasClass("expanded"):this.onToggleChange._show=!!this.getToggleVal(),this.onToggleChange._show?(this.showTarget(this._$target),this.hideTarget(this._$reverseTarget)):(this.hideTarget(this._$target),this.showTarget(this._$reverseTarget)),delete this.onToggleChange._show)},showTarget:function(t){var e=this;if(t&&t.length){if(this.showTarget._currentHeight=t.height(),t.removeClass("hidden"),"select"!==this.type&&"fieldset"!==this.type){"link"===this.type&&(this.$toggle.removeClass("collapsed"),this.$toggle.addClass("expanded"));for(var i=0;i<t.length;i++)!function(t){"SPAN"!==t.prop("nodeName")&&(t.height("auto"),e.showTarget._targetHeight=t.height(),t.css({height:e.showTarget._currentHeight,overflow:"hidden"}),t.velocity("stop"),t.velocity({height:e.showTarget._targetHeight},"fast",(function(){t.css({height:"",overflow:""})})))}(t.eq(i));delete this.showTarget._targetHeight}delete this.showTarget._currentHeight,Garnish.$win.trigger("resize")}},hideTarget:function(t){if(t&&t.length)if("select"===this.type||"fieldset"===this.type)t.addClass("hidden");else{"link"===this.type&&(this.$toggle.removeClass("expanded"),this.$toggle.addClass("collapsed"));for(var e=0;e<t.length;e++)!function(t){t.hasClass("hidden")||("SPAN"===t.prop("nodeName")?t.addClass("hidden"):(t.css("overflow","hidden"),t.velocity("stop"),t.velocity({height:0},"fast",(function(){t.addClass("hidden")}))))}(t.eq(e))}},destroy:function(){this.$toggle.removeData("fieldtoggle"),this.base()}})},9478:function(){Craft.Grid=Garnish.Base.extend({$container:null,$items:null,items:null,totalCols:null,colGutterDrop:null,colPctWidth:null,possibleItemColspans:null,possibleItemPositionsByColspan:null,itemPositions:null,itemColspansByPosition:null,layouts:null,layout:null,itemHeights:null,leftPadding:null,_refreshingCols:!1,_refreshColsAfterRefresh:!1,_forceRefreshColsAfterRefresh:!1,init:function(t,e){var i=this;this.$container=$(t),this.$container.data("grid")&&(console.warn("Double-instantiating a grid on an element"),this.$container.data("grid").destroy()),this.$container.data("grid",this),this.setSettings(e,Craft.Grid.defaults),this.handleContainerHeightProxy=function(){i.refreshCols(!1,!0)},this.$items=this.$container.children(this.settings.itemSelector),this.setItems(),this.refreshCols(!0,!1),Garnish.$doc.ready((function(){i.refreshCols(!1,!1)}))},addItems:function(t){this.$items=$().add(this.$items.add(t)),this.setItems(),this.refreshCols(!0,!0)},removeItems:function(t){this.$items=$().add(this.$items.not(t)),this.setItems(),this.refreshCols(!0,!0)},resetItemOrder:function(){this.$items=$().add(this.$items),this.setItems(),this.refreshCols(!0,!0)},setItems:function(){for(this.setItems._={},this.items=[],this.setItems._.i=0;this.setItems._.i<this.$items.length;this.setItems._.i++)this.items.push($(this.$items[this.setItems._.i]));delete this.setItems._},refreshCols:function(t){if(this._refreshingCols)return this._refreshColsAfterRefresh=!0,void(t&&(this._forceRefreshColsAfterRefresh=!0));if(this._refreshingCols=!0,this.items.length)if(this.refreshCols._={},this.refreshCols._.oldHeight=this.$container[0].style.height,this.$container[0].style.height=1,this.refreshCols._.scrollHeight=this.$container[0].scrollHeight,this.$container[0].style.height=this.refreshCols._.oldHeight,0!==this.refreshCols._.scrollHeight)if(this.settings.cols?this.refreshCols._.totalCols=this.settings.cols:(this.refreshCols._.totalCols=Math.floor(this.$container.width()/this.settings.minColWidth),null!==this.totalCols&&this.refreshCols._.totalCols>this.totalCols&&(this.refreshCols._.totalCols=Math.floor((this.$container.width()-20)/this.settings.minColWidth)),this.settings.maxCols&&this.refreshCols._.totalCols>this.settings.maxCols&&(this.refreshCols._.totalCols=this.settings.maxCols)),0===this.refreshCols._.totalCols&&(this.refreshCols._.totalCols=1),!0===t||this.totalCols!==this.refreshCols._.totalCols){if(this.totalCols=this.refreshCols._.totalCols,this.colGutterDrop=this.settings.gutter*(this.totalCols-1)/this.totalCols,this.removeListener(this.$container,"resize"),"grid"===this.settings.fillMode)for(this.refreshCols._.itemIndex=0;this.refreshCols._.itemIndex<this.items.length;){for(this.refreshCols._.tallestItemHeight=-1,this.refreshCols._.colIndex=0,this.refreshCols._.i=this.refreshCols._.itemIndex;this.refreshCols._.i<this.refreshCols._.itemIndex+this.totalCols&&this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.refreshCols._.itemHeight=this.items[this.refreshCols._.i].height("auto").height(),this.refreshCols._.itemHeight>this.refreshCols._.tallestItemHeight&&(this.refreshCols._.tallestItemHeight=this.refreshCols._.itemHeight),this.refreshCols._.colIndex++;for(this.settings.snapToGrid&&(this.refreshCols._.remainder=this.refreshCols._.tallestItemHeight%this.settings.snapToGrid,this.refreshCols._.remainder&&(this.refreshCols._.tallestItemHeight+=this.settings.snapToGrid-this.refreshCols._.remainder)),this.refreshCols._.i=this.refreshCols._.itemIndex;this.refreshCols._.i<this.refreshCols._.itemIndex+this.totalCols&&this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.items[this.refreshCols._.i].height(this.refreshCols._.tallestItemHeight);this.refreshCols._.itemIndex+=this.totalCols}else if(this.removeListener(this.$items,"resize"),1===this.totalCols)this.$container.height("auto"),this.$items.show().css({position:"relative",width:"auto",top:0}).css(Craft.left,0);else{for(this.$items.css("position","absolute"),this.colPctWidth=100/this.totalCols,this.layouts=[],this.itemPositions=[],this.itemColspansByPosition=[],this.possibleItemColspans=[],this.possibleItemPositionsByColspan=[],this.itemHeightsByColspan=[],this.refreshCols._.item=0;this.refreshCols._.item<this.items.length;this.refreshCols._.item++)for(this.possibleItemColspans[this.refreshCols._.item]=[],this.possibleItemPositionsByColspan[this.refreshCols._.item]={},this.itemHeightsByColspan[this.refreshCols._.item]={},this.refreshCols._.$item=this.items[this.refreshCols._.item].show(),this.refreshCols._.positionRight="right"===this.refreshCols._.$item.data("position"),this.refreshCols._.positionLeft="left"===this.refreshCols._.$item.data("position"),this.refreshCols._.minColspan=this.refreshCols._.$item.data("colspan")?this.refreshCols._.$item.data("colspan"):this.refreshCols._.$item.data("min-colspan")?this.refreshCols._.$item.data("min-colspan"):1,this.refreshCols._.maxColspan=this.refreshCols._.$item.data("colspan")?this.refreshCols._.$item.data("colspan"):this.refreshCols._.$item.data("max-colspan")?this.refreshCols._.$item.data("max-colspan"):this.totalCols,this.refreshCols._.minColspan>this.totalCols&&(this.refreshCols._.minColspan=this.totalCols),this.refreshCols._.maxColspan>this.totalCols&&(this.refreshCols._.maxColspan=this.totalCols),this.refreshCols._.colspan=this.refreshCols._.minColspan;this.refreshCols._.colspan<=this.refreshCols._.maxColspan;this.refreshCols._.colspan++)for(this.refreshCols._.$item.css("width",this.getItemWidthCss(this.refreshCols._.colspan)),this.itemHeightsByColspan[this.refreshCols._.item][this.refreshCols._.colspan]=this.refreshCols._.$item.outerHeight(),this.possibleItemColspans[this.refreshCols._.item].push(this.refreshCols._.colspan),this.possibleItemPositionsByColspan[this.refreshCols._.item][this.refreshCols._.colspan]=[],this.refreshCols._.positionLeft?(this.refreshCols._.minPosition=0,this.refreshCols._.maxPosition=0):this.refreshCols._.positionRight?(this.refreshCols._.minPosition=this.totalCols-this.refreshCols._.colspan,this.refreshCols._.maxPosition=this.refreshCols._.minPosition):(this.refreshCols._.minPosition=0,this.refreshCols._.maxPosition=this.totalCols-this.refreshCols._.colspan),this.refreshCols._.position=this.refreshCols._.minPosition;this.refreshCols._.position<=this.refreshCols._.maxPosition;this.refreshCols._.position++)this.possibleItemPositionsByColspan[this.refreshCols._.item][this.refreshCols._.colspan].push(this.refreshCols._.position);for(this.refreshCols._.colHeights=[],this.refreshCols._.i=0;this.refreshCols._.i<this.totalCols;this.refreshCols._.i++)this.refreshCols._.colHeights.push(0);for(this.createLayouts(0,[],[],this.refreshCols._.colHeights,0),this.refreshCols._.layoutTotalCols=[],this.refreshCols._.i=0;this.refreshCols._.i<this.layouts.length;this.refreshCols._.i++)for(this.refreshCols._.layoutTotalCols[this.refreshCols._.i]=0,this.refreshCols._.j=0;this.refreshCols._.j<this.totalCols;this.refreshCols._.j++)this.layouts[this.refreshCols._.i].colHeights[this.refreshCols._.j]&&this.refreshCols._.layoutTotalCols[this.refreshCols._.i]++;for(this.refreshCols._.highestTotalCols=Math.max.apply(null,this.refreshCols._.layoutTotalCols),this.refreshCols._.i=this.layouts.length-1;this.refreshCols._.i>=0;this.refreshCols._.i--)this.refreshCols._.layoutTotalCols[this.refreshCols._.i]!==this.refreshCols._.highestTotalCols&&this.layouts.splice(this.refreshCols._.i,1);for(this.refreshCols._.layoutHeights=[],this.refreshCols._.i=0;this.refreshCols._.i<this.layouts.length;this.refreshCols._.i++)this.refreshCols._.layoutHeights.push(Math.max.apply(null,this.layouts[this.refreshCols._.i].colHeights));for(this.refreshCols._.shortestHeight=Math.min.apply(null,this.refreshCols._.layoutHeights),this.refreshCols._.shortestLayouts=[],this.refreshCols._.emptySpaces=[],this.refreshCols._.i=0;this.refreshCols._.i<this.refreshCols._.layoutHeights.length;this.refreshCols._.i++)if(this.refreshCols._.layoutHeights[this.refreshCols._.i]===this.refreshCols._.shortestHeight){for(this.refreshCols._.shortestLayouts.push(this.layouts[this.refreshCols._.i]),this.refreshCols._.emptySpace=this.layouts[this.refreshCols._.i].emptySpace,this.refreshCols._.j=0;this.refreshCols._.j<this.totalCols;this.refreshCols._.j++)this.refreshCols._.emptySpace+=this.refreshCols._.shortestHeight-this.layouts[this.refreshCols._.i].colHeights[this.refreshCols._.j];this.refreshCols._.emptySpaces.push(this.refreshCols._.emptySpace)}for(this.layout=this.refreshCols._.shortestLayouts[$.inArray(Math.min.apply(null,this.refreshCols._.emptySpaces),this.refreshCols._.emptySpaces)],this.refreshCols._.i=0;this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.refreshCols._.css={width:this.getItemWidthCss(this.layout.colspans[this.refreshCols._.i])},this.refreshCols._.css[Craft.left]=this.getItemLeftPosCss(this.layout.positions[this.refreshCols._.i]),this.items[this.refreshCols._.i].css(this.refreshCols._.css);this.isSimpleLayout()?(this.$container.height("auto"),this.$items.css({position:"relative",top:0,"margin-bottom":this.settings.gutter+"px"})):(this.$items.css("position","absolute"),this.positionItems(),this.addListener(this.$items,"resize","onItemResize"))}this.completeRefreshCols(),this.addListener(this.$container,"resize",this.handleContainerHeightProxy),this.onRefreshCols()}else this.completeRefreshCols();else this.completeRefreshCols();else this.completeRefreshCols()},completeRefreshCols:function(){var t=this;if(void 0!==this.refreshCols._&&delete this.refreshCols._,this._refreshingCols=!1,this._refreshColsAfterRefresh){var e=this._forceRefreshColsAfterRefresh;this._refreshColsAfterRefresh=!1,this._forceRefreshColsAfterRefresh=!1,Garnish.requestAnimationFrame((function(){t.refreshCols(e)}))}},getItemWidth:function(t){return this.colPctWidth*t},getItemWidthCss:function(t){return"calc("+this.getItemWidth(t)+"% - "+this.colGutterDrop+"px)"},getItemWidthInPx:function(t){return this.getItemWidth(t)/100*this.$container.width()-this.colGutterDrop},getItemLeftPosCss:function(t){return"calc(("+this.getItemWidth(1)+"% + "+(this.settings.gutter-this.colGutterDrop)+"px) * "+t+")"},getItemLeftPosInPx:function(t){return(this.getItemWidth(1)/100*this.$container.width()+(this.settings.gutter-this.colGutterDrop))*t},createLayouts:function(t,e,i,s,n){new Craft.Grid.LayoutGenerator(this).createLayouts(t,e,i,s,n)},isSimpleLayout:function(){for(this.isSimpleLayout._={},this.isSimpleLayout._.i=0;this.isSimpleLayout._.i<this.layout.positions.length;this.isSimpleLayout._.i++)if(0!==this.layout.positions[this.isSimpleLayout._.i])return delete this.isSimpleLayout._,!1;return delete this.isSimpleLayout._,!0},positionItems:function(){for(this.positionItems._={},this.positionItems._.colHeights=[],this.positionItems._.i=0;this.positionItems._.i<this.totalCols;this.positionItems._.i++)this.positionItems._.colHeights.push(0);for(this.positionItems._.i=0;this.positionItems._.i<this.items.length;this.positionItems._.i++){for(this.positionItems._.endingCol=this.layout.positions[this.positionItems._.i]+this.layout.colspans[this.positionItems._.i]-1,this.positionItems._.affectedColHeights=[],this.positionItems._.col=this.layout.positions[this.positionItems._.i];this.positionItems._.col<=this.positionItems._.endingCol;this.positionItems._.col++)this.positionItems._.affectedColHeights.push(this.positionItems._.colHeights[this.positionItems._.col]);for(this.positionItems._.top=Math.max.apply(null,this.positionItems._.affectedColHeights),this.positionItems._.top>0&&(this.positionItems._.top+=this.settings.gutter),this.items[this.positionItems._.i].css("top",this.positionItems._.top),this.positionItems._.col=this.layout.positions[this.positionItems._.i];this.positionItems._.col<=this.positionItems._.endingCol;this.positionItems._.col++)this.positionItems._.colHeights[this.positionItems._.col]=this.positionItems._.top+this.itemHeightsByColspan[this.positionItems._.i][this.layout.colspans[this.positionItems._.i]]}this.$container.height(Math.max.apply(null,this.positionItems._.colHeights)),delete this.positionItems._},onItemResize:function(t){this.onItemResize._={},t.stopPropagation(),this.onItemResize._.item=$.inArray(t.currentTarget,this.$items),-1!==this.onItemResize._.item&&(this.onItemResize._.newHeight=this.items[this.onItemResize._.item].outerHeight(),this.onItemResize._.newHeight!==this.itemHeightsByColspan[this.onItemResize._.item][this.layout.colspans[this.onItemResize._.item]]&&(this.itemHeightsByColspan[this.onItemResize._.item][this.layout.colspans[this.onItemResize._.item]]=this.onItemResize._.newHeight,this.positionItems(!1))),delete this.onItemResize._},onRefreshCols:function(){this.trigger("refreshCols"),this.settings.onRefreshCols()},destroy:function(){this.$container.removeData("grid"),this.base()}},{defaults:{itemSelector:".item",cols:null,maxCols:null,minColWidth:320,gutter:14,fillMode:"top",colClass:"col",snapToGrid:null,onRefreshCols:$.noop}}),Craft.Grid.LayoutGenerator=Garnish.Base.extend({grid:null,_:null,init:function(t){this.grid=t},createLayouts:function(t,e,i,s,n){for(this._={},this._.c=0;this._.c<this.grid.possibleItemColspans[t].length;this._.c++){for(this._.colspan=this.grid.possibleItemColspans[t][this._.c],this._.tallestColHeightsByPosition=[],this._.p=0;this._.p<this.grid.possibleItemPositionsByColspan[t][this._.colspan].length;this._.p++){for(this._.position=this.grid.possibleItemPositionsByColspan[t][this._.colspan][this._.p],this._.colHeightsForPosition=[],this._.endingCol=this._.position+this._.colspan-1,this._.col=this._.position;this._.col<=this._.endingCol;this._.col++)this._.colHeightsForPosition.push(s[this._.col]);this._.tallestColHeightsByPosition[this._.p]=Math.max.apply(null,this._.colHeightsForPosition)}for(this._.p=$.inArray(Math.min.apply(null,this._.tallestColHeightsByPosition),this._.tallestColHeightsByPosition),this._.position=this.grid.possibleItemPositionsByColspan[t][this._.colspan][this._.p],this._.positions=e.slice(0),this._.colspans=i.slice(0),this._.colHeights=s.slice(0),this._.emptySpace=n,this._.positions.push(this._.position),this._.colspans.push(this._.colspan),this._.tallestColHeight=this._.tallestColHeightsByPosition[this._.p],this._.endingCol=this._.position+this._.colspan-1,this._.col=this._.position;this._.col<=this._.endingCol;this._.col++)this._.emptySpace+=this._.tallestColHeight-this._.colHeights[this._.col],this._.colHeights[this._.col]=this._.tallestColHeight+this.grid.itemHeightsByColspan[t][this._.colspan];t===this.grid.items.length-1?this.grid.layouts.push({positions:this._.positions,colspans:this._.colspans,colHeights:this._.colHeights,emptySpace:this._.emptySpace}):this.grid.createLayouts(t+1,this._.positions,this._.colspans,this._.colHeights,this._.emptySpace)}delete this._}})},2387:function(){Craft.HandleGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){var e=t.replace(/<(.*?)>/g,"");e=(e=e.replace(/['"‘’“”\[\]\(\)\{\}:]/g,"")).toLowerCase(),e=Craft.asciiString(e),this.settings.allowNonAlphaStart||(e=e.replace(/^[^a-z]+/,""));var i=Craft.filterArray(e.split(/[^a-z0-9]+/));if(e="","snake"===Craft.handleCasing)return i.join("_");for(var s=0;s<i.length;s++)"pascal"!==Craft.handleCasing&&0===s?e+=i[s]:e+=i[s].charAt(0).toUpperCase()+i[s].substring(1);return e}})},7966:function(){Craft.ImageUpload=Garnish.Base.extend({$container:null,progressBar:null,uploader:null,init:function(t){this.setSettings(t,Craft.ImageUpload.defaults),this.initImageUpload()},initImageUpload:function(){this.$container=$(this.settings.containerSelector),this.progressBar=new Craft.ProgressBar($('<div class="progress-shade"></div>').appendTo(this.$container));var t={url:Craft.getActionUrl(this.settings.uploadAction),formData:this.settings.postParameters,fileInput:this.$container.find(this.settings.fileInputSelector),paramName:this.settings.uploadParamName};void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(t.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),t.events={},t.events.fileuploadstart=this._onUploadStart.bind(this),t.events.fileuploadprogressall=this._onUploadProgress.bind(this),t.events.fileuploaddone=this._onUploadComplete.bind(this),t.events.fileuploadfail=this._onUploadFailure.bind(this),this.uploader=new Craft.Uploader(this.$container,t),this.initButtons()},initButtons:function(){var t=this;this.$container.find(this.settings.uploadButtonSelector).on("click",(function(e){t.$container.find(t.settings.fileInputSelector).trigger("click")})),this.$container.find(this.settings.deleteButtonSelector).on("click",(function(e){confirm(Craft.t("app","Are you sure you want to delete this image?"))&&($(e.currentTarget).parent().append('<div class="blocking-modal"></div>'),Craft.sendActionRequest("POST",t.settings.deleteAction,{data:t.settings.postParameters}).then((function(e){var i=e.data;t.refreshImage(i)})))}))},refreshImage:function(t){$(this.settings.containerSelector).replaceWith(t.html),this.settings.onAfterRefreshImage(t),this.initImageUpload()},_onUploadStart:function(t){this.progressBar.$progressBar.css({top:Math.round(this.$container.outerHeight()/2)-6}),this.$container.addClass("uploading"),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){e.result.error?Craft.cp.displayError(e.result.error):($(e.result.html),this.refreshImage(e.result)),this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))},_onUploadFailure:function(t,e){var i,s=e.response(),n=(null==s||null===(i=s.jqXHR)||void 0===i?void 0:i.responseJSON)||{},a=n.message,r=n.filename;a||(a=r?Craft.t("app","Upload failed for “{filename}”.",{filename:r}):Craft.t("app","Upload failed.")),Craft.cp.displayError(a),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading")}},{defaults:{postParameters:{},uploadAction:"",deleteAction:"",fileInputSelector:"",onAfterRefreshImage:$.noop,containerSelector:null,uploadButtonSelector:null,deleteButtonSelector:null,uploadParamName:"files"}})},657:function(){Craft.InfoIcon=Garnish.Base.extend({$container:null,$icon:null,$liveRegion:null,content:null,hud:null,init:function(t){var e=this;if(this.$icon=$(t),this.$liveRegion=$("<span/>",{role:"status",class:"visually-hidden"}),this.$icon.data("infoicon")?(console.warn("Double-instantiating an info icon on an element"),this.content=this.$icon.data("infoicon").content,this.$icon.data("infoicon").destroy()):(this.content=this.$icon.html(),this.$icon.html("").attr({tabindex:0,role:"button",type:"button","aria-label":Craft.t("app","More info")}).wrap($("<span/>",{class:"infoicon-container"})),this.$container=this.$icon.parent(),this.$container.append(this.$liveRegion)),this.$icon.data("infoicon",this),this.$icon[0].previousSibling&&this.$icon[0].previousSibling.nodeType===Node.TEXT_NODE&&!this.$icon.parent().hasClass("nowrap")){var i=this.$icon[0].previousSibling.nodeValue.match(/[^\s\-]+\s*$/);i&&(this.$icon[0].previousSibling.nodeValue=this.$icon[0].previousSibling.nodeValue.substring(0,i.index),$("<span/>",{class:"nowrap",html:i[0].replace(/\s+$/,"")+" "}).insertAfter(this.$icon[0].previousSibling).append(this.$icon))}this.addListener(this.$icon,"click",(function(t){t.preventDefault(),t.stopPropagation(),e.showHud()})),this.addListener(this.$icon,"keydown",(function(t){e.hud&&e.hud.showing||![Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)||(t.preventDefault(),t.stopPropagation(),e.showHud())}))},showHud:function(t){var e=this;this.hud?this.hud.show():(this.hud=new Garnish.HUD(this.$icon,this.content,{hudClass:"hud info-hud",closeOtherHUDs:!1,onShow:function(){Garnish.uiLayerManager.registerShortcut(Garnish.SPACE_KEY,(function(){e.hud.hide()})),e.$liveRegion.html(""),setTimeout((function(){e.$liveRegion.html(e.content)}),200)},onHide:function(){e.$liveRegion.html("")}}),Craft.initUiElements(this.hud.$body))},destroy:function(){this.$icon.removeData("infoicon"),this.base()}})},4487:function(){Craft.LightSwitch=Garnish.Base.extend({settings:null,$outerContainer:null,$innerContainer:null,$input:null,small:!1,on:!1,indeterminate:!1,dragger:null,dragStartMargin:null,init:function(t,e){if(this.$outerContainer=$(t),this.$outerContainer.data("lightswitch")&&(console.warn("Double-instantiating a lightswitch on an element"),this.$outerContainer.data("lightswitch").destroy()),this.$outerContainer.data("lightswitch",this),this.small=this.$outerContainer.hasClass("small"),this.setSettings(e,Craft.LightSwitch.defaults),this.$innerContainer=this.$outerContainer.find(".lightswitch-container:first"),this.$input=this.$outerContainer.find("input:first"),!this.$input.prop("disabled")){this.on=this.$outerContainer.hasClass("on"),this.indeterminate=this.$outerContainer.hasClass("indeterminate"),this.addListener(this.$outerContainer,"mousedown","_onMouseDown"),this.addListener(this.$outerContainer,"keydown","_onKeyDown"),this.dragger=new Garnish.BaseDrag(this.$outerContainer,{axis:Garnish.X_AXIS,ignoreHandleSelector:null,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)});var i=this.$outerContainer.parent(".lightswitch-inner-container");i.length&&(this.addListener(i.children('span[data-toggle="off"]'),"click",this.turnOff),this.addListener(i.children('span[data-toggle="on"]'),"click",this.turnOn))}},turnOn:function(t){var e=!this.on;if(this.on=!0,this.indeterminate=!1,this.$outerContainer.addClass("dragging"),Garnish.prefersReducedMotion())this.$innerContainer.css("margin-"+Craft.left,0);else{var i={};i["margin-"+Craft.left]=0,this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this))}this.$input.val(this.settings.value),this.$outerContainer.addClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","true"),e&&!0!==t&&this.onChange()},turnOff:function(t){var e=this.on||this.indeterminate;if(this.on=!1,this.indeterminate=!1,this.$outerContainer.addClass("dragging"),Garnish.prefersReducedMotion())this.$innerContainer.css("margin-"+Craft.left,this._getOffMargin());else{var i={};i["margin-"+Craft.left]=this._getOffMargin(),this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this))}this.$input.val(""),this.$outerContainer.removeClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","false"),e&&!0!==t&&this.onChange()},turnIndeterminate:function(t){var e=!this.indeterminate;this.on=!1,this.indeterminate=!0,this.$outerContainer.addClass("dragging");var i={};i["margin-"+Craft.left]=this._getOffMargin()/2,this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this)),this.$input.val(this.settings.indeterminateValue),this.$outerContainer.removeClass("on"),this.$outerContainer.addClass("indeterminate"),this.$outerContainer.attr("aria-checked","mixed"),e&&!0!==t&&this.onChange()},toggle:function(){this.indeterminate||!this.on?this.turnOn():this.turnOff()},onChange:function(){this.trigger("change"),this.settings.onChange(this.on),this.$outerContainer.trigger("change")},_onMouseDown:function(){this.addListener(Garnish.$doc,"mouseup","_onMouseUp")},_onMouseUp:function(){this.removeListener(Garnish.$doc,"mouseup"),this.dragger.dragging||this.toggle()},_onKeyDown:function(t){switch(t.keyCode){case Garnish.SPACE_KEY:this.toggle(),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?this.turnOn():this.turnOff(),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?this.turnOff():this.turnOn(),t.preventDefault()}},_getMargin:function(){return parseInt(this.$innerContainer.css("margin-"+Craft.left))},_onDragStart:function(){this.$outerContainer.addClass("dragging"),this.dragStartMargin=this._getMargin()},_onDrag:function(){var t;(t="ltr"===Craft.orientation?this.dragStartMargin+this.dragger.mouseDistX:this.dragStartMargin-this.dragger.mouseDistX)<this._getOffMargin()?t=this._getOffMargin():t>0&&(t=0),this.$innerContainer.css("margin-"+Craft.left,t)},_onDragStop:function(){this._getMargin()>this._getOffMargin()/2?this.turnOn():this.turnOff()},_onSettle:function(){this.$outerContainer.removeClass("dragging")},destroy:function(){this.$outerContainer.removeData("lightswitch"),this.base(),this.dragger.destroy()},_getOffMargin:function(){return this.small?-10:-12}},{animationDuration:100,defaults:{value:"1",indeterminateValue:"-",onChange:$.noop}})},6966:function(){Craft.Listbox=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,selectedOptionIndex:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.Listbox.defaults),this.$container.data("listbox")&&(console.warn("Double-instantiating a listbox on an element"),this.$container.data("listbox").destroy()),this.$container.data("listbox",this),this.$options=this.$container.find("button,[role=option]"),this.$selectedOption=this.$options.filter("[aria-pressed=true],[aria-selected=true]").removeAttr("aria-selected").attr("aria-pressed","true"),this.$selectedOption.length?this.selectedOptionIndex=this.$options.index(this.$selectedOption):this.$selectedOption=null,this.addListener(this.$options,"click",(function(t){i.select(i.$options.index($(t.currentTarget))),t.preventDefault()}))},select:function(t){t<0||t>=this.$options.length||t===this.selectedOptionIndex||(this.$selectedOption&&this.$selectedOption.removeClass(this.settings.selectedClass).attr("aria-pressed","false"),this.$selectedOption=this.$options.eq(t).addClass(this.settings.selectedClass).attr("aria-pressed","true"),this.selectedOptionIndex=t,this.settings.onChange(this.$selectedOption,t),this.trigger("change",{$selectedOption:this.$selectedOption,selectedOptionIndex:t}))},disable:function(){this.base(),this.$container.attr("aria-disabled","true")},enable:function(){this.base(),this.$container.removeAttr("aria-disabled")},destroy:function(){this.$container.removeData("listbox"),this.base()}},{defaults:{selectedClass:"active",focusClass:"focus",onChange:$.noop}})},5080:function(){Craft.LivePreview=Garnish.Base.extend({$extraFields:null,$trigger:null,$shade:null,$editorContainer:null,$editor:null,$dragHandle:null,$previewContainer:null,$iframeContainer:null,$iframe:null,$fieldPlaceholder:null,previewUrl:null,token:null,basePostData:null,inPreviewMode:!1,fields:null,lastPostData:null,updateIframeInterval:null,loading:!1,checkAgain:!1,dragger:null,dragStartEditorWidth:null,_slideInOnIframeLoad:!1,_scrollX:null,_scrollY:null,_editorWidth:null,_editorWidthInPx:null,init:function(t){var e=this;this.setSettings(t,Craft.LivePreview.defaults),this.settings.previewUrl?this.previewUrl=this.settings.previewUrl:this.previewUrl=Craft.baseSiteUrl.replace(/\/+$/,"")+"/","https:"===document.location.protocol&&(this.previewUrl=this.previewUrl.replace(/^http:/,"https:")),this.basePostData=$.extend({},this.settings.previewParams),this.$extraFields=$(this.settings.extraFields),this.$trigger=$(this.settings.trigger),this.$fieldPlaceholder=$("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.LivePreview.defaultEditorWidth),this.addListener(this.$trigger,"activate","toggle"),Craft.cp.on("beforeSaveShortcut",(function(){e.inPreviewMode&&e.moveFieldsBack()})),Craft.Preview.instances.push(this)},get editorWidth(){return this._editorWidth},get editorWidthInPx(){return this._editorWidthInPx},set editorWidth(t){var e;t>=1?(e=t,t/=Garnish.$win.width()):e=Math.round(t*Garnish.$win.width()),e<Craft.LivePreview.minEditorWidthInPx&&(t=(e=Craft.LivePreview.minEditorWidthInPx)/Garnish.$win.width()),this._editorWidth=t,this._editorWidthInPx=e},toggle:function(){this.inPreviewMode?this.exit():this.enter()},enter:function(){var t=this;if(!this.inPreviewMode)if(this.token){if(this.trigger("beforeEnter"),$(document.activeElement).trigger("blur"),!this.$editor){this.$shade=$("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=$("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$iframeContainer=$("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$editorContainer=$("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=$("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=$("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=$("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);$("<div/>",{class:"flex-grow"}).appendTo(e);var s=$("<button/>",{type:"button",class:"btn submit",text:Craft.t("app","Save")}).appendTo(e);this.dragger=new Garnish.BaseDrag(this.$dragHandle,{axis:Garnish.X_AXIS,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)}),this.addListener(i,"click","exit"),this.addListener(s,"click","save")}this.handleWindowResize(),this.addListener(Garnish.$win,"resize","handleWindowResize"),this.$editorContainer.css(Craft.left,-this.editorWidthInPx+"px"),this.$previewContainer.css(Craft.right,-this.getIframeWidth()),this.fields=[];for(var n=$(this.settings.fields),a=0;a<n.length;a++){var r=$(n[a]),o=this._getClone(r);this.$fieldPlaceholder.insertAfter(r),r.detach(),this.$fieldPlaceholder.replaceWith(o),r.appendTo(this.$editor),this.fields.push({$field:r,$clone:o})}this.updateIframe()?this._slideInOnIframeLoad=!0:this.slideIn(),Craft.ElementThumbLoader.retryAll(),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.exit()})),this.inPreviewMode=!0,this.trigger("enter")}else this.createToken()},createToken:function(){var t=this,e={previewAction:this.settings.previewAction};Craft.sendActionRequest("POST","live-preview/create-token",{data:e}).then((function(e){t.token=e.data.token,t.enter()}))},save:function(){Craft.cp.submitPrimaryForm()},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){var t=this;$("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",(function(){t.trigger("slideIn"),Garnish.$win.trigger("resize")})),this.$previewContainer.show().velocity("stop").animateRight(0,"slow",(function(){t.updateIframeInterval=setInterval(t.updateIframe.bind(t),1e3)}))},exit:function(){var t=this;this.inPreviewMode&&(this.trigger("beforeExit"),$("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),Garnish.uiLayerManager.removeLayer(),this.updateIframeInterval&&clearInterval(this.updateIframeInterval),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",(function(){for(var e=0;e<t.fields.length;e++)t.fields[e].$newClone.remove();t.$editorContainer.hide(),t.trigger("slideOut")})),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",(function(){t.$previewContainer.hide()})),Craft.ElementThumbLoader.retryAll(),this.inPreviewMode=!1,this.trigger("exit"))},moveFieldsBack:function(){for(var t=0;t<this.fields.length;t++){var e=this.fields[t];e.$newClone=this._getClone(e.$field),this.$fieldPlaceholder.insertAfter(e.$field),e.$field.detach(),this.$fieldPlaceholder.replaceWith(e.$newClone),e.$clone.replaceWith(e.$field)}Garnish.$win.trigger("resize")},getIframeWidth:function(){return Garnish.$win.width()-this.editorWidthInPx},updateWidths:function(){this.$editorContainer.css("width",this.editorWidthInPx+"px"),this.$previewContainer.width(this.getIframeWidth())},updateIframe:function(t){if(t&&(this.lastPostData=null),!this.inPreviewMode)return!1;if(this.loading)return this.checkAgain=!0,!1;var e=$.extend(Garnish.getPostData(this.$editor),Garnish.getPostData(this.$extraFields));if(this.lastPostData&&Craft.compare(e,this.lastPostData,!1))return!1;this.lastPostData=e,this.loading=!0;var i=this.$iframe?$(this.$iframe[0].contentWindow.document):null;return this._scrollX=i?i.scrollLeft():0,this._scrollY=i?i.scrollTop():0,$.ajax({url:this.previewUrl+(-1!==this.previewUrl.indexOf("?")?"&":"?")+Craft.tokenParam+"="+this.token,method:"POST",data:$.extend({},e,this.basePostData),headers:{"X-Craft-Token":this.token},xhrFields:{withCredentials:!0},crossDomain:!0,success:this.handleSuccess.bind(this),error:this.handleError.bind(this)}),!0},forceUpdateIframe:function(){return this.updateIframe(!0)},handleSuccess:function(t){var e=this,i=t+'<script type="text/javascript">window.scrollTo('+this._scrollX+", "+this._scrollY+");<\/script>",s=$('<iframe class="lp-preview" frameborder="0"/>');this.$iframe?s.insertBefore(this.$iframe):s.appendTo(this.$iframeContainer),this.addListener(s,"load",(function(){this.$iframe&&this.$iframe.remove(),this.$iframe=s,this._slideInOnIframeLoad&&(this.slideIn(),this._slideInOnIframeLoad=!1),this.removeListener(s,"load")})),Garnish.requestAnimationFrame((function(){s[0].contentWindow.document.open(),s[0].contentWindow.document.write(i),s[0].contentWindow.document.close(),e.onResponse()}))},handleError:function(){this.onResponse()},onResponse:function(){this.loading=!1,this.checkAgain&&(this.checkAgain=!1,this.updateIframe())},_getClone:function(t){var e=t.clone();return Garnish.copyInputValues(t,e),e.attr("id",""),e.find("[id]").attr("id",""),e},_onDragStart:function(){this.dragStartEditorWidth=this.editorWidthInPx,this.$previewContainer.addClass("dragging")},_onDrag:function(){"ltr"===Craft.orientation?this.editorWidth=this.dragStartEditorWidth+this.dragger.mouseDistX:this.editorWidth=this.dragStartEditorWidth-this.dragger.mouseDistX,this.updateWidths()},_onDragStop:function(){this.$previewContainer.removeClass("dragging"),Craft.setLocalStorage("LivePreview.editorWidth",this.editorWidth)},destroy:function(){var t=this;Craft.Preview.instances=Craft.Preview.instances.filter((function(e){return e!==t})),this.base()}},{defaultEditorWidth:.33,minEditorWidthInPx:320,instances:[],defaults:{trigger:".livepreviewbtn",fields:null,extraFields:null,previewUrl:null,previewAction:null,previewParams:{}}}),Craft.LivePreview.init=function(t){Craft.livePreview=new Craft.LivePreview(t)}},7439:function(){Craft.PasswordInput=Garnish.Base.extend({$passwordWrapper:null,$passwordInput:null,$textInput:null,$currentInput:null,$showPasswordToggle:null,showingPassword:null,init:function(t,e){this.$passwordInput=$(t),this.$passwordWrapper=this.$passwordInput.parent(".passwordwrapper"),this.settings=$.extend({},Craft.PasswordInput.defaults,e),this.$passwordInput.data("passwordInput")&&(console.warn("Double-instantiating a password input on an element"),this.$passwordInput.data("passwordInput").destroy()),this.$passwordInput.data("passwordInput",this),this.$showPasswordToggle=$('<button type="button" class="invisible" />'),this.$showPasswordToggle.addClass("password-toggle"),this.$showPasswordToggle.insertAfter(this.$passwordInput),this.initInputFocusEvents(this.$passwordInput),this.addListener(this.$showPasswordToggle,"click","onClick"),this.hidePassword(),this.addListener(this.$passwordWrapper.closest("form"),"submit","hidePassword")},setCurrentInput:function(t){this.$currentInput&&(t.insertAfter(this.$currentInput),this.$currentInput.detach(),t.trigger("focus"),t.val(this.$currentInput.val())),this.$currentInput=t,this.addListener(this.$currentInput,"keypress,keyup,change,blur","onInputChange")},updateToggleLabel:function(t){this.$showPasswordToggle.text(t)},initInputFocusEvents:function(t){this.addListener(t,"focus",(function(){this.$passwordWrapper.addClass("focus")})),this.addListener(t,"blur",(function(){this.$passwordWrapper.removeClass("focus")}))},showPassword:function(){this.showingPassword||(this.$textInput||(this.$textInput=this.$passwordInput.clone(!0),this.$textInput.attr({type:"text",autocapitalize:"off"}),this.initInputFocusEvents(this.$textInput)),this.setCurrentInput(this.$textInput),this.updateToggleLabel(Craft.t("app","Hide")),this.showingPassword=!0)},hidePassword:function(){!1!==this.showingPassword&&(this.setCurrentInput(this.$passwordInput),this.updateToggleLabel(Craft.t("app","Show")),this.showingPassword=!1)},togglePassword:function(){this.showingPassword?this.hidePassword():this.showPassword(),this.settings.onToggleInput(this.$currentInput)},onInputChange:function(){this.$currentInput.val()?this.$showPasswordToggle.removeClass("invisible"):this.$showPasswordToggle.addClass("invisible")},onClick:function(t){if(this.$currentInput[0].setSelectionRange){var e=this.$currentInput[0].selectionStart,i=this.$currentInput[0].selectionEnd;this.togglePassword(),this.$currentInput[0].setSelectionRange(e,i)}else this.togglePassword()},destroy:function(){this.$passwordInput.removeData("passwordInput"),this.base()}},{defaults:{onToggleInput:$.noop}})},5328:function(){function t(t,i){var s="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!s){if(Array.isArray(t)||(s=function(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}(t))||i&&t&&"number"==typeof t.length){s&&(t=s);var n=0,a=function(){};return{s:a,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){s=s.call(t)},n:function(){var t=s.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==s.return||s.return()}finally{if(l)throw r}}}}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function i(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,s)}return i}function s(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?i(Object(s),!0).forEach((function(e){n(t,e,s[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):i(Object(s)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))}))}return t}function n(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function a(t){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a(t)}Craft.Preview=Garnish.Base.extend({elementEditor:null,$shade:null,$editorContainer:null,$editor:null,$spinner:null,$statusIcon:null,$dragHandle:null,$previewWrapper:null,$previewContainer:null,$previewSkipLink:null,$bumperLink:null,$notifier:null,$iframeContainer:null,$previewHeader:null,$targetBtn:null,$targetMenu:null,$deviceTypeContainer:null,$orientationBtn:null,$refreshBtn:null,$deviceMask:null,$devicePreviewContainer:null,$iframe:null,iframeLoaded:!1,$tempInput:null,$fieldPlaceholder:null,isActive:!1,isVisible:!1,activeTarget:0,animationDuration:"slow",currentDeviceType:"desktop",deviceOrientation:null,deviceWidth:"",deviceHeight:"",deviceMaskDimensions:{phone:{width:375,height:753},tablet:{width:768,height:1110}},draftId:null,url:null,fields:null,iframeHeight:null,scrollTop:null,scrollLeft:null,dragger:null,dragStartEditorWidth:null,_updateIframeProxy:null,_editorWidth:null,_editorWidthInPx:null,init:function(t){this.elementEditor=t,this._updateIframeProxy=this.updateIframe.bind(this),this.$tempInput=$("<input/>",{type:"hidden",name:"__PREVIEW_FIELDS__",value:"1"}),this.$fieldPlaceholder=$("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.Preview.defaultEditorWidth),Craft.Preview.instances.push(this)},get editorWidth(){return this._editorWidth},get editorWidthInPx(){return this._editorWidthInPx},set editorWidth(t){var e;t>=1?(e=t,t/=Garnish.$win.width()):e=Math.round(t*Garnish.$win.width()),e<Craft.Preview.minEditorWidthInPx&&(t=(e=Craft.Preview.minEditorWidthInPx)/Garnish.$win.width()),this._editorWidth=t,this._editorWidthInPx=e},open:function(){var t=this;if(!this.isActive){if(this.isActive=!0,this.trigger("beforeOpen"),$(document.activeElement).trigger("blur"),!this.$editor){var e=Craft.t("app","Skip to {title}",{title:Craft.t("app","Top of preview")});this.$shade=$("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewWrapper=$("<div/>",{role:"dialog","aria-modal":"true","aria-labelledby":"lp-preview-heading"}).appendTo(Garnish.$bod),this.$modalLabel=$("<h2/>",{id:"lp-preview-heading",class:"visually-hidden",html:Craft.t("app","Preview")}).appendTo(this.$previewWrapper),this.$editorContainer=$("<div/>",{class:"lp-editor-container"}).appendTo(this.$previewWrapper),this.$previewContainer=$("<div/>",{class:"lp-preview-container",id:"lp-preview-container"}).appendTo(this.$previewWrapper),this.$notifier=$("<span/>",{class:"visually-hidden","aria-live":"assertive"}).appendTo(this.$previewContainer);var i=$("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=$("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=$("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var s=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(i);if($("<div/>",{class:"flex-grow"}).appendTo(i),this.$spinner=$("<div/>",{class:"spinner hidden",title:Craft.t("app","Saving")}).appendTo(i),this.$statusIcon=$("<div/>",{class:"invisible"}).appendTo(i),this.$statusMessage=$("<span/>",{class:"visually-hidden","aria-live":"polite"}).appendTo(i),this.$previewSkipLink=$("<a/>",{class:"skip-link btn",href:"#lp-preview-container",html:e}).appendTo(i),Craft.Pro){if(this.$previewHeader=$("<header/>",{class:"lp-preview-header"}).appendTo(this.$previewContainer),this.elementEditor.settings.previewTargets.length>1){this.$targetBtn=$("<button/>",{type:"button",class:"btn menubtn",text:this.elementEditor.settings.previewTargets[0].label}).appendTo(this.$previewHeader),this.$targetMenu=$("<div/>",{class:"menu lp-target-menu"}).insertAfter(this.$targetBtn);for(var n,a=$("<ul/>",{class:"padded"}).appendTo(this.$targetMenu),r=0;r<this.elementEditor.settings.previewTargets.length;r++)n=$("<li/>").appendTo(a),$("<a/>",{data:{target:r},text:this.elementEditor.settings.previewTargets[r].label,class:0===r?"sel":null}).appendTo(n);new Garnish.MenuBtn(this.$targetBtn,{onOptionSelect:function(e){t.switchTarget($(e).data("target"))}}),$('<div class="flex-grow"/>').appendTo(this.$previewHeader)}this._buildDeviceTypeFieldset(),$('<div class="flex-grow"/>').appendTo(this.$previewHeader);var o=$('<div class="buttons"/>').appendTo(this.$previewHeader);this.$orientationBtn=$("<button/>",{type:"button",class:"btn disabled","data-icon":"rotate","aria-disabled":"true",text:Craft.t("app","Rotate"),"aria-label":Craft.t("app","Rotate")}).appendTo(o),this.addListener(this.$orientationBtn,"click","switchOrientation"),this.$refreshBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Refresh"),"data-icon":"refresh"}).appendTo(o),this.addListener(this.$refreshBtn,"click",(function(){t.updateIframe(!1,!0)})),this.deviceOrientation=Craft.getLocalStorage("LivePreview.orientation")}this.$iframeContainer=$("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$devicePreviewContainer=$("<div/>",{class:"lp-device-preview-container"}).appendTo(this.$iframeContainer),this.$deviceMask=$("<div/>",{class:"lp-device-mask"}).appendTo(this.$iframeContainer),this.$bumperLink=$("<a/>",{class:"skip-link btn lp-preview-container__bumper-link",html:e,href:"#lp-preview-container"}),this.$bumperLink.appendTo(this.$previewContainer),this.dragger=new Garnish.BaseDrag(this.$dragHandle,{axis:Garnish.X_AXIS,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)}),this.addListener(s,"click","close"),this.addListener(this.$statusIcon,"click",(function(){t.elementEditor.showStatusHud(t.$statusIcon)}))}this.handleWindowResize(),this.addListener(Garnish.$win,"resize","handleWindowResize"),this.$editorContainer.css(Craft.left,-this.editorWidthInPx+"px"),this.$previewContainer.css(Craft.right,-this.getIframeWidth()),this.fields=[];var l=$("#content .field").not($("#content .field .field"));if(l.length){this.$tempInput.insertBefore(l.get(0));for(var h=0;h<l.length;h++){var d=$(l[h]),c=this._getClone(d);this.$fieldPlaceholder.insertAfter(d),d.detach(),this.$fieldPlaceholder.replaceWith(c),d.appendTo(this.$editor),this.fields.push({$field:d,$clone:c})}}this.updateIframe(),this.elementEditor.on("update",this._updateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.trigger("open")}},_getDeviceTypeTranslation:function(t){var e;switch(t){case"phone":e=Craft.t("app","Mobile");break;case"tablet":e=Craft.t("app","Tablet");break;default:e=Craft.t("app","Desktop")}return e},_getDeviceOrientationTranslation:function(t){return"portrait"===t?Craft.t("app","Portrait"):Craft.t("app","Landscape")},_buildDeviceTypeFieldset:function(){var t=this;this.$deviceTypeContainer=$("<section/>",{class:"btngroup lp-device-type","aria-label":Craft.t("app","Device type")}).appendTo(this.$previewHeader),$("<button/>",{type:"button",class:"btn lp-device-type-btn--desktop active",title:Craft.t("app","Desktop"),"aria-label":Craft.t("app","Desktop"),"aria-pressed":"true",data:{width:"",height:"",deviceType:"desktop"}}).appendTo(this.$deviceTypeContainer),$("<button/>",{type:"button",class:"btn lp-device-type-btn--tablet",title:Craft.t("app","Tablet"),"aria-label":Craft.t("app","Tablet"),"aria-pressed":"false",data:{width:768,height:1024,deviceType:"tablet"}}).appendTo(this.$deviceTypeContainer),$("<button/>",{type:"button",class:"btn lp-device-type-btn--phone",title:Craft.t("app","Mobile"),"aria-label":Craft.t("app","Mobile"),"aria-pressed":"false",data:{width:375,height:667,deviceType:"phone"}}).appendTo(this.$deviceTypeContainer),this.deviceBtnGroup=new Craft.Listbox(this.$deviceTypeContainer,{onChange:function(e){t.switchDeviceType(e)}})},_activeTarget:function(){return this.elementEditor.settings.previewTargets[this.activeTarget]},_autoRefresh:function(){var t=this._activeTarget();return void 0===a(t.refresh)||!!t.refresh},switchTarget:function(t){this.activeTarget=t,this.$targetBtn.text(this.elementEditor.settings.previewTargets[t].label),this.$targetMenu.find("a.sel").removeClass("sel"),this.$targetMenu.find("a").eq(t).addClass("sel"),this.updateIframe(!0),this.trigger("switchTarget",{previewTarget:this.elementEditor.settings.previewTargets[t]})},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){var t=this;this.isActive&&!this.isVisible&&($("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,Garnish.getUserPreferredAnimationDuration(this.animationDuration),(function(){t.trigger("slideIn"),Garnish.$win.trigger("resize")})),this.$previewContainer.show().velocity("stop").animateRight(0,Garnish.getUserPreferredAnimationDuration(this.animationDuration)),this.isVisible=!0,Garnish.uiLayerManager.addLayer(this.$previewWrapper),Garnish.hideModalBackgroundLayers(),Craft.setFocusWithin(this.$previewWrapper),Craft.trapFocusWithin(this.$previewWrapper),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.close()})))},close:function(){var t=this;this.isActive&&this.isVisible&&(this.trigger("beforeClose"),$("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),Garnish.uiLayerManager.removeLayer(),Garnish.resetModalBackgroundLayerVisibility(),this.$tempInput.detach(),this.moveFieldsBack(),Garnish.prefersReducedMotion()?this.$shade.velocity("fadeOut"):this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,Garnish.getUserPreferredAnimationDuration(this.animationDuration),(function(){for(var e=0;e<t.fields.length;e++)t.fields[e].$newClone.remove();t.$editorContainer.hide(),t.trigger("slideOut")})),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),Garnish.getUserPreferredAnimationDuration(this.animationDuration),(function(){t.$iframeContainer.removeClass("lp-iframe-container--rotating"),t.$previewContainer.hide()})),this.elementEditor.off("update",this._updateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.elementEditor.$previewBtn&&this.elementEditor.$previewBtn.focus(),this.isActive=!1,this.isVisible=!1,this.trigger("close"))},moveFieldsBack:function(){for(var t=0;t<this.fields.length;t++){var e=this.fields[t];e.$newClone=this._getClone(e.$field),this.$fieldPlaceholder.insertAfter(e.$field),e.$field.detach(),this.$fieldPlaceholder.replaceWith(e.$newClone),e.$clone.replaceWith(e.$field)}Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll")},getIframeWidth:function(){return Garnish.$win.width()-this.editorWidthInPx},updateWidths:function(){this.$editorContainer.css("width",this.editorWidthInPx+"px"),this.$previewContainer.width(this.getIframeWidth()),this._devicePreviewIsActive()&&this.updateDevicePreview()},_useIframeResizer:function(){return!1!==Craft.previewIframeResizerOptions},updateIframe:function(t,e){var i=this;if(!this.isActive)return!1;t=!0===t,this.draftId===(this.draftId=this.elementEditor.settings.draftId)&&this.$iframe||(e=!0);var s=this._activeTarget();void 0===e&&(e=t||this._autoRefresh()),this.trigger("beforeUpdateIframe",{previewTarget:s,resetScroll:t,refresh:e}),e?this.elementEditor.getTokenizedPreviewUrl(s.url,"x-craft-live-preview").then((function(e){var s;t?(i.scrollTop=null,i.scrollLeft=null):i.iframeLoaded&&i.$iframe&&(i._useIframeResizer()?(i.iframeHeight=i.$iframe.height(),i.scrollTop=i.$iframeContainer.scrollTop(),i.scrollLeft=i.$iframeContainer.scrollLeft()):(s=Craft.isSameHost(e))&&i.$iframe[0].contentWindow&&(i.scrollTop=$(i.$iframe[0].contentWindow.document).scrollTop(),i.scrollLeft=$(i.$iframe[0].contentWindow.document).scrollLeft())),i.iframeLoaded=!1;var n=$("<iframe/>",{class:"lp-preview",frameborder:0,src:e,title:Craft.t("app","Preview")});i.$iframe?i.$iframe.replaceWith(n):n.appendTo(i.$devicePreviewContainer),i._useIframeResizer()?(t||null===i.iframeHeight||(n.height(i.iframeHeight),i.$iframeContainer.scrollTop(i.scrollTop),i.$iframeContainer.scrollLeft(i.scrollLeft)),iFrameResize($.extend({checkOrigin:!1,scrolling:!0,onInit:function(t){i.iframeLoaded=!0,i.iframeHeight=null,i.scrollTop=null,i.scrollLeft=null,t.scrolling="no"}},Craft.previewIframeResizerOptions||{}),n[0])):n.on("load",(function(){i.iframeLoaded=!0,!t&&s&&(null!==i.scrollTop&&$(n[0].contentWindow.document).scrollTop(i.scrollTop),null!==i.scrollLeft&&$(n[0].contentWindow.document).scrollLeft(i.scrollLeft))})),i.url=e,i.$iframe=n,i._devicePreviewIsActive()&&i.updateDevicePreview(),i.trigger("afterUpdateIframe",{previewTarget:i.elementEditor.settings.previewTargets[i.activeTarget],$iframe:i.$iframe}),i.slideIn()})):this.slideIn()},_devicePreviewIsActive:function(){return"desktop"!==this.currentDeviceType},_updateNotifier:function(){var t=this;this.$notifier.html="";var e="desktop"===this.currentDeviceType?"Previewing {type} device":"Previewing {type} device in {orientation}",i={type:this._getDeviceTypeTranslation(this.currentDeviceType)};"desktop"!==this.currentDeviceType&&(i=s(s({},i),{orientation:this._getDeviceOrientationTranslation(this.deviceOrientation)}));var n=Craft.t("app",e,i);setTimeout((function(){t.$notifier.text(n)}),200)},switchDeviceType:function(t){this.$iframeContainer.removeClass("lp-iframe-container--rotating");var e=t.data("deviceType");if(e===this.currentDeviceType)return!1;this.currentDeviceType=e,this.deviceWidth=t.data("width"),this.deviceHeight=t.data("height"),"desktop"===this.currentDeviceType?(this.$orientationBtn.addClass("disabled").attr("aria-disabled","true"),this.$iframeContainer.removeClass("lp-iframe-container--has-device-preview")):(this.$orientationBtn.removeClass("disabled").removeAttr("aria-disabled"),this.$iframeContainer.addClass("lp-iframe-container--has-device-preview")),"tablet"===this.currentDeviceType?this.$iframeContainer.addClass("lp-iframe-container--tablet"):this.$iframeContainer.removeClass("lp-iframe-container--tablet"),this._updateNotifier(),"desktop"!==this.currentDeviceType&&this.updateDevicePreview()},switchOrientation:function(){var t=this;if(!this._devicePreviewIsActive())return!1;this.deviceOrientation&&"portrait"!==this.deviceOrientation?this.deviceOrientation="portrait":this.deviceOrientation="landscape",Craft.setLocalStorage("LivePreview.orientation",this.deviceOrientation),this.$iframeContainer.addClass("lp-iframe-container--rotating"),this.updateDevicePreview(),this._updateNotifier(),setTimeout((function(){t.$iframeContainer.removeClass("lp-iframe-container--rotating")}),300)},updateDevicePreview:function(){var t=1,e=1,i=1,s=this.$previewContainer.height()-50-48,n=this.$previewContainer.width()-48,a=this.deviceMaskDimensions[this.currentDeviceType].height,r=this.deviceMaskDimensions[this.currentDeviceType].width;"landscape"===this.deviceOrientation?(n<a&&(t=n/a),s<r&&(e=s/r)):(s<a&&(t=s/a),n<r&&(e=n/r)),i=t,e<t&&(i=e);var o=-100/i/2,l="landscape"===this.deviceOrientation?"-90deg":"0deg";this.$deviceMask.css({width:this.deviceMaskDimensions[this.currentDeviceType].width+"px",height:this.deviceMaskDimensions[this.currentDeviceType].height+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%) rotate("+l+")"}),"landscape"===this.deviceOrientation?this.$devicePreviewContainer.css({width:this.deviceHeight+"px",height:this.deviceWidth+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%)",marginTop:0,marginLeft:"-"+12*i+"px"}):this.$devicePreviewContainer.css({width:this.deviceWidth+"px",height:this.deviceHeight+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%)",marginTop:"-"+12*i+"px",marginLeft:0})},_getClone:function(t){var e=t.clone();return Garnish.copyInputValues(t,e),e.attr("id",""),e.find("[id]").attr("id",""),e.find("[name]").prop("disabled",!0),e},_onDragStart:function(){this.dragStartEditorWidth=this.editorWidthInPx,this.$previewContainer.addClass("dragging")},_onDrag:function(){"ltr"===Craft.orientation?this.editorWidth=this.dragStartEditorWidth+this.dragger.mouseDistX:this.editorWidth=this.dragStartEditorWidth-this.dragger.mouseDistX,this.updateWidths()},_onDragStop:function(){this.$previewContainer.removeClass("dragging"),Craft.setLocalStorage("LivePreview.editorWidth",this.editorWidth)},destroy:function(){var t=this;Craft.Preview.instances=Craft.Preview.instances.filter((function(e){return e!==t})),this.base()}},{defaultEditorWidth:.33,minEditorWidthInPx:320,instances:[],refresh:function(){var e,i=t(Craft.Preview.instances);try{for(i.s();!(e=i.n()).done;)preview=e.value,preview.updateIframe()}catch(t){i.e(t)}finally{i.f()}var s,n=t(Craft.LivePreview.instances);try{for(n.s();!(s=n.n()).done;)preview=s.value,preview.forceUpdateIframe()}catch(t){n.e(t)}finally{n.f()}}})},6419:function(){Craft.PreviewFileModal=Garnish.Modal.extend({assetId:null,$spinner:null,$triggerElement:null,$bumperButtonStart:null,$bumperButtonEnd:null,elementSelect:null,type:null,loaded:null,requestId:0,init:function(t,e,i){var s=this;if(i=$.extend(this.defaultSettings,i),this.$triggerElement=Garnish.getFocusedElement(),i.onHide=this._onHide.bind(this),Craft.PreviewFileModal.openInstance){var n=Craft.PreviewFileModal.openInstance;return n.assetId!==t&&(n.loadAsset(t,i.startingWidth,i.startingHeight),n.elementSelect=e),this.destroy()}Craft.PreviewFileModal.openInstance=this,this.elementSelect=e,this.$container=$('<div class="modal previewmodal loading"/>').appendTo(Garnish.$bod),this.base(this.$container,$.extend({resizable:!0},i)),this.$container&&(this.$container.velocity("stop"),this.$container.show().css("opacity",1),this.$shade.velocity("stop"),this.$shade.show().css("opacity",1),Garnish.setFocusWithin(this.$container)),this.$bumperButtonStart=Craft.ui.createButton({html:Craft.t("app","Close Preview"),class:"skip-link"}),this.addListener(this.$bumperButtonStart,"click",(function(){s.hide()})),this.$bumperButtonEnd=this.$bumperButtonStart.clone(!0),this.loadAsset(t,i.startingWidth,i.startingHeight)},_onHide:function(){return Craft.PreviewFileModal.openInstance=null,this.elementSelect?this.elementSelect.focusItem(this.elementSelect.$focusedItem):this.$triggerElement&&this.$triggerElement.length&&this.$triggerElement.trigger("focus"),this.$shade.remove(),this.destroy()},_addBumperButtons:function(){this.$container.prepend(this.$bumperButtonStart).append(this.$bumperButtonEnd)},_addModalName:function(){var t="preview-heading";$("<h1/>",{class:"visually-hidden",id:t,text:Craft.t("app","Preview file")}).prependTo(this.$container),this.$container.attr("aria-labelledby",t)},selfDestruct:function(){var t=Craft.PreviewFileModal.openInstance;return t.hide(),t.$shade.remove(),t.destroy(),Craft.PreviewFileModal.openInstance=null,Craft.focalPoint.destruct(),Craft.focalPoint=null,!0},loadAsset:function(t,e,i){var s=this;this.assetId=t,this.$container.empty(),this.loaded=!1,this.desiredHeight=null,this.desiredWidth=null;var n=.66*Garnish.$win.height(),a=Math.min(n/3*4,Garnish.$win.width()-2*this.settings.minGutter);if(n=a/4*3,e&&i){var r=e/i;a=Math.min(e,Garnish.$win.width()-2*this.settings.minGutter),(a=(n=Math.min(a/r,Garnish.$win.height()-2*this.settings.minGutter))*r)>Math.min(e,Garnish.$win.width()-2*this.settings.minGutter)&&(n=(a=Math.min(e,Garnish.$win.width()-2*this.settings.minGutter))/r)}this._resizeContainer(a,n),this.$spinner=$('<div class="spinner centeralign"></div>').appendTo(this.$container);var o=this.$container.height()/2-this.$spinner.height()/2+"px",l=this.$container.width()/2-this.$spinner.width()/2+"px";this.$spinner.css({left:l,top:o,position:"absolute"}),this.requestId++;var h={assetId:t,requestId:this.requestId},d=function(){s.$container.removeClass("loading"),s.$spinner.remove(),s.loaded=!0};Craft.sendActionRequest("POST","assets/preview-file",{data:h}).then((function(t){if(d(),t.data.requestId==s.requestId){if(!t.data.previewHtml)return s.$container.addClass("zilch"),s.$container.append($("<p/>",{text:Craft.t("app","No preview available.")})),void s._addBumperButtons();s.$container.removeClass("zilch"),s.$container.attr("data-asset-id",s.assetId),s.$container.append(t.data.previewHtml),s._addBumperButtons(),s._addModalName(),Craft.appendHeadHtml(t.data.headHtml),Craft.appendBodyHtml(t.data.bodyHtml)}})).catch((function(t){var e=t.response;d(),Craft.cp.displayError(e.data.message),s.hide()}))},_resizeContainer:function(t,e){this.$container.css({width:t,"min-width":t,"max-width":t,height:e,"min-height":e,"max-height":e,top:(Garnish.$win.height()-e)/2,left:(Garnish.$win.width()-t)/2})}},{defaultSettings:{startingWidth:null,startingHeight:null}})},872:function(){Craft.ProgressBar=Garnish.Base.extend({$progressBar:null,$innerProgressBar:null,$progressBarStatus:null,_itemCount:0,_processedItemCount:0,_displaySteps:!1,init:function(t,e){e&&(this._displaySteps=!0),this.$progressBar=$('<div class="progressbar pending hidden"/>').appendTo(t),this.$innerProgressBar=$('<div class="progressbar-inner"/>').appendTo(this.$progressBar),this.$progressBarStatus=$('<div class="progressbar-status hidden" />').insertAfter(this.$progressBar),this.resetProgressBar()},resetProgressBar:function(){this.setProgressPercentage(100),this.$progressBar.addClass("pending"),this.setItemCount(1),this.setProcessedItemCount(0),this.$progressBarStatus.html(""),this._displaySteps&&this.$progressBar.addClass("has-status")},hideProgressBar:function(){this.$progressBar.addClass("hidden"),this.$progressBarStatus.addClass("hidden")},showProgressBar:function(){this.$progressBar.removeClass("hidden"),this.$progressBarStatus.removeClass("hidden")},setItemCount:function(t){this._itemCount=t},incrementItemCount:function(t){this._itemCount+=t},setProcessedItemCount:function(t){this._processedItemCount=t},incrementProcessedItemCount:function(t){this._processedItemCount+=t},updateProgressBar:function(){this._itemCount=Math.max(this._itemCount,1);var t=Math.min(100,Math.round(100*this._processedItemCount/this._itemCount));this.setProgressPercentage(t),this._displaySteps&&this.$progressBarStatus.html(this._processedItemCount+" / "+this._itemCount)},setProgressPercentage:function(t,e){0===t?this.$progressBar.addClass("pending"):(this.$progressBar.removeClass("pending"),e?this.$innerProgressBar.velocity("stop").velocity({width:t+"%"},"fast"):this.$innerProgressBar.velocity("stop").width(t+"%"))}})},1396:function(){Craft.PromptHandler=Garnish.Base.extend({modal:null,$modalContainerDiv:null,$prompt:null,$promptApplyToRemainingContainer:null,$promptApplyToRemainingCheckbox:null,$promptApplyToRemainingLabel:null,$pomptChoices:null,_prompts:[],_promptBatchCallback:$.noop,_promptBatchReturnData:[],_promptBatchNum:0,resetPrompts:function(){this._prompts=[],this._promptBatchCallback=$.noop,this._promptBatchReturnData=[],this._promptBatchNum=0},addPrompt:function(t){this._prompts.push(t)},getPromptCount:function(){return this._prompts.length},showBatchPrompts:function(t){this._promptBatchCallback=t,this._promptBatchReturnData=[],this._promptBatchNum=0,this._showNextPromptInBatch()},_showNextPromptInBatch:function(){var t=this._prompts[this._promptBatchNum].prompt,e=this._prompts.length-(this._promptBatchNum+1);this._showPrompt(t.message,t.choices,this._handleBatchPromptSelection.bind(this),e)},_handleBatchPromptSelection:function(t,e){var i=this._prompts[this._promptBatchNum],s=this._prompts.length-(this._promptBatchNum+1),n=$.extend(i,{choice:t});this._promptBatchReturnData.push(n),s?(this._promptBatchNum++,e?this._handleBatchPromptSelection(t,!0):this._showNextPromptInBatch()):"function"==typeof this._promptBatchCallback&&this._promptBatchCallback(this._promptBatchReturnData)},_showPrompt:function(t,e,i,s){this._promptCallback=i,null===this.modal&&(this.modal=new Garnish.Modal({closeOtherModals:!1})),null===this.$modalContainerDiv&&(this.$modalContainerDiv=$('<div class="modal fitted prompt-modal"></div>').addClass().appendTo(Garnish.$bod)),this.$prompt=$('<div class="body"></div>').appendTo(this.$modalContainerDiv.empty()),this.$promptMessage=$('<p class="prompt-msg"/>').appendTo(this.$prompt),this.$promptChoices=$('<div class="options"></div>').appendTo(this.$prompt),this.$promptApplyToRemainingContainer=$('<label class="assets-applytoremaining"/>').appendTo(this.$prompt).hide(),this.$promptApplyToRemainingCheckbox=$('<input type="checkbox"/>').appendTo(this.$promptApplyToRemainingContainer),this.$promptApplyToRemainingLabel=$("<span/>").appendTo(this.$promptApplyToRemainingContainer),this.$promptButtons=$('<div class="buttons right"/>').appendTo(this.$prompt),this.modal.setContainer(this.$modalContainerDiv),this.$promptMessage.html(t);for(var n=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$promptButtons),a=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","OK")}).appendTo(this.$promptButtons),r=0;r<e.length;r++){var o=$('<div><label><input type="radio" name="promptAction" value="'+e[r].value+'"/> '+e[r].title+"</label></div>").appendTo(this.$promptChoices).find("input");this.addListener(o,"click",(function(){a.removeClass("disabled")}))}this.addListener(a,"activate",(function(t){var e=$(t.currentTarget).parents(".modal").find("input[name=promptAction]:checked").val(),i=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice(e,i)})),this.addListener(n,"activate",(function(){var t=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice("cancel",t)})),s&&(this.$promptApplyToRemainingContainer.show(),this.$promptApplyToRemainingLabel.html(" "+Craft.t("app","Apply this to the {number} remaining conflicts?",{number:s}))),this.modal.show(),this.modal.removeListener(Garnish.Modal.$shade,"click"),this.addListener(Garnish.Modal.$shade,"click","_cancelPrompt")},_selectPromptChoice:function(t,e){var i=this;this.$prompt.fadeOut("fast",(function(){i.modal.hide(),i._promptCallback(t,e)}))},_cancelPrompt:function(){this._selectPromptChoice("cancel",!0)}})},8960:function(){Craft.Queue=Garnish.Base.extend({running:!1,paused:!1,pausedForVisibility:!1,jobs:null,get length(){return this.jobs.length},get isPaused(){return this.paused||this.pausedForVisibility},init:function(){var t=this;this.jobs=[],Garnish.$doc.on("visibilitychange",(function(){t.pausedForVisibility&&Craft.isVisible()&&(t.pausedForVisibility=!1,t._resume())}))},push:function(t){return this._add(t,"push")},unshift:function(t){return this._add(t,"unshift")},pause:function(){this.paused||(this.paused=!0,this.pausedForVisibility||this.trigger("pause"))},resume:function(){this.paused&&(this.paused=!1,this._resume())},_add:function(t,e){var i=this;return new Promise((function(s,n){i.jobs[e]((function(){return new Promise((function(e,i){t().then((function(t){s(t),e()})).catch((function(t){n(t),i()}))}))})),i.running||(i.trigger("beforeRun"),i.running=!0,i._exec())}))},clear:function(){this.jobs.length=0},_exec:function(){var t=this;if(!this.jobs.length)return this.running=!1,void this.trigger("afterRun");this.pausedForVisibility||Craft.isVisible()||(this.pausedForVisibility=!0,this.paused||this.trigger("pause")),this.paused||this.pausedForVisibility||(this.trigger("beforeExec"),this.jobs.shift()().finally((function(){t.trigger("afterExec"),t._exec()})))},_resume:function(){this.isPaused||(this.trigger("resume"),this._exec())}}),Craft.queue=new Craft.Queue},4070:function(){!function(t){Craft.SlidePicker=Garnish.Base.extend({min:null,max:null,totalSteps:null,value:null,label:null,describedBy:null,$container:null,$buttons:null,init:function(e,i){var s=this;this.setSettings(i,Craft.SlidePicker.defaults),this.$container=t("<div/>",{class:"slide-picker",role:"slider",tabindex:0}),this.refresh(),this.setValue(e,!1),this.addListener(this.$container,"keydown",(function(t){switch(t.keyCode){case Garnish.UP_KEY:s.setValue(s.value+s.settings.step),t.preventDefault();break;case Garnish.DOWN_KEY:s.setValue(s.value-s.settings.step),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?s.setValue(s.value+s.settings.step):s.setValue(s.value-s.settings.step),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?s.setValue(s.value-s.settings.step):s.setValue(s.value+s.settings.step),t.preventDefault();break;case Garnish.HOME_KEY:s.setValue(s.min),t.preventDefault();break;case Garnish.END_KEY:s.setValue(s.max),t.preventDefault()}}))},refresh:function(){var e=this;if(this.min=this._min(),this.max=this._max(),this.totalSteps=(this.max-this.min)/this.settings.step,this.label=this.settings.label,this.describedBy=this.settings.describedBy,!Number.isInteger(this.totalSteps))throw"Invalid SlidePicker config";this.$buttons&&this.$buttons.remove(),this.$container.attr("aria-valuemin",this.min),this.$container.attr("aria-valuemax",this.max),this.label&&this.$container.attr("aria-label",this.label),this.describedBy&&this.$container.attr("aria-describedby",this.describedBy),this.$buttons=t();for(var i=this.min;i<=this.max;i+=this.settings.step)this.$buttons=this.$buttons.add(t("<a/>",{title:this.settings.valueLabel(i),data:{value:i}}));if(this.$buttons.appendTo(this.$container),null!==this.value){var s=this.value;this.value=null,this.setValue(s,!1)}this.addListener(this.$buttons,"mouseover",(function(i){e.$buttons.removeClass("active-hover last-active-hover"),t(i.currentTarget).addClass("active-hover last-active-hover").prevAll().addClass("active-hover")})),this.addListener(this.$buttons,"mouseout",(function(){e.$buttons.removeClass("active-hover")})),this.addListener(this.$buttons,"click",(function(i){e.setValue(t.data(i.currentTarget,"value")),i.stopPropagation(),e.$container.focus()}))},setValue:function(t,e){if(t=Math.max(Math.min(t,this.max),this.min),this.value!==(this.value=t)){this.$container.attr({"aria-valuenow":this.value,"aria-valuetext":this.settings.valueLabel(this.value)}),this.$buttons.removeClass("last-active active");var i=this.$buttons.eq((this.value-this.min)/this.settings.step);i.add(i.prevAll()).addClass("active"),i.addClass("last-active"),!1!==e&&this.settings.onChange(t)}},_min:function(){return"function"==typeof this.settings.min?this.settings.min():this.settings.min},_max:function(){return"function"==typeof this.settings.max?this.settings.max():this.settings.max}},{defaults:{min:0,max:100,step:10,valueLabel:null,onChange:t.noop}})}(jQuery)},5763:function(){Craft.SlideRuleInput=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,$input:null,value:null,startPositionX:null,init:function(t,e){var i=this;this.setSettings(e,Craft.SlideRuleInput.defaultSettings),this.value=0,this.graduationsMin=-70,this.graduationsMax=70,this.slideMin=-45,this.slideMax=45,this.$container=$("#"+t),this.$overlay=$('<div class="overlay"></div>').appendTo(this.$container),this.$cursor=$('<div class="cursor"></div>').appendTo(this.$container),this.$graduations=$('<div class="graduations"></div>').appendTo(this.$container),this.$graduationsUl=$("<ul></ul>").appendTo(this.$graduations),this.$container.attr({role:"slider",tabindex:"0","aria-valuemin":this.slideMin,"aria-valuemax":this.slideMax,"aria-valuenow":"0","aria-valuetext":Craft.t("app","{num, number} {num, plural, =1{degree} other{degrees}}",{num:0})});for(var s=this.graduationsMin;s<=this.graduationsMax;s++){var n=$('<li class="graduation" data-graduation="'+s+'"><div class="label">'+s+"</div></li>").appendTo(this.$graduationsUl);s%5==0&&n.addClass("main-graduation"),0===s&&n.addClass("selected")}this.$options=this.$container.find(".graduation"),this.addListener(this.$container,"resize",this._handleResize.bind(this)),this.addListener(this.$container,"tapstart",this._handleTapStart.bind(this)),this.addListener(Garnish.$bod,"tapmove",this._handleTapMove.bind(this)),this.addListener(Garnish.$bod,"tapend",this._handleTapEnd.bind(this)),this.addListener(this.$container,"keydown",this._handleKeypress.bind(this)),setTimeout((function(){i.graduationsCalculatedWidth=10*(i.$options.length-1),i.$graduationsUl.css("left",-i.graduationsCalculatedWidth/2+i.$container.width()/2)}),50)},_handleResize:function(){var t=this.valueToPosition(this.value);this.$graduationsUl.css("left",t)},_handleKeypress:function(t){var e=parseInt(this.$container.attr("aria-valuenow"),10);switch(t.keyCode){case Garnish.UP_KEY:case Garnish.RIGHT_KEY:this.setValue(e+1);break;case Garnish.DOWN_KEY:case Garnish.LEFT_KEY:this.setValue(e-1);break;case Garnish.PAGE_UP_KEY:this.setValue(e+10);break;case Garnish.PAGE_DOWN_KEY:this.setValue(e-10);break;case Garnish.HOME_KEY:this.setValue(this.slideMin);break;case Garnish.END_KEY:this.setValue(this.slideMax)}this.onChange()},_handleTapStart:function(t,e){t.preventDefault(),this.startPositionX=e.position.x,this.startLeft=this.$graduationsUl.position().left,this.dragging=!0,this.onStart()},_handleTapMove:function(t,e){if(this.dragging){t.preventDefault();var i=this.startPositionX-e.position.x,s=this.startLeft-i,n=this.positionToValue(s);this.setValue(n),this.onChange()}},setValue:function(t){var e=this.valueToPosition(t);t<this.slideMin?(t=this.slideMin,e=this.valueToPosition(t)):t>this.slideMax&&(t=this.slideMax,e=this.valueToPosition(t)),this.$graduationsUl.css("left",e),t>=this.slideMin&&t<=this.slideMax&&(this.$options.removeClass("selected"),$.each(this.$options,(function(e,i){$(i).data("graduation")>0&&$(i).data("graduation")<=t&&$(i).addClass("selected"),$(i).data("graduation")<0&&$(i).data("graduation")>=t&&$(i).addClass("selected"),0==$(i).data("graduation")&&$(i).addClass("selected")}))),this.$container.attr({"aria-valuenow":t,"aria-valuetext":Craft.t("app","{num, number} {num, plural, =1{degree} other{degrees}}",{num:parseInt(t,10)})}),this.value=t},_handleTapEnd:function(t){this.dragging&&(t.preventDefault(),this.dragging=!1,this.onEnd())},positionToValue:function(t){var e=-1*this.graduationsMin,i=-1*(this.graduationsMin-this.graduationsMax);return(this.$graduations.width()/2+-1*t)/this.graduationsCalculatedWidth*i-e},valueToPosition:function(t){var e=-1*this.graduationsMin,i=-1*(this.graduationsMin-this.graduationsMax);return-((t+e)*this.graduationsCalculatedWidth/i-this.$graduations.width()/2)},onStart:function(){"function"==typeof this.settings.onChange&&this.settings.onStart(this)},onChange:function(){"function"==typeof this.settings.onChange&&this.settings.onChange(this)},onEnd:function(){"function"==typeof this.settings.onChange&&this.settings.onEnd(this)},defaultSettings:{onStart:$.noop,onChange:$.noop,onEnd:$.noop}})},5759:function(){!function(t){Craft.Slideout=Garnish.Base.extend({$outerContainer:null,$container:null,$shade:null,isOpen:!1,init:function(e,i){var s=this;this.setSettings(i,Craft.Slideout.defaults),Craft.useMobileStyles()||(this.$shade=t('<div class="slideout-shade"/>').appendTo(Garnish.$bod),this.settings.closeOnShadeClick&&this.addListener(this.$shade,"click",(function(t){t.stopPropagation(),s.close()}))),this.$outerContainer=t("<div/>",{class:"slideout-container hidden"}),this.$container=t("<".concat(this.settings.containerElement,"/>"),this.settings.containerAttributes).attr("data-slideout","").addClass("slideout").append(e).data("slideout",this).appendTo(this.$outerContainer),Garnish.addModalAttributes(this.$outerContainer),Craft.useMobileStyles()&&this.$container.addClass("so-mobile"),Craft.trapFocusWithin(this.$container),this.settings.autoOpen&&this.open()},open:function(){var t=this;this.isOpen||(this.setTriggerElement(document.activeElement),this._cancelTransitionListeners(),this.$shade&&this.$shade.appendTo(Garnish.$bod).show(),this.$outerContainer.appendTo(Garnish.$bod).removeClass("hidden"),Craft.useMobileStyles()?this.$container.css("top","100vh"):this.$container.css(Garnish.ltr?"left":"right","100vw"),this.$container.one("transitionend.slideout",(function(){Craft.setFocusWithin(t.$container)})),this.$shade&&(this.$shade[0].offsetWidth,this.$shade.addClass("so-visible")),this.$container[0].offsetWidth,Craft.Slideout.addPanel(this),this.enable(),Garnish.uiLayerManager.addLayer(this.$outerContainer),Garnish.hideModalBackgroundLayers(),this.settings.closeOnEsc&&Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.close()})),this.isOpen=!0,this.trigger("open"))},setTriggerElement:function(t){this.settings.triggerElement=t},close:function(){var t=this;this.isOpen&&(this.trigger("beforeClose"),this.disable(),this.isOpen=!1,this._cancelTransitionListeners(),this.$shade&&this.$shade.removeClass("so-visible").one("transitionend.slideout",(function(){t.$shade.hide()})),Craft.Slideout.removePanel(this),Garnish.uiLayerManager.removeLayer(),Garnish.resetModalBackgroundLayerVisibility(),this.$container.one("transitionend.slideout",(function(){t.$outerContainer.addClass("hidden"),t.trigger("close")})),this.settings.triggerElement&&this.settings.triggerElement.focus())},_cancelTransitionListeners:function(){this.$shade&&this.$shade.off("transitionend.slideout"),this.$container.off("transitionend.slideout")},destroy:function(){this.$shade&&(this.$shade.remove(),this.$shade=null),this.$outerContainer.remove(),this.$outerContainer=null,this.$container=null,this.base()}},{defaults:{containerElement:"div",containerAttributes:{},autoOpen:!0,closeOnEsc:!0,closeOnShadeClick:!0,triggerElement:null},openPanels:[],addPanel:function(t){Craft.Slideout.openPanels.unshift(t),Craft.useMobileStyles()?t.$container.css("top",0):Craft.Slideout.updateStyles()},removePanel:function(t){Craft.Slideout.openPanels=Craft.Slideout.openPanels.filter((function(e){return e!==t})),Craft.useMobileStyles()?t.$container.css("top","100vh"):(t.$container.css(Garnish.ltr?"left":"right","100vw"),Craft.Slideout.updateStyles())},updateStyles:function(){var t=Craft.Slideout.openPanels.length;Craft.Slideout.openPanels.forEach((function(e,i){e.$container.css(Garnish.ltr?"left":"right","".concat((t-i)/t*50,"vw"))})),0!==t?Garnish.$bod.addClass("no-scroll"):Garnish.$bod.removeClass("no-scroll")}})}(jQuery)},5185:function(){Craft.SlugGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){t=(t=t.replace(/<(.*?)>/g,"")).replace(/['"‘’“”\[\]\(\)\{\}:]/g,""),Craft.allowUppercaseInSlug||(t=t.toLowerCase()),Craft.limitAutoSlugsToAscii&&(t=Craft.asciiString(t,this.settings.charMap));var e=Craft.filterArray(XRegExp.matchChain(t,[XRegExp("[\\p{L}\\p{N}\\p{M}]+")]));return e.length?e.join(Craft.slugWordSeparator):""}})},8030:function(){Craft.Structure=Garnish.Base.extend({id:null,$container:null,state:null,structureDrag:null,init:function(t,e,i){this.id=t,this.$container=$(e),this.setSettings(i,Craft.Structure.defaults),this.$container.data("structure")&&(console.warn("Double-instantiating a structure on an element"),this.$container.data("structure").destroy()),this.$container.data("structure",this),this.state={},this.settings.storageKey&&$.extend(this.state,Craft.getLocalStorage(this.settings.storageKey,{})),void 0===this.state.collapsedElementIds&&(this.state.collapsedElementIds=[]);for(var s=this.$container.find("ul").prev(".row"),n=0;n<s.length;n++){var a=$(s[n]),r=a.parent(),o=$('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(a);-1!==$.inArray(a.children(".element").data("id"),this.state.collapsedElementIds)&&r.addClass("collapsed"),this.initToggle(o)}this.settings.sortable&&(this.structureDrag=new Craft.StructureDrag(this,this.settings.maxLevels)),this.settings.newChildUrl&&this.initNewChildMenus(this.$container.find(".add"))},initToggle:function(t){var e=this;t.on("click",(function(t){var i=$(t.currentTarget).closest("li"),s=i.children(".row").find(".element:first").data("id"),n=$.inArray(s,e.state.collapsedElementIds);i.hasClass("collapsed")?(i.removeClass("collapsed"),-1!==n&&e.state.collapsedElementIds.splice(n,1)):(i.addClass("collapsed"),-1===n&&e.state.collapsedElementIds.push(s)),e.settings.storageKey&&Craft.setLocalStorage(e.settings.storageKey,e.state)}))},initNewChildMenus:function(t){this.addListener(t,"click","onNewChildMenuClick")},onNewChildMenuClick:function(t){var e=$(t.currentTarget);if(!e.data("menubtn")){var i=e.parent().children(".element").data("id"),s=Craft.getUrl(this.settings.newChildUrl,"parentId="+i);$('<div class="menu"><ul><li><a href="'+s+'">'+Craft.t("app","New child")+"</a></li></ul></div>").insertAfter(e),new Garnish.MenuBtn(e).showMenu()}},getIndent:function(t){return Craft.Structure.baseIndent+(t-1)*Craft.Structure.nestedIndent},addElement:function(t){var e=$('<li data-level="1"/>').appendTo(this.$container),i=$('<div class="row" style="margin-'+Craft.left+": -"+Craft.Structure.baseIndent+"px; padding-"+Craft.left+": "+Craft.Structure.baseIndent+'px;">').appendTo(e);if(i.append(t),this.settings.sortable&&(i.append('<a class="move icon" title="'+Craft.t("app","Move")+'"></a>'),this.structureDrag.addItems(e)),this.settings.newChildUrl){var s=$('<a class="add icon" title="'+Craft.t("app","New child")+'"></a>').appendTo(i);this.initNewChildMenus(s)}i.css("margin-bottom",-30),i.velocity({"margin-bottom":0},"fast")},removeElement:function(t){var e,i=this,s=t.parent().parent();this.settings.sortable&&this.structureDrag.removeItems(s),s.siblings().length||(e=s.parent()),s.css("visibility","hidden").velocity({marginBottom:-s.height()},"fast",(function(){s.remove(),void 0!==e&&i._removeUl(e)}))},_removeUl:function(t){t.siblings(".row").children(".toggle").remove(),t.remove()},destroy:function(){this.$container.removeData("structure"),this.base()}},{baseIndent:8,nestedIndent:35,defaults:{storageKey:null,sortable:!1,newChildUrl:null,maxLevels:null}})},3096:function(){Craft.StructureDrag=Garnish.Drag.extend({structure:null,maxLevels:null,draggeeLevel:null,$helperLi:null,$targets:null,draggeeHeight:null,init:function(t,e){this.structure=t,this.maxLevels=e,this.$insertion=$('<li class="draginsertion"/>');var i=this.structure.$container.find("li");this.base(i,{handle:".element:first, .move:first",helper:this.getHelper.bind(this)})},getHelper:function(t){this.$helperLi=t;var e=$('<ul class="structure draghelper"/>').append(t);return t.css("padding-"+Craft.left,this.$draggee.css("padding-"+Craft.left)),t.find(".move").removeAttr("title"),e},onDragStart:function(){var t=this;this.$targets=$(),this.findTargets(this.structure.$container),this.draggeeLevel=0;var e=this.$draggee;do{this.draggeeLevel++,e=e.find("> ul > li")}while(e.length);this.draggeeHeight=this.$draggee.height(),this.$draggee.velocity({height:0},"fast",(function(){t.$draggee.addClass("hidden")})),this.base(),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.ESC_KEY&&this.cancelDrag()}))},findTargets:function(t){for(var e=t.children().not(this.$draggee),i=0;i<e.length;i++){var s=$(e[i]);this.$targets=this.$targets.add(s.children(".row")),s.hasClass("collapsed")||this.findTargets(s.children("ul"))}},onDrag:function(){for(this._.$closestTarget&&(this._.$closestTarget.removeClass("draghover"),this.$insertion.remove()),this._.$closestTarget=null,this._.closestTargetPos=null,this._.closestTargetYDiff=null,this._.closestTargetOffset=null,this._.closestTargetHeight=null,this._.i=0;this._.i<this.$targets.length&&(this._.$target=$(this.$targets[this._.i]),this._.targetOffset=this._.$target.offset(),this._.targetHeight=this._.$target.outerHeight(),this._.targetYMidpoint=this._.targetOffset.top+this._.targetHeight/2,this._.targetYDiff=Math.abs(this.mouseY-this._.targetYMidpoint),0===this._.i||this.mouseY>=this._.targetOffset.top+5&&this._.targetYDiff<this._.closestTargetYDiff);this._.i++)this._.$closestTarget=this._.$target,this._.closestTargetPos=this._.i,this._.closestTargetYDiff=this._.targetYDiff,this._.closestTargetOffset=this._.targetOffset,this._.closestTargetHeight=this._.targetHeight;if(this._.$closestTarget)if(0===this._.closestTargetPos&&this.mouseY<this._.closestTargetOffset.top+5)this.$insertion.prependTo(this.structure.$container);else if(this._.$closestTargetLi=this._.$closestTarget.parent(),this._.closestTargetLevel=this._.$closestTargetLi.data("level"),this._.closestTargetPos<this.$targets.length-1?(this._.$nextTargetLi=$(this.$targets[this._.closestTargetPos+1]).parent(),this._.nextTargetLevel=this._.$nextTargetLi.data("level")):(this._.$nextTargetLi=null,this._.nextTargetLevel=null),this._.hoveringBetweenRows=this.mouseY>=this._.closestTargetOffset.top+this._.closestTargetHeight-5,this._.$nextTargetLi&&this._.nextTargetLevel==this._.closestTargetLevel)this._.hoveringBetweenRows?(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel-1)&&this.$insertion.insertAfter(this._.$closestTargetLi):(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel)&&this._.$closestTarget.addClass("draghover");else if(this._.$nextTargetLi&&this._.nextTargetLevel>this._.closestTargetLevel)(!this.maxLevels||this.maxLevels>=this._.nextTargetLevel+this.draggeeLevel-1)&&(this._.hoveringBetweenRows?this.$insertion.insertBefore(this._.$nextTargetLi):(this._.$closestTarget.addClass("draghover"),this.$insertion.appendTo(this._.$closestTargetLi.children("ul"))));else if(this._.hoveringBetweenRows){for(this._.draggeeX=this.mouseX-this.targetItemMouseDiffX,"rtl"===Craft.orientation&&(this._.draggeeX+=this.$helperLi.width()),this._.$parentLis=this._.$closestTarget.parentsUntil(this.structure.$container,"li"),this._.$closestParentLi=null,this._.closestParentLiXDiff=null,this._.closestParentLevel=null,this._.i=0;this._.i<this._.$parentLis.length;this._.i++)this._.$parentLi=$(this._.$parentLis[this._.i]),this._.parentLiX=this._.$parentLi.offset().left,"rtl"===Craft.orientation&&(this._.parentLiX+=this._.$parentLi.width()),this._.parentLiXDiff=Math.abs(this._.parentLiX-this._.draggeeX),this._.parentLevel=this._.$parentLi.data("level"),(!this.maxLevels||this.maxLevels>=this._.parentLevel+this.draggeeLevel-1)&&(!this._.$closestParentLi||this._.parentLiXDiff<this._.closestParentLiXDiff&&(!this._.$nextTargetLi||this._.parentLevel>=this._.nextTargetLevel))&&(this._.$closestParentLi=this._.$parentLi,this._.closestParentLiXDiff=this._.parentLiXDiff,this._.closestParentLevel=this._.parentLevel);this._.$closestParentLi&&this.$insertion.insertAfter(this._.$closestParentLi)}else(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel)&&this._.$closestTarget.addClass("draghover")},cancelDrag:function(){this.$insertion.remove(),this._.$closestTarget&&this._.$closestTarget.removeClass("draghover"),this.onMouseUp()},onDragStop:function(){var t=this;if(this._.$closestTarget&&(this.$insertion.parent().length||this._.$closestTarget.hasClass("draghover"))){var e,i;if(this.$draggee.siblings().length||(e=this.$draggee.parent()),this.$insertion.parent().length){var s=this.$insertion.next().add(this.$insertion.prev());-1===$.inArray(this.$draggee[0],s)?(this.$insertion.replaceWith(this.$draggee),i=!0):(this.$insertion.remove(),i=!1)}else{var n=this._.$closestTargetLi.children("ul");if(e&&n.length&&n[0]===e[0])i=!1;else{if(n.length)this._.$closestTargetLi.hasClass("collapsed")&&this._.$closestTarget.children(".toggle").trigger("click");else{var a=$('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(this._.$closestTarget);this.structure.initToggle(a),n=$("<ul>").appendTo(this._.$closestTargetLi)}this.$draggee.appendTo(n),i=!0}}if(this._.$closestTarget.removeClass("draghover"),i){e&&this.structure._removeUl(e);var r,o=this.$draggee.parentsUntil(this.structure.$container,"li").length+1;o!=this.$draggee.data("level")&&(1==this.$draggee.data("level")?((r={})["padding-"+Craft.left]=38,this.$helperLi.velocity(r,"fast")):1==o&&((r={})["padding-"+Craft.left]=Craft.Structure.baseIndent,this.$helperLi.velocity(r,"fast")),this.setLevel(this.$draggee,o));var l=this.$draggee.children(".row").children(".element"),h={structureId:this.structure.id,elementId:l.data("id"),siteId:l.data("site-id"),prevId:this.$draggee.prev().children(".row").children(".element").data("id"),parentId:this.$draggee.parent("ul").parent("li").children(".row").children(".element").data("id")};Craft.sendActionRequest("POST","structures/move-element",{data:h}).then((function(t){Craft.cp.displaySuccess(Craft.t("app","New order saved."))}))}}this.$draggee.velocity("stop").removeClass("hidden").velocity({height:this.draggeeHeight},"fast",(function(){t.$draggee.css("height","auto")})),this.returnHelpersToDraggees(),this.base()},setLevel:function(t,e){t.data("level",e);var i=this.structure.getIndent(e),s={};s["margin-"+Craft.left]="-"+i+"px",s["padding-"+Craft.left]=i+"px",this.$draggee.children(".row").css(s);for(var n=t.children("ul").children(),a=0;a<n.length;a++)this.setLevel($(n[a]),e+1)}})},3331:function(){Craft.StructureTableSorter=Garnish.DragSort.extend({tableView:null,structureId:null,maxLevels:null,_basePadding:null,_helperMargin:null,_$firstRowCells:null,_$titleHelperCell:null,_titleHelperCellOuterWidth:null,_ancestors:null,_updateAncestorsFrame:null,_draggeeLevel:null,_draggeeLevelDelta:null,draggingLastElements:null,_loadingDraggeeLevelDelta:!1,_targetLevel:null,_targetLevelBounds:null,_positionChanged:null,init:function(t,e,i){this.tableView=t,this.structureId=this.tableView.$table.data("structure-id"),this.maxLevels=parseInt(this.tableView.$table.attr("data-max-levels")),this._basePadding=14+(this.tableView.elementIndex.actions?34:24),this._helperMargin=this.tableView.elementIndex.actions?54:0,i=$.extend({},Craft.StructureTableSorter.defaults,i,{handle:".move",collapseDraggees:!0,singleHelper:!0,helperSpacingY:2,magnetStrength:4,helper:this.getHelper.bind(this),helperLagBase:1.5,axis:Garnish.Y_AXIS}),this.base(e,i)},findDraggee:function(){var t=this;this._draggeeLevel=this._targetLevel=this.$targetItem.data("level"),this._draggeeLevelDelta=0;for(var e=$(this.$targetItem),i=this.$targetItem.next();i.length;){var s=i.data("level");if(s<=this._draggeeLevel)break;var n=s-this._draggeeLevel;n>this._draggeeLevelDelta&&(this._draggeeLevelDelta=n),e=e.add(i),i=i.next()}if(this.draggingLastElements=!i.length,this.maxLevels&&this.draggingLastElements&&this.tableView.getMorePending()){this._loadingDraggeeLevelDelta=!0;var a=this._getAjaxBaseData(this.$targetItem);Craft.sendActionRequest("POST","structures/get-element-level-delta",{data:a}).then((function(e){t._loadingDraggeeLevelDelta=!1,t.dragging&&(t._draggeeLevelDelta=e.data.delta,t.drag(!1))}))}return e},getHelper:function(t){var e=$('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),i=$('<div class="tableview"/>').appendTo(e),s=$('<table class="data"/>').appendTo(i),n=$("<tbody/>").appendTo(s);t.appendTo(n),this._$firstRowCells=this.tableView.$elementContainer.children("tr:first").children();for(var a=t.children(),r=0;r<a.length;r++){var o=$(a[r]);if(o.hasClass("checkbox-cell"))o.remove();else{var l=$(this._$firstRowCells[r]),h=l[0].getBoundingClientRect().width;l.css("width",h+"px"),o.css("width",h+"px"),Garnish.hasAttr(l,"data-titlecell")&&(this._$titleHelperCell=o,parseInt(l.css("padding-"+Craft.left)),this._titleHelperCellOuterWidth=h,o.css("padding-"+Craft.left,this._basePadding))}}return e},canInsertBefore:function(t){return!this._loadingDraggeeLevelDelta&&!1!==this._getLevelBounds(t.prev(),t)},canInsertAfter:function(t){return!this._loadingDraggeeLevelDelta&&!1!==this._getLevelBounds(t,t.next())},onDragStart:function(){this._ancestors=this._getAncestors(this.$targetItem,this.$targetItem.data("level")),this._setTargetLevelBounds(),this.tableView.maybeLoadMore(),this.base()},onDrag:function(){this.base(),this._updateIndent()},onInsertionPointChange:function(){this._setTargetLevelBounds(),this._updateAncestorsBeforeRepaint(),this.base()},onDragStop:function(){var t=this;if(this._positionChanged=!1,this.base(),this._targetLevel!=this._draggeeLevel){for(var e=this._targetLevel-this._draggeeLevel,i=0;i<this.$draggee.length;i++){var s=$(this.$draggee[i]),n=s.data("level")+e,a=this._basePadding+this._getLevelIndent(n);s.data("level",n),s.find(".element").data("level",n),s.children("[data-titlecell]:first").css("padding-"+Craft.left,a)}this._positionChanged=!0}if(this._positionChanged){for(var r=this._getAjaxBaseData(this.$draggee),o=this.$draggee.first().prev();o.length;){var l=o.data("level");if(l==this._targetLevel){r.prevId=o.data("id");break}if(l<this._targetLevel){r.parentId=o.data("id");var h=o.find("> th > .toggle");if(!h.hasClass("expanded")){h.addClass("expanded");var d=this.tableView._createSpinnerRowAfter(o);this.tableView.elementSelect&&this.tableView.elementSelect.removeItems(this.$targetItem),this.removeItems(this.$targetItem),this.$targetItem.remove(),this.tableView._totalVisible--}break}o=o.prev()}Craft.sendActionRequest("POST","structures/move-element",{data:r}).then((function(e){Craft.cp.displaySuccess(Craft.t("app","New position saved.")),t.onPositionChange(),d&&d.parent().length&&(d.remove(),t.tableView._expandElement(h,!0)),Craft.cp.runQueue()})).catch((function(e){e.response,Craft.cp.displayError(Craft.t("app","A server error occurred.")),t.tableView.elementIndex.updateElements()}))}},onSortChange:function(){this.tableView.elementSelect&&this.tableView.elementSelect.resetItemOrder(),this._positionChanged=!0,this.base()},onPositionChange:function(){var t=this;Garnish.requestAnimationFrame((function(){t.trigger("positionChange"),t.settings.onPositionChange()}))},onReturnHelpersToDraggees:function(){if(this._$firstRowCells.css("width",""),this.draggingLastElements&&this.tableView.getMorePending()){this.tableView._totalVisible+=this.newDraggeeIndexes[0]-this.oldDraggeeIndexes[0];var t=this.$draggee.last().nextAll();t.length&&(this.removeItems(t),t.remove(),this.tableView.maybeLoadMore())}this.base()},_getLevelBounds:function(t,e){if(e&&e.length?this._getLevelBounds._minLevel=e.data("level"):this._getLevelBounds._minLevel=1,t&&t.length?this._getLevelBounds._maxLevel=t.data("level")+1:this._getLevelBounds._maxLevel=1,this.maxLevels){if(1!=this._getLevelBounds._minLevel&&this._getLevelBounds._minLevel+this._draggeeLevelDelta>this.maxLevels)return!1;this._getLevelBounds._maxLevel+this._draggeeLevelDelta>this.maxLevels&&(this._getLevelBounds._maxLevel=this.maxLevels-this._draggeeLevelDelta,this._getLevelBounds._maxLevel<this._getLevelBounds._minLevel&&(this._getLevelBounds._maxLevel=this._getLevelBounds._minLevel))}return{min:this._getLevelBounds._minLevel,max:this._getLevelBounds._maxLevel}},_setTargetLevelBounds:function(){this._targetLevelBounds=this._getLevelBounds(this.$draggee.first().prev(),this.$draggee.last().next())},_updateIndent:function(t){this._updateIndent._mouseDist=this.realMouseX-this.mousedownX,"rtl"===Craft.orientation&&(this._updateIndent._mouseDist*=-1),this._updateIndent._indentationDist=Math.round(this._updateIndent._mouseDist/Craft.StructureTableSorter.LEVEL_INDENT),this._updateIndent._targetLevel=this._draggeeLevel+this._updateIndent._indentationDist,this._updateIndent._targetLevel<this._targetLevelBounds.min?(this._updateIndent._indentationDist+=this._targetLevelBounds.min-this._updateIndent._targetLevel,this._updateIndent._targetLevel=this._targetLevelBounds.min):this._updateIndent._targetLevel>this._targetLevelBounds.max&&(this._updateIndent._indentationDist-=this._updateIndent._targetLevel-this._targetLevelBounds.max,this._updateIndent._targetLevel=this._targetLevelBounds.max),this._targetLevel!==(this._targetLevel=this._updateIndent._targetLevel)&&this._updateAncestorsBeforeRepaint(),this._updateIndent._targetLevelMouseDiff=this._updateIndent._mouseDist-this._updateIndent._indentationDist*Craft.StructureTableSorter.LEVEL_INDENT,this._updateIndent._magnetImpact=Math.round(this._updateIndent._targetLevelMouseDiff/15),Math.abs(this._updateIndent._magnetImpact)>Craft.StructureTableSorter.MAX_GIVE&&(this._updateIndent._magnetImpact=(this._updateIndent._magnetImpact>0?1:-1)*Craft.StructureTableSorter.MAX_GIVE),this._updateIndent._closestLevelMagnetIndent=this._getLevelIndent(this._targetLevel)+this._updateIndent._magnetImpact,this.helpers[0].css("margin-"+Craft.left,this._updateIndent._closestLevelMagnetIndent+this._helperMargin),this._$titleHelperCell.css("width",this._titleHelperCellOuterWidth-this._updateIndent._closestLevelMagnetIndent)},_getLevelIndent:function(t){return(t-1)*Craft.StructureTableSorter.LEVEL_INDENT},_getAjaxBaseData:function(t){return{structureId:this.structureId,elementId:t.data("id"),siteId:t.find(".element:first").data("site-id")}},_getAncestors:function(t,e){if(this._getAncestors._ancestors=[],0!=e)for(this._getAncestors._level=e,this._getAncestors._$prevRow=t.prev();this._getAncestors._$prevRow.length&&!(this._getAncestors._$prevRow.data("level")<this._getAncestors._level&&(this._getAncestors._ancestors.unshift(this._getAncestors._$prevRow),this._getAncestors._level=this._getAncestors._$prevRow.data("level"),0==this._getAncestors._level));)this._getAncestors._$prevRow=this._getAncestors._$prevRow.prev();return this._getAncestors._ancestors},_updateAncestorsBeforeRepaint:function(){this._updateAncestorsFrame&&Garnish.cancelAnimationFrame(this._updateAncestorsFrame),this._updateAncestorsFrame=Garnish.requestAnimationFrame(this._updateAncestors.bind(this))},_updateAncestors:function(){for(this._updateAncestorsFrame=null,this._updateAncestors._i=0;this._updateAncestors._i<this._ancestors.length;this._updateAncestors._i++)this._updateAncestors._$ancestor=this._ancestors[this._updateAncestors._i],this._updateAncestors._$ancestor.data("descendants",this._updateAncestors._$ancestor.data("descendants")-1),0==this._updateAncestors._$ancestor.data("descendants")&&this._updateAncestors._$ancestor.find("> th > .toggle:first").remove();for(this._updateAncestors._newAncestors=this._getAncestors(this.$targetItem,this._targetLevel),this._updateAncestors._i=0;this._updateAncestors._i<this._updateAncestors._newAncestors.length;this._updateAncestors._i++)if(this._updateAncestors._$ancestor=this._updateAncestors._newAncestors[this._updateAncestors._i],this._updateAncestors._$ancestor.data("descendants",this._updateAncestors._$ancestor.data("descendants")+1),1==this._updateAncestors._$ancestor.data("descendants")){var t=this._updateAncestors._$ancestor.data("title");$('<button class="toggle expanded" type="button" aria-expanded="true" title="'+Craft.t("app","Show/hide children")+'" aria-label="'+Craft.t("app","Show {title} children",{title:t})+'"></button>').insertAfter(this._updateAncestors._$ancestor.find("> th .move:first"))}this._ancestors=this._updateAncestors._newAncestors,delete this._updateAncestors._i,delete this._updateAncestors._$ancestor,delete this._updateAncestors._newAncestors}},{HELPER_MARGIN:0,LEVEL_INDENT:44,MAX_GIVE:22,defaults:{onPositionChange:$.noop}})},53:function(){function t(t,i){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(t,i)||function(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}(t,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.TableElementIndexView=Craft.BaseElementIndexView.extend({$table:null,$tableCaption:null,$selectedSortHeader:null,$statusMessage:null,structureTableSort:null,_totalVisiblePostStructureTableDraggee:null,_morePendingPostStructureTableDraggee:!1,_broadcastListener:null,getElementContainer:function(){return this.$table=this.$container.find("table:first"),this.$table.children("tbody:first")},afterInit:function(){var t=this;this.$tableCaption=this.$table.find("caption"),this.$statusMessage=this.$table.parent().find("[data-status-message]"),this.initTableHeaders(),this.elementIndex.on("updateElements",(function(){t._updateScreenReaderStatus()})),"index"===this.elementIndex.settings.context&&"structure"===this.elementIndex.viewMode&&Garnish.hasAttr(this.$table,"data-structure-id")?this.structureTableSort=new Craft.StructureTableSorter(this,this.getAllElements()):this.structureTableSort=null,"structure"===this.elementIndex.viewMode&&this.addListener(this.$elementContainer,"click",(function(t){var e=$(t.target);e.hasClass("toggle")&&!1===this._collapseElement(e)&&this._expandElement(e)})),Craft.messageReceiver&&(this._broadcastListener=function(e){if("saveElement"===e.data.event){var i=t.$table.find('> tbody > tr[data-id="'.concat(e.data.id,'"]'));if(i.length){var s={elementType:t.elementIndex.elementType,source:t.elementIndex.sourceKey,id:e.data.id,siteId:t.elementIndex.siteId};Craft.sendActionRequest("POST","element-indexes/element-table-html",{data:s}).then((function(t){for(var e=t.data,s=0;s<i.length;s++){var n=i.eq(s);for(var a in n.find("> th[data-titlecell] .element").replaceWith(e.elementHtml),e.attributeHtml)e.attributeHtml.hasOwnProperty(a)&&n.find('> td[data-attr="'.concat(a,'"]')).html(e.attributeHtml[a])}Craft.cp.elementThumbLoader.load(i)}))}}},Craft.messageReceiver.addEventListener("message",this._broadcastListener))},initTableHeaders:function(){var e,i;if("structure"===this.elementIndex.viewMode)e="structure",i="asc";else{var s=t(this.elementIndex.getSortAttributeAndDirection(),2);e=s[0],i=s[1]}for(var n=this.$table.children("thead").children().children("[data-attribute]"),a=0;a<n.length;a++){var r=n.eq(a),o=r.attr("data-attribute"),l="none";o===e?(this.$selectedSortHeader=r,l="asc"===i?"ascending":"descending",r.addClass("ordered "+i),this.makeColumnSortable(r,!0)):this.elementIndex.getSortOption(o)&&this.makeColumnSortable(r),r.attr("aria-sort",l)}},makeColumnSortable:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];t.addClass("orderable");var i=t.html(),s=this.$tableCaption.find("[data-sort-instructions]"),n=$("<button/>",{id:"".concat(this.elementIndex.idPrefix,"-").concat(t.attr("data-attribute")),type:"button","aria-pressed":"false"}).html(i);s.length&&n.attr("aria-describedby",s.attr("id")),e?(n.attr("aria-pressed","true"),n.on("click",this._handleSelectedSortHeaderClick.bind(this))):n.on("click",this._handleUnselectedSortHeaderClick.bind(this)),t.empty().append(n)},isVerticalList:function(){return!0},getTotalVisible:function(){return this._isStructureTableDraggingLastElements()?this._totalVisiblePostStructureTableDraggee:this._totalVisible},setTotalVisible:function(t){this._isStructureTableDraggingLastElements()?this._totalVisiblePostStructureTableDraggee=t:this._totalVisible=t},getMorePending:function(){return this._isStructureTableDraggingLastElements()?this._morePendingPostStructureTableDraggee:this._morePending},setMorePending:function(t){this._isStructureTableDraggingLastElements()?this._morePendingPostStructureTableDraggee=t:this._morePending=this._morePendingPostStructureTableDraggee=t},getLoadMoreParams:function(){var t=this.base();return this._isStructureTableDraggingLastElements()&&(t.criteria.positionedAfter=this.structureTableSort.$targetItem.data("id")),t},appendElements:function(t){this.base(t),this.structureTableSort&&this.structureTableSort.addItems(t),Craft.cp.updateResponsiveTables()},_collapseElement:function(t,e){if(!e&&!t.hasClass("expanded"))return!1;t.removeClass("expanded"),t.attr("aria-expanded","false");for(var i=t.parent().parent(),s=i.data("id"),n=i.data("level"),a=i.next();a.length;){if(!Garnish.hasAttr(a,"data-spinnerrow")){if(a.data("level")<=n)break;this.elementSelect&&this.elementSelect.removeItems(a),this.structureTableSort&&this.structureTableSort.removeItems(a),this._totalVisible--}var r=a.next();a.remove(),a=r}this.elementIndex.instanceState.collapsedElementIds||(this.elementIndex.instanceState.collapsedElementIds=[]),this.elementIndex.instanceState.collapsedElementIds.push(s),this.elementIndex.setInstanceState("collapsedElementIds",this.elementIndex.instanceState.collapsedElementIds),this.maybeLoadMore()},_expandElement:function(t,e){var i=this;if(!e&&t.hasClass("expanded"))return!1;if(t.addClass("expanded"),t.attr("aria-expanded","true"),this.elementIndex.instanceState.collapsedElementIds){var s=t.parent().parent(),n=s.data("id"),a=$.inArray(n,this.elementIndex.instanceState.collapsedElementIds);if(-1!==a){this.elementIndex.instanceState.collapsedElementIds.splice(a,1),this.elementIndex.setInstanceState("collapsedElementIds",this.elementIndex.instanceState.collapsedElementIds);var r=this._createSpinnerRowAfter(s),o=$.extend(!0,{},this.settings.params);o.criteria.descendantOf=n,Craft.sendActionRequest("POST",this.settings.loadMoreElementsAction,{data:o}).then((function(t){if(r.parent().length){var e=$(t.data.html),s=i._totalVisible+e.length,n=i.settings.batchSize&&e.length===i.settings.batchSize;if(n){var a=r.nextAll();i.elementSelect&&i.elementSelect.removeItems(a),i.structureTableSort&&i.structureTableSort.removeItems(a),a.remove(),s-=a.length}else n=i._morePending;r.replaceWith(e),i.thumbLoader.load(e),(i.elementIndex.actions||i.settings.selectable)&&(i.elementSelect.addItems(e.filter(":not(.disabled)")),i.elementIndex.updateActionTriggers()),i.structureTableSort&&i.structureTableSort.addItems(e),Craft.appendHeadHtml(t.data.headHtml),Craft.appendBodyHtml(t.data.bodyHtml),Craft.cp.updateResponsiveTables(),i.setTotalVisible(s),i.setMorePending(n),i.maybeLoadMore()}})).catch((function(t){Craft.cp.displayError(),r.parent().length}))}}},_createSpinnerRowAfter:function(t){return $('<tr data-spinnerrow><td class="centeralign" colspan="'+t.children().length+'"><div class="spinner"/></td></tr>').insertAfter(t)},_isStructureTableDraggingLastElements:function(){return this.structureTableSort&&this.structureTableSort.dragging&&this.structureTableSort.draggingLastElements},_handleSelectedSortHeaderClick:function(t){var e=$(t.currentTarget).closest("th");if(!e.hasClass("loading")){var i="asc"===this.elementIndex.getSelectedSortDirection()?"desc":"asc";this.elementIndex.selectViewMode("table"),this.elementIndex.setSelectedSortDirection(i),this._handleSortHeaderClick(t,e)}},_handleUnselectedSortHeaderClick:function(t){var e=$(t.currentTarget).closest("th");if(!e.hasClass("loading")){var i=e.attr("data-attribute");this.elementIndex.selectViewMode("table"),this.elementIndex.setSelectedSortAttribute(i),this._handleSortHeaderClick(t,e)}},_handleSortHeaderClick:function(t,e){this.$selectedSortHeader&&this.$selectedSortHeader.removeClass("ordered asc desc"),e.addClass("ordered loading"),this.elementIndex.updateElements(),this.elementIndex.setIndexAvailable()},_updateScreenReaderStatus:function(){var e,i;if("structure"===this.elementIndex.viewMode)e="structure",i="asc";else{var s=t(this.elementIndex.getSortAttributeAndDirection(),2);e=s[0],i=s[1]}var n=this.elementIndex.getSortLabel(e);if(n){var a="asc"===i?Craft.t("app","Ascending"):Craft.t("app","Descending"),r=Craft.t("app","Table {name} sorted by {attribute}, {direction}",{name:this.$table.attr("data-name"),attribute:n,direction:a});this.$statusMessage.empty(),this.$statusMessage.text(r)}},_updateTableAttributes:function(t,e){var i=t.closest("tr");for(var s in e)e.hasOwnProperty(s)&&i.children('[data-attr="'+s+'"]:first').html(e[s])},destroy:function(){this._broadcastListener&&(Craft.messageReceiver.removeEventListener("message",this._broadcastListener),delete this._broadcastListener),this.base()}})},7745:function(){Craft.Tabs=Garnish.Base.extend({$container:null,$tablist:null,$menuBtn:null,$tabs:null,$firstTab:null,$lastTab:null,$selectedTab:null,$focusableTab:null,menu:null,init:function(t){var e=this;this.$container=$(t),this.$tablist=this.$container.find('> [role="tablist"]:first'),this.$tabs=this.$tablist.find('> [role="tab"]'),this.$firstTab=this.$tabs.first(),this.$lastTab=this.$tabs.last(),this.$selectedTab=this.$tabs.filter(".sel:first"),this.$focusableTab=this.$tabs.filter("[tabindex=0]:first"),this.$menuBtn=this.$container.find("> .menubtn:first").menubtn(),this.menu=this.$menuBtn.data("menubtn").menu,this.$container.data("tabs")&&(console.warn("Double-instantiating a tab manager on an element"),this.$container.data("tabs").destroy()),this.$container.data("tabs",this);for(var i=0;i<this.$tabs.length;i++){var s=this.$tabs.eq(i),n=s.attr("href");n&&"#"===n.charAt(0)&&(this.addListener(s,"keydown",(function(t){[Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)&&(t.preventDefault(),e.selectTab(t.currentTarget))})),this.addListener(s,"click",(function(t){t.preventDefault(),e.selectTab(t.currentTarget)}))),this.addListener(s,"keydown",(function(t){var i;[Garnish.LEFT_KEY,Garnish.RIGHT_KEY].includes(t.keyCode)&&$.contains(e.$tablist[0],t.currentTarget)?i=t.keyCode===("ltr"===Craft.orientation?Garnish.LEFT_KEY:Garnish.RIGHT_KEY)?(i=$(t.currentTarget).prevAll('[role="tab"]:not(.hidden):first')).length?i:e.$lastTab:(i=$(t.currentTarget).nextAll('[role="tab"]:not(.hidden):first')).length?i:e.$firstTab:t.keyCode!==Garnish.HOME_KEY&&t.keyCode!==Garnish.END_KEY||(i=t.keyCode===Garnish.HOME_KEY?e.$firstTab:e.$lastTab),i&&(t.preventDefault(),e.makeTabFocusable(i),i.focus(),e.scrollToTab(i))}))}this.updateMenuBtn(),Garnish.$win.on("resize",(function(){e.updateMenuBtn()})),this.menu.$options.on("click",(function(t){var e=$(t.currentTarget).attr("href");e&&"#"===e.charAt(0)&&t.preventDefault()})),this.menu.on("optionselect",(function(t){e.selectTab($(t.selectedOption).data("id"))}))},selectTab:function(t){var e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._getTab(t);if(i[0]!==this.$selectedTab[0]){this.deselectTab(),this.$selectedTab=i.addClass("sel").attr("aria-selected","true"),this.makeTabFocusable(i),e&&i.trigger("focus"),this.scrollToTab(i),this.menu.$options.removeClass("sel"),this.menu.$options.filter('[data-id="'.concat(i.data("id"),'"]')).addClass("sel"),this.trigger("selectTab",{$tab:i}),$("#content").trigger("scroll");var s=i.closest(".slideout-container");s.length&&s.find(".so-content").trigger("scroll")}},deselectTab:function(){var t=this.$selectedTab.removeClass("sel").attr("aria-selected","false");this.$selectedTab=null,this.trigger("deselectTab",{$tab:t})},makeTabFocusable:function(t){var e=this._getTab(t);e[0]!==this.$focusableTab[0]&&(this.$focusableTab.attr("tabindex","-1"),this.$focusableTab=e.attr("tabindex","0"))},scrollToTab:function(t){var e=this._getTab(t),i=this.$tablist.scrollLeft(),s=e.offset().left-this.$tablist.offset().left,n=!1;if(s<0)n=i+s-24;else{var a=e.outerWidth(),r=this.$tablist.prop("clientWidth");s+a>r&&(n=i+(s-(r-a))+24)}!1!==n&&this.$tablist.scrollLeft(n)},updateMenuBtn:function(){Math.floor(this.$tablist.prop("scrollWidth")-48)>this.$container.prop("clientWidth")?(this.$tablist.addClass("scrollable"),this.$menuBtn.removeClass("hidden")):(this.$tablist.removeClass("scrollable"),this.$menuBtn.addClass("hidden"))},_getTab:function(t){if(t instanceof jQuery)return t;if(t instanceof HTMLElement)return $(t);if("string"!=typeof t)throw"Invalid tab ID";var e=this.$tabs.filter('[data-id="'.concat(t,'"]'));if(!e.length)throw"Invalid tab ID: ".concat(t);return e},destroy:function(){this.$container.removeData("tabs"),this.base()}})},5074:function(){Craft.TagSelectInput=Craft.BaseElementSelectInput.extend({searchTimeout:null,searchMenu:null,$container:null,$elementsContainer:null,$elements:null,$addTagInput:null,$spinner:null,_ignoreBlur:!1,init:function(t){var e=this;if(!$.isPlainObject(t)){for(var i={},s=["id","name","tagGroupId","sourceElementId"],n=0;n<s.length&&void 0!==arguments[n];n++)i[s[n]]=arguments[n];t=i}this.base($.extend({},Craft.TagSelectInput.defaults,t)),this.$addTagInput=this.$container.children(".add").children(".text"),this.$spinner=this.$addTagInput.next(),this.addListener(this.$addTagInput,"input",(function(){e.searchTimeout&&clearTimeout(e.searchTimeout),e.searchTimeout=setTimeout(e.searchForTags.bind(e),500)})),this.addListener(this.$addTagInput,"keydown",(function(t){switch(t.keyCode===Garnish.RETURN_KEY&&t.preventDefault(),t.keyCode){case Garnish.RETURN_KEY:return t.preventDefault(),void(this.searchMenu&&this.selectTag(this.searchMenu.$options.filter(".hover")));case Garnish.DOWN_KEY:if(t.preventDefault(),this.searchMenu){var e=this.searchMenu.$options.filter(".hover");if(e.length){var i=e.parent().nextAll().find("a:not(.disabled)").first();i.length&&this.focusOption(i)}else this.focusOption(this.searchMenu.$options.eq(0))}return;case Garnish.UP_KEY:if(t.preventDefault(),this.searchMenu){var s=this.searchMenu.$options.filter(".hover");if(s.length){var n=s.parent().prevAll().find("a:not(.disabled)").last();n.length&&this.focusOption(n)}else this.focusOption(this.searchMenu.$options.eq(this.searchMenu.$options.length-1))}return}})),this.addListener(this.$addTagInput,"focus",(function(){this.searchMenu&&this.searchMenu.show()})),this.addListener(this.$addTagInput,"blur",(function(){var t=this;this._ignoreBlur?this._ignoreBlur=!1:setTimeout((function(){t.searchMenu&&t.searchMenu.hide()}),1)}))},focusOption:function(t){this.searchMenu.$options.removeClass("hover"),t.addClass("hover"),this.searchMenu.$menuList.attr("aria-activedescendant",t.attr("id"))},getAddElementsBtn:$.noop,getElementSortAxis:function(){return null},searchForTags:function(){var t=this;if(this.searchMenu&&this.killSearchMenu(),this.$addTagInput.val()){this.$spinner.removeClass("hidden");for(var e=[],i=0;i<this.$elements.length;i++){var s=$(this.$elements[i]).data("id");s&&e.push(s)}this.settings.sourceElementId&&!this.settings.allowSelfRelations&&e.push(this.settings.sourceElementId);var n={search:this.$addTagInput.val(),tagGroupId:this.settings.tagGroupId,excludeIds:e};Craft.sendActionRequest("POST","tags/search-for-tags",{data:n}).then((function(e){t.searchMenu&&t.killSearchMenu(),t.$spinner.addClass("hidden");for(var i,s=$('<div class="menu tagmenu"/>').appendTo(Garnish.$bod),a=$("<ul/>").appendTo(s),r=0;r<e.data.tags.length;r++)i=$("<li/>").appendTo(a),$('<a data-icon="tag"/>').appendTo(i).text(e.data.tags[r].title).data("id",e.data.tags[r].id).addClass(e.data.tags[r].exclude?"disabled":"");e.data.exactMatch||(i=$("<li/>").appendTo(a),$('<a data-icon="plus"/>').appendTo(i).text(n.search)),a.find("a:not(.disabled):first").addClass("hover"),t.searchMenu=new Garnish.Menu(s,{attachToElement:t.$addTagInput,onOptionSelect:t.selectTag.bind(t)}),t.addListener(s,"mousedown",(function(){t._ignoreBlur=!0})),t.searchMenu.show()})).catch((function(e){e.response,t.searchMenu&&t.killSearchMenu(),t.$spinner.addClass("hidden")}))}else this.$spinner.addClass("hidden")},selectTag:function(t){var e=this,i=$(t);if(!i.hasClass("disabled")){var s=i.data("id"),n=i.text(),a=$("<div/>",{class:"element small removable","data-id":s,"data-site-id":this.settings.targetSiteId,"data-label":n,"data-editable":"1"}).appendTo(this.$elementsContainer),r=$("<input/>",{type:"hidden",name:this.settings.name+"[]",value:s}).appendTo(a);$("<button/>",{class:"delete icon",title:Craft.t("app","Remove"),type:"button","aria-label":Craft.t("app","Remove {label}",{label:n})}).appendTo(a);var o=$("<div/>",{class:"label"}).appendTo(a);if($("<span/>",{class:"title",text:n}).appendTo(o),this.$elements=this.$elements.add(a),this.addElements(a),this.killSearchMenu(),this.$addTagInput.val(""),this.$addTagInput.trigger("focus"),!s){a.addClass("loading disabled");var l={groupId:this.settings.tagGroupId,title:n};Craft.sendActionRequest("POST","tags/create-tag",{data:l}).then((function(t){a.attr("data-id",t.data.id),r.val(t.data.id),a.removeClass("loading disabled")})).catch((function(t){t.response,e.removeElement(a),Craft.cp.displayError(Craft.t("app","A server error occurred."))}))}}},killSearchMenu:function(){this.searchMenu.hide(),this.searchMenu.destroy(),this.searchMenu=null}},{defaults:{tagGroupId:null}})},3958:function(){Craft.ThumbsElementIndexView=Craft.BaseElementIndexView.extend({getElementContainer:function(){return this.$container.children("ul")}})},1592:function(){Craft.ui={createButton:function(t){var e=$("<button/>",{type:t.type||"button",class:"btn"});return t.id&&e.attr("id",t.id),t.class&&e.addClass(t.class),t.ariaLabel&&e.attr("aria-label",t.ariaLabel),t.role&&e.attr("role",t.role),t.html?e.html(t.html):t.label?e.append($('<div class="label"/>').text(t.label)):e.addClass("btn-empty"),t.toggle&&e.attr("aria-expanded","false"),t.controls&&e.attr("aria-controls",t.controls),t.spinner&&e.append($('<div class="spinner spinner-absolute"/>')),e},createSubmitButton:function(t){var e=this.createButton(Object.assign({},t,{type:"submit",label:t.label||Craft.t("app","Submit")}));return e.addClass("submit"),e},createTextInput:function(t){t=$.extend({autocomplete:!1},t);var e=$("<input/>",{attr:{class:"text",type:t.type||"text",inputmode:t.inputmode,id:t.id,size:t.size,name:t.name,value:t.value,maxlength:t.maxlength,autofocus:this.getAutofocusValue(t.autofocus),autocomplete:"boolean"==typeof t.autocomplete?t.autocomplete?"on":"off":t.autocomplete,disabled:this.getDisabledValue(t.disabled),readonly:t.readonly,title:t.title,placeholder:t.placeholder,step:t.step,min:t.min,max:t.max}});return t.class&&e.addClass(t.class),t.placeholder&&e.addClass("nicetext"),"password"===t.type&&e.addClass("password"),t.disabled&&e.addClass("disabled"),t.size||e.addClass("fullwidth"),t.showCharsLeft&&t.maxlength&&e.attr("data-show-chars-left").css("padding-"+("ltr"===Craft.orientation?"right":"left"),7.2*t.maxlength.toString().length+14+"px"),(t.placeholder||t.showCharsLeft)&&new Garnish.NiceText(e),"password"===t.type?$('<div class="passwordwrapper"/>').append(e):e},createTextField:function(t){return t.id||(t.id="text"+Math.floor(1e9*Math.random())),this.createField(this.createTextInput(t),t)},createCopyTextInput:function(t){var e=t.id||"copytext"+Math.floor(1e9*Math.random()),i=t.buttonId||"".concat(e,"-btn"),s=$("<div/>",{class:"copytext"}),n=this.createTextInput($.extend({},t,{readonly:!0})).appendTo(s);return $("<button/>",{type:"button",id:i,class:"btn","data-icon":"clipboard",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard")}).appendTo(s).on("click",(function(){n[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),s.trigger("copy"),n[0].setSelectionRange(0,0)})),s},createCopyTextBtn:function(t){var e=t.id||"copytext"+Math.floor(1e9*Math.random()),i=t.value,s=$("<div/>",{id:e,class:"copytextbtn",role:"button",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard"),tabindex:"0"});t.class&&s.addClass(t.class);var n=$("<input/>",{value:i,readonly:!0,size:i.length,tabindex:"-1"}).appendTo(s),a=($("<span/>",{"data-icon":"clipboard","aria-hidden":"true"}).appendTo(s),function(){n[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),s.trigger("copy"),n[0].setSelectionRange(0,0),s.focus()});return s.on("click",(function(){a()})),s.on("keydown",(function(t){t.keyCode===Garnish.SPACE_KEY&&(a(),t.preventDefault())})),s},createCopyTextField:function(t){return t.id||(t.id="copytext"+Math.floor(1e9*Math.random())),this.createField(this.createCopyTextInput(t),t)},createCopyTextPrompt:function(t){var e=$("<div/>",{class:"modal fitted"}),i=$("<div/>",{class:"body"}).appendTo(e);this.createCopyTextField($.extend({size:Math.max(Math.min(t.value.length,50),25)},t)).appendTo(i);var s=i.find("label");s.length>0&&s.attr("id")&&e.attr("aria-labelledby",s.attr("id"));var n=new Garnish.Modal(e,{closeOtherModals:!1});return e.on("copy",(function(){n.hide()})),e},createTextarea:function(t){var e=$("<textarea/>",{class:"text",rows:t.rows||2,cols:t.cols||50,id:t.id,name:t.name,maxlength:t.maxlength,autofocus:t.autofocus&&!Garnish.isMobileBrowser(!0),disabled:!!t.disabled,placeholder:t.placeholder,html:t.value});return t.showCharsLeft&&e.attr("data-show-chars-left",""),t.class&&e.addClass(t.class),t.size||e.addClass("fullwidth"),e},createTextareaField:function(t){return t.id||(t.id="textarea"+Math.floor(1e9*Math.random())),this.createField(this.createTextarea(t),t)},createSelect:function(t){var e=$("<div/>",{class:"select"});t.class&&e.addClass(t.class);var i=$("<select/>",{id:t.id,name:t.name,autofocus:t.autofocus&&Garnish.isMobileBrowser(!0),disabled:t.disabled,"data-target-prefix":t.targetPrefix,"aria-labelledby":t.labelledBy}).appendTo(e);if($.isPlainObject(t.options)){var s=[];for(var n in t.options)if(t.options.hasOwnProperty(n)){var a=t.options[n];$.isPlainObject(a)?void 0!==a.optgroup?s.push(a):s.push({label:a.label,value:void 0!==a.value?a.value:n,disabled:void 0!==a.disabled&&a.disabled}):s.push({label:a,value:n})}t.options=s}for(var r=null,o=0;o<t.options.length;o++){var l=t.options[o];void 0!==l.optgroup?r=$("<optgroup/>",{label:l.label}).appendTo(i):$("<option/>",{value:l.value,selected:l.value==t.value,disabled:void 0!==l.disabled&&l.disabled,html:l.label}).appendTo(r||i)}return t.toggle&&(i.addClass("fieldtoggle"),new Craft.FieldToggle(i)),e},createSelectField:function(t){return t.id||(t.id="select"+Math.floor(1e9*Math.random())),this.createField(this.createSelect(t),t)},createCheckbox:function(t){var e=t.id||"checkbox"+Math.floor(1e9*Math.random()),i=$("<input/>",{type:"checkbox",value:void 0!==t.value?t.value:"1",id:e,class:"checkbox",name:t.name,checked:t.checked?"checked":null,autofocus:this.getAutofocusValue(t.autofocus),disabled:this.getDisabledValue(t.disabled),"data-target":t.toggle,"data-reverse-target":t.reverseToggle});t.class&&i.addClass(t.class),(t.toggle||t.reverseToggle)&&(i.addClass("fieldtoggle"),new Craft.FieldToggle(i));var s=$("<label/>",{for:e,html:t.label});return t.name&&(t.name.length<3||"[]"!==t.name.slice(-2))?$([$("<input/>",{type:"hidden",name:t.name,value:""})[0],i[0],s[0]]):$([i[0],s[0]])},createCheckboxField:function(t){t.id||(t.id="checkbox"+Math.floor(1e9*Math.random()));var e=$('<div class="field checkboxfield"/>',{id:"".concat(t.id,"-field")});return t.first&&e.addClass("first"),t.instructions&&e.addClass("has-instructions"),this.createCheckbox(t).appendTo(e),t.instructions&&$('<div class="instructions"/>').text(t.instructions).appendTo(e),e},createCheckboxSelect:function(t){var e,i,s=$('<fieldset class="checkbox-select"/>');t.class&&s.addClass(t.class),t.showAllOption?(e=t.allValue||"*",i=t.values==e,$("<div/>").appendTo(s).append(this.createCheckbox({id:t.id,class:"all",label:"<b>"+(t.allLabel||Craft.t("app","All"))+"</b>",name:t.name,value:e,checked:i,autofocus:t.autofocus}))):i=!1;for(var n=0;n<t.options.length;n++){var a=t.options[n];a.value!=e&&$("<div/>").appendTo(s).append(this.createCheckbox({label:a.label,name:t.name?t.name+"[]":null,value:a.value,checked:i||(t.values||[]).includes(a.value),disabled:i}))}return new Garnish.CheckboxSelect(s),s},createCheckboxSelectField:function(t){return t.fieldset=!0,t.id||(t.id="checkboxselect"+Math.floor(1e9*Math.random())),this.createField(this.createCheckboxSelect(t),t)},createLightswitch:function(t){var e=t.value||"1",i=t.indeterminateValue||"-",s=$("<button/>",{type:"button",class:"lightswitch","data-value":e,"data-indeterminate-value":i,id:t.id,role:"switch","aria-checked":t.on?"true":t.indeterminate?"mixed":"false","aria-labelledby":t.labelId,"data-target":t.toggle,"data-reverse-target":t.reverseToggle});return t.on?s.addClass("on"):t.indeterminate&&s.addClass("indeterminate"),t.small&&s.addClass("small"),t.disabled&&s.addClass("disabled"),$('<div class="lightswitch-container"><div class="handle"></div></div>').appendTo(s),t.name&&$("<input/>",{type:"hidden",name:t.name,value:t.on?e:t.indeterminate?i:"",disabled:t.disabled}).appendTo(s),(t.toggle||t.reverseToggle)&&(s.addClass("fieldtoggle"),new Craft.FieldToggle(s)),new Craft.LightSwitch(s,{onChange:t.onChange||$.noop}),s},createLightswitchField:function(t){return t.id||(t.id="lightswitch"+Math.floor(1e9*Math.random())),t.labelId||(t.labelId="".concat(t.id,"-label")),this.createField(this.createLightswitch(t),t).addClass("lightswitch-field")},createColorInput:function(t){var e=t.id||"color"+Math.floor(1e9*Math.random()),i=t.containerId||e+"-container",s=t.name||null,n=t.value||null,a=t.small||!1,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{id:i,class:"flex color-container"}),h=$("<div/>",{class:"color static"+(a?" small":"")}).appendTo(l),d=($("<div/>",{class:"color-preview",style:t.value?{backgroundColor:t.value}:null}).appendTo(h),$("<div/>",{class:"color-input-container"}).append($("<div/>",{class:"color-hex-indicator light code","aria-hidden":"true",text:"#"})).appendTo(l));return this.createTextInput({id:e,name:s,value:Craft.ltrim(n,"#"),size:10,class:"color-input",autofocus:r,disabled:o,"aria-label":Craft.t("app","Color hex value")}).appendTo(d),new Craft.ColorInput(l),l},createColorField:function(t){return t.fieldset=!0,o,t.id||(t.id="color"+Math.floor(1e9*Math.random())),this.createField(this.createColorInput(t),t)},createDateInput:function(t){var e=Garnish.isMobileBrowser(),i=(t.id||"date"+Math.floor(1e9*Math.random()))+"-date",s=t.name||null,n=s?s+"[date]":null,a=t.value&&"function"==typeof t.value.getMonth?t.value:null,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{class:"datewrapper"}),h=this.createTextInput({id:i,type:e?"date":"text",class:!(!e||a)&&"empty-value",name:n,value:a?e?a.toISOString().split("T")[0]:Craft.formatDate(a):"",placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return $('<div data-icon="date"></div>').appendTo(l),s&&$("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),e?h.datetimeinput():h.datepicker($.extend({defaultDate:a||new Date},Craft.datepickerOptions)),t.hasOuterContainer?l:$('<div class="datetimewrapper"/>').append(l).datetime()},createDateField:function(t){return t.id||(t.id="date"+Math.floor(1e9*Math.random())),this.createField(this.createDateInput(t),t)},createDateRangePicker:function(t){var e=new Date,i=new Date(e.getFullYear(),e.getMonth(),e.getDate());t=$.extend({class:"",options:["today","thisWeek","thisMonth","thisYear","past7Days","past30Days","past90Days","pastYear"],onChange:$.noop,selected:null,startDate:null,endDate:null},t);var s,n,a=$("<div/>",{class:"menu"}),r=$("<ul/>",{class:"padded"}).appendTo(a),o=$("<a/>").addClass("sel").text(Craft.t("app","All")).data("handle","all");$("<li/>").append(o).appendTo(r);for(var l=0;l<t.options.length;l++){var h=t.options[l];switch(h){case"today":s={label:Craft.t("app","Today"),startDate:i,endDate:i};break;case"thisWeek":var d=e.getDay()-Craft.datepickerOptions.firstDay;d<0&&(d+=7),s={label:Craft.t("app","This week"),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-d),endDate:i};break;case"thisMonth":s={label:Craft.t("app","This month"),startDate:new Date(e.getFullYear(),e.getMonth()),endDate:i};break;case"thisYear":s={label:Craft.t("app","This year"),startDate:new Date(e.getFullYear(),0),endDate:i};break;case"past7Days":s={label:Craft.t("app","Past {num} days",{num:7}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-7),endDate:i};break;case"past30Days":s={label:Craft.t("app","Past {num} days",{num:30}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-30),endDate:i};break;case"past90Days":s={label:Craft.t("app","Past {num} days",{num:90}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-90),endDate:i};break;case"pastYear":s={label:Craft.t("app","Past year"),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-365),endDate:i}}var c=$("<li/>"),u=$("<a/>",{text:s.label}).data("handle",h).data("startDate",s.startDate).data("endDate",s.endDate).data("startTime",s.startDate?s.startDate.getTime():null).data("endTime",s.endDate?s.endDate.getTime():null);t.selected&&h==t.selected&&(n=u[0]),c.append(u),c.appendTo(r)}$("<hr/>").appendTo(a);var p=$("<div/>",{class:"flex flex-nowrap padded"}).appendTo(a),f=this.createDateField({label:Craft.t("app","From")}).appendTo(p).find("input"),g=this.createDateField({label:Craft.t("app","To")}).appendTo(p).find("input"),m=f.add(g);m.on("keyup",(function(t){t.keyCode===Garnish.ESC_KEY&&$(this).data("datepicker")&&$(this).data("datepicker").dpDiv.is(":visible")&&t.stopPropagation()})),f.data("datepicker")&&f.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()})),g.data("datepicker")&&g.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()}));var v=new Garnish.Menu(a,{onOptionSelect:function(e){var i=$(e);C.text(i.text()),v.setPositionRelativeToAnchor(),a.find(".sel").removeClass("sel"),i.addClass("sel"),f.datepicker("setDate",i.data("startDate")),g.datepicker("setDate",i.data("endDate")),t.onChange(i.data("startDate")||null,i.data("endDate")||null,i.data("handle"))}});m.on("change",(function(){for(var e,i=f.datepicker("getDate"),s=g.datepicker("getDate"),n=i?i.getTime():null,o=s?s.getTime():null,l=r.find("a"),h=!1,d=0;d<l.length;d++)if(n===((e=l.eq(d)).data("startTime")||null)&&o===(e.data("endTime")||null)){v.selectOption(e[0]),h=!0,t.onChange(null,null,e.data("handle"));break}h||(a.find(".sel").removeClass("sel"),p.addClass("sel"),n||o?n&&o?C.text(f.val()+" - "+g.val()):n?C.text(Craft.t("app","From {date}",{date:f.val()})):C.text(Craft.t("app","To {date}",{date:g.val()})):C.text(Craft.t("app","All")),v.setPositionRelativeToAnchor(),t.onChange(i,s,"custom"))})),v.on("hide",(function(){f.datepicker("hide"),g.datepicker("hide")}));var b="btn menubtn";t.class&&(b=b+" "+t.class);var C=$("<button/>",{type:"button",class:b,"data-icon":"date",text:Craft.t("app","All")});return new Garnish.MenuBtn(C,v),n&&v.selectOption(n),t.startDate&&f.datepicker("setDate",t.startDate),t.endDate&&g.datepicker("setDate",t.endDate),(t.startDate||t.endDate)&&m.trigger("change"),C},createTimeInput:function(t){var e=Garnish.isMobileBrowser(),i=(t.id||"time"+Math.floor(1e9*Math.random()))+"-time",s=t.name||null,n=s?s+"[time]":null,a=t.value&&"function"==typeof t.value.getMonth?t.value:null,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{class:"timewrapper"}),h=this.createTextInput({id:i,type:e?"time":"text",class:!(!e||a)&&"empty-value",name:n,placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return $('<div data-icon="time"></div>').appendTo(l),s&&$("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),e?(a&&h.val(a.toISOString().split("T")[1]),h.datetimeinput()):(h.timepicker(Craft.timepickerOptions),a&&h.timepicker("setTime",3600*a.getHours()+60*a.getMinutes()+a.getSeconds())),t.hasOuterContainer?l:$('<div class="datetimewrapper"/>').append(l).datetime()},createTimeField:function(t){return t.id||(t.id="time"+Math.floor(1e9*Math.random())),this.createField(this.createTimeInput(t),t)},createField:function(t,e){var i=e.label&&"__blank__"!==e.label?e.label:null,s=$(e.fieldset?"<fieldset/>":"<div/>",{class:"field",id:e.fieldId||(e.id?e.id+"-field":null)});if(e.first&&s.addClass("first"),e.fieldClass&&s.addClass(e.fieldClass),i&&e.fieldset&&$("<legend/>",{text:i,class:"visually-hidden","data-label":i}).appendTo(s),i){var n=$('<div class="heading"/>').appendTo(s);$(e.fieldset?"<legend/>":"<label/>",{id:e.labelId||(e.id?"".concat(e.id,"-").concat(e.fieldset?"legend":"label"):null),class:e.required?"required":null,for:!e.fieldset&&e.id||null,text:i}).appendTo(n)}if(e.instructions&&$('<div class="instructions"/>').text(e.instructions).appendTo(s),$('<div class="input"/>').append(t).appendTo(s),e.tip){var a=$('<p class="notice has-icon"/>');$('<span class="icon" aria-hidden="true"/>').appendTo(a),$('<span class="visually-hidden"/>').text(Craft.t("app","Tip")+": ").appendTo(a),$("<span/>").text(e.tip).appendTo(a),a.appendTo(s)}if(e.warning){var r=$('<p class="warning has-icon"/>');$('<span class="icon" aria-hidden="true"/>').appendTo(r),$('<span class="visually-hidden"/>').text(Craft.t("app","Warning")+": ").appendTo(r),$("<span/>").text(e.warning).appendTo(r),r.appendTo(s)}return e.errors&&this.addErrorsToField(s,e.errors),s},createErrorList:function(t){var e=$('<ul class="errors"/>');return t&&this.addErrorsToList(e,t),e},addErrorsToList:function(t,e){for(var i=0;i<e.length;i++)$("<li/>").text(e[i]).appendTo(t)},addErrorsToField:function(t,e){if(e){t.addClass("has-errors"),t.children(".input").addClass("errors");var i=t.children("ul.errors");i.length||(i=this.createErrorList().appendTo(t)),this.addErrorsToList(i,e)}},clearErrorsFromField:function(t){t.removeClass("has-errors"),t.children(".input").removeClass("errors"),t.children("ul.errors").remove()},getAutofocusValue:function(t){return t&&!Garnish.isMobileBrowser(!0)?"autofocus":null},getDisabledValue:function(t){return t?"disabled":null}}},1752:function(){Craft.Uploader=Garnish.Base.extend({uploader:null,allowedKinds:null,$element:null,settings:null,_rejectedFiles:{},_extensionList:null,_totalFileCounter:0,_validFileCounter:0,init:function(t,e){this._rejectedFiles={size:[],type:[],limit:[]},this.$element=t,this.allowedKinds=null,this._extensionList=null,this._totalFileCounter=0,this._validFileCounter=0;var i=(e=$.extend({},Craft.Uploader.defaults,e)).events;for(var s in delete e.events,e.allowedKinds&&e.allowedKinds.length&&("string"==typeof e.allowedKinds&&(e.allowedKinds=[e.allowedKinds]),this.allowedKinds=e.allowedKinds,delete e.allowedKinds),e.autoUpload=!1,this.uploader=this.$element.fileupload(e),i)i.hasOwnProperty(s)&&this.uploader.on(s,i[s]);this.settings=e,this.uploader.on("fileuploadadd",this.onFileAdd.bind(this))},setParams:function(t){void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(t[Craft.csrfTokenName]=Craft.csrfTokenValue),this.uploader.fileupload("option",{formData:t})},getInProgress:function(){return this.uploader.fileupload("active")},isLastUpload:function(){return this.getInProgress()<2},onFileAdd:function(t,e){var i=this;t.stopPropagation();var s=!1;return this.allowedKinds&&(this._extensionList||this._createExtensionList(),s=!0),e.process().done((function(){var t=e.files[0],n=!0;if(s){var a=t.name.match(/\.([a-z0-4_]+)$/i)[1];-1===$.inArray(a.toLowerCase(),i._extensionList)&&(n=!1,i._rejectedFiles.type.push("“"+t.name+"”"))}t.size>i.settings.maxFileSize&&(i._rejectedFiles.size.push("“"+t.name+"”"),n=!1),n&&"function"==typeof i.settings.canAddMoreFiles&&!i.settings.canAddMoreFiles(i._validFileCounter)&&(i._rejectedFiles.limit.push("“"+t.name+"”"),n=!1),n&&(i._validFileCounter++,e.submit()),++i._totalFileCounter===e.originalFiles.length&&(i._totalFileCounter=0,i._validFileCounter=0,i.processErrorMessages())})),!0},processErrorMessages:function(){var t;this._rejectedFiles.type.length&&(t=1===this._rejectedFiles.type.length?"The file {files} could not be uploaded. The allowed file kinds are: {kinds}.":"The files {files} could not be uploaded. The allowed file kinds are: {kinds}.",t=Craft.t("app",t,{files:this._rejectedFiles.type.join(", "),kinds:this.allowedKinds.join(", ")}),this._rejectedFiles.type=[],Craft.cp.displayError(t)),this._rejectedFiles.size.length&&(t=1===this._rejectedFiles.size.length?"The file {files} could not be uploaded, because it exceeds the maximum upload size of {size}.":"The files {files} could not be uploaded, because they exceeded the maximum upload size of {size}.",t=Craft.t("app",t,{files:this._rejectedFiles.size.join(", "),size:this.humanFileSize(Craft.maxUploadSize)}),this._rejectedFiles.size=[],Craft.cp.displayError(t)),this._rejectedFiles.limit.length&&(t=1===this._rejectedFiles.limit.length?"The file {files} could not be uploaded, because the field limit has been reached.":"The files {files} could not be uploaded, because the field limit has been reached.",t=Craft.t("app",t,{files:this._rejectedFiles.limit.join(", ")}),this._rejectedFiles.limit=[],Craft.cp.displayError(t))},humanFileSize:function(t){var e=1024;if(t<e)return t+" B";var i=-1;do{t/=e,++i}while(t>=e);return t.toFixed(1)+" "+["kB","MB","GB","TB","PB","EB","ZB","YB"][i]},_createExtensionList:function(){this._extensionList=[];for(var t=0;t<this.allowedKinds.length;t++){var e=this.allowedKinds[t];if(void 0!==Craft.fileKinds[e])for(var i=0;i<Craft.fileKinds[e].extensions.length;i++){var s=Craft.fileKinds[e].extensions[i];this._extensionList.push(s)}}},destroy:function(){this.$element.fileupload("destroy"),this.base()}},{defaults:{dropZone:null,pasteZone:null,fileInput:null,sequentialUploads:!0,maxFileSize:Craft.maxUploadSize,allowedKinds:null,events:{},canAddMoreFiles:null,headers:{Accept:"application/json;q=0.9,*/*;q=0.8"},paramName:"assets-upload"}})},7e3:function(){Craft.UriFormatGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){t=(t=t.replace(/<(.*?)>/g,"")).toLowerCase(),t=(t=(t=Craft.asciiString(t)).replace(/^[^a-z]+/,"")).replace(/[^a-z0-9]+$/,"");var e=Craft.filterArray(t.split(/[^a-z0-9]+/)).join(Craft.slugWordSeparator);return e&&this.settings.suffix&&(e+=this.settings.suffix),e}})},8654:function(){Craft.UserIndex=Craft.BaseElementIndex.extend({init:function(t,e,i){this.on("selectSource",this.updateUrl.bind(this)),this.base(t,e,i)},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultSourceSlug)for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("slug")===defaultSourceSlug)return e.data("key")}return this.base()},updateUrl:function(){if("index"===this.settings.context){var t="users",e=this.$source.data("slug");e&&(t+="/".concat(e)),Craft.setPath(t)}}}),Craft.registerElementIndexClass("craft\\elements\\User",Craft.UserIndex)},9712:function(){Craft.VolumeFolderSelectorModal=Craft.BaseElementSelectorModal.extend({init:function(t){(t=Object.assign({},Craft.VolumeFolderSelectorModal.defaults,t,{showSiteMenu:!1})).indexSettings.disabledFolderIds=t.disabledFolderIds,this.base("craft\\elements\\Asset",t)},getElementIndexParams:function(){return Object.assign({},this.base(),{foldersOnly:!0})},hasSelection:function(){return this.base()||this.elementIndex&&this.elementIndex.sourcePath.length&&void 0!==this.elementIndex.sourcePath[this.elementIndex.sourcePath.length-1].folderId&&!this.settings.disabledFolderIds.includes(this.elementIndex.sourcePath[this.elementIndex.sourcePath.length-1].folderId)},getElementInfo:function(t){return[{folderId:t.length?parseInt(t.find(".element:first").data("folder-id")):this.elementIndex.sourcePath[this.elementIndex.sourcePath.length-1].folderId}]},getIndexSettings:function(){var t=this;return Object.assign(this.base(),{foldersOnly:!0,canSelectElement:function(e){var i=e.find(".element:first").data("folder-id");return i&&!t.settings.disabledFolderIds.includes(i)}})}},{defaults:{disabledFolderIds:[],indexSettings:{}}})},5537:function(){},9383:function(){},6558:function(t,e,i){var s=i(5537);s.__esModule&&(s=s.default),"string"==typeof s&&(s=[[t.id,s,""]]),s.locals&&(t.exports=s.locals),(0,i(9673).Z)("3790022a",s,!0,{})},2179:function(t,e,i){var s=i(9383);s.__esModule&&(s=s.default),"string"==typeof s&&(s=[[t.id,s,""]]),s.locals&&(t.exports=s.locals),(0,i(9673).Z)("80058a3c",s,!0,{})},9673:function(t,e,i){"use strict";function s(t,e){for(var i=[],s={},n=0;n<e.length;n++){var a=e[n],r=a[0],o={id:t+":"+n,css:a[1],media:a[2],sourceMap:a[3]};s[r]?s[r].parts.push(o):i.push(s[r]={id:r,parts:[o]})}return i}i.d(e,{Z:function(){return f}});var n="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!n)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var a={},r=n&&(document.head||document.getElementsByTagName("head")[0]),o=null,l=0,h=!1,d=function(){},c=null,u="data-vue-ssr-id",p="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());function f(t,e,i,n){h=i,c=n||{};var r=s(t,e);return g(r),function(e){for(var i=[],n=0;n<r.length;n++){var o=r[n];(l=a[o.id]).refs--,i.push(l)}for(e?g(r=s(t,e)):r=[],n=0;n<i.length;n++){var l;if(0===(l=i[n]).refs){for(var h=0;h<l.parts.length;h++)l.parts[h]();delete a[l.id]}}}}function g(t){for(var e=0;e<t.length;e++){var i=t[e],s=a[i.id];if(s){s.refs++;for(var n=0;n<s.parts.length;n++)s.parts[n](i.parts[n]);for(;n<i.parts.length;n++)s.parts.push(v(i.parts[n]));s.parts.length>i.parts.length&&(s.parts.length=i.parts.length)}else{var r=[];for(n=0;n<i.parts.length;n++)r.push(v(i.parts[n]));a[i.id]={id:i.id,refs:1,parts:r}}}}function m(){var t=document.createElement("style");return t.type="text/css",r.appendChild(t),t}function v(t){var e,i,s=document.querySelector("style["+u+'~="'+t.id+'"]');if(s){if(h)return d;s.parentNode.removeChild(s)}if(p){var n=l++;s=o||(o=m()),e=C.bind(null,s,n,!1),i=C.bind(null,s,n,!0)}else s=m(),e=_.bind(null,s),i=function(){s.parentNode.removeChild(s)};return e(t),function(s){if(s){if(s.css===t.css&&s.media===t.media&&s.sourceMap===t.sourceMap)return;e(t=s)}else i()}}var b,$=(b=[],function(t,e){return b[t]=e,b.filter(Boolean).join("\n")});function C(t,e,i,s){var n=i?"":s.css;if(t.styleSheet)t.styleSheet.cssText=$(e,n);else{var a=document.createTextNode(n),r=t.childNodes;r[e]&&t.removeChild(r[e]),r.length?t.insertBefore(a,r[e]):t.appendChild(a)}}function _(t,e){var i=e.css,s=e.media,n=e.sourceMap;if(s&&t.setAttribute("media",s),c.ssrId&&t.setAttribute(u,e.id),n&&(i+="\n/*# sourceURL="+n.sources[0]+" */",i+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(n))))+" */"),t.styleSheet)t.styleSheet.cssText=i;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(i))}}}},__webpack_module_cache__={};function __webpack_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var i=__webpack_module_cache__[t]={id:t,exports:{}};return __webpack_modules__[t](i,i.exports,__webpack_require__),i.exports}__webpack_require__.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return __webpack_require__.d(e,{a:e}),e},__webpack_require__.d=function(t,e){for(var i in e)__webpack_require__.o(e,i)&&!__webpack_require__.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},__webpack_require__.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};var __webpack_exports__={};!function(){"use strict";__webpack_require__(2179),__webpack_require__(6558),__webpack_require__(587),__webpack_require__(8960),__webpack_require__(5774),__webpack_require__(8495),__webpack_require__(5970),__webpack_require__(4993),__webpack_require__(8843),__webpack_require__(5759),__webpack_require__(8167),__webpack_require__(4211),__webpack_require__(7745),__webpack_require__(8895),__webpack_require__(463),__webpack_require__(3839),__webpack_require__(7452),__webpack_require__(6872),__webpack_require__(2495),__webpack_require__(1016),__webpack_require__(5077),__webpack_require__(4606),__webpack_require__(8391),__webpack_require__(9222);var t=jQuery,e=__webpack_require__.n(t);function i(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=n(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var s=0,a=function(){};return{s:a,n:function(){return s>=t.length?{done:!0}:{done:!1,value:t[s++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==i.return||i.return()}finally{if(l)throw r}}}}function s(t){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},s(t)}function n(t,e){if(t){if("string"==typeof t)return a(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?a(t,e):void 0}}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CP=Garnish.Base.extend({elementThumbLoader:null,authManager:null,$nav:null,$navToggle:null,$globalSidebar:null,$globalContainer:null,$mainContainer:null,$alerts:null,$crumbs:null,$breadcrumbList:null,$breadcrumbItems:null,$notificationContainer:null,$main:null,$primaryForm:null,$headerContainer:null,$header:null,$mainContent:null,$details:null,$sidebarContainer:null,$sidebarToggle:null,$sidebar:null,$contentContainer:null,$edition:null,$confirmUnloadForms:null,$deltaForms:null,$collapsibleTables:null,isMobile:null,fixedHeader:!1,breadcrumbListWidth:0,breadcrumbDisclosureItem:'<li class="breadcrumb-toggle-wrapper" data-disclosure-item><button data-disclosure-trigger aria-controls="breadcrumb-disclosure" aria-haspopup="true">'.concat(Craft.t("app","More…"),'</button><div id="breadcrumb-disclosure" class="menu menu--disclosure" data-disclosure-menu><ul></ul></div></li>'),tabManager:null,enableQueue:!0,totalJobs:0,jobInfo:null,displayedJobInfo:null,displayedJobInfoUnchanged:1,trackJobProgressTimeout:null,jobProgressIcon:null,checkingForUpdates:!1,forcingRefreshOnUpdatesCheck:!1,includingDetailsOnUpdatesCheck:!1,checkForUpdatesCallbacks:null,resizeTimeout:null,init:function(){var t=this;this.elementThumbLoader=new Craft.ElementThumbLoader,0!==Craft.remainingSessionTime&&(this.authManager=new Craft.AuthManager),this.$nav=e()("#nav"),this.$navToggle=e()("#primary-nav-toggle"),this.$globalSidebar=e()("#global-sidebar"),this.$globalContainer=e()("#global-container"),this.$mainContainer=e()("#main-container"),this.$alerts=e()("#alerts"),this.$crumbs=e()("#crumbs"),this.$breadcrumbList=e()(".breadcrumb-list"),this.$breadcrumbItems=e()(".breadcrumb-list li"),this.$notificationContainer=e()("#notifications"),this.$main=e()("#main"),this.$primaryForm=e()("#main-form"),this.$headerContainer=e()("#header-container"),this.$header=e()("#header"),this.$mainContent=e()("#main-content"),this.$details=e()("#details"),this.$sidebarContainer=e()("#sidebar-container"),this.$sidebarToggle=e()("#sidebar-toggle"),this.$sidebar=e()("#sidebar"),this.$contentContainer=e()("#content-container"),this.$collapsibleTables=e()("table.collapsible"),this.isMobile=Garnish.isMobileBrowser(),this.updateContentHeading();for(var i=this.$details.find(".meta > .field > .instructions"),s=0;s<i.length;s++){var a=i.eq(s),r=a.siblings(".heading").children("label");e()("<span/>",{class:"info",html:a.children().html()}).appendTo(r),a.remove()}if(!this.isMobile&&this.$header.length&&(this.addListener(Garnish.$win,"scroll","updateFixedHeader"),this.updateFixedHeader()),Garnish.$doc.ready((function(){t.addListener(Garnish.$win,"resize",(function(e){if(e.target===window){t.handleWindowResize(),clearTimeout(t.resizeTimeout);var i=t;t.resizeTimeout=setTimeout((function(){i.setSidebarNavAttributes()}),100)}})),t.handleWindowResize(),t.setSidebarNavAttributes(),Garnish.requestAnimationFrame(t.initSpecialForms.bind(t))})),this.$alerts.length&&this.initAlerts(),this.addListener(this.$navToggle,"click","toggleNav"),this.addListener(this.$sidebarToggle,"click","toggleSidebar"),this.$primaryForm.length||(this.$primaryForm=e()("form[data-saveshortcut]:first")),this.$primaryForm.length&&Garnish.hasAttr(this.$primaryForm,"data-saveshortcut")&&function(){var e=[],i=t.$primaryForm.data("actions");if(void 0===i)e.push([{keyCode:Garnish.S_KEY,ctrl:!0},{redirect:t.$primaryForm.data("saveshortcut-redirect"),retainScroll:Garnish.hasAttr(t.$primaryForm,"saveshortcut-scroll")}]);else for(var s=0;s<i.length;s++){var n=i[s];n.shortcut&&e.push([{keyCode:Garnish.S_KEY,ctrl:!0,shift:!!n.shift},{action:n.action,redirect:n.redirect,confirm:n.confirm,params:n.params,data:n.data,retainScroll:n.retainScroll}])}for(var a=function(i){Garnish.uiLayerManager.registerShortcut(e[i][0],(function(){t.submitPrimaryForm(e[i][1])}))},r=0;r<e.length;r++)a(r)}(),this.initTabs(),this.tabManager&&window.LOCATION_HASH){var o=this.tabManager.$tabs.filter('[href="#'.concat(window.LOCATION_HASH,'"]'));o.length&&this.tabManager.selectTab(o)}var l=Craft.getLocalStorage("scrollY");if(void 0!==l&&(Craft.removeLocalStorage("scrollY"),Garnish.$doc.ready((function(){Garnish.requestAnimationFrame((function(){window.scrollTo(0,l)}))}))),e().isTouchCapable()&&(this.$mainContainer.on("focus","input, textarea, .focusable-input",this._handleInputFocus.bind(this)),this.$mainContainer.on("blur","input, textarea, .focusable-input",this._handleInputBlur.bind(this))),Craft.announcements.length){var h,d,c=e()("#announcements-btn").removeClass("hidden"),u=Craft.announcements.some((function(t){return t.unread}));u&&(h=e()("<span/>",{class:"visually-hidden",html:Craft.t("app","Unread messages")}),c.addClass("unread").append(h)),this.addListener(c,"click",(function(){if(d)d.show();else{var t="";Craft.announcements.forEach((function(e){t+='<div class="announcement '.concat(e.unread?"unread":"",'" role="listitem">')+'<div class="announcement__header">'+'<h3 class="announcement__heading h2">'.concat(e.heading,"</h3>")+'<div class="announcement-label-container">'+'<div class="announcement-icon" aria-hidden="true">'.concat(e.icon,"</div>")+'<div class="announcement-label">'.concat(e.label,"</div>")+"</div></div>"+"<p>".concat(e.body,"</p>")+"</div>"})),d=new Garnish.HUD(c,'<h2 class="visually-hidden">'.concat(Craft.t("app","Announcements"),'</h2><div id="announcements" role="list">').concat(t,"</div>"),{onShow:function(){c.addClass("active")},onHide:function(){c.removeClass("active")}}),e()("a",d.$main).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===e()(this).attr("target")&&e()(this).attr("rel","noopener").attr("target","_blank")})),u&&(c.removeClass("unread"),h.remove(),Craft.sendActionRequest("POST","users/mark-announcements-as-read",{data:{ids:Craft.announcements.map((function(t){return t.id}))}}))}}))}var p=document.getElementById("footer");p&&new IntersectionObserver((function(t){var e=function(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(t,e)||n(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(t,1)[0];e.target.classList.toggle("stuck",e.intersectionRatio<1)}),{rootMargin:"0px 0px -1px 0px",threshold:[1]}).observe(p),this.elementThumbLoader.load(this.$mainContent)},get $contentHeader(){var t=e()("#content-header");return t.length?t:e()("<header/>",{id:"content-header",class:"pane-header"}).prependTo(e()("#content"))},get $noticeContainer(){var t=e()("#content-notice");return t.length?t:e()('<div id="content-notice"/>').attr("role","status").prependTo(this.$contentHeader)},initSpecialForms:function(){var t=this;if(this.$confirmUnloadForms=e()("form[data-confirm-unload]"),this.$deltaForms=e()("form[data-delta]"),this.$confirmUnloadForms.length){for(var i=this.$confirmUnloadForms.add(this.$deltaForms),s=function(e){var s=i.eq(e),n=void 0;s.data("initialSerializedValue")||(n="function"==typeof s.data("serializer")?s.data("serializer")():s.serialize(),s.data("initialSerializedValue",n)),t.addListener(s,"submit",(function(t){if(Garnish.hasAttr(s,"data-confirm-unload")&&this.removeListener(Garnish.$win,"beforeunload"),Garnish.hasAttr(s,"data-delta")){var e;t.preventDefault(),e="function"==typeof s.data("serializer")?s.data("serializer")():s.serialize();var i=Craft.findDeltaData(s.data("initialSerializedValue"),e,s.data("delta-names"),null,s.data("initial-delta-values"),s.data("modified-delta-names"));Craft.createForm(i).appendTo(Garnish.$bod).submit()}}))},n=0;n<i.length;n++)s(n);this.addListener(Garnish.$win,"beforeunload",(function(t){var e=!1;if(void 0!==Craft.livePreview&&Craft.livePreview.inPreviewMode)e=!0;else for(var i=0;i<this.$confirmUnloadForms.length;i++){var s,n=this.$confirmUnloadForms.eq(i);if(s="function"==typeof n.data("serializer")?n.data("serializer")():n.serialize(),n.data("initialSerializedValue")!==s){e=!0;break}}if(e){var a=Craft.t("app","Any changes will be lost if you leave this page.");return t?t.originalEvent.returnValue=a:window.event.returnValue=a,a}}))}},_handleInputFocus:function(){this.updateFixedHeader()},_handleInputBlur:function(){this.updateFixedHeader()},submitPrimaryForm:function(t){this.trigger("beforeSaveShortcut"),"object"===s(t)&&e().isPlainObject(t)||(t={}),t.redirect||(t.redirect=this.$primaryForm.data("saveshortcut-redirect")),t.data||(t.data={}),t.data.saveShortcut=!0,Craft.submitForm(this.$primaryForm,t)},updateSidebarMenuLabel:function(){this.updateContentHeading()},updateContentHeading:function(){var t=this.$sidebar.find("a.sel:first"),i=t.children(".label");e()("#content-heading").text(i.length?i.text():t.text()),Garnish.$bod.removeClass("showing-sidebar")},toggleNav:function(){var t=this.navIsExpanded();null!==t&&(t?(this.disableGlobalSidebarLinks(),this.$navToggle.focus(),this.$navToggle.attr("aria-expanded","false"),Garnish.$bod.removeClass("showing-nav")):(this.enableGlobalSidebarLinks(),this.$globalSidebar.find(":focusable")[0].focus(),this.$navToggle.attr("aria-expanded","true"),Garnish.$bod.addClass("showing-nav")))},enableGlobalSidebarLinks:function(){var t=this.$globalSidebar.find(":focusable");e()(t).each((function(){e()(this).attr("tabindex","0")}))},disableGlobalSidebarLinks:function(){var t=this.$globalSidebar.find(":focusable");e()(t).each((function(){e()(this).attr("tabindex","-1")}))},setSidebarNavAttributes:function(){var t=this.navIsExpanded();null!==t&&(t?this.enableGlobalSidebarLinks():this.disableGlobalSidebarLinks())},navIsExpanded:function(){if(!this.$globalSidebar[0])return null;var t=getComputedStyle(this.$globalSidebar[0]).getPropertyValue("--is-always-visible").trim();return"true"===this.$navToggle.attr("aria-expanded")||"true"===t},toggleSidebar:function(){var t="true"===this.$sidebarToggle.attr("aria-expanded")?"false":"true";this.$sidebarToggle.attr("aria-expanded",t),Garnish.$bod.toggleClass("showing-sidebar")},initTabs:function(){this.tabManager&&(this.tabManager.destroy(),this.tabManager=null);var t=e()("#tabs");t.length&&(this.tabManager=new Craft.Tabs(t),this.tabManager.on("selectTab",(function(t){var i=t.$tab.attr("href");if(i&&"#"===i.charAt(0)&&e()(i).removeClass("hidden"),Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll"),i&&"#"===i.charAt(0)){var s=e()("#context-btn").menubtn().data("menubtn");if(s)for(var n=0;n<s.menu.$options.length;n++){var a=s.menu.$options[n];a.href&&(a.href=a.href.match(/^[^#]*/)[0]+i)}}"undefined"!=typeof history&&Garnish.requestAnimationFrame((function(){history.replaceState(void 0,void 0,i)}))})),this.tabManager.on("deselectTab",(function(t){var i=t.$tab.attr("href");i&&"#"===i.charAt(0)&&e()(t.$tab.attr("href")).addClass("hidden")})))},updateTabs:function(t){if(t){var i=e()(t).attr("id","tabs");this.tabManager?this.tabManager.$container.replaceWith(i):i.appendTo(this.$contentHeader),this.initTabs()}else this.tabManager&&(this.tabManager.$container.siblings().length?this.tabManager.$container.remove():this.tabManager.$container.parent().remove(),this.tabManager.destroy(),this.tabManager=null)},get $tabsContainer(){return this.tabManager?this.tabManager.$container:void 0},get $tabsList(){return this.tabManager?this.tabManager.$tablist:void 0},get $tabs(){return this.tabManager?this.tabManager.$tablist.find("> a"):void 0},get $selectedTab(){return this.tabManager?this.tabManager.$selectedTab:void 0},get selectedTabIndex(){return this.tabManager?this.tabManager.$tabs.index(this.tabManager.$selectedTab):void 0},get $focusableTab(){return this.tabManager?this.tabManager.$focusableTab:void 0},selectTab:function(t){this.tabManager&&this.tabManager.selectTab(t)},deselectTab:function(){this.tabManager&&this.tabManager.deselectTab()},handleWindowResize:function(){this.updateResponsiveTables(),this.handleBreadcrumbVisibility()},breadcrumbItemsWrap:function(){if(this.$breadcrumbItems[0]){this.$breadcrumbList.css("ltr"===Craft.orientation?"margin-right":"margin-left","");for(var t=this.$breadcrumbList[0].getBoundingClientRect().width,e=0,i=this.$breadcrumbList.find("li"),s=0;s<i.length;s++)e+=i.get(s).getBoundingClientRect().width;return this.breadcrumbListWidth=t,!(e<=t||e<t+1&&(this.$breadcrumbList.css("ltr"===Craft.orientation?"margin-right":"margin-left","-1px"),1))}},handleBreadcrumbVisibility:function(){if(this.breadcrumbItemsWrap()){0===this.$breadcrumbList.find("[data-disclosure-item]").length&&this.$breadcrumbList.append(this.breadcrumbDisclosureItem);var t,e=this.$breadcrumbList.find("[data-disclosure-item]")[0].offsetWidth,i=this.breadcrumbListWidth;this.$breadcrumbItems.each((function(s){if(!(e+this.offsetWidth<i))return!1;t=s,e+=this.offsetWidth}));var s=this.$breadcrumbItems.slice(0,t+1),n=this.$breadcrumbItems.slice(t+1);this.$breadcrumbList.html(""),this.$breadcrumbList.append(s),this.$breadcrumbList.append(this.breadcrumbDisclosureItem),this.$breadcrumbList.find("[data-disclosure-menu] ul").append(n),this.$breadcrumbList.find("[data-disclosure-trigger]").disclosureMenu()}},updateResponsiveTables:function(){for(this.updateResponsiveTables._i=0;this.updateResponsiveTables._i<this.$collapsibleTables.length;this.updateResponsiveTables._i++)this.updateResponsiveTables._$table=this.$collapsibleTables.eq(this.updateResponsiveTables._i),this.updateResponsiveTables._containerWidth=this.updateResponsiveTables._$table.parent().width(),this.updateResponsiveTables._check=!1,this.updateResponsiveTables._containerWidth>0&&(void 0===this.updateResponsiveTables._$table.data("lastContainerWidth")?this.updateResponsiveTables._check=!0:(this.updateResponsiveTables._isCollapsed=this.updateResponsiveTables._$table.hasClass("collapsed"),this.updateResponsiveTables._containerWidth>this.updateResponsiveTables._$table.data("lastContainerWidth")?this.updateResponsiveTables._isCollapsed&&(this.updateResponsiveTables._$table.removeClass("collapsed"),this.updateResponsiveTables._check=!0):this.updateResponsiveTables._isCollapsed||(this.updateResponsiveTables._check=!0)),this.updateResponsiveTables._check&&this.updateResponsiveTables._$table.width()-30>this.updateResponsiveTables._containerWidth&&this.updateResponsiveTables._$table.addClass("collapsed"),this.updateResponsiveTables._$table.data("lastContainerWidth",this.updateResponsiveTables._containerWidth))},updateFixedHeader:function(){if(!this.isMobile)if(this.$main.length&&this.$headerContainer[0].getBoundingClientRect().top<0){if(!this.fixedHeader){var t=this.$headerContainer.height();this.$contentContainer.css("min-height","calc(100vh - "+(t+14+48-1)+"px)"),this.$headerContainer.height(t),Garnish.$bod.addClass("fixed-header"),this.$contentContainer.outerHeight(),this.$details.outerHeight();var e={top:t+"px","max-height":"calc(100vh - "+t+"px)"};this.$sidebar.addClass("fixed").css(e),this.$details.addClass("fixed").css(e),this.fixedHeader=!0}}else this.fixedHeader&&(this.$headerContainer.height("auto"),Garnish.$bod.removeClass("fixed-header"),this.$contentContainer.css("min-height",""),this.$sidebar.removeClass("fixed").css({top:"","max-height":""}),this.$details.removeClass("fixed").css({top:"","max-height":""}),this.fixedHeader=!1)},displayNotification:function(t,e,i){var s=new Craft.CP.Notification(t,e,i);return this.trigger("displayNotification",{notificationType:t,message:e,notification:s}),s},displayNotice:function(t,e){return this.displayNotification("notice",t,Object.assign({icon:"info",iconLabel:Craft.t("app","Notice")},e))},displaySuccess:function(t,e){return this.displayNotification("success",t,Object.assign({icon:"check",iconLabel:Craft.t("app","Success")},e))},displayError:function(t,e){return t&&"object"!==s(t)||(e=t,t=Craft.t("app","A server error occurred.")),this.displayNotification("error",t,Object.assign({icon:"alert",iconLabel:Craft.t("app","Error")},e))},fetchAlerts:function(){return Craft.queue.push((function(){return new Promise((function(t,e){var i={path:Craft.path};Craft.sendActionRequest("POST","app/get-cp-alerts",{data:i}).then((function(e){var i=e.data;t(i.alerts)})).catch(e)}))}))},displayAlerts:function(t){if(this.$alerts.remove(),Garnish.isArray(t)&&t.length){this.$alerts=e()('<ul id="alerts"/>').prependTo(e()("#page-container"));var s,n=i(t);try{for(n.s();!(s=n.n()).done;){var a=s.value;e().isPlainObject(a)||(a={content:a,showIcon:!0});var r=a.content;a.showIcon&&(r='<span data-icon="alert" aria-label="'.concat(Craft.t("app","Error"),'"></span> ').concat(r)),e()("<li>".concat(r,"</li>")).appendTo(this.$alerts)}}catch(t){n.e(t)}finally{n.f()}var o=this.$alerts.outerHeight();this.$alerts.css("margin-top",-o).velocity({"margin-top":0},"fast"),this.initAlerts()}},initAlerts:function(){for(var t=this,i=this.$alerts.find('a[class^="shun:"]'),s=0;s<i.length;s++)this.addListener(i[s],"click",(function(i){i.preventDefault(),Craft.queue.push((function(){return new Promise((function(s,n){var a=e()(i.currentTarget),r={message:a.prop("className").substring(5)};Craft.sendActionRequest("POST","app/shun-cp-alert",{data:r}).then((function(){a.parent().remove(),s()})).catch((function(e){var i=e.response;t.displayError(i.data.message),n()}))}))}))}))},checkForUpdates:function(t,e,i){var s=this;if("function"==typeof e&&(i=e,e=!1),this.checkingForUpdates&&(!0===t&&!this.forcingRefreshOnUpdatesCheck||!0===e&&!this.includingDetailsOnUpdatesCheck)){var n=i;i=function(){s.checkForUpdates(t,e,n)}}"function"==typeof i&&(Garnish.isArray(this.checkForUpdatesCallbacks)||(this.checkForUpdatesCallbacks=[]),this.checkForUpdatesCallbacks.push(i)),this.checkingForUpdates||(this.checkingForUpdates=!0,this.forcingRefreshOnUpdatesCheck=!0===t,this.includingDetailsOnUpdatesCheck=!0===e,this._checkForUpdates(t,e).then((function(t){if(s.updateUtilitiesBadge(),s.checkingForUpdates=!1,Garnish.isArray(s.checkForUpdatesCallbacks)){var e=s.checkForUpdatesCallbacks;s.checkForUpdatesCallbacks=null;for(var i=0;i<e.length;i++)e[i](t)}s.trigger("checkForUpdates",{updateInfo:t})})))},_checkForUpdates:function(t,e){var i=this;return new Promise((function(s,n){t?i._getUpdates(e).then(s).catch(n):i._checkForCachedUpdates(e).then((function(t){t.cached?s(t):i._getUpdates(e).then((function(t){s(t)}))})).catch(n)}))},_checkForCachedUpdates:function(t){return new Promise((function(e,i){var s={onlyIfCached:!0,includeDetails:t};Craft.sendActionRequest("POST","app/check-for-updates",{data:s}).then((function(t){var i=t.data;e(i)})).catch((function(){e({cached:!1})}))}))},_getUpdates:function(t){var e=this;return new Promise((function(i,s){Craft.sendApiRequest("GET","updates").then((function(s){e._cacheUpdates(s,t).then((function(t){i(t)}))})).catch(s)}))},_cacheUpdates:function(t,e){return new Promise((function(i,s){var n={updates:t,includeDetails:e};Craft.sendActionRequest("POST","app/cache-updates",{data:n}).then((function(t){var e=t.data;i(e)})).catch(s)}))},updateUtilitiesBadge:function(){var t=e()("#nav-utilities").find("> a:not(.sel)");t.length&&Craft.queue.push((function(){return new Promise((function(i,s){Craft.sendActionRequest("POST","app/get-utilities-badge-count").then((function(s){var n=s.data,a=t.children(".badge"),r=t.children("[data-notification]");n.badgeCount?(a.length||(a=e()('<span class="badge" aria-hidden="true"/>').appendTo(t)),r.length||(r=e()('<span class="visually-hidden" data-notification/>').appendTo(t)),a.text(n.badgeCount),r.text(Craft.t("app","{num, number} {num, plural, =1{notification} other{notifications}}",{num:n.badgeCount}))):a.length&&r.length&&(a.remove(),r.remove()),i()})).catch(s)}))}))},runQueue:function(){var t=this;this.enableQueue&&(Craft.runQueueAutomatically?Craft.queue.push((function(){return new Promise((function(e,i){Craft.sendActionRequest("POST","queue/run").then((function(){t.trackJobProgress(!1,!0),e()})).catch(i)}))})):this.trackJobProgress(!1,!0))},trackJobProgress:function(t,e){if(e&&this.trackJobProgressTimeout&&(clearTimeout(this.trackJobProgressTimeout),this.trackJobProgressTimeout=null),!this.trackJobProgressTimeout&&this.enableQueue)if(!0===t){var i=Math.min(6e4,500*this.displayedJobInfoUnchanged);this.trackJobProgressTimeout=setTimeout(this._trackJobProgressInternal.bind(this),i)}else this._trackJobProgressInternal()},_trackJobProgressInternal:function(){var t=this;Craft.queue.push((function(){return new Promise((function(e,i){Craft.sendActionRequest("POST","queue/get-job-info?limit=50&dontExtendSession=1").then((function(i){var s=i.data;t.trackJobProgressTimeout=null,t.totalJobs=s.total,t.setJobInfo(s.jobs),t.jobInfo.length&&t.trackJobProgress(!0),e()})).catch(i)}))}))},setJobInfo:function(t){if(this.enableQueue){this.jobInfo=t;var e=this.displayedJobInfo;this.displayedJobInfo=this.getDisplayedJobInfo(),e&&this.displayedJobInfo&&e.id===this.displayedJobInfo.id&&e.progress===this.displayedJobInfo.progress&&e.progressLabel===this.displayedJobInfo.progressLabel&&e.status===this.displayedJobInfo.status?this.displayedJobInfoUnchanged++:this.displayedJobInfoUnchanged=1,this.updateJobIcon(),this.trigger("setJobInfo")}},getDisplayedJobInfo:function(){if(!this.enableQueue)return null;for(var t=[Craft.CP.JOB_STATUS_RESERVED,Craft.CP.JOB_STATUS_FAILED,Craft.CP.JOB_STATUS_WAITING],e=0;e<t.length;e++)for(var i=0;i<this.jobInfo.length;i++)if(this.jobInfo[i].status===t[e]&&(t[e]!==Craft.CP.JOB_STATUS_WAITING||!this.jobInfo[i].delay))return this.jobInfo[i];return null},updateJobIcon:function(){this.enableQueue&&this.$nav.length&&(this.displayedJobInfo?(this.jobProgressIcon||(this.jobProgressIcon=new r),this.displayedJobInfo.status===Craft.CP.JOB_STATUS_RESERVED||this.displayedJobInfo.status===Craft.CP.JOB_STATUS_WAITING?(this.jobProgressIcon.hideFailMode(),this.jobProgressIcon.setDescription(this.displayedJobInfo.description,this.displayedJobInfo.progressLabel),this.jobProgressIcon.setProgress(this.displayedJobInfo.progress)):this.displayedJobInfo.status===Craft.CP.JOB_STATUS_FAILED&&this.jobProgressIcon.showFailMode(Craft.t("app","Failed"))):this.jobProgressIcon&&(this.jobProgressIcon.hideFailMode(),this.jobProgressIcon.complete(),delete this.jobProgressIcon))},getSiteId:function(){var t=Craft.getLocalStorage("BaseElementIndex.siteId");if(void 0!==t){Craft.removeLocalStorage("BaseElementIndex.siteId");try{this.setSiteId(t)}catch(t){}}return Craft.siteId},setSiteId:function(t){var s=Craft.sites.find((function(e){return e.id===t}));if(!s)throw"Invalid site ID: ".concat(t);Craft.siteId=t,Craft.actionUrl=Craft.getUrl(Craft.actionUrl,{site:s.handle}),Craft.baseCpUrl=Craft.getUrl(Craft.baseCpUrl,{site:s.handle}),Craft.baseUrl=Craft.getUrl(Craft.baseUrl,{site:s.handle});var n=Craft.getUrl(document.location.href,{site:s.handle});history.replaceState({},"",n);var a,r=i(document.body.classList);try{for(r.s();!(a=r.n()).done;){var o=a.value;o.match(/^site--/)&&document.body.classList.remove(o)}}catch(t){r.e(t)}finally{r.f()}document.body.classList.add("site--".concat(s.handle)),e()("a").each((function(){this.hostname.length&&this.hostname===location.hostname&&-1!==this.href.indexOf(Craft.cpTrigger)&&(this.href=Craft.getUrl(this.href,{site:s.handle}))}))}},{notificationDuration:5e3,JOB_STATUS_WAITING:1,JOB_STATUS_RESERVED:2,JOB_STATUS_DONE:3,JOB_STATUS_FAILED:4}),Craft.CP.Notification=Garnish.Base.extend({type:null,message:null,settings:null,closing:!1,closeTimeout:null,_preventDelayedClose:!1,$container:null,$closeBtn:null,originalActiveElement:null,init:function(t,i,s){var n=this;this.type=t,this.message=i,this.settings=s||{},this.$container=e()("<div/>",{class:"notification","data-type":this.type}).appendTo(Craft.cp.$notificationContainer);var a=e()('<div class="notification-body"/>').appendTo(this.$container);if(this.settings.icon){var r=e()("<span/>",{class:"notification-icon","data-icon":this.settings.icon}).appendTo(a);this.settings.iconLabel?r.attr({"aria-label":this.settings.iconLabel,role:"img"}):r.attr("aria-hidden","true")}var o=e()('<div class="notification-main"/>').appendTo(a);e()("<div/>",{class:"notification-message",text:this.message}).appendTo(o);var l=e()("<div/>").appendTo(this.$container);this.$closeBtn=e()("<button/>",{type:"button",class:"notification-close-btn","aria-label":Craft.t("app","Close"),"data-icon":"remove"}).appendTo(l),this.settings.details&&e()('<div class="notification-details"/>').append(this.settings.details).appendTo(o).find("button,input").length&&(Garnish.uiLayerManager.addLayer(this.$container),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){n.close()})),this.originalActiveElement=document.activeElement,this.$container.attr("tabindex","-1").focus(),this.$container.on("keydown",(function(t){t.keyCode===Garnish.ESC_KEY&&(t.stopPropagation(),n.close())}))),this.$container.css({opacity:0,"margin-bottom":this._negMargin()}).velocity({opacity:1,"margin-bottom":0},{duration:"fast"}),Craft.initUiElements(this.$container),this.addListener(this.$closeBtn,"click","close"),Craft.notificationDuration&&this._initDelayedClose()},_initDelayedClose:function(){var t=this;this._preventDelayedClose||(Craft.isVisible()?(this.delayedClose(),this.$container.on("keypress keyup change focus blur click mousedown mouseup",(function(e){e.target!=t.$closeBtn[0]&&(t.$container.off("keypress keyup change focus blur click mousedown mouseup"),t.preventDelayedClose())}))):Garnish.$doc.one("visibilitychange",(function(){t._initDelayedClose()})))},_negMargin:function(){return"-".concat(this.$container.outerHeight()+12,"px")},close:function(){var t=this;this.closing||(this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null),this.closing=!0,this.originalActiveElement&&document.activeElement&&(document.activeElement===this.$container[0]||e().contains(this.$container[0],document.activeElement))&&e()(this.originalActiveElement).focus(),this.$container.velocity({opacity:0,"margin-bottom":this._negMargin()},{duration:"fast",complete:function(){t.$container.remove()}}))},delayedClose:function(){var t=this;this.closeTimeout=setTimeout((function(){t.close()}),Craft.notificationDuration),this.$container.one("mouseover",(function(){clearTimeout(t.closeTimeout),t.closeTimeout=null,t.$container.on("mouseout",(function(e){e.target==t.$container[0]&&(t.$container.off("mouseout"),t.delayedClose())}))}))},preventDelayedClose:function(){this._preventDelayedClose=!0,this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null),this.$container.off("mouseover mouseout")}}),Garnish.$scrollContainer=Garnish.$win,Craft.cp=new Craft.CP;var r=Garnish.Base.extend({$li:null,$a:null,$label:null,$progressLabel:null,progress:null,failMode:!1,_$bgCanvas:null,_$staticCanvas:null,_$hoverCanvas:null,_$failCanvas:null,_staticCtx:null,_hoverCtx:null,_canvasSize:null,_arcPos:null,_arcRadius:null,_lineWidth:null,_arcStartPos:0,_arcEndPos:0,_arcStartStepSize:null,_arcEndStepSize:null,_arcStep:null,_arcStepTimeout:null,_arcAnimateCallback:null,_progressBar:null,init:function(){this.$li=e()("<li/>").appendTo(Craft.cp.$nav.children("ul")),this.$a=e()("<a/>",{id:"job-icon",href:Craft.canAccessQueueManager?Craft.getUrl("utilities/queue-manager"):null}).appendTo(this.$li),this.$canvasContainer=e()('<span class="icon"/>').appendTo(this.$a);var t=e()('<span class="label"/>').appendTo(this.$a);this.$label=e()("<span/>").appendTo(t),this.$progressLabel=e()('<span class="progress-label"/>').appendTo(t).hide();var i=window.devicePixelRatio>1?2:1;this._canvasSize=18*i,this._arcPos=this._canvasSize/2,this._arcRadius=7*i,this._lineWidth=3*i,this._$bgCanvas=this._createCanvas("bg","#61666b"),this._$staticCanvas=this._createCanvas("static","#d7d9db"),this._$hoverCanvas=this._createCanvas("hover","#fff"),this._$failCanvas=this._createCanvas("fail","#da5a47").hide(),this._staticCtx=this._$staticCanvas[0].getContext("2d"),this._hoverCtx=this._$hoverCanvas[0].getContext("2d"),this._drawArc(this._$bgCanvas[0].getContext("2d"),0,1),this._drawArc(this._$failCanvas[0].getContext("2d"),0,1)},setDescription:function(t,e){this.$a.attr("title",t),this.$label.text(t),e?this.$progressLabel.text(e).show():this.$progressLabel.hide()},setProgress:function(t){0==t?(this._$staticCanvas.hide(),this._$hoverCanvas.hide()):(this._$staticCanvas.show(),this._$hoverCanvas.show(),this.progress&&t>this.progress?this._animateArc(0,t/100):this._setArc(0,t/100)),this.progress=t},complete:function(){var t=this;this._animateArc(0,1,(function(){t._$bgCanvas.velocity("fadeOut"),t._animateArc(1,1,(function(){t.$a.remove(),t.destroy()}))}))},showFailMode:function(t){this.failMode||(this.failMode=!0,this.progress=null,this._$bgCanvas.hide(),this._$staticCanvas.hide(),this._$hoverCanvas.hide(),this._$failCanvas.show(),this.setDescription(t))},hideFailMode:function(){this.failMode&&(this.failMode=!1,this._$bgCanvas.show(),this._$staticCanvas.show(),this._$hoverCanvas.show(),this._$failCanvas.hide())},_createCanvas:function(t,i){var s=e()('<canvas id="job-icon-'+t+'" width="'+this._canvasSize+'" height="'+this._canvasSize+'"/>').appendTo(this.$canvasContainer),n=s[0].getContext("2d");return n.strokeStyle=i,n.lineWidth=this._lineWidth,n.lineCap="round",s},_setArc:function(t,e){this._arcStartPos=t,this._arcEndPos=e,this._drawArc(this._staticCtx,t,e),this._drawArc(this._hoverCtx,t,e)},_drawArc:function(t,e,i){t.clearRect(0,0,this._canvasSize,this._canvasSize),t.beginPath(),t.arc(this._arcPos,this._arcPos,this._arcRadius,(1.5+2*e)*Math.PI,(1.5+2*i)*Math.PI),t.stroke(),t.closePath()},_animateArc:function(t,e,i){this._arcStepTimeout&&clearTimeout(this._arcStepTimeout),this._arcStep=0,this._arcStartStepSize=(t-this._arcStartPos)/10,this._arcEndStepSize=(e-this._arcEndPos)/10,this._arcAnimateCallback=i,this._takeNextArcStep()},_takeNextArcStep:function(){this._setArc(this._arcStartPos+this._arcStartStepSize,this._arcEndPos+this._arcEndStepSize),this._arcStep++,this._arcStep<10?this._arcStepTimeout=setTimeout(this._takeNextArcStep.bind(this),50):this._arcAnimateCallback&&this._arcAnimateCallback()}});__webpack_require__(3778),__webpack_require__(6617),__webpack_require__(9482),__webpack_require__(3352),__webpack_require__(691),__webpack_require__(1519),__webpack_require__(501),__webpack_require__(2318),__webpack_require__(4755),__webpack_require__(8468),__webpack_require__(5049),__webpack_require__(7998),__webpack_require__(4233),__webpack_require__(9699),__webpack_require__(1402),__webpack_require__(8201),__webpack_require__(9712),__webpack_require__(3347),__webpack_require__(9478),__webpack_require__(2387),__webpack_require__(7966),__webpack_require__(657),__webpack_require__(4487),__webpack_require__(6966),__webpack_require__(5080),__webpack_require__(7439),__webpack_require__(5328),__webpack_require__(6419),__webpack_require__(872),__webpack_require__(1396),__webpack_require__(4070),__webpack_require__(5763),__webpack_require__(5185),__webpack_require__(8030),__webpack_require__(3096),__webpack_require__(3331),__webpack_require__(53),__webpack_require__(5074),__webpack_require__(3958),__webpack_require__(1592),__webpack_require__(1752),__webpack_require__(7e3),__webpack_require__(8654)}()})();
+(function(){var __webpack_modules__={463:function(){Craft.Accordion=Garnish.Base.extend({$trigger:null,targetSelector:null,_$target:null,init:function(t){var e=this;this.$trigger=$(t),this.$trigger.data("accordion")&&(console.warn("Double-instantiating an accordion trigger on an element"),this.$trigger.data("accordion").destroy()),this.$trigger.data("accordion",this),this.targetSelector=this.$trigger.attr("aria-controls")?"#".concat(this.$trigger.attr("aria-controls")):null,this.targetSelector&&(this._$target=$(this.targetSelector)),this.addListener(this.$trigger,"click","onTriggerClick"),this.addListener(this.$trigger,"keypress",(function(t){var i=t.keyCode;i!==Garnish.SPACE_KEY&&i!==Garnish.RETURN_KEY||(t.preventDefault(),e.onTriggerClick())}))},onTriggerClick:function(){"true"===this.$trigger.attr("aria-expanded")?this.hideTarget(this._$target):this.showTarget(this._$target)},showTarget:function(t){var e=this;if(t&&t.length){this.showTarget._currentHeight=t.height(),t.removeClass("hidden"),this.$trigger.removeClass("collapsed").addClass("expanded").attr("aria-expanded","true");for(var i=0;i<t.length;i++)!function(t){"SPAN"!==t.prop("nodeName")&&(t.height("auto"),e.showTarget._targetHeight=t.height(),t.css({height:e.showTarget._currentHeight,overflow:"hidden"}),t.velocity("stop"),t.velocity({height:e.showTarget._targetHeight},Garnish.getUserPreferredAnimationDuration("fast"),(function(){t.css({height:"",overflow:""})})))}(t.eq(i));delete this.showTarget._targetHeight,delete this.showTarget._currentHeight,Garnish.$win.trigger("resize")}},hideTarget:function(t){if(t&&t.length){this.$trigger.removeClass("expanded").addClass("collapsed").attr("aria-expanded","false");for(var e=0;e<t.length;e++)!function(t){t.hasClass("hidden")||("SPAN"===t.prop("nodeName")?t.addClass("hidden"):(t.css("overflow","hidden"),t.velocity("stop"),t.velocity({height:0},Garnish.getUserPreferredAnimationDuration("fast"),(function(){t.addClass("hidden")}))))}(t.eq(e))}},destroy:function(){this.$trigger.removeData("accordion"),this.base()}})},3839:function(){Craft.AddressesInput=Garnish.Base.extend({$container:null,$addBtn:null,$addBtnItem:null,$cards:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.AddressesInput.defaults),this.$container.data("addresses")&&(console.warn("Double-instantiating an address input on an element"),this.$container.data("addresses").destroy()),this.$container.data("addresses",this),this.$addBtn=this.$container.find(".address-cards__add-btn"),this.$addBtnItem=this.$addBtn.closest("li"),this.$cards=this.$container.find("> .address-card");for(var s=0;s<this.$cards.length;s++)this.initCard(this.$cards.eq(s));this.updateAddButton(),this.addListener(this.$addBtn,"click",(function(){i.createAddress()}))},initCard:function(t){var e=this;this.addListener(t,"click",(function(i){$(i.target).closest(".menubtn").length||e.editAddress(t)}));var i=t.find(".menubtn").disclosureMenu();if(i.length){var s=i.data("trigger"),n=s.$container,a=n.find('[data-action="edit"]');this.addListener(a,"click",(function(i){i.stopPropagation(),e.editAddress(t)}));var r=n.find('[data-action="delete"]');this.addListener(r,"click",(function(i){if(i.preventDefault(),i.stopPropagation(),confirm(Craft.t("app","Are you sure you want to delete this address?"))){e.$addBtn.addClass("loading");var a=t.data("id"),r=t.data("draft-id");Craft.sendActionRequest("POST","elements/delete",{data:{elementId:a,draftId:r}}).then((function(){t.remove(),n.remove(),s.destroy(),e.$cards=e.$cards.not(t),e.updateAddButton(),e.trigger("deleteAddress",{addressId:a,draftId:r})})).finally((function(){e.$addBtn.removeClass("loading")}))}}))}},editAddress:function(t,e){var i=this;Craft.createElementEditor("craft\\elements\\Address",t,e).on("submit",(function(e){i.trigger("saveAddress",{data:e.data}),Craft.sendActionRequest("POST","addresses/card-html",{data:{addressId:e.data.id}}).then((function(e){var s=$(e.data.html);t?(t.replaceWith(s),i.$cards=i.$cards.not(t)):s.insertBefore(i.$addBtnItem),Craft.initUiElements(s),i.initCard(s),i.$cards=i.$cards.add(s),i.updateAddButton()}))}))},updateAddButton:function(){this.canCreateAddress()?this.$addBtn.removeClass("hidden"):this.$addBtn.addClass("hidden")},canCreateAddress:function(){return!this.settings.maxAddresses||this.$cards.length<this.settings.maxAddresses},createAddress:function(){var t=this;if(!this.canCreateAddress())throw"No more addresses can be created.";this.$addBtn.addClass("loading"),Craft.sendActionRequest("POST","elements/create",{data:{elementType:"craft\\elements\\Address",ownerId:this.settings.ownerId}}).then((function(e){t.editAddress(null,{elementId:e.data.element.id,draftId:e.data.element.draftId})})).finally((function(){t.$addBtn.removeClass("loading")}))},destroy:function(){this.$container.removeData("addresses"),this.base()}},{ownerId:null,defaults:{maxAddresses:null}})},7452:function(){Craft.AdminTable=Garnish.Base.extend({settings:null,totalItems:null,sorter:null,$noItems:null,$table:null,$tbody:null,$deleteBtns:null,init:function(t){var e=this;this.setSettings(t,Craft.AdminTable.defaults),this.settings.allowDeleteAll||(this.settings.minItems=1),this.$noItems=$(this.settings.noItemsSelector),this.$table=$(this.settings.tableSelector),this.$tbody=this.$table.children("tbody"),this.totalItems=this.$tbody.children().length,this.settings.sortable&&(this.sorter=new Craft.DataTableSorter(this.$table,{onSortChange:this.reorderItems.bind(this)})),this.$deleteBtns=this.$table.find(".delete:not(.disabled)"),this.addListener(this.$deleteBtns,"click","handleDeleteBtnClick"),this.addListener(this.$deleteBtns,"keydown",(function(t){t.keyCode!==Garnish.SPACE_KEY&&t.keyCode!==Garnish.RETURN_KEY||(t.preventDefault(),e.handleDeleteBtnClick(t))})),this.updateUI()},addRow:function(t){if(!(this.settings.maxItems&&this.totalItems>=this.settings.maxItems)){var e=$(t).appendTo(this.$tbody),i=e.find(".delete");this.settings.sortable&&this.sorter.addItems(e),this.$deleteBtns=this.$deleteBtns.add(i),this.addListener(i,"click","handleDeleteBtnClick"),this.totalItems++,this.updateUI()}},reorderItems:function(){var t=this;if(this.settings.sortable){for(var e=[],i=0;i<this.sorter.$items.length;i++){var s=$(this.sorter.$items[i]).attr(this.settings.idAttribute);e.push(s)}var n={ids:JSON.stringify(e)};Craft.sendActionRequest("POST",this.settings.reorderAction,{data:n}).then((function(i){t.onReorderItems(e),Craft.cp.displaySuccess(Craft.t("app",t.settings.reorderSuccessMessage))})).catch((function(e){e.response,Craft.cp.displayError(Craft.t("app",t.settings.reorderFailMessage))}))}},handleDeleteBtnClick:function(t){if(!(this.settings.minItems&&this.totalItems<=this.settings.minItems)){var e=$(t.target).closest("tr");this.confirmDeleteItem(e)&&this.deleteItem(e)}},confirmDeleteItem:function(t){if(!this.settings.confirmDeleteMessage)return!0;var e=this.getItemName(t);return confirm(Craft.t("app",this.settings.confirmDeleteMessage,{name:e}))},deleteItem:function(t){var e=this,i={id:this.getItemId(t)};Craft.sendActionRequest("POST",this.settings.deleteAction,{data:i}).then((function(i){return e.handleDeleteItemSuccess(i.data,t)})).catch((function(i){var s=i.response;return e.handleDeleteItemFailure(s.data,t)}))},handleDeleteItemFailure:function(t,e){this.getItemId(e);var i=this.getItemName(e);Craft.cp.displayError(Craft.t("app",this.settings.deleteFailMessage,{name:i}))},handleDeleteItemSuccess:function(t,e){var i=this.getItemId(e),s=this.getItemName(e);this.sorter&&this.sorter.removeItems(e),e.remove(),this.totalItems--,this.updateUI(),this.onDeleteItem(i),this.settings.deleteSuccessMessage&&Craft.cp.displaySuccess(Craft.t("app",this.settings.deleteSuccessMessage,{name:s}))},onReorderItems:function(t){this.settings.onReorderItems(t)},onDeleteItem:function(t){this.settings.onDeleteItem(t)},getItemId:function(t){return t.attr(this.settings.idAttribute)},getItemName:function(t){return Craft.escapeHtml(t.attr(this.settings.nameAttribute))},updateUI:function(){if(0===this.totalItems?(this.$table.hide(),this.$noItems.removeClass("hidden")):(this.$table.show(),this.$noItems.addClass("hidden")),this.settings.sortable){var t=this.$table.find(".move");1===this.totalItems?t.addClass("disabled"):t.removeClass("disabled")}this.settings.minItems&&this.totalItems<=this.settings.minItems?this.$deleteBtns.addClass("disabled"):this.$deleteBtns.removeClass("disabled"),this.settings.newItemBtnSelector&&(this.settings.maxItems&&this.totalItems>=this.settings.maxItems?$(this.settings.newItemBtnSelector).addClass("hidden"):$(this.settings.newItemBtnSelector).removeClass("hidden"))}},{defaults:{tableSelector:null,noItemsSelector:null,newItemBtnSelector:null,idAttribute:"data-id",nameAttribute:"data-name",sortable:!1,allowDeleteAll:!0,minItems:0,maxItems:null,reorderAction:null,deleteAction:null,reorderSuccessMessage:Craft.t("app","New order saved."),reorderFailMessage:Craft.t("app","Couldn’t save new order."),confirmDeleteMessage:Craft.t("app","Are you sure you want to delete “{name}”?"),deleteSuccessMessage:Craft.t("app","“{name}” deleted."),deleteFailMessage:Craft.t("app","Couldn’t delete “{name}”."),onReorderItems:$.noop,onDeleteItem:$.noop}})},6872:function(){Craft.AssetImageEditor=Garnish.Modal.extend({$body:null,$footer:null,$imageTools:null,$buttons:null,$cancelBtn:null,$replaceBtn:null,$saveBtn:null,$focalPointBtn:null,$editorContainer:null,$straighten:null,$croppingCanvas:null,$spinner:null,$constraintContainer:null,$constraintRadioInputs:null,$customConstraints:null,canvas:null,image:null,viewport:null,focalPoint:null,grid:null,croppingCanvas:null,clipper:null,croppingRectangle:null,cropperHandles:null,cropperGrid:null,croppingShade:null,imageStraightenAngle:0,viewportRotation:0,originalWidth:0,originalHeight:0,imageVerticeCoords:null,zoomRatio:1,animationInProgress:!1,currentView:"",assetId:null,cacheBust:null,draggingCropper:!1,scalingCropper:!1,draggingFocal:!1,previousMouseX:0,previousMouseY:0,shiftKeyHeld:!1,editorHeight:0,editorWidth:0,cropperState:!1,scaleFactor:1,flipData:{},focalPointState:!1,maxImageSize:null,lastLoadedDimensions:null,imageIsLoading:!1,mouseMoveEvent:null,croppingConstraint:!1,constraintOrientation:"landscape",showingCustomConstraint:!1,saving:!1,renderImage:null,renderCropper:null,_queue:null,init:function(t,e){var i=this;this._queue=new Craft.Queue,this.cacheBust=Date.now(),this.setSettings(e,Craft.AssetImageEditor.defaults),null===this.settings.allowDegreeFractions&&(this.settings.allowDegreeFractions=Craft.isImagick),Garnish.prefersReducedMotion()&&(this.settings.animationDuration=1),this.assetId=t,this.flipData={x:0,y:0},this.$container=$('<form class="modal fitted imageeditor"></form>').appendTo(Garnish.$bod),this.$body=$('<div class="body"></div>').appendTo(this.$container),this.$footer=$('<div class="footer"/>').appendTo(this.$container),this.base(this.$container,this.settings),this.$buttons=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn cancel",text:Craft.t("app","Cancel")}).appendTo(this.$buttons),this.settings.allowSavingAsNew&&(this.$saveBtn=Craft.ui.createButton({class:"save copy",label:Craft.t("app","Save as a new asset"),spinner:!0}).appendTo(this.$buttons),this.addListener(this.$saveBtn,"activate",this.saveImage)),this.$replaceBtn=Craft.ui.createSubmitButton({class:"save replace",label:Craft.t("app","Save"),spinner:!0}).appendTo(this.$buttons),this.addListener(this.$replaceBtn,"activate",this.saveImage),this.addListener(this.$cancelBtn,"activate",this.hide),this.removeListener(this.$shade,"click"),this.maxImageSize=this.getMaxImageSize(),Craft.sendActionRequest("POST","assets/image-editor",{data:{assetId:t}}).then((function(t){return i.loadEditor(t.data)}))},getMaxImageSize:function(){var t=Garnish.$doc.get(0).documentElement.clientWidth,e=Garnish.$doc.get(0).documentElement.clientHeight;return Math.max(e,t)*(window.devicePixelRatio>1?2:1)},loadEditor:function(t){var e=this;t.html||Craft.cp.displayError(Craft.t("app","Could not load the image editor.")),this.$body.html(t.html),this.$tabs=$(".tabs li",this.$body),this.$viewsContainer=$(".views",this.$body),this.$views=$("> div",this.$viewsContainer),this.$imageTools=$(".image-container .image-tools",this.$body),this.$editorContainer=$(".image-container .image",this.$body),this.$constraintContainer=$(".constraint-group",this.$body),this.$constraintRadioInputs=$('[name="constraint"]',this.$constraintContainer),this.$focalPointBtn=$(".focal-point",this.$body),this.editorHeight=this.$editorContainer.innerHeight(),this.editorWidth=this.$editorContainer.innerWidth(),this._showSpinner(),this.updateSizeAndPosition(),$customConstraintWrapper=this.$constraintRadioInputs.filter('[value="custom"]').parent(),this.$customConstraints=$("<div/>",{class:"constraint custom hidden","data-constraint":"custom"}).append($("<input/>",{type:"text",class:"custom-constraint-w",size:3,value:1,"aria-label":Craft.t("app","Width unit")})).append($("<span/>",{class:"custom-constraint-spacer",text:"x","aria-hidden":"true"})).append($("<input/>",{type:"text",class:"custom-constraint-h",size:3,value:1,"aria-label":Craft.t("app","Height unit")})).appendTo($customConstraintWrapper),this.$constraintRadioInputs.filter((function(){var t=$(this).val();return/^\d*\.\d+$/.test(t)})).addClass("flip"),this.canvas=new fabric.StaticCanvas("image-canvas"),this.$croppingCanvas=$("#cropping-canvas",this.$editorContainer),this.$croppingCanvas.width(this.editorWidth),this.$croppingCanvas.height(this.editorHeight),this.canvas.enableRetinaScaling=!0,this.renderImage=function(){Garnish.requestAnimationFrame(e.canvas.renderAll.bind(e.canvas))};var i=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});fabric.Image.fromURL(i,(function(i){e.image=i,e.image.set({originX:"center",originY:"center",left:e.editorWidth/2,top:e.editorHeight/2}),e.canvas.add(e.image),e.originalHeight=e.image.getHeight(),e.originalWidth=e.image.getWidth(),e.zoomRatio=1,e.lastLoadedDimensions=e.getScaledImageDimensions(),e._setFittedImageVerticeCoordinates(),e._repositionEditorElements();var s={imageDimensions:e.getScaledImageDimensions(),offsetX:0,offsetY:0},n=!1;if(t.focalPoint){var a=t.focalPoint,r=s.imageDimensions.width*a.x,o=s.imageDimensions.height*a.y;s.offsetX=r-s.imageDimensions.width/2,s.offsetY=o-s.imageDimensions.height/2,n=!0}e.storeFocalPointState(s),n&&e._createFocalPoint(),e._createViewport(),e.storeCropperState(),e._addControlListeners(),e.addListener(e.$croppingCanvas,"mousemove,touchmove",e._handleMouseMove),e.addListener(e.$croppingCanvas,"mousedown,touchstart",e._handleMouseDown),e.addListener(e.$croppingCanvas,"mouseup,touchend",e._handleMouseUp),e.addListener(e.$croppingCanvas,"mouseout,touchcancel",e._handleMouseOut),e._hideSpinner(),e.renderImage(),e.$tabs.first().trigger("click")}))},_reloadImage:function(){var t=this;if(!this.imageIsLoading){this.imageIsLoading=!0,this.maxImageSize=this.getMaxImageSize();var e=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});this.image.setSrc(e,(function(e){t.originalHeight=e.getHeight(),t.originalWidth=e.getWidth(),t.lastLoadedDimensions={width:t.originalHeight,height:t.originalWidth},t.updateSizeAndPosition(),t.renderImage(),t.imageIsLoading=!1}))}},updateSizeAndPosition:function(){if(this.$container){var t=window.innerWidth,e=window.innerHeight;this.$container.css({width:t,"min-width":t,left:0,height:e,"min-height":e,top:0}),this.$body.css({height:e-(this.$footer.outerHeight()-1)}),t<e?this.$container.addClass("vertical"):this.$container.removeClass("vertical"),this.$editorContainer&&this.image&&this._repositionEditorElements()}},_repositionEditorElements:function(){var t={width:this.editorWidth,height:this.editorHeight};this.editorHeight=this.$editorContainer.innerHeight(),this.editorWidth=this.$editorContainer.innerWidth(),this.canvas.setDimensions({width:this.editorWidth,height:this.editorHeight});var e=this.getScaledImageDimensions();if("crop"===this.currentView){this.zoomRatio=this.getZoomToFitRatio(this.getScaledImageDimensions());var i=this._getBoundingRectangle(this.imageVerticeCoords);this._setFittedImageVerticeCoordinates(),this._repositionCropper(i)}else this.zoomRatio=this.getZoomToCoverRatio(this.getScaledImageDimensions())*this.scaleFactor;this._repositionImage(t),this._repositionViewport(),this._repositionFocalPoint(t),this._zoomImage(),this.renderImage(),(e.width/this.lastLoadedDimensions.width>1.5||e.height/this.lastLoadedDimensions.height>1.5)&&this._reloadImage()},_repositionImage:function(t){this.image.set({left:this.image.left-(t.width-this.editorWidth)/2,top:this.image.top-(t.height-this.editorHeight)/2})},_createViewport:function(){this.viewport=new fabric.Rect({width:this.image.width,height:this.image.height,fill:"rgba(127,0,0,1)",originX:"center",originY:"center",globalCompositeOperation:"destination-in",left:this.image.left,top:this.image.top}),this.canvas.add(this.viewport),this.renderImage()},_createFocalPoint:function(){var t=this.focalPointState,e=this.getScaledImageDimensions().width/t.imageDimensions.width,i=t.offsetX*e*this.zoomRatio*this.scaleFactor,s=t.offsetY*e*this.zoomRatio*this.scaleFactor;i+=this.image.left,s+=this.image.top;var n=0,a=0;this.viewport&&0===t.offsetX&&0===t.offsetY&&("crop"!==this.currentView?(n=this.viewport.left-this.image.left,a=this.viewport.top-this.image.top):(n=this.clipper.left-this.image.left,a=this.clipper.top-this.image.top),i+=n,s+=a,t.offsetX+=n/(e*this.zoomRatio*this.scaleFactor),t.offsetY+=a/(e*this.zoomRatio*this.scaleFactor)),this.focalPoint=new fabric.Group([new fabric.Circle({radius:8,fill:"rgba(0,0,0,0.5)",strokeWidth:2,stroke:"rgba(255,255,255,0.8)",left:0,top:0,originX:"center",originY:"center"}),new fabric.Circle({radius:1,fill:"rgba(255,255,255,0)",strokeWidth:2,stroke:"rgba(255,255,255,0.8)",left:0,top:0,originX:"center",originY:"center"})],{originX:"center",originY:"center",left:i,top:s}),this.storeFocalPointState(t),this.canvas.add(this.focalPoint)},toggleFocalPoint:function(){this.focalPoint?(this.canvas.remove(this.focalPoint),this.focalPoint=null,this.$focalPointBtn.attr("aria-pressed","false")):(this._createFocalPoint(),this.$focalPointBtn.attr("aria-pressed","true")),this.renderImage()},_repositionViewport:function(){if(this.viewport){var t={left:this.editorWidth/2,top:this.editorHeight/2};if("crop"===this.currentView)t.width=this.editorWidth,t.height=this.editorHeight;else if(this.cropperState){var e=this.cropperState,i=this.getScaledImageDimensions().width/e.imageDimensions.width;t.width=e.width*i*this.zoomRatio,t.height=e.height*i*this.zoomRatio,this.image.set({left:this.editorWidth/2-e.offsetX*i,top:this.editorHeight/2-e.offsetY*i})}else $.extend(t,this.getScaledImageDimensions());this.viewport.set(t)}},_repositionFocalPoint:function(t){if(this.focalPoint){var e=this.focalPoint.left-this.editorWidth/2,i=this.focalPoint.top-this.editorHeight/2,s=this.image.width,n=this.getScaledImageDimensions().width*this.zoomRatio/s/this.scaleFactor;e-=(t.width-this.editorWidth)/2,i-=(t.height-this.editorHeight)/2,e*=n,i*=n,this.focalPoint.set({left:this.editorWidth/2+e,top:this.editorHeight/2+i})}},hasOrientationChanged:function(){return this.viewportRotation%180!=0},getScaledImageDimensions:function(){return void 0===this.getScaledImageDimensions._&&(this.getScaledImageDimensions._={}),this.getScaledImageDimensions._.imageRatio=this.originalHeight/this.originalWidth,this.getScaledImageDimensions._.editorRatio=this.editorHeight/this.editorWidth,this.getScaledImageDimensions._.dimensions={},this.getScaledImageDimensions._.imageRatio>this.getScaledImageDimensions._.editorRatio?(this.getScaledImageDimensions._.dimensions.height=Math.min(this.editorHeight,this.originalHeight),this.getScaledImageDimensions._.dimensions.width=Math.round(this.originalWidth/(this.originalHeight/this.getScaledImageDimensions._.dimensions.height))):(this.getScaledImageDimensions._.dimensions.width=Math.min(this.editorWidth,this.originalWidth),this.getScaledImageDimensions._.dimensions.height=Math.round(this.originalHeight*(this.getScaledImageDimensions._.dimensions.width/this.originalWidth))),this.getScaledImageDimensions._.dimensions},_zoomImage:function(){void 0===this._zoomImage._&&(this._zoomImage._={}),this._zoomImage._.imageDimensions=this.getScaledImageDimensions(),this.image.set({width:this._zoomImage._.imageDimensions.width*this.zoomRatio,height:this._zoomImage._.imageDimensions.height*this.zoomRatio})},_getPrevTab:function(){var t,e=this._getActiveTabIndex();if(!(e<0))return t=e>0?e-1:this.$tabs.length-1,this.$tabs.eq(t)},_getNextTab:function(){var t,e=this._getActiveTabIndex();if(!(e<0))return t=e<this.$tabs.length-1?e+1:0,this.$tabs.eq(t)},_getActiveTab:function(){return this.$tabs.filter('[aria-selected="true"]')},_getActiveTabIndex:function(){var t=this._getActiveTab();if(t.length)return t.index()},_addControlListeners:function(){var t=this;this.addListener(this.$tabs,"click",this._handleTabClick),this.addListener(this.$tabs,"keydown",(function(e){switch(e.keyCode){case Garnish.LEFT_KEY:case Garnish.UP_KEY:e.preventDefault();var i=t._getPrevTab();t.activateTab(i);break;case Garnish.RIGHT_KEY:case Garnish.DOWN_KEY:e.preventDefault();var s=t._getNextTab();t.activateTab(s)}})),this.addListener(this.$focalPointBtn,"click",this.toggleFocalPoint),this.addListener($(".rotate-left"),"click",(function(){this.rotateImage(-90)})),this.addListener($(".rotate-right"),"click",(function(){this.rotateImage(90)})),this.addListener($(".flip-vertical"),"click",(function(){this.flipImage("y")})),this.addListener($(".flip-horizontal"),"click",(function(){this.flipImage("x")})),this.straighteningInput=new Craft.SlideRuleInput("slide-rule",{onStart:function(){t._showGrid()},onChange:function(e){t.straighten(e)},onEnd:function(){t._hideGrid(),t._cleanupFocalPointAfterStraighten()}}),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.SHIFT_KEY&&(this.shiftKeyHeld=!0)})),this.addListener(Garnish.$doc,"keyup",(function(t){t.keyCode===Garnish.SHIFT_KEY&&(this.shiftKeyHeld=!1)})),this.addListener(this.$constraintRadioInputs,"change",this._handleConstraintChange),this.addListener($(".orientation input",this.$container),"click",this._handleOrientationClick),this.addListener($(".constraint-group .custom input",this.$container),"keyup",this._applyCustomConstraint)},_handleConstraintClick:function(t){var e=$(t.currentTarget).data("constraint"),i=$(t.currentTarget);if(i.siblings().removeClass("active"),i.addClass("active"),"custom"==e)return this._showCustomConstraint(),void this._applyCustomConstraint();this._hideCustomConstraint(),this.setCroppingConstraint(e),this.enforceCroppingConstraint()},_handleConstraintChange:function(t){var e=$(t.target).val();if("custom"==e)return this._showCustomConstraint(),void this._applyCustomConstraint();this._hideCustomConstraint(),this.setCroppingConstraint(e),this.enforceCroppingConstraint()},_handleOrientationClick:function(t){if(t.currentTarget.value!==this.constraintOrientation){this.constraintOrientation=t.currentTarget.value;for(var e=$(".flip",this.$constraintContainer),i=0;i<e.length;i++){var s=$(e[i]),n='label[for="'+s.attr("id")+'"]',a=$(n,this.$constraintContainer);s.val(1/s.val()),a.html(a.text().split(":").reverse().join(":").replace(/\s/g,""))}e.filter(":checked").trigger("change")}},_applyCustomConstraint:function(){var t=this._getCustomConstraint();t.w>0&&t.h>0&&(this.setCroppingConstraint(t.w/t.h),this.enforceCroppingConstraint())},_getCustomConstraint:function(){var t=parseFloat($(".custom-constraint-w").val()),e=parseFloat($(".custom-constraint-h").val());return{w:isNaN(t)?0:t,h:isNaN(e)?0:e}},_setCustomConstraint:function(t,e){$(".custom-constraint-w").val(parseFloat(t)),$(".custom-constraint-h").val(parseFloat(e))},_hideCustomConstraint:function(){this.showingCustomConstraint=!1,this.$customConstraints.addClass("hidden"),$(".orientation",this.$container).removeClass("hidden")},_showCustomConstraint:function(){this.showingCustomConstraint||(this.showingCustomConstraint=!0,this.$customConstraints.removeClass("hidden"),$(".orientation",this.$container).addClass("hidden"))},_handleTabClick:function(t){if(!this.animationInProgress){var e=$(t.currentTarget);this.activateTab(e)}},activateTab:function(t){var e=$(t).data("view");this.$tabs.removeClass("selected").attr({"aria-selected":"false",tabindex:"-1"}),$(t).addClass("selected").attr({"aria-selected":"true",tabindex:"0"}).trigger("focus"),this.showView(e)},showView:function(t){var e=this;this.currentView!==t&&(this.$views.addClass("hidden"),this.$views.filter('[data-view="'+t+'"]').removeClass("hidden"),"rotate"===t?this.enableSlider():this.disableSlider(),this.updateSizeAndPosition(),"crop"===this.currentView&&"crop"!==t?this._queue.push((function(){return new Promise((function(t,i){e.disableCropMode(),t()}))})):"crop"!==this.currentView&&"crop"===t&&this._queue.push((function(){return new Promise((function(t,i){e.enableCropMode(),t()}))})),this.currentView=t)},storeCropperState:function(t){void 0===this.storeCropperState._&&(this.storeCropperState._={}),t?this.cropperState=t:this.clipper?(this.storeCropperState._.zoomFactor=1/this.zoomRatio,this.cropperState={offsetX:(this.clipper.left-this.image.left)*this.storeCropperState._.zoomFactor,offsetY:(this.clipper.top-this.image.top)*this.storeCropperState._.zoomFactor,height:this.clipper.height*this.storeCropperState._.zoomFactor,width:this.clipper.width*this.storeCropperState._.zoomFactor,imageDimensions:this.getScaledImageDimensions()}):(this.storeCropperState._.dimensions=this.getScaledImageDimensions(),this.cropperState={offsetX:0,offsetY:0,height:this.storeCropperState._.dimensions.height,width:this.storeCropperState._.dimensions.width,imageDimensions:this.storeCropperState._.dimensions})},storeFocalPointState:function(t){void 0===this.storeFocalPointState._&&(this.storeFocalPointState._={}),t?this.focalPointState=t:this.focalPoint&&(this.storeFocalPointState._.zoomFactor=1/this.zoomRatio,this.focalPointState={offsetX:(this.focalPoint.left-this.image.left)*this.storeFocalPointState._.zoomFactor/this.scaleFactor,offsetY:(this.focalPoint.top-this.image.top)*this.storeFocalPointState._.zoomFactor/this.scaleFactor,imageDimensions:this.getScaledImageDimensions()})},rotateImage:function(t){var e=this;if(!this.animationInProgress){if(90!==t&&-90!==t)return!1;this.animationInProgress=!0,this.viewportRotation+=t,this.viewportRotation=parseInt((this.viewportRotation+360)%360,10);var i,s=this.image.angle+t,n=this.getScaledImageDimensions();i=this.hasOrientationChanged()?this.getZoomToCoverRatio({height:n.width,width:n.height}):this.getZoomToCoverRatio(n),this.zoomRatio>i&&(i=this.zoomRatio);var a={angle:90===t?"+=90":"-=90"},r={angle:s,width:n.width*i,height:n.height*i},o=1;this.scaleFactor<1?(o=1/this.scaleFactor,this.scaleFactor=1):(this.viewport.width>this.editorHeight?o=this.editorHeight/this.viewport.width:this.viewport.height>this.editorWidth&&(o=this.editorWidth/this.viewport.height),this.scaleFactor=o),o<1&&(r.width*=o,r.height*=o);var l=this.cropperState,h=l.offsetX,d=l.offsetY,c=t*(Math.PI/180),u=h*Math.cos(c)-d*Math.sin(c),p=h*Math.sin(c)+d*Math.cos(c),f=n.width/l.imageDimensions.width,g=u*f*this.zoomRatio*this.scaleFactor,m=p*f*this.zoomRatio*this.scaleFactor;r.left=this.editorWidth/2-g,r.top=this.editorHeight/2-m,l.offsetX=u,l.offsetY=p;var v=l.width;l.width=l.height,l.height=v,this.storeCropperState(l),this.focalPoint&&this.canvas.remove(this.focalPoint),this.viewport.animate(a,{duration:this.settings.animationDuration,onComplete:function(){var t=e.viewport.height*o;e.viewport.height=e.viewport.width*o,e.viewport.width=t,e.viewport.set({angle:0})}}),this.image.animate(r,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){var i=parseFloat((e.image.angle+360)%360);e.image.set({angle:i}),e.animationInProgress=!1,e.focalPoint?(e._adjustFocalPointByAngle(t),e.straighten(e.straighteningInput),e.canvas.add(e.focalPoint)):e._resetFocalPointPosition()}})}},flipImage:function(t){var e=this;if(!this.animationInProgress){this.animationInProgress=!0,this.hasOrientationChanged()&&(t="y"===t?"x":"y"),this.focalPoint?this.canvas.remove(this.focalPoint):this._resetFocalPointPosition();var i={x:this.editorWidth/2,y:this.editorHeight/2};this.straighteningInput.setValue(-this.imageStraightenAngle),this.imageStraightenAngle=-this.imageStraightenAngle;var s,n,a={angle:this.viewportRotation+this.imageStraightenAngle},r=this.cropperState,o=this.focalPointState;"y"===t&&this.hasOrientationChanged()||"y"!==t&&!this.hasOrientationChanged()?(r.offsetX=-r.offsetX,o.offsetX=-o.offsetX,n=this.image.left-i.x,a.left=i.x-n):(r.offsetY=-r.offsetY,o.offsetY=-o.offsetY,s=this.image.top-i.y,a.top=i.y-s),"y"===t?(a.scaleY=-1*this.image.scaleY,this.flipData.y=1-this.flipData.y):(a.scaleX=-1*this.image.scaleX,this.flipData.x=1-this.flipData.x),this.storeCropperState(r),this.storeFocalPointState(o),this.image.animate(a,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){e.animationInProgress=!1,e.focalPoint&&(e._adjustFocalPointByAngle(0),e.canvas.add(e.focalPoint))}})}},straighten:function(t){if(!this.animationInProgress){this.animationInProgress=!0;var e=this.image.angle;this.imageStraightenAngle=(this.settings.allowDegreeFractions?parseFloat(t.value):Math.round(parseFloat(t.value)))%360,this.image.set({angle:this.viewportRotation+this.imageStraightenAngle}),this.zoomRatio=this.getZoomToCoverRatio(this.getScaledImageDimensions())*this.scaleFactor,this._zoomImage(),this.cropperState&&this._adjustEditorElementsOnStraighten(e),this.renderImage(),this.animationInProgress=!1}},_adjustEditorElementsOnStraighten:function(t){var e,i,s,n,a,r=this.getScaledImageDimensions(),o=this.image.angle-t,l=this.cropperState,h=this.zoomRatio,d=1;do{var c=l.offsetX,u=l.offsetY,p=o*(Math.PI/180);s=c*Math.cos(p)-u*Math.sin(p),n=c*Math.sin(p)+u*Math.cos(p),e=s*h*(a=r.width/l.imageDimensions.width),i=n*h*a;var f=this.getImageVerticeCoords(h),g={width:this.viewport.width,height:this.viewport.height,left:this.editorWidth/2-this.viewport.width/2+e,top:this.editorHeight/2-this.viewport.height/2+i};h*=d=this._getZoomRatioToFitRectangle(g,f)}while(1!==d);this.image.set({left:this.editorWidth/2-e,top:this.editorHeight/2-i}),l.offsetX=s,l.offsetY=n,l.width=this.viewport.width/h/a,l.height=this.viewport.height/h/a,this.storeCropperState(l),this.zoomRatio=h,this.focalPoint?(this._adjustFocalPointByAngle(o),this._isCenterInside(this.focalPoint,this.viewport)?this.focalPoint.set({opacity:1}):this.focalPoint.set({opacity:0})):0!==o&&this._resetFocalPointPosition(),this._zoomImage()},_cleanupFocalPointAfterStraighten:function(){if(this.focalPoint&&!this._isCenterInside(this.focalPoint,this.viewport)){this.focalPoint.set({opacity:1});var t=this.focalPointState;t.offsetX=0,t.offsetY=0,this.storeFocalPointState(t),this.toggleFocalPoint()}},_resetFocalPointPosition:function(){var t=this.focalPointState;t.offsetX=0,t.offsetY=0,this.storeFocalPointState(t)},_isCenterInside:function(t,e){return t.left>e.left-e.width/2&&t.top>e.top-e.height/2&&t.left<e.left+e.width/2&&t.top<e.top+e.height/2},_adjustFocalPointByAngle:function(t){var e=t*(Math.PI/180),i=this.focalPointState,s=i.offsetX,n=i.offsetY,a=s*Math.cos(e)-n*Math.sin(e),r=s*Math.sin(e)+n*Math.cos(e),o=this.getScaledImageDimensions().width/i.imageDimensions.width,l=a*o*this.zoomRatio,h=r*o*this.zoomRatio;this.focalPoint.left=this.image.left+l,this.focalPoint.top=this.image.top+h,i.offsetX=a,i.offsetY=r,this.storeFocalPointState(i)},_getZoomRatioToFitRectangle:function(t,e){for(var i,s,n=this._getRectangleVertices(t),a=0;a<n.length&&(i=n[a],this.arePointsInsideRectangle([i],e));a++)i=!1;if(i){var r=this._getEdgeCrossed(e,i),o={x:t.left+t.width/2,y:t.top+t.height/2},l=Math.abs((r[1].y-r[0].y)*i.x-(r[1].x-r[0].x)*i.y+r[1].x*r[0].y-r[1].y*r[0].x)/Math.sqrt(Math.pow(r[1].y-r[0].y,2)+Math.pow(r[1].x-r[0].x,2)),h=Math.abs((r[1].y-r[0].y)*o.x-(r[1].x-r[0].x)*o.y+r[1].x*r[0].y-r[1].y*r[0].x)/Math.sqrt(Math.pow(r[1].y-r[0].y,2)+Math.pow(r[1].x-r[0].x,2));s=(l+h)/h}else s=1;return s},saveImage:function(t){var e=this,i=$(t.currentTarget);if(this.saving)return!1;this.saving=!0,i.addClass("loading");var s=i.hasClass("replace"),n={assetId:this.assetId,viewportRotation:this.viewportRotation,imageRotation:this.imageStraightenAngle,replace:s?1:0};if(this.cropperState){var a={};a.height=this.cropperState.height,a.width=this.cropperState.width,a.offsetX=this.cropperState.offsetX,a.offsetY=this.cropperState.offsetY,n.imageDimensions=this.cropperState.imageDimensions,n.cropData=a}else n.imageDimensions=this.getScaledImageDimensions();this.focalPoint&&(n.focalPoint=this.focalPointState),n.flipData=this.flipData,n.zoom=this.zoomRatio,Craft.sendActionRequest("POST","assets/save-image",{data:n}).then((function(t){var i=t.data;e.onSave(i),s&&Craft.broadcaster&&Craft.broadcaster.postMessage({event:"saveElement",id:e.assetId}),e.hide(),Craft.cp.runQueue(),Craft.Preview.refresh()})).catch((function(t){var e=t.response;Craft.cp.displayError(e.data.message)})).finally((function(){e.$buttons.find(".btn").removeClass("loading"),e.saving=!1}))},getZoomToCoverRatio:function(t){var e=Math.abs(this.imageStraightenAngle)*(Math.PI/180),i=Math.sin(e)*t.height+Math.cos(e)*t.width,s=Math.sin(e)*t.width+Math.cos(e)*t.height;return Math.max(i/t.width,s/t.height)},getZoomToFitRatio:function(t){var e=this._getImageBoundingBox(t),i=1;if(e.height>this.editorHeight||e.width>this.editorWidth){var s=this.editorHeight/e.height,n=this.editorWidth/e.width;i=Math.min(n,s)}return i},getCombinedZoomRatio:function(t){return this.getZoomToCoverRatio(t)/this.getZoomToFitRatio(t)},_showGrid:function(){if(!this.grid){var t,e={strokeWidth:1,stroke:"rgba(255,255,255,0.5)"},i=this.viewport.width,s=this.viewport.height,n=i/9,a=s/9,r=[new fabric.Rect({strokeWidth:2,stroke:"rgba(255,255,255,1)",originX:"center",originY:"center",width:i,height:s,left:i/2,top:s/2,fill:"rgba(255,255,255,0)"})];for(t=1;t<=8;t++)r.push(new fabric.Line([t*n,0,t*n,s],e));for(t=1;t<=8;t++)r.push(new fabric.Line([0,t*a,i,t*a],e));this.grid=new fabric.Group(r,{left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",angle:this.viewport.angle}),this.canvas.add(this.grid),this.renderImage()}},_hideGrid:function(){this.canvas.remove(this.grid),this.grid=null,this.renderImage()},onFadeOut:function(){this.destroy()},show:function(){this.base(),Garnish.$bod.addClass("no-scroll")},hide:function(){this.removeAllListeners(),this.straighteningInput.removeAllListeners(),Garnish.$bod.removeClass("no-scroll"),this.base()},onSave:function(t){this.settings.onSave(t),this.trigger("save")},enableSlider:function(){this.$imageTools.removeClass("hidden")},disableSlider:function(){this.$imageTools.addClass("hidden")},enableCropMode:function(){var t=this,e=this.getScaledImageDimensions();this.zoomRatio=this.getZoomToFitRatio(e);var i={width:this.editorWidth,height:this.editorHeight},s={width:e.width*this.zoomRatio,height:e.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2};this._editorModeTransition((function(){t._setFittedImageVerticeCoordinates();var e=t.cropperState,i=t.getScaledImageDimensions(),s=i.width/e.imageDimensions.width,n={left:t.image.left+e.offsetX*s*t.zoomRatio,top:t.image.top+e.offsetY*s*t.zoomRatio,width:e.width*s*t.zoomRatio,height:e.height*s*t.zoomRatio};t._showCropper(n),t.focalPoint&&(s=i.width/t.focalPointState.imageDimensions.width,t.focalPoint.left=t.image.left+t.focalPointState.offsetX*s*t.zoomRatio,t.focalPoint.top=t.image.top+t.focalPointState.offsetY*s*t.zoomRatio,t.canvas.add(t.focalPoint))}),s,i)},disableCropMode:function(){var t=this,e={};this._hideCropper();var i=this.getScaledImageDimensions(),s=this.getZoomToCoverRatio(i)*this.scaleFactor,n=s/this.zoomRatio;this.zoomRatio=s;var a={width:i.width*this.zoomRatio,height:i.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2},r=(this.clipper.left-this.image.left)*n,o=(this.clipper.top-this.image.top)*n;a.left=this.editorWidth/2-r,a.top=this.editorHeight/2-o,e.height=this.clipper.height*n,e.width=this.clipper.width*n,(!this.focalPoint||this.focalPoint&&!this._isCenterInside(this.focalPoint,this.clipper))&&(this.focalPoint&&this.toggleFocalPoint(),this._resetFocalPointPosition()),this._editorModeTransition((function(){if(t.focalPoint){var e=t.getScaledImageDimensions().width/t.focalPointState.imageDimensions.width;t.focalPoint.left=t.image.left+t.focalPointState.offsetX*e*t.zoomRatio,t.focalPoint.top=t.image.top+t.focalPointState.offsetY*e*t.zoomRatio,t.canvas.add(t.focalPoint)}}),a,e)},_editorModeTransition:function(t,e,i){var s=this;this._queue.pause(),this.animationInProgress||(this.animationInProgress=!0,this.focalPoint&&(this.canvas.remove(this.focalPoint),this.renderImage()),this.image.animate(e,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){t(),s.animationInProgress=!1,s.renderImage(),s._queue.resume()}}),this.viewport.animate(i,{duration:this.settings.animationDuration}))},_showSpinner:function(){this.$spinner||(this.$spinner=$('<div class="spinner big spinner-absolute"/>')),this.$spinner.appendTo(this.$container.find(".image"))},_hideSpinner:function(){this.$spinner.remove()},_showCropper:function(t){this._setupCropperLayer(t),this._redrawCropperElements(),this.renderCropper()},_hideCropper:function(){this.clipper&&(this.croppingCanvas.remove(this.clipper),this.croppingCanvas.remove(this.croppingShade),this.croppingCanvas.remove(this.cropperHandles),this.croppingCanvas.remove(this.cropperGrid),this.croppingCanvas.remove(this.croppingRectangle),this.croppingCanvas=null,this.renderCropper=null)},_setupCropperLayer:function(t){var e=this;this.croppingCanvas=new fabric.StaticCanvas("cropping-canvas",{backgroundColor:"rgba(0,0,0,0)",hoverCursor:"default",selection:!1}),this.croppingCanvas.setDimensions({width:this.editorWidth,height:this.editorHeight}),this.renderCropper=function(){return Garnish.requestAnimationFrame(e.croppingCanvas.renderAll.bind(e.croppingCanvas))},$("#cropping-canvas",this.$editorContainer).css({position:"absolute",top:0,left:0}),this.croppingShade=new fabric.Rect({left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",width:this.editorWidth,height:this.editorHeight,fill:"rgba(0,0,0,0.7)"});var i=this.getScaledImageDimensions(),s=0===this.imageStraightenAngle?1:1.2*this.getCombinedZoomRatio(i),n=i.width/s,a=i.height/s;if(this.hasOrientationChanged()){var r=a;a=n,n=r}this.clipper=new fabric.Rect({left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",width:n,height:a,stroke:"black",fill:"rgba(128,0,0,1)",strokeWidth:0}),t&&this.clipper.set(t),this.clipper.globalCompositeOperation="destination-out",this.croppingCanvas.add(this.croppingShade),this.croppingCanvas.add(this.clipper)},_redrawCropperElements:function(){void 0===this._redrawCropperElements._&&(this._redrawCropperElements._={}),this.cropperHandles&&(this.croppingCanvas.remove(this.cropperHandles),this.croppingCanvas.remove(this.cropperGrid),this.croppingCanvas.remove(this.croppingRectangle)),this._redrawCropperElements._.lineOptions={strokeWidth:4,stroke:"rgb(255,255,255)",fill:!1},this._redrawCropperElements._.gridOptions={strokeWidth:2,stroke:"rgba(255,255,255,0.5)"},this._redrawCropperElements._.pathGroup=[new fabric.Path("M 0,10 L 0,0 L 10,0",this._redrawCropperElements._.lineOptions),new fabric.Path("M "+(this.clipper.width-8)+",0 L "+(this.clipper.width+4)+",0 L "+(this.clipper.width+4)+",10",this._redrawCropperElements._.lineOptions),new fabric.Path("M "+(this.clipper.width+4)+","+(this.clipper.height-8)+" L"+(this.clipper.width+4)+","+(this.clipper.height+4)+" L "+(this.clipper.width-8)+","+(this.clipper.height+4),this._redrawCropperElements._.lineOptions),new fabric.Path("M 10,"+(this.clipper.height+4)+" L 0,"+(this.clipper.height+4)+" L 0,"+(this.clipper.height-8),this._redrawCropperElements._.lineOptions)],this.cropperHandles=new fabric.Group(this._redrawCropperElements._.pathGroup,{left:this.clipper.left,top:this.clipper.top,originX:"center",originY:"center"}),this.croppingRectangle=new fabric.Rect({left:this.clipper.left,top:this.clipper.top,width:this.clipper.width,height:this.clipper.height,fill:"rgba(0,0,0,0)",stroke:"rgba(255,255,255,0.8)",strokeWidth:2,originX:"center",originY:"center"}),this.cropperGrid=new fabric.Group([new fabric.Line([.33*this.clipper.width,0,.33*this.clipper.width,this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([.66*this.clipper.width,0,.66*this.clipper.width,this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([0,.33*this.clipper.height,this.clipper.width,.33*this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([0,.66*this.clipper.height,this.clipper.width,.66*this.clipper.height],this._redrawCropperElements._.gridOptions)],{left:this.clipper.left,top:this.clipper.top,originX:"center",originY:"center"}),this._redrawCropperElements._.cropTextTop=this.croppingRectangle.top+this.clipper.height/2+12,this._redrawCropperElements._.cropTextBackgroundColor="rgba(0,0,0,0)",this._redrawCropperElements._.cropTextTop+12>this.editorHeight-2&&(this._redrawCropperElements._.cropTextTop-=24,this._redrawCropperElements._.cropTextBackgroundColor="rgba(0,0,0,0.5)"),this.croppingCanvas.add(this.cropperHandles),this.croppingCanvas.add(this.cropperGrid),this.croppingCanvas.add(this.croppingRectangle)},_repositionCropper:function(t){if(this.croppingCanvas){var e=this.clipper.left-this.croppingCanvas.width/2,i=this.clipper.top-this.croppingCanvas.height/2;this.croppingCanvas.setDimensions({width:this.editorWidth,height:this.editorHeight});var s=this._getBoundingRectangle(this.imageVerticeCoords).width/t.width;this.clipper.width=Math.round(this.clipper.width*s),this.clipper.height=Math.round(this.clipper.height*s),this.clipper.left=this.editorWidth/2+e*s,this.clipper.top=this.editorHeight/2+i*s,this.croppingShade.set({width:this.editorWidth,height:this.editorHeight,left:this.editorWidth/2,top:this.editorHeight/2}),this._redrawCropperElements(),this.renderCropper()}},_getBoundingRectangle:function(t){return{width:Math.max(t.a.x,t.b.x,t.c.x,t.d.x)-Math.min(t.a.x,t.b.x,t.c.x,t.d.x),height:Math.max(t.a.y,t.b.y,t.c.y,t.d.y)-Math.min(t.a.y,t.b.y,t.c.y,t.d.y)}},_handleMouseDown:function(t){var e=this.focalPoint&&this._isMouseOver(t,this.focalPoint),i=this.croppingCanvas&&this._isMouseOver(t,this.clipper),s=this.croppingCanvas&&this._cropperHandleHitTest(t);(s||i||e)&&(this.previousMouseX=t.pageX,this.previousMouseY=t.pageY,e?this.draggingFocal=!0:s?this.scalingCropper=s:i&&(this.draggingCropper=!0))},_handleMouseMove:function(t){null!==this.mouseMoveEvent&&Garnish.requestAnimationFrame(this._handleMouseMoveInternal.bind(this)),this.mouseMoveEvent=t},_handleMouseMoveInternal:function(){null!==this.mouseMoveEvent&&(this.focalPoint&&this.draggingFocal?(this._handleFocalDrag(this.mouseMoveEvent),this.storeFocalPointState(),this.renderImage()):this.draggingCropper||this.scalingCropper?(this.draggingCropper?this._handleCropperDrag(this.mouseMoveEvent):this._handleCropperResize(this.mouseMoveEvent),this._redrawCropperElements(),this.storeCropperState(),this.renderCropper()):this._setMouseCursor(this.mouseMoveEvent),this.previousMouseX=this.mouseMoveEvent.pageX,this.previousMouseY=this.mouseMoveEvent.pageY,this.mouseMoveEvent=null)},_handleMouseUp:function(){this.draggingCropper=!1,this.scalingCropper=!1,this.draggingFocal=!1},_handleMouseOut:function(t){this._handleMouseUp(t),this.mouseMoveEvent=t,this._handleMouseMoveInternal()},_handleCropperDrag:function(t){if(void 0===this._handleCropperDrag._&&(this._handleCropperDrag._={}),this._handleCropperDrag._.deltaX=t.pageX-this.previousMouseX,this._handleCropperDrag._.deltaY=t.pageY-this.previousMouseY,0===this._handleCropperDrag._.deltaX&&0===this._handleCropperDrag._.deltaY)return!1;if(this._handleCropperDrag._.rectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this._handleCropperDrag._.vertices=this._getRectangleVertices(this._handleCropperDrag._.rectangle,this._handleCropperDrag._.deltaX,this._handleCropperDrag._.deltaY),!this.arePointsInsideRectangle(this._handleCropperDrag._.vertices,this.imageVerticeCoords)){for(this._handleCropperDrag._.dxi=0,this._handleCropperDrag._.dyi=0,this._handleCropperDrag._.xStep=this._handleCropperDrag._.deltaX>0?-1:1,this._handleCropperDrag._.yStep=this._handleCropperDrag._.deltaY>0?-1:1,this._handleCropperDrag._.furthest=0,this._handleCropperDrag._.furthestDeltas={},this._handleCropperDrag._.dxi=Math.min(Math.abs(this._handleCropperDrag._.deltaX),10);this._handleCropperDrag._.dxi>=0;this._handleCropperDrag._.dxi--)for(this._handleCropperDrag._.dyi=Math.min(Math.abs(this._handleCropperDrag._.deltaY),10);this._handleCropperDrag._.dyi>=0;this._handleCropperDrag._.dyi--)this._handleCropperDrag._.vertices=this._getRectangleVertices(this._handleCropperDrag._.rectangle,this._handleCropperDrag._.dxi*(this._handleCropperDrag._.deltaX>0?1:-1),this._handleCropperDrag._.dyi*(this._handleCropperDrag._.deltaY>0?1:-1)),this.arePointsInsideRectangle(this._handleCropperDrag._.vertices,this.imageVerticeCoords)&&this._handleCropperDrag._.dxi+this._handleCropperDrag._.dyi>this._handleCropperDrag._.furthest&&(this._handleCropperDrag._.furthest=this._handleCropperDrag._.dxi+this._handleCropperDrag._.dyi,this._handleCropperDrag._.furthestDeltas={x:this._handleCropperDrag._.dxi*(this._handleCropperDrag._.deltaX>0?1:-1),y:this._handleCropperDrag._.dyi*(this._handleCropperDrag._.deltaY>0?1:-1)});if(0==this._handleCropperDrag._.furthest)return;this._handleCropperDrag._.deltaX=this._handleCropperDrag._.furthestDeltas.x,this._handleCropperDrag._.deltaY=this._handleCropperDrag._.furthestDeltas.y}this.clipper.set({left:this.clipper.left+this._handleCropperDrag._.deltaX,top:this.clipper.top+this._handleCropperDrag._.deltaY})},_handleFocalDrag:function(t){if(void 0===this._handleFocalDrag._&&(this._handleFocalDrag._={}),this.focalPoint){if(this._handleFocalDrag._.deltaX=t.pageX-this.previousMouseX,this._handleFocalDrag._.deltaY=t.pageY-this.previousMouseY,0===this._handleFocalDrag._.deltaX&&0===this._handleFocalDrag._.deltaY)return;if(this._handleFocalDrag._.newX=this.focalPoint.left+this._handleFocalDrag._.deltaX,this._handleFocalDrag._.newY=this.focalPoint.top+this._handleFocalDrag._.deltaY,"crop"===this.currentView){if(!this.arePointsInsideRectangle([{x:this._handleFocalDrag._.newX,y:this._handleFocalDrag._.newY}],this.imageVerticeCoords))return}else if(!(this.viewport.left-this.viewport.width/2-this._handleFocalDrag._.newX<0&&this.viewport.left+this.viewport.width/2-this._handleFocalDrag._.newX>0&&this.viewport.top-this.viewport.height/2-this._handleFocalDrag._.newY<0&&this.viewport.top+this.viewport.height/2-this._handleFocalDrag._.newY>0))return;this.focalPoint.set({left:this.focalPoint.left+this._handleFocalDrag._.deltaX,top:this.focalPoint.top+this._handleFocalDrag._.deltaY})}},setCroppingConstraint:function(t){switch(this.updateSizeAndPosition(),t){case"none":this.croppingConstraint=!1;break;case"original":this.croppingConstraint=this.originalWidth/this.originalHeight;break;case"current":this.croppingConstraint=this.clipper.width/this.clipper.height;break;case"custom":break;default:this.croppingConstraint=parseFloat(t)}},enforceCroppingConstraint:function(){var t=this;void 0===this.enforceCroppingConstraint._&&(this.enforceCroppingConstraint._={}),!this.animationInProgress&&this.croppingConstraint&&(this.animationInProgress=!0,this.enforceCroppingConstraint._.rectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this.clipper.width>this.clipper.height*this.croppingConstraint?(this.enforceCroppingConstraint._.previousHeight=this.enforceCroppingConstraint._.rectangle.height,this.enforceCroppingConstraint._.rectangle.height=this.clipper.width/this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.top-=(this.enforceCroppingConstraint._.rectangle.height-this.enforceCroppingConstraint._.previousHeight)/2,this.arePointsInsideRectangle(this._getRectangleVertices(this.enforceCroppingConstraint._.rectangle),this.imageVerticeCoords)||(this.enforceCroppingConstraint._.rectangle.width=this.clipper.height*this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.height=this.enforceCroppingConstraint._.rectangle.width/this.croppingConstraint)):(this.enforceCroppingConstraint._.previousWidth=this.enforceCroppingConstraint._.rectangle.width,this.enforceCroppingConstraint._.rectangle.width=this.clipper.height*this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.left-=(this.enforceCroppingConstraint._.rectangle.width-this.enforceCroppingConstraint._.previousWidth)/2,this.arePointsInsideRectangle(this._getRectangleVertices(this.enforceCroppingConstraint._.rectangle),this.imageVerticeCoords)||(this.enforceCroppingConstraint._.rectangle.height=this.clipper.width/this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.width=this.enforceCroppingConstraint._.rectangle.height*this.croppingConstraint)),this.enforceCroppingConstraint._.properties={height:this.enforceCroppingConstraint._.rectangle.height,width:this.enforceCroppingConstraint._.rectangle.width},this.clipper.animate(this.enforceCroppingConstraint._.properties,{onChange:function(){t._redrawCropperElements(),t.croppingCanvas.renderAll()},duration:this.settings.animationDuration,onComplete:function(){t._redrawCropperElements(),t.animationInProgress=!1,t.renderCropper(),t.storeCropperState()}}))},_handleCropperResize:function(t){void 0===this._handleCropperResize._&&(this._handleCropperResize._={}),this._handleCropperResize._.deltaX=t.pageX-this.previousMouseX,this._handleCropperResize._.deltaY=t.pageY-this.previousMouseY,"b"!==this.scalingCropper&&"t"!==this.scalingCropper||(this._handleCropperResize._.deltaX=0),"l"!==this.scalingCropper&&"r"!==this.scalingCropper||(this._handleCropperResize._.deltaY=0),0===this._handleCropperResize._.deltaX&&0===this._handleCropperResize._.deltaY||(this._handleCropperResize._.startingRectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this._handleCropperResize._.rectangle=this._calculateNewCropperSizeByDeltas(this._handleCropperResize._.startingRectangle,this._handleCropperResize._.deltaX,this._handleCropperResize._.deltaY,this.scalingCropper),this._handleCropperResize._.rectangle.height<30||this._handleCropperResize._.rectangle.width<30||this.arePointsInsideRectangle(this._getRectangleVertices(this._handleCropperResize._.rectangle),this.imageVerticeCoords)&&(this.clipper.set({top:this._handleCropperResize._.rectangle.top+this._handleCropperResize._.rectangle.height/2,left:this._handleCropperResize._.rectangle.left+this._handleCropperResize._.rectangle.width/2,width:this._handleCropperResize._.rectangle.width,height:this._handleCropperResize._.rectangle.height}),this._redrawCropperElements()))},_calculateNewCropperSizeByDeltas:function(t,e,i,s){if(void 0===this._calculateNewCropperSizeByDeltas._&&(this._calculateNewCropperSizeByDeltas._={}),this._calculateNewCropperSizeByDeltas._.topDelta=0,this._calculateNewCropperSizeByDeltas._.leftDelta=0,this._calculateNewCropperSizeByDeltas._.rectangle=t,this._calculateNewCropperSizeByDeltas._.deltaX=e,this._calculateNewCropperSizeByDeltas._.deltaY=i,this.croppingConstraint){switch(this._calculateNewCropperSizeByDeltas._.change=0,s){case"t":this._calculateNewCropperSizeByDeltas._.change=-this._calculateNewCropperSizeByDeltas._.deltaY;break;case"b":this._calculateNewCropperSizeByDeltas._.change=this._calculateNewCropperSizeByDeltas._.deltaY;break;case"r":this._calculateNewCropperSizeByDeltas._.change=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"l":this._calculateNewCropperSizeByDeltas._.change=-this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tr":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?-this._calculateNewCropperSizeByDeltas._.deltaY:this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tl":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?-this._calculateNewCropperSizeByDeltas._.deltaY:-this._calculateNewCropperSizeByDeltas._.deltaX;break;case"br":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?this._calculateNewCropperSizeByDeltas._.deltaY:this._calculateNewCropperSizeByDeltas._.deltaX;break;case"bl":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?this._calculateNewCropperSizeByDeltas._.deltaY:-this._calculateNewCropperSizeByDeltas._.deltaX}switch(this.croppingConstraint>1?(this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.change,this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.deltaX/this.croppingConstraint):(this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.change,this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.deltaY*this.croppingConstraint),this._calculateNewCropperSizeByDeltas._.rectangle.height+=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.width+=this._calculateNewCropperSizeByDeltas._.deltaX,s){case"t":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX/2;break;case"b":this._calculateNewCropperSizeByDeltas._.rectangle.left+=-this._calculateNewCropperSizeByDeltas._.deltaX/2;break;case"r":this._calculateNewCropperSizeByDeltas._.rectangle.top+=-this._calculateNewCropperSizeByDeltas._.deltaY/2;break;case"l":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY/2,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tr":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY;break;case"tl":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"bl":this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX}}else!this.shiftKeyHeld||"tl"!==s&&"tr"!==s&&"bl"!==s&&"br"!==s||(this._calculateNewCropperSizeByDeltas._.ratio,Math.abs(e)>Math.abs(i)?(this._calculateNewCropperSizeByDeltas._.ratio=t.width/t.height,this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.deltaX/this._calculateNewCropperSizeByDeltas._.ratio,this._calculateNewCropperSizeByDeltas._.deltaY*="tr"===s||"bl"===s?-1:1):(this._calculateNewCropperSizeByDeltas._.ratio=t.width/t.height,this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.deltaY*this._calculateNewCropperSizeByDeltas._.ratio,this._calculateNewCropperSizeByDeltas._.deltaX*="tr"===s||"bl"===s?-1:1)),s.match(/t/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.top+=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.height-=this._calculateNewCropperSizeByDeltas._.deltaY),s.match(/b/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.height+=this._calculateNewCropperSizeByDeltas._.deltaY),s.match(/r/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.width+=this._calculateNewCropperSizeByDeltas._.deltaX),s.match(/l/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.left+=this._calculateNewCropperSizeByDeltas._.deltaX,this._calculateNewCropperSizeByDeltas._.rectangle.width-=this._calculateNewCropperSizeByDeltas._.deltaX);return this._calculateNewCropperSizeByDeltas._.rectangle.top=this._calculateNewCropperSizeByDeltas._.rectangle.top,this._calculateNewCropperSizeByDeltas._.rectangle.left=this._calculateNewCropperSizeByDeltas._.rectangle.left,this._calculateNewCropperSizeByDeltas._.rectangle.width=this._calculateNewCropperSizeByDeltas._.rectangle.width,this._calculateNewCropperSizeByDeltas._.rectangle.height=this._calculateNewCropperSizeByDeltas._.rectangle.height,this._calculateNewCropperSizeByDeltas._.rectangle},_setMouseCursor:function(t){void 0===this._setMouseCursor._&&(this._setMouseCursor._={}),Garnish.isMobileBrowser(!0)||(this._setMouseCursor._.cursor="default",this._setMouseCursor._.handle=this.croppingCanvas&&this._cropperHandleHitTest(t),this.focalPoint&&this._isMouseOver(t,this.focalPoint)?this._setMouseCursor._.cursor="pointer":this._setMouseCursor._.handle?"t"===this._setMouseCursor._.handle||"b"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="ns-resize":"l"===this._setMouseCursor._.handle||"r"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="ew-resize":"tl"===this._setMouseCursor._.handle||"br"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="nwse-resize":"bl"!==this._setMouseCursor._.handle&&"tr"!==this._setMouseCursor._.handle||(this._setMouseCursor._.cursor="nesw-resize"):this.croppingCanvas&&this._isMouseOver(t,this.clipper)&&(this._setMouseCursor._.cursor="move"),$(".body").css("cursor",this._setMouseCursor._.cursor))},_cropperHandleHitTest:function(t){if(void 0===this._cropperHandleHitTest._&&(this._cropperHandleHitTest._={}),this._cropperHandleHitTest._.parentOffset=this.$croppingCanvas.offset(),this._cropperHandleHitTest._.mouseX=t.pageX-this._cropperHandleHitTest._.parentOffset.left,this._cropperHandleHitTest._.mouseY=t.pageY-this._cropperHandleHitTest._.parentOffset.top,this._cropperHandleHitTest._.lb=this.clipper.left-this.clipper.width/2,this._cropperHandleHitTest._.rb=this._cropperHandleHitTest._.lb+this.clipper.width,this._cropperHandleHitTest._.tb=this.clipper.top-this.clipper.height/2,this._cropperHandleHitTest._.bb=this._cropperHandleHitTest._.tb+this.clipper.height,this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb-3){if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-3)return"tl";if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+3&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-10)return"bl"}if(this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.rb-13&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb+3){if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-3)return"tr";if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+2&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-10)return"br"}return this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.lb+3&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb-3&&this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb-10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb+10?"l":this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb+1&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.rb-5&&this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb-10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb+10?"r":this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+4&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-2&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb-10?"t":this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+2&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-4&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb-10&&"b"},_isMouseOver:function(t,e){return void 0===this._isMouseOver._&&(this._isMouseOver._={}),this._isMouseOver._.parentOffset=this.$croppingCanvas.offset(),this._isMouseOver._.mouseX=t.pageX-this._isMouseOver._.parentOffset.left,this._isMouseOver._.mouseY=t.pageY-this._isMouseOver._.parentOffset.top,this._isMouseOver._.lb=e.left-e.width/2,this._isMouseOver._.rb=this._isMouseOver._.lb+e.width,this._isMouseOver._.tb=e.top-e.height/2,this._isMouseOver._.bb=this._isMouseOver._.tb+e.height,this._isMouseOver._.mouseX>=this._isMouseOver._.lb&&this._isMouseOver._.mouseX<=this._isMouseOver._.rb&&this._isMouseOver._.mouseY>=this._isMouseOver._.tb&&this._isMouseOver._.mouseY<=this._isMouseOver._.bb},_getRectangleVertices:function(t,e,i){return void 0===this._getRectangleVertices._&&(this._getRectangleVertices._={}),void 0===e&&(e=0),void 0===i&&(i=0),this._getRectangleVertices._.topLeft={x:t.left+e,y:t.top+i},this._getRectangleVertices._.topRight={x:this._getRectangleVertices._.topLeft.x+t.width,y:this._getRectangleVertices._.topLeft.y},this._getRectangleVertices._.bottomRight={x:this._getRectangleVertices._.topRight.x,y:this._getRectangleVertices._.topRight.y+t.height},this._getRectangleVertices._.bottomLeft={x:this._getRectangleVertices._.topLeft.x,y:this._getRectangleVertices._.bottomRight.y},[this._getRectangleVertices._.topLeft,this._getRectangleVertices._.topRight,this._getRectangleVertices._.bottomRight,this._getRectangleVertices._.bottomLeft]},_setFittedImageVerticeCoordinates:function(){this.imageVerticeCoords=this.getImageVerticeCoords("fit")},getImageVerticeCoords:function(t){var e,i=-1*((this.hasOrientationChanged()?90:0)+this.imageStraightenAngle)*(Math.PI/180),s=this.getScaledImageDimensions();e="number"==typeof t?t:"cover"===t?this.getZoomToCoverRatio(s):this.getZoomToFitRatio(s);var n=s.height*e,a=s.width*e,r=Math.cos(i)*n,o=Math.sin(i)*a,l=Math.cos(i)*a,h=Math.sin(i)*n,d=(this.editorHeight-(r+o))/2,c=(this.editorWidth-(h+l))/2;return{a:{x:c+l,y:d},b:{x:this.editorWidth-c,y:d+r},c:{x:c+h,y:this.editorHeight-d},d:{x:c,y:d+o}}},_debug:function(t){this.canvas.remove(this.debugger),this.debugger=t,this.canvas.add(this.debugger)},arePointsInsideRectangle:function(t,e){for(void 0===this.arePointsInsideRectangle._&&(this.arePointsInsideRectangle._={}),this.arePointsInsideRectangle._.ab=this._getVector(e.a,e.b),this.arePointsInsideRectangle._.bc=this._getVector(e.b,e.c),this.arePointsInsideRectangle._.scalarAbAb=this._getScalarProduct(this.arePointsInsideRectangle._.ab,this.arePointsInsideRectangle._.ab),this.arePointsInsideRectangle._.scalarBcBc=this._getScalarProduct(this.arePointsInsideRectangle._.bc,this.arePointsInsideRectangle._.bc),this.arePointsInsideRectangle._.i=0;this.arePointsInsideRectangle._.i<t.length;this.arePointsInsideRectangle._.i++)if(this.arePointsInsideRectangle._.point=t[this.arePointsInsideRectangle._.i],this.arePointsInsideRectangle._.ap=this._getVector(e.a,this.arePointsInsideRectangle._.point),this.arePointsInsideRectangle._.bp=this._getVector(e.b,this.arePointsInsideRectangle._.point),this.arePointsInsideRectangle._.scalarAbAp=this._getScalarProduct(this.arePointsInsideRectangle._.ab,this.arePointsInsideRectangle._.ap),this.arePointsInsideRectangle._.scalarBcBp=this._getScalarProduct(this.arePointsInsideRectangle._.bc,this.arePointsInsideRectangle._.bp),this.arePointsInsideRectangle._.projectsOnAB=0<=this.arePointsInsideRectangle._.scalarAbAp&&this.arePointsInsideRectangle._.scalarAbAp<=this.arePointsInsideRectangle._.scalarAbAb,this.arePointsInsideRectangle._.projectsOnBC=0<=this.arePointsInsideRectangle._.scalarBcBp&&this.arePointsInsideRectangle._.scalarBcBp<=this.arePointsInsideRectangle._.scalarBcBc,!this.arePointsInsideRectangle._.projectsOnAB||!this.arePointsInsideRectangle._.projectsOnBC)return!1;return!0},_getVector:function(t,e){return{x:e.x-t.x,y:e.y-t.y}},_getScalarProduct:function(t,e){return t.x*e.x+t.y*e.y},_getVectorMagnitude:function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},_getAngleBetweenVectors:function(t,e){return Math.round(180*Math.acos(Math.min(1,this._getScalarProduct(t,e)/(this._getVectorMagnitude(t)*this._getVectorMagnitude(e))))/Math.PI*100)/100},_getEdgeCrossed:function(t,e){for(var i=[[t.a,t.b],[t.b,t.c],[t.c,t.d],[t.d,t.a]],s={x:this.editorWidth/2,y:this.editorHeight/2},n=180,a=null,r=0;r<i.length;r++){var o=i[r],l=this._getVector(o[0],s),h=this._getVector(o[0],o[1]),d=this._getVector(o[0],e),c=Math.abs(this._getAngleBetweenVectors(l,d)-(this._getAngleBetweenVectors(l,h)+this._getAngleBetweenVectors(h,d)));c<n&&(n=c,a=o)}return a},_getImageBoundingBox:function(t){var e={},i=Math.abs(this.imageStraightenAngle)*(Math.PI/180),s=t.height/t.width;if(e.height=t.width*(Math.sin(i)+Math.cos(i)*s),e.width=t.width*(Math.cos(i)+Math.sin(i)*s),this.hasOrientationChanged()){var n=e.width;e.width=e.height,e.height=n}return e}},{defaults:{animationDuration:100,allowSavingAsNew:!0,onSave:$.noop,allowDegreeFractions:null}})},2495:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function e(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Craft.AssetIndex=Craft.BaseElementIndex.extend({$includeSubfoldersContainer:null,$includeSubfoldersCheckbox:null,showingIncludeSubfoldersCheckbox:!1,$uploadButton:null,$uploadInput:null,$progressBar:null,uploader:null,promptHandler:null,progressBar:null,$listedFolders:null,itemDrag:null,_uploadTotalFiles:0,_uploadFileProgress:{},_currentUploaderSettings:{},init:function(t,i,s){var n,a=this;s=Object.assign({},Craft.AssetIndex.defaults,s),this.base(t,i,s),"index"===this.settings.context?(this.itemDrag=new Garnish.DragDrop((e(n={activeDropTargetClass:"sel",minMouseDist:10,hideDraggee:!1,moveHelperToCursor:!0},"activeDropTargetClass","active-drop-target"),e(n,"handle",(function(t){return $(t).closest("tr,li")})),e(n,"filter",(function(){var t=a.itemDrag.$targetItem.closest("tr,li");return a.view.elementSelect.selectItem(t),a._findDraggableItems(a.view.getSelectedElements())})),e(n,"helper",(function(t,e){return $('<div class="offset-drag-helper"/>').append(t).css({opacity:Math.max(.9-.05*e,0),width:"",height:""})})),e(n,"dropTargets",(function(){var t=$(a.$visibleSources.toArray().filter((function(t){return Garnish.hasAttr(t,"data-folder-id")&&Garnish.hasAttr(t,"data-can-move-peer-files-to")})));if(a.sourcePath.length<=1)t=t.not(a.$source);else for(var e=0;e<a.sourcePath.length-1;e++){var i=a.sourcePath[e];i.folderId&&(t=t.add(i.$btn))}return a.$listedFolders&&(t=t.add(a.$listedFolders.filter("[data-folder-id]").closest("tr,li")).not(a.view.getSelectedElements())),t})),e(n,"onDragStart",(function(){Garnish.$bod.addClass("dragging"),a.itemDrag.$draggee.closest("tr,li").addClass("draggee")})),e(n,"onDragStop",(function(){Garnish.$bod.removeClass("dragging");var t=a.itemDrag.$draggee,e=a._targetFolderId(a.itemDrag.$activeDropTarget);if(!e)return t.closest("tr,li").removeClass("draggee"),void a.itemDrag.returnHelpersToDraggees();a.itemDrag.fadeOutHelpers();var i=t.filter("[data-is-folder]"),s=t.not(i),n=i.toArray().map((function(t){return parseInt($(t).data("folder-id"))})),r=s.toArray().map((function(t){return parseInt($(t).data("id"))})),o=new Craft.AssetMover;o.moveFolders(n,e).then((function(i){o.moveAssets(r,e).then((function(e){var s=i+e;s?(Craft.cp.displayNotice(Craft.t("app","{totalItems, plural, =1{Item} other{Items}} moved.",{totalItems:s})),Craft.elementIndex.updateElements(!0)):t.closest("tr,li").removeClass("draggee")}))}))})),n)),this.addListener(Garnish.$win,"resize,scroll","_positionProgressBar")):(this.addListener(this.$main,"scroll","_positionProgressBar"),this.settings.modal&&this.settings.modal.on("updateSizeAndPosition",this._positionProgressBar.bind(this)))},_findDraggableItems:function(t){return $(t.toArray().map((function(t){return $(t).find(".element:first")[0]})).filter((function(t){return t&&Garnish.hasAttr(t,"data-movable")})))},_targetFolderId:function(t){if(!t||!t.length)return!1;if(t.is(this.$visibleSources))return t.data("folder-id");for(var e=0;e<this.sourcePath.length-1;e++){var i=this.sourcePath[e];if(t.is(i.$btn))return i.folderId}return t.find(".element:first").data("folder-id")||!1},afterInit:function(){this.settings.foldersOnly||this.initForFiles(),this.base()},initForFiles:function(){var t=this;this.$uploadButton||(this.$uploadButton=$("<button/>",{type:"button",class:"btn submit","data-icon":"upload",style:"position: relative; overflow: hidden;",text:Craft.t("app","Upload files")}),this.addButton(this.$uploadButton),this.$uploadInput=$('<input type="file" multiple="multiple" name="assets-upload" />').hide().insertBefore(this.$uploadButton)),this.promptHandler=new Craft.PromptHandler,this.progressBar=new Craft.ProgressBar(this.$main,!1);var e={url:Craft.getActionUrl("assets/upload"),fileInput:this.$uploadInput,dropZone:this.$container};e.events={fileuploadstart:this._onUploadStart.bind(this),fileuploadprogressall:this._onUploadProgress.bind(this),fileuploaddone:this._onUploadSuccess.bind(this),fileuploadalways:this._onUploadAlways.bind(this),fileuploadfail:this._onUploadFailure.bind(this)},this.settings.criteria&&void 0!==this.settings.criteria.kind&&(e.allowedKinds=this.settings.criteria.kind),this._currentUploaderSettings=e,this.uploader=new Craft.Uploader(this.$uploadButton,e),this.$uploadButton.on("click",(function(){t.$uploadButton.hasClass("disabled")||t.isIndexBusy||t.$uploadButton.parent().find("input[name=assets-upload]").trigger("click")}))},onSelectSource:function(){this.settings.foldersOnly||(this.$source.data("folder-id")&&Garnish.hasAttr(this.$source,"data-can-upload")?(this.uploader.setParams({folderId:this.$source.attr("data-folder-id")}),this.$uploadButton.removeClass("disabled")):this.$uploadButton.addClass("disabled")),this.base()},onSourcePathChange:function(){if(!this.settings.foldersOnly&&this.sourcePath.length){var t=this.sourcePath[this.sourcePath.length-1];if(t.folderId){this.uploader&&this.uploader.setParams({folderId:t.folderId});var e=!!t.canMoveSubItems;this.settings.selectable=this.settings.selectable||e,this.settings.multiSelect=this.settings.multiSelect||e}}this.base()},startSearching:function(){if(!this.settings.hideSidebar&&this.sourcePath[this.sourcePath.length-1].hasChildren){if(null===this.$includeSubfoldersContainer){var t="includeSubfolders-"+Math.floor(1e9*Math.random());this.$includeSubfoldersContainer=$('<div style="margin-bottom: -25px; opacity: 0;"/>').insertAfter(this.$search);var e=$('<div style="padding-top: 5px;"/>').appendTo(this.$includeSubfoldersContainer);this.$includeSubfoldersCheckbox=$('<input type="checkbox" id="'+t+'" class="checkbox"/>').appendTo(e),$('<label class="light smalltext" for="'+t+'"/>').text(" "+Craft.t("app","Search in subfolders")).appendTo(e),this.addListener(this.$includeSubfoldersCheckbox,"change",(function(){this.setSelecetedSourceState("includeSubfolders",this.$includeSubfoldersCheckbox.prop("checked")),this.updateElements()}))}else this.$includeSubfoldersContainer.velocity("stop").removeClass("hidden");var i=this.getSelectedSourceState("includeSubfolders",!1);this.$includeSubfoldersCheckbox.prop("checked",i),this.$includeSubfoldersContainer.velocity({marginBottom:0,opacity:1},"fast"),this.showingIncludeSubfoldersCheckbox=!0}this.base()},stopSearching:function(){var t=this;this.showingIncludeSubfoldersCheckbox&&(this.$includeSubfoldersContainer.velocity("stop"),this.$includeSubfoldersContainer.velocity({marginBottom:-25,opacity:0},{duration:"fast",complete:function(){t.$includeSubfoldersContainer.addClass("hidden")}}),this.showingIncludeSubfoldersCheckbox=!1),this.base()},getViewSettings:function(){var t={};return"index"===this.settings.context&&(t.canSelectElement=function(){return!0}),t},getViewParams:function(){var t=Object.assign(this.base(),{showFolders:this.settings.showFolders&&!this.trashed,foldersOnly:this.settings.foldersOnly});return this.showingIncludeSubfoldersCheckbox&&this.$includeSubfoldersCheckbox.prop("checked")&&(t.criteria.includeSubfolders=!0),t},_onUploadStart:function(){this.setIndexBusy(),this._positionProgressBar(),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar(),this.promptHandler.resetPrompts()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadSuccess:function(t,e){var i=e.result;this.selectElementAfterUpdate(i.assetId),i.conflict&&(i.prompt={message:Craft.t("app",i.conflict,{file:i.filename}),choices:[{value:"keepBoth",title:Craft.t("app","Keep both")},{value:"replace",title:Craft.t("app","Replace it")}]},this.promptHandler.addPrompt(i)),Craft.cp.runQueue()},_onUploadAlways:function(){this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.setIndexAvailable(),this.promptHandler.getPromptCount()?this.promptHandler.showBatchPrompts(this._uploadFollowup.bind(this)):this._updateAfterUpload())},_onUploadFailure:function(t,e){var i,s=e.response(),n=(null==s||null===(i=s.jqXHR)||void 0===i?void 0:i.responseJSON)||{},a=n.message,r=n.filename;a||(a=r?Craft.t("app","Upload failed for “{filename}”.",{filename:r}):Craft.t("app","Upload failed.")),Craft.cp.displayError(a)},_updateAfterUpload:function(){"index"!==this.settings.context&&(this.clearSearch(),this.setSelectedSortAttribute("dateCreated","desc")),this.updateElements()},_uploadFollowup:function(t){var e=this;this.setIndexBusy(),this.progressBar.resetProgressBar(),this.promptHandler.resetPrompts(),this.progressBar.setItemCount(t.length),this.progressBar.showProgressBar(),function t(i,s,n){var a={},r=null,o=function(){s++,e.progressBar.incrementProcessedItemCount(1),e.progressBar.updateProgressBar(),s===i.length?n():t(i,s,n)},l=function(t){t.assetId&&e.selectElementAfterUpdate(t.assetId),o()};"replace"===i[s].choice?(r="assets/replace-file",a.sourceAssetId=i[s].assetId,i[s].conflictingAssetId?a.assetId=i[s].conflictingAssetId:a.targetFilename=i[s].filename):"cancel"===i[s].choice&&(r="assets/delete-asset",a.assetId=i[s].assetId),r?Craft.sendActionRequest("POST",r,{data:a}).then((function(t){return l(t.data)})).catch((function(t){return function(t){Craft.cp.displayError(t.message),o()}(t.response.data)})):l({assetId:i[s].assetId})}(t,0,(function(){e.progressBar.hideProgressBar(),e.setIndexAvailable(),e._updateAfterUpload()}))},onUpdateElements:function(){var t=this;this._onUpdateElements(!1,this.view.getAllElements()),this.view.on("appendElements",(function(e){t._onUpdateElements(!0,e.newElements)})),this.base()},_onUpdateElements:function(t,e){var i=this;this.removeListener(this.$elements,"keydown"),this.addListener(this.$elements,"keydown",this._onKeyDown.bind(this)),this.view.elementSelect.on("focusItem",this._onElementFocus.bind(this)),this.$listedFolders=e.find(".element[data-is-folder][data-folder-name]");for(var s=function(t){var s=i.$listedFolders.eq(t),n=s.find(".label"),a=n.find(".title"),r=parseInt(s.data("folder-id")),o=s.data("folder-name"),l=Craft.t("app","{name} folder",{name:o});if(i.settings.disabledFolderIds.includes(r))return n.attr("aria-label",l),e.has(s).addClass("disabled"),"continue";var h=s.data("source-path");if(h){var d=$("<a/>",{href:Craft.getCpUrl(h[h.length-1].uri),html:a.html(),role:"button","aria-label":l});n.empty().append(d),i.addListener(d,"activate",(function(t){i.sourcePath=h,i.clearSearch(!1),i.updateElements().then((function(){var t=i.$elements.find(":focusable:not(.selectallcontainer)")[0];t&&t.focus()}))}))}},n=0;n<this.$listedFolders.length;n++)s(n);if(this.itemDrag){var a=this.sourcePath[this.sourcePath.length-1],r=!!(a&&a.folderId&&a.canMoveSubItems);r&&t||this.itemDrag.removeAllItems(),r&&this.itemDrag.addItems(this._findDraggableItems(e))}},_onKeyDown:function(t){if(t.keyCode===Garnish.SPACE_KEY&&t.shiftKey){if(Craft.PreviewFileModal.openInstance)Craft.PreviewFileModal.openInstance.selfDestruct();else{var e=this.view.elementSelect.$focusedItem.find(".element");e.length&&this._loadPreview(e)}return t.stopPropagation(),!1}},_onElementFocus:function(t){var e=$(t.item).find(".element");Craft.PreviewFileModal.openInstance&&e.length&&this._loadPreview(e)},_loadPreview:function(t){var e={};t.data("image-width")&&(e.startingWidth=t.data("image-width"),e.startingHeight=t.data("image-height")),new Craft.PreviewFileModal(t.data("id"),this.view.elementSelect,e)},getSourcePathLabel:function(){return Craft.t("app","Volume path")},getSourcePathActionLabel:function(){return Craft.t("app","Folder actions")},getSourcePathActions:function(){var t=this,e=[],i=this.sourcePath[this.sourcePath.length-1];return i.canCreate&&e.push({label:Craft.t("app","New subfolder"),onSelect:function(){t._createSubfolder()}}),"index"===this.settings.context&&i.canRename&&(e.push({label:Craft.t("app","Rename folder"),onSelect:function(){t._renameFolder()}}),i.canMove&&this.getMoveTargetSourceKeys(!0).length&&e.push({label:Craft.t("app","Move folder"),onSelect:function(){t._moveFolder()}}),i.canDelete&&e.push({label:Craft.t("app","Delete folder"),destructive:!0,onSelect:function(){t._deleteFolder()}})),e},_createSubfolder:function(){var t=this,e=this.sourcePath[this.sourcePath.length-1],i=prompt(Craft.t("app","Enter the name of the folder"));if(i){var s={parentId:e.folderId,folderName:i};this.setIndexBusy(),Craft.sendActionRequest("POST","assets/create-folder",{data:s}).then((function(e){t.setIndexAvailable(),Craft.cp.displayNotice(Craft.t("app","Folder created.")),t.updateElements(!0)})).catch((function(e){var i=e.response;t.setIndexAvailable(),Craft.cp.displayError(i.data.message)}))}},_deleteFolder:function(){var t=this,e=this.sourcePath[this.sourcePath.length-1];if(confirm(Craft.t("app","Really delete folder “{folder}”?",{folder:e.label}))){var i={folderId:e.folderId};this.setIndexBusy(),Craft.sendActionRequest("POST","assets/delete-folder",{data:i}).then((function(e){t.setIndexAvailable(),Craft.cp.displayNotice(Craft.t("app","Folder deleted.")),t.sourcePath=t.sourcePath.slice(0,t.sourcePath.length-1),t.updateElements()})).catch((function(e){var i=e.response;t.setIndexAvailable(),Craft.cp.displayError(i.data.message)}))}},_renameFolder:function(){var t=this,e=this.sourcePath[this.sourcePath.length-1],i=prompt(Craft.t("app","Rename folder"),e.label);i&&i!==e.label&&(this.setIndexBusy(),Craft.sendActionRequest("POST","assets/rename-folder",{data:{folderId:e.folderId,newName:i}}).then((function(e){Craft.cp.displayNotice(Craft.t("app","Folder renamed."));var i=t.sourcePath.slice();i[i.length-1].label=e.data.newName,i[i.length-1].uri=i[i.length-2].uri+"/".concat(e.data.newName),t.sourcePath=i})).catch((function(t){var e=t.response;Craft.cp.displayError(e.data.message)})).finally((function(){t.setIndexAvailable()})))},getMoveTargetSourceKeys:function(t){var e=t?"data-can-move-peer-files-to":"data-can-move-to";return this.$sources.toArray().filter((function(t){var i=$(t).data("volume-handle");return i&&"temp"!==i&&Garnish.hasAttr(t,e)})).map((function(t){return $(t).data("key")}))},_moveFolder:function(){var e=this,i=this.sourcePath[this.sourcePath.length-1],s=this.sourcePath[this.sourcePath.length-2],n=[i.folderId];s&&n.push(s.folderId),new Craft.VolumeFolderSelectorModal({sources:this.getMoveTargetSourceKeys(!0),showTitle:!0,modalTitle:Craft.t("app","Move to"),selectBtnLabel:Craft.t("app","Move"),disabledFolderIds:n,indexSettings:{defaultSource:this.sourceKey,defaultSourcePath:this.sourcePath.slice(0,this.sourcePath.length-1)},onSelect:function(s){var n,a,r=(n=s,a=1,function(t){if(Array.isArray(t))return t}(n)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(n,a)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(n,a)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())[0];e.$sourcePathActionsBtn.focus(),(new Craft.AssetMover).moveFolders([i.folderId],r.folderId).then((function(t){t&&(Craft.cp.displayNotice(Craft.t("app","{totalItems, plural, =1{Item} other{Items}} moved.",{totalItems:t})),e.sourcePath=e.sourcePath.slice(0,e.sourcePath.length-1),e.clearSearch(!1),e.updateElements())}))}})},_positionProgressBar:function(){this.progressBar||(this.progressBar=new Craft.ProgressBar(this.$main,!0));var t=$(),e=0,i=0;"index"===this.settings.context?(t=this.progressBar.$progressBar.closest("#content"),e=Garnish.$win.scrollTop()):(t=this.progressBar.$progressBar.closest(".main"),e=this.$main.scrollTop());var s=e-t.offset().top,n=Garnish.$win.height();i=t.height()>n?n/2-6+s:t.height()/2-6,"index"!==this.settings.context&&(i=e+(t.height()/2-6)),this.progressBar.$progressBar.css({top:i})}},{defaults:{showFolders:!0,foldersOnly:!1,disabledFolderIds:[]}}),Craft.registerElementIndexClass("craft\\elements\\Asset",Craft.AssetIndex)},1016:function(){function t(t,i){var s="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!s){if(Array.isArray(t)||(s=e(t))||i&&t&&"number"==typeof t.length){s&&(t=s);var n=0,a=function(){};return{s:a,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){s=s.call(t)},n:function(){var t=s.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==s.return||s.return()}finally{if(l)throw r}}}}function e(t,e){if(t){if("string"==typeof t)return i(t,e);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?i(t,e):void 0}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.AssetMover=Garnish.Base.extend({moveAssets:function(t,e){var i=t.map((function(t){return{for:"asset",action:"assets/move-asset",params:{assetId:t,folderId:e}}}));return this._batchMoveRequests(i,{conflictChoices:[{value:"keepBoth",title:Craft.t("app","Keep both")},{value:"replace",title:Craft.t("app","Replace it")}],handleConflictChoice:function(t){var e={folderId:t.request.params.folderId,assetId:t.assetId};switch(t.choice){case"replace":e.force=!0;break;case"keepBoth":e.filename=t.suggestedFilename}return{action:"assets/move-asset",params:e}}})},moveFolders:function(t,s){var n=this;return new Promise((function(a,r){var o=[],l=[],h=t.map((function(t){return{for:"folder",action:"assets/move-folder",params:{folderId:t,parentId:s},onSuccess:function(s){var n;s.transferList.length&&o.push.apply(o,function(t){if(Array.isArray(t))return i(t)}(n=s.transferList)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(n)||e(n)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),l.push(t)}}}));n._batchMoveRequests(h,{conflictChoices:[{value:"replace",title:Craft.t("app","Replace the folder (all existing files will be deleted)")},{value:"merge",title:Craft.t("app","Merge the folder (any conflicting files will be replaced)")}],handleConflictChoice:function(t){var e={folderId:t.folderId,parentId:t.parentId};switch(t.choice){case"replace":e.force=!0;break;case"merge":e.merge=!0}return{action:"assets/move-folder",params:e}}}).then((function(t){n._processTransferList(o).then((function(){n._deleteFolders(l).then((function(){a(t)}))}))})).catch(r)}))},_processTransferList:function(t){return this._batchRequests(t.map((function(t){return{action:"assets/move-asset",params:t}})))},_deleteFolders:function(t){return this._batchRequests(t.map((function(t){return{action:"assets/delete-folder",params:{folderId:t}}})))},_batchMoveRequests:function(e,i){var s=this;return new Promise((function(n){var a=0;s._batchRequests(e).then((function(e){Craft.elementIndex.promptHandler.resetPrompts();var r,o=t(e);try{for(o.s();!(r=o.n()).done;){var l=r.value;l.success&&a++,l.conflict&&Craft.elementIndex.promptHandler.addPrompt(Object.assign({},l,{prompt:{message:l.conflict,choices:i.conflictChoices}})),l.error&&Craft.cp.displayError(l.error)}}catch(t){o.e(t)}finally{o.f()}Craft.elementIndex.promptHandler.getPromptCount()?Craft.elementIndex.promptHandler.showBatchPrompts((function(e){Craft.elementIndex.promptHandler.resetPrompts();var r,o=[],l=t(e);try{for(l.s();!(r=l.n()).done;){var h=r.value;if("cancel"!==h.choice&&i.handleConflictChoice){var d=i.handleConflictChoice(h);h.request&&h.request.onSuccess&&(d.onSuccess=h.request.onSuccess),o.push(d)}}}catch(t){l.e(t)}finally{l.f()}s._batchMoveRequests(o,i).then((function(t){n(a+t)}))})):n(a)}))}))},_batchRequests:function(e){return new Promise((function(i){if(e.length){Craft.elementIndex.setIndexBusy(),Craft.elementIndex._positionProgressBar(),Craft.elementIndex.progressBar.resetProgressBar(),Craft.elementIndex.progressBar.setItemCount(e.length),Craft.elementIndex.progressBar.showProgressBar();var s,n=[],a=e.length,r=t(e);try{var o=function(){var t=s.value;Craft.sendActionRequest("POST",t.action,{data:t.params}).then((function(e){n.push(Object.assign({},e.data,{request:t})),e.data.success&&t.onSuccess&&t.onSuccess(e.data)})).catch((function(e){e.response&&e.response.data&&n.push(Object.assign({},e.response.data,{request:t}))})).finally((function(){0==--a?(Craft.elementIndex.setIndexAvailable(),Craft.elementIndex.progressBar.hideProgressBar(),Craft.cp.runQueue(),i(n)):(Craft.elementIndex.progressBar.incrementProcessedItemCount(1),Craft.elementIndex.progressBar.updateProgressBar())}))};for(r.s();!(s=r.n()).done;)o()}catch(t){r.e(t)}finally{r.f()}}else i([])}))}})},5077:function(){Craft.AssetSelectInput=Craft.BaseElementSelectInput.extend({$uploadBtn:null,uploader:null,progressBar:null,openPreviewTimeout:null,init:function(){this.base.apply(this,arguments),this.settings.canUpload&&this._attachUploader(),this.updateAddElementsBtn(),this.addListener(this.$elementsContainer,"keydown",this._onKeyDown.bind(this)),this.elementSelect.on("focusItem",this._onElementFocus.bind(this))},_onKeyDown:function(t){if(t.keyCode===Garnish.SPACE_KEY&&t.shiftKey)return this.openPreview(),t.stopPropagation(),!1},onAddElements:function(){var t=this;this.$elements.find(".elementthumb").addClass("open-preview").on("click",(function(e){t.clearOpenPreviewTimeout(),t.openPreviewTimeout=setTimeout((function(){t.openPreview(),t.openPreviewTimeout=null}),500)})).on("dblclick",(function(e){t.clearOpenPreviewTimeout()})),this.base()},clearOpenPreviewTimeout:function(){this.openPreviewTimeout&&(clearTimeout(this.openPreviewTimeout),this.openPreviewTimeout=null)},openPreview:function(){if(Craft.PreviewFileModal.openInstance)Craft.PreviewFileModal.openInstance.selfDestruct();else{var t=this.elementSelect.$focusedItem;t.length&&this._loadPreview(t)}},_onElementFocus:function(t){var e=$(t.item);Craft.PreviewFileModal.openInstance&&e.length&&this._loadPreview(e)},_loadPreview:function(t){var e={minGutter:50};t.data("image-width")&&(e.startingWidth=t.data("image-width"),e.startingHeight=t.data("image-height")),new Craft.PreviewFileModal(t.data("id"),this.elementSelect,e)},_attachUploader:function(){var t=this;this.progressBar=new Craft.ProgressBar($('<div class="progress-shade"></div>').appendTo(this.$container));var e={url:Craft.getActionUrl("assets/upload"),dropZone:this.$container,formData:{fieldId:this.settings.fieldId}};this.settings.sourceElementId&&(e.formData.elementId=this.settings.sourceElementId),this.settings.criteria.siteId&&(e.formData.siteId=this.settings.criteria.siteId),this.$addElementBtn&&(this.$uploadBtn=$("<button/>",{type:"button",class:"btn dashed","data-icon":"upload","aria-label":1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files"),"aria-describedby":this.settings.describedBy,text:1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files")}).insertAfter(this.$addElementBtn),e.fileInput=$("<input/>",{type:"file",class:"hidden",multiple:1!=this.settings.limit}).insertAfter(this.$uploadBtn),Garnish.$win.trigger("resize")),void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(e.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),void 0!==this.settings.criteria.kind&&(e.allowedKinds=this.settings.criteria.kind),e.canAddMoreFiles=this.canAddMoreFiles.bind(this),e.events={},e.events.fileuploadstart=this._onUploadStart.bind(this),e.events.fileuploadprogressall=this._onUploadProgress.bind(this),e.events.fileuploaddone=this._onUploadComplete.bind(this),e.events.fileuploadfail=this._onUploadFailure.bind(this),this.uploader=new Craft.Uploader(this.$container,e),this.$uploadBtn&&this.$uploadBtn.on("click",(function(e){t.$uploadBtn.next("input[type=file]").trigger("click")}))},enableAddElementsBtn:function(){this.$uploadBtn&&this.$uploadBtn.removeClass("hidden"),this.base()},disableAddElementsBtn:function(){this.$uploadBtn&&this.$uploadBtn.addClass("hidden"),this.base()},selectUploadedFile:function(t){if(this.canAddMoreElements()){var e=t.$element;e.addClass("removable"),e.prepend('<input type="hidden" name="'+this.settings.name+'[]" value="'+t.id+'"><a class="delete icon" title="'+Craft.t("app","Remove")+'"></a>'),e.appendTo(this.$elementsContainer);var i=-(e.outerWidth()+10);this.$addElementBtn.css("margin-"+Craft.left,i+"px");var s={};s["margin-"+Craft.left]=0,this.$addElementBtn.velocity(s,"fast"),this.addElements(e),delete this.modal}},_onUploadStart:function(){this.progressBar.$progressBar.css({top:Math.round(this.$container.outerHeight()/2)-6}),this.$container.addClass("uploading"),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){var i=this;if(e.result.error)Craft.cp.displayError(e.result.error),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading");else{var s={elementId:e.result.assetId,siteId:this.settings.criteria.siteId,thumbSize:this.settings.viewMode};Craft.sendActionRequest("POST","elements/get-element-html",{data:s}).then((function(t){var e=$(t.data.html);Craft.appendHeadHtml(t.data.headHtml),i.selectUploadedFile(Craft.getElementInfo(e)),i.uploader.isLastUpload()&&(i.progressBar.hideProgressBar(),i.$container.removeClass("uploading"),i.$container.trigger("change"))})).catch((function(t){var e=t.response;Craft.cp.displayError(e.data.message)})),Craft.cp.runQueue()}},_onUploadFailure:function(t,e){var i,s=e.response(),n=(null==s||null===(i=s.jqXHR)||void 0===i?void 0:i.responseJSON)||{},a=n.message,r=n.filename;a||(a=r?Craft.t("app","Upload failed for “{filename}”.",{filename:r}):Craft.t("app","Upload failed.")),Craft.cp.displayError(a),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading")},canAddMoreFiles:function(t){return!this.settings.limit||this.$elements.length+t<this.settings.limit}})},4606:function(){Craft.AssetSelectorModal=Craft.BaseElementSelectorModal.extend({$selectTransformBtn:null,_selectedTransform:null,init:function(t,e){e=$.extend({},Craft.AssetSelectorModal.defaults,e),this.base(t,e),e.transforms.length&&this.createSelectTransformButton(e.transforms)},createSelectTransformButton:function(t){if(t&&t.length){var e=$('<div class="btngroup"/>').appendTo(this.$primaryButtons);this.$selectBtn.appendTo(e),this.$selectTransformBtn=$("<button/>",{type:"button",class:"btn menubtn disabled",text:Craft.t("app","Select transform")}).appendTo(e);for(var i=$('<div class="menu" data-align="right"></div>').insertAfter(this.$selectTransformBtn),s=$("<ul></ul>").appendTo(i),n=0;n<t.length;n++)$('<li><a data-transform="'+t[n].handle+'">'+t[n].name+"</a></li>").appendTo(s);var a=new Garnish.MenuBtn(this.$selectTransformBtn,{onOptionSelect:this.onSelectTransform.bind(this)});a.disable(),this.$selectTransformBtn.data("menuButton",a)}},onSelectionChange:function(t){var e=this.elementIndex.getSelectedElements(),i=!1;if(e.length&&this.settings.transforms.length){i=!0;for(var s=0;s<e.length&&$(".element.hasthumb:first",e[s]).length;s++);}var n=null;this.$selectTransformBtn&&(n=this.$selectTransformBtn.data("menuButton")),i?(n&&n.enable(),this.$selectTransformBtn.removeClass("disabled")):this.$selectTransformBtn&&(n&&n.disable(),this.$selectTransformBtn.addClass("disabled")),this.base()},onSelectTransform:function(t){var e=$(t).data("transform");this.selectImagesWithTransform(e)},selectImagesWithTransform:function(t){var e=this;void 0===Craft.AssetSelectorModal.transformUrls[t]&&(Craft.AssetSelectorModal.transformUrls[t]={});for(var i=this.elementIndex.getSelectedElements(),s=[],n=0;n<i.length;n++){var a=$(i[n]),r=Craft.getElementInfo(a).id;void 0===Craft.AssetSelectorModal.transformUrls[t][r]&&s.push(r)}s.length?(this.showFooterSpinner(),this.fetchMissingTransformUrls(s,t,(function(){e.hideFooterSpinner(),e.selectImagesWithTransform(t)}))):(this._selectedTransform=t,this.selectElements(),this._selectedTransform=null)},fetchMissingTransformUrls:function(t,e,i){var s=this,n=t.pop(),a={assetId:n,handle:e};Craft.sendActionRequest("POST","assets/generate-transform",{data:a}).then((function(t){Craft.AssetSelectorModal.transformUrls[e][n]=t.data.url||!1})).catch((function(){Craft.AssetSelectorModal.transformUrls[e][n]=!1})).finally((function(){t.length?s.fetchMissingTransformUrls(t,e,i):i()}))},getElementInfo:function(t){var e=this.base(t);if(this._selectedTransform)for(var i=0;i<e.length;i++){var s=e[i].id;void 0!==Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s]&&!1!==Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s]&&(e[i].url=Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s])}return e},onSelect:function(t){this.settings.onSelect(t,this._selectedTransform)}},{defaults:{canSelectImageTransforms:!1,transforms:[]},transformUrls:{}}),Craft.registerElementSelectorModalClass("craft\\elements\\Asset",Craft.AssetSelectorModal)},8391:function(){Craft.AssetsFieldSettings=Garnish.Base.extend({$useSingleFolderInput:null,$sourceInputs:null,$defaultUploadLocationSelect:null,$defaultUploadLocationOptions:null,init:function(t,e,i){var s=this;this.$useSingleFolderInput=$("#".concat(t)),this.$sourceInputs=$("#".concat(e," input")),this.$defaultUploadLocationSelect=$("#".concat(i)),this.$defaultUploadLocationOptions=this.$defaultUploadLocationSelect.children("option"),this.updateDefaultUploadLocationSelect(),Garnish.requestAnimationFrame((function(){s.addListener(s.$useSingleFolderInput,"change","updateDefaultUploadLocationSelect"),s.addListener(s.$sourceInputs,"change","updateDefaultUploadLocationSelect")}))},updateDefaultUploadLocationSelect:function(){if(!this.$useSingleFolderInput.prop("checked")){for(var t,e=this.$defaultUploadLocationSelect.val(),i=0;i<this.$sourceInputs.length;i++){var s=this.$sourceInputs.eq(i),n=s.val(),a=s.prop("checked");if("*"===n){if(a)return void this.$defaultUploadLocationOptions.prop("disabled",!1)}else this.getOption(n).prop("disabled",!a),a&&!t&&(t=n)}var r=this.getOption(e);(!r.length||r.prop("disabled")&&t)&&this.$defaultUploadLocationSelect.val(t)}},getOption:function(t){return this.$defaultUploadLocationOptions.filter('[value="'.concat(t,'"]'))}})},9222:function(){Craft.AuthManager=Garnish.Base.extend({remainingSessionTime:null,checkRemainingSessionTimer:null,showLoginModalTimer:null,decrementLogoutWarningInterval:null,showingLogoutWarningModal:!1,showingLoginModal:!1,logoutWarningModal:null,loginModal:null,$logoutWarningPara:null,$passwordInput:null,$loginBtn:null,$loginErrorPara:null,submitLoginIfLoggedOut:!1,init:function(){Craft.username&&this.updateRemainingSessionTime(Craft.remainingSessionTime)},setCheckRemainingSessionTimer:function(t){this.checkRemainingSessionTimer&&clearTimeout(this.checkRemainingSessionTimer),this.checkRemainingSessionTimer=setTimeout(this.checkRemainingSessionTime.bind(this),1e3*t)},checkRemainingSessionTime:function(t){var e=this;$.ajax({url:Craft.getActionUrl("users/session-info",t?null:"dontExtendSession=1"),type:"GET",dataType:"json",complete:function(t,i){"success"===i?(void 0!==t.responseJSON.csrfTokenValue&&void 0!==Craft.csrfTokenValue&&(Craft.csrfTokenValue=t.responseJSON.csrfTokenValue),e.updateRemainingSessionTime(t.responseJSON.timeout),e.submitLoginIfLoggedOut=!1):e.updateRemainingSessionTime(-1)}})},updateRemainingSessionTime:function(t){this.remainingSessionTime=parseInt(t),-1!==this.remainingSessionTime&&this.remainingSessionTime<Craft.AuthManager.minSafeSessionTime?(this.remainingSessionTime?(this.showingLogoutWarningModal||this.showLogoutWarningModal(),this.remainingSessionTime<Craft.AuthManager.checkInterval&&(this.showLoginModalTimer&&clearTimeout(this.showLoginModalTimer),this.showLoginModalTimer=setTimeout(this.showLoginModal.bind(this),1e3*this.remainingSessionTime))):this.showingLoginModal?this.submitLoginIfLoggedOut&&this.submitLogin():this.showLoginModal(),this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval)):(this.hideLogoutWarningModal(),this.hideLoginModal(),-1!==this.remainingSessionTime&&this.remainingSessionTime<Craft.AuthManager.minSafeSessionTime+Craft.AuthManager.checkInterval?this.setCheckRemainingSessionTimer(this.remainingSessionTime-Craft.AuthManager.minSafeSessionTime+1):this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval))},showLogoutWarningModal:function(){var t;if(this.showingLoginModal?(this.hideLoginModal(!0),t=!0):t=!1,this.showingLogoutWarningModal=!0,!this.logoutWarningModal){var e=$('<form id="logoutwarningmodal" class="modal alert fitted"/>'),i=$('<div class="body"/>').appendTo(e),s=$('<div class="buttons right"/>').appendTo(i),n=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Sign out now")}).appendTo(s),a=$("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Keep me signed in")}).appendTo(s);this.$logoutWarningPara=$("<p/>").prependTo(i),this.logoutWarningModal=new Garnish.Modal(e,{autoShow:!1,closeOtherModals:!1,hideOnEsc:!1,hideOnShadeClick:!1,shadeClass:"modal-shade dark logoutwarningmodalshade",onFadeIn:function(){Garnish.isMobileBrowser(!0)||setTimeout((function(){a.trigger("focus")}),100)}}),this.addListener(n,"activate","logout"),this.addListener(e,"submit","renewSession")}t?this.logoutWarningModal.quickShow():this.logoutWarningModal.show(),this.updateLogoutWarningMessage(),this.decrementLogoutWarningInterval=setInterval(this.decrementLogoutWarning.bind(this),1e3)},updateLogoutWarningMessage:function(){this.$logoutWarningPara.text(Craft.t("app","Your session will expire in {time}.",{time:Craft.secondsToHumanTimeDuration(this.remainingSessionTime)})),this.logoutWarningModal.updateSizeAndPosition()},decrementLogoutWarning:function(){this.remainingSessionTime>0&&(this.remainingSessionTime--,this.updateLogoutWarningMessage()),0===this.remainingSessionTime&&clearInterval(this.decrementLogoutWarningInterval)},hideLogoutWarningModal:function(t){this.showingLogoutWarningModal=!1,this.logoutWarningModal&&(t?this.logoutWarningModal.quickHide():this.logoutWarningModal.hide(),this.decrementLogoutWarningInterval&&clearInterval(this.decrementLogoutWarningInterval))},showLoginModal:function(){var t,e=this;if(this.showingLogoutWarningModal?(this.hideLogoutWarningModal(!0),t=!0):t=!1,this.showingLoginModal=!0,!this.loginModal){var i=$('<form id="loginmodal" class="modal alert fitted"/>'),s=$('<div class="body"><h2>'+Craft.t("app","Your session has ended.")+"</h2><p>"+Craft.t("app","Enter your password to log back in.")+"</p></div>").appendTo(i),n=$('<div class="inputcontainer">').appendTo(s),a=$('<div class="flex"/>').appendTo(n),r=$('<div class="flex-grow"/>').appendTo(a),o=$("<div/>").appendTo(a),l=$('<div class="passwordwrapper"/>').appendTo(r);this.$passwordInput=$('<input type="password" class="text password fullwidth" autocomplete="current-password" placeholder="'+Craft.t("app","Password")+'"/>').appendTo(l),this.$loginBtn=Craft.ui.createSubmitButton({class:"disabled",label:Craft.t("app","Sign in"),spinner:!0}).attr("aria-disabled","true").appendTo(o),this.$loginErrorPara=$('<p class="error"/>').appendTo(s),this.loginModal=new Garnish.Modal(i,{autoShow:!1,closeOtherModals:!1,hideOnEsc:!1,hideOnShadeClick:!1,shadeClass:"modal-shade dark loginmodalshade",onFadeIn:function(){Garnish.isMobileBrowser(!0)||setTimeout((function(){e.$passwordInput.trigger("focus")}),100)},onFadeOut:function(){e.$passwordInput.val("")}}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:function(t){e.$passwordInput=t}}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(i,"submit","login")}t?this.loginModal.quickShow():this.loginModal.show()},hideLoginModal:function(t){this.showingLoginModal=!1,this.loginModal&&(t?this.loginModal.quickHide():this.loginModal.hide())},logout:function(){$.get({url:Craft.getActionUrl("users/logout"),dataType:"json",success:function(){Craft.redirectTo("")}})},renewSession:function(t){t&&t.preventDefault(),this.hideLogoutWarningModal(),this.checkRemainingSessionTime(!0)},validatePassword:function(){return this.$passwordInput.val().length>=6?(this.$loginBtn.removeClass("disabled"),this.$loginBtn.removeAttr("aria-disabled"),!0):(this.$loginBtn.addClass("disabled"),this.$loginBtn.attr("aria-disabled","true"),!1)},login:function(t){t&&t.preventDefault(),this.validatePassword()&&(this.$loginBtn.addClass("loading"),this.clearLoginError(),void 0!==Craft.csrfTokenValue?(this.submitLoginIfLoggedOut=!0,this.checkRemainingSessionTime()):this.submitLogin())},submitLogin:function(){var t=this,e={loginName:Craft.username,password:this.$passwordInput.val()};Craft.sendActionRequest("POST","users/login",{data:e}).then((function(e){t.$loginBtn.removeClass("loading"),t.hideLoginModal(),t.checkRemainingSessionTime()})).catch((function(e){var i=e.response;t.$loginBtn.removeClass("loading"),t.showLoginError(i.data.message||null),Garnish.shake(t.loginModal.$container),Garnish.isMobileBrowser(!0)||t.$passwordInput.trigger("focus")}))},showLoginError:function(t){null==t&&(t=Craft.t("app","A server error occurred.")),this.$loginErrorPara.text(t),this.loginModal.updateSizeAndPosition()},clearLoginError:function(){this.showLoginError("")}},{checkInterval:60,minSafeSessionTime:120})},5774:function(){function t(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,s)}return i}function e(e){for(var s=1;s<arguments.length;s++){var n=null!=arguments[s]?arguments[s]:{};s%2?t(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function s(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(t,e)||r(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(t){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n(t)}function a(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=r(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var s=0,n=function(){};return{s:n,n:function(){return s>=t.length?{done:!0}:{done:!1,value:t[s++]}},e:function(t){throw t},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,o=!0,l=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return o=t.done,t},e:function(t){l=!0,a=t},f:function(){try{o||null==i.return||i.return()}finally{if(l)throw a}}}}function r(t,e){if(t){if("string"==typeof t)return o(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?o(t,e):void 0}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.BaseElementIndex=Garnish.Base.extend({initialized:!1,elementType:null,idPrefix:null,instanceState:null,sourceStates:null,sourceStatesStorageKey:null,searchTimeout:null,sourceSelect:null,$container:null,$main:null,isIndexBusy:!1,$sidebar:null,showingSidebar:null,sourceKey:null,rootSourceKey:null,sourceViewModes:null,$source:null,$rootSource:null,sourcesByKey:null,$visibleSources:null,$sourceActionsContainer:null,$sourceActionsBtn:null,$toolbar:null,toolbarOffset:null,$searchContainer:null,$search:null,$filterBtn:null,searching:!1,searchText:null,sortByScore:null,trashed:!1,drafts:!1,$clearSearchBtn:null,$statusMenuBtn:null,$statusMenuContainer:null,statusMenu:null,status:null,$siteMenuBtn:null,siteMenu:null,siteId:null,_sourcePath:null,$sourcePathOuterContainer:null,$sourcePathInnerContainer:null,$sourcePathOverflowBtnContainer:null,$sourcePathActionsBtn:null,$elements:null,$updateSpinner:null,$viewModeBtnContainer:null,viewModeBtns:null,_viewMode:null,view:null,_autoSelectElements:null,$countSpinner:null,$countContainer:null,$actionsContainer:null,page:1,resultSet:null,totalResults:null,$exportBtn:null,actions:null,actionsHeadHtml:null,actionsBodyHtml:null,$selectAllContainer:null,$selectAllCheckbox:null,showingActionTriggers:!1,exporters:null,exportersByType:null,_$triggers:null,_cancelToken:null,viewMenus:null,activeViewMenu:null,filterHuds:null,_activeElement:null,get viewMode(){return"structure"!==this._viewMode||this.canSortByStructure()?this._viewMode:"table"},set viewMode(t){this._viewMode=t},init:function(t,e,i){var s=this;if(this.elementType=t,this.$container=e,this.setSettings(i,Craft.BaseElementIndex.defaults),this.idPrefix=Craft.randomString(10),this.instanceState=this.getDefaultInstanceState(),this.sourceStates={},this.settings.storageKey&&$.extend(this.instanceState,Craft.getLocalStorage(this.settings.storageKey),{}),this.sourceStatesStorageKey="BaseElementIndex."+this.elementType+"."+this.settings.context,$.extend(this.sourceStates,Craft.getLocalStorage(this.sourceStatesStorageKey,{})),this.$main=this.$container.find(".main"),this.$toolbar=this.$container.find(this.settings.toolbarSelector),this.$statusMenuBtn=this.$toolbar.find(".statusmenubtn:first"),this.$statusMenuContainer=this.$statusMenuBtn.parent(),this.$siteMenuBtn=this.$container.find(".sitemenubtn:first"),this.$searchContainer=this.$toolbar.find(".search-container:first"),this.$search=this.$searchContainer.children("input:first"),this.$filterBtn=this.$searchContainer.children(".filter-btn:first"),this.$clearSearchBtn=this.$searchContainer.children(".clear-btn:first"),this.$sidebar=this.$container.find(".sidebar:first"),this.$sourceActionsContainer=this.$sidebar.find("#source-actions"),this.$elements=this.$container.find(".elements:first"),this.$updateSpinner=this.$elements.find(".spinner"),this.$updateSpinner.length||(this.$updateSpinner=$("<div/>",{class:"update-spinner spinner spinner-absolute"}).appendTo(this.$elements)),this.$countSpinner=this.$container.find("#count-spinner"),this.$countContainer=this.$container.find("#count-container"),this.$actionsContainer=this.$container.find("#actions-container"),this.$exportBtn=this.$container.find("#export-btn"),this.settings.hideSidebar&&(this.$sidebar.hide(),$(".body, .content",this.$container).removeClass("has-sidebar")),this.initSources()){if(this.$statusMenuBtn.length&&(this.statusMenu=this.$statusMenuBtn.menubtn().data("menubtn").menu,this.statusMenu.on("optionselect",this._handleStatusChange.bind(this))),this.$siteMenuBtn.length){this.siteMenu=this.$siteMenuBtn.menubtn().data("menubtn").menu;var n=this.siteMenu.$options.filter(".sel:first");if(n.length||(n=this.siteMenu.$options.first()),n.length?this._setSite(n.data("site-id")):this.settings.criteria={id:"0"},this.siteMenu.on("optionselect",this._handleSiteChange.bind(this)),this.siteId){var a=this.settings.defaultSiteId||Craft.cp.getSiteId();if(a&&a!=this.siteId){var r=this.siteMenu.$options.filter('[data-site-id="'+a+'"]:first');r.length&&r.trigger("click")}}}else this.settings.criteria&&this.settings.criteria.siteId&&"*"!==this.settings.criteria.siteId?this._setSite(this.settings.criteria.siteId):this._setSite(Craft.siteId);this.settings.criteria&&this.settings.criteria.siteId&&delete this.settings.criteria.siteId,this.addListener(this.$search,"input",(function(){!s.searching&&s.$search.val()?s.startSearching():s.searching&&!s.$search.val()&&s.stopSearching(),s.searchTimeout&&clearTimeout(s.searchTimeout),s.searchTimeout=setTimeout(s.updateElementsIfSearchTextChanged.bind(s),500)})),this.addListener(this.$search,"keypress",(function(t){t.keyCode===Garnish.RETURN_KEY&&(t.preventDefault(),s.searchTimeout&&clearTimeout(s.searchTimeout),s.updateElementsIfSearchTextChanged())})),this.addListener(this.$clearSearchBtn,"click",(function(){s.clearSearch(!0),Garnish.isMobileBrowser(!0)||s.$search.trigger("focus")})),Garnish.isMobileBrowser(!0)||this.$search.trigger("focus"),this.viewMenus={},this.filterHuds={},this.addListener(this.$filterBtn,"click","showFilterHud");var o="index"===this.settings.context?Craft.getQueryParams():{};if(o.status){var l;switch(o.status){case"trashed":l="[data-trashed]";break;case"drafts":l="[data-drafts]";break;default:l='[data-status="'.concat(o.status,'"]')}var h=this.statusMenu.$options.filter(l);h.length?this.statusMenu.selectOption(h[0]):Craft.setQueryParam("status",null)}this.addListener(this.$exportBtn,"click","_showExportHud"),this.initialized=!0,this.afterInit(),this.selectDefaultSource();var d=this.getDefaultSourcePath();if(null!==d&&(this.sourcePath=d),"index"===this.settings.context&&this.addListener(Garnish.$win,"resize","handleResize"),this.handleResize(),o.search&&(this.startSearching(),this.searchText=o.search),o.sort){var c=o.sort.lastIndexOf("-");if(-1!==c){var u=o.sort.substring(0,c),p=o.sort.substring(c+1);this.setSelectedSortAttribute(u,p)}}this.setPage(Craft.pageNum),this.updateElements(!0)}},afterInit:function(){this.onAfterInit()},handleResize:function(){this.sourcePath.length&&this.settings.showSourcePath&&this._updateSourcePathVisibility()},_createCancelToken:function(){return this._cancelToken=axios.CancelToken.source(),this._cancelToken.token},_cancelRequests:function(){this._cancelToken&&this._cancelToken.cancel()},getSourceContainer:function(){return this.$sidebar.find("nav > ul")},get $sources(){if(this.sourceSelect)return this.sourceSelect.$items},getSite:function(){var t=this;if(this.siteId)return Craft.sites.find((function(e){return e.id==t.siteId}))},initSources:function(){var t=this._getSourcesInList(this.getSourceContainer(),!0);if(0===t.length)return!1;this.sourceSelect||(this.sourceSelect=new Garnish.Select(this.$sidebar.find("nav"),{multi:!1,allowEmpty:!1,vertical:!0,onSelectionChange:this._handleSourceSelectionChange.bind(this)})),this.sourcesByKey={};for(var e=0;e<t.length;e++)this.initSource($(t[e]));return!0},selectDefaultSource:function(){var t,e;return"index"===this.settings.context&&(t=Craft.getQueryParam("source")),t||(t=this.getDefaultSourceKey()),t&&(e=this.getSourceByKey(t),-1===this.$visibleSources.index(e)&&(e=null)),t&&e||(e=this.$visibleSources.first()),this.selectSource(e)},refreshSources:function(){var t=this;this.sourceSelect.removeAllItems(),this.setIndexBusy(),Craft.sendActionRequest("POST",this.settings.refreshSourcesAction,{data:{context:this.settings.context,elementType:this.elementType}}).then((function(e){t.setIndexAvailable(),t.getSourceContainer().replaceWith(e.data.html),t.initSources(),t.selectDefaultSource()})).catch((function(e){axios.isCancel(e)||(t.setIndexAvailable(),Craft.cp.displayError(Craft.t("app","A server error occurred.")))}))},initSource:function(t){this.sourceSelect.addItems(t),this.initSourceToggle(t),this.sourcesByKey[t.data("key")]=t,t.data("hasNestedSources")&&-1!==this.instanceState.expandedSources.indexOf(t.data("key"))&&this._expandSource(t)},initSourceToggle:function(t){this.deinitSourceToggle(t);var e=this._getSourceToggle(t);e.length?(this.addListener(t,"dblclick","_handleSourceDblClick"),this.addListener(e,"click","_handleSourceToggleClick"),t.data("hasNestedSources",!0)):t.data("hasNestedSources",!1)},deinitSource:function(t){this.sourceSelect.removeItems(t),this.deinitSourceToggle(t),delete this.sourcesByKey[t.data("key")]},deinitSourceToggle:function(t){t.data("hasNestedSources")&&(this.removeListener(t,"dblclick"),this.removeListener(this._getSourceToggle(t),"click")),t.removeData("hasNestedSources")},getDefaultInstanceState:function(){return{selectedSource:null,expandedSources:[]}},getDefaultSourceKey:function(){var t,e=null;if(this.settings.defaultSource){var i,s=null,n=!1,r=a(this.settings.defaultSource.split("/"));try{for(r.s();!(i=r.n()).done;){var o=i.value;s&&(this._expandSource(s),n=!0);var l=(null!==e?"".concat(e,"/"):"")+o,h=this.getSourceByKey(l);if(!h){s&&this._collapseSource(s);break}s=h,e=l}}catch(t){r.e(t)}finally{r.f()}n&&this._setSite(this.siteId)}return null!==(t=e)&&void 0!==t?t:this.instanceState.selectedSource},getDefaultSourcePath:function(){return null!==this.settings.defaultSourcePath&&void 0!==this.settings.defaultSourcePath[0]&&!0===this.settings.defaultSourcePath[0].canView&&(this.sourcePath.length>0&&this.sourcePath[0].handle===this.settings.defaultSourcePath[0].handle||0===this.sourcePath.length)?this.settings.defaultSourcePath:null},getDefaultExpandedSources:function(){return this.instanceState.expandedSources},get sourcePath(){return this._sourcePath||[]},set sourcePath(t){var e=this;this._sourcePath=t&&t.length?t:null,this.$sourcePathOuterContainer&&(this.$sourcePathOuterContainer.remove(),this.$sourcePathOuterContainer=null,this.$sourcePathInnerContainer=null,this.$sourcePathOverflowBtnContainer=null,this.$sourcePathActionsBtn=null),this._sourcePath&&this.settings.showSourcePath&&function(){var i=e.getSourcePathActions();e.$sourcePathOuterContainer=$("<div/>",{class:"source-path"}).insertBefore(e.$elements),e.$sourcePathInnerContainer=$("<div/>",{class:"chevron-btns"}).appendTo(e.$sourcePathOuterContainer);var s,n,a,r=$("<nav/>",{"aria-label":e.getSourcePathLabel()}).appendTo(e.$sourcePathInnerContainer),o=$("<ol/>").appendTo(r);if(t.length>1){e.$sourcePathOverflowBtnContainer=$("<li/>",{class:"first-step hidden"}).appendTo(o),n="menu"+Math.floor(1e6*Math.random()),s=$("<button/>",{type:"button",class:"btn",title:Craft.t("app","More items"),"aria-label":Craft.t("app","More items"),"data-disclosure-trigger":!0,"aria-controls":n}).append($("<span/>",{class:"btn-body"}).append($("<span/>",{class:"label"}).append($("<span/>",{"data-icon":"ellipsis","aria-hidden":"true"})))).append($("<span/>",{class:"chevron-right"})).appendTo(e.$sourcePathOverflowBtnContainer);var l=$("<div/>",{id:n,class:"menu menu--disclosure"}).appendTo(e.$sourcePathOverflowBtnContainer);a=$("<ul/>").appendTo(l),s.disclosureMenu()}for(var h=0;h<t.length;h++)!function(n){var r=t[n];a&&n<t.length-1&&(r.$overflowLi=$("<li/>",{class:"hidden"}).appendTo(a),$("<a/>",{class:"flex flex-nowrap",href:"#",type:"button",role:"button",html:r.icon?'<span data-icon="'.concat(r.icon,'" aria-hidden="true"></span><span>').concat(r.label,"</span>"):r.label}).appendTo(r.$overflowLi).on("click",(function(t){t.preventDefault(),s.data("trigger").hide(),e.selectSourcePathStep(n)})));var l=0===n,h=n===t.length-1;r.$li=$("<li/>").appendTo(o),l&&r.$li.addClass("first-step"),r.$btn=$("<a/>",{href:r.uri?Craft.getCpUrl(r.uri):"#",class:"btn",role:"button"}),r.icon&&r.$btn.attr("aria-label",r.label);var d=$("<span/>",{class:"btn-body"}).appendTo(r.$btn);r.$label=$("<span/>",{class:"label",html:r.icon?'<span data-icon="'.concat(r.icon,'" aria-hidden="true"></span>'):r.label}).appendTo(d),r.$btn.append($('<span class="chevron-left"/>')),h&&i.length?r.$btn.addClass("has-action-menu"):r.$btn.append($('<span class="chevron-right"/>')),h&&r.$btn.addClass("current-step").attr("aria-current","page"),r.$btn.appendTo(r.$li),e.addListener(r.$btn,"activate",(function(){e.selectSourcePathStep(n)}))}(h);if(i&&i.length){var d=e.getSourcePathActionLabel(),c="menu"+Math.floor(1e6*Math.random());e.$sourcePathActionsBtn=$("<button/>",{type:"button",class:"btn current-step",title:d,"aria-label":d,"data-disclosure-trigger":!0,"aria-controls":c}).append($("<span/>",{class:"btn-body"}).append($("<span/>",{class:"label"}))).append($("<span/>",{class:"chevron-right"})).appendTo(e.$sourcePathInnerContainer);var u=[i.filter((function(t){return!t.destructive&&!t.administrative})),i.filter((function(t){return t.destructive&&!t.administrative})),i.filter((function(t){return t.administrative}))].filter((function(t){return t.length})),p=$("<div/>",{id:c,class:"menu menu--disclosure"}).appendTo(e.$sourcePathInnerContainer);u.forEach((function(t,i){0!==i&&$("<hr/>").appendTo(p),e._buildSourcePathActionList(t).appendTo(p)})),e.$sourcePathActionsBtn.disclosureMenu(),e._updateSourcePathVisibility()}"index"===e.settings.context&&void 0!==t[t.length-1].uri&&"undefined"!=typeof history&&history.replaceState({},"",Craft.getCpUrl(t[t.length-1].uri))}(),this.onSourcePathChange()},getSourcePathLabel:function(){return""},getSourcePathActions:function(){return[]},getSourcePathActionLabel:function(){return""},_updateSourcePathVisibility:function(){var t=this.sourcePath[0],e=this.sourcePath[this.sourcePath.length-1];this.$sourcePathOverflowBtnContainer&&(this.$sourcePathOverflowBtnContainer.addClass("hidden"),t.$li.addClass("first-step"));var i,s=a(this.sourcePath);try{for(s.s();!(i=s.n()).done;){var n=i.value;n.$overflowLi&&n.$overflowLi.addClass("hidden"),n.$li.removeClass("hidden")}}catch(t){s.e(t)}finally{s.f()}e.$label.css("width",""),e.$btn.removeAttr("title");var r=this._checkSourcePathOverage();if(r){if(this.$sourcePathOverflowBtnContainer){this.$sourcePathOverflowBtnContainer.removeClass("hidden"),t.$li.removeClass("first-step");for(var o=0;o<this.sourcePath.length-1;o++){var l=this.sourcePath[o];if(l.$overflowLi.removeClass("hidden"),l.$li.addClass("hidden"),!(r=this._checkSourcePathOverage()))return}}if(!e.icon){var h=e.$label[0].getBoundingClientRect().width;e.$label.width(Math.floor(h-r)),e.$btn.attr("title",e.label)}}},_checkSourcePathOverage:function(){var t=this.$sourcePathOuterContainer[0].getBoundingClientRect().width,e=this.$sourcePathInnerContainer[0].getBoundingClientRect().width;return Math.max(e-t,0)},_buildSourcePathActionList:function(t){var e=this,i=$("<ul/>");return t.forEach((function(t){var s=$("<a/>",{href:"#",type:"button",role:"button","aria-label":t.label,text:t.label}).on("click",(function(i){i.preventDefault(),e.$sourcePathActionsBtn.data("trigger").hide(),t.onSelect&&t.onSelect()}));t.destructive&&s.addClass("error"),$("<li/>").append(s).appendTo(i)})),i},onSourcePathChange:function(){this.settings.onSourcePathChange(),this.trigger("sourcePathChange")},selectSourcePathStep:function(t){this.sourcePath=this.sourcePath.slice(0,t+1),this.sourcePath[t].$btn.focus(),this.clearSearch(!1),this.updateElements()},startSearching:function(){this.$clearSearchBtn.removeClass("hidden"),this.searching=!0,this.sortByScore=!0,this.activeViewMenu&&this.activeViewMenu.updateSortField()},clearSearch:function(t){this.searching&&(this.$search.val(""),this.searchTimeout&&clearTimeout(this.searchTimeout),this.stopSearching(),t?this.updateElementsIfSearchTextChanged():this.searchText=null)},stopSearching:function(){this.$clearSearchBtn.addClass("hidden"),this.searching=!1,this.sortByScore=!1,this.activeViewMenu&&this.activeViewMenu.updateSortField()},setInstanceState:function(t,e){"object"===n(t)?$.extend(this.instanceState,t):this.instanceState[t]=e,this.storeInstanceState()},storeInstanceState:function(){this.settings.storageKey&&Craft.setLocalStorage(this.settings.storageKey,this.instanceState)},getSourceState:function(t,e,i){return null==t?null:(t=t.replace(/\/.*/,""),void 0===this.sourceStates[t]&&(this.sourceStates[t]={}),void 0===e?this.sourceStates[t]:void 0!==this.sourceStates[t][e]?this.sourceStates[t][e]:void 0!==i?i:null)},getSelectedSourceState:function(t,e){return this.getSourceState(this.instanceState.selectedSource,t,e)},setSelecetedSourceState:function(t,e){var i=this.getSelectedSourceState();if(null==i&&(i=[]),"object"===n(t))for(var s in t)t.hasOwnProperty(s)&&(null!==t[s]?i[s]=t[s]:delete i[s]);else null!==e?i[t]=e:delete i[t];var a="*";for(var r in null!=this.instanceState.selectedSource&&(a=this.instanceState.selectedSource.replace(/\/.*/,"")),this.sourceStates[a]=i,this.sourceStates)this.sourceStates.hasOwnProperty(r)&&r.includes("/")&&delete this.sourceStates[r];Craft.setLocalStorage(this.sourceStatesStorageKey,this.sourceStates)},storeSortAttributeAndDirection:function(){},setPage:function(t){if("index"===this.settings.context){t=Math.max(t,1),this.page=t;var e=Craft.getPageUrl(this.page);history.replaceState({},"",e)}},_resetCount:function(){this.resultSet=null,this.totalResults=null},updateSourceMenu:function(){var t=this;if(this.$sourceActionsContainer.length){this.$sourceActionsBtn&&(this.$sourceActionsBtn.data("trigger").destroy(),this.$sourceActionsContainer.empty(),$("#source-actions-menu").remove(),this.$sourceActionsBtn=null);var e=this.getSourceActions();if(e.length){var i=[e.filter((function(t){return!t.destructive&&!t.administrative})),e.filter((function(t){return t.destructive&&!t.administrative})),e.filter((function(t){return t.administrative}))].filter((function(t){return t.length}));this.$sourceActionsBtn=$("<button/>",{type:"button",class:"btn settings icon menubtn",title:Craft.t("app","Source settings"),"aria-label":Craft.t("app","Source settings"),"aria-controls":"source-actions-menu"}).appendTo(this.$sourceActionsContainer);var s=$("<div/>",{id:"source-actions-menu",class:"menu menu--disclosure"}).appendTo(this.$sourceActionsContainer);i.forEach((function(e,i){0!==i&&$("<hr/>").appendTo(s),t._buildActionList(e).appendTo(s)})),this.$sourceActionsBtn.disclosureMenu()}}},_buildActionList:function(t){var e=this,i=$("<ul/>");return t.forEach((function(t){var s=$("<button/>",{type:"button",class:"menu-option",text:t.label}).on("click",(function(){e.$sourceActionsBtn.data("trigger").hide(),t.onSelect&&t.onSelect()}));t.destructive&&s.addClass("error"),$("<li/>").append(s).appendTo(i)})),i},getSourceActions:function(){var t=this,e=[];return Craft.userIsAdmin&&Craft.allowAdminChanges&&e.push({label:Craft.t("app","Customize sources"),administrative:!0,onSelect:function(){t.createCustomizeSourcesModal()}}),e},updateViewMenu:function(){this.activeViewMenu&&this.activeViewMenu===this.viewMenus[this.rootSourceKey]||(this.activeViewMenu&&this.activeViewMenu.hideTrigger(),this.viewMenus[this.rootSourceKey]||(this.viewMenus[this.rootSourceKey]=new l(this,this.$rootSource)),this.activeViewMenu=this.viewMenus[this.rootSourceKey],this.activeViewMenu.showTrigger())},getViewSettings:function(){return{}},getViewParams:function(){var t={siteId:this.siteId,search:this.searchText,offset:this.settings.batchSize*(this.page-1),limit:this.settings.batchSize};if(this.settings.canHaveDrafts&&(this.drafts||"index"===this.settings.context&&!this.status)&&(t.drafts=this.drafts||null,t.savedDraftsOnly=!0,this.drafts||(t.draftOf=!1)),this.trashed&&(t.trashed=!0),Garnish.hasAttr(this.$source,"data-override-status")||(t.status=this.status),$.extend(t,this.settings.criteria),this.sourcePath.length){var e=this.sourcePath[this.sourcePath.length-1];void 0!==e.criteria&&$.extend(t,e.criteria)}var i={context:this.settings.context,elementType:this.elementType,source:this.instanceState.selectedSource,condition:this.settings.condition,referenceElementId:this.settings.referenceElementId,referenceElementSiteId:this.settings.referenceElementSiteId,criteria:t,disabledElementIds:this.settings.disabledElementIds,viewState:$.extend({},this.getSelectedSourceState()),paginated:this._isViewPaginated()?1:0};if(i.viewState.mode=this.viewMode,"structure"===this.viewMode)i.viewState.mode="table",i.viewState.order="structure",i.viewState.sort="asc",void 0===this.instanceState.collapsedElementIds&&(this.instanceState.collapsedElementIds=[]),i.collapsedElementIds=this.instanceState.collapsedElementIds;else{var n=s(this.getSortAttributeAndDirection(),2),a=n[0],r=n[1];i.viewState.order=a,i.viewState.sort=r}return this.filterHuds[this.siteId]&&this.filterHuds[this.siteId][this.sourceKey]&&this.filterHuds[this.siteId][this.sourceKey].serialized&&(i.filters=this.filterHuds[this.siteId][this.sourceKey].serialized),this.trigger("registerViewParams",{params:i}),i},updateElements:function(t,e){var i=this;return new Promise((function(s,n){if(i.initialized){i._cancelRequests(),i.setIndexBusy(),i.view&&(i.view.destroy(),delete i.view),!0!==t&&(i.setPage(1),i._resetCount());var a=i.getViewParams();Craft.sendActionRequest("POST",i.settings.updateElementsAction,{data:a,cancelToken:i._createCancelToken()}).then((function(t){if(i.setIndexAvailable(),"index"===i.settings.context){if(Craft.cp.fixedHeader){var n=Craft.cp.$headerContainer.height(),r=i.$main.offset().top-n;r<Garnish.$scrollContainer.scrollTop()&&Garnish.$scrollContainer.scrollTop(r)}}else i.$main.scrollTop(0);if(i._updateView(a,t.data),e){var o=i.view.getElementContainer();Garnish.firstFocusableElement(o).trigger("focus")}s()})).catch((function(t){axios.isCancel(t)||(i.setIndexAvailable(),Craft.cp.displayError(Craft.t("app","A server error occurred."))),n(t)}))}else n("The element index isn’t initialized yet.")}))},updateElementsIfSearchTextChanged:function(){this.searchText!==(this.searchText=this.searching?this.$search.val():null)&&("index"===this.settings.context&&Craft.setQueryParam("search",this.$search.val()),this.updateElements())},showActionTriggers:function(){this.showingActionTriggers||(this._$triggers?this._$triggers.appendTo(this.$actionsContainer):this._createTriggers(),this.showingActionTriggers=!0)},submitAction:function(t,e){var i=this,s=this.view.getSelectedElementIds();if(0!==s.length&&("string"==typeof t&&(t=this._findAction(t)),!t.confirm||confirm(t.confirm))){this._cancelRequests();var n=this.getViewParams();e=e?Craft.expandPostArray(e):{};var a=$.extend(n,t.settings||{},e,{elementAction:t.type,elementIds:s});this.setIndexBusy(),this._autoSelectElements=s,t.download?(Craft.csrfTokenName&&(a[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl(this.settings.submitActionsAction),a).then((function(t){i.setIndexAvailable()})).catch((function(t){i.setIndexAvailable()}))):Craft.sendActionRequest("POST",this.settings.submitActionsAction,{data:a,cancelToken:this._createCancelToken()}).then((function(e){i._resetCount(),i._updateView(n,e.data),void 0!==e.data.badgeCounts&&i._updateBadgeCounts(e.data.badgeCounts),e.data.message&&Craft.cp.displaySuccess(e.data.message),i.afterAction(t,a)})).catch((function(t){var e=t.response;Craft.cp.displayError(e.data.message)})).finally((function(){i.setIndexAvailable()}))}},_findAction:function(t){for(var e=0;e<this.actions.length;e++)if(this.actions[e].type===t)return this.actions[e];throw"Invalid element action: ".concat(t)},afterAction:function(t,e){Craft.cp.runQueue(),this.onAfterAction(t,e)},hideActionTriggers:function(){this.showingActionTriggers&&(this._$triggers.detach(),this.showingActionTriggers=!1)},updateActionTriggers:function(){if(this.actions){var t=this.view.getSelectedElements().length;0!==t?(t===this.view.getEnabledElements().length?(this.$selectAllCheckbox.removeClass("indeterminate"),this.$selectAllCheckbox.addClass("checked"),this.$selectAllCheckbox.attr("aria-checked","true")):(this.$selectAllCheckbox.addClass("indeterminate"),this.$selectAllCheckbox.removeClass("checked"),this.$selectAllCheckbox.attr("aria-checked","mixed")),this.showActionTriggers()):(this.$selectAllCheckbox.removeClass("indeterminate checked"),this.$selectAllCheckbox.attr("aria-checked","false"),this.hideActionTriggers())}},getSelectedElements:function(){return this.view?this.view.getSelectedElements():$()},getSelectedElementIds:function(){return this.view?this.view.getSelectedElementIds():[]},setStatus:function(t){var e=this.statusMenu.$options.filter('a[data-status="'+t+'"]:first');e.length&&this.statusMenu.selectOption(e[0])},getSelectedSortAttribute:function(t){if(t=t?this.getRootSource(t):this.$rootSource){var e=this.getSourceState(t.data("key"),"order");if(this.getSortOption(e,t))return e}return this.getDefaultSort()[0]},getSelectedSortDirection:function(t){if(t=t||this.$source){var e=this.getSourceState(t.data("key"),"sort");if(["asc","desc"].includes(e))return e}return this.getDefaultSort()[1]},setSortAttribute:function(t){this.setSelectedSortAttribute(t)},setSelectedSortAttribute:function(t,e){if("score"===t)return this.sortByScore=!0,void(this.activeViewMenu&&this.activeViewMenu.updateSortField());this.sortByScore=!1;var i=this.getSortOption(t);if(i){e||(e=i.defaultDir);var n=[],a=[t],r=this.getSelectedSourceState("order");r&&r!==t&&(n.push([r,this.getSelectedSourceState("sort")]),a.push(r));for(var o=this.getSelectedSourceState("orderHistory",[]),l=0;l<o.length;l++){var h=s(o[l],1)[0];if(!h||a.includes(h))break;n.push(o[l]),a.push(h)}this.setSelecetedSourceState({order:t,sort:e,orderHistory:n}),this.activeViewMenu&&this.activeViewMenu.updateSortField(),"index"===this.settings.context&&Craft.setQueryParam("sort","".concat(t,"-").concat(e))}else console.warn("Invalid sort option: ".concat(t))},setSortDirection:function(t){this.setSelectedSortDirection(t)},setSelectedSortDirection:function(t){this.setSelectedSortAttribute(this.getSelectedSortAttribute(),t)},canSortByStructure:function(){return!this.trashed&&!this.drafts&&!this.searching},getSortAttributeAndDirection:function(){return this.searching&&this.sortByScore?["score","desc"]:[this.getSelectedSortAttribute(),this.getSelectedSortDirection()]},getSortLabel:function(t){var e=this.getSortOption(t);return e?e.label:null},getSelectedViewMode:function(){return this.getSelectedSourceState("mode")||"table"},getSourceLevel:function(t){return t.parentsUntil("nav","ul.nested").length+1},getParentSource:function(t){var e=t.parent().parent().siblings("a");return e.length?e:null},getRootSource:function(t){for(var e;e=this.getParentSource(t);)t=e;return t},getSourceByKey:function(t){return this.sourcesByKey[t]||null},selectSource:function(t){var e=$(t);if(!this.sourcesByKey||!Object.keys(this.sourcesByKey).length)return!1;if(this.$source&&this.$source[0]&&this.$source[0]===e[0]&&e.data("key")===this.sourceKey)return!1;if(this.hideActionTriggers(),this.$source=e,this.$rootSource=this.getRootSource(e),this.sourceKey=e.data("key"),this.rootSourceKey=this.$rootSource.data("key"),this.setInstanceState("selectedSource",this.sourceKey),this.sourceSelect.selectItem(e),Craft.cp.updateContentHeading(),this.searching&&(this.searchText=null,this.$search.val(""),"index"===this.settings.context&&Craft.setQueryParam("search",null),this.stopSearching()),this.$statusMenuBtn.length&&(Garnish.hasAttr(this.$source,"data-override-status")?this.$statusMenuContainer.addClass("hidden"):this.$statusMenuContainer.removeClass("hidden"),this.trashed)){var i=this.statusMenu.$options.first();this.setStatus(i.data("status"))}if(this.$viewModeBtnContainer&&this.$viewModeBtnContainer.remove(),this.viewModeBtns={},this.viewMode=null,this.sourceViewModes=this.getViewModesForSource(),this.sourceViewModes.length>1){this.$viewModeBtnContainer=$('<section class="btngroup btngroup--exclusive"/>').attr("aria-label",Craft.t("app","View")).insertAfter(this.$searchContainer);for(var s=0;s<this.sourceViewModes.length;s++){var n=this.sourceViewModes[s],a=$("<button/>",{type:"button",class:"btn"+(void 0!==n.className?" ".concat(n.className):""),"data-view":n.mode,"data-icon":n.icon,"aria-label":n.title,"aria-pressed":"false",title:n.title}).appendTo(this.$viewModeBtnContainer);this.viewModeBtns[n.mode]=a,this.addListener(a,"click",{mode:n.mode},(function(t){this.selectViewMode(t.data.mode),this.updateElements()}))}}var r=this.getSelectedSourceState("mode");if("table"===r&&"structure"===this.getSourceState(e.data("key"),"order")&&(r="structure"),r&&this.doesSourceHaveViewMode(r)||(r=this.viewMode&&this.doesSourceHaveViewMode(this.viewMode)?this.viewMode:this.sourceViewModes[0].mode),this.selectViewMode(r),this.updateSourceMenu(),this.updateViewMenu(),this.updateFilterBtn(),this.sourcePath=this.$source.data("default-source-path"),this.onSelectSource(),"index"===this.settings.context){var o=Craft.getQueryParams();o.source=this.sourceKey,Craft.setUrl(Craft.getUrl(Craft.path,o))}return!0},selectSourceByKey:function(t){var e=this.getSourceByKey(t);return!!e&&this.selectSource(e)},getSortOptions:function(t){var e=((t=t?this.getRootSource(t):this.$rootSource)?t.data("sort-opts"):null)||[];return e.length||e.push({label:Craft.t("app","Title"),attr:"title",defaultDir:"asc"}),e},getSortOption:function(t,e){return this.getSortOptions(e).find((function(e){return e.attr===t}))||null},getDefaultSort:function(t){if(t=t?this.getRootSource(t):this.$rootSource){var e=t.data("default-sort");if(e){"string"==typeof e&&(e=[e]);var i=this.getSortOption(e[0],t);if(i)return e[1]||(e[1]=i.defaultDir),e}}var s=this.getSortOptions(t);return[s[0].attr,s[0].defaultDir]},getTableColumnOptions:function(t){return((t=t?this.getRootSource(t):this.$rootSource)?t.data("table-col-opts"):null)||[]},getTableColumnOption:function(t,e){return this.getTableColumnOptions(e).find((function(e){return e.attr===t}))||null},getDefaultTableColumns:function(t){return((t=t?this.getRootSource(t):this.$rootSource)?t.data("default-table-cols"):null)||[]},getSelectedTableColumns:function(t){var e=this;if(t=t?this.getRootSource(t):this.$rootSource){var i=this.getSourceState(t.data("key"),"tableColumns");if(i)return i.filter((function(i){return!!e.getTableColumnOption(i,t)}))}return this.getDefaultTableColumns(t)},setSelectedTableColumns:function(t){this.setSelecetedSourceState({tableColumns:t}),this.activeViewMenu&&this.activeViewMenu.updateTableColumnField()},getViewModesForSource:function(){var t=[];return Garnish.hasAttr(this.$source,"data-has-structure")&&t.push({mode:"structure",title:Craft.t("app","Display in a structured table"),icon:"rtl"===Craft.orientation?"structurertl":"structure"}),t.push({mode:"table",title:Craft.t("app","Display in a table"),icon:"list"}),this.$source&&Garnish.hasAttr(this.$source,"data-has-thumbs")&&t.push({mode:"thumbs",title:Craft.t("app","Display as thumbnails"),icon:"grid"}),t},doesSourceHaveViewMode:function(t){for(var e=0;e<this.sourceViewModes.length;e++)if(this.sourceViewModes[e].mode===t)return!0;return!1},selectViewMode:function(t,e){e||this.doesSourceHaveViewMode(t)||(t=this.sourceViewModes[0].mode),t!==this._viewMode&&(this._viewMode&&void 0!==this.viewModeBtns[this._viewMode]&&this.viewModeBtns[this._viewMode].removeClass("active").attr("aria-pressed","false"),this._viewMode=t,this.setSelecetedSourceState("mode",this._viewMode),void 0!==this.viewModeBtns[this._viewMode]&&this.viewModeBtns[this._viewMode].addClass("active").attr("aria-pressed","true"),this.activeViewMenu&&this.activeViewMenu.updateSortField())},createView:function(t,e){return new(this.getViewClass(t))(this,this.$elements,e)},getViewClass:function(t){switch(t){case"table":case"structure":return Craft.TableElementIndexView;case"thumbs":return Craft.ThumbsElementIndexView;default:throw'View mode "'.concat(t,'" not supported.')}},rememberDisabledElementId:function(t){-1===$.inArray(t,this.settings.disabledElementIds)&&this.settings.disabledElementIds.push(t)},forgetDisabledElementId:function(t){var e=$.inArray(t,this.settings.disabledElementIds);-1!==e&&this.settings.disabledElementIds.splice(e,1)},enableElements:function(t){t.removeClass("disabled").parents(".disabled").removeClass("disabled");for(var e=0;e<t.length;e++){var i=$(t[e]).data("id");this.forgetDisabledElementId(i)}this.onEnableElements(t)},disableElements:function(t){t.removeClass("sel").addClass("disabled");for(var e=0;e<t.length;e++){var i=$(t[e]).data("id");this.rememberDisabledElementId(i)}this.onDisableElements(t)},getElementById:function(t){return this.view.getElementById(t)},enableElementsById:function(t){t=$.makeArray(t);for(var e=0;e<t.length;e++){var i=t[e],s=this.getElementById(i);s&&s.length?this.enableElements(s):this.forgetDisabledElementId(i)}},disableElementsById:function(t){t=$.makeArray(t);for(var e=0;e<t.length;e++){var i=t[e],s=this.getElementById(i);s&&s.length?this.disableElements(s):this.rememberDisabledElementId(i)}},selectElementAfterUpdate:function(t){null===this._autoSelectElements&&(this._autoSelectElements=[]),this._autoSelectElements.push(t)},addButton:function(t){this.getButtonContainer().append(t)},isShowingSidebar:function(){return null===this.showingSidebar&&(this.showingSidebar=this.$sidebar.length&&!this.$sidebar.hasClass("hidden")),this.showingSidebar},getButtonContainer:function(){if(this.settings.buttonContainer)return $(this.settings.buttonContainer);var t=$("#action-buttons");return t.length||(t=$('<div id="action-buttons"/>').appendTo($("#header"))),t},setIndexBusy:function(){this.$elements.addClass("busy"),this.$updateSpinner.appendTo(this.$elements),this.isIndexBusy=!0,document.activeElement&&this.$elements[0].contains(document.activeElement)&&(this._activeElement=document.activeElement,document.activeElement.blur());var t=this.$elements.height(),e=window.innerHeight,i=$(document).scrollTop();if("modal"==this.settings.context&&(e=this.$elements.parents(".modal").height(),i=this.$elements.scrollParent().scrollTop()),t>e){var s=Math.floor(i+e/2)-100;s=Math.floor(s/t*100),document.documentElement.style.setProperty("--elements-busy-top-position",s+"%")}},setIndexAvailable:function(){this.$elements.removeClass("busy"),this.$updateSpinner.remove(),this.isIndexBusy=!1,this._activeElement&&(document.activeElement&&document.activeElement!==document.body||(document.body.contains(this._activeElement)?this._activeElement.focus():this._activeElement.id&&$("#".concat(this._activeElement.id)).focus()),this._activeElement=null)},createCustomizeSourcesModal:function(){var t=new Craft.CustomizeSourcesModal(this,{hideOnEsc:!1,hideOnShadeClick:!1,onHide:function(){t.destroy()}});return t},disable:function(){this.sourceSelect&&this.sourceSelect.disable(),this.view&&this.view.disable(),this.base()},enable:function(){this.sourceSelect&&this.sourceSelect.enable(),this.view&&this.view.enable(),this.base()},onAfterInit:function(){this.settings.onAfterInit(),this.trigger("afterInit")},onSelectSource:function(){this.settings.onSelectSource(this.sourceKey),this.trigger("selectSource",{sourceKey:this.sourceKey})},onSelectSite:function(){this.settings.onSelectSite(this.siteId),this.trigger("selectSite",{siteId:this.siteId})},onUpdateElements:function(){this.settings.onUpdateElements(),this.trigger("updateElements")},onSelectionChange:function(){this.settings.onSelectionChange(),this.trigger("selectionChange")},onEnableElements:function(t){this.settings.onEnableElements(t),this.trigger("enableElements",{elements:t})},onDisableElements:function(t){this.settings.onDisableElements(t),this.trigger("disableElements",{elements:t})},onAfterAction:function(t,e){this.settings.onAfterAction(t,e),this.trigger("afterAction",{action:t,params:e})},_handleSourceSelectionChange:function(){this.sourceSelect.totalSelected?this.selectSource(this.sourceSelect.$selectedItems)&&this.updateElements():this.sourceSelect.selectItem(this.$visibleSources.first())},_handleActionTriggerSubmit:function(t){t.preventDefault();var e=$(t.currentTarget);e.hasClass("disabled")||e.data("custom-handler")||this.submitAction(e.data("action"),Garnish.getPostData(e))},_handleMenuActionTriggerSubmit:function(t){var e=$(t.option);e.hasClass("disabled")||e.data("custom-handler")||this.submitAction(e.data("action"))},_handleStatusChange:function(t){this.statusMenu.$options.removeClass("sel");var e=$(t.selectedOption).addClass("sel");this.$statusMenuBtn.html(e.html()),this.trashed=!1,this.drafts=!1,this.status=null;var i=null;Garnish.hasAttr(e,"data-trashed")?(this.trashed=!0,i="trashed"):Garnish.hasAttr(e,"data-drafts")?(this.drafts=!0,i="drafts"):this.status=i=e.data("status")||null,this.activeViewMenu&&this.activeViewMenu.updateSortField(),"index"===this.settings.context&&Craft.setQueryParam("status",i),this.updateElements()},_handleSiteChange:function(t){this.siteMenu.$options.removeClass("sel");var e=$(t.selectedOption).addClass("sel");this.$siteMenuBtn.html(e.html()),this._setSite(e.data("site-id")),this.initialized&&this.updateElements(),this.onSelectSite()},_setSite:function(t){var e=null===this.siteId;this.siteId=t,this.updateSourceVisibility(),!this.initialized||e||this.$source&&this.$source.length||!this.$visibleSources.length||this.selectSource(this.$visibleSources[0]);for(var i,s=this.getSourceContainer().children(".heading"),n=0;n<s.length;n++)0!==(i=s.eq(n)).has("> ul > li:not(.hidden)").length?i.removeClass("hidden"):i.addClass("hidden");this.initialized&&("index"===this.settings.context&&Craft.cp.setSiteId(t),this.updateFilterBtn())},updateSourceVisibility:function(){this.$visibleSources=$();for(var t=0;t<this.$sources.length;t++){var e=this.$sources.eq(t);Garnish.hasAttr(e,"data-disabled")||void 0!==e.data("sites")&&-1===e.data("sites").toString().split(",").indexOf(this.siteId.toString())?(e.parent().addClass("hidden"),this.$source&&this.$source.get(0)===e.get(0)&&(this.$source=null,this.$rootSource=null,this.sourceKey=null,this.rootSourceKey=null)):(e.parent().removeClass("hidden"),this.$visibleSources=this.$visibleSources.add(e))}},_handleSelectionChange:function(){this.updateActionTriggers(),this.onSelectionChange()},_handleSourceDblClick:function(t){this._toggleSource($(t.currentTarget)),t.stopPropagation()},_handleSourceToggleClick:function(t){this._toggleSource($(t.currentTarget).prev("a")),t.stopPropagation()},_getSourcesInList:function(t,e){var i=t.find("> li:not(.heading) > a");return e&&(i=i.add(t.find("> li.heading > ul > li > a"))),i},_getChildSources:function(t){var e=t.siblings("ul");return this._getSourcesInList(e)},_getSourceToggle:function(t){return t.siblings(".toggle")},_toggleSource:function(t){t.parent("li").hasClass("expanded")?this._collapseSource(t):this._expandSource(t)},_expandSource:function(t){t.next(".toggle").attr({"aria-expanded":"true","aria-label":Craft.t("app","Hide nested sources")}),t.parent("li").addClass("expanded");for(var e=this._getChildSources(t),i=0;i<e.length;i++)this.initSource($(e[i])),this.$visibleSources&&(this.$visibleSources=this.$visibleSources.add(e[i]));var s=t.data("key");-1===this.instanceState.expandedSources.indexOf(s)&&(this.instanceState.expandedSources.push(s),this.storeInstanceState())},_collapseSource:function(t){t.next(".toggle").attr({"aria-expanded":"false","aria-label":Craft.t("app","Show nested sources")}),t.parent("li").removeClass("expanded");for(var e=this._getChildSources(t),i=0;i<e.length;i++)this.deinitSource($(e[i])),this.$visibleSources=this.$visibleSources.not(e[i]);var s=this.instanceState.expandedSources.indexOf(t.data("key"));-1!==s&&(this.instanceState.expandedSources.splice(s,1),this.storeInstanceState())},_isViewPaginated:function(){return"index"===this.settings.context&&"structure"!==this.viewMode},_updateView:function(t,e){var i=this;this.actions&&(this.hideActionTriggers(),this.actions=this.actionsHeadHtml=this.actionsBodyHtml=this._$triggers=null),this.$countContainer.length&&(this.$countSpinner.removeClass("hidden"),this.$countContainer.html(""),this._countResults().then((function(t){i.$countSpinner.addClass("hidden");var e=Craft.elementTypeNames[i.elementType]?Craft.elementTypeNames[i.elementType][2]:i.settings.elementTypeName.toLowerCase(),s=Craft.elementTypeNames[i.elementType]?Craft.elementTypeNames[i.elementType][3]:i.settings.elementTypePluralName.toLowerCase();if(i._isViewPaginated()){var n=Math.min(i.settings.batchSize*(i.page-1)+1,t),a=Math.min(n+(i.settings.batchSize-1),t),r=Craft.t("app","{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}",{first:n,last:a,total:t,item:e,items:s}),o=$('<div class="flex pagination"/>').appendTo(i.$countContainer),l=Math.max(Math.ceil(t/i.settings.batchSize),1),h=$("<nav/>",{class:"flex","aria-label":Craft.t("app","{element} pagination",{element:e})}).appendTo(o),d=$("<button/>",{role:"button",class:"page-link prev-page"+(i.page>1?"":" disabled"),disabled:1===i.page,title:Craft.t("app","Previous Page")}).appendTo(h),c=$("<button/>",{role:"button",class:"page-link next-page"+(i.page<l?"":" disabled"),disabled:i.page===l,title:Craft.t("app","Next Page")}).appendTo(h);$("<div/>",{class:"page-info",text:r}).appendTo(o),i.page>1&&i.addListener(d,"click",(function(){this.removeListener(d,"click"),this.removeListener(c,"click"),this.setPage(this.page-1),this.updateElements(!0,!0)})),i.page<l&&i.addListener(c,"click",(function(){this.removeListener(d,"click"),this.removeListener(c,"click"),this.setPage(this.page+1),this.updateElements(!0,!0)}))}else{var u=Craft.t("app","{total, number} {total, plural, =1{{item}} other{{items}}}",{total:t,item:e,items:s});i.$countContainer.text(u)}})).catch((function(){i.$countSpinner.addClass("hidden")}))),this.$elements.html(e.html),Craft.appendHeadHtml(e.headHtml),Craft.appendBodyHtml(e.bodyHtml),this.$selectAllContainer=this.$elements.find(".selectallcontainer:first"),e.actions&&e.actions.length?this.$selectAllContainer.length&&(this.actions=e.actions,this.actionsHeadHtml=e.actionsHeadHtml,this.actionsBodyHtml=e.actionsBodyHtml,this.$selectAllCheckbox=$('<div class="checkbox"/>').prependTo(this.$selectAllContainer).attr({role:"checkbox",tabindex:"0","aria-checked":"false","aria-label":Craft.t("app","Select all")}),this.addListener(this.$selectAllCheckbox,"click",(function(){0===this.view.getSelectedElements().length?this.view.selectAllElements():this.view.deselectAllElements()})),this.addListener(this.$selectAllCheckbox,"keydown",(function(t){t.keyCode===Garnish.SPACE_KEY&&(t.preventDefault(),$(t.currentTarget).trigger("click"))}))):(this.$selectAllContainer.siblings().length||this.$selectAllContainer.parent(".header").remove(),this.$selectAllContainer.remove()),this.exporters=e.exporters,this.exportersByType=Craft.index(this.exporters||[],(function(t){return t.type})),this.exporters&&this.exporters.length?this.$exportBtn.removeClass("hidden"):this.$exportBtn.addClass("hidden");var s=this.actions||this.settings.selectable,n=Object.assign({context:this.settings.context,batchSize:"index"!==this.settings.context||"structure"===this.viewMode?this.settings.batchSize:null,params:t,selectable:s,multiSelect:this.actions||this.settings.multiSelect,canSelectElement:this.settings.canSelectElement,checkboxMode:!!this.actions,onSelectionChange:this._handleSelectionChange.bind(this)},this.getViewSettings());if(this.view=this.createView(this.getSelectedViewMode(),n),this._autoSelectElements){if(s)for(var a=0;a<this._autoSelectElements.length;a++)this.view.selectElementById(this._autoSelectElements[a]);this._autoSelectElements=null}this.onUpdateElements()},_updateBadgeCounts:function(t){for(var e in t)if(t.hasOwnProperty(e)){var i=this.getSourceByKey(e);if(i){var s=i.children(".badge");null!==t[e]?(s.length||(s=$('<span class="badge"/>').appendTo(i)),s.text(t[e])):s&&s.remove()}}},_countResults:function(){var t=this;return new Promise((function(e,i){if(null!==t.totalResults)e(t.totalResults);else{var s=t.getViewParams();delete s.criteria.offset,delete s.criteria.limit,null===t.resultSet&&(t.resultSet=Math.floor(1e8*Math.random())),s.resultSet=t.resultSet,Craft.sendActionRequest("POST",t.settings.countElementsAction,{data:s,cancelToken:t._createCancelToken()}).then((function(s){s.data.resultSet==t.resultSet?(t.totalResults=s.data.count,e(s.data.count)):i()})).catch(i)}}))},_createTriggers:function(){var t,e,i=[],s=[],n=[];for(t=0;t<this.actions.length;t++){var a=this.actions[t];if(a.trigger){var r=$('<form id="'+Craft.formatInputId(a.type)+'-actiontrigger"/>').data("action",a).append(a.trigger);r.find(".btn").addClass("secondary"),this.addListener(r,"submit","_handleActionTriggerSubmit"),i.push(r)}else a.destructive?n.push(a):s.push(a)}if(s.length||n.length){var o=$("<form/>");e=$("<button/>",{type:"button",class:"btn secondary menubtn","data-icon":"settings",title:Craft.t("app","Actions")}).appendTo(o);var l=$('<ul class="menu"/>').appendTo(o),h=this._createMenuTriggerList(s,!1),d=this._createMenuTriggerList(n,!0);h&&h.appendTo(l),h&&d&&$("<hr/>").appendTo(l),d&&d.appendTo(l),i.push(o)}for(this._$triggers=$(),t=0;t<i.length;t++){var c=$("<div/>").append(i[t]);this._$triggers=this._$triggers.add(c)}this._$triggers.appendTo(this.$actionsContainer),Craft.appendHeadHtml(this.actionsHeadHtml),Craft.appendBodyHtml(this.actionsBodyHtml),Craft.initUiElements(this._$triggers),e&&e.data("menubtn").on("optionSelect",this._handleMenuActionTriggerSubmit.bind(this))},_showExportHud:function(){var t=this;this.$exportBtn.addClass("active"),this.$exportBtn.attr("aria-expanded","true");for(var e=$("<form/>",{class:"export-form"}),i=[],s=0;s<this.exporters.length;s++)i.push({label:this.exporters[s].name,value:this.exporters[s].type});var n=Craft.ui.createSelectField({label:Craft.t("app","Export Type"),options:i,class:"fullwidth"}).appendTo(e),a=Craft.ui.createSelectField({label:Craft.t("app","Format"),options:[{label:"CSV",value:"csv"},{label:"JSON",value:"json"},{label:"XML",value:"xml"}],class:"fullwidth"}).appendTo(e),r=n.find("select");this.addListener(r,"change",(function(){var e=r.val();t.exportersByType[e].formattable?a.removeClass("hidden"):a.addClass("hidden")})),r.trigger("change");var o=this.view.getSelectedElementIds();if(!o.length)var l=Craft.ui.createTextField({label:Craft.t("app","Limit"),placeholder:Craft.t("app","No limit"),type:"number",min:1}).appendTo(e);var h=Craft.ui.createSubmitButton({class:"fullwidth",label:Craft.t("app","Export"),spinner:!0}).appendTo(e),d=new Garnish.MultiFunctionBtn(h);new Garnish.HUD(this.$exportBtn,e).on("hide",(function(){t.$exportBtn.removeClass("active"),t.$exportBtn.attr("aria-expanded","false")}));var c=!1;this.addListener(e,"submit",(function(t){if(t.preventDefault(),!c){c=!0,d.busyEvent();var e=this.getViewParams();if(delete e.criteria.offset,delete e.criteria.limit,delete e.collapsedElementIds,e.type=n.find("select").val(),e.format=a.find("select").val(),o.length)e.criteria.id=o;else{var i=parseInt(l.find("input").val());i&&!isNaN(i)&&(e.criteria.limit=i)}Craft.csrfTokenValue&&(e[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl("element-indexes/export"),e).catch((function(t){axios.isCancel(t)||Craft.cp.displayError(Craft.t("app","A server error occurred."))})).finally((function(){c=!1,d.successEvent()}))}}))},_createMenuTriggerList:function(t,e){if(t&&t.length){for(var i=$("<ul/>"),s=0;s<t.length;s++)$("<li/>").append($("<a/>",{id:Craft.formatInputId(t[s].type)+"-actiontrigger",class:e?"error":null,data:{action:t[s]},text:t[s].name})).appendTo(i);return i}},showFilterHud:function(){this.filterHuds[this.siteId]||(this.filterHuds[this.siteId]={}),this.filterHuds[this.siteId][this.sourceKey]?this.filterHuds[this.siteId][this.sourceKey].show():(this.filterHuds[this.siteId][this.sourceKey]=new h(this,this.sourceKey,this.siteId),this.updateFilterBtn())},updateFilterBtn:function(){this.$filterBtn.removeClass("active"),this.filterHuds[this.siteId]&&this.filterHuds[this.siteId][this.sourceKey]?(this.$filterBtn.attr("aria-controls",this.filterHuds[this.siteId][this.sourceKey].id).attr("aria-expanded",this.filterHuds[this.siteId][this.sourceKey].showing?"true":"false"),(this.filterHuds[this.siteId][this.sourceKey].showing||this.filterHuds[this.siteId][this.sourceKey].hasRules())&&this.$filterBtn.addClass("active")):this.$filterBtn.attr("aria-controls",null)}},{defaults:{context:"index",modal:null,storageKey:null,condition:null,referenceElementId:null,referenceElementSiteId:null,criteria:null,batchSize:100,disabledElementIds:[],selectable:!1,multiSelect:!1,canSelectElement:null,buttonContainer:null,hideSidebar:!1,toolbarSelector:".toolbar:first",refreshSourcesAction:"element-indexes/get-source-tree-html",updateElementsAction:"element-indexes/get-elements",countElementsAction:"element-indexes/count-elements",submitActionsAction:"element-indexes/perform-action",defaultSiteId:null,defaultSource:null,defaultSourcePath:null,showSourcePath:!0,canHaveDrafts:!1,elementTypeName:Craft.t("app","Element"),elementTypePluralName:Craft.t("app","Elements"),onAfterInit:$.noop,onSelectSource:$.noop,onSelectSite:$.noop,onUpdateElements:$.noop,onSelectionChange:$.noop,onSourcePathChange:$.noop,onEnableElements:$.noop,onDisableElements:$.noop,onAfterAction:$.noop}});var l=Garnish.Base.extend({elementIndex:null,$source:null,sourceKey:null,menu:null,id:null,$trigger:null,$container:null,$sortField:null,$sortAttributeSelect:null,$sortDirectionPicker:null,sortDirectionListbox:null,$tableColumnsField:null,$tableColumnsContainer:null,$revertContainer:null,$revertBtn:null,$closeBtn:null,init:function(t,e){var i=this;this.elementIndex=t,this.$source=e,this.sourceKey=e.data("key"),this.id="view-menu-".concat(Math.floor(1e9*Math.random())),this.$trigger=$("<button/>",{type:"button",class:"btn menubtn hidden",text:Craft.t("app","View"),"aria-label":Craft.t("app","View settings"),"aria-controls":this.id,"data-icon":"sliders"}).appendTo(this.elementIndex.$toolbar),this.$container=$("<div/>",{id:this.id,class:"menu menu--disclosure element-index-view-menu","data-align":"right"}).appendTo(Garnish.$bod),this._buildMenu(),this.addListener(this.$container,"mousedown",(function(t){t.stopPropagation()})),this.menu=new Garnish.DisclosureMenu(this.$trigger),this.menu.on("show",(function(){i.$trigger.addClass("active")})),this.menu.on("hide",(function(){i.$trigger.removeClass("active"),setTimeout((function(){i.tidyTableColumnField()}),Garnish.FX_DURATION)}))},showTrigger:function(){this.$trigger.removeClass("hidden")},hideTrigger:function(){this.$trigger.data("trigger").hide(),this.$trigger.addClass("hidden"),this.menu.hide()},updateSortField:function(){this.$sortField&&("structure"===this.elementIndex.viewMode?(this.$sortField.addClass("hidden"),this.$tableColumnsField.addClass("first-child")):(this.$sortField.removeClass("hidden"),this.$tableColumnsField.removeClass("first-child")));var t=s(this.elementIndex.getSortAttributeAndDirection(),2),e=t[0],i=t[1],n=this.$sortAttributeSelect.children('option[value="score"]');this.elementIndex.searching?n.length||this.$sortAttributeSelect.prepend($("<option/>",{value:"score",text:Craft.t("app","Score")})):n.length&&n.remove(),this.$sortAttributeSelect.val(e),this.sortDirectionListbox.select("asc"===i?0:1),"score"===e?(this.sortDirectionListbox.disable(),this.$sortDirectionPicker.addClass("disabled")):(this.sortDirectionListbox.enable(),this.$sortDirectionPicker.removeClass("disabled"))},updateTableColumnField:function(){var t,e,i=this,s=this.elementIndex.getSelectedTableColumns();s.forEach((function(s){var n=i.$tableColumnsContainer.find('input[value="'.concat(s,'"]'));n.prop("checked")||n.prop("checked",!0);var a=n.parent();t&&a.index()<e&&a.insertAfter(t),t=a,e=a.index()}));for(var n=this._getTableColumnCheckboxes(),a=0;a<n.length;a++){var r=n.eq(a);r.prop("checked")&&!s.includes(r.val())&&r.prop("checked",!1)}},tidyTableColumnField:function(){var t=this.elementIndex.getTableColumnOptions(this.$source).map((function(t){return t.attr})).reduce((function(t,s,n){return e(e({},t),{},i({},s,n))}),{});this.$tableColumnsContainer.children().sort((function(e,i){var s=$(e).children('input[type="checkbox"]')[0],n=$(i).children('input[type="checkbox"]')[0];return s.checked&&n.checked?0:s.checked||n.checked?s.checked?-1:1:t[s.value]<t[n.value]?-1:1})).appendTo(this.$tableColumnsContainer)},revert:function(){this.elementIndex.setSelecetedSourceState({order:null,sort:null,tableColumns:null}),this.updateSortField(),this.updateTableColumnField(),this.tidyTableColumnField(),this.$revertBtn.remove(),this.$revertBtn=null,this.$closeBtn.focus(),this.elementIndex.updateElements()},_buildMenu:function(){var t=this,e=$('<div class="meta"/>').appendTo(this.$container);this.$sortField=this._createSortField().appendTo(e),this.$tableColumnsField=this._createTableColumnsField().appendTo(e),this.updateSortField(),this.$sortAttributeSelect.focus();var i=$("<div/>",{class:"flex menu-footer"}).appendTo(this.$container);this.$revertContainer=$("<div/>",{class:"flex-grow"}).appendTo(i),(this.elementIndex.getSelectedSourceState("order")||this.elementIndex.getSelectedSourceState("sort")||this.elementIndex.getSelectedSourceState("tableColumns"))&&this._createRevertBtn(),this.$closeBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close")}).appendTo(i).on("click",(function(){t.menu.hide()}))},_createSortField:function(){var t=this,e=$('<div class="flex"/>'),i=Craft.ui.createSelect({options:this.elementIndex.getSortOptions(this.$source).map((function(t){return{label:Craft.escapeHtml(t.label),value:t.attr}}))}).addClass("fullwidth").appendTo($('<div class="flex-grow"/>').appendTo(e));this.$sortAttributeSelect=i.children("select").attr({"aria-label":Craft.t("app","Sort attribute")}),this.$sortDirectionPicker=$("<section/>",{class:"btngroup btngroup--exclusive","aria-label":Craft.t("app","Sort direction")}).append($("<button/>",{type:"button",class:"btn",title:Craft.t("app","Sort ascending"),"aria-label":Craft.t("app","Sort ascending"),"aria-pressed":"false","data-icon":"asc","data-dir":"asc"})).append($("<button/>",{type:"button",class:"btn",title:Craft.t("app","Sort descending"),"aria-label":Craft.t("app","Sort descending"),"aria-pressed":"false","data-icon":"desc","data-dir":"desc"})).appendTo(e),this.sortDirectionListbox=new Craft.Listbox(this.$sortDirectionPicker,{onChange:function(e){e.data("dir")!==t.elementIndex.getSelectedSortDirection()&&(t.elementIndex.setSelectedSortAttribute(t.$sortAttributeSelect.val(),e.data("dir")),t.elementIndex.sortByScore||t.elementIndex.selectViewMode(t.elementIndex.viewMode),t.elementIndex.updateElements(),t._createRevertBtn())}}),this.$sortAttributeSelect.on("change",(function(){t.elementIndex.setSelectedSortAttribute(t.$sortAttributeSelect.val(),null,!1),t.elementIndex.selectViewMode(t.elementIndex.viewMode),t.elementIndex.updateElements(),t._createRevertBtn()}));var s=Craft.ui.createField(e,{label:Craft.t("app","Sort by"),fieldset:!0});return s.addClass("sort-field"),s},_getTableColumnCheckboxes:function(){return this.$tableColumnsContainer.find('input[type="checkbox"]')},_createTableColumnsField:function(){var t=this,e=this.elementIndex.getTableColumnOptions(this.$source);if(!e.length)return $();this.$tableColumnsContainer=$("<div/>"),e.forEach((function(e){$('<div class="element-index-view-menu-table-column"/>').append('<div class="icon move"/>').append(Craft.ui.createCheckbox({label:Craft.escapeHtml(e.label),value:e.attr})).appendTo(t.$tableColumnsContainer)})),this.updateTableColumnField(),this.tidyTableColumnField(),new Garnish.DragSort(this.$tableColumnsContainer.children(),{handle:".move",axis:"y",onSortChange:function(){t._onTableColumnChange()}}),this._getTableColumnCheckboxes().on("change",(function(e){t._onTableColumnChange()}));var i=Craft.ui.createField(this.$tableColumnsContainer,{label:Craft.t("app","Table Columns"),fieldset:!0});return i.addClass("table-columns-field"),i},_onTableColumnChange:function(){for(var t=[],e=this._getTableColumnCheckboxes().filter(":checked"),i=0;i<e.length;i++)t.push(e.eq(i).val());Craft.compare(t,this.elementIndex.getSelectedTableColumns(this.$source))||(this.elementIndex.setSelectedTableColumns(t,!1),this.elementIndex.updateElements(),this._createRevertBtn())},_createRevertBtn:function(){var t=this;this.$revertBtn||(this.$revertBtn=$("<button/>",{type:"button",class:"light",text:Craft.t("app","Use defaults")}).appendTo(this.$revertContainer).on("click",(function(){t.revert()})))},destroy:function(){this.menu.destroy(),delete this.menu,this.base()}}),h=Garnish.HUD.extend({elementIndex:null,sourceKey:null,siteId:null,id:null,loading:!0,serialized:null,$clearBtn:null,cleared:!1,init:function(t,e,i){var s=this;this.elementIndex=t,this.sourceKey=e,this.siteId=i,this.id="filter-".concat(Math.floor(1e9*Math.random()));var n=$("<div/>").append($("<div/>",{class:"spinner"})).append($("<div/>",{text:Craft.t("app","Loading"),class:"visually-hidden","aria-role":"alert"}));this.base(this.elementIndex.$filterBtn,n,{hudClass:"hud element-filter-hud loading"}),this.$hud.attr({id:this.id,"aria-live":"polite","aria-busy":"false"}),this.$tip.remove(),this.$tip=null,this.$body.on("submit",(function(t){t.preventDefault(),s.hide()})),Craft.sendActionRequest("POST","element-indexes/filter-hud",{data:{elementType:this.elementIndex.elementType,source:this.sourceKey,condition:this.elementIndex.settings.condition,id:"".concat(this.id,"-filters")}}).then((function(t){s.loading=!1,s.$hud.removeClass("loading"),n.remove(),s.$main.append(t.data.hudHtml),Craft.appendHeadHtml(t.data.headHtml),Craft.appendBodyHtml(t.data.bodyHtml);var e=$("<div/>",{class:"flex flex-nowrap"}).appendTo(s.$main);$("<div/>",{class:"flex-grow"}).appendTo(e),s.$clearBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(e),$("<button/>",{type:"submit",class:"btn secondary",text:Craft.t("app","Apply")}).appendTo(e),s.$clearBtn.on("click",(function(){s.clear()})),s.$hud.find(".condition-container").on("htmx:beforeRequest",(function(){s.setBusy()})),s.$hud.find(".condition-container").on("htmx:load",(function(){s.setReady(),s.updateSizeAndPosition(!0)})),s.setFocus()})).catch((function(){Craft.cp.displayError(Craft.t("app","A server error occurred."))})),this.$hud.css("position","fixed"),this.addListener(Garnish.$win,"scroll,resize",(function(){s.updateSizeAndPosition(!0)}))},addListener:function(t,e,i,s){t===this.$main&&"resize"===e||this.base(t,e,i,s)},setBusy:function(){this.$hud.attr("aria-busy","true"),$("<div/>",{class:"visually-hidden",text:Craft.t("app","Loading")}).insertAfter(this.$main.find(".htmx-indicator"))},setReady:function(){this.$hud.attr("aria-busy","false")},setFocus:function(){Garnish.setFocusWithin(this.$main)},clear:function(){this.cleared=!0,this.hide()},updateSizeAndPositionInternal:function(){var t,e=this.elementIndex.$searchContainer[0].getBoundingClientRect(),i=Garnish.$win.height(),s=i-e.bottom;this.$body.height()>s&&(t=i-e.bottom-10),this.$hud.css({width:this.elementIndex.$searchContainer.outerWidth()-2,top:e.top+this.elementIndex.$searchContainer.outerHeight(),left:e.left+1,height:t?"".concat(t,"px"):"unset",overflowY:t?"scroll":"unset"})},onShow:function(){this.base(),this.$clearBtn&&this.$clearBtn.text(Craft.t("app","Clear")),this.elementIndex.updateFilterBtn(),this.setFocus()},onHide:function(){this.base(),this.serialized!==(this.serialized=this.serialize())&&this.elementIndex.updateElements(),this.cleared?this.destroy():(this.$hud.detach(),this.$shade.detach()),this.elementIndex.updateFilterBtn(),this.elementIndex.$filterBtn.focus()},hasRules:function(){return 0!==this.$main.has(".condition-rule").length},serialize:function(){return!this.cleared&&this.hasRules()?this.$body.serialize():null},destroy:function(){this.base(),delete this.elementIndex.filterHuds[this.siteId][this.sourceKey]}})},8495:function(){Craft.BaseElementIndexView=Garnish.Base.extend({$container:null,$loadingMoreSpinner:null,$elementContainer:null,$scroller:null,elementIndex:null,elementSelect:null,loadingMore:!1,_totalVisible:null,_morePending:null,_handleEnableElements:null,_handleDisableElements:null,get thumbLoader(){return console.warn("Craft.BaseElementIndexView::thumbLoader is deprecated. Craft.cp.elementThumbLoader should be used instead."),Craft.cp.elementThumbLoader},init:function(t,e,i){var s=this;this.elementIndex=t,this.$container=$(e),this.setSettings(i,Craft.BaseElementIndexView.defaults),this.$loadingMoreSpinner=$('<div class="centeralign hidden"><div class="spinner loadingmore"></div></div>').insertAfter(this.$container),this.$elementContainer=this.getElementContainer();var n=this.$elementContainer.children();this.setTotalVisible(n.length),this.setMorePending(this.settings.batchSize&&n.length==this.settings.batchSize),Craft.cp.elementThumbLoader.load(n),this.settings.selectable&&(this.elementSelect=new Garnish.Select(this.$elementContainer,$(n.toArray().filter((function(t){return s.canSelectElement($(t))}))),{multi:this.settings.multiSelect,vertical:this.isVerticalList(),handle:"index"===this.settings.context?".checkbox, .element:first":null,filter:":not(a):not(.toggle)",checkboxMode:this.settings.checkboxMode,onSelectionChange:this.onSelectionChange.bind(this)}),this._handleEnableElements=function(t){s.elementSelect.addItems(t.elements)},this._handleDisableElements=function(t){s.elementSelect.removeItems(t.elements)},this.elementIndex.on("enableElements",this._handleEnableElements),this.elementIndex.on("disableElements",this._handleDisableElements)),"index"===this.settings.context&&(this._handleElementEditing=function(t){var e=$(t.target);if("A"!==e.prop("nodeName")){var i;if(e.hasClass("element"))i=e;else if(!(i=e.closest(".element")).length)return;Garnish.hasAttr(i,"data-editable")&&Craft.createElementEditor(i.data("type"),i)}},this.elementIndex.trashed||this.addListener(this.$elementContainer,"dblclick,taphold",this._handleElementEditing)),this.afterInit(),this.settings.batchSize&&("index"===this.settings.context?this.$scroller=Garnish.$scrollContainer:this.$scroller=this.elementIndex.$main,this.$scroller.scrollTop(0),this.addListener(this.$scroller,"scroll","maybeLoadMore"),this.maybeLoadMore())},canSelectElement:function(t){return!t.hasClass("disabled")&&(this.settings.canSelectElement?this.settings.canSelectElement(t):!!t.data("id"))},getElementContainer:function(){throw"Classes that extend Craft.BaseElementIndexView must supply a getElementContainer() method."},afterInit:function(){},getAllElements:function(){return this.$elementContainer.children()},getEnabledElements:function(){return this.$elementContainer.children(":not(.disabled)")},getElementById:function(t){var e=this.$elementContainer.children('[data-id="'+t+'"]:first');return e.length?e:null},getSelectedElements:function(){if(!this.elementSelect)throw"This view is not selectable.";return this.elementSelect.$selectedItems},getSelectedElementIds:function(){var t;try{t=this.getSelectedElements()}catch(t){}var e=[];if(t)for(var i=0;i<t.length;i++)e.push(t.eq(i).data("id"));return e},selectElement:function(t){if(!this.elementSelect)throw"This view is not selectable.";return this.elementSelect.selectItem(t,!0),!0},selectElementById:function(t){if(!this.elementSelect)throw"This view is not selectable.";var e=this.getElementById(t);return!!e&&(this.elementSelect.selectItem(e,!0),!0)},selectAllElements:function(){this.elementSelect.selectAll()},deselectAllElements:function(){this.elementSelect.deselectAll()},getElementCheckbox:function(t){return $(t).find('[role="checkbox"]')},isVerticalList:function(){return!1},getTotalVisible:function(){return this._totalVisible},setTotalVisible:function(t){this._totalVisible=t},getMorePending:function(){return this._morePending},setMorePending:function(t){this._morePending=t},maybeLoadMore:function(){this.canLoadMore()&&this.loadMore()},canLoadMore:function(){return!(!this.getMorePending()||!this.settings.batchSize)&&(this.$scroller[0]===Garnish.$win[0]?Garnish.$win.innerHeight()+Garnish.$win.scrollTop()>=this.$container.offset().top+this.$container.height():this.$scroller.prop("scrollHeight")-this.$scroller.scrollTop()<=this.$scroller.outerHeight()+15)},loadMore:function(){var t=this;this.getMorePending()&&!this.loadingMore&&this.settings.batchSize&&(this.loadingMore=!0,this.$loadingMoreSpinner.removeClass("hidden"),this.removeListener(this.$scroller,"scroll"),Craft.sendActionRequest("POST",this.settings.loadMoreElementsAction,{data:this.getLoadMoreParams()}).then((function(e){t.loadingMore=!1,t.$loadingMoreSpinner.addClass("hidden");var i=$(e.data.html);t.appendElements(i),Craft.appendHeadHtml(e.data.headHtml),Craft.appendBodyHtml(e.data.bodyHtml),t.elementSelect&&(t.elementSelect.addItems(i.filter(":not(.disabled)")),t.elementIndex.updateActionTriggers()),t.setTotalVisible(t.getTotalVisible()+i.length),t.setMorePending(i.length==t.settings.batchSize),t.addListener(t.$scroller,"scroll","maybeLoadMore"),t.maybeLoadMore()})).catch((function(e){t.loadingMore=!1,t.$loadingMoreSpinner.addClass("hidden")})))},getLoadMoreParams:function(){var t=$.extend(!0,{},this.settings.params);return t.criteria.offset=this.getTotalVisible(),t},appendElements:function(t){t.appendTo(this.$elementContainer),Craft.cp.elementThumbLoader.load(t),this.onAppendElements(t)},onAppendElements:function(t){this.settings.onAppendElements(t),this.trigger("appendElements",{newElements:t})},onSelectionChange:function(){var t=this;this.settings.onSelectionChange(),this.trigger("selectionChange"),this.settings.checkboxMode&&this.elementSelect.$items.each((function(e,i){t.elementSelect.isSelected(i)?t.getElementCheckbox(i).attr("aria-checked","true"):t.getElementCheckbox(i).attr("aria-checked","false")}))},disable:function(){this.elementSelect&&this.elementSelect.disable()},enable:function(){this.elementSelect&&this.elementSelect.enable()},destroy:function(){this.$loadingMoreSpinner.remove(),this.elementSelect&&(this.elementIndex.off("enableElements",this._handleEnableElements),this.elementIndex.off("disableElements",this._handleDisableElements),this.elementSelect.destroy(),delete this.elementSelect),this.base()}},{defaults:{context:"index",batchSize:null,params:null,selectable:!1,multiSelect:!1,canSelectElement:null,checkboxMode:!1,loadMoreElementsAction:"element-indexes/get-more-elements",onAppendElements:$.noop,onSelectionChange:$.noop}})},5970:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.BaseElementSelectInput=Garnish.Base.extend({elementSelect:null,elementSort:null,modal:null,elementEditor:null,$container:null,$form:null,$elementsContainer:null,$elements:null,$addElementBtn:null,$spinner:null,_initialized:!1,get thumbLoader(){return console.warn("Craft.BaseElementSelectInput::thumbLoader is deprecated. Craft.cp.elementThumbLoader should be used instead."),Craft.cp.elementThumbLoader},init:function(t){var e=this;if(!$.isPlainObject(t)){for(var i={},s=["id","name","elementType","sources","criteria","sourceElementId","limit","modalStorageKey","fieldId"],n=0;n<s.length&&void 0!==arguments[n];n++)i[s[n]]=arguments[n];t=i}this.setSettings(t,Craft.BaseElementSelectInput.defaults),this.settings.modalStorageKey&&(this.modalStorageKey="BaseElementSelectInput."+this.settings.modalStorageKey),(1==this.settings.limit||this.settings.maintainHierarchy)&&(this.settings.sortable=!1),this.$container=this.getContainer(),this.$form=this.$container.closest("form"),this.$container.data("elementSelect",this),this.$elementsContainer=this.getElementsContainer(),this.$addElementBtn=this.getAddElementsBtn(),this.$spinner=this.getSpinner(),this.initElementSelect(),this.initElementSort(),this.resetElements(),this.$addElementBtn&&this.addListener(this.$addElementBtn,"activate","showModal"),Garnish.requestAnimationFrame((function(){e._initialized=!0}))},get totalSelected(){return this.$elements.length},getContainer:function(){return $("#"+this.settings.id)},getElementsContainer:function(){return this.$container.children(".elements")},getElements:function(){return this.$elementsContainer.find(".element")},getAddElementsBtn:function(){return this.$container.find(".btn.add:first")},getSpinner:function(){return this.$container.find(".spinner")},initElementSelect:function(){this.settings.selectable&&(this.elementSelect=new Garnish.Select({multi:this.settings.sortable,filter:":not(.delete)"}))},initElementSort:function(){var t=this;this.settings.sortable&&(this.elementSort=new Garnish.DragSort({container:this.$elementsContainer,filter:this.settings.selectable?function(){return t.elementSort.$targetItem.hasClass("sel")?t.elementSelect.getSelectedItems():t.elementSort.$targetItem}:null,ignoreHandleSelector:".delete",axis:this.getElementSortAxis(),collapseDraggees:!0,magnetStrength:4,helperLagBase:1.5,onSortChange:this.settings.selectable?function(){t.elementSelect.resetItemOrder()}:null}))},getElementSortAxis:function(){return"list"===this.settings.viewMode?"y":null},canAddMoreElements:function(){return!this.settings.limit||this.$elements.length<this.settings.limit},updateAddElementsBtn:function(){this.canAddMoreElements()?this.enableAddElementsBtn():this.disableAddElementsBtn()},enableAddElementsBtn:function(){this.$addElementBtn&&this.$addElementBtn.removeClass("hidden"),this.updateButtonContainer()},disableAddElementsBtn:function(){this.$addElementBtn&&this.$addElementBtn.addClass("hidden"),this.updateButtonContainer()},showSpinner:function(){this.$spinner&&this.$spinner.removeClass("hidden"),this.updateButtonContainer()},hideSpinner:function(){this.$spinner&&this.$spinner.addClass("hidden"),this.updateButtonContainer()},updateButtonContainer:function(){var t=this.$addElementBtn&&this.$addElementBtn.parent(".flex");t&&t.length&&(t.children(":not(.hidden)").length?t.removeClass("hidden"):t.addClass("hidden"))},focusNextLogicalElement:function(){if(this.canAddMoreElements()){var t=this.$addElementBtn;t&&t.get(0).focus()}else this.focusLastRemoveBtn()},focusLastRemoveBtn:function(){var t=this.$container.find(".delete");t.length&&t.last()[0].focus()},resetElements:function(){null!==this.$elements?this.removeElements(this.$elements):this.$elements=$(),this.addElements(this.getElements())},addElements:function(t){var e=this;Craft.cp.elementThumbLoader.load(t),this.settings.selectable&&this.elementSelect.addItems(t),this.settings.sortable&&this.elementSort.addItems(t),this.settings.editable&&(this._handleShowElementEditor=function(t){var i=$(t.currentTarget);!Garnish.hasAttr(i,"data-editable")||i.hasClass("disabled")||i.hasClass("loading")||(e.elementEditor=e.createElementEditor(i))},this.addListener(t,"dblclick",this._handleShowElementEditor),$.isTouchCapable()&&this.addListener(t,"taphold",this._handleShowElementEditor)),t.find(".delete").on("click dblclick",(function(t){e.removeElement($(t.currentTarget).closest(".element")),t.stopPropagation()})),t.on("keydown",(function(t){if([Garnish.BACKSPACE_KEY,Garnish.DELETE_KEY].includes(t.keyCode)){t.stopPropagation(),t.preventDefault();for(var i=e.elementSelect.getSelectedItems(),s=0;s<i.length;s++)e.removeElement(i.eq(s))}})),this.$elements=this.$elements.add(t),this.updateAddElementsBtn(),this.onAddElements()},createElementEditor:function(t,e){return e=Object.assign({elementSelectInput:this,prevalidate:this.settings.prevalidate},e),Craft.createElementEditor(this.settings.elementType,t,e)},replaceElement:function(t,e){var i=this;return new Promise((function(s,n){var a=i.$elements.filter('[data-id="'.concat(t,'"]'));if(a.length){i.showSpinner();var r={elementId:e,siteId:i.settings.criteria.siteId,thumbSize:i.settings.viewMode};Craft.sendActionRequest("POST","elements/get-element-html",{data:r}).then((function(t){i.removeElement(a);var e=Craft.getElementInfo(t.data.html);i.selectElements([e]),s()})).catch((function(t){var e=t.response;e&&e.data&&e.data.message?Craft.cp.displayError(e.data.message):Craft.cp.displayError(),n(e.data.message)})).finally((function(){i.hideSpinner()}))}else n("No element selected with an ID of ".concat(t,"."))}))},removeElements:function(t){if(this.settings.selectable&&this.elementSelect.removeItems(t),this.modal){for(var e=[],i=0;i<t.length;i++){var s=t.eq(i).data("id");s&&e.push(s)}e.length&&this.modal.elementIndex.enableElementsById(e)}var n;if(t.children("input").prop("disabled",!0),this.settings.selectable){var a=this.$elements.index(t.last());n=this.$elements.eq(a+1).find(".delete")}n.length?n.focus():this.focusNextLogicalElement(),this.$elements=this.$elements.not(t),this.updateAddElementsBtn(),this.onRemoveElements()},removeElement:function(t){if(this.settings.maintainHierarchy){var e=t.add(t.parent().siblings("ul").find(".element"));$("[name]",e).removeAttr("name"),this.removeElements(e);for(var i=0;i<e.length;i++)this._animateStructureElementAway(e,i)}else $("[name]",t).removeAttr("name"),this.removeElements(t),this.animateElementAway(t,(function(){t.remove()}))},animateElementAway:function(t,e){t.css("z-index",0);var i={opacity:-1};i["margin-"+Craft.left]=-(t.outerWidth()+parseInt(t.css("margin-"+Craft.right))),"list"!==this.settings.viewMode&&0!==this.$elements.length||(i["margin-bottom"]=-(t.outerHeight()+parseInt(t.css("margin-bottom")))),t.velocity(i,Craft.BaseElementSelectInput.REMOVE_FX_DURATION,(function(){e&&e()}))},showModal:function(){this.canAddMoreElements()&&(this.modal?this.modal.show():this.modal=this.createModal())},createModal:function(){return Craft.createElementSelectorModal(this.settings.elementType,this.getModalSettings())},getModalSettings:function(){return $.extend({closeOtherModals:!1,storageKey:this.modalStorageKey,sources:this.settings.sources,condition:this.settings.condition,referenceElementId:this.settings.referenceElementId,referenceElementSiteId:this.settings.referenceElementSiteId,criteria:this.settings.criteria,multiSelect:1!=this.settings.limit,hideOnSelect:!this.settings.maintainHierarchy,showSiteMenu:this.settings.showSiteMenu,disabledElementIds:this.getDisabledElementIds(),onSelect:this.onModalSelect.bind(this),onHide:this.onModalHide.bind(this),triggerElement:this.$addElementBtn,modalTitle:Craft.t("app","Choose")},this.settings.modalSettings)},getSelectedElementIds:function(){for(var t=[],e=0;e<this.$elements.length;e++)t.push(this.$elements.eq(e).data("id"));return t},getDisabledElementIds:function(){var e,i=this.getSelectedElementIds();return!this.settings.allowSelfRelations&&this.settings.sourceElementId&&i.push(this.settings.sourceElementId),this.settings.disabledElementIds&&i.push.apply(i,function(e){if(Array.isArray(e))return t(e)}(e=this.settings.disabledElementIds)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(e)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),i},onModalSelect:function(t){if(this.settings.maintainHierarchy)this.selectStructuredElements(t);else{if(this.settings.limit){var e=this.settings.limit-this.$elements.length;t.length>e&&(t=t.slice(0,e))}this.selectElements(t),this.updateDisabledElementsInModal()}},onModalHide:function(){var t=this;this.modal&&this.settings.condition&&this.settings.referenceElementId&&(this.modal.destroy(),this.modal=null),this.canAddMoreElements()||setTimeout((function(){t.focusNextLogicalElement()}),200)},selectElements:function(t){for(var e=0;e<t.length;e++){var i=t[e],s=this.createNewElement(i);this.appendElement(s),this.addElements(s),this.animateElementIntoPlace(i.$element,s),i.$element=s}this.onSelectElements(t)},selectStructuredElements:function(t){var e=this;this.modal.disable(),this.modal.disableCancelBtn(),this.modal.disableSelectBtn(),this.modal.showFooterSpinner();for(var i=this.getSelectedElementIds(),s=0;s<t.length;s++)i.push(t[s].id);var n={elementIds:i,siteId:t[0].siteId,containerId:this.settings.id,name:this.settings.name,branchLimit:this.settings.branchLimit,selectionLabel:this.settings.selectionLabel,elementType:this.settings.elementType},a=function(){e.modal.enable(),e.modal.enableCancelBtn(),e.modal.enableSelectBtn(),e.modal.hideFooterSpinner()};Craft.sendActionRequest("POST","relational-fields/structured-input-html",{data:n}).then((function(i){a();var s=$(i.data.html).children(".elements");e.$elementsContainer.replaceWith(s),e.$elementsContainer=s,e.resetElements();for(var n=[],r=0;r<t.length;r++){var o=t[r],l=e.getElementById(o.id);l&&(e.animateElementIntoPlace(o.$element,l),n.push(o))}e.updateDisabledElementsInModal(),e.modal.hide(),e.onSelectElements(n)})).catch((function(t){t.response,a()}))},createNewElement:function(t){var e=t.$element.clone(),i=Craft.t("app","Remove {label}",{label:Craft.escapeHtml(t.label)});return Craft.setElementSize(e,"large"===this.settings.viewMode?"large":"small"),e.addClass("removable").prepend($("<input/>",{type:"hidden",name:this.settings.name+(this.settings.single?"":"[]"),value:t.id})).prepend($("<button/>",{type:"button",class:"delete icon",title:Craft.t("app","Remove"),"aria-label":i})),e},appendElement:function(t){t.appendTo(this.$elementsContainer)},animateElementIntoPlace:function(t,e){var i=t.offset(),s=e.offset(),n=e.clone().appendTo(Garnish.$bod);e.css("visibility","hidden"),n.css({position:"absolute",zIndex:1e4,top:i.top,left:i.left});var a={top:s.top,left:s.left};n.velocity(a,Craft.BaseElementSelectInput.ADD_FX_DURATION,(function(){n.remove(),e.css("visibility","visible")}))},updateDisabledElementsInModal:function(){this.modal.elementIndex&&this.modal.elementIndex.disableElementsById(this.getDisabledElementIds())},getElementById:function(t){for(var e=0;e<this.$elements.length;e++){var i=this.$elements.eq(e);if(i.data("id")==t)return i}},onSelectElements:function(t){this.trigger("selectElements",{elements:t}),this.settings.onSelectElements(t),this.$container.trigger("change")},onAddElements:function(){this.trigger("addElements"),this.settings.onAddElements(),this.$container.trigger("change")},onRemoveElements:function(){this.trigger("removeElements"),this.settings.onRemoveElements(),this.$container.trigger("change")},_animateStructureElementAway:function(t,e){var i,s=this;e===t.length-1&&(i=function(){var e=t.first().parent().parent(),i=e.parent();i[0]===s.$elementsContainer[0]||e.siblings().length?e.remove():i.remove()});var n=function(){s.animateElementAway(t.eq(e),i)};0===e?n():setTimeout(n,100*e)}},{ADD_FX_DURATION:200,REMOVE_FX_DURATION:200,defaults:{id:null,name:null,fieldId:null,elementType:null,sources:null,condition:null,referenceElementId:null,referenceElementSiteId:null,criteria:{},allowSelfRelations:!1,sourceElementId:null,disabledElementIds:null,viewMode:"list",single:!1,maintainHierarchy:!1,branchLimit:null,limit:null,showSiteMenu:!1,modalStorageKey:null,modalSettings:{},onAddElements:$.noop,onSelectElements:$.noop,onRemoveElements:$.noop,sortable:!0,selectable:!0,editable:!0,prevalidate:!1,editorSettings:{}}})},4993:function(){Craft.BaseElementSelectorModal=Garnish.Modal.extend({elementType:null,elementIndex:null,supportSidebarToggleView:!1,$body:null,$content:null,$footer:null,$selectBtn:null,$sidebar:null,$sources:null,$sourceToggles:null,$sidebarToggleBtn:null,$sidebarCloseBtn:null,$mainHeading:null,$main:null,$search:null,$elements:null,$tbody:null,$primaryButtons:null,$secondaryButtons:null,$cancelBtn:null,init:function(t,e){this.elementType=t,this.setSettings(e,Craft.BaseElementSelectorModal.defaults);var i="elementSelectorModalHeading-"+Date.now(),s=$("<div/>",{class:"modal elementselectormodal","aria-labelledby":i}).appendTo(Garnish.$bod),n=$("<div/>",{class:this.settings.showTitle?"header":"visually-hidden"}).appendTo(s);$("<h1/>",{id:i,text:this.settings.modalTitle}).appendTo(n);var a=$("<div/>",{class:"body"}).append($("<div/>",{class:"spinner big"})).appendTo(s);this.$footer=$("<div/>",{class:"footer"}).appendTo(s),this.settings.fullscreen&&(s.addClass("fullscreen"),this.settings.minGutter=0),this.base(s,this.settings),this.$secondaryButtons=$('<div class="buttons left secondary-buttons"/>').appendTo(this.$footer),this.$primaryButtons=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$primaryButtons),this.$selectBtn=Craft.ui.createSubmitButton({class:"disabled",label:this.settings.selectBtnLabel,spinner:!0}).attr("aria-disabled","true").appendTo(this.$primaryButtons),this.$body=a,this.addListener(this.$cancelBtn,"activate","cancel"),this.addListener(this.$selectBtn,"activate","selectElements")},updateModalBottomPadding:function(){var t=this.$footer.outerHeight();t!==parseInt(this.$container.css("padding-bottom"))&&this.$container.css("padding-bottom",t)},updateSidebarView:function(){this.supportSidebarToggleView&&(this.sidebarShouldBeHidden()?this.$sidebarToggleBtn||this.buildSidebarToggleView():this.$sidebarToggleBtn&&this.resetView())},sidebarShouldBeHidden:function(){return this.$container.outerWidth()<550},resetView:function(){this.$mainHeader&&this.$mainHeader.remove(),this.$sidebarHeader&&this.$sidebarHeader.remove(),this.$sidebarToggleBtn=null,this.$body.addClass("has-sidebar"),this.$content.addClass("has-sidebar"),this.$sidebar.removeClass("hidden")},buildSidebarToggleView:function(){var t=this;!this.$sidebarToggleBtn&&this.sidebarShouldBeHidden()&&(this.$sidebarHeader=$('<div class="sidebar-header"/>').prependTo(this.$sidebar),this.$sidebarCloseBtn=Craft.ui.createButton({class:"nav-close close-btn"}).attr("aria-label",Craft.t("app","Close")).removeClass("btn").appendTo(this.$sidebarHeader),this.$mainHeader=$('<div class="main-header"/>').prependTo(this.$main),this.$mainHeading=$('<h2 class="main-heading">'.concat(this.getActiveSourceName(),"</h2>")).appendTo(this.$mainHeader),this.$sidebarToggleBtn=Craft.ui.createButton({toggle:!0,controls:"modal-sidebar",class:"nav-toggle"}).removeClass("btn").attr("aria-label",Craft.t("app","Show sidebar")).appendTo(this.$mainHeader),this.$sidebar.attr("id","modal-sidebar"),this.closeSidebar(),this.addListener(this.$sidebarToggleBtn,"click",(function(){t.toggleSidebar()})),this.addListener(this.$sidebarCloseBtn,"click",(function(){t.toggleSidebar()})))},sidebarIsOpen:function(){return"true"===this.$sidebarToggleBtn.attr("aria-expanded")},toggleSidebar:function(){this.sidebarIsOpen()?this.closeSidebar():this.openSidebar()},openSidebar:function(){var t=this;this.$body.addClass("has-sidebar"),this.$content.addClass("has-sidebar"),this.$sidebar.removeClass("hidden"),this.$sidebarToggleBtn.attr("aria-expanded","true"),this.$sidebar.find(":focusable").first().focus(),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.closeSidebar();var e=Garnish.getFocusedElement();$.contains(t.$sidebar.get(0),e.get(0))&&t.$sidebarToggleBtn.focus()}))},closeSidebar:function(){this.$sidebarToggleBtn&&(this.sidebarIsOpen()&&(Garnish.uiLayerManager.removeLayer(),this.$sidebar.addClass("hidden"),this.$sidebarToggleBtn.attr("aria-expanded","false")),this.$body.removeClass("has-sidebar"),this.$content.removeClass("has-sidebar"))},getActiveSourceName:function(){return this.$sidebar.find(".sel").text()},onFadeIn:function(){this.elementIndex?(this.updateModalBottomPadding(),Garnish.isMobileBrowser(!0)||this.elementIndex.$search.trigger("focus")):this._createElementIndex(),this.base()},onSelectionChange:function(){this.updateSelectBtnState()},onSelectSource:function(){this.updateHeading(),this.updateModalBottomPadding()},updateHeading:function(){this.$mainHeading&&this.$mainHeading.text(this.getActiveSourceName())},updateSelectBtnState:function(){this.$selectBtn&&(this.hasSelection()?this.enableSelectBtn():this.disableSelectBtn())},hasSelection:function(){return this.elementIndex&&this.elementIndex.getSelectedElements().length},enableSelectBtn:function(){this.$selectBtn.removeClass("disabled").attr("aria-disabled","false")},disableSelectBtn:function(){this.$selectBtn.addClass("disabled").attr("aria-disabled","true")},enableCancelBtn:function(){this.$cancelBtn.removeClass("disabled")},disableCancelBtn:function(){this.$cancelBtn.addClass("disabled")},showFooterSpinner:function(){this.$selectBtn.addClass("loading")},hideFooterSpinner:function(){this.$selectBtn.removeClass("loading")},cancel:function(){this.$cancelBtn.hasClass("disabled")||this.hide()},selectElements:function(){if(this.hasSelection()){this.elementIndex.view&&this.elementIndex.view.elementSelect&&this.elementIndex.view.elementSelect.clearMouseUpTimeout();var t=this.elementIndex.getSelectedElements(),e=this.getElementInfo(t);this.onSelect(e),this.settings.disableElementsOnSelect&&this.elementIndex.disableElements(this.elementIndex.getSelectedElements()),this.settings.hideOnSelect&&this.hide()}},getElementInfo:function(t){for(var e=[],i=0;i<t.length;i++){var s=$(t[i]),n=Craft.getElementInfo(s);e.push(n)}return e},onShow:function(){this.updateSelectBtnState(),this.addListener(Garnish.$win,"resize",this.updateSidebarView),this.addListener(Garnish.$win,"resize",this.updateModalBottomPadding),this.updateModalBottomPadding(),this.updateSidebarView(),this.base()},onHide:function(){this.closeSidebar(),this.base()},onSelect:function(t){this.settings.onSelect(t)},disable:function(){this.elementIndex&&this.elementIndex.disable(),this.base()},enable:function(){this.elementIndex&&this.elementIndex.enable(),this.base()},getElementIndexParams:function(){var t={context:"modal",elementType:this.elementType,sources:this.settings.sources};return null!==this.settings.showSiteMenu&&"auto"!==this.settings.showSiteMenu&&(t.showSiteMenu=this.settings.showSiteMenu?"1":"0"),t},_createElementIndex:function(){var t=this;Craft.sendActionRequest("POST",this.settings.bodyAction,{data:this.getElementIndexParams()}).then((function(e){t.$body.html(e.data.html),t.$body.has(".sidebar:not(.hidden)").length&&(t.$body.addClass("has-sidebar"),t.supportSidebarToggleView=!0),t.elementIndex=Craft.createElementIndex(t.elementType,t.$body,t.getIndexSettings()),t.$main=t.elementIndex.$main,t.$sidebar=t.elementIndex.$sidebar,t.$content=t.$body.find(".content"),t.updateSidebarView(),t.updateModalBottomPadding(),t.addListener(t.elementIndex.$elements,"doubletap",(function(t,e){e.firstTap.target===e.secondTap.target&&-1!=this.elementIndex.view.elementSelect.getItemIndex(e.firstTap.target)&&this.selectElements()})),t.on("updateSizeAndPosition",(function(){t.elementIndex.handleResize()})),t.updateSelectBtnState()}))},getIndexSettings:function(){var t=this;return Object.assign({context:"modal",modal:this,storageKey:this.settings.storageKey,condition:this.settings.condition,referenceElementId:this.settings.referenceElementId,referenceElementSiteId:this.settings.referenceElementSiteId,criteria:this.settings.criteria,disabledElementIds:this.settings.disabledElementIds,selectable:!0,multiSelect:this.settings.multiSelect,buttonContainer:this.$secondaryButtons,onSelectionChange:function(){t.elementIndex&&t.onSelectionChange()},onSourcePathChange:function(){t.elementIndex&&t.onSelectionChange()},onSelectSource:this.onSelectSource.bind(this),hideSidebar:this.settings.hideSidebar,defaultSiteId:this.settings.defaultSiteId,defaultSource:this.settings.defaultSource,defaultSourcePath:this.settings.defaultSourcePath,showSourcePath:this.settings.showSourcePath},this.settings.indexSettings)}},{defaults:{fullscreen:!1,resizable:!0,storageKey:null,sources:null,condition:null,referenceElementId:null,referenceElementSiteId:null,criteria:null,multiSelect:!1,showSiteMenu:null,disabledElementIds:[],disableElementsOnSelect:!1,hideOnSelect:!0,modalTitle:Craft.t("app","Select element"),showTitle:!1,selectBtnLabel:Craft.t("app","Select"),onCancel:$.noop,onSelect:$.noop,hideSidebar:!1,defaultSiteId:null,defaultSource:null,defaultSourcePath:null,showSourcePath:!0,bodyAction:"element-selector-modals/body",indexSettings:{}}})},8843:function(){Craft.BaseInputGenerator=Garnish.Base.extend({$source:null,$target:null,$form:null,settings:null,listening:null,timeout:null,init:function(t,e,i){this.$source=$(t),this.$target=$(e),this.$form=this.$source.closest("form"),this.setSettings(i),this.startListening()},setNewSource:function(t){var e=this.listening;this.stopListening(),this.$source=$(t),e&&this.startListening()},startListening:function(){this.listening||(this.listening=!0,this.addListener(this.$source,"input","onSourceTextChange"),this.addListener(this.$target,"input","onTargetTextChange"),this.addListener(this.$form,"submit","onFormSubmit"))},stopListening:function(){this.listening&&(this.listening=!1,this.timeout&&clearTimeout(this.timeout),this.removeAllListeners(this.$source),this.removeAllListeners(this.$target),this.removeAllListeners(this.$form))},onSourceTextChange:function(){this.timeout&&clearTimeout(this.timeout),this.timeout=setTimeout(this.updateTarget.bind(this),250)},onTargetTextChange:function(){this.$target.get(0)===document.activeElement&&this.stopListening()},onFormSubmit:function(){this.timeout&&clearTimeout(this.timeout),this.updateTarget()},updateTarget:function(){if(this.$target.is(":visible")){var t=this.$source.val();if(void 0!==t){var e=this.generateTargetValue(t);this.$target.val(e);for(var i=0;i<this.$target.length;i++)this.$target[i].dispatchEvent(new InputEvent("input",{inputType:"insertText"})),this.$target[i].dispatchEvent(new Event("input"));this.$target.is(":focus")&&Craft.selectFullValue(this.$target)}}},generateTargetValue:function(t){return t}})},3778:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CategoryIndex=Craft.BaseElementIndex.extend({editableGroups:null,$newCategoryBtnGroup:null,$newCategoryBtn:null,init:function(t,e,i){this.editableGroups=[],this.on("selectSource",this.updateButton.bind(this)),this.on("selectSite",this.updateButton.bind(this)),this.base(t,e,i)},afterInit:function(){var t=this;this.editableGroups=Craft.editableCategoryGroups.filter((function(e){return!!t.getSourceByKey("group:".concat(e.uid))})),this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultGroupHandle)for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("handle")===defaultGroupHandle)return e.data("key")}return this.base()},updateButton:function(){var e=this;if(this.$source){var i=this.$source.data("handle");if(this.editableGroups.length&&function(){e.$newCategoryBtnGroup&&e.$newCategoryBtnGroup.remove();var s,n=e.editableGroups.find((function(t){return t.handle===i}));e.$newCategoryBtnGroup=$('<div class="btngroup submit" data-wrapper/>');var a="new-category-menu-"+Craft.randomString(10);if(n){var r="index"===e.settings.context?Craft.t("app","New category"):Craft.t("app","New {group} category",{group:n.name}),o="index"===e.settings.context?Craft.t("app","New category in the {group} category group",{group:n.name}):r,l="index"===e.settings.context?"link":null;e.$newCategoryBtn=Craft.ui.createButton({label:r,ariaLabel:o,spinner:!0,role:l}).addClass("submit add icon").appendTo(e.$newCategoryBtnGroup),e.addListener(e.$newCategoryBtn,"click mousedown",(function(t){"index"===e.settings.context&&("click"===t.type&&Garnish.isCtrlKeyPressed(t)||"mousedown"===t.type&&1===t.originalEvent.button)?window.open(Craft.getUrl("categories/".concat(n.handle,"/new"))):"click"===t.type&&e._createCategory(n.id)})),e.editableGroups.length>1&&(s=$("<button/>",{type:"button",class:"btn submit menubtn btngroup-btn-last","aria-controls":a,"data-disclosure-trigger":"","aria-label":Craft.t("app","New category, choose a category group")}).appendTo(e.$newCategoryBtnGroup))}else e.$newCategoryBtn=s=Craft.ui.createButton({label:Craft.t("app","New category"),ariaLabel:Craft.t("app","New category, choose a category group"),spinner:!0}).addClass("submit add icon menubtn btngroup-btn-last").attr("aria-controls",a).attr("data-disclosure-trigger","").appendTo(e.$newCategoryBtnGroup);if(e.addButton(e.$newCategoryBtnGroup),s){var h,d=$("<div/>",{id:a,class:"menu menu--disclosure"}).appendTo(e.$newCategoryBtnGroup),c=$("<ul/>").appendTo(d),u=function(e,i){var s="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!s){if(Array.isArray(e)||(s=function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(e))||i&&e&&"number"==typeof e.length){s&&(e=s);var n=0,a=function(){};return{s:a,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){s=s.call(e)},n:function(){var t=s.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==s.return||s.return()}finally{if(l)throw r}}}}(e.editableGroups);try{var p=function(){var t=h.value,i="index"===e.settings.context?"link":"button";if("index"===e.settings.context||t!==n){var a=$("<li/>").appendTo(c),r=$("<a/>",{role:"button"===i?"button":null,href:"#",type:"button"===i?"button":null,text:Craft.t("app","New {group} category",{group:t.name})}).appendTo(a);e.addListener(r,"click",(function(){s.data("trigger").hide(),e._createCategory(t.id)})),"button"===i&&e.addListener(r,"keydown",(function(i){i.keyCode===Garnish.SPACE_KEY&&(i.preventDefault(),s.data("trigger").hide(),e._createCategory(t.id))}))}};for(u.s();!(h=u.n()).done;)p()}catch(t){u.e(t)}finally{u.f()}new Garnish.DisclosureMenu(s)}}(),"index"===this.settings.context){var s="categories";i&&(s+="/"+i),Craft.setPath(s)}}},_createCategory:function(t){var e=this;if(this.$newCategoryBtn.hasClass("loading"))console.warn("New category creation already in progress.");else{var i=this.editableGroups.find((function(e){return e.id===t}));if(!i)throw"Invalid category group ID: ".concat(t);this.$newCategoryBtn.addClass("loading"),Craft.sendActionRequest("POST","elements/create",{data:{elementType:this.elementType,siteId:this.siteId,groupId:t}}).then((function(t){"index"===e.settings.context?document.location.href=Craft.getUrl(t.data.cpEditUrl,{fresh:1}):Craft.createElementEditor(e.elementType,{siteId:e.siteId,elementId:t.data.element.id,draftId:t.data.element.draftId,params:{fresh:1}}).on("submit",(function(){var s="group:".concat(i.uid);e.sourceKey!==s&&e.selectSourceByKey(s),e.clearSearch(),e.selectElementAfterUpdate(t.data.element.id),e.updateElements()}))})).finally((function(){e.$newCategoryBtn.removeClass("loading")}))}}}),Craft.registerElementIndexClass("craft\\elements\\Category",Craft.CategoryIndex)},6617:function(){Craft.CategorySelectInput=Craft.BaseElementSelectInput.extend({setSettings:function(){this.base.apply(this,arguments),this.settings.sortable=!1},getModalSettings:function(){var t=this.base();return t.hideOnSelect=!1,t},getElements:function(){return this.$elementsContainer.find(".element")},onModalSelect:function(t){var e=this;this.modal.disable(),this.modal.disableCancelBtn(),this.modal.disableSelectBtn(),this.modal.showFooterSpinner();for(var i=this.getSelectedElementIds(),s=0;s<t.length;s++)i.push(t[s].id);var n={categoryIds:i,siteId:t[0].siteId,id:this.settings.id,name:this.settings.name,branchLimit:this.settings.branchLimit,selectionLabel:this.settings.selectionLabel},a=function(){e.modal.enable(),e.modal.enableCancelBtn(),e.modal.enableSelectBtn(),e.modal.hideFooterSpinner()};Craft.sendActionRequest("POST","categories/input-html",{data:n}).then((function(i){a();var s=$(i.data.html).children(".elements");e.$elementsContainer.replaceWith(s),e.$elementsContainer=s,e.resetElements();for(var n=[],r=0;r<t.length;r++){var o=t[r],l=e.getElementById(o.id);l&&(e.animateElementIntoPlace(o.$element,l),n.push(o))}e.updateDisabledElementsInModal(),e.modal.hide(),e.onSelectElements(n)})).catch((function(t){t.response,a()}))},removeElement:function(t){var e=t.add(t.parent().siblings("ul").find(".element"));this.removeElements(e);for(var i=0;i<e.length;i++)this._animateCategoryAway(e,i)},_animateCategoryAway:function(t,e){var i,s=this;e===t.length-1&&(i=function(){var e=t.first().parent().parent(),i=e.parent();i[0]===s.$elementsContainer[0]||e.siblings().length?e.remove():i.remove()});var n=function(){s.animateElementAway(t.eq(e),i)};0===e?n():setTimeout(n,100*e)}})},9482:function(){Craft.charts={},Craft.charts.DataTable=Garnish.Base.extend({columns:null,rows:null,init:function(t){var e=t.columns,i=t.rows;i.forEach((function(t){$.each(t,(function(i){var s;switch(e[i].type){case"date":s=d3.timeParse("%Y-%m-%d"),t[i]=s(t[i]);break;case"datetime":s=d3.timeParse("%Y-%m-%d %H:00:00"),t[i]=s(t[i]);break;case"percent":t[i]=t[i]/100;break;case"number":t[i]=+t[i]}}))})),this.columns=e,this.rows=i}}),Craft.charts.Tip=Garnish.Base.extend({$container:null,$tip:null,init:function(t){this.$container=t,this.$tip=$('<div class="tooltip"></div>').appendTo(this.$container),this.hide()},setContent:function(t){this.$tip.html(t)},setPosition:function(t){this.$tip.css("left","".concat(t.left,"px")),this.$tip.css("top","".concat(t.top,"px"))},show:function(){this.$tip.css("display","block")},hide:function(){this.$tip.css("display","none")}}),Craft.charts.BaseChart=Garnish.Base.extend({$container:null,$chart:null,chartBaseClass:"cp-chart",dataTable:null,formatLocale:null,timeFormatLocale:null,orientation:null,svg:null,width:null,height:null,init:function(t,e){var i=this;this.$container=t,this.setSettings(Craft.charts.BaseChart.defaults),this.setSettings(e);var s={formats:window.d3Formats,formatLocaleDefinition:window.d3FormatLocaleDefinition,timeFormatLocaleDefinition:window.d3TimeFormatLocaleDefinition};this.setSettings(s),d3.select(window).on("resize",(function(){i.resize()}))},setSettings:function(t,e){var i=void 0===this.settings?{}:this.settings;this.settings=$.extend(!0,{},i,e,t)},draw:function(t,e){this.setSettings(e),this.dataTable=t,this.formatLocale=d3.formatLocale(this.settings.formatLocaleDefinition),this.timeFormatLocale=d3.timeFormatLocale(this.settings.timeFormatLocaleDefinition),this.orientation=this.settings.orientation,this.$chart&&this.$chart.remove();var i=this.chartBaseClass;this.settings.chartClass&&(i+=" "+this.settings.chartClass),this.$chart=$('<div class="'.concat(i,'" />')).appendTo(this.$container)},resize:function(){this.draw(this.dataTable,this.settings)},onAfterDrawTicks:function(){$(".tick",this.$chart).each((function(t,e){var i=$("text",e);i.clone().appendTo(e),i.attr("stroke","#ffffff"),i.attr("stroke-width",3)}))}},{defaults:{formatLocaleDefinition:null,timeFormatLocaleDefinition:null,formats:{numberFormat:",.2f",percentFormat:",.2%",currencyFormat:"$,.2f",shortDateFormats:{day:"%-m/%-d",month:"%-m/%y",year:"%Y"}},margin:{top:0,right:0,bottom:0,left:0},chartClass:null,colors:["#0594D1","#DE3800","#FF9A00","#009802","#9B009B"]}}),Craft.charts.Area=Craft.charts.BaseChart.extend({tip:null,drawingArea:null,init:function(t,e){this.base(t,Craft.charts.Area.defaults),this.setSettings(e)},draw:function(t,e){this.base(t,e),this.tip&&(this.tip=null);var i=this.getChartMargin();this.width=this.$chart.width()-i.left-i.right,this.height=this.$chart.height()-i.top-i.bottom;var s={width:this.width+(i.left+i.right),height:this.height+(i.top+i.bottom),translateX:"rtl"!==this.orientation?i.left:i.right,translateY:i.top};this.svg=d3.select(this.$chart.get(0)).append("svg").attr("width",s.width).attr("height",s.height),this.drawingArea=this.svg.append("g").attr("transform","translate(".concat(s.translateX,",").concat(s.translateY,")")),this.drawTicks(),this.drawAxes(),this.drawChart(),this.drawTipTriggers()},drawTicks:function(){var t=this.getX(!0),e=d3.axisBottom(t).tickFormat(this.getXFormatter()).ticks(3);this.drawingArea.append("g").attr("class","x ticks-axis").attr("transform","translate(0, ".concat(this.height,")")).call(e);var i,s=this.getY();"rtl"!==this.orientation?(i=d3.axisLeft(s).tickFormat(this.getYFormatter()).tickValues(this.getYTickValues()).ticks(2),this.drawingArea.append("g").attr("class","y ticks-axis").call(i)):(i=d3.axisRight(s).tickFormat(this.getYFormatter()).tickValues(this.getYTickValues()).ticks(2),this.drawingArea.append("g").attr("class","y ticks-axis").attr("transform","translate(".concat(this.width,",0)")).call(i)),this.onAfterDrawTicks()},drawAxes:function(){if(this.settings.xAxis.showAxis){var t=this.getX(),e=d3.axisBottom(t).ticks(0).tickSizeOuter(0);this.drawingArea.append("g").attr("class","x axis").attr("transform","translate(0, ".concat(this.height,")")).call(e)}if(this.settings.yAxis.showAxis){var i,s=this.getY();"rtl"===this.orientation?(i=d3.axisLeft(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(".concat(this.width-0,", 0)")).call(i)):(i=d3.axisRight(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(".concat(0,", 0)")).call(i))}},drawChart:function(){var t=this.getX(!0),e=this.getY();if(this.settings.xAxis.gridlines){var i=d3.axisBottom(t);this.drawingArea.append("g").attr("class","x grid-line").attr("transform","translate(0,".concat(this.height,")")).call(i.tickSize(-this.height,0,0).tickFormat(""))}if(this.settings.yAxis.gridlines){var s=d3.axisLeft(e);this.drawingArea.append("g").attr("class","y grid-line").attr("transform","translate(0 , 0)").call(s.tickSize(-this.width,0).tickFormat("").tickValues(this.getYTickValues()).ticks(2))}var n=d3.line().x((function(e){return t(e[0])})).y((function(t){return e(t[1])}));this.drawingArea.append("g").attr("class","chart-line").append("path").datum(this.dataTable.rows).style("fill","none").style("stroke",this.settings.colors[0]).style("stroke-width","3px").attr("d",n);var a=d3.area().x((function(e){return t(e[0])})).y0(this.height).y1((function(t){return e(t[1])}));this.drawingArea.append("g").attr("class","chart-area").append("path").datum(this.dataTable.rows).style("fill",this.settings.colors[0]).style("fill-opacity","0.3").attr("d",a),this.settings.plots&&this.drawingArea.append("g").attr("class","plots").selectAll("circle").data(this.dataTable.rows).enter().append("circle").style("fill",this.settings.colors[0]).attr("class",(function(t,e){return"plot plot-".concat(e)})).attr("r",4).attr("cx",(function(e){return t(e[0])})).attr("cy",(function(t){return e(t[1])}))},drawTipTriggers:function(){var t=this;if(this.settings.tips){this.tip||(this.tip=new Craft.charts.Tip(this.$chart));var e=this.getChartMargin(),i=(this.drawingArea.select(".x path.domain").node().getTotalLength()-e.left-e.right-12)/(this.dataTable.rows.length-1),s=Math.max(0,i),n=this.getX(!0),a=this.getY();this.drawingArea.append("g").attr("class","tip-triggers").selectAll("rect").data(this.dataTable.rows).enter().append("rect").attr("class","tip-trigger").style("fill","transparent").style("fill-opacity","1").attr("width",s).attr("height",this.height).attr("x",(function(t){return n(t[0])-s/2})).on("mouseover",(function(e,i){t.drawingArea.select(".plot-"+i).attr("r",5);var s=$("<div />"),r=$('<div class="x-value" />').appendTo(s),o=$('<div class="y-value" />').appendTo(s);r.html(t.getXFormatter()(e[0])),o.html(t.getYFormatter()(e[1]));var l=s.get(0);t.tip.setContent(l);var h,d=t.getChartMargin(),c=24,u=a(e[1])+c;"rtl"!==t.orientation?(h=n(e[0])+d.left+c,t.$chart.offset().left+h+t.tip.$tip.width()>t.$chart.offset().left+t.$chart.width()-c&&(h=n(e[0])-(t.tip.$tip.width()+c))):h=n(e[0])-(t.tip.$tip.width()+d.left+c),h<0&&(h=n(e[0])+d.left+c);var p={top:u,left:h};t.tip.setPosition(p),t.tip.show()})).on("mouseout",(function(e,i){t.drawingArea.select(".plot-"+i).attr("r",4),t.tip.hide()}))}},getChartMargin:function(){var t=this,e=this.settings.margin,i=this.getYTickValues(),s=0;return $.each(i,(function(e,i){var n=8*t.getYFormatter()(i).length;n>s&&(s=n)})),s+=10,e.left=s,e},getX:function(t){var e=d3.min(this.dataTable.rows,(function(t){return t[0]})),i=d3.max(this.dataTable.rows,(function(t){return t[0]})),s=[e,i];"rtl"===this.orientation&&(s=[i,e]);var n=0,a=0;t&&(n=0,a=0);var r=d3.scaleTime().range([n,this.width-a]);return r.domain(s),r},getY:function(){var t=[0,this.getYMaxValue()],e=d3.scaleLinear().range([this.height,0]);return e.domain(t),e},getXFormatter:function(){return this.settings.xAxis.formatter!==$.noop?this.settings.xAxis.formatter(this):Craft.charts.utils.getTimeFormatter(this.timeFormatLocale,this.settings)},getYFormatter:function(){return this.settings.yAxis.formatter!==$.noop?this.settings.yAxis.formatter(this):Craft.charts.utils.getNumberFormatter(this.formatLocale,this.dataTable.columns[1].type,this.settings)},getYMaxValue:function(){return d3.max(this.dataTable.rows,(function(t){return t[1]}))},getYTickValues:function(){var t=this.getYMaxValue();return t>1?[t/2,t]:[0,t]}},{defaults:{chartClass:"area",margin:{top:25,right:5,bottom:25,left:0},plots:!0,tips:!0,xAxis:{gridlines:!1,showAxis:!0,formatter:$.noop},yAxis:{gridlines:!0,showAxis:!1,formatter:$.noop}}}),Craft.charts.utils={getDuration:function(t){var e=parseInt(t,10),i={hours:Math.floor(e/3600),minutes:Math.floor((e-3600*i.hours)/60),seconds:e-3600*i.hours-60*i.minutes};return i.hours<10&&(i.hours="0".concat(i.hours)),i.minutes<10&&(i.minutes="0".concat(i.minutes)),i.seconds<10&&(i.seconds="0".concat(i.seconds)),"".concat(i.hours,":").concat(i.minutes,":").concat(i.seconds)},getTimeFormatter:function(t,e){switch(e.dataScale){case"year":return t.format("%Y");case"month":return t.format(e.formats.shortDateFormats.month);case"hour":return t.format("".concat(e.formats.shortDateFormats.day," %H:00:00"));default:return t.format(e.formats.shortDateFormats.day)}},getNumberFormatter:function(t,e,i){switch(e){case"currency":return t.format(i.formats.currencyFormat);case"percent":return t.format(i.formats.percentFormat);case"time":return Craft.charts.utils.getDuration;case"number":return t.format(i.formats.numberFormat)}}}},3352:function(){Craft.ColorInput=Garnish.Base.extend({$container:null,$input:null,$colorContainer:null,$colorPreview:null,$colorInput:null,init:function(t){this.$container=$(t),this.$input=this.$container.find(".color-input"),this.$colorContainer=this.$container.children(".color"),this.$colorPreview=this.$colorContainer.children(".color-preview"),this.createColorInput(),this.handleTextChange(),this.addListener(this.$input,"input","handleTextChange")},createColorInput:function(){var t=document.createElement("input");t.setAttribute("type","color"),"color"===t.type&&(this.$colorContainer.removeClass("static"),this.$colorInput=$(t).addClass("color-preview-input").attr({"aria-controls":this.$input.attr("id"),"aria-label":Craft.t("app","Color picker")}).appendTo(this.$colorPreview),this.addListener(this.$colorInput,"click",(function(t){t.stopPropagation()})),this.addListener(this.$colorContainer,"click",(function(){this.$colorInput.trigger("click")})),this.addListener(this.$colorInput,"input","updateColor"))},updateColor:function(){this.$input.val(this.$colorInput.val()),this.handleTextChange()},handleTextChange:function(){var t=this.$input.val();t!==(t=Craft.trim(t))&&this.$input.val(t),t.length&&"#"===t[0]&&(t=t.substring(1),this.$input.val(t)),t.length?(3===t.length&&(t=t[0].repeat(2)+t[1].repeat(2)+t[2].repeat(2)),t.match(/^[0-9a-f]{6}$/i)?(this.$colorPreview.css("background-color","#".concat(t)),this.$colorInput&&this.$colorInput.val("#".concat(t))):this.$colorPreview.css("background-color","")):this.$colorPreview.css("background-color","")}},{_browserSupportsColorInputs:null,doesBrowserSupportColorInputs:function(){return Craft.ColorInput._browserSupportsColorInputs,Craft.ColorInput._browserSupportsColorInputs}})},8167:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function e(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Craft.CpScreenSlideout=Craft.Slideout.extend({action:null,namespace:null,showingLoadSpinner:!1,hasTabs:!1,hasCpLink:!1,hasSidebar:!1,$header:null,$toolbar:null,$tabContainer:null,$loadSpinner:null,$editLink:null,$sidebarBtn:null,$body:null,$content:null,$sidebar:null,$footer:null,$noticeContainer:null,$cancelBtn:null,$saveBtn:null,tabManager:null,showingSidebar:!1,cancelToken:null,ignoreFailedRequest:!1,fieldsWithErrors:null,init:function(t,e){var i=this;this.action=t,this.setSettings(e,Craft.CpScreenSlideout.defaults),this.fieldsWithErrors=[],this.$header=$("<header/>",{class:"pane-header"}),this.$toolbar=$("<div/>",{class:"so-toolbar"}).appendTo(this.$header),this.$tabContainer=$("<div/>",{class:"pane-tabs"}).appendTo(this.$toolbar),this.$loadSpinner=$("<div/>",{class:"spinner",title:Craft.t("app","Loading"),"aria-label":Craft.t("app","Loading")}).appendTo(this.$toolbar),this.$editLink=$("<a/>",{target:"_blank",class:"btn header-btn hidden",title:Craft.t("app","Open the full edit page in a new tab"),"aria-label":Craft.t("app","Open the full edit page in a new tab"),"data-icon":"external"}).appendTo(this.$toolbar),this.$sidebarBtn=$("<button/>",{type:"button",class:"btn header-btn hidden sidebar-btn",title:Craft.t("app","Show sidebar"),"aria-label":Craft.t("app","Show sidebar"),"data-icon":"sidebar-".concat(Garnish.ltr?"right":"left"),"aria-expanded":"false"}).appendTo(this.$toolbar),this.addListener(this.$sidebarBtn,"click",(function(t){t.preventDefault(),i.showingSidebar?i.hideSidebar():i.showSidebar()})),this.$body=$("<div/>",{class:"so-body"}),this.$content=$("<div/>",{class:"so-content"}).appendTo(this.$body),this.$sidebar=$("<div/>",{class:"so-sidebar details hidden"}).appendTo(this.$body),this.$footer=$("<div/>",{class:"so-footer hidden"}),this.$noticeContainer=$("<div/>",{class:"so-notice"}).appendTo(this.$footer),$("<div/>",{class:"flex-grow"}).appendTo(this.$footer);var s=$("<div/>",{class:"flex flex-nowrap"}).appendTo(this.$footer);this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(s),this.$saveBtn=Craft.ui.createSubmitButton({label:Craft.t("app","Save"),spinner:!0}).appendTo(s);var n=this.$header.add(this.$body).add(this.$footer);this.base(n,{containerElement:"form",containerAttributes:{id:"cp-screen-".concat(Math.floor(1e8*Math.random())),action:"",method:"post",novalidate:"",class:"cp-screen"},closeOnEsc:!1,closeOnShadeClick:!1}),this.$container.data("cpScreen",this),this.on("beforeClose",(function(){i.hideSidebar()})),Garnish.uiLayerManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0},(function(t){i.handleSubmit(t)})),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){i.closeMeMaybe()})),this.addListener(this.$cancelBtn,"click",(function(){i.closeMeMaybe()})),this.addListener(this.$shade,"click",(function(){i.closeMeMaybe()})),this.addListener(this.$container,"click",(function(t){var e=$(event.target);!i.showingSidebar||e.closest(i.$sidebarBtn).length||e.closest(i.$sidebar).length||i.hideSidebar()})),this.addListener(this.$container,"submit","handleSubmit"),this.load()},load:function(t,e){var i=this;return new Promise((function(t,s){i.trigger("beforeLoad"),i.showLoadSpinner(),i.cancelToken&&(i.ignoreFailedRequest=!0,i.cancelToken.cancel()),i.cancelToken=axios.CancelToken.source(),Craft.sendActionRequest("GET",i.action,$.extend({params:Object.assign({},i.getParams(),i.settings.params),cancelToken:i.cancelToken.token,headers:{"X-Craft-Container-Id":i.$container.attr("id")}},i.settings.requestOptions)).then((function(n){i.update(n.data).then((function(){!1!==e&&(i.$container.data("delta-names",n.data.deltaNames),i.$container.data("initial-delta-values",n.data.initialDeltaValues),i.$container.data("initialSerializedValue",i.$container.serialize())),t()})).catch((function(t){s(t)}))})).catch((function(t){i.ignoreFailedRequest||(Craft.cp.displayError(),s(t)),i.ignoreFailedRequest=!1})).finally((function(){i.hideLoadSpinner(),i.cancelToken=null}))}))},getParams:function(){return{}},updateHeaderVisibility:function(){var t=this.settings.showHeader||this.hasTabs||this.hasCpLink||this.showingLoadSpinner;t||this.hasSidebar?this.$header.removeClass("hidden"):this.$header.addClass("hidden"),t?this.$header.addClass("so-visible"):this.$header.removeClass("so-visible")},showLoadSpinner:function(){this.$loadSpinner.removeClass("hidden"),this.showingLoadSpinner=!0,this.updateHeaderVisibility()},hideLoadSpinner:function(){this.$loadSpinner.addClass("hidden"),this.showingLoadSpinner=!1,this.updateHeaderVisibility()},update:function(t){var e=this;return new Promise((function(i){e.namespace=t.namespace,e.$content.html(t.content),t.submitButtonLabel&&e.$saveBtn.text(t.submitButtonLabel),e.updateTabs(t.tabs),t.formAttributes&&Craft.setElementAttributes(e.$container,t.formAttributes),t.editUrl?(e.$editLink.removeClass("hidden").attr("href",t.editUrl),e.hasCpLink=!0):(e.$editLink.addClass("hidden"),e.hasCpLink=!1),t.sidebar?(e.$container.addClass("has-sidebar"),e.$sidebarBtn.removeClass("hidden"),e.$sidebar.html(t.sidebar),e.$sidebar.find("a").each((function(){this.hostname.length&&void 0===$(this).attr("target")&&$(this).attr("target","_blank")})),e.hasSidebar=!0):(e.$container.removeClass("has-sidebar"),e.$sidebarBtn.addClass("hidden"),e.$sidebar.addClass("hidden").html(""),e.hasSidebar=!1),t.notice?e.$noticeContainer.html(t.notice):e.$noticeContainer.empty(),e.updateHeaderVisibility(),e.$footer.removeClass("hidden"),Garnish.requestAnimationFrame((function(){Craft.appendHeadHtml(t.headHtml),Craft.appendBodyHtml(t.bodyHtml),Craft.initUiElements(e.$content),Craft.cp.elementThumbLoader.load($(e.$content)),t.sidebar&&(Craft.initUiElements(e.$sidebar),Craft.cp.elementThumbLoader.load(e.$sidebar)),Garnish.isMobileBrowser()||Craft.setFocusWithin(e.$content),i(),e.trigger("load")}))}))},updateTabs:function(t){var e=this;if(this.tabManager&&(this.tabManager.destroy(),this.tabManager=null,this.$tabContainer.html("")),this.hasTabs=!!t,this.hasTabs){var i=$(t);this.$tabContainer.replaceWith(i),this.$tabContainer=i,this.tabManager=new Craft.Tabs(this.$tabContainer),this.tabManager.on("deselectTab",(function(t){$(t.$tab.attr("href")).addClass("hidden")})),this.tabManager.on("selectTab",(function(t){$(t.$tab.attr("href")).removeClass("hidden"),Garnish.$win.trigger("resize"),e.$body.trigger("scroll")}))}},showSidebar:function(){var t=this;this.showingSidebar||(this.$body.scrollTop(0).addClass("no-scroll"),this.$sidebar.off("transitionend.so").css(this._closedSidebarStyles()).removeClass("hidden"),this.$sidebar[0].offsetWidth,this.$sidebar.css(this._openedSidebarStyles()),Garnish.isMobileBrowser()||this.$sidebar.one("transitionend.so",(function(){Craft.setFocusWithin(t.$sidebar)})),Craft.trapFocusWithin(this.$sidebar),this.$sidebarBtn.addClass("active").attr({"aria-expanded":"true"}),Garnish.$win.trigger("resize"),this.$sidebar.trigger("scroll"),Garnish.uiLayerManager.addLayer(),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.hideSidebar()})),this.showingSidebar=!0)},hideSidebar:function(){var t=this;this.showingSidebar&&(this.$body.removeClass("no-scroll"),this.$sidebar.off("transitionend.so").css(this._closedSidebarStyles()).one("transitionend.so",(function(){t.$sidebar.addClass("hidden"),t.$sidebarBtn.focus()})),this.$sidebarBtn.removeClass("active").attr({"aria-expanded":"false"}),Garnish.uiLayerManager.removeLayer(),this.showingSidebar=!1)},_openedSidebarStyles:function(){return e({},Garnish.ltr?"right":"left","0")},_closedSidebarStyles:function(){return e({},Garnish.ltr?"right":"left","-350px")},showSubmitSpinner:function(){this.$saveBtn.addClass("loading")},hideSubmitSpinner:function(){this.$saveBtn.removeClass("loading")},handleSubmit:function(t){t.preventDefault(),this.submit()},submit:function(){var t=this;this.showSubmitSpinner();var e=Craft.findDeltaData(this.$container.data("initialSerializedValue"),this.$container.serialize(),this.$container.data("delta-names"),null,this.$container.data("initial-delta-values"));Craft.sendActionRequest("POST",null,{data:e,headers:{"X-Craft-Namespace":this.namespace}}).then((function(e){t.handleSubmitResponse(e)})).catch((function(e){t.handleSubmitError(e)})).finally((function(){t.hideSubmitSpinner()}))},handleSubmitResponse:function(t){this.clearErrors();var e=t.data||{};e.message&&Craft.cp.displaySuccess(e.message,e.notificationSettings),this.trigger("submit",{response:t,data:e.modelName&&e[e.modelName]||{}}),this.settings.closeOnSubmit&&this.close()},handleSubmitError:function(t){if(!t.isAxiosError||!t.response||400===!t.response.status)throw Craft.cp.displayError(),t;var e=t.response.data||{};Craft.cp.displayError(e.message),e.errors&&this.showErrors(e.errors)},showErrors:function(e){var i=this;this.clearErrors(),Object.entries(e).forEach((function(e){var s,n,a=(n=2,function(t){if(Array.isArray(t))return t}(s=e)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(s,n)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(s,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),r=a[0],o=a[1],l=i.$container.find('[data-attribute="'.concat(r,'"]'));l&&(Craft.ui.addErrorsToField(l,o),i.fieldsWithErrors.push(l))}))},clearErrors:function(){this.fieldsWithErrors.forEach((function(t){Craft.ui.clearErrorsFromField(t)}))},isDirty:function(){return void 0!==this.$container.data("initialSerializedValue")&&this.$container.serialize()!==this.$container.data("initialSerializedValue")},closeMeMaybe:function(){this.isOpen&&(this.isDirty()&&!confirm(Craft.t("app","Are you sure you want to close this screen? Any changes will be lost."))||this.close())},close:function(){this.base(),this.cancelToken&&(this.ignoreFailedRequest=!0,this.cancelToken.cancel())}},{defaults:{params:{},requestOptions:{},showHeader:null,closeOnSubmit:!0}})},587:function(){function t(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=s(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var n=0,a=function(){};return{s:a,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}((function(t){throw t})),f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return o=t.done,t},e:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}((function(t){l=!0,r=t})),f:function(){try{o||null==i.return||i.return()}finally{if(l)throw r}}}}function i(t){return function(t){if(Array.isArray(t))return n(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||s(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(t,e){if(t){if("string"==typeof t)return n(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?n(t,e):void 0}}function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function a(t){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a(t)}var r=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi;if(jQuery.htmlPrefilter=function(t){return t.replace(r,"<$1></$2>")},$.extend(Craft,{navHeight:48,index:function(t,e){if(!$.isArray(t))throw"The first argument passed to Craft.index() must be an array.";return t.reduce((function(t,i,s){return t["string"==typeof e?i[e]:e(i,s)]=i,t}),{})},group:function(t,e){if(!$.isArray(t))throw"The first argument passed to Craft.group() must be an array.";var i={};return t.reduce((function(t,s,n){var a="string"==typeof e?s[e]:e(s,n);return i.hasOwnProperty(a)||(i[a]=[[],a],t.push(i[a])),i[a][0].push(s),t}),[])},t:function(t,e,i){return void 0!==Craft.translations[t]&&void 0!==Craft.translations[t][e]&&(e=Craft.translations[t][e]),i?this.formatMessage(e,i):e},formatMessage:function(t,e){var i;if(!1===(i=this._tokenizePattern(t)))throw"Message pattern is invalid.";for(var s=0;s<i.length;s++){var n=i[s];if("object"===a(n)&&!1===(i[s]=this._parseToken(n,e)))throw"Message pattern is invalid."}return i.join("")},_tokenizePattern:function(t){var e,s,n=1,a=i(t);if(-1===(e=s=a.indexOf("{")))return[t];for(var r=[a.slice(0,s).join("")];;){var o=a.indexOf("{",s+1),l=a.indexOf("}",s+1);if(-1===o&&(o=!1),-1===l&&(l=!1),!1===o&&!1===l)break;if(!1===o&&(o=a.length),l>o?(n++,s=o):(n--,s=l),0===n&&(r.push(a.slice(e+1,s).join("").split(",",3)),e=s+1,r.push(a.slice(e,o).join("")),e=o),0!==n&&(!1===o||!1===l))break}return 0===n&&r},_parseToken:function(t,e){var s=this,n=Craft.trim(t[0]);if(void 0===e[n])return"{".concat(t.join(","),"}");var r=e[n],o=void 0!==t[1]?Craft.trim(t[1]):"none";switch(o){case"number":return function(){var e=void 0!==t[2]?Craft.trim(t[2]):null;if(null!==e&&"integer"!==e)throw"Message format 'number' is only supported for integer values.";var i,s=Craft.formatNumber(r);return null===e&&-1!==(i="".concat(r).indexOf("."))&&(s+=".".concat(r.substring(i+1))),s}();case"none":return r;case"select":return function(){if(void 0===t[2])return!1;for(var i=s._tokenizePattern(t[2]),n=i.length,a=!1,o=0;o+1<n;o++){if(Garnish.isArray(i[o])||!Garnish.isArray(i[o+1]))return!1;var l=Craft.trim(i[o++]);(!1===a&&"other"===l||l==r)&&(a=i[o].join(","))}return!1!==a&&s.formatMessage(a,e)}();case"plural":return function(){if(void 0===t[2])return!1;for(var n=s._tokenizePattern(t[2]),o=n.length,l=!1,h=0,d=0;d+1<o;d++){if("object"===a(n[d])||"object"!==a(n[d+1]))return!1;var c=Craft.trim(n[d++]),u=i(c);if(1===d&&"offset:"===c.substring(0,7)){var p=i(c.replace(/[\n\r\t]/g," ")).indexOf(" ",7);if(-1===p)throw"Message pattern is invalid.";h=parseInt(Craft.trim(u.slice(7,p).join(""))),c=Craft.trim(u.slice(p+1,p+1+u.length).join(""))}(!1===l&&"other"===c||"="===c[0]&&parseInt(u.slice(1,1+u.length).join(""))===r||"one"===c&&r-h==1)&&(l=("string"==typeof n[d]?[n[d]]:n[d]).map((function(t){return t.replace("#",r-h)})).join(","))}return!1!==l&&s.formatMessage(l,e)}();default:throw"Message format '".concat(o,"' is not supported.")}},formatDate:function(t){return"object"!==a(t)&&(t=new Date(t)),$.datepicker.formatDate(Craft.datepickerOptions.dateFormat,t)},formatNumber:function(t,e){return void 0===e&&(e=",.0f"),d3.formatLocale(d3FormatLocaleDefinition).format(e)(t)},shortcutText:function(t,e,i){return"Mac"===Craft.clientOs?(i?"⌥":"")+(e?"⇧":"")+"⌘"+t:"Ctrl+"+(i?"Alt+":"")+(e?"Shift+":"")+t},escapeHtml:function(t){return $("<div/>").text(t).html()},escapeRegex:function(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},getText:function(t){return $("<div/>").html(t).text()},encodeUriComponent:function(t){t=encodeURIComponent(t);var e={"!":"%21","*":"%2A","'":"%27","(":"%28",")":"%29"};for(var i in e){var s=new RegExp("\\"+i,"g");t=t.replace(s,e[i])}return t},selectFullValue:function(t){var e=$(t),i=e.val();if(void 0!==e[0].setSelectionRange){var s=2*i.length;e[0].setSelectionRange(0,s)}else e.val(i)},formatInputId:function(t){return this.rtrim(t.replace(/[^\w\-]+/g,"-"),"-")},getUrl:function(t,e,i){"string"!=typeof t&&(t="");var s=null;if($.isPlainObject(e))void 0!==e["#"]&&(s=e["#"],delete e["#"]);else if("string"==typeof e){var n=e.indexOf("#");-1!==n&&(s=e.substring(n+1),e=e.substring(0,n)),e=Object.fromEntries(new URLSearchParams(e).entries())}else e={};var a=t.indexOf("#");-1!==a&&(s||(s=t.substring(a+1)),t=t.substring(0,a));var r,o=t.indexOf("?");if(-1!==o&&(e=$.extend(Object.fromEntries(new URLSearchParams(t.substring(o+1)).entries()),e),t=t.substring(0,o)),-1!==t.search("://")||"/"===t[0])return t+($.isEmptyObject(e)?"":"?".concat($.param(e)))+(s?"#".concat(s):"");if(t=Craft.trim(t,"/"),i){if(r=i,t&&Craft.pathParam){var l=r.match(new RegExp("[&?]"+Craft.escapeRegex(Craft.pathParam)+"=[^&]+"));l&&(r=r.replace(l[0],Craft.rtrim(l[0],"/")+"/"+t),t="")}}else r=Craft.baseUrl;return-1!==(o=r.indexOf("?"))&&(e=$.extend(Object.fromEntries(new URLSearchParams(r.substring(o+1)).entries()),e),r=r.substring(0,o)),!Craft.omitScriptNameInUrls&&t&&(Craft.usePathInfo||!Craft.pathParam?-1===r.search(Craft.scriptName)&&(r=Craft.rtrim(r,"/")+"/"+Craft.scriptName):(void 0!==e[Craft.pathParam]&&(t=Craft.rtrim(e[Craft.pathParam])+(t?"/"+t:"")),e[Craft.pathParam]=t,t=null)),t&&(r=Craft.rtrim(r,"/")+"/"+t),$.isEmptyObject(e)||(r+="?".concat($.param(e))),s&&(r+="#".concat(s)),r},getCpUrl:function(t,e){return this.getUrl(t,e,Craft.baseCpUrl)},getSiteUrl:function(t,e){return this.getUrl(t,e,Craft.baseSiteUrl)},getActionUrl:function(t,e){return Craft.getUrl(t,e,Craft.actionUrl)},redirectTo:function(t){document.location.href=this.getUrl(t)},setUrl:function(t){"undefined"!=typeof history&&(t.match(/#/)||(t+=document.location.hash),history.replaceState({},"",t))},setPath:function(t){this.path=t,this.setUrl(Craft.getUrl(t,document.location.search))},setQueryParam:function(t,e){var i=document.location.origin+document.location.pathname,s=this.getQueryParams();null!=e&&!1!==e?s[t]=e:delete s[t],this.setUrl(Craft.getUrl(i,s))},getPageUrl:function(t){var e=document.location.origin+document.location.pathname;e=Craft.rtrim(e,"/");var i=document.location.search?document.location.search.substring(1):"";if("?"===Craft.pageTrigger[0]){var s=Craft.pageTrigger.substring(1);if(document.location.search){var n=Object.fromEntries(new URLSearchParams(i).entries());delete n[s],i=$.param(n)}1!==t&&(i+=(""!==i?"&":"")+"".concat(s,"=").concat(t))}else e=e.replace(new RegExp("/"+Craft.escapeRegex(Craft.pageTrigger)+"\\d+$"),""),1!==t&&(e+="/".concat(Craft.pageTrigger).concat(t));return e+(i?"?".concat(i):"")+document.location.hash},getCsrfInput:function(){return Craft.csrfTokenName?'<input type="hidden" name="'+Craft.csrfTokenName+'" value="'+Craft.csrfTokenValue+'"/>':""},postActionRequest:function(t,e,i,s){"function"==typeof e&&(s=i,i=e,e={}),(s=s||{}).contentType&&s.contentType.match(/\bjson\b/)&&("object"===a(e)&&(e=JSON.stringify(e)),s.contentType="application/json; charset=utf-8");var n=$.ajax($.extend({url:Craft.getActionUrl(t),type:"POST",dataType:"json",headers:this._actionHeaders(),data:e,success:i,error:function(t,e,s){4===t.readyState&&(400!==t.status&&(void 0!==Craft.cp?Craft.cp.displayError():alert(Craft.t("app","A server error occurred."))),i&&i(400===t.status?t.responseJSON:null,e,t))}},s));return"function"==typeof s.send&&s.send(n),n},_actionHeaders:function(){var t={"X-Registered-Asset-Bundles":Object.keys(Craft.registeredAssetBundles).join(","),"X-Registered-Js-Files":Object.keys(Craft.registeredJsFiles).join(",")};return Craft.csrfTokenValue&&(t["X-CSRF-Token"]=Craft.csrfTokenValue),t},sendActionRequest:function(t,e){var i=this,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if($.isPlainObject(e)&&(s=e,e=null),"POST"===t.toUpperCase()&&e&&s.data)if("string"==typeof s.data){var n=s&&s.headers&&s.headers["X-Craft-Namespace"],a=this.namespaceInputName("action",n);s.data+="&".concat(a,"=").concat(e)}else delete s.data.action;return new Promise((function(n,a){(s=s?$.extend({},s):{}).method=t,s.url=e?Craft.getActionUrl(e):Craft.getCpUrl(),s.headers=$.extend({"X-Requested-With":"XMLHttpRequest"},s.headers||{},i._actionHeaders()),s.params=$.extend({},s.params||{},{v:(new Date).getTime()}),axios.request(s).then(n).catch(a)}))},sendApiRequest:function(t,e,i){var s=this;return new Promise((function(n,a){var r=(i=i?$.extend({},i):{}).cancelToken||null;s._getApiHeaders(r).then((function(o){i.method=t,i.baseURL=Craft.baseApiUrl,i.url=e,i.headers=$.extend(o,i.headers||{}),i.params=$.extend(Craft.apiParams||{},i.params||{},{v:(new Date).getTime()}),s._apiHeaders||(i.params.processCraftHeaders=1),Craft.httpProxy&&(i.proxy=Craft.httpProxy),axios.request(i).then((function(t){s._processApiHeaders(t.headers,r).then((function(){n(t.data)})).catch(a)})).catch(a)})).catch(a)}))},_loadingApiHeaders:!1,_apiHeaders:null,_apiHeaderWaitlist:[],_getApiHeaders:function(t){var i=this;return new Promise((function(s,n){i._loadingApiHeaders?i._apiHeaderWaitlist.push([s,n]):i._apiHeaders?s(i._apiHeaders):(i._loadingApiHeaders=!0,i.sendActionRequest("POST","app/api-headers",{cancelToken:t}).then((function(t){i._loadingApiHeaders?s(t.data):n(e)})).catch((function(t){i._rejectApiRequests(n,t)})))}))},_processApiHeaders:function(t,i){var s=this;return new Promise((function(n,a){s._apiHeaders?n():s.sendActionRequest("POST","app/process-api-response-headers",{data:{headers:t},cancelToken:i}).then((function(t){if(s._loadingApiHeaders)for(s._apiHeaders=t.data,s._loadingApiHeaders=!1,n();s._apiHeaderWaitlist.length;)s._apiHeaderWaitlist.shift()[0](s._apiHeaders);else a(e)})).catch((function(t){s._rejectApiRequests(a,t)}))}))},_rejectApiRequests:function(t,e){for(this._loadingApiHeaders=!1,t(e);this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[1](e)},clearCachedApiHeaders:function(){for(this._apiHeaders=null,this._loadingApiHeaders=!1;this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[1]()},downloadFromUrl:function(t,e,i){return new Promise((function(s,n){var r=new XMLHttpRequest;r.open(t,e,!0),"object"===a(i)?(r.setRequestHeader("Content-Type","application/json; charset=UTF-8"),i=JSON.stringify(i)):r.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),r.responseType="blob",r.onload=function(){if(200===r.status){var t=r.getResponseHeader("content-disposition"),e=/"([^"]*)"/.exec(t),i=null!=e&&e[1]?e[1]:"Download",a=r.getResponseHeader("content-type"),o=new Blob([r.response],{type:a}),l=document.createElement("a");l.href=window.URL.createObjectURL(o),l.download=i,document.body.appendChild(l),l.click(),document.body.removeChild(l),s()}else n()},r.send(i)}))},stringToArray:function(t){if("string"!=typeof t)return t;for(var e=t.split(","),i=0;i<e.length;i++)e[i]=$.trim(e[i]);return e},findDeltaData:function(t,e,i,s,n,r){t="string"==typeof t?t:"",e="string"==typeof e?e:"",i=$.isArray(i)?i:[],n=$.isPlainObject(n)?n:{},r=$.isArray(r)?r:[],i.sort((function(t,e){return t.length===e.length?0:t.length>e.length?1:-1}));for(var o=this._groupParamsByDeltaNames(t.split("&"),i,!1,n),l=this._groupParamsByDeltaNames(e.split("&"),i,!0,!1),h=l.__root__,d=0;d<i.length;d++)(Craft.inArray(i[d],r)||"object"===a(l[i[d]])&&("object"!==a(o[i[d]])||JSON.stringify(o[i[d]])!==JSON.stringify(l[i[d]])))&&((h=h.concat(l[i[d]])).push("modifiedDeltaNames[]="+i[d]),s&&s(i[d],l[i[d]]));return h.join("&")},_groupParamsByDeltaNames:function(t,e,i,s){var n={};i&&(n.__root__=[]);var a=function(t){return encodeURIComponent(t).replace("%3D","=")};t=t.map((function(t){return decodeURIComponent(t)}));t:for(var r=0;r<t.length;r++){for(var o=e.length-1;o>=0;o--){var l=t[r].substring(0,e[o].length+1);if(l===e[o]+"="||l===e[o]+"["){void 0===n[e[o]]&&(n[e[o]]=[]),n[e[o]].push(a(t[r]));continue t}}i&&n.__root__.push(a(t[r]))}if(s){var h=function(t,e){return $.isArray(e)||$.isPlainObject(e)?e=$.param(e):"string"==typeof e?e=encodeURIComponent(e):null===e&&(e=""),"".concat(encodeURIComponent(t),"=").concat(e)};for(var d in s)if(s.hasOwnProperty(d))if($.isPlainObject(s[d]))for(var c in n[d]=[],s[d])s[d].hasOwnProperty(c)&&n[d].push(h("".concat(d,"[").concat(c,"]"),s[d][c]));else n[d]=[h(d,s[d])]}return n},expandPostArray:function(t){var e,i={};for(var s in t)if(t.hasOwnProperty(s)){var n,r=t[s],o=s.match(/^(\w+)(\[.*)?/);if(o[2])for(n=o[2].match(/\[[^\[\]]*\]/g),e=0;e<n.length;e++)n[e]=n[e].substring(1,n[e].length-1);else n=[];n.unshift(o[1]);var l=i;for(e=0;e<n.length;e++)e<n.length-1?("object"!==a(l[n[e]])&&(n[e+1]&&parseInt(n[e+1])!=n[e+1]?l[n[e]]={}:l[n[e]]=[]),l=l[n[e]]):(n[e]||(n[e]=l.length),l[n[e]]=r)}return i},createForm:function(t){var e=$("<form/>",{attr:{method:"post",action:"","accept-charset":"UTF-8"}});if("string"==typeof t)for(var i,s=t.split("&"),n=0;n<s.length;n++)i=s[n].split("=",2),$("<input/>",{type:"hidden",name:decodeURIComponent(i[0]),value:decodeURIComponent(i[1]||"")}).appendTo(e);return e},compare:function(t,e,i){if(a(t)!==a(e))return!1;if("object"===a(t)&&null!==t&&null!==e){if(t.length!==e.length)return!1;if(t instanceof Array!=e instanceof Array)return!1;if(!(t instanceof Array))if(void 0===i||!0===i){if(!Craft.compare(Craft.getObjectKeys(t).sort(),Craft.getObjectKeys(e).sort()))return!1}else if(!Craft.compare(Craft.getObjectKeys(t),Craft.getObjectKeys(e)))return!1;for(var s in t)if(t.hasOwnProperty(s)&&!Craft.compare(t[s],e[s]))return!1;return!0}return t===e},getObjectKeys:function(t){var e=[];for(var i in t)t.hasOwnProperty(i)&&e.push(i);return e},escapeChars:function(t){Garnish.isArray(t)||(t=t.split());for(var e="",i=0;i<t.length;i++)e+="\\"+t[i];return e},ltrim:function(t,e){if(!t)return t;void 0===e&&(e=" \t\n\r\0\v");var i=new RegExp("^["+Craft.escapeChars(e)+"]+");return t.replace(i,"")},rtrim:function(t,e){if(!t)return t;void 0===e&&(e=" \t\n\r\0\v");var i=new RegExp("["+Craft.escapeChars(e)+"]+$");return t.replace(i,"")},trim:function(t,e){return t=Craft.ltrim(t,e),Craft.rtrim(t,e)},startsWith:function(t,e){return t.substring(0,e.length)===e},filterArray:function(t,e){for(var i=[],s=0;s<t.length;s++)("function"==typeof e?e(t[s],s):t[s])&&i.push(t[s]);return i},inArray:function(t,e){return $.isPlainObject(e)&&(e=Object.values(e)),e.includes(t)},removeFromArray:function(t,e){var i=$.inArray(t,e);return-1!==i&&(e.splice(i,1),!0)},getLast:function(t){return t.length?t[t.length-1]:null},uppercaseFirst:function(t){return t.charAt(0).toUpperCase()+t.slice(1)},lowercaseFirst:function(t){return t.charAt(0).toLowerCase()+t.slice(1)},parseUrl:function(t){var e=t.match(/^(?:(https?):\/\/|\/\/)([^\/\:]*)(?:\:(\d+))?(\/[^\?]*)?(?:\?([^#]*))?(#.*)?/);return e?{scheme:e[1],host:e[2]+(e[3]?":"+e[3]:""),hostname:e[2],port:e[3]||null,path:e[4]||"/",query:e[5]||null,hash:e[6]||null}:{}},getQueryParams:function(){return Object.fromEntries(new URLSearchParams(window.location.search).entries())},getQueryParam:function(t){return new Proxy(new URLSearchParams(window.location.search),{get:function(t,e){return t.get(e)}})[t]},isSameHost:function(t){var e=this.parseUrl(document.location.href);if(!e)return!1;var i=this.parseUrl(t);return!!i&&e.host===i.host},secondsToHumanTimeDuration:function(t,e){void 0===e&&(e=!0);var i=604800,s=Math.floor(t/i);t%=i;var n=Math.floor(t/86400);t%=86400;var a,r=Math.floor(t/3600);t%=3600,e?(a=Math.floor(t/60),t%=60):(a=Math.round(t/60),t=0);var o=[];return s&&o.push(s+" "+(1===s?Craft.t("app","week"):Craft.t("app","weeks"))),n&&o.push(n+" "+(1===n?Craft.t("app","day"):Craft.t("app","days"))),r&&o.push(r+" "+(1===r?Craft.t("app","hour"):Craft.t("app","hours"))),!a&&(e||s||n||r)||o.push(a+" "+(1===a?Craft.t("app","minute"):Craft.t("app","minutes"))),!t&&(!e||s||n||r||a)||o.push(t+" "+(1===t?Craft.t("app","second"):Craft.t("app","seconds"))),o.join(", ")},asciiString:function(t,e){t=t.normalize("NFC");for(var i,s="",n=0;n<t.length;n++)i=t.charAt(n),s+="string"==typeof(e||Craft.asciiCharMap)[i]?(e||Craft.asciiCharMap)[i]:i;return s},uuid:function(){return"function"==typeof crypto.randomUUID?crypto.randomUUID():([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(t){return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}))},namespaceInputName:function(t,e){return e?t.replace(/([^'"\[\]]+)([^'"]*)/,"".concat(e,"[$1]$2")):t},namespaceId:function(t,e){return Craft.formatInputId(e?"".concat(e,"-").concat(t):t)},randomString:function(t){for(var e="",i=0;i<t;i++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()));return e},createErrorList:function(t){for(var e=$(document.createElement("ul")).addClass("errors"),i=0;i<t.length;i++){var s=$(document.createElement("li"));s.appendTo(e),s.html(t[i])}return e},appendHeadHtml:function(t){if(t){var e=$("link[href]");if(e.length){for(var i,s=[],n=0;n<e.length;n++)i=e.eq(n).attr("href").replace(/&/g,"&amp;"),s.push(Craft.escapeRegex(i));var a=new RegExp('<link\\s[^>]*href="(?:'+s.join("|")+')".*?></link>',"g");t=t.replace(a,"")}$("head").append(t)}},appendBodyHtml:function(t){if(t){var e=$("script[src]");if(e.length){for(var i,s=[],n=0;n<e.length;n++)i=e.eq(n).attr("src").replace(/&/g,"&amp;"),s.push(Craft.escapeRegex(i));var a=new RegExp('<script\\s[^>]*src="(?:'+s.join("|")+')".*?><\/script>',"g");t=t.replace(a,"")}Garnish.$bod.append(t)}},appendFootHtml:function(t){console.warn("Craft.appendFootHtml() is deprecated. Craft.appendBodyHtml() should be used instead."),this.appendBodyHtml(t)},initUiElements:function(t){$(".grid",t).grid(),$(".info",t).infoicon(),$(".checkbox-select",t).checkboxselect(),$(".fieldtoggle",t).fieldtoggle(),$(".lightswitch",t).lightswitch(),$(".nicetext",t).nicetext(),$(".formsubmit",t).formsubmit(),$(".menubtn:not([data-disclosure-trigger])",t).menubtn(),$("[data-disclosure-trigger]",t).disclosureMenu(),$(".datetimewrapper",t).datetime(),$('.datewrapper > input[type="date"], .timewrapper > input[type="time"]',t).datetimeinput(),$("a",t).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===$(this).attr("target")&&$(this).attr("rel","noopener").attr("target","_blank")}))},_elementIndexClasses:{},_elementSelectorModalClasses:{},_elementEditorClasses:{},registerElementIndexClass:function(t,e){if(void 0!==this._elementIndexClasses[t])throw"An element index class has already been registered for the element type “"+t+"”.";this._elementIndexClasses[t]=e},registerElementSelectorModalClass:function(t,e){if(void 0!==this._elementSelectorModalClasses[t])throw"An element selector modal class has already been registered for the element type “"+t+"”.";this._elementSelectorModalClasses[t]=e},registerElementEditorClass:function(t,e){if(void 0!==this._elementEditorClasses[t])throw"An element editor class has already been registered for the element type “"+t+"”.";this._elementEditorClasses[t]=e},createElementIndex:function(t,e,i){return new(void 0!==this._elementIndexClasses[t]?this._elementIndexClasses[t]:Craft.BaseElementIndex)(t,e,i)},createElementSelectorModal:function(t,e){return new(void 0!==this._elementSelectorModalClasses[t]?this._elementSelectorModalClasses[t]:Craft.BaseElementSelectorModal)(t,e)},createElementEditor:function(t,e,i){return void 0===i&&$.isPlainObject(e)?(i=e,e=null):"object"!==a(i)&&(i={}),i.elementType||(i.elementType=t),new Craft.ElementEditorSlideout(e,i)},getLocalStorage:function(t,e){return t="Craft-"+Craft.systemUid+"."+t,"undefined"!=typeof localStorage&&void 0!==localStorage[t]?JSON.parse(localStorage[t]):e},setLocalStorage:function(t,e){if("undefined"!=typeof localStorage){t="Craft-"+Craft.systemUid+"."+t;try{localStorage[t]=JSON.stringify(e)}catch(t){}}},removeLocalStorage:function(t){"undefined"!=typeof localStorage&&localStorage.removeItem("Craft-".concat(Craft.systemUid,".").concat(t))},getCookie:function(t){return document.cookie.replace(new RegExp("(?:(?:^|.*;\\s*)Craft-".concat(Craft.systemUid,":").concat(t,"\\s*\\=\\s*([^;]*).*$)|^.*$")),"$1")},setCookie:function(t,e,i){i=$.extend({},this.defaultCookieOptions,i);var s="Craft-".concat(Craft.systemUid,":").concat(t,"=").concat(encodeURIComponent(e));i.path&&(s+=";path=".concat(i.path)),i.domain&&(s+=";domain=".concat(i.domain)),i.maxAge?s+=";max-age-in-seconds=".concat(i.maxAge):i.expires&&(s+=";expires=".concat(i.expires.toUTCString())),i.secure&&(s+=";secure"),document.cookie=s},removeCookie:function(t){this.setCookie(t,"",new Date("1970-01-01T00:00:00"))},getElementInfo:function(t){var e=$(t);return e.hasClass("element")||(e=e.find(".element:first")),{id:e.data("id"),siteId:e.data("site-id"),label:e.data("label"),status:e.data("status"),url:e.data("url"),hasThumb:e.hasClass("hasthumb"),$element:e}},setElementSize:function(t,e){var i=$(t);if("small"!==e&&"large"!==e&&(e="small"),!i.hasClass(e)){var s="small"===e?"large":"small";if(i.addClass(e).removeClass(s),i.hasClass("hasthumb")){var n=i.find("> .elementthumb > img"),a=$("<img/>",{sizes:("small"===e?"30":"100")+"px",srcset:n.attr("srcset")||n.attr("data-pfsrcset")});n.replaceWith(a),picturefill({elements:[a[0]]})}}},submitForm:function(t,e){if(void 0===e&&(e={}),!e.confirm||confirm(e.confirm)){if(e.action&&$("<input/>",{type:"hidden",name:"action",val:e.action}).appendTo(t),e.redirect&&$("<input/>",{type:"hidden",name:"redirect",val:e.redirect}).appendTo(t),e.params)for(var i in e.params){var s=e.params[i];$("<input/>",{type:"hidden",name:i,val:s}).appendTo(t)}e.retainScroll&&this.setLocalStorage("scrollY",window.scrollY),t.trigger($.extend({type:"submit"},e.data))}},trapFocusWithin:function(t){Garnish.trapFocusWithin(t)},setFocusWithin:function(t){Garnish.setFocusWithin(t)},filterInputVal:function(t,e){for(var i=$(t),s=i.val(),n=i[0].selectionStart,a="",r=0;r<s.length;r++)s[r].match(e)?a+=s[r]:r<n&&n--;a!==s&&(i.val(a),i[0].setSelectionRange(n,n))},filterNumberInputVal:function(t){this.filterInputVal(t,/[0-9.,\-]/)},setElementAttributes:function(e,i){var s=$(e);for(var n in i)if(i.hasOwnProperty(n)){var a=i[n];if(null===a||!1===a)s.removeAttr(n);else if(!0===a)s.attr(n,"");else if($.isArray(a)||$.isPlainObject(a))if(Craft.dataAttributes.includes(n)){for(var r in a=Object.assign({},a))if(a.hasOwnProperty(r)){var o=a[r];null!==o&&!1!==o&&(o=$.isPlainObject(o)||$.isArray(o)?JSON.stringify(o):!0===o?"":this.escapeHtml(o),s.attr("".concat(n,"-").concat(r),o))}}else if("class"===n){$.isPlainObject(a)&&(a=Object.values(a));var l,h=t(a);try{for(h.s();!(l=h.n()).done;){var d=l.value;s.addClass(d)}}catch(t){h.e(t)}finally{h.f()}}else"style"===n?s.css(a):s.attr(n,JSON.stringify(a));else s.attr(n,this.escapeHtml(a))}},isVisible:function(){return void 0===document.visibilityState||"visible"===document.visibilityState},useMobileStyles:function(){return Garnish.isMobileBrowser()||document.body.clientWidth<600}}),Craft.pageId=Craft.uuid(),"undefined"!=typeof BroadcastChannel){var o="CraftCMS:".concat(Craft.appId);Craft.broadcaster=new BroadcastChannel(o),Craft.messageReceiver=new BroadcastChannel(o),Craft.messageReceiver.addEventListener("message",(function(e){if("saveElement"===e.data.event){var i=$('div.element[data-id="'.concat(e.data.id,'"][data-settings]'));if(!i.length)return;for(var s={type:i.data("type"),id:e.data.id,instances:[]},n=0;n<i.length;n++){var a=i.eq(n);s.instances.push(Object.assign({siteId:a.data("site-id")},a.data("settings")))}Craft.sendActionRequest("POST","app/render-element",{data:s}).then((function(e){for(var s=e.data,n=0;n<i.length;n++){var a=i.eq(n);if(s.elementHtml[n]){var r,o=$(s.elementHtml[n]),l=t(o[0].attributes);try{for(l.s();!(r=l.n()).done;){var h=r.value;"class"===h.name?a.addClass(h.value):a.attr(h.name,h.value)}}catch(t){l.e(t)}finally{l.f()}var d=a.find("input,button").detach();a.html(o.html()),d.length&&d.prependTo(a)}}Craft.cp.elementThumbLoader.load(i)}))}}))}$.extend($.fn,{animateLeft:function(t,e,i,s){return"ltr"===Craft.orientation?this.velocity({left:t},e,i,s):this.velocity({right:t},e,i,s)},animateRight:function(t,e,i,s){return"ltr"===Craft.orientation?this.velocity({right:t},e,i,s):this.velocity({left:t},e,i,s)},disable:function(){return this.each((function(){var t=$(this);t.addClass("disabled"),t.data("activatable")&&t.removeAttr("tabindex")}))},enable:function(){return this.each((function(){var t=$(this);t.removeClass("disabled"),t.data("activatable")&&t.attr("tabindex","0")}))},grid:function(){return this.each((function(){var t=$(this),e={};t.data("item-selector")&&(e.itemSelector=t.data("item-selector")),t.data("cols")&&(e.cols=parseInt(t.data("cols"))),t.data("max-cols")&&(e.maxCols=parseInt(t.data("max-cols"))),t.data("min-col-width")&&(e.minColWidth=parseInt(t.data("min-col-width"))),t.data("mode")&&(e.mode=t.data("mode")),t.data("fill-mode")&&(e.fillMode=t.data("fill-mode")),t.data("col-class")&&(e.colClass=t.data("col-class")),t.data("snap-to-grid")&&(e.snapToGrid=!!t.data("snap-to-grid")),new Craft.Grid(this,e)}))},infoicon:function(){return this.each((function(){new Craft.InfoIcon(this)}))},checkboxselect:function(){return this.each((function(){$.data(this,"checkboxselect")||new Garnish.CheckboxSelect(this)}))},fieldtoggle:function(){return this.each((function(){$.data(this,"fieldtoggle")||new Craft.FieldToggle(this)}))},lightswitch:function(t,e,i){return"settings"===t?("string"==typeof e?(t={})[e]=i:t=e,this.each((function(){var e=$.data(this,"lightswitch");e&&e.setSettings(t)}))):($.isPlainObject(t)||(t={}),this.each((function(){var e=$.extend({},t);Garnish.hasAttr(this,"data-value")&&(e.value=$(this).attr("data-value")),Garnish.hasAttr(this,"data-indeterminate-value")&&(e.indeterminateValue=$(this).attr("data-indeterminate-value")),$.data(this,"lightswitch")||new Craft.LightSwitch(this,e)})))},nicetext:function(){return this.each((function(){$.data(this,"nicetext")||new Garnish.NiceText(this)}))},formsubmit:function(){return this.on("click",(function(t){var e=$(t.currentTarget),i=e.data("params")||{};e.data("param")&&(i[e.data("param")]=e.data("value"));var s=e.data("menu")?e.data("menu").$anchor:e,n=s.attr("data-form")?$("#"+s.attr("data-form")):s.closest("form");Craft.submitForm(n,{confirm:e.data("confirm"),action:e.data("action"),redirect:e.data("redirect"),params:i,data:$.extend({customTrigger:e},e.data("event-data"))})}))},menubtn:function(){return this.each((function(){var t=$(this);if(!t.data("menubtn")&&t.next().hasClass("menu")){var e={};t.data("menu-anchor")&&(e.menuAnchor=t.data("menu-anchor")),new Garnish.MenuBtn(t,e)}}))},disclosureMenu:function(){return this.each((function(){var t=$(this);!t.data("trigger")&&t.attr("aria-controls")&&new Garnish.DisclosureMenu(t)}))},datetime:function(){return this.each((function(){var t=$(this),e=t.find('input:not([name$="[timezone]"])'),i=function(){for(var i=!1,s=0;s<e.length;s++)if(e.eq(s).val()){i=!0;break}if(i){if(!t.children(".clear-btn").length)var n=$("<button/>",{type:"button",class:"clear-btn",title:Craft.t("app","Clear"),"aria-label":Craft.t("app","Clear")}).appendTo(t).on("click",(function(){for(var t=0;t<e.length;t++)e.eq(t).val("").trigger("input").trigger("change");n.remove(),e.first().filter('[type="text"]').focus()}))}else t.children(".clear-btn").remove()};e.on("change",i),i()}))},datetimeinput:function(){return this.each((function(){var t=$(this),e=function(){""===t.val()?t.addClass("empty-value"):t.removeClass("empty-value")};t.on("input",e),e()}))}}),Garnish.NiceText.charsLeftHtml=function(t){return Craft.t("app",'<span class="visually-hidden">Characters left:</span> {chars, number}',{chars:t})},Garnish.$doc.ready((function(){Craft.initUiElements()}))},691:function(){function t(t){return function(t){if(Array.isArray(t))return s(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||i(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function e(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(t,e)||i(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(t,e){if(t){if("string"==typeof t)return s(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?s(t,e):void 0}}function s(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CustomizeSourcesModal=Garnish.Modal.extend({elementIndex:null,$elementIndexSourcesContainer:null,$sidebar:null,$sidebarToggleBtn:null,$sourcesContainer:null,$sourcesHeader:null,$sourcesHeading:null,$sourceSettingsContainer:null,$sourceSettingsHeader:null,$addSourceMenu:null,addSourceMenu:null,$footer:null,$footerBtnContainer:null,$saveBtn:null,$cancelBtn:null,$loadingSpinner:null,sourceSort:null,sources:null,selectedSource:null,elementTypeName:null,baseSortOptions:null,availableTableAttributes:null,customFieldAttributes:null,conditionBuilderHtml:null,conditionBuilderJs:null,userGroups:null,init:function(t,e){var i=this;this.base(),this.setSettings(e,{resizable:!0}),this.elementIndex=t,this.$elementIndexSourcesContainer=this.elementIndex.$sidebar.children("nav").children("ul");var s=$('<form class="modal customize-sources-modal"/>').appendTo(Garnish.$bod);this.$sidebar=$('<div class="cs-sidebar block-types"/>').appendTo(s).attr({role:"navigation","aria-label":Craft.t("app","Source")}),this.$sourcesContainer=$('<div class="sources">').appendTo(this.$sidebar),this.$sourceSettingsContainer=$('<div class="source-settings">').appendTo(s),this.$footer=$('<div class="footer"/>').appendTo(s),this.$footerBtnContainer=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$footerBtnContainer),this.$saveBtn=Craft.ui.createSubmitButton({class:"disabled",label:Craft.t("app","Save"),spinner:!0}).appendTo(this.$footerBtnContainer),this.$loadingSpinner=$('<div class="spinner"/>').appendTo(this.$sourceSettingsContainer),this.setContainer(s),this.show(),Craft.sendActionRequest("POST","element-index-settings/get-customize-sources-modal-data",{data:{elementType:this.elementIndex.elementType}}).then((function(t){i.$saveBtn.removeClass("disabled"),i.buildModal(t.data)})).finally((function(){i.$loadingSpinner.remove(),Garnish.setFocusWithin(i.$sidebar)})),this.addListener(this.$cancelBtn,"click","hide"),this.addListener(this.$saveBtn,"click","save"),this.addListener(this.$container,"submit","save")},buildModal:function(t){var e=this;this.baseSortOptions=t.baseSortOptions,this.defaultSortOptions=t.defaultSortOptions,this.availableTableAttributes=t.availableTableAttributes,this.customFieldAttributes=t.customFieldAttributes,this.elementTypeName=t.elementTypeName,this.conditionBuilderHtml=t.conditionBuilderHtml,this.conditionBuilderJs=t.conditionBuilderJs,this.userGroups=t.userGroups,t.headHtml&&Craft.appendHeadHtml(t.headHtml),t.bodyHtml&&Craft.appendBodyHtml(t.bodyHtml),this.sourceSort=new Garnish.DragSort({handle:".move",axis:"y"}),this.sources=[];for(var i=0;i<t.sources.length;i++)this.sources.push(this.addSource(t.sources[i]));this.selectedSource||void 0===this.sources[0]||this.sources[0].select();var s=$('<div class="buttons left" data-wrapper/>').appendTo(this.$footer),n=$("<button/>",{type:"button",class:"btn menubtn add icon","aria-label":Craft.t("app","Add…"),"aria-controls":"add-source-menu",title:Craft.t("app","Add…"),"data-disclosure-trigger":""}).appendTo(s);this.$addSourceMenu=$("<div/>",{id:"add-source-menu",class:"menu menu--disclosure"}).appendTo(s);var a=function(t){var i=e.addSource(t,!0);Garnish.scrollContainerToElement(e.$sidebar,i.$item),i.select(),e.addSourceMenu.hide()},r=$("<button/>",{type:"button",class:"menu-option",text:Craft.t("app","New heading")}).on("click",(function(){a({type:"heading"}),e.focusLabelInput()})),o=$("<button/>",{type:"button",class:"menu-option",text:Craft.t("app","New custom source"),"data-type":"custom"}).on("click",(function(){var t=e.baseSortOptions.slice(0);t.push(e.defaultSortOptions),a({type:"custom",key:"custom:".concat(Craft.uuid()),sortOptions:t,defaultSort:[t[0].attr,t[1].defaultDir],tableAttributes:[],availableTableAttributes:[]}),e.focusLabelInput()})),l=$("<ul/>").append($("<li/>").append(r)).appendTo(this.$addSourceMenu);t.conditionBuilderHtml&&$("<li/>").append(o).appendTo(l),Craft.useMobileStyles()&&this.buildSidebarToggleView(),this.addListener(Garnish.$win,"resize",this.updateSidebarView),this.addSourceMenu=new Garnish.DisclosureMenu(n)},focusLabelInput:function(){this.selectedSource.$labelInput.trigger("focus")},getSourceName:function(){return this.selectedSource?this.selectedSource.sourceData.label:this.sources[0].sourceData.label},updateSidebarView:function(){Craft.useMobileStyles()?this.$sidebarToggleBtn||this.buildSidebarToggleView():this.$sidebarToggleBtn&&this.resetView()},resetView:function(){this.$sourceSettingsHeader&&this.$sourceSettingsHeader.remove(),this.$sourcesHeader&&this.$sourcesHeader.remove(),this.$sidebarToggleBtn=null,this.$container.removeClass("sidebar-hidden")},updateHeading:function(){this.$sourcesHeading&&this.$sourcesHeading.text(this.getSourceName())},buildSidebarToggleView:function(){var t=this;this.$sourcesHeader=$('<div class="sources-header"/>').addClass("sidebar-header").prependTo(this.$sourcesContainer),this.$sidebarCloseBtn=Craft.ui.createButton({class:"nav-close close-btn"}).attr("aria-label",Craft.t("app","Close")).removeClass("btn").appendTo(this.$sourcesHeader),this.$sourcesHeading=$('<h1 class="main-heading"/>').text(this.getSourceName()),this.$sourceSettingsHeader=$('<div class="source-settings-header"/>').addClass("main-header").append(this.$sourcesHeading).prependTo(this.$sourceSettingsContainer),this.$sidebarToggleBtn=Craft.ui.createButton({toggle:!0,controls:"modal-sidebar",class:"nav-toggle"}).removeClass("btn").attr("aria-label",Craft.t("app","Show sidebar")).appendTo(this.$sourceSettingsHeader),this.closeSidebar(),this.addListener(this.$sidebarToggleBtn,"click",(function(){t.toggleSidebar()})),this.addListener(this.$sidebarCloseBtn,"click",(function(){t.toggleSidebar(),t.$sidebarToggleBtn.trigger("focus")}))},toggleSidebar:function(){this.sidebarIsOpen()?this.closeSidebar():this.openSidebar()},openSidebar:function(){var t=this;this.$container.removeClass("sidebar-hidden"),this.$sidebarToggleBtn.attr("aria-expanded","true"),this.$sidebar.find(":focusable").first().focus(),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.closeSidebar(),Garnish.focusIsInside(t.$sidebar)&&t.$sidebarToggleBtn.focus()}))},closeSidebar:function(){this.$container.addClass("sidebar-hidden"),this.$sidebarToggleBtn&&this.$sidebarToggleBtn.attr("aria-expanded","false"),Garnish.uiLayerManager.currentLayer.$container.hasClass("cs-sidebar")&&Garnish.uiLayerManager.removeLayer()},sidebarIsOpen:function(){return"true"===this.$sidebarToggleBtn.attr("aria-expanded")},addSource:function(t,e){var i,s=$('<div class="customize-sources-item"/>').appendTo(this.$sourcesContainer),n=$('<div class="label customize-sources-item__btn"/>').attr({tabindex:"0",role:"button"}).appendTo(s),a=$('<input type="hidden"/>').appendTo(s);return $('<a class="move icon customize-sources-item__move" title="'.concat(Craft.t("app","Reorder"),'" role="button"></a>')).appendTo(s),"heading"===t.type?(s.addClass("heading"),a.attr("name","sourceOrder[][heading]"),(i=new Craft.CustomizeSourcesModal.Heading(this,s,n,a,t,e)).updateItemLabel(t.heading)):(a.attr("name","sourceOrder[][key]").val(t.key),(i="native"===t.type?new Craft.CustomizeSourcesModal.Source(this,s,n,a,t,e):new Craft.CustomizeSourcesModal.CustomSource(this,s,n,a,t,e)).updateItemLabel(t.label),t.key===this.elementIndex.rootSourceKey&&i.select()),this.sourceSort.addItems(s),i},save:function(t){var e=this;t&&t.preventDefault(),this.$saveBtn.hasClass("disabled")||this.$saveBtn.hasClass("loading")||(this.$saveBtn.addClass("loading"),Craft.sendActionRequest("POST","element-index-settings/save-customize-sources-modal-settings",{data:this.$container.serialize()+"&elementType=".concat(this.elementIndex.elementType)}).then((function(t){var i=t.data,s=null;e.selectedSource&&e.selectedSource.sourceData.key&&!i.disabledSourceKeys.includes(e.selectedSource.sourceData.key)?s=e.selectedSource.sourceData.key:e.elementIndex.sourceKey||(s=e.elementIndex.$visibleSources.first().data("key")),s&&e.elementIndex.selectSourceByKey(s),window.location.reload()})).catch((function(){Craft.cp.displayError(Craft.t("app","A server error occurred."))})).finally((function(){e.$saveBtn.removeClass("loading")})))},appendIndexSourceItem:function(t,e){if(e){var i=t.hasClass("heading");if(e.hasClass("heading")&&!i)t.appendTo(e.children("ul"));else{if(i){var s=e.parentsUntil(this.$elementIndexSourcesContainer,"li").last();s.length&&(e=s)}t.insertAfter(e)}}else t.prependTo(this.$elementIndexSourcesContainer)},destroy:function(){for(var t=0;t<this.sources.length;t++)this.sources[t].destroy();this.addSourceMenu&&(this.addSourceMenu.destroy(),this.$addSourceMenu.remove()),delete this.sources,this.base()}}),Craft.CustomizeSourcesModal.BaseSource=Garnish.Base.extend({modal:null,$item:null,$itemLabel:null,$itemInput:null,$settingsContainer:null,sourceData:null,isNew:null,init:function(t,e,i,s,n,a){var r=this;this.modal=t,this.$item=e,this.$itemLabel=i,this.$itemInput=s,this.sourceData=n,this.isNew=a,this.$item.data("source",this),this.addListener(this.$itemLabel,"click","select"),this.addListener(this.$itemLabel,"keypress",(function(t){return Garnish.handleActivatingKeypress(t,r.select.bind(r))}))},isHeading:function(){return!1},isNative:function(){return!1},isSelected:function(){return this.modal.selectedSource===this},select:function(){this.isSelected()||(this.modal.selectedSource&&this.modal.selectedSource.deselect(),this.$item.addClass("sel"),this.$itemLabel.attr({"aria-current":"true"}),this.modal.selectedSource=this,this.modal.updateHeading(),this.$settingsContainer?this.$settingsContainer.removeClass("hidden"):(this.$settingsContainer=$("<div/>").appendTo(this.modal.$sourceSettingsContainer),this.createSettings(this.$settingsContainer)),this.modal.$sourceSettingsContainer.scrollTop(0))},createSettings:function(){},getIndexSourceItem:function(){},deselect:function(){this.$item.removeClass("sel"),this.$itemLabel.attr({"aria-current":"false"}),this.modal.selectedSource=null,this.$settingsContainer.addClass("hidden")},updateItemLabel:function(t){t?this.$itemLabel.text(t):this.$itemLabel.html("&nbsp;")},destroy:function(){this.modal.sourceSort.removeItems(this.$item),this.modal.sources.splice($.inArray(this,this.modal.sources),1),this.isSelected()&&(this.deselect(),this.modal.sources.length&&this.modal.sources[0].select(),Garnish.setFocusWithin(this.modal.$sourceSettingsContainer)),this.$item.data("source",null),this.$item.remove(),this.$settingsContainer&&this.$settingsContainer.remove(),this.base()}}),Craft.CustomizeSourcesModal.Source=Craft.CustomizeSourcesModal.BaseSource.extend({$sortAttributeSelect:null,$sortDirectionPicker:null,$sortDirectionInput:null,sortDirectionListbox:null,isNative:function(){return!0},createSettings:function(t){Craft.ui.createLightswitchField({label:Craft.t("app","Enabled"),name:"sources[".concat(this.sourceData.key,"][enabled]"),on:!this.sourceData.disabled}).appendTo(t),this.createSortField(t),this.createTableAttributesField(t)},createSortField:function(t){var e=this,i=$('<div class="flex"/>'),s=Craft.ui.createSelect({name:"sources[".concat(this.sourceData.key,"][defaultSort][0]"),options:this.sourceData.sortOptions.map((function(t){return{label:Craft.escapeHtml(t.label),value:t.attr}})),value:this.sourceData.defaultSort[0]}).addClass("fullwidth").appendTo($("<div/>").appendTo(i));this.$sortAttributeSelect=s.children("select").attr("aria-label",Craft.t("app","Sort attribute")),this.$sortDirectionPicker=$("<section/>",{class:"btngroup btngroup--exclusive","aria-label":Craft.t("app","Sort direction")}).append($("<button/>",{type:"button",class:"btn",title:Craft.t("app","Sort ascending"),"aria-label":Craft.t("app","Sort ascending"),"aria-pressed":"false","data-icon":"asc","data-dir":"asc"})).append($("<button/>",{type:"button",class:"btn",title:Craft.t("app","Sort descending"),"aria-label":Craft.t("app","Sort descending"),"aria-pressed":"false","data-icon":"desc","data-dir":"desc"})).appendTo(i),this.$sortDirectionInput=$("<input/>",{type:"hidden",name:"sources[".concat(this.sourceData.key,"][defaultSort][1]")}).appendTo(i),this.sortDirectionListbox=new Craft.Listbox(this.$sortDirectionPicker,{onChange:function(t){e.$sortDirectionInput.val(t.data("dir"))}}),this.$sortAttributeSelect.on("change",(function(){e.handleSortAttributeChange()})),this.handleSortAttributeChange(!0),Craft.ui.createField(i,{label:Craft.t("app","Default Sort"),fieldset:!0}).appendTo(t).addClass("sort-field")},handleSortAttributeChange:function(t){var e=this.$sortAttributeSelect.val();if("structure"===e)this.sortDirectionListbox.select(0),this.sortDirectionListbox.disable(),this.$sortDirectionPicker.addClass("disabled");else{this.sortDirectionListbox.enable(),this.$sortDirectionPicker.removeClass("disabled");var i=t?this.sourceData.defaultSort[1]:this.sourceData.sortOptions.find((function(t){return t.attr===e})).defaultDir;this.sortDirectionListbox.select("asc"===i?0:1)}},createTableAttributesField:function(t){var i=this.availableTableAttributes();if(this.sourceData.tableAttributes.length||i.length){var s=$("<div/>"),n=[];$('<input type="hidden" name="sources['.concat(this.sourceData.key,'][tableAttributes][]" value=""/>')).appendTo(s);for(var a=0;a<this.sourceData.tableAttributes.length;a++){var r=e(this.sourceData.tableAttributes[a],2),o=r[0],l=r[1];s.append(this.createTableColumnOption(o,l,!0)),n.push(o)}for(var h=0;h<i.length;h++){var d=e(i[h],2),c=d[0],u=d[1];Craft.inArray(c,n)||s.append(this.createTableColumnOption(c,u,!1))}new Garnish.DragSort(s.children(),{handle:".move",axis:"y"}),Craft.ui.createField(s,{label:Craft.t("app","Default Table Columns"),instructions:Craft.t("app","Choose which table columns should be visible for this source by default.")}).appendTo(t)}},availableTableAttributes:function(){var e=this.modal.availableTableAttributes.slice(0);return e.push.apply(e,t(this.sourceData.availableTableAttributes)),e},createTableColumnOption:function(t,e,i){return $('<div class="customize-sources-table-column"/>').append('<div class="icon move"/>').append(Craft.ui.createCheckbox({label:Craft.escapeHtml(e),name:"sources[".concat(this.sourceData.key,"][tableAttributes][]"),value:t,checked:i}))},getIndexSourceItem:function(){var t=this.modal.elementIndex.getSourceByKey(this.sourceData.key);if(t)return t.closest("li")}}),Craft.CustomizeSourcesModal.CustomSource=Craft.CustomizeSourcesModal.Source.extend({$labelInput:null,createSettings:function(t){var e=this,i=Craft.ui.createTextField({label:Craft.t("app","Label"),name:"sources[".concat(this.sourceData.key,"][label]"),value:this.sourceData.label}).appendTo(t);this.$labelInput=i.find(".text");var s="condition".concat(Math.floor(1e6*Math.random())),n=function(t){return t.replace(/__ID__/g,s).replace(/__SOURCE_KEY__(?=-)/g,Craft.formatInputId(e.sourceData.key)).replace(/__SOURCE_KEY__/g,e.sourceData.key)},a=this.sourceData.conditionBuilderHtml||n(this.modal.conditionBuilderHtml),r=this.sourceData.conditionBuilderJs||n(this.modal.conditionBuilderJs);Craft.ui.createField($("<div/>").append(a),{id:"criteria",label:Craft.t("app","{type} Criteria",{type:this.modal.elementTypeName})}).appendTo(t),Craft.appendBodyHtml(r),this.createSortField(t),this.createTableAttributesField(t),this.modal.userGroups.length&&Craft.ui.createCheckboxSelectField({label:Craft.t("app","User Groups"),instructions:Craft.t("app","Choose which user groups should have access to this source."),name:"sources[".concat(this.sourceData.key,"][userGroups]"),options:this.modal.userGroups,values:this.sourceData.userGroups||"*",showAllOption:!0}).appendTo(t),t.append("<hr/>"),this.$deleteBtn=$('<a class="error delete"/>').attr({role:"button",tabindex:"0"}).text(Craft.t("app","Delete custom source")).appendTo(t),this.addListener(this.$labelInput,"input","handleLabelInputChange"),this.addListener(this.$deleteBtn,"click","destroy"),this.addListener(this.$deleteBtn,"keypress",(function(t){Garnish.handleActivatingKeypress(t,e.destroy.bind(e))}))},availableTableAttributes:function(){var e=this.base();return this.isNew&&e.push.apply(e,t(this.modal.customFieldAttributes)),e},handleLabelInputChange:function(){this.updateItemLabel(this.$labelInput.val())},getIndexSourceItem:function(){var t,e=this.base();if(e?t=e.find(".label"):(t=$("<span/>",{class:"label"}),e=$("<li/>").append($("<a/>",{"data-key":this.sourceData.key}).append(t))),this.$labelInput){var i=Craft.trim(this.$labelInput.val());""===i&&(i=Craft.t("app","(blank)")),t.text(i)}return e}}),Craft.CustomizeSourcesModal.Heading=Craft.CustomizeSourcesModal.BaseSource.extend({$labelInput:null,$deleteBtn:null,isHeading:function(){return!0},createSettings:function(t){var e=this,i=Craft.ui.createTextField({label:Craft.t("app","Heading"),instructions:Craft.t("app","This can be left blank if you just want an unlabeled separator."),value:this.sourceData.heading||""}).appendTo(t);this.$labelInput=i.find(".text"),t.append("<hr/>"),this.$deleteBtn=$('<a class="error delete"/>').text(Craft.t("app","Delete heading")).attr({role:"button",tabindex:"0"}).appendTo(t),this.addListener(this.$labelInput,"input","handleLabelInputChange"),this.addListener(this.$deleteBtn,"click","destroy"),this.addListener(this.$deleteBtn,"keypress",(function(t){Garnish.handleActivatingKeypress(t,e.destroy.bind(e))}))},handleLabelInputChange:function(){this.updateItemLabel(this.$labelInput.val())},updateItemLabel:function(t){this.$itemLabel.html((t?Craft.escapeHtml(t):"<em>".concat(Craft.t("app","(blank)"),"</em>"))+"&nbsp;"),this.$itemInput.val(t)},getIndexSourceItem:function(){var t=(this.$labelInput?this.$labelInput.val():null)||this.sourceData.heading||"";return $('<li class="heading"/>').append($("<span/>").text(t)).append("<ul/>")}})},1519:function(){Craft.DataTableSorter=Garnish.DragSort.extend({$table:null,init:function(t,e){this.$table=$(t);var i=this.$table.children("tbody").children(":not(.filler)");(e=$.extend({},Craft.DataTableSorter.defaults,e)).container=this.$table.children("tbody"),e.helper=this.getHelper.bind(this),e.caboose="<tr/>",e.axis=Garnish.Y_AXIS,e.magnetStrength=4,e.helperLagBase=1.5,this.base(i,e)},getHelper:function(t){var e=$('<div class="'+this.settings.helperClass+'"/>').appendTo(Garnish.$bod),i=$("<table/>").appendTo(e),s=$("<tbody/>").appendTo(i);t.appendTo(s),i.width(this.$table.width()),i.prop("className",this.$table.prop("className"));for(var n=this.$table.find("tr:first").children(),a=t.children(),r=0;r<a.length;r++)$(a[r]).width($(n[r]).width());return e}},{defaults:{handle:".move",helperClass:"datatablesorthelper"}})},501:function(){Craft.DeleteUserModal=Garnish.Modal.extend({id:null,userId:null,$deleteActionRadios:null,$deleteSubmitBtn:null,userSelect:null,_deleting:!1,init:function(t,e){var i=this;this.id=Math.floor(1e9*Math.random()),this.userId=t,e=$.extend(Craft.DeleteUserModal.defaults,e);var s,n=$('<form class="modal fitted deleteusermodal" method="post" accept-charset="UTF-8">'+Craft.getCsrfInput()+'<input type="hidden" name="action" value="users/delete-user"/>'+(Garnish.isArray(this.userId)?"":'<input type="hidden" name="userId" value="'+this.userId+'"/>')+(e.redirect?'<input type="hidden" name="redirect" value="'+e.redirect+'"/>':"")+"</form>").appendTo(Garnish.$bod),a=$('<div class="body"><div class="content-summary"><p>'+Craft.t("app","What do you want to do with their content?")+'</p><ul class="bullets"></ul></div><div class="options"><label><input type="radio" name="contentAction" value="transfer"/> '+Craft.t("app","Transfer it to:")+'</label><div id="transferselect'+this.id+'" class="elementselect"><div class="elements"></div><button type="button" class="btn add icon dashed">'+Craft.t("app","Choose a user")+'</button></div></div><div><label class="error"><input type="radio" name="contentAction" value="delete"/> '+Craft.t("app","Delete their content")+"</label></div></div>").appendTo(n),r=$('<div class="buttons right"/>').appendTo(a),o=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(r);if(e.contentSummary.length)for(var l=0;l<e.contentSummary.length;l++)a.find("ul").append($("<li/>",{text:e.contentSummary[l]}));else a.find("ul").remove();if(this.$deleteActionRadios=a.find("input[type=radio]"),this.$deleteSubmitBtn=Craft.ui.createSubmitButton({class:"disabled",label:this._submitBtnLabel(!1),spinner:!0}).appendTo(r),Garnish.isArray(this.userId)){s=["and"];for(var h=0;h<this.userId.length;h++)s.push("not "+this.userId[h])}else s="not "+this.userId;this.userSelect=new Craft.BaseElementSelectInput({id:"transferselect"+this.id,name:"transferContentTo",elementType:"craft\\elements\\User",criteria:{id:s},limit:1,modalSettings:{closeOtherModals:!1},onSelectElements:function(){i.updateSizeAndPosition(),i.$deleteActionRadios.first().prop("checked")?i.validateDeleteInputs():i.$deleteActionRadios.first().trigger("click")},onRemoveElements:this.validateDeleteInputs.bind(this),selectable:!1,editable:!1}),this.addListener(o,"click","hide"),this.addListener(this.$deleteActionRadios,"change","validateDeleteInputs"),this.addListener(n,"submit","handleSubmit"),this.base(n,e)},_submitBtnLabel:function(t){var e=t?"Delete {num, plural, =1{user} other{users}} and content":"Delete {num, plural, =1{user} other{users}}";return Craft.t("app",e,{num:Garnish.isArray(this.userId)?this.userId.length:1})},validateDeleteInputs:function(){var t=!1;return this.$deleteActionRadios.eq(1).prop("checked")?(t=!0,this.$deleteSubmitBtn.find(".label").text(this._submitBtnLabel(!0))):(this.$deleteSubmitBtn.find(".label").text(this._submitBtnLabel(!1)),this.$deleteActionRadios.eq(0).prop("checked")&&(t=!!this.userSelect.totalSelected)),this.updateSizeAndPosition(),t?this.$deleteSubmitBtn.removeClass("disabled"):this.$deleteSubmitBtn.addClass("disabled"),t},handleSubmit:function(t){if(!this._deleting&&this.validateDeleteInputs()){this.$deleteSubmitBtn.addClass("loading"),this.disable(),this.userSelect.disable(),this._deleting=!0;try{!1===this.settings.onSubmit()&&t.preventDefault()}catch(e){throw t.preventDefault(),this.$deleteSubmitBtn.removeClass("loading"),e}}else t.preventDefault()},onFadeIn:function(){Garnish.isMobileBrowser(!0)||this.$deleteActionRadios.first().trigger("focus"),this.base()}},{defaults:{contentSummary:[],onSubmit:$.noop,redirect:null}})},2318:function(){Craft.DynamicGenerator=Craft.BaseInputGenerator.extend({callback:$.noop,init:function(t,e,i){this.callback=i,this.base(t,e)},generateTargetValue:function(t){return this.callback(t)}})},4755:function(){Craft.EditableTable=Garnish.Base.extend({initialized:!1,id:null,baseName:null,columns:null,sorter:null,biggestId:-1,$table:null,$tbody:null,$addRowBtn:null,$tableParent:null,$statusMessage:null,rowCount:0,hasMaxRows:!1,hasMinRows:!1,radioCheckboxes:null,init:function(t,e,i,s){var n=this;if(this.id=t,this.baseName=e,this.columns=i,this.setSettings(s,Craft.EditableTable.defaults),this.radioCheckboxes={},this.$table=$("#"+t),this.$tbody=this.$table.children("tbody"),this.$tableParent=this.$table.parent(),this.$statusMessage=this.$tableParent.find("[data-status-message]"),this.rowCount=this.$tbody.find("tr").length,this.$table.data("editable-table")&&(console.warn("Double-instantiating an editable table on an element"),this.$table.data("editable-table").destroy()),this.$table.data("editable-table",this),this.sorter=new Craft.DataTableSorter(this.$table,{helperClass:"editabletablesorthelper",copyDraggeeInputValuesToHelper:!0,onSortChange:function(){n.updateAllRows()}}),this.isVisible()?this.initialize():window.setTimeout(this.initializeIfVisible.bind(this),500),this.settings.minRows&&this.rowCount<this.settings.minRows)for(var a=this.rowCount;a<this.settings.minRows;a++)this.addRow()},isVisible:function(){return this.$table.parent().height()>0},initialize:function(){if(this.initialized)return!1;this.initialized=!0,this.removeListener(Garnish.$win,"resize");for(var t=this.$tbody.children(),e=0;e<t.length;e++)this.createRowObj(t[e]);var i=this.$table.parent(".input");return i.length&&this.$table.width()>i.width()&&i.css("overflow-x","auto"),this.$addRowBtn=this.$table.next(".add"),this.updateAddRowButton(),this.addListener(this.$addRowBtn,"activate","addRow"),!0},initializeIfVisible:function(){this.removeListener(Garnish.$win,"resize"),this.isVisible()?this.initialize():this.addListener(Garnish.$win,"resize","initializeIfVisible")},updateAddRowButton:function(){this.canAddRow()?(this.$addRowBtn.css("opacity","1"),this.$addRowBtn.css("pointer-events","auto"),this.$addRowBtn.attr("aria-disabled","false")):(this.$addRowBtn.css("opacity","0.2"),this.$addRowBtn.css("pointer-events","none"),this.$addRowBtn.attr("aria-disabled","true"))},updateAllRows:function(){if(!this.settings.staticRows)for(var t=this.$table.find("> tbody > tr"),e=0;e<t.length;e++)this.updateRow(t.eq(e))},updateRow:function(t){if(!this.settings.staticRows){var e=t.find("button.delete");e.length&&(e.attr("aria-label",Craft.t("app","Delete row {index}",{index:t.index()+1})),this.canDeleteRow()?e.removeAttr("disabled").removeClass("disabled"):e.attr("disabled","disabled").addClass("disabled"))}},updateDeleteRowButton:function(t){this.updateRow(this.$table.find('tr[data-id="'.concat(t,'"]')))},updateStatusMessage:function(){var t,e=this;this.$statusMessage.empty(),t=this.canAddRow()?Craft.t("app","Row could not be deleted. Minimum number of rows reached."):Craft.t("app","Row could not be added. Maximum number of rows reached."),setTimeout((function(){e.$statusMessage.text(t)}),250)},canDeleteRow:function(){return!!this.settings.allowDelete&&this.rowCount>this.settings.minRows},deleteRow:function(t){this.canDeleteRow()?(this.sorter.removeItems(t.$tr),t.$tr.remove(),this.rowCount--,this.updateAllRows(),this.updateAddRowButton(),0===this.rowCount?(this.$table.addClass("hidden"),this.$addRowBtn.trigger("focus")):this.$tbody.find(":focusable").last().trigger("focus"),this.settings.onDeleteRow(t.$tr),t.destroy()):this.updateStatusMessage()},canAddRow:function(){return!!this.settings.allowAdd&&(!this.settings.maxRows||this.rowCount<this.settings.maxRows)},addRow:function(t,e){if(this.canAddRow()){var i=this.settings.rowIdPrefix+(this.biggestId+1),s=this.createRow(i,this.columns,this.baseName,$.extend({},this.settings.defaultValues));e?s.prependTo(this.$tbody):s.appendTo(this.$tbody);var n=this.createRowObj(s);return this.sorter.addItems(s),!1!==t&&s.find("input:visible,textarea:visible,select:visible").first().trigger("focus"),this.rowCount++,this.updateAllRows(),this.updateAddRowButton(),this.$table.removeClass("hidden"),this.settings.onAddRow(s),n}this.updateStatusMessage()},createRow:function(t,e,i,s){return Craft.EditableTable.createRow(t,e,i,s,this.settings.allowReorder,this.settings.allowDelete)},createRowObj:function(t){return new Craft.EditableTable.Row(this,t)},focusOnPrevRow:function(t,e,i){var s,n=t.prev("tr");if((s=n.length?n.data("editable-table-row"):this.addRow(!1,!0))&&s.$tds[e])if($(s.$tds[e]).hasClass("disabled"))n&&this.focusOnPrevRow(n,e,i);else{var a=$("textarea,input.text",s.$tds[e]);a.length&&($(i).trigger("blur"),a.trigger("focus"))}},focusOnNextRow:function(t,e,i){var s,n=t.next("tr");if((s=n.length?n.data("editable-table-row"):this.addRow(!1))&&s.$tds[e])if($(s.$tds[e]).hasClass("disabled"))n&&this.focusOnNextRow(n,e,i);else{var a=$("textarea,input.text",s.$tds[e]);a.length&&($(i).trigger("blur"),a.trigger("focus"))}},importData:function(t,e,i){for(var s=t.split(/\r?\n|\r/),n=0;n<s.length;n++){for(var a=s[n].split("\t"),r=0;r<a.length;r++){var o=a[r];e.$tds.eq(i+r).find("textarea,input[type!=hidden]").val(o).trigger("input")}var l=e.$tr.next("tr");e=l.length?l.data("editable-table-row"):this.addRow(!1)}},destroy:function(){this.$table.removeData("editable-table"),this.base()}},{textualColTypes:["autosuggest","color","date","email","multiline","number","singleline","template","time","url"],defaults:{rowIdPrefix:"",defaultValues:{},allowAdd:!1,allowReorder:!1,allowDelete:!1,minRows:null,maxRows:null,onAddRow:$.noop,onDeleteRow:$.noop},createRow:function(t,e,i,s,n,a){var r=$("<tr/>",{"data-id":t});for(var o in e)if(e.hasOwnProperty(o)){var l,h=e[o],d=void 0!==s[o]?s[o]:"";if("heading"===h.type)l=$("<th/>",{scope:"row",class:h.class,html:d});else{var c=i+"["+t+"]["+o+"]";switch(l=$("<td/>",{class:"".concat(h.class," ").concat(h.type,"-cell"),width:h.width}),Craft.inArray(h.type,Craft.EditableTable.textualColTypes)&&l.addClass("textual"),h.code&&l.addClass("code"),h.type){case"checkbox":$('<div class="checkbox-wrapper"/>').append(Craft.ui.createCheckbox({name:c,value:h.value||"1",checked:!!d})).appendTo(l);break;case"color":Craft.ui.createColorInput({name:c,value:d,small:!0}).appendTo(l);break;case"date":Craft.ui.createDateInput({name:c,value:d}).appendTo(l);break;case"lightswitch":Craft.ui.createLightswitch({name:c,value:h.value||"1",on:!!d,small:!0}).appendTo(l);break;case"select":Craft.ui.createSelect({name:c,options:h.options,value:d||function(){for(var t in h.options)if(h.options.hasOwnProperty(t)&&h.options[t].default)return void 0!==h.options[t].value?h.options[t].value:t;return null}(),class:"small"}).appendTo(l);break;case"time":Craft.ui.createTimeInput({name:c,value:d}).appendTo(l);break;case"email":case"url":Craft.ui.createTextInput({name:c,value:d,type:h.type,placeholder:h.placeholder||null}).appendTo(l);break;default:$("<textarea/>",{name:c,rows:h.rows||1,val:d,placeholder:h.placeholder}).appendTo(l)}}l.appendTo(r)}return n&&$("<td/>",{class:"thin action"}).append($("<a/>",{class:"move icon",title:Craft.t("app","Reorder"),role:"button",type:"button"})).appendTo(r),a&&$("<td/>",{class:"thin action"}).append($("<button/>",{class:"delete icon",title:Craft.t("app","Delete"),type:"button"})).appendTo(r),r}}),Craft.EditableTable.Row=Garnish.Base.extend({table:null,id:null,niceTexts:null,$tr:null,$tds:null,tds:null,$textareas:null,$deleteBtn:null,init:function(t,e){this.table=t,this.$tr=$(e),this.$tds=this.$tr.children(),this.tds=[],this.id=this.$tr.attr("data-id"),this.$tr.data("editable-table-row",this);var i=parseInt(this.id.substring(this.table.settings.rowIdPrefix.length));i>this.table.biggestId&&(this.table.biggestId=i),this.$textareas=$(),this.niceTexts=[];var s,n,a,r,o,l={},h=0;for(s in this.table.columns)this.table.columns.hasOwnProperty(s)&&(n=this.table.columns[s],a=this.tds[s]=this.$tds[h],Craft.inArray(n.type,Craft.EditableTable.textualColTypes)?(r=$("textarea",a),this.$textareas=this.$textareas.add(r),this.addListener(r,"focus","onTextareaFocus"),this.addListener(r,"mousedown","ignoreNextTextareaFocus"),this.niceTexts.push(new Garnish.NiceText(r,{onHeightChange:this.onTextareaHeightChange.bind(this)})),this.addListener(r,"keypress",{tdIndex:h,type:n.type},"handleKeypress"),this.addListener(r,"input",{type:n.type},"validateValue"),r.trigger("input"),"multiline"!==n.type&&this.addListener(r,"paste",{tdIndex:h,type:n.type},"handlePaste"),l[s]=r):"checkbox"===n.type&&(o=$('input[type="checkbox"]',a),n.radioMode&&(void 0===this.table.radioCheckboxes[s]&&(this.table.radioCheckboxes[s]=[]),this.table.radioCheckboxes[s].push(o[0]),this.addListener(o,"change",{colId:s},"onRadioCheckboxChange")),n.toggle&&this.addListener(o,"change",{colId:s},(function(t){this.applyToggleCheckbox(t.data.colId)}))),$(a).hasClass("disabled")||this.addListener(a,"click",{td:a},(function(t){t.target===t.data.td&&$(t.data.td).find("textarea,input,select,.lightswitch").focus()})),h++);for(s in this.onTextareaHeightChange(),this.table.columns)this.table.columns.hasOwnProperty(s)&&"checkbox"===(n=this.table.columns[s]).type&&n.toggle&&this.applyToggleCheckbox(s);for(s in this.table.columns)this.table.columns.hasOwnProperty(s)&&(n=this.table.columns[s]).autopopulate&&void 0!==l[n.autopopulate]&&!l[s].val()&&new Craft.HandleGenerator(l[s],l[n.autopopulate],{allowNonAlphaStart:!0});var d=this.$tr.children().last().find(".delete");this.addListener(d,"click","deleteRow");var c=this.$tr.find("input,textarea,select,.lightswitch");this.addListener(c,"focus",(function(t){$(t.currentTarget).closest("td:not(.disabled)").addClass("focus")})),this.addListener(c,"blur",(function(t){$(t.currentTarget).closest("td").removeClass("focus")}))},onTextareaFocus:function(t){this.onTextareaHeightChange();var e=$(t.currentTarget);e.data("ignoreNextFocus")?e.data("ignoreNextFocus",!1):window.setTimeout((function(){Craft.selectFullValue(e)}),0)},onRadioCheckboxChange:function(t){if(t.currentTarget.checked)for(var e=0;e<this.table.radioCheckboxes[t.data.colId].length;e++){var i=this.table.radioCheckboxes[t.data.colId][e];i.checked=i===t.currentTarget}},applyToggleCheckbox:function(t){for(var e,i,s=this.table.columns[t],n=$('input[type="checkbox"]',this.tds[t]).prop("checked"),a=0;a<s.toggle.length;a++)e=s.toggle[a],this.table.colum,(i="!"===e[0])&&(e=e.substring(1)),n&&!i||!n&&i?$(this.tds[e]).removeClass("disabled").find("textarea, input").prop("disabled",!1):$(this.tds[e]).addClass("disabled").find("textarea, input").prop("disabled",!0)},ignoreNextTextareaFocus:function(t){$.data(t.currentTarget,"ignoreNextFocus",!0)},handleKeypress:function(t){var e=t.keyCode?t.keyCode:t.charCode,i=Garnish.isCtrlKeyPressed(t);if(e===Garnish.RETURN_KEY&&("multiline"!==t.data.type||i))return t.preventDefault(),void(t.shiftKey?this.table.focusOnPrevRow(this.$tr,t.data.tdIndex,t.currentTarget):this.table.focusOnNextRow(this.$tr,t.data.tdIndex,t.currentTarget))},handlePaste:function(t){var e=Craft.trim(t.originalEvent.clipboardData.getData("Text")," \n\r");e.match(/[\t\r\n]/)&&(t.preventDefault(),this.table.importData(e,this,t.data.tdIndex))},validateValue:function(t){if("multiline"!==t.data.type)if("number"!==t.data.type){var e=t.currentTarget.value.replace(/[\r\n]/g,"");e!==t.currentTarget.value&&(t.currentTarget.value=e)}else Craft.filterNumberInputVal(t.currentTarget)},onTextareaHeightChange:function(){for(var t=-1,e=0;e<this.niceTexts.length;e++)this.niceTexts[e].height>t&&(t=this.niceTexts[e].height);this.$textareas.css("min-height",t);var i=this.$textareas.filter(":visible").first().parent().height();i>t&&this.$textareas.css("min-height",i)},deleteRow:function(){this.table.deleteRow(this)}},{numericKeyCodes:[9,8,37,38,39,40,45,91,46,190,48,49,50,51,52,53,54,55,56,57]})},8468:function(){Craft.ElementActionTrigger=Garnish.Base.extend({maxLevels:null,newChildUrl:null,$trigger:null,$selectedItems:null,triggerEnabled:!0,init:function(t){$.isPlainObject(t)||(t={}),void 0!==t.batch&&(t.bulk=t.batch,delete t.batch),Object.defineProperty(t,"batch",{get:function(){return this.bulk},set:function(t){this.bulk=t}}),this.setSettings(t,Craft.ElementActionTrigger.defaults),this.$trigger=$("#"+t.type.replace(/[\[\]\\]+/g,"-")+"-actiontrigger"),this.settings.activate&&(this.$trigger.data("custom-handler",!0),"FORM"===this.$trigger.prop("nodeName")?this.addListener(this.$trigger,"submit","handleTriggerActivation"):this.addListener(this.$trigger,"activate","handleTriggerActivation")),this.updateTrigger(),Craft.elementIndex.on("selectionChange",this.updateTrigger.bind(this))},updateTrigger:function(){0!==Craft.elementIndex.getSelectedElements().length&&(this.validateSelection()?this.enableTrigger():this.disableTrigger())},validateSelection:function(){return this.$selectedItems=Craft.elementIndex.getSelectedElements(),!(!this.settings.bulk&&this.$selectedItems.length>1)&&(!this.settings.requireId||!this.$selectedItems.is('[data-id=""]'))&&("function"!=typeof this.settings.validateSelection||this.settings.validateSelection(this.$selectedItems))},enableTrigger:function(){this.triggerEnabled||(this.$trigger.removeClass("disabled").removeAttr("aria-disabled"),this.triggerEnabled=!0)},disableTrigger:function(){this.triggerEnabled&&(this.$trigger.addClass("disabled").attr("aria-disabled","true"),this.triggerEnabled=!1)},handleTriggerActivation:function(){this.triggerEnabled&&this.settings.activate(this.$selectedItems)}},{defaults:{type:null,bulk:!0,requireId:!0,validateSelection:null,activate:null}})},5049:function(){function t(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.ElementEditor=Garnish.Base.extend({isFullPage:null,$container:null,$tabContainer:null,$contentContainer:null,$revisionBtn:null,$revisionLabel:null,$spinner:null,$expandSiteStatusesBtn:null,$statusIcon:null,$previewBtn:null,$editMetaBtn:null,metaHud:null,$nameTextInput:null,$saveMetaBtn:null,$siteStatusPane:null,$globalLightswitch:null,$siteLightswitches:null,$additionalSiteField:null,siteIds:null,newSiteIds:null,enableAutosave:null,lastSerializedValue:null,listeningForChanges:!1,pauseLevel:0,timeout:null,cancelToken:null,ignoreFailedRequest:!1,queue:null,submittingForm:!1,duplicatedElements:null,failed:!1,httpStatus:null,httpError:null,openingPreview:!1,preview:null,activatedPreviewToken:!1,previewTokenQueue:null,previewLinks:null,scrollY:null,hiddenTipsStorageKey:"Craft-"+Craft.systemUid+".TipField.hiddenTips",get tipDismissBtn(){return this.$container.find(".tip-dismiss-btn")},get slideout(){return this.$container.data("slideout")},init:function(e,i){var s=this;if(this.$container=$(e),"FORM"!==this.$container.prop("tagName"))throw"Element editors may only be used with forms.";this.$container.data("elementEditor")&&(console.warn("Double-instantiating an element editor on an element."),this.$container.data("elementEditor").destroy()),this.$container.data("elementEditor",this),this.$container.attr("data-element-editor",""),this.setSettings(i,Craft.ElementEditor.defaults),this.isFullPage=this.$container[0]===Craft.cp.$primaryForm[0],this.isFullPage?(this.$tabContainer=$("#tabs"),this.$contentContainer=$("#content")):(this.$tabContainer=this.slideout.$tabContainer,this.$contentContainer=this.slideout.$content),this.queue=this._createQueue(),this.previewTokenQueue=this._createQueue(),this.duplicatedElements={},this.enableAutosave=Craft.autosaveDrafts,this.previewLinks=[],this.siteIds=Object.keys(this.settings.siteStatuses).map((function(t){return parseInt(t)})),this.$revisionBtn=this.$container.find(".context-btn"),this.$revisionLabel=this.$container.find(".revision-label"),this.$previewBtn=this.$container.find(".preview-btn");var n,a,r=this.isFullPage?$("#page-title"):this.slideout.$toolbar;if(this.$spinner=$("<div/>",{class:"revision-spinner spinner hidden",title:Craft.t("app","Saving")}).appendTo(r),this.$statusIcon=$("<div/>",{class:"revision-status ".concat(this.isFullPage?"invisible":"hidden")}).appendTo(r),this.$statusMessage=$("<div/>",{class:"revision-status-message visually-hidden","aria-live":"polite"}).appendTo(r),this.$expandSiteStatusesBtn=$(".expand-status-btn"),this.settings.canEditMultipleSites&&this.addListener(this.$expandSiteStatusesBtn,"click","expandSiteStatuses"),this.settings.previewTargets.length&&this.isFullPage){this.settings.enablePreview&&this.addListener(this.$previewBtn,"click","openPreview");var o=this.$container.find(".preview-btn-container");if(1===this.settings.previewTargets.length){var l=(n=this.settings.previewTargets,a=1,function(t){if(Array.isArray(t))return t}(n)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(n,a)||t(n,a)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())[0];this.createPreviewLink(l).addClass("view-btn btn").attr("aria-label",Craft.t("app","View")).appendTo(o)}else this.createShareMenu(o)}this.settings.revisionId||(this.$container.data("serializer",(function(){return s.serializeForm(!0)})),this.$container.data("initialSerializedValue",this.serializeForm(!0)),this.isFullPage&&this.addListener(this.$container,"submit","handleSubmit"),this.settings.isProvisionalDraft?this.initForProvisionalDraft():this.settings.draftId&&!this.settings.isUnpublishedDraft?this.initForDraft():this.settings.canSaveCanonical||this.addListener(this.$container,"submit.saveShortcut",(function(t){t.saveShortcut&&(t.preventDefault(),s.createDraft(),s.removeListener(s.$container,"submit.saveShortcut"))})),this.listenForChanges(),this.addListener(this.$statusIcon,"click",(function(){s.showStatusHud(s.$statusIcon)})),this.handleDismissibleTips(),this.isFullPage&&Craft.messageReceiver&&Craft.broadcaster.addEventListener("message",(function(t){if("saveDraft"===t.data.event&&t.data.canonicalId===s.settings.canonicalId&&(t.data.draftId===s.settings.draftId||t.data.isProvisionalDraft&&!s.settings.draftId)||"saveElement"===t.data.event&&t.data.id===s.settings.canonicalId&&!s.settings.draftId)Craft.setLocalStorage("scrollY",window.scrollY),window.location.reload();else if("deleteDraft"===t.data.event&&t.data.canonicalId===s.settings.canonicalId&&t.data.draftId===s.settings.draftId){var e=new URL(window.location.href);e.searchParams.delete("draftId"),e.href!==document.location.href?window.location.href=e:(Craft.setLocalStorage("scrollY",window.scrollY),window.location.reload())}})))},_createQueue:function(){var t=this,e=new Craft.Queue;return e.on("beforeRun",(function(){t.showSpinner()})),e.on("afterRun",(function(){t.hideSpinner()})),e},get namespace(){return this.isFullPage?null:this.slideout.namespace},namespaceInputName:function(t){return Craft.namespaceInputName(t,this.namespace)},namespaceId:function(t){return Craft.namespaceId(t,this.namespace)},listenForChanges:function(){var t=this;if(!(this.listeningForChanges||this.pauseLevel>0)&&this.enableAutosave&&this.settings.canCreateDrafts){this.listeningForChanges=!0;var e=this.isFullPage?Garnish.$bod:this.$container;this.addListener(e,"keypress,keyup,change,focus,blur,click,mousedown,mouseup",(function(e){$(e.target).is(t.statusIcons())||(clearTimeout(t.timeout),["keypress","keyup","change"].includes(e.type)?t.timeout=setTimeout(t.checkForm.bind(t),500):t.checkForm())}))}},stopListeningForChanges:function(){this.listeningForChanges&&(this.removeListener(Garnish.$bod,"keypress,keyup,change,focus,blur,click,mousedown,mouseup"),clearTimeout(this.timeout),this.listeningForChanges=!1)},pause:function(){this.pauseLevel++,this.stopListeningForChanges()},resume:function(){if(0===this.pauseLevel)throw"Craft.ElementEditor::resume() should only be called after pause().";this.pauseLevel--,0===this.pauseLevel&&this.enableAutosave&&(this.checkForm(),this.listenForChanges())},initForProvisionalDraft:function(){var t=this,e=this.$container.find(".discard-changes-btn");if(!e.length){var i,s,n;this.isFullPage?(i=$("#content").height(),s=Garnish.$win.scrollTop(),n=Craft.cp.$noticeContainer):n=this.$container.find(".so-notice");var a=$("<div/>",{class:"draft-notice"}).append($("<div/>",{class:"draft-icon","aria-hidden":"true","data-icon":"edit"})).append($("<p/>",{text:Craft.t("app","Showing your unsaved changes.")})).appendTo(n);if(e=$("<button/>",{type:"button",class:"discard-changes-btn btn",text:Craft.t("app","Discard")}).appendTo(a),this.isFullPage){var r=$("#content").height()-i;if(Garnish.$win.scrollTop(s+r),Garnish.$win.scrollTop()===s){Craft.cp.$contentContainer.css("pointer-events","none"),$("#content-header").css("min-height","auto");var o=n.height();n.css({height:o-r,overflow:"hidden"}).velocity({height:o},"fast",(function(){$("#content-header").css("min-height",""),n.css({height:"",overflow:""}),setTimeout((function(){Craft.cp.$contentContainer.css("pointer-events","")}),300)}))}}}this.addListener(e,"keypress,keyup,change,focus,blur,click,mousedown,mouseup",(function(t){t.stopPropagation()})),this.addListener(e,"click",(function(){confirm(Craft.t("app","Are you sure you want to discard your changes?"))&&t.queue.unshift((function(){return new Promise((function(e,i){t.isFullPage?Craft.submitForm(t.$container,{action:"elements/delete-draft",redirect:t.settings.hashedCpEditUrl,params:{draftId:t.settings.draftId,provisional:1}}):Craft.sendActionRequest("POST","elements/delete-draft",{data:{elementId:t.settings.canonicalId,draftId:t.settings.draftId,provisional:1}}).then((function(e){Craft.cp.displaySuccess(e.data.message),t.slideout.close()})).catch(i)}))}))}))},initForDraft:function(){var t=this;this.createEditMetaBtn(),this.settings.canSaveCanonical&&Garnish.uiLayerManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0,alt:!0},(function(){Craft.submitForm(t.$container,{action:"elements/apply-draft",redirect:t.settings.hashedCpEditUrl})}),0)},expandSiteStatuses:function(){var t=this;this.removeListener(this.$expandSiteStatusesBtn,"click"),this.$expandSiteStatusesBtn.velocity({opacity:0},"fast",(function(){t.$expandSiteStatusesBtn.remove()}));var e=this.$container.find(".enabled-for-site-".concat(this.settings.siteId,"-field"));if(this.$siteStatusPane=e.parent(),this.settings.revisionId)this._getOtherSupportedSites().forEach((function(e){return t._createSiteStatusField(e)}));else{e.addClass("nested");var i=Craft.ui.createLightswitchField({label:Craft.t("app","Enabled for all sites"),name:this.namespaceInputName("enabled")}).insertBefore(e);i.find("label").css("font-weight","bold"),this.$globalLightswitch=i.find(".lightswitch"),this.settings.revisionId||this._showField(i);var s=Object.values(this.settings.siteStatuses),n=s.includes(!0),a=s.includes(!1),r=n&&a?"-":n?"1":"",o=encodeURIComponent(this.namespaceInputName("enabledForSite[".concat(this.settings.siteId,"]")))+"="+(this.settings.enabledForSite?"1":"");this.$siteLightswitches=e.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this)),this._getOtherSupportedSites().forEach((function(e){return t._createSiteStatusField(e)}));for(var l=encodeURIComponent(this.namespaceInputName("enabled"))+"=".concat(r),h=0;h<this.$siteLightswitches.length;h++){var d=this.$siteLightswitches.eq(h).data("lightswitch").$input;l+="&"+encodeURIComponent(d.attr("name"))+"="+d.val()}this.$container.data("initialSerializedValue",this.$container.data("initialSerializedValue").replace(o,l)),this.lastSerializedValue&&(this.lastSerializedValue=this.lastSerializedValue.replace(o,l)),this.settings.additionalSites&&this.settings.additionalSites.length&&this.isFullPage&&this._createAddlSiteField(),this.$globalLightswitch.focus(),this.$globalLightswitch.on("change",this._updateSiteStatuses.bind(this)),this._updateGlobalStatus()}},_getOtherSupportedSites:function(){var t=this;return Craft.sites.filter((function(e){return e.id!=t.settings.siteId&&t.siteIds.includes(e.id)}))},_showField:function(t){var e=t.height();t.css({overflow:"hidden","min-height":"auto"}).height(0).velocity({height:e},"fast",(function(){t.css({overflow:"",height:"","min-height":""})}))},_removeField:function(t){t.css({overflow:"hidden","min-height":"auto"}).velocity({height:0},"fast",(function(){t.remove()}))},_updateGlobalStatus:function(){var t=!0,e=!0;this.$siteLightswitches.each((function(){if($(this).data("lightswitch").on?e=!1:t=!1,!t&&!e)return!1})),t?this.$globalLightswitch.data("lightswitch").turnOn(!0):e?this.$globalLightswitch.data("lightswitch").turnOff(!0):this.$globalLightswitch.data("lightswitch").turnIndeterminate(!0)},_updateSiteStatuses:function(){var t=this.$globalLightswitch.data("lightswitch").on;this.$siteLightswitches.each((function(){t?$(this).data("lightswitch").turnOn(!0):$(this).data("lightswitch").turnOff(!0)}))},_createSiteStatusField:function(t,e){var i=Craft.ui.createLightswitchField({fieldClass:"enabled-for-site-".concat(t.id,"-field"),label:t.name,name:this.namespaceInputName("enabledForSite[".concat(t.id,"]")),on:void 0!==e?e:!this.settings.siteStatuses.hasOwnProperty(t.id)||this.settings.siteStatuses[t.id],disabled:!!this.settings.revisionId});if(this.$additionalSiteField?i.insertBefore(this.$additionalSiteField):i.appendTo(this.$siteStatusPane),!this.settings.revisionId){i.addClass("nested");var s=i.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this));this.$siteLightswitches=this.$siteLightswitches.add(s)}return this._showField(i),i},_createAddlSiteField:function(){var i,s=this,n=Craft.sites.filter((function(t){return!s.siteIds.includes(t.id)&&s.settings.additionalSites.some((function(e){return e.siteId==t.id}))}));if(n.length){var a="add-site-label",r=$("<span/>",{text:Craft.t("app","Add a site..."),class:"visually-hidden",id:a}),o=Craft.ui.createSelect({options:[{label:Craft.t("app","Add a site…")}].concat((i=n.map((function(t){return{label:t.name,value:t.id}})),function(t){if(Array.isArray(t))return e(t)}(i)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(i)||t(i)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())),labelledBy:a}).addClass("fullwidth");this.$additionalSiteField=Craft.ui.createField(o,{}).addClass("nested add").appendTo(this.$siteStatusPane),r.prependTo(this.$additionalSiteField);var l=o.find("select");l.on("change",(function(){var t=parseInt(l.val()),e=Craft.sites.find((function(e){return e.id===t}));if(e){var i=s.settings.additionalSites.find((function(t){return t.siteId==e.id}));s._createSiteStatusField(e,i.enabledByDefault),s._updateGlobalStatus(),l.val("").find('option[value="'.concat(t,'"]')).remove(),null===s.newSiteIds&&(s.newSiteIds=[]),s.siteIds.push(t),s.newSiteIds.push(t),1===l.find("option").length&&s._removeField(s.$additionalSiteField)}})),this._showField(this.$additionalSiteField)}},showStatusHud:function(t){var e;this.failed?(e='<p class="error"><strong>'.concat(this._saveFailMessage(),"</strong></p>"),this.httpError&&(e+='<p class="http-error code">'.concat(Craft.escapeHtml(this.httpError),"</p>")),400===this.httpStatus&&(e+='<button class="btn refresh-btn">'.concat(Craft.t("app","Refresh"),"</button>"))):e="<p>".concat(this._saveSuccessMessage(),"</p>");var i=new Garnish.HUD(t,e,{hudClass:"hud revision-status-hud",onHide:function(){i.destroy()}});i.$mainContainer.find(".refresh-btn").on("click",(function(){window.location.reload()}))},_saveSuccessMessage:function(){return this.settings.isProvisionalDraft||this.settings.isUnpublishedDraft?Craft.t("app","Your changes have been stored."):Craft.t("app","The draft has been saved.")},_saveFailMessage:function(){return this.settings.isProvisionalDraft||this.settings.isUnpublishedDraft?Craft.t("app","Your changes could not be stored."):Craft.t("app","The draft could not be saved.")},spinners:function(){return this.preview?this.$spinner.add(this.preview.$spinner):this.$spinner},showSpinner:function(){this.spinners().removeClass("hidden")},hideSpinner:function(){this.spinners().addClass("hidden")},statusIcons:function(){return this.preview?this.$statusIcon.add(this.preview.$statusIcon):this.$statusIcon},statusMessage:function(){return this.preview?this.$statusMessage.add(this.preview.$statusMessage):this.$statusMessage},createEditMetaBtn:function(){var t=this.$container.find(".context-btngroup");this.$editMetaBtn=$("<button/>",{type:"button",class:"btn edit icon","aria-expanded":"false","aria-label":Craft.t("app","Edit draft settings"),title:Craft.t("app","Edit draft settings")}).appendTo(t),t.find(".btngroup-btn-last").removeClass("btngroup-btn-last"),this.addListener(this.$editMetaBtn,"click","showMetaHud")},createPreviewLink:function(t,e){var i=this,s=$("<a/>",{href:this.getTokenizedPreviewUrl(t.url,null,!1),text:e||Craft.t("app","View"),target:"_blank",data:{targetUrl:t.url,targetLabel:t.label}});return this.addListener(s,"click",(function(){setTimeout((function(){i.activatePreviewToken()}),1)})),this.previewLinks.push(s),s},updatePreviewLinks:function(){var t=this;this.previewLinks.forEach((function(e){t.updatePreviewLinkHref(e),t.activatedPreviewToken&&t.removeListener(e,"click")}))},updatePreviewLinkHref:function(t){t.attr("href",this.getTokenizedPreviewUrl(t.data("targetUrl"),null,!1))},activatePreviewToken:function(){this.settings.isLive||(this.activatedPreviewToken=!0,this.updatePreviewLinks())},createShareMenu:function(t){var e=this,i=$("<button/>",{type:"button",class:"view-btn btn menubtn",text:Craft.t("app","View")}).appendTo(t),s=$("<div/>",{class:"menu"}).appendTo(t),n=$("<ul/>").appendTo(s);this.settings.previewTargets.forEach((function(t){$("<li/>").append(e.createPreviewLink(t,t.label)).appendTo(n)})),new Garnish.MenuBtn(i)},getPreviewTokenParams:function(){var t={elementType:this.settings.elementType,canonicalId:this.settings.canonicalId,siteId:this.settings.siteId,revisionId:this.settings.revisionId,previewToken:this.settings.previewToken};return this.settings.draftId&&!this.settings.isProvisionalDraft&&(t.draftId=this.settings.draftId),t},getPreviewToken:function(){var t=this;return this.previewTokenQueue.push((function(){return new Promise((function(e,i){t.activatedPreviewToken?e(t.settings.previewToken):Craft.sendActionRequest("POST","preview/create-token",{data:t.getPreviewTokenParams()}).then((function(){t.activatePreviewToken(),e(t.settings.previewToken)})).catch(i)}))}))},getTokenizedPreviewUrl:function(t,e,i){var s=this;void 0===i&&(i=!0);var n={};if(!e&&this.settings.isLive||(n[e||"x-craft-preview"]=Craft.randomString(10)),this.settings.siteToken&&(n[Craft.siteToken]=this.settings.siteToken),this.settings.isLive){var a=Craft.getUrl(t,n);return i?new Promise((function(t){t(a)})):a}if(!this.settings.previewToken)throw"Missing preview token";n[Craft.tokenParam]=this.settings.previewToken;var r=Craft.getUrl(t,n);if(this.activatedPreviewToken)return i?new Promise((function(t){t(r)})):r;if(i)return new Promise((function(t,e){s.getPreviewToken().then((function(){t(r)})).catch(e)}));var o=this.getPreviewTokenParams();return o.redirect=r,Craft.getActionUrl("preview/create-token",o)},getPreview:function(){var t=this;return this.preview||(this.preview=new Craft.Preview(this),this.enableAutosave||(this.preview.on("open",(function(){t.enableAutosave=!0,t.listenForChanges()})),this.preview.on("close",(function(){t.enableAutosave=!1,t.stopListeningForChanges();var e=t.statusIcons();e.hasClass("checkmark-icon")&&e.addClass("hidden")}))),this.preview.on("close",(function(){t.scrollY&&(window.scrollTo(0,t.scrollY),t.scrollY=null)}))),this.preview},openPreview:function(){var t=this;Garnish.hasAttr(this.$previewBtn,"aria-disabled")||(this.$previewBtn.attr("aria-disabled",!0),this.$previewBtn.addClass("loading"),this.queue.push((function(){return new Promise((function(e,i){t.openingPreview=!0,t.ensureIsDraftOrRevision(!0).then((function(){t.scrollY=window.scrollY,t.$previewBtn.removeAttr("aria-disabled"),t.$previewBtn.removeClass("loading"),t.getPreview().open(),t.openingPreview=!1,e()})).catch(i)}))})))},ensureIsDraftOrRevision:function(t){var e=this;return new Promise((function(i,s){if(e.settings.draftId||e.settings.revisionId)i();else{if(t&&e.serializeForm(!0)===e.$container.data("initialSerializedValue"))return void i();e.createDraft().then(i).catch(s)}}))},serializeForm:function(t){var e=this.$container.serialize();if(this.isPreviewActive()&&(e=e.replace("__PREVIEW_FIELDS__=1",this.preview.$editor.serialize())),t&&!this.settings.isUnpublishedDraft){var i=this.namespaceInputName("action"),s=this.namespaceInputName("redirect");e=(e=e.replace(new RegExp("&".concat(Craft.escapeRegex(i),"=[^&]*")),"")).replace(new RegExp("&".concat(Craft.escapeRegex(s),"=[^&]*")),"")}return e},checkForm:function(t){var e=this;return this.queue.push((function(){return new Promise((function(i,s){if(e.settings.revisionId||e.pauseLevel>0||!e.enableAutosave||!e.settings.canCreateDrafts)i();else if(clearTimeout(e.timeout),e.timeout=null,void 0!==e.$container.data("initialSerializedValue")){var n=e.serializeForm(!0);t||n!==(e.lastSerializedValue||e.$container.data("initialSerializedValue"))?e.saveDraft(n).then(i).catch((function(t){console.warn("Couldn’t save draft:",t),s(t)})):i()}else e.timeout=setTimeout(e.checkForm.bind(e),500)}))}))},isPreviewActive:function(){return this.preview&&this.preview.isActive},createDraft:function(){var t=this;return this.queue.push((function(){return new Promise((function(e,i){t.saveDraft(t.serializeForm(!0)).then(e).catch(i)}))}))},saveDraft:function(t){var e=this;return new Promise((function(i,s){if(e.submittingForm)s("Form already being submitted.");else{e.lastSerializedValue=t,e.failed=!1,e.httpStatus=null,e.httpError=null,e.cancelToken=axios.CancelToken.source(),e.statusIcons().velocity("stop").css("opacity","").removeClass("hidden invisible checkmark-icon alert-icon fade-out").addClass("hidden"),e.statusMessage().empty(),e.$saveMetaBtn&&e.$saveMetaBtn.addClass("active");var n,a,r,o=[],l=e.prepareData(t,e.settings.isUnpublishedDraft?null:function(t,e){e.length&&o.push(decodeURIComponent(e[0].split("=")[0]))}),h=(n={},a=e.namespaceInputName("visibleLayoutElements"),r=e.settings.visibleLayoutElements,a in n?Object.defineProperty(n,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):n[a]=r,n);!e.settings.isProvisionalDraft&&e.settings.draftId||(h[e.namespaceInputName("provisional")]=1);var d=e.$contentContainer.children("[data-layout-tab]:not(.hidden)").data("id");d&&(h[e.namespaceInputName("selectedTab")]=d),l+="&".concat($.param(h)),Craft.sendActionRequest("POST","elements/save-draft",{cancelToken:e.cancelToken.token,headers:e._saveHeaders,data:l}).then((function(s){var n=e.$contentContainer.children("[data-layout-tab]:not(.hidden)").data("id");e._afterSaveDraft();var a=!e.settings.draftId;a&&(e.settings.isProvisionalDraft=!0,e.$revisionLabel.append($("<span/>",{text:" — ".concat(Craft.t("app","Edited"))}))),e.isFullPage&&(s.data.title&&e.$container.find(".screen-title").text(s.data.title),s.data.docTitle&&(document.title=s.data.docTitle)),e.settings.isProvisionalDraft||(e.$revisionLabel.text(s.data.draftName),e.settings.draftName=s.data.draftName);var r=e.$revisionBtn.data("menubtn")?e.$revisionBtn.data("menubtn").menu:null;for(var l in e.newSiteIds&&(r||(e.$revisionBtn.removeClass("disabled").addClass("menubtn"),new Garnish.MenuBtn(e.$revisionBtn),(r=e.$revisionBtn.data("menubtn").menu).$container.removeClass("hidden")),e.newSiteIds.forEach((function(t){var i=r.$options.filter("[data-site-id=".concat(t,"]")),s=e.settings.additionalSites.find((function(e){return e.siteId==t}));s&&void 0!==s.enabledByDefault&&!s.enabledByDefault||i.find(".status").removeClass("disabled").addClass("enabled"),i.parent().removeClass("hidden").closest(".site-group").removeClass("hidden")})),r.$container.find(".revision-hr").removeClass("hidden"),e.newSiteIds=null),e.settings.isProvisionalDraft?a&&(e.$container.find("input.action-input").attr("value","elements/apply-draft"),e.settings.draftId=s.data.draftId,e.settings.isLive=!1,e.previewToken=null,e.initForProvisionalDraft()):r&&(r.$options.filter(".sel").find(".draft-name").text(s.data.draftName),r.$options.filter(".sel").find(".draft-meta").text(s.data.creator?Craft.t("app","Saved {timestamp} by {creator}",{timestamp:s.data.timestamp,creator:s.data.creator}):Craft.t("app","Saved {timestamp}",{timestamp:s.data.timestamp}))),s.data.previewTargets&&JSON.stringify(s.data.previewTargets)!==JSON.stringify(e.settings.previewTargets)&&e.updatePreviewTargets(s.data.previewTargets),a&&(e.updatePreviewLinks(),e.trigger("createProvisionalDraft")),e.$nameTextInput&&e.checkMetaValues(),s.data.duplicatedElements)l!=e.settings.canonicalId&&s.data.duplicatedElements.hasOwnProperty(l)&&(e.duplicatedElements[l]=s.data.duplicatedElements[l]);for(var h=s.data.modifiedAttributes.map((function(t){return t=e.namespaceInputName(t),'[name="'.concat(t,'"],[name^="').concat(t,'["]')})).concat(o.map((function(t){return'[name="'.concat(t,'"]')}))),c=$(h.join(",")).parents().filter(".flex-fields > .field:not(:has(> .status-badge))"),u=0;u<c.length;u++)c.eq(u).prepend($("<div/>",{class:"status-badge modified",title:Craft.t("app","This field has been modified.")}).append($("<span/>",{class:"visually-hidden",html:Craft.t("app","This field has been modified.")})));for(var p=e.serializeForm(!0)===t,f=$(),g={},m=!1,v=0;v<s.data.missingElements.length;v++){var b=s.data.missingElements[v],C=e.$contentContainer.children('[data-layout-tab="'.concat(b.uid,'"]'));C.length||(C=$("<div/>",{id:e.namespaceId(b.id),class:"flex-fields","data-id":b.id,"data-layout-tab":b.uid}),b.id!==d&&C.addClass("hidden"),C.appendTo(e.$contentContainer)),f=f.add(C);for(var _=0;_<b.elements.length;_++){var w=b.elements[_];if(!1!==w.html){if(g[b.uid]||(g[b.uid]=[]),g[b.uid].push(w.uid),"string"==typeof w.html){var S=C.children('[data-layout-element="'.concat(w.uid,'"]')),y=$(w.html);S.length?S.replaceWith(y):y.appendTo(C),Craft.initUiElements(y),m=!0}}else{var I=C.children('[data-layout-element="'.concat(w.uid,'"]'));if(!I.length||!Garnish.hasAttr(I,"data-layout-element-placeholder")){var T=$("<div/>",{class:"hidden","data-layout-element":w.uid,"data-layout-element-placeholder":""});I.length?I.replaceWith(T):T.appendTo(C),m=!0}}}}var x,P=e.$contentContainer.children("[data-layout-tab]").not(f).not('[data-layout-tab=""]');if(P.length&&(P.remove(),m=!0),f.filter(":not(.hidden)").length||f.first().removeClass("hidden"),e.settings.visibleLayoutElements=g,e.isFullPage?(Craft.cp.updateTabs(s.data.tabs),x=Craft.cp.tabManager):(e.slideout.updateTabs(s.data.tabs),x=e.slideout.tabManager),d&&n&&d!==n){var B=x.$tabs.filter('[data-id="'.concat(n,'"]'));B.length?x.selectTab(B):x.selectTab(x.$tabs.first())}Craft.appendHeadHtml(s.data.headHtml),Craft.appendBodyHtml(s.data.bodyHtml),m&&(s.data.initialDeltaValues&&Object.assign(e.$container.data("initial-delta-values"),s.data.initialDeltaValues),p&&(e.lastSerializedValue=e.serializeForm(!0))),e.handleDismissibleTips(),e.afterUpdate(t),Craft.broadcaster&&Craft.broadcaster.postMessage({pageId:Craft.pageId,event:"saveDraft",canonicalId:e.settings.canonicalId,draftId:e.settings.draftId,isProvisionalDraft:e.settings.isProvisionalDraft}),i()})).catch((function(t){e._afterSaveDraft(),e.ignoreFailedRequest||(e.failed=!0,t&&t.response&&(e.httpStatus=t.response.status,e.httpError=t.response.data?t.response.data.message:null),e._showFailStatus(),s(t)),e.ignoreFailedRequest=!1}))}}))},_afterSaveDraft:function(){this.$saveMetaBtn&&this.$saveMetaBtn.removeClass("active")},_showFailStatus:function(){this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden checkmark-icon").addClass("alert-icon"),this.setStatusMessage(this._saveFailMessage())},prepareData:function(t,e){t=Craft.findDeltaData(this.$container.data("initialSerializedValue"),t,this.$container.data("delta-names"),e,this.$container.data("initial-delta-values"),this.$container.data("modified-delta-names")),t=this.swapDuplicatedElementIds(t);var i={};return this.settings.draftId&&(i[this.namespaceInputName("draftId")]=this.settings.draftId,this.settings.isProvisionalDraft&&(i[this.namespaceInputName("provisional")]=1)),null!==this.settings.draftName&&(i[this.namespaceInputName("draftName")]=this.settings.draftName),$.isEmptyObject(i)||(t+="&".concat($.param(i))),t},get _saveHeaders(){var t={"content-type":"application/x-www-form-urlencoded"};return this.namespace&&(t["X-Craft-Namespace"]=this.namespace),t},swapDuplicatedElementIds:function(t){var e=this,i=Object.keys(this.duplicatedElements).join("|");if(""===i)return t;var s=encodeURIComponent("["),n=encodeURIComponent("]"),a=this.namespaceInputName("fields");for(a=this.isFullPage?Craft.escapeRegex(a):encodeURIComponent(a);t!==(t=t.replace(new RegExp("(&".concat(a).concat(s,"[^=]+").concat(n).concat(s,")(").concat(i,")(").concat(n,")"),"g"),(function(t,i,s,n){return e._filterFieldInputName(i)?i+e.duplicatedElements[s]+n:t})).replace(new RegExp("&(".concat(a).concat(s,"[^=]+)=(").concat(i,")\\b"),"g"),(function(t,i,a){return!e._filterFieldInputName(i)||i.match(new RegExp("".concat(s,"(enabled|sortOrder|type|typeId)").concat(n,"$")))?t:"&".concat(i,"=").concat(e.duplicatedElements[a])}))););return t},_filterFieldInputName:function(t){var e=encodeURIComponent("["),i=encodeURIComponent("]"),s=t.match(new RegExp("(\\bfields|".concat(e,"fields").concat(i,")").concat(e,".+?").concat(i),"g"));if(!s)throw"Unexpected input name: ".concat(t);var n=s[s.length-1].match(new RegExp("(?:\\bfields|".concat(e,"fields").concat(i,")").concat(e,"(.+?)").concat(i)))[1];return Craft.fieldsWithoutContent.includes(n)},updatePreviewTargets:function(t){var e=this;t.forEach((function(t){var i=e.settings.previewTargets.find((function(e){return e.label===t.label}));i&&(i.url=t.url);var s=e.previewLinks.find((function(e){return e.data("targetLabel")===t.label}));s&&(s.data("targetUrl",t.url),e.updatePreviewLinkHref(s))}))},afterUpdate:function(t){this.$container.data("initialSerializedValue",t),this.$container.data("initial-delta-values",{});var e=this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden").addClass("checkmark-icon");this.setStatusMessage(this._saveSuccessMessage()),Craft.autosaveDrafts||e.velocity("stop").velocity({opacity:0},{delay:2e3,complete:function(){e.addClass("hidden")}}),this.trigger("update")},setStatusMessage:function(t){this.statusIcons().attr("title",t),this.statusMessage().empty().append($("<span/>",{class:"visually-hidden",text:t}))},showMetaHud:function(){this.metaHud?this.metaHud.show():(this.createMetaHud(),this.onMetaHudShow()),Garnish.isMobileBrowser(!0)||this.$nameTextInput.trigger("focus")},createMetaHud:function(){var t=$("<div/>"),e=$('<div class="field"><div class="heading"><label for="draft-name">'+Craft.t("app","Draft Name")+"</label></div></div>").appendTo(t),i=$('<div class="input"/>').appendTo(e);this.$nameTextInput=$('<input type="text" class="text fullwidth" id="draft-name"/>').appendTo(i).val(this.settings.draftName);var s=$('<div class="hud-footer flex flex-center"/>').appendTo(t);$('<div class="flex-grow"></div>').appendTo(s),this.$saveMetaBtn=$("<button/>",{type:"submit",class:"btn submit disabled","aria-disabled":"true",text:Craft.t("app","Save")}).appendTo(s),this.metaHud=new Garnish.HUD(this.$editMetaBtn,t,{onSubmit:this.saveMeta.bind(this)}),this.addListener(this.$nameTextInput,"input","checkMetaValues"),this.metaHud.on("show",this.onMetaHudShow.bind(this)),this.metaHud.on("hide",this.onMetaHudHide.bind(this)),this.metaHud.on("escape",this.onMetaHudEscape.bind(this))},onMetaHudShow:function(){this.$editMetaBtn.addClass("active"),this.$editMetaBtn.attr("aria-expanded","true")},onMetaHudHide:function(){this.$editMetaBtn.removeClass("active"),this.$editMetaBtn.attr("aria-expanded","false"),Garnish.focusIsInside(this.metaHud.$body)&&this.$editMetaBtn.trigger("focus")},onMetaHudEscape:function(){this.$nameTextInput.val(this.settings.draftName)},checkMetaValues:function(){return this.$nameTextInput.val()&&this.$nameTextInput.val()!==this.settings.draftName?(this.$saveMetaBtn.removeClass("disabled"),this.$saveMetaBtn.removeAttr("aria-disabled"),!0):(this.$saveMetaBtn.addClass("disabled"),this.$saveMetaBtn.attr("aria-disabled","true"),!1)},shakeMetaHud:function(){Garnish.shake(this.metaHud.$hud)},saveMeta:function(){var t=this;return new Promise((function(e,i){if(!t.checkMetaValues())return t.shakeMetaHud(),void i();t.settings.draftName=t.$nameTextInput.val(),t.metaHud.hide(),t.checkForm(!0).then(e).catch(i)}))},handleSubmit:function(t){var e=this;if(t.preventDefault(),t.stopPropagation(),!this.submittingForm)if(!this.settings.draftId||this.settings.isUnpublishedDraft||this.settings.isProvisionalDraft||void 0!==t.autosave&&!t.autosave||!(t.saveShortcut||t.customTrigger&&"elements/save-draft"===t.customTrigger.data("action"))||!this.enableAutosave){this.submittingForm=!0,Craft.cp.$confirmUnloadForms=Craft.cp.$confirmUnloadForms.not(this.$container),this.cancelToken&&(this.ignoreFailedRequest=!0,this.cancelToken.cancel()),this.trigger("beforeSubmit");var i=this.prepareData(this.serializeForm(!1));if(this.isFullPage){this.stopListeningForChanges();var s=Craft.createForm(i);s.appendTo(Garnish.$bod),s.submit()}else this.slideout.showSubmitSpinner(),Craft.sendActionRequest("POST",null,{headers:this._saveHeaders,data:i}).then((function(t){e.slideout.handleSubmitResponse(t)})).catch((function(t){e.slideout.handleSubmitError(t)})).finally((function(){e.submittingForm=!1,e.slideout.hideSubmitSpinner()}))}else this.checkForm(!0)},handleDismissibleTips:function(){var t=this;this.addListener(this.tipDismissBtn,"click",(function(e){t.hideTip(e)}))},getHiddenTipsUids:function(){return Craft.getLocalStorage("dismissedTips",[])},setHiddenTipsUids:function(t){Craft.setLocalStorage("dismissedTips",t)},hideTip:function(t){var e=t.target;if(e){var i=$(e).closest(".readable");if(i.length){var s=i.data("layout-element");if(i.remove(),"undefined"!=typeof Storage){var n=this.getHiddenTipsUids();n.includes(s)||(n.push(s),this.setHiddenTipsUids(n))}}}}},{defaults:{additionalSites:[],canCreateDrafts:!1,canEditMultipleSites:!1,canSaveCanonical:!1,canonicalId:null,draftId:null,draftName:null,elementType:null,enablePreview:!1,enabled:!1,enabledForSite:!1,hashedCpEditUrl:null,isLive:!1,isProvisionalDraft:!1,isUnpublishedDraft:!1,previewTargets:[],previewToken:null,revisionId:null,siteId:null,siteStatuses:null,siteToken:null,visibleLayoutElements:{}}})},4211:function(){Craft.ElementEditorSlideout=Craft.CpScreenSlideout.extend({$element:null,init:function(t,e){var i=this;this.$element=$(t),e=Object.assign({},Craft.ElementEditorSlideout.defaults,e,{showHeader:!0}),this.base("elements/edit",e),this.on("load",(function(){var t=i.$container.data("elementEditor");t&&t.on("beforeSubmit",(function(){Object.keys(i.settings.saveParams).forEach((function(e){$("<input/>",{class:"hidden",name:t.namespaceInputName(e),value:i.settings.saveParams[e]}).appendTo(i.$container)}))}))})),this.on("submit",(function(t){if(Craft.broadcaster&&Craft.broadcaster.postMessage({event:"saveElement",id:t.response.data.element.id}),i.settings.onSaveElement){var e=Object.assign({},t.response.data,t.response.data.element);delete e.element,delete e.modelName,delete e.message,i.settings.onSaveElement(e)}Craft.Preview.refresh()}))},getParams:function(){var t={};return this.settings.elementType&&(t.elementType=this.settings.elementType),this.settings.elementId?t.elementId=this.settings.elementId:this.$element&&this.$element.data("id")&&(t.elementId=this.$element.data("id")),this.settings.draftId?t.draftId=this.settings.draftId:this.$element&&this.$element.data("draft-id")?t.draftId=this.$element.data("draft-id"):this.settings.revisionId?t.revisionId=this.settings.revisionId:this.$element&&this.$element.data("revision-id")&&(t.revisionId=this.$element.data("revision-id")),this.settings.siteId?t.siteId=this.settings.siteId:this.$element&&this.$element.data("site-id")&&(t.siteId=this.$element.data("site-id")),this.settings.prevalidate&&(t.prevalidate=1),t},handleSubmit:function(t){this.$container.data("elementEditor").handleSubmit(t)}},{defaults:{elementId:null,draftId:null,revisionId:null,elementType:null,siteId:null,prevalidate:!1,saveParams:{},onSaveElement:null,validators:[]}})},7998:function(){Craft.ElementFieldSettings=Garnish.Base.extend({allowMultipleSources:null,$maintainHierarchyField:null,$maintainHierarchyInput:null,$sourcesField:null,$sourceSelect:null,$branchLimitField:null,$maxRelationsField:null,$minRelationsField:null,init:function(t,e,i,s,n,a){this.allowMultipleSources=t,this.$maintainHierarchyField=$("#".concat(e)),this.$maintainHierarchyInput=this.$maintainHierarchyField.find('input[type="checkbox"]'),this.$sourcesField=$("#".concat(i)),this.allowMultipleSources||(this.$sourceSelect=this.$sourcesField.find("select")),this.$branchLimitField=$("#".concat(s)),this.$minRelationsField=$("#".concat(n)),this.$maxRelationsField=$("#".concat(a)),this.updateLimitFields(),this.addListener(this.$maintainHierarchyInput,"change","updateLimitFields"),this.allowMultipleSources?this.$sourcesField.find("[type=checkbox]").each(function(t,e){this.addListener($(e),"change","updateMaintainHierarchyField")}.bind(this)):this.addListener(this.$sourceSelect,"change","updateMaintainHierarchyField"),this.updateMaintainHierarchyField()},updateLimitFields:function(){!this.$maintainHierarchyField.hasClass("hidden")&&this.$maintainHierarchyInput.is(":checked")?(this.$minRelationsField.addClass("hidden"),this.$maxRelationsField.addClass("hidden"),this.$branchLimitField.removeClass("hidden")):(this.$branchLimitField.addClass("hidden"),this.$minRelationsField.removeClass("hidden"),this.$maxRelationsField.removeClass("hidden"))},updateMaintainHierarchyField:function(){var t;if(this.allowMultipleSources){var e=this.$sourcesField.find('[type="checkbox"]:checked');t=1===e.length&&e.data("structure-id")}else t=this.$sourceSelect.children("option:selected").data("structure-id");t?this.$maintainHierarchyField.removeClass("hidden"):this.$maintainHierarchyField.addClass("hidden"),this.updateLimitFields()}})},8895:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.ElementThumbLoader=Garnish.Base.extend({queue:null,workers:[],init:function(){this.queue=[];for(var t=0;t<3;t++)this.workers.push(new Craft.ElementThumbLoader.Worker(this))},load:function(t){for(var e=this,i=t.find(".elementthumb"),s=function(t){var s=i.eq(t),n=s.scrollParent();if("FIELDSET"===n.prop("nodeName")&&(n=n.scrollParent()),n[0]===document.body&&(n=Garnish.$doc),e.isVisible(s,n))e.addToQueue(s[0]);else{var a="thumb"+Math.floor(1e6*Math.random());Craft.ElementThumbLoader.invisibleThumbs[a]=[e,s,n],n.on("scroll.".concat(a),{$thumb:s,$scrollParent:n,key:a},(function(t){e.isVisible(t.data.$thumb,t.data.$scrollParent)&&(delete Craft.ElementThumbLoader.invisibleThumbs[t.data.key],n.off("scroll.".concat(t.data.key)),e.addToQueue(t.data.$thumb[0]))}))}},n=0;n<i.length;n++)s(n)},addToQueue:function(t){this.queue.push(t);for(var e=0;e<this.workers.length;e++)this.workers[e].active||this.workers[e].loadNext()},isVisible:function(t,e){var i,s,n=t.offset().top;return e[0]===document?(i=e.scrollTop(),s=Garnish.$win.height()):(i=e.offset().top,s=e.height()),n>i&&n<i+s+1e3},destroy:function(){for(var t=0;t<this.workers.length;t++)this.workers[t].destroy();this.base()}},{invisibleThumbs:{},retryAll:function(){for(var e in Craft.ElementThumbLoader.invisibleThumbs){var i=(r=Craft.ElementThumbLoader.invisibleThumbs[e],o=3,function(t){if(Array.isArray(t))return t}(r)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(r,o)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(r,o)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),s=i[0],n=i[1],a=i[2];delete Craft.ElementThumbLoader.invisibleThumbs[e],a.off("scroll.".concat(e)),s.load(n.parent())}var r,o}}),Craft.ElementThumbLoader.Worker=Garnish.Base.extend({loader:null,active:!1,init:function(t){this.loader=t},loadNext:function(){var t=this.loader.queue.shift();if(void 0!==t){this.active=!0;var e=$(t);if(e.find("img").length)this.loadNext();else{var i=$("<img/>",{sizes:e.attr("data-sizes"),srcset:e.attr("data-srcset"),alt:e.attr("data-alt")||""});this.addListener(i,"load,error","loadNext"),i.appendTo(e),picturefill({elements:[i[0]]})}}else this.active=!1}})},4233:function(){Craft.ElevatedSessionForm=Garnish.Base.extend({$form:null,inputs:null,init:function(t,e){if(this.$form=$(t),void 0!==e){this.inputs=[],e=$.makeArray(e);for(var i=0;i<e.length;i++)for(var s=$(e[i]),n=0;n<s.length;n++){var a=s.eq(n);this.inputs.push({input:a,val:Garnish.getInputPostVal(a)})}}this.addListener(this.$form,"submit","handleFormSubmit")},handleFormSubmit:function(t){if(Craft.elevatedSessionManager.fetchingTimeout)return t.preventDefault(),void t.stopImmediatePropagation();if(this.inputs){for(var e,i=!1,s=0;s<this.inputs.length;s++)if((e=this.inputs[s].input).data("passwordInput")&&(e=e.data("passwordInput").$currentInput),Garnish.getInputPostVal(e)!==this.inputs[s].val){i=!0;break}if(!i)return}t.preventDefault(),t.stopImmediatePropagation(),Craft.elevatedSessionManager.requireElevatedSession(this.submitForm.bind(this))},submitForm:function(){this.disable(),this.$form.trigger("submit"),this.enable()}})},9699:function(){Craft.ElevatedSessionManager=Garnish.Base.extend({fetchingTimeout:!1,passwordModal:null,$passwordInput:null,$submitBtn:null,$errorPara:null,callback:null,requireElevatedSession:function(t){var e=this;this.callback=t,this.fetchingTimeout=!0,Craft.sendActionRequest("POST","users/get-elevated-session-timeout").then((function(t){e.fetchingTimeout=!1,!1===t.data.timeout||t.data.timeout>=Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout?e.callback():e.showPasswordModal()})).catch((function(){e.fetchingTimeout=!1}))},showPasswordModal:function(){var t=this;if(this.passwordModal)this.passwordModal.show();else{var e=$('<form id="elevatedsessionmodal" class="modal secure fitted"/>'),i=$('<div class="body"><p>'+Craft.t("app","Enter your password to continue.")+"</p></div>").appendTo(e),s=$('<div class="inputcontainer">').appendTo(i),n=$('<div class="flex"/>').appendTo(s),a=$('<div class="flex-grow"/>').appendTo(n),r=$("<td/>").appendTo(n),o=$('<div class="passwordwrapper"/>').appendTo(a);this.$passwordInput=$('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'" autocomplete="current-password"/>').appendTo(o),this.$submitBtn=Craft.ui.createSubmitButton({class:"disabled",label:Craft.t("app","Submit"),spinner:!0}).appendTo(r),this.$errorPara=$('<p class="error"/>').appendTo(i),this.passwordModal=new Garnish.Modal(e,{closeOtherModals:!1,onFadeIn:function(){setTimeout(t.focusPasswordInput.bind(t),100)},onFadeOut:function(){t.$passwordInput.val("")}}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:function(e){t.$passwordInput=e}}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(e,"submit","submitPassword")}},focusPasswordInput:function(){Garnish.isMobileBrowser(!0)||this.$passwordInput.trigger("focus")},validatePassword:function(){return this.$passwordInput.val().length>=6?(this.$submitBtn.removeClass("disabled"),!0):(this.$submitBtn.addClass("disabled"),!1)},submitPassword:function(t){var e=this;if(t&&t.preventDefault(),this.validatePassword()){this.$submitBtn.addClass("loading"),this.clearLoginError();var i={currentPassword:this.$passwordInput.val()};Craft.sendActionRequest("POST","users/start-elevated-session",{data:i}).then((function(t){e.$submitBtn.removeClass("loading"),e.passwordModal.hide(),e.callback()})).catch((function(t){var i=t.response;e.$submitBtn.removeClass("loading"),e.showPasswordError(i.data.message||Craft.t("app","Incorrect password.")),Garnish.shake(e.passwordModal.$container),e.focusPasswordInput()}))}},showPasswordError:function(t){null==t&&(t=Craft.t("app","A server error occurred.")),this.$errorPara.text(t),this.passwordModal.updateSizeAndPosition()},clearLoginError:function(){this.showPasswordError("")}},{minSafeElevatedSessionTimeout:5}),Craft.elevatedSessionManager=new Craft.ElevatedSessionManager},1402:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.EntryIndex=Craft.BaseElementIndex.extend({publishableSections:null,$newEntryBtnGroup:null,$newEntryBtn:null,init:function(t,e,i){this.publishableSections=[],this.on("selectSource",this.updateButton.bind(this)),this.on("selectSite",this.updateButton.bind(this)),this.base(t,e,i)},afterInit:function(){var t=this;this.publishableSections=Craft.publishableSections.filter((function(e){return!!t.getSourceByKey("section:".concat(e.uid))})),this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultSectionHandle){if("singles"===defaultSectionHandle)return"singles";for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("handle")===defaultSectionHandle)return e.data("key")}}return this.base()},updateButton:function(){var e,i=this;if(this.$source&&(e="singles"===this.$source.data("key")?"singles":this.$source.data("handle"),this.publishableSections.length&&function(){i.$newEntryBtnGroup&&i.$newEntryBtnGroup.remove();var s,n=i.publishableSections.find((function(t){return t.handle===e}));i.$newEntryBtnGroup=$('<div class="btngroup submit" data-wrapper/>');var a="new-entry-menu-"+Craft.randomString(10);if(n){var r="index"===i.settings.context?Craft.t("app","New entry"):Craft.t("app","New {section} entry",{section:n.name}),o="index"===i.settings.context?Craft.t("app","New entry in the {section} section",{section:n.name}):r,l="index"===i.settings.context?"link":null;i.$newEntryBtn=Craft.ui.createButton({label:r,ariaLabel:o,spinner:!0,role:l}).addClass("submit add icon").appendTo(i.$newEntryBtnGroup),i.addListener(i.$newEntryBtn,"click mousedown",(function(t){"index"===i.settings.context&&("click"===t.type&&Garnish.isCtrlKeyPressed(t)||"mousedown"===t.type&&1===t.originalEvent.button)?window.open(Craft.getUrl("entries/".concat(n.handle,"/new"))):"click"===t.type&&i._createEntry(n.id)})),i.publishableSections.length>1&&(s=$("<button/>",{type:"button",class:"btn submit menubtn btngroup-btn-last","aria-controls":a,"data-disclosure-trigger":"","aria-label":Craft.t("app","New entry, choose a section")}).appendTo(i.$newEntryBtnGroup))}else i.$newEntryBtn=s=Craft.ui.createButton({label:Craft.t("app","New entry"),ariaLabel:Craft.t("app","New entry, choose a section"),spinner:!0}).addClass("submit add icon menubtn btngroup-btn-last").attr("aria-controls",a).attr("data-disclosure-trigger","").appendTo(i.$newEntryBtnGroup);if(i.addButton(i.$newEntryBtnGroup),s){var h,d=$("<div/>",{id:a,class:"menu menu--disclosure"}).appendTo(i.$newEntryBtnGroup),c=$("<ul/>").appendTo(d),u=function(e,i){var s="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!s){if(Array.isArray(e)||(s=function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(e))||i&&e&&"number"==typeof e.length){s&&(e=s);var n=0,a=function(){};return{s:a,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){s=s.call(e)},n:function(){var t=s.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==s.return||s.return()}finally{if(l)throw r}}}}(i.publishableSections);try{var p=function(){var t=h.value,e="index"===i.settings.context?"link":"button";if("index"===i.settings.context&&-1!==$.inArray(i.siteId,t.sites)||"index"!==i.settings.context&&t!==n){var a=$("<li/>").appendTo(c),r=$("<a/>",{role:"button"===e?"button":null,href:"#",type:"button"===e?"button":null,text:Craft.t("app","New {section} entry",{section:t.name})}).appendTo(a);i.addListener(r,"click",(function(){s.data("trigger").hide(),i._createEntry(t.id)})),"button"===e&&i.addListener(r,"keydown",(function(e){e.keyCode===Garnish.SPACE_KEY&&(e.preventDefault(),s.data("trigger").hide(),i._createEntry(t.id))}))}};for(u.s();!(h=u.n()).done;)p()}catch(t){u.e(t)}finally{u.f()}new Garnish.DisclosureMenu(s)}}(),"index"===this.settings.context)){var s="entries";e&&(s+="/"+e),Craft.setPath(s)}},_createEntry:function(t){var e=this;if(this.$newEntryBtn.hasClass("loading"))console.warn("New entry creation already in progress.");else{var i=this.publishableSections.find((function(e){return e.id===t}));if(!i)throw"Invalid section ID: ".concat(t);this.$newEntryBtn.addClass("loading"),Craft.sendActionRequest("POST","entries/create",{data:{siteId:this.siteId,section:i.handle}}).then((function(t){var s=t.data;"index"===e.settings.context?document.location.href=Craft.getUrl(s.cpEditUrl,{fresh:1}):Craft.createElementEditor(e.elementType,{siteId:e.siteId,elementId:s.entry.id,draftId:s.entry.draftId,params:{fresh:1}}).on("submit",(function(){var t="section:".concat(i.uid);e.sourceKey!==t&&e.selectSourceByKey(t),e.clearSearch(),e.setSelectedSortAttribute("dateCreated","desc"),e.selectElementAfterUpdate(s.entry.id),e.updateElements()}))})).finally((function(){e.$newEntryBtn.removeClass("loading")}))}}}),Craft.registerElementIndexClass("craft\\elements\\Entry",Craft.EntryIndex)},8201:function(){Craft.FieldLayoutDesigner=Garnish.Base.extend({$container:null,$configInput:null,$tabContainer:null,$newTabBtn:null,$sidebar:null,$libraryToggle:null,$selectedLibrary:null,$fieldLibrary:null,$uiLibrary:null,$uiLibraryElements:null,$fieldSearch:null,$clearFieldSearchBtn:null,$fieldGroups:null,$fields:null,tabGrid:null,elementDrag:null,_config:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.FieldLayoutDesigner.defaults),this.$configInput=this.$container.children("input[data-config-input]"),this._config=JSON.parse(this.$configInput.val()),this._config.tabs||(this._config.tabs=[]);var s=this.$container.children(".fld-workspace");this.$tabContainer=s.children(".fld-tabs"),this.$newTabBtn=s.children(".fld-new-tab-btn"),this.$sidebar=this.$container.children(".fld-sidebar"),this.$fieldLibrary=this.$selectedLibrary=this.$sidebar.children(".fld-field-library");var n=this.$fieldLibrary.children(".search");this.$fieldSearch=n.children("input"),this.$clearFieldSearchBtn=n.children(".clear"),this.$fieldGroups=this.$sidebar.find(".fld-field-group"),this.$fields=this.$fieldGroups.children(".fld-element"),this.$uiLibrary=this.$sidebar.children(".fld-ui-library"),this.$uiLibraryElements=this.$uiLibrary.children(),this.tabGrid=new Craft.Grid(this.$tabContainer,{itemSelector:".fld-tab",minColWidth:264,fillMode:"grid",snapToGrid:24});for(var a=this.$tabContainer.children(),r=0;r<a.length;r++)this.initTab($(a[r]));if(this.elementDrag=new Craft.FieldLayoutDesigner.ElementDrag(this),this.settings.customizableTabs&&(this.tabDrag=new Craft.FieldLayoutDesigner.TabDrag(this),this.addListener(this.$newTabBtn,"activate","addTab")),this.settings.customizableUi){var o=this.$sidebar.children(".btngroup");new Craft.Listbox(o,{onChange:function(t){i.$selectedLibrary.addClass("hidden"),i.$selectedLibrary=i["$".concat(t.data("library"),"Library")].removeClass("hidden")}})}this.addListener(this.$fieldSearch,"input",(function(){var t=i.$fieldSearch.val().toLowerCase().replace(/['"]/g,"");if(!t)return i.$fieldLibrary.find(".filtered").removeClass("filtered"),void i.$clearFieldSearchBtn.addClass("hidden");i.$clearFieldSearchBtn.removeClass("hidden");var e=i.$fields.filter('[data-keywords*="'.concat(t,'"]')).add(i.$fieldGroups.filter('[data-name*="'.concat(t,'"]')).children(".fld-element")).removeClass("filtered");i.$fields.not(e).addClass("filtered");for(var s=0;s<i.$fieldGroups.length;s++){var n=i.$fieldGroups.eq(s);n.find(".fld-element:not(.hidden):not(.filtered)").length?n.removeClass("filtered"):n.addClass("filtered")}})),this.addListener(this.$fieldSearch,"keydown",(function(t){switch(t.keyCode){case Garnish.ESC_KEY:i.$fieldSearch.val("").trigger("input");break;case Garnish.RETURN_KEY:t.preventDefault()}})),this.addListener(this.$clearFieldSearchBtn,"click",(function(){i.$fieldSearch.val("").trigger("input")}))},initTab:function(t){return new Craft.FieldLayoutDesigner.Tab(this,t)},removeFieldByHandle:function(t){this.$fields.filter('[data-attribute="'.concat(t,'"]:first')).removeClass("hidden").closest(".fld-field-group").removeClass("hidden")},addTab:function(){if(this.settings.customizableTabs){var t=Craft.escapeHtml(prompt(Craft.t("app","Give your tab a name.")));if(t){var e=$('\n<div class="fld-tab">\n  <div class="tabs">\n    <div class="tab sel draggable">\n      <span>'.concat(t,'</span>\n      <a class="settings icon" title="').concat(Craft.t("app","Settings"),'"></a>\n    </div>\n  </div>\n  <div class="fld-tabcontent"></div>\n</div>\n')).appendTo(this.$tabContainer);this.tabGrid.addItems(e),this.tabDrag.addItems(e),this.initTab(e).updatePositionInConfig()}}},get config(){return this._config},set config(t){this._config=t,this.$configInput.val(JSON.stringify(t))},updateConfig:function(t){var e=t(this.config);!1!==e&&(this.config=e)}},{defaults:{customizableTabs:!0,customizableUi:!0},createSlideout:function createSlideout(contents,js){var $body=$("<div/>",{class:"fld-element-settings-body"});$("<div/>",{class:"fields",html:contents}).appendTo($body);var $footer=$("<div/>",{class:"fld-element-settings-footer"});$("<div/>",{class:"flex-grow"}).appendTo($footer);var $cancelBtn=Craft.ui.createButton({label:Craft.t("app","Close"),spinner:!0}).appendTo($footer);Craft.ui.createSubmitButton({class:"secondary",label:Craft.t("app","Apply"),spinner:!0}).appendTo($footer);var $contents=$body.add($footer),slideout=new Craft.Slideout($contents,{containerElement:"form",containerAttributes:{action:"",method:"post",novalidate:"",class:"fld-element-settings"}});return slideout.on("open",(function(){Garnish.requestAnimationFrame((function(){slideout.$container.find(".text:first").trigger("focus")}))})),$cancelBtn.on("click",(function(){slideout.close()})),js&&eval(js),Craft.initUiElements(slideout.$container),slideout}}),Craft.FieldLayoutDesigner.Tab=Garnish.Base.extend({designer:null,uid:null,$container:null,slideout:null,destroyed:!1,init:function(t,e){this.designer=t,this.$container=e,this.$container.data("fld-tab",this),this.uid=this.$container.data("uid"),this.uid||(this.uid=Craft.uuid(),this.config={uid:this.uid,name:this.$container.find(".tabs .tab span").text(),elements:[]},this.$container.data("settings-namespace",this.designer.$container.data("new-tab-settings-namespace").replace(/\bTAB_UID\b/g,this.uid)),this.$container.data("settings-html",this.designer.$container.data("new-tab-settings-html").replace(/\bTAB_UID\b/g,this.uid).replace(/\bTAB_NAME\b/g,this.config.name)),this.$container.data("settings-js",this.designer.$container.data("new-tab-settings-js").replace(/\bTAB_UID\b/g,this.uid))),this.designer.settings.customizableTabs&&(this.settingsNamespace=this.$container.data("settings-namespace"),this.createMenu());for(var i=this.$container.children(".fld-tabcontent").children(),s=0;s<i.length;s++)this.initElement($(i[s]))},createMenu:function(){var t=this,e=this.$container.find(".tabs .settings");$('<div class="menu" data-align="center"/>').insertAfter(e).append($("<ul/>").append($("<li/>").append($("<a/>",{"data-action":"settings",text:Craft.t("app","Settings")}))).append($("<li/>").append($("<a/>",{"data-action":"remove",text:Craft.t("app","Remove")})))).append($("<hr/>")).append($("<ul/>").append($("<li/>").append($("<a/>",{"data-action":"moveLeft",text:Craft.t("app","Move to the left")}))).append($("<li/>").append($("<a/>",{"data-action":"moveRight",text:Craft.t("app","Move to the right")}))));var i=new Garnish.MenuBtn(e,{onOptionSelect:this.onTabOptionSelect.bind(this)});i.menu.on("show",(function(){t.$container.prev(".fld-tab").length?i.menu.$container.find("[data-action=moveLeft]").removeClass("disabled"):i.menu.$container.find("[data-action=moveLeft]").addClass("disabled"),t.$container.next(".fld-tab").length?i.menu.$container.find("[data-action=moveRight]").removeClass("disabled"):i.menu.$container.find("[data-action=moveRight]").addClass("disabled")}))},onTabOptionSelect:function(t){if(this.designer.settings.customizableTabs)switch($(t).data("action")){case"settings":this.slideout?this.slideout.open():this.createSettings();break;case"remove":this.destroy();break;case"moveLeft":var e=this.$container.prev(".fld-tab");e.length&&(this.$container.insertBefore(e),this.updatePositionInConfig());break;case"moveRight":var i=this.$container.next(".fld-tab");i.length&&(this.$container.insertAfter(i),this.updatePositionInConfig())}},createSettings:function(){var t=this,e=this.$container.data("settings-html"),i=this.$container.data("settings-js");this.slideout=Craft.FieldLayoutDesigner.createSlideout(e,i),this.slideout.$container.on("submit",(function(e){e.preventDefault(),t.applySettings()}))},applySettings:function(){var t=this;if(this.slideout.$container.find('[name$="[name]"]').val()){var e=this.slideout.$container.find("button[type=submit]").addClass("loading"),i=$.extend({},this.config);delete i.elements,Craft.sendActionRequest("POST","fields/apply-layout-tab-settings",{data:{config:i,settingsNamespace:this.settingsNamespace,settings:this.slideout.$container.serialize()}}).then((function(e){t.updateConfig((function(t){return $.extend(e.data.config,{elements:t.elements})}));var i=t.$container.find(".tabs .tab span"),s=i.children(".fld-indicator");e.data.hasConditions?s.length||i.append($("<div/>",{class:"fld-indicator",title:Craft.t("app","This tab is conditional"),"aria-label":Craft.t("app","This tab is conditional"),"data-icon":"condition",role:"img"})):s.length&&s.remove(),t.slideout.close()})).catch((function(t){Craft.cp.displayError(),console.error(t)})).finally((function(){e.removeClass("loading"),t.slideout.close()}))}else Craft.cp.displayError(Craft.t("app","You must specify a tab name."))},initElement:function(t){return new Craft.FieldLayoutDesigner.Element(this,t)},get index(){var t=this;return this.designer.config.tabs.findIndex((function(e){return e.uid===t.uid}))},get config(){var t=this;if(!this.uid)throw"Tab is missing its UID";var e=this.designer.config.tabs.find((function(e){return e.uid===t.uid}));return e||(e={uid:this.uid,elements:[]},this.config=e),e},set config(t){if(!this.destroyed){t.name&&t.name!==this.config.name&&this.$container.find(".tabs .tab span").text(t.name);var e=this.designer.config,i=this.index;if(-1!==i)e.tabs[i]=t;else{var s=$.inArray(this.$container[0],this.$container.parent().children(".fld-tab"));e.tabs.splice(s,0,t)}this.designer.config=e}},updateConfig:function(t){if(!this.destroyed){var e=t(this.config);!1!==e&&(this.config=e)}},updatePositionInConfig:function(){var t=this;this.destroyed||this.designer.updateConfig((function(e){var i=t.config,s=t.index,n=$.inArray(t.$container[0],t.$container.parent().children(".fld-tab"));return-1!==s&&e.tabs.splice(s,1),e.tabs.splice(n,0,i),e}))},destroy:function(){var t=this;if(!this.destroyed){this.destroyed=!0,this.designer.updateConfig((function(e){var i=t.index;return-1!==i&&(e.tabs.splice(i,1),e)}));for(var e=this.$container.find(".fld-element"),i=0;i<e.length;i++)e.eq(i).data("fld-element").destroy();this.designer.tabGrid.removeItems(this.$container),this.designer.tabDrag.removeItems(this.$container),this.$container.remove(),this.base()}}}),Craft.FieldLayoutDesigner.Element=Garnish.Base.extend({tab:null,$container:null,$settingsContainer:null,$editBtn:null,uid:null,isField:!1,attribute:null,requirable:!1,hasCustomWidth:!1,hasSettings:!1,settingsNamespace:null,slideout:null,init:function(t,e){var i=this;this.tab=t,this.$container=e,this.$container.data("fld-element",this),this.uid=this.$container.data("uid"),this.uid||(this.uid=Craft.uuid(),this.config=$.extend(this.$container.data("config"),{uid:this.uid})),this.isField=this.$container.hasClass("fld-field"),this.requirable=this.isField&&Garnish.hasAttr(this.$container,"data-requirable"),this.isField&&(this.attribute=this.$container.data("attribute")),this.settingsNamespace=this.$container.data("settings-namespace").replace(/\bELEMENT_UID\b/g,this.uid);var s=(this.$container.data("settings-html")||"").replace(/\bELEMENT_UID\b/g,this.uid),n=this.requirable&&this.$container.hasClass("fld-required");if(this.hasCustomWidth=this.tab.designer.settings.customizableUi&&Garnish.hasAttr(this.$container,"data-has-custom-width"),this.hasSettings=s||this.requirable,this.hasSettings){this.$settingsContainer=$("<div/>",{class:"hidden"}),this.$editBtn=$("<a/>",{role:"button",tabindex:0,class:"settings icon",title:Craft.t("app","Edit")});var a=function(){i.slideout?i.slideout.open():i.createSettings(s,n)};this.$editBtn.on("click",a),this.$container.on("dblclick",a)}this.initUi(),this.$container.attr("data-keywords",null),this.$container.attr("data-settings-html",null)},initUi:function(){var t=this;this.hasCustomWidth&&new Craft.SlidePicker(this.config.width||100,{min:25,max:100,step:25,valueLabel:function(t){return Craft.t("app","{pct} width",{pct:"".concat(t,"%")})},onChange:function(e){t.updateConfig((function(t){return t.width=e,t}))}}).$container.appendTo(this.$container),this.hasSettings&&this.$editBtn.appendTo(this.$container)},createSettings:function(t,e){var i=this,s=(this.$container.data("settings-js")||"").replace(/\bELEMENT_UID\b/g,this.uid);if(this.slideout=Craft.FieldLayoutDesigner.createSlideout(t,s),this.slideout.$container.on("submit",(function(t){t.preventDefault(),i.applySettings()})),this.requirable){var n=this.slideout.$container.find(".fields:first");Craft.ui.createLightswitchField({label:Craft.t("app","Required"),name:"".concat(this.settingsNamespace,"[required]"),on:e}).prependTo(n)}this.trigger("createSettings")},applySettings:function(){var t=this,e=this.slideout.$container.find("button[type=submit]").addClass("loading");Craft.sendActionRequest("POST","fields/apply-layout-element-settings",{data:{config:this.config,settingsNamespace:this.settingsNamespace,settings:this.slideout.$container.serialize()}}).then((function(e){t.config=e.data.config,t.$editBtn.detach(),t.$container.html($(e.data.selectorHtml).html()),t.initUi()})).catch((function(t){Craft.cp.displayError(),console.error(t)})).finally((function(){e.removeClass("loading"),t.updateRequiredClass(),t.slideout.close()}))},updateRequiredClass:function(){this.requirable&&(this.config.required?this.$container.addClass("fld-required"):this.$container.removeClass("fld-required"))},get index(){var t=this,e=this.tab.config;return void 0===e?-1:e.elements.findIndex((function(e){return e.uid===t.uid}))},get config(){var t=this;if(!this.uid)throw"Tab is missing its UID";var e=this.tab.config.elements.find((function(e){return e.uid===t.uid}));return e||(e={uid:this.uid},this.config=e),e},set config(t){var e=this.tab.config,i=this.index;if(-1!==i)e.elements[i]=t;else{var s=$.inArray(this.$container[0],this.$container.parent().children(".fld-element"));e.elements.splice(s,0,t)}this.tab.config=e},updateConfig:function(t){var e=t(this.config);!1!==e&&(this.config=e)},updatePositionInConfig:function(){var t=this;this.tab.updateConfig((function(e){var i=t.config,s=t.index,n=$.inArray(t.$container[0],t.$container.parent().children(".fld-element"));return-1!==s&&e.elements.splice(s,1),e.elements.splice(n,0,i),e}))},destroy:function(){var t=this;this.tab.updateConfig((function(e){var i=t.index;return-1!==i&&(e.elements.splice(i,1),e)})),this.tab.designer.elementDrag.removeItems(this.$container),this.$container.remove(),this.isField&&this.tab.designer.removeFieldByHandle(this.attribute),this.base()}}),Craft.FieldLayoutDesigner.BaseDrag=Garnish.Drag.extend({designer:null,$insertion:null,showingInsertion:!1,$caboose:null,init:function(t,e){this.designer=t,this.base(this.findItems(),e)},onDragStart:function(){this.base(),this.$insertion=this.createInsertion(),this.$caboose=this.createCaboose(),this.$items=$().add(this.$items.add(this.$caboose)),Garnish.$bod.addClass("dragging")},removeCaboose:function(){this.$items=this.$items.not(this.$caboose),this.$caboose.remove()},swapDraggeeWithInsertion:function(){this.$insertion.insertBefore(this.$draggee),this.$draggee.detach(),this.$items=$().add(this.$items.not(this.$draggee).add(this.$insertion)),this.showingInsertion=!0},swapInsertionWithDraggee:function(){this.$insertion.replaceWith(this.$draggee),this.$items=$().add(this.$items.not(this.$insertion).add(this.$draggee)),this.showingInsertion=!1},setMidpoints:function(){for(var t=0;t<this.$items.length;t++){var e=$(this.$items[t]),i=e.offset();e.hasClass("unused")||e.data("midpoint",{left:i.left+e.outerWidth()/2,top:i.top+e.outerHeight()/2})}},getClosestItem:function(){for(this.getClosestItem._closestItem=null,this.getClosestItem._closestItemMouseDiff=null,this.getClosestItem._i=0;this.getClosestItem._i<this.$items.length;this.getClosestItem._i++)this.getClosestItem._$item=$(this.$items[this.getClosestItem._i]),this.getClosestItem._midpoint=this.getClosestItem._$item.data("midpoint"),this.getClosestItem._midpoint&&(this.getClosestItem._mouseDiff=Garnish.getDist(this.getClosestItem._midpoint.left,this.getClosestItem._midpoint.top,this.mouseX,this.mouseY),(null===this.getClosestItem._closestItem||this.getClosestItem._mouseDiff<this.getClosestItem._closestItemMouseDiff)&&(this.getClosestItem._closestItem=this.getClosestItem._$item[0],this.getClosestItem._closestItemMouseDiff=this.getClosestItem._mouseDiff));return this.getClosestItem._closestItem},checkForNewClosestItem:function(){this.checkForNewClosestItem._closestItem=this.getClosestItem(),this.checkForNewClosestItem._closestItem!==this.$insertion[0]&&(this.showingInsertion&&$.inArray(this.$insertion[0],this.$items)<$.inArray(this.checkForNewClosestItem._closestItem,this.$items)&&-1===$.inArray(this.checkForNewClosestItem._closestItem,this.$caboose)?this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem):this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem),this.$items=$().add(this.$items.add(this.$insertion)),this.showingInsertion=!0,this.designer.tabGrid.refreshCols(!0),this.setMidpoints())},onDragStop:function(){var t=this;this.showingInsertion&&this.swapInsertionWithDraggee(),this.removeCaboose(),this.designer.tabGrid.refreshCols(!0);var e=this.$draggee.offset();!e||0===e.top&&0===e.left?(this.$draggee.css({display:this.draggeeDisplay,visibility:"visible",opacity:0}).velocity({opacity:1},Garnish.FX_DURATION),this.helpers[0].velocity({opacity:0},Garnish.FX_DURATION,(function(){t._showDraggee()}))):this.returnHelpersToDraggees(),this.base(),Garnish.$bod.removeClass("dragging")}}),Craft.FieldLayoutDesigner.TabDrag=Craft.FieldLayoutDesigner.BaseDrag.extend({init:function(t){this.base(t,{handle:".tab"})},findItems:function(){return this.designer.$tabContainer.find("> div.fld-tab")},onDragStart:function(){this.base(),this.swapDraggeeWithInsertion(),this.setMidpoints()},swapDraggeeWithInsertion:function(){this.base(),this.designer.tabGrid.removeItems(this.$draggee),this.designer.tabGrid.addItems(this.$insertion)},swapInsertionWithDraggee:function(){this.base(),this.designer.tabGrid.removeItems(this.$insertion),this.designer.tabGrid.addItems(this.$draggee)},onDrag:function(){this.checkForNewClosestItem(),this.base()},onDragStop:function(){this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:"hidden"}),this.$draggee.data("fld-tab").updatePositionInConfig()},createCaboose:function(){var t=$('<div class="fld-tab fld-tab-caboose"/>').appendTo(this.designer.$tabContainer);return this.designer.tabGrid.addItems(t),t},removeCaboose:function(){this.base(),this.designer.tabGrid.removeItems(this.$caboose)},createInsertion:function(){var t=this.$draggee.find(".tab");return $('\n<div class="fld-tab fld-insertion" style="height: '.concat(this.$draggee.height(),'px;">\n  <div class="tabs"><div class="tab sel draggable" style="width: ').concat(t.outerWidth(),"px; height: ").concat(t.outerHeight()+2,'px;"></div></div>\n  <div class="fld-tabcontent" style="height: ').concat(this.$draggee.find(".fld-tabcontent").height()-2,'px;"></div>\n</div>\n'))}}),Craft.FieldLayoutDesigner.ElementDrag=Craft.FieldLayoutDesigner.BaseDrag.extend({draggingLibraryElement:!1,draggingField:!1,originalTab:null,onDragStart:function(){this.base(),this.draggingLibraryElement=this.$draggee.hasClass("unused"),this.draggingField=this.$draggee.hasClass("fld-field"),this.draggingLibraryElement&&!this.draggingField&&this.$draggee.css({display:this.draggeeDisplay,visibility:"visible"}),this.draggingLibraryElement?this.originalTab=null:(this.originalTab=this.$draggee.closest(".fld-tab").data("fld-tab"),this.swapDraggeeWithInsertion()),this.setMidpoints()},onDrag:function(){this.isDraggeeMandatory()||this.isHoveringOverTab()?this.checkForNewClosestItem():this.showingInsertion&&(this.$insertion.remove(),this.$items=$().add(this.$items.not(this.$insertion)),this.showingInsertion=!1,this.designer.tabGrid.refreshCols(!0),this.setMidpoints()),this.base()},isDraggeeMandatory:function(){return Garnish.hasAttr(this.$draggee,"data-mandatory")},isHoveringOverTab:function(){for(var t=0;t<this.designer.tabGrid.$items.length;t++)if(Garnish.hitTest(this.mouseX,this.mouseY,this.designer.tabGrid.$items.eq(t)))return!0;return!1},findItems:function(){return this.designer.$tabContainer.find(".fld-element").add(this.designer.$sidebar.find(".fld-element"))},createCaboose:function(){for(var t=$(),e=this.designer.$tabContainer.find("> .fld-tab > .fld-tabcontent"),i=0;i<e.length;i++)t=t.add($("<div/>").appendTo(e[i]));return t},createInsertion:function(){return $('<div class="fld-element fld-insertion" style="height: '.concat(this.$draggee.outerHeight(),'px;"/>'))},onDragStop:function(){var t=this.showingInsertion;if(t){if(this.draggingLibraryElement){var e=this.$draggee.clone().removeClass("unused");this.draggingField&&(this.$draggee.css({visibility:"inherit",display:"field"}).addClass("hidden"),0===this.$draggee.siblings(".fld-field:not(.hidden)").length&&this.$draggee.closest(".fld-field-group").addClass("hidden")),this.$draggee=e,this.addItems(e)}}else if(!this.draggingLibraryElement){var i=this.draggingField?this.designer.$fields.filter('[data-attribute="'.concat(this.$draggee.data("attribute"),'"]:first')):this.designer.$uiLibraryElements.filter('[data-type="'.concat(this.$draggee.data("type"),'"]:first'));this.draggingField&&(i.removeClass("hidden"),i.closest(".fld-field-group").removeClass("hidden")),this.$draggee.data("fld-element").destroy(),this.$draggee=i}if(this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:this.draggingField||t?"hidden":"visible"}),t){var s,n=this.$draggee.closest(".fld-tab").data("fld-tab");if(this.draggingLibraryElement)s=n.initElement(this.$draggee);else if(s=this.$draggee.data("fld-element"),n!==this.originalTab){var a=s.config;this.originalTab.updateConfig((function(t){var e=s.index;return-1!==e&&(t.elements.splice(e,1),t)})),this.$draggee.data("fld-element").tab=n,s.config=a}s.updatePositionInConfig()}}})},3347:function(){Craft.FieldToggle=Garnish.Base.extend({$toggle:null,targetPrefix:null,targetSelector:null,reverseTargetSelector:null,_$target:null,_$reverseTarget:null,type:null,init:function(t){switch(this.$toggle=$(t),this.$toggle.data("fieldtoggle")&&(console.warn("Double-instantiating a field toggle on an element"),this.$toggle.data("fieldtoggle").destroy()),this.$toggle.data("fieldtoggle",this),this.type=this.getType(),"select"===this.type||"fieldset"===this.type?this.targetPrefix=this.$toggle.attr("data-target-prefix")||"":(this.targetSelector=this.normalizeTargetSelector(this.$toggle.data("target")),this.reverseTargetSelector=this.normalizeTargetSelector(this.$toggle.data("reverse-target"))),this.findTargets(),this.type){case"link":this.addListener(this.$toggle,"click","onToggleChange");break;case"fieldset":this.addListener(this.$toggle.find("input"),"change","onToggleChange");break;default:this.addListener(this.$toggle,"change","onToggleChange"),this.onToggleChange()}},normalizeTargetSelector:function(t){return t&&!t.match(/^[#\.]/)&&(t="#"+t),t},getType:function(){var t=this.$toggle.prop("nodeName");if("INPUT"===t&&"checkbox"===this.$toggle.attr("type")||"checkbox"===this.$toggle.attr("role")||"switch"===this.$toggle.attr("role"))return"checkbox";switch(t){case"SELECT":return Garnish.hasAttr(this.$toggle,"data-boolean-menu")?"booleanMenu":"select";case"A":return"link";default:return"fieldset"}},findTargets:function(){"select"===this.type||"fieldset"===this.type?(this.getToggleVal(),this._$target=$(this.normalizeTargetSelector(this.targetPrefix+this.getToggleVal()))):(this.targetSelector&&(this._$target=$(this.targetSelector)),this.reverseTargetSelector&&(this._$reverseTarget=$(this.reverseTargetSelector)))},getToggleVal:function(){switch(this.type){case"checkbox":return void 0!==this.$toggle.prop("checked")?this.$toggle.prop("checked"):"true"===this.$toggle.attr("aria-checked");case"booleanMenu":var t=this.$toggle.data("boolean");if(void 0!==t)return t;var e=this.$toggle.val();return e&&"0"!==e;default:var i;return null==(i="fieldset"===this.type?this.$toggle.find("input:checked:first").val():Garnish.getInputPostVal(this.$toggle))?null:i.replace(/[^\w]+/g,"-")}},onToggleChange:function(){"select"===this.type||"fieldset"===this.type?(this.hideTarget(this._$target),this.findTargets(),this.showTarget(this._$target)):(this.findTargets(),"link"===this.type?this.onToggleChange._show=this.$toggle.hasClass("collapsed")||!this.$toggle.hasClass("expanded"):this.onToggleChange._show=!!this.getToggleVal(),this.onToggleChange._show?(this.showTarget(this._$target),this.hideTarget(this._$reverseTarget)):(this.hideTarget(this._$target),this.showTarget(this._$reverseTarget)),delete this.onToggleChange._show)},showTarget:function(t){var e=this;if(t&&t.length){if(this.showTarget._currentHeight=t.height(),t.removeClass("hidden"),"select"!==this.type&&"fieldset"!==this.type){"link"===this.type&&(this.$toggle.removeClass("collapsed"),this.$toggle.addClass("expanded"));for(var i=0;i<t.length;i++)!function(t){"SPAN"!==t.prop("nodeName")&&(t.height("auto"),e.showTarget._targetHeight=t.height(),t.css({height:e.showTarget._currentHeight,overflow:"hidden"}),t.velocity("stop"),t.velocity({height:e.showTarget._targetHeight},"fast",(function(){t.css({height:"",overflow:""})})))}(t.eq(i));delete this.showTarget._targetHeight}delete this.showTarget._currentHeight,Garnish.$win.trigger("resize")}},hideTarget:function(t){if(t&&t.length)if("select"===this.type||"fieldset"===this.type)t.addClass("hidden");else{"link"===this.type&&(this.$toggle.removeClass("expanded"),this.$toggle.addClass("collapsed"));for(var e=0;e<t.length;e++)!function(t){t.hasClass("hidden")||("SPAN"===t.prop("nodeName")?t.addClass("hidden"):(t.css("overflow","hidden"),t.velocity("stop"),t.velocity({height:0},"fast",(function(){t.addClass("hidden")}))))}(t.eq(e))}},destroy:function(){this.$toggle.removeData("fieldtoggle"),this.base()}})},9478:function(){Craft.Grid=Garnish.Base.extend({$container:null,$items:null,items:null,totalCols:null,colGutterDrop:null,colPctWidth:null,possibleItemColspans:null,possibleItemPositionsByColspan:null,itemPositions:null,itemColspansByPosition:null,layouts:null,layout:null,itemHeights:null,leftPadding:null,_refreshingCols:!1,_refreshColsAfterRefresh:!1,_forceRefreshColsAfterRefresh:!1,init:function(t,e){var i=this;this.$container=$(t),this.$container.data("grid")&&(console.warn("Double-instantiating a grid on an element"),this.$container.data("grid").destroy()),this.$container.data("grid",this),this.setSettings(e,Craft.Grid.defaults),this.handleContainerHeightProxy=function(){i.refreshCols(!1,!0)},this.$items=this.$container.children(this.settings.itemSelector),this.setItems(),this.refreshCols(!0,!1),Garnish.$doc.ready((function(){i.refreshCols(!1,!1)}))},addItems:function(t){this.$items=$().add(this.$items.add(t)),this.setItems(),this.refreshCols(!0,!0)},removeItems:function(t){this.$items=$().add(this.$items.not(t)),this.setItems(),this.refreshCols(!0,!0)},resetItemOrder:function(){this.$items=$().add(this.$items),this.setItems(),this.refreshCols(!0,!0)},setItems:function(){for(this.setItems._={},this.items=[],this.setItems._.i=0;this.setItems._.i<this.$items.length;this.setItems._.i++)this.items.push($(this.$items[this.setItems._.i]));delete this.setItems._},refreshCols:function(t){if(this._refreshingCols)return this._refreshColsAfterRefresh=!0,void(t&&(this._forceRefreshColsAfterRefresh=!0));if(this._refreshingCols=!0,this.items.length)if(this.refreshCols._={},this.refreshCols._.oldHeight=this.$container[0].style.height,this.$container[0].style.height=1,this.refreshCols._.scrollHeight=this.$container[0].scrollHeight,this.$container[0].style.height=this.refreshCols._.oldHeight,0!==this.refreshCols._.scrollHeight)if(this.settings.cols?this.refreshCols._.totalCols=this.settings.cols:(this.refreshCols._.totalCols=Math.floor(this.$container.width()/this.settings.minColWidth),null!==this.totalCols&&this.refreshCols._.totalCols>this.totalCols&&(this.refreshCols._.totalCols=Math.floor((this.$container.width()-20)/this.settings.minColWidth)),this.settings.maxCols&&this.refreshCols._.totalCols>this.settings.maxCols&&(this.refreshCols._.totalCols=this.settings.maxCols)),0===this.refreshCols._.totalCols&&(this.refreshCols._.totalCols=1),!0===t||this.totalCols!==this.refreshCols._.totalCols){if(this.totalCols=this.refreshCols._.totalCols,this.colGutterDrop=this.settings.gutter*(this.totalCols-1)/this.totalCols,this.removeListener(this.$container,"resize"),"grid"===this.settings.fillMode)for(this.refreshCols._.itemIndex=0;this.refreshCols._.itemIndex<this.items.length;){for(this.refreshCols._.tallestItemHeight=-1,this.refreshCols._.colIndex=0,this.refreshCols._.i=this.refreshCols._.itemIndex;this.refreshCols._.i<this.refreshCols._.itemIndex+this.totalCols&&this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.refreshCols._.itemHeight=this.items[this.refreshCols._.i].height("auto").height(),this.refreshCols._.itemHeight>this.refreshCols._.tallestItemHeight&&(this.refreshCols._.tallestItemHeight=this.refreshCols._.itemHeight),this.refreshCols._.colIndex++;for(this.settings.snapToGrid&&(this.refreshCols._.remainder=this.refreshCols._.tallestItemHeight%this.settings.snapToGrid,this.refreshCols._.remainder&&(this.refreshCols._.tallestItemHeight+=this.settings.snapToGrid-this.refreshCols._.remainder)),this.refreshCols._.i=this.refreshCols._.itemIndex;this.refreshCols._.i<this.refreshCols._.itemIndex+this.totalCols&&this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.items[this.refreshCols._.i].height(this.refreshCols._.tallestItemHeight);this.refreshCols._.itemIndex+=this.totalCols}else if(this.removeListener(this.$items,"resize"),1===this.totalCols)this.$container.height("auto"),this.$items.show().css({position:"relative",width:"auto",top:0}).css(Craft.left,0);else{for(this.$items.css("position","absolute"),this.colPctWidth=100/this.totalCols,this.layouts=[],this.itemPositions=[],this.itemColspansByPosition=[],this.possibleItemColspans=[],this.possibleItemPositionsByColspan=[],this.itemHeightsByColspan=[],this.refreshCols._.item=0;this.refreshCols._.item<this.items.length;this.refreshCols._.item++)for(this.possibleItemColspans[this.refreshCols._.item]=[],this.possibleItemPositionsByColspan[this.refreshCols._.item]={},this.itemHeightsByColspan[this.refreshCols._.item]={},this.refreshCols._.$item=this.items[this.refreshCols._.item].show(),this.refreshCols._.positionRight="right"===this.refreshCols._.$item.data("position"),this.refreshCols._.positionLeft="left"===this.refreshCols._.$item.data("position"),this.refreshCols._.minColspan=this.refreshCols._.$item.data("colspan")?this.refreshCols._.$item.data("colspan"):this.refreshCols._.$item.data("min-colspan")?this.refreshCols._.$item.data("min-colspan"):1,this.refreshCols._.maxColspan=this.refreshCols._.$item.data("colspan")?this.refreshCols._.$item.data("colspan"):this.refreshCols._.$item.data("max-colspan")?this.refreshCols._.$item.data("max-colspan"):this.totalCols,this.refreshCols._.minColspan>this.totalCols&&(this.refreshCols._.minColspan=this.totalCols),this.refreshCols._.maxColspan>this.totalCols&&(this.refreshCols._.maxColspan=this.totalCols),this.refreshCols._.colspan=this.refreshCols._.minColspan;this.refreshCols._.colspan<=this.refreshCols._.maxColspan;this.refreshCols._.colspan++)for(this.refreshCols._.$item.css("width",this.getItemWidthCss(this.refreshCols._.colspan)),this.itemHeightsByColspan[this.refreshCols._.item][this.refreshCols._.colspan]=this.refreshCols._.$item.outerHeight(),this.possibleItemColspans[this.refreshCols._.item].push(this.refreshCols._.colspan),this.possibleItemPositionsByColspan[this.refreshCols._.item][this.refreshCols._.colspan]=[],this.refreshCols._.positionLeft?(this.refreshCols._.minPosition=0,this.refreshCols._.maxPosition=0):this.refreshCols._.positionRight?(this.refreshCols._.minPosition=this.totalCols-this.refreshCols._.colspan,this.refreshCols._.maxPosition=this.refreshCols._.minPosition):(this.refreshCols._.minPosition=0,this.refreshCols._.maxPosition=this.totalCols-this.refreshCols._.colspan),this.refreshCols._.position=this.refreshCols._.minPosition;this.refreshCols._.position<=this.refreshCols._.maxPosition;this.refreshCols._.position++)this.possibleItemPositionsByColspan[this.refreshCols._.item][this.refreshCols._.colspan].push(this.refreshCols._.position);for(this.refreshCols._.colHeights=[],this.refreshCols._.i=0;this.refreshCols._.i<this.totalCols;this.refreshCols._.i++)this.refreshCols._.colHeights.push(0);for(this.createLayouts(0,[],[],this.refreshCols._.colHeights,0),this.refreshCols._.layoutTotalCols=[],this.refreshCols._.i=0;this.refreshCols._.i<this.layouts.length;this.refreshCols._.i++)for(this.refreshCols._.layoutTotalCols[this.refreshCols._.i]=0,this.refreshCols._.j=0;this.refreshCols._.j<this.totalCols;this.refreshCols._.j++)this.layouts[this.refreshCols._.i].colHeights[this.refreshCols._.j]&&this.refreshCols._.layoutTotalCols[this.refreshCols._.i]++;for(this.refreshCols._.highestTotalCols=Math.max.apply(null,this.refreshCols._.layoutTotalCols),this.refreshCols._.i=this.layouts.length-1;this.refreshCols._.i>=0;this.refreshCols._.i--)this.refreshCols._.layoutTotalCols[this.refreshCols._.i]!==this.refreshCols._.highestTotalCols&&this.layouts.splice(this.refreshCols._.i,1);for(this.refreshCols._.layoutHeights=[],this.refreshCols._.i=0;this.refreshCols._.i<this.layouts.length;this.refreshCols._.i++)this.refreshCols._.layoutHeights.push(Math.max.apply(null,this.layouts[this.refreshCols._.i].colHeights));for(this.refreshCols._.shortestHeight=Math.min.apply(null,this.refreshCols._.layoutHeights),this.refreshCols._.shortestLayouts=[],this.refreshCols._.emptySpaces=[],this.refreshCols._.i=0;this.refreshCols._.i<this.refreshCols._.layoutHeights.length;this.refreshCols._.i++)if(this.refreshCols._.layoutHeights[this.refreshCols._.i]===this.refreshCols._.shortestHeight){for(this.refreshCols._.shortestLayouts.push(this.layouts[this.refreshCols._.i]),this.refreshCols._.emptySpace=this.layouts[this.refreshCols._.i].emptySpace,this.refreshCols._.j=0;this.refreshCols._.j<this.totalCols;this.refreshCols._.j++)this.refreshCols._.emptySpace+=this.refreshCols._.shortestHeight-this.layouts[this.refreshCols._.i].colHeights[this.refreshCols._.j];this.refreshCols._.emptySpaces.push(this.refreshCols._.emptySpace)}for(this.layout=this.refreshCols._.shortestLayouts[$.inArray(Math.min.apply(null,this.refreshCols._.emptySpaces),this.refreshCols._.emptySpaces)],this.refreshCols._.i=0;this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.refreshCols._.css={width:this.getItemWidthCss(this.layout.colspans[this.refreshCols._.i])},this.refreshCols._.css[Craft.left]=this.getItemLeftPosCss(this.layout.positions[this.refreshCols._.i]),this.items[this.refreshCols._.i].css(this.refreshCols._.css);this.isSimpleLayout()?(this.$container.height("auto"),this.$items.css({position:"relative",top:0,"margin-bottom":this.settings.gutter+"px"})):(this.$items.css("position","absolute"),this.positionItems(),this.addListener(this.$items,"resize","onItemResize"))}this.completeRefreshCols(),this.addListener(this.$container,"resize",this.handleContainerHeightProxy),this.onRefreshCols()}else this.completeRefreshCols();else this.completeRefreshCols();else this.completeRefreshCols()},completeRefreshCols:function(){var t=this;if(void 0!==this.refreshCols._&&delete this.refreshCols._,this._refreshingCols=!1,this._refreshColsAfterRefresh){var e=this._forceRefreshColsAfterRefresh;this._refreshColsAfterRefresh=!1,this._forceRefreshColsAfterRefresh=!1,Garnish.requestAnimationFrame((function(){t.refreshCols(e)}))}},getItemWidth:function(t){return this.colPctWidth*t},getItemWidthCss:function(t){return"calc("+this.getItemWidth(t)+"% - "+this.colGutterDrop+"px)"},getItemWidthInPx:function(t){return this.getItemWidth(t)/100*this.$container.width()-this.colGutterDrop},getItemLeftPosCss:function(t){return"calc(("+this.getItemWidth(1)+"% + "+(this.settings.gutter-this.colGutterDrop)+"px) * "+t+")"},getItemLeftPosInPx:function(t){return(this.getItemWidth(1)/100*this.$container.width()+(this.settings.gutter-this.colGutterDrop))*t},createLayouts:function(t,e,i,s,n){new Craft.Grid.LayoutGenerator(this).createLayouts(t,e,i,s,n)},isSimpleLayout:function(){for(this.isSimpleLayout._={},this.isSimpleLayout._.i=0;this.isSimpleLayout._.i<this.layout.positions.length;this.isSimpleLayout._.i++)if(0!==this.layout.positions[this.isSimpleLayout._.i])return delete this.isSimpleLayout._,!1;return delete this.isSimpleLayout._,!0},positionItems:function(){for(this.positionItems._={},this.positionItems._.colHeights=[],this.positionItems._.i=0;this.positionItems._.i<this.totalCols;this.positionItems._.i++)this.positionItems._.colHeights.push(0);for(this.positionItems._.i=0;this.positionItems._.i<this.items.length;this.positionItems._.i++){for(this.positionItems._.endingCol=this.layout.positions[this.positionItems._.i]+this.layout.colspans[this.positionItems._.i]-1,this.positionItems._.affectedColHeights=[],this.positionItems._.col=this.layout.positions[this.positionItems._.i];this.positionItems._.col<=this.positionItems._.endingCol;this.positionItems._.col++)this.positionItems._.affectedColHeights.push(this.positionItems._.colHeights[this.positionItems._.col]);for(this.positionItems._.top=Math.max.apply(null,this.positionItems._.affectedColHeights),this.positionItems._.top>0&&(this.positionItems._.top+=this.settings.gutter),this.items[this.positionItems._.i].css("top",this.positionItems._.top),this.positionItems._.col=this.layout.positions[this.positionItems._.i];this.positionItems._.col<=this.positionItems._.endingCol;this.positionItems._.col++)this.positionItems._.colHeights[this.positionItems._.col]=this.positionItems._.top+this.itemHeightsByColspan[this.positionItems._.i][this.layout.colspans[this.positionItems._.i]]}this.$container.height(Math.max.apply(null,this.positionItems._.colHeights)),delete this.positionItems._},onItemResize:function(t){this.onItemResize._={},t.stopPropagation(),this.onItemResize._.item=$.inArray(t.currentTarget,this.$items),-1!==this.onItemResize._.item&&(this.onItemResize._.newHeight=this.items[this.onItemResize._.item].outerHeight(),this.onItemResize._.newHeight!==this.itemHeightsByColspan[this.onItemResize._.item][this.layout.colspans[this.onItemResize._.item]]&&(this.itemHeightsByColspan[this.onItemResize._.item][this.layout.colspans[this.onItemResize._.item]]=this.onItemResize._.newHeight,this.positionItems(!1))),delete this.onItemResize._},onRefreshCols:function(){this.trigger("refreshCols"),this.settings.onRefreshCols()},destroy:function(){this.$container.removeData("grid"),this.base()}},{defaults:{itemSelector:".item",cols:null,maxCols:null,minColWidth:320,gutter:14,fillMode:"top",colClass:"col",snapToGrid:null,onRefreshCols:$.noop}}),Craft.Grid.LayoutGenerator=Garnish.Base.extend({grid:null,_:null,init:function(t){this.grid=t},createLayouts:function(t,e,i,s,n){for(this._={},this._.c=0;this._.c<this.grid.possibleItemColspans[t].length;this._.c++){for(this._.colspan=this.grid.possibleItemColspans[t][this._.c],this._.tallestColHeightsByPosition=[],this._.p=0;this._.p<this.grid.possibleItemPositionsByColspan[t][this._.colspan].length;this._.p++){for(this._.position=this.grid.possibleItemPositionsByColspan[t][this._.colspan][this._.p],this._.colHeightsForPosition=[],this._.endingCol=this._.position+this._.colspan-1,this._.col=this._.position;this._.col<=this._.endingCol;this._.col++)this._.colHeightsForPosition.push(s[this._.col]);this._.tallestColHeightsByPosition[this._.p]=Math.max.apply(null,this._.colHeightsForPosition)}for(this._.p=$.inArray(Math.min.apply(null,this._.tallestColHeightsByPosition),this._.tallestColHeightsByPosition),this._.position=this.grid.possibleItemPositionsByColspan[t][this._.colspan][this._.p],this._.positions=e.slice(0),this._.colspans=i.slice(0),this._.colHeights=s.slice(0),this._.emptySpace=n,this._.positions.push(this._.position),this._.colspans.push(this._.colspan),this._.tallestColHeight=this._.tallestColHeightsByPosition[this._.p],this._.endingCol=this._.position+this._.colspan-1,this._.col=this._.position;this._.col<=this._.endingCol;this._.col++)this._.emptySpace+=this._.tallestColHeight-this._.colHeights[this._.col],this._.colHeights[this._.col]=this._.tallestColHeight+this.grid.itemHeightsByColspan[t][this._.colspan];t===this.grid.items.length-1?this.grid.layouts.push({positions:this._.positions,colspans:this._.colspans,colHeights:this._.colHeights,emptySpace:this._.emptySpace}):this.grid.createLayouts(t+1,this._.positions,this._.colspans,this._.colHeights,this._.emptySpace)}delete this._}})},2387:function(){Craft.HandleGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){var e=t.replace(/<(.*?)>/g,"");e=(e=e.replace(/['"‘’“”\[\]\(\)\{\}:]/g,"")).toLowerCase(),e=Craft.asciiString(e),this.settings.allowNonAlphaStart||(e=e.replace(/^[^a-z]+/,""));var i=Craft.filterArray(e.split(/[^a-z0-9]+/));if(e="","snake"===Craft.handleCasing)return i.join("_");for(var s=0;s<i.length;s++)"pascal"!==Craft.handleCasing&&0===s?e+=i[s]:e+=i[s].charAt(0).toUpperCase()+i[s].substring(1);return e}})},7966:function(){Craft.ImageUpload=Garnish.Base.extend({$container:null,progressBar:null,uploader:null,init:function(t){this.setSettings(t,Craft.ImageUpload.defaults),this.initImageUpload()},initImageUpload:function(){this.$container=$(this.settings.containerSelector),this.progressBar=new Craft.ProgressBar($('<div class="progress-shade"></div>').appendTo(this.$container));var t={url:Craft.getActionUrl(this.settings.uploadAction),formData:this.settings.postParameters,fileInput:this.$container.find(this.settings.fileInputSelector),paramName:this.settings.uploadParamName};void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(t.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),t.events={},t.events.fileuploadstart=this._onUploadStart.bind(this),t.events.fileuploadprogressall=this._onUploadProgress.bind(this),t.events.fileuploaddone=this._onUploadComplete.bind(this),t.events.fileuploadfail=this._onUploadFailure.bind(this),this.uploader=new Craft.Uploader(this.$container,t),this.initButtons()},initButtons:function(){var t=this;this.$container.find(this.settings.uploadButtonSelector).on("click",(function(e){t.$container.find(t.settings.fileInputSelector).trigger("click")})),this.$container.find(this.settings.deleteButtonSelector).on("click",(function(e){confirm(Craft.t("app","Are you sure you want to delete this image?"))&&($(e.currentTarget).parent().append('<div class="blocking-modal"></div>'),Craft.sendActionRequest("POST",t.settings.deleteAction,{data:t.settings.postParameters}).then((function(e){var i=e.data;t.refreshImage(i)})))}))},refreshImage:function(t){$(this.settings.containerSelector).replaceWith(t.html),this.settings.onAfterRefreshImage(t),this.initImageUpload()},_onUploadStart:function(t){this.progressBar.$progressBar.css({top:Math.round(this.$container.outerHeight()/2)-6}),this.$container.addClass("uploading"),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){e.result.error?Craft.cp.displayError(e.result.error):($(e.result.html),this.refreshImage(e.result)),this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))},_onUploadFailure:function(t,e){var i,s=e.response(),n=(null==s||null===(i=s.jqXHR)||void 0===i?void 0:i.responseJSON)||{},a=n.message,r=n.filename;a||(a=r?Craft.t("app","Upload failed for “{filename}”.",{filename:r}):Craft.t("app","Upload failed.")),Craft.cp.displayError(a),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading")}},{defaults:{postParameters:{},uploadAction:"",deleteAction:"",fileInputSelector:"",onAfterRefreshImage:$.noop,containerSelector:null,uploadButtonSelector:null,deleteButtonSelector:null,uploadParamName:"files"}})},657:function(){Craft.InfoIcon=Garnish.Base.extend({$container:null,$icon:null,$liveRegion:null,content:null,hud:null,init:function(t){var e=this;if(this.$icon=$(t),this.$liveRegion=$("<span/>",{role:"status",class:"visually-hidden"}),this.$icon.data("infoicon")?(console.warn("Double-instantiating an info icon on an element"),this.content=this.$icon.data("infoicon").content,this.$icon.data("infoicon").destroy()):(this.content=this.$icon.html(),this.$icon.html("").attr({tabindex:0,role:"button",type:"button","aria-label":Craft.t("app","More info")}).wrap($("<span/>",{class:"infoicon-container"})),this.$container=this.$icon.parent(),this.$container.append(this.$liveRegion)),this.$icon.data("infoicon",this),this.$icon[0].previousSibling&&this.$icon[0].previousSibling.nodeType===Node.TEXT_NODE&&!this.$icon.parent().hasClass("nowrap")){var i=this.$icon[0].previousSibling.nodeValue.match(/[^\s\-]+\s*$/);i&&(this.$icon[0].previousSibling.nodeValue=this.$icon[0].previousSibling.nodeValue.substring(0,i.index),$("<span/>",{class:"nowrap",html:i[0].replace(/\s+$/,"")+" "}).insertAfter(this.$icon[0].previousSibling).append(this.$icon))}this.addListener(this.$icon,"click",(function(t){t.preventDefault(),t.stopPropagation(),e.showHud()})),this.addListener(this.$icon,"keydown",(function(t){e.hud&&e.hud.showing||![Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)||(t.preventDefault(),t.stopPropagation(),e.showHud())}))},showHud:function(t){var e=this;this.hud?this.hud.show():(this.hud=new Garnish.HUD(this.$icon,this.content,{hudClass:"hud info-hud",closeOtherHUDs:!1,onShow:function(){Garnish.uiLayerManager.registerShortcut(Garnish.SPACE_KEY,(function(){e.hud.hide()})),e.$liveRegion.html(""),setTimeout((function(){e.$liveRegion.html(e.content)}),200)},onHide:function(){e.$liveRegion.html("")}}),Craft.initUiElements(this.hud.$body))},destroy:function(){this.$icon.removeData("infoicon"),this.base()}})},4487:function(){Craft.LightSwitch=Garnish.Base.extend({settings:null,$outerContainer:null,$innerContainer:null,$input:null,small:!1,on:!1,indeterminate:!1,dragger:null,dragStartMargin:null,init:function(t,e){if(this.$outerContainer=$(t),this.$outerContainer.data("lightswitch")&&(console.warn("Double-instantiating a lightswitch on an element"),this.$outerContainer.data("lightswitch").destroy()),this.$outerContainer.data("lightswitch",this),this.small=this.$outerContainer.hasClass("small"),this.setSettings(e,Craft.LightSwitch.defaults),this.$innerContainer=this.$outerContainer.find(".lightswitch-container:first"),this.$input=this.$outerContainer.find("input:first"),!this.$input.prop("disabled")){this.on=this.$outerContainer.hasClass("on"),this.indeterminate=this.$outerContainer.hasClass("indeterminate"),this.addListener(this.$outerContainer,"mousedown","_onMouseDown"),this.addListener(this.$outerContainer,"keydown","_onKeyDown"),this.dragger=new Garnish.BaseDrag(this.$outerContainer,{axis:Garnish.X_AXIS,ignoreHandleSelector:null,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)});var i=this.$outerContainer.parent(".lightswitch-inner-container");i.length&&(this.addListener(i.children('span[data-toggle="off"]'),"click",this.turnOff),this.addListener(i.children('span[data-toggle="on"]'),"click",this.turnOn))}},turnOn:function(t){var e=!this.on;if(this.on=!0,this.indeterminate=!1,this.$outerContainer.addClass("dragging"),Garnish.prefersReducedMotion())this.$innerContainer.css("margin-"+Craft.left,0);else{var i={};i["margin-"+Craft.left]=0,this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this))}this.$input.val(this.settings.value),this.$outerContainer.addClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","true"),e&&!0!==t&&this.onChange()},turnOff:function(t){var e=this.on||this.indeterminate;if(this.on=!1,this.indeterminate=!1,this.$outerContainer.addClass("dragging"),Garnish.prefersReducedMotion())this.$innerContainer.css("margin-"+Craft.left,this._getOffMargin());else{var i={};i["margin-"+Craft.left]=this._getOffMargin(),this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this))}this.$input.val(""),this.$outerContainer.removeClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","false"),e&&!0!==t&&this.onChange()},turnIndeterminate:function(t){var e=!this.indeterminate;this.on=!1,this.indeterminate=!0,this.$outerContainer.addClass("dragging");var i={};i["margin-"+Craft.left]=this._getOffMargin()/2,this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this)),this.$input.val(this.settings.indeterminateValue),this.$outerContainer.removeClass("on"),this.$outerContainer.addClass("indeterminate"),this.$outerContainer.attr("aria-checked","mixed"),e&&!0!==t&&this.onChange()},toggle:function(){this.indeterminate||!this.on?this.turnOn():this.turnOff()},onChange:function(){this.trigger("change"),this.settings.onChange(this.on),this.$outerContainer.trigger("change")},_onMouseDown:function(){this.addListener(Garnish.$doc,"mouseup","_onMouseUp")},_onMouseUp:function(){this.removeListener(Garnish.$doc,"mouseup"),this.dragger.dragging||this.toggle()},_onKeyDown:function(t){switch(t.keyCode){case Garnish.SPACE_KEY:this.toggle(),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?this.turnOn():this.turnOff(),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?this.turnOff():this.turnOn(),t.preventDefault()}},_getMargin:function(){return parseInt(this.$innerContainer.css("margin-"+Craft.left))},_onDragStart:function(){this.$outerContainer.addClass("dragging"),this.dragStartMargin=this._getMargin()},_onDrag:function(){var t;(t="ltr"===Craft.orientation?this.dragStartMargin+this.dragger.mouseDistX:this.dragStartMargin-this.dragger.mouseDistX)<this._getOffMargin()?t=this._getOffMargin():t>0&&(t=0),this.$innerContainer.css("margin-"+Craft.left,t)},_onDragStop:function(){this._getMargin()>this._getOffMargin()/2?this.turnOn():this.turnOff()},_onSettle:function(){this.$outerContainer.removeClass("dragging")},destroy:function(){this.$outerContainer.removeData("lightswitch"),this.base(),this.dragger.destroy()},_getOffMargin:function(){return this.small?-10:-12}},{animationDuration:100,defaults:{value:"1",indeterminateValue:"-",onChange:$.noop}})},6966:function(){Craft.Listbox=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,selectedOptionIndex:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.Listbox.defaults),this.$container.data("listbox")&&(console.warn("Double-instantiating a listbox on an element"),this.$container.data("listbox").destroy()),this.$container.data("listbox",this),this.$options=this.$container.find("button,[role=option]"),this.$selectedOption=this.$options.filter("[aria-pressed=true],[aria-selected=true]").removeAttr("aria-selected").attr("aria-pressed","true"),this.$selectedOption.length?this.selectedOptionIndex=this.$options.index(this.$selectedOption):this.$selectedOption=null,this.addListener(this.$options,"click",(function(t){i.select(i.$options.index($(t.currentTarget))),t.preventDefault()}))},select:function(t){t<0||t>=this.$options.length||t===this.selectedOptionIndex||(this.$selectedOption&&this.$selectedOption.removeClass(this.settings.selectedClass).attr("aria-pressed","false"),this.$selectedOption=this.$options.eq(t).addClass(this.settings.selectedClass).attr("aria-pressed","true"),this.selectedOptionIndex=t,this.settings.onChange(this.$selectedOption,t),this.trigger("change",{$selectedOption:this.$selectedOption,selectedOptionIndex:t}))},disable:function(){this.base(),this.$container.attr("aria-disabled","true")},enable:function(){this.base(),this.$container.removeAttr("aria-disabled")},destroy:function(){this.$container.removeData("listbox"),this.base()}},{defaults:{selectedClass:"active",focusClass:"focus",onChange:$.noop}})},5080:function(){Craft.LivePreview=Garnish.Base.extend({$extraFields:null,$trigger:null,$shade:null,$editorContainer:null,$editor:null,$dragHandle:null,$previewContainer:null,$iframeContainer:null,$iframe:null,$fieldPlaceholder:null,previewUrl:null,token:null,basePostData:null,inPreviewMode:!1,fields:null,lastPostData:null,updateIframeInterval:null,loading:!1,checkAgain:!1,dragger:null,dragStartEditorWidth:null,_slideInOnIframeLoad:!1,_scrollX:null,_scrollY:null,_editorWidth:null,_editorWidthInPx:null,init:function(t){var e=this;this.setSettings(t,Craft.LivePreview.defaults),this.settings.previewUrl?this.previewUrl=this.settings.previewUrl:this.previewUrl=Craft.baseSiteUrl.replace(/\/+$/,"")+"/","https:"===document.location.protocol&&(this.previewUrl=this.previewUrl.replace(/^http:/,"https:")),this.basePostData=$.extend({},this.settings.previewParams),this.$extraFields=$(this.settings.extraFields),this.$trigger=$(this.settings.trigger),this.$fieldPlaceholder=$("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.LivePreview.defaultEditorWidth),this.addListener(this.$trigger,"activate","toggle"),Craft.cp.on("beforeSaveShortcut",(function(){e.inPreviewMode&&e.moveFieldsBack()})),Craft.Preview.instances.push(this)},get editorWidth(){return this._editorWidth},get editorWidthInPx(){return this._editorWidthInPx},set editorWidth(t){var e;t>=1?(e=t,t/=Garnish.$win.width()):e=Math.round(t*Garnish.$win.width()),e<Craft.LivePreview.minEditorWidthInPx&&(t=(e=Craft.LivePreview.minEditorWidthInPx)/Garnish.$win.width()),this._editorWidth=t,this._editorWidthInPx=e},toggle:function(){this.inPreviewMode?this.exit():this.enter()},enter:function(){var t=this;if(!this.inPreviewMode)if(this.token){if(this.trigger("beforeEnter"),$(document.activeElement).trigger("blur"),!this.$editor){this.$shade=$("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=$("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$iframeContainer=$("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$editorContainer=$("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=$("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=$("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=$("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);$("<div/>",{class:"flex-grow"}).appendTo(e);var s=$("<button/>",{type:"button",class:"btn submit",text:Craft.t("app","Save")}).appendTo(e);this.dragger=new Garnish.BaseDrag(this.$dragHandle,{axis:Garnish.X_AXIS,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)}),this.addListener(i,"click","exit"),this.addListener(s,"click","save")}this.handleWindowResize(),this.addListener(Garnish.$win,"resize","handleWindowResize"),this.$editorContainer.css(Craft.left,-this.editorWidthInPx+"px"),this.$previewContainer.css(Craft.right,-this.getIframeWidth()),this.fields=[];for(var n=$(this.settings.fields),a=0;a<n.length;a++){var r=$(n[a]),o=this._getClone(r);this.$fieldPlaceholder.insertAfter(r),r.detach(),this.$fieldPlaceholder.replaceWith(o),r.appendTo(this.$editor),this.fields.push({$field:r,$clone:o})}this.updateIframe()?this._slideInOnIframeLoad=!0:this.slideIn(),Craft.ElementThumbLoader.retryAll(),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.exit()})),this.inPreviewMode=!0,this.trigger("enter")}else this.createToken()},createToken:function(){var t=this,e={previewAction:this.settings.previewAction};Craft.sendActionRequest("POST","live-preview/create-token",{data:e}).then((function(e){t.token=e.data.token,t.enter()}))},save:function(){Craft.cp.submitPrimaryForm()},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){var t=this;$("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",(function(){t.trigger("slideIn"),Garnish.$win.trigger("resize")})),this.$previewContainer.show().velocity("stop").animateRight(0,"slow",(function(){t.updateIframeInterval=setInterval(t.updateIframe.bind(t),1e3)}))},exit:function(){var t=this;this.inPreviewMode&&(this.trigger("beforeExit"),$("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),Garnish.uiLayerManager.removeLayer(),this.updateIframeInterval&&clearInterval(this.updateIframeInterval),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",(function(){for(var e=0;e<t.fields.length;e++)t.fields[e].$newClone.remove();t.$editorContainer.hide(),t.trigger("slideOut")})),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",(function(){t.$previewContainer.hide()})),Craft.ElementThumbLoader.retryAll(),this.inPreviewMode=!1,this.trigger("exit"))},moveFieldsBack:function(){for(var t=0;t<this.fields.length;t++){var e=this.fields[t];e.$newClone=this._getClone(e.$field),this.$fieldPlaceholder.insertAfter(e.$field),e.$field.detach(),this.$fieldPlaceholder.replaceWith(e.$newClone),e.$clone.replaceWith(e.$field)}Garnish.$win.trigger("resize")},getIframeWidth:function(){return Garnish.$win.width()-this.editorWidthInPx},updateWidths:function(){this.$editorContainer.css("width",this.editorWidthInPx+"px"),this.$previewContainer.width(this.getIframeWidth())},updateIframe:function(t){if(t&&(this.lastPostData=null),!this.inPreviewMode)return!1;if(this.loading)return this.checkAgain=!0,!1;var e=$.extend(Garnish.getPostData(this.$editor),Garnish.getPostData(this.$extraFields));if(this.lastPostData&&Craft.compare(e,this.lastPostData,!1))return!1;this.lastPostData=e,this.loading=!0;var i=this.$iframe?$(this.$iframe[0].contentWindow.document):null;return this._scrollX=i?i.scrollLeft():0,this._scrollY=i?i.scrollTop():0,$.ajax({url:this.previewUrl+(-1!==this.previewUrl.indexOf("?")?"&":"?")+Craft.tokenParam+"="+this.token,method:"POST",data:$.extend({},e,this.basePostData),headers:{"X-Craft-Token":this.token},xhrFields:{withCredentials:!0},crossDomain:!0,success:this.handleSuccess.bind(this),error:this.handleError.bind(this)}),!0},forceUpdateIframe:function(){return this.updateIframe(!0)},handleSuccess:function(t){var e=this,i=t+'<script type="text/javascript">window.scrollTo('+this._scrollX+", "+this._scrollY+");<\/script>",s=$('<iframe class="lp-preview" frameborder="0"/>');this.$iframe?s.insertBefore(this.$iframe):s.appendTo(this.$iframeContainer),this.addListener(s,"load",(function(){this.$iframe&&this.$iframe.remove(),this.$iframe=s,this._slideInOnIframeLoad&&(this.slideIn(),this._slideInOnIframeLoad=!1),this.removeListener(s,"load")})),Garnish.requestAnimationFrame((function(){s[0].contentWindow.document.open(),s[0].contentWindow.document.write(i),s[0].contentWindow.document.close(),e.onResponse()}))},handleError:function(){this.onResponse()},onResponse:function(){this.loading=!1,this.checkAgain&&(this.checkAgain=!1,this.updateIframe())},_getClone:function(t){var e=t.clone();return Garnish.copyInputValues(t,e),e.attr("id",""),e.find("[id]").attr("id",""),e},_onDragStart:function(){this.dragStartEditorWidth=this.editorWidthInPx,this.$previewContainer.addClass("dragging")},_onDrag:function(){"ltr"===Craft.orientation?this.editorWidth=this.dragStartEditorWidth+this.dragger.mouseDistX:this.editorWidth=this.dragStartEditorWidth-this.dragger.mouseDistX,this.updateWidths()},_onDragStop:function(){this.$previewContainer.removeClass("dragging"),Craft.setLocalStorage("LivePreview.editorWidth",this.editorWidth)},destroy:function(){var t=this;Craft.Preview.instances=Craft.Preview.instances.filter((function(e){return e!==t})),this.base()}},{defaultEditorWidth:.33,minEditorWidthInPx:320,instances:[],defaults:{trigger:".livepreviewbtn",fields:null,extraFields:null,previewUrl:null,previewAction:null,previewParams:{}}}),Craft.LivePreview.init=function(t){Craft.livePreview=new Craft.LivePreview(t)}},7439:function(){Craft.PasswordInput=Garnish.Base.extend({$passwordWrapper:null,$passwordInput:null,$textInput:null,$currentInput:null,$showPasswordToggle:null,showingPassword:null,init:function(t,e){this.$passwordInput=$(t),this.$passwordWrapper=this.$passwordInput.parent(".passwordwrapper"),this.settings=$.extend({},Craft.PasswordInput.defaults,e),this.$passwordInput.data("passwordInput")&&(console.warn("Double-instantiating a password input on an element"),this.$passwordInput.data("passwordInput").destroy()),this.$passwordInput.data("passwordInput",this),this.$showPasswordToggle=$('<button type="button" class="invisible" />'),this.$showPasswordToggle.addClass("password-toggle"),this.$showPasswordToggle.insertAfter(this.$passwordInput),this.initInputFocusEvents(this.$passwordInput),this.addListener(this.$showPasswordToggle,"click","onClick"),this.hidePassword(),this.addListener(this.$passwordWrapper.closest("form"),"submit","hidePassword")},setCurrentInput:function(t){this.$currentInput&&(t.insertAfter(this.$currentInput),this.$currentInput.detach(),t.trigger("focus"),t.val(this.$currentInput.val())),this.$currentInput=t,this.addListener(this.$currentInput,"keypress,keyup,change,blur","onInputChange")},updateToggleLabel:function(t){this.$showPasswordToggle.text(t)},initInputFocusEvents:function(t){this.addListener(t,"focus",(function(){this.$passwordWrapper.addClass("focus")})),this.addListener(t,"blur",(function(){this.$passwordWrapper.removeClass("focus")}))},showPassword:function(){this.showingPassword||(this.$textInput||(this.$textInput=this.$passwordInput.clone(!0),this.$textInput.attr({type:"text",autocapitalize:"off"}),this.initInputFocusEvents(this.$textInput)),this.setCurrentInput(this.$textInput),this.updateToggleLabel(Craft.t("app","Hide")),this.showingPassword=!0)},hidePassword:function(){!1!==this.showingPassword&&(this.setCurrentInput(this.$passwordInput),this.updateToggleLabel(Craft.t("app","Show")),this.showingPassword=!1)},togglePassword:function(){this.showingPassword?this.hidePassword():this.showPassword(),this.settings.onToggleInput(this.$currentInput)},onInputChange:function(){this.$currentInput.val()?this.$showPasswordToggle.removeClass("invisible"):this.$showPasswordToggle.addClass("invisible")},onClick:function(t){if(this.$currentInput[0].setSelectionRange){var e=this.$currentInput[0].selectionStart,i=this.$currentInput[0].selectionEnd;this.togglePassword(),this.$currentInput[0].setSelectionRange(e,i)}else this.togglePassword()},destroy:function(){this.$passwordInput.removeData("passwordInput"),this.base()}},{defaults:{onToggleInput:$.noop}})},5328:function(){function t(t,i){var s="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!s){if(Array.isArray(t)||(s=function(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}(t))||i&&t&&"number"==typeof t.length){s&&(t=s);var n=0,a=function(){};return{s:a,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){s=s.call(t)},n:function(){var t=s.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==s.return||s.return()}finally{if(l)throw r}}}}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function i(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,s)}return i}function s(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?i(Object(s),!0).forEach((function(e){n(t,e,s[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):i(Object(s)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))}))}return t}function n(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function a(t){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a(t)}Craft.Preview=Garnish.Base.extend({elementEditor:null,$shade:null,$editorContainer:null,$editor:null,$spinner:null,$statusIcon:null,$dragHandle:null,$previewWrapper:null,$previewContainer:null,$previewSkipLink:null,$bumperLink:null,$notifier:null,$iframeContainer:null,$previewHeader:null,$targetBtn:null,$targetMenu:null,$deviceTypeContainer:null,$orientationBtn:null,$refreshBtn:null,$deviceMask:null,$devicePreviewContainer:null,$iframe:null,iframeLoaded:!1,$tempInput:null,$fieldPlaceholder:null,isActive:!1,isVisible:!1,activeTarget:0,animationDuration:"slow",currentDeviceType:"desktop",deviceOrientation:null,deviceWidth:"",deviceHeight:"",deviceMaskDimensions:{phone:{width:375,height:753},tablet:{width:768,height:1110}},draftId:null,url:null,fields:null,iframeHeight:null,scrollTop:null,scrollLeft:null,dragger:null,dragStartEditorWidth:null,_updateIframeProxy:null,_editorWidth:null,_editorWidthInPx:null,init:function(t){this.elementEditor=t,this._updateIframeProxy=this.updateIframe.bind(this),this.$tempInput=$("<input/>",{type:"hidden",name:"__PREVIEW_FIELDS__",value:"1"}),this.$fieldPlaceholder=$("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.Preview.defaultEditorWidth),Craft.Preview.instances.push(this)},get editorWidth(){return this._editorWidth},get editorWidthInPx(){return this._editorWidthInPx},set editorWidth(t){var e;t>=1?(e=t,t/=Garnish.$win.width()):e=Math.round(t*Garnish.$win.width()),e<Craft.Preview.minEditorWidthInPx&&(t=(e=Craft.Preview.minEditorWidthInPx)/Garnish.$win.width()),this._editorWidth=t,this._editorWidthInPx=e},open:function(){var t=this;if(!this.isActive){if(this.isActive=!0,this.trigger("beforeOpen"),$(document.activeElement).trigger("blur"),!this.$editor){var e=Craft.t("app","Skip to {title}",{title:Craft.t("app","Top of preview")});this.$shade=$("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewWrapper=$("<div/>",{role:"dialog","aria-modal":"true","aria-labelledby":"lp-preview-heading"}).appendTo(Garnish.$bod),this.$modalLabel=$("<h2/>",{id:"lp-preview-heading",class:"visually-hidden",html:Craft.t("app","Preview")}).appendTo(this.$previewWrapper),this.$editorContainer=$("<div/>",{class:"lp-editor-container"}).appendTo(this.$previewWrapper),this.$previewContainer=$("<div/>",{class:"lp-preview-container",id:"lp-preview-container"}).appendTo(this.$previewWrapper),this.$notifier=$("<span/>",{class:"visually-hidden","aria-live":"assertive"}).appendTo(this.$previewContainer);var i=$("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=$("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=$("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var s=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(i);if($("<div/>",{class:"flex-grow"}).appendTo(i),this.$spinner=$("<div/>",{class:"spinner hidden",title:Craft.t("app","Saving")}).appendTo(i),this.$statusIcon=$("<div/>",{class:"invisible"}).appendTo(i),this.$statusMessage=$("<span/>",{class:"visually-hidden","aria-live":"polite"}).appendTo(i),this.$previewSkipLink=$("<a/>",{class:"skip-link btn",href:"#lp-preview-container",html:e}).appendTo(i),Craft.Pro){if(this.$previewHeader=$("<header/>",{class:"lp-preview-header"}).appendTo(this.$previewContainer),this.elementEditor.settings.previewTargets.length>1){this.$targetBtn=$("<button/>",{type:"button",class:"btn menubtn",text:this.elementEditor.settings.previewTargets[0].label}).appendTo(this.$previewHeader),this.$targetMenu=$("<div/>",{class:"menu lp-target-menu"}).insertAfter(this.$targetBtn);for(var n,a=$("<ul/>",{class:"padded"}).appendTo(this.$targetMenu),r=0;r<this.elementEditor.settings.previewTargets.length;r++)n=$("<li/>").appendTo(a),$("<a/>",{data:{target:r},text:this.elementEditor.settings.previewTargets[r].label,class:0===r?"sel":null}).appendTo(n);new Garnish.MenuBtn(this.$targetBtn,{onOptionSelect:function(e){t.switchTarget($(e).data("target"))}}),$('<div class="flex-grow"/>').appendTo(this.$previewHeader)}this._buildDeviceTypeFieldset(),$('<div class="flex-grow"/>').appendTo(this.$previewHeader);var o=$('<div class="buttons"/>').appendTo(this.$previewHeader);this.$orientationBtn=$("<button/>",{type:"button",class:"btn disabled","data-icon":"rotate","aria-disabled":"true",text:Craft.t("app","Rotate"),"aria-label":Craft.t("app","Rotate")}).appendTo(o),this.addListener(this.$orientationBtn,"click","switchOrientation"),this.$refreshBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Refresh"),"data-icon":"refresh"}).appendTo(o),this.addListener(this.$refreshBtn,"click",(function(){t.updateIframe(!1,!0)})),this.deviceOrientation=Craft.getLocalStorage("LivePreview.orientation")}this.$iframeContainer=$("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$devicePreviewContainer=$("<div/>",{class:"lp-device-preview-container"}).appendTo(this.$iframeContainer),this.$deviceMask=$("<div/>",{class:"lp-device-mask"}).appendTo(this.$iframeContainer),this.$bumperLink=$("<a/>",{class:"skip-link btn lp-preview-container__bumper-link",html:e,href:"#lp-preview-container"}),this.$bumperLink.appendTo(this.$previewContainer),this.dragger=new Garnish.BaseDrag(this.$dragHandle,{axis:Garnish.X_AXIS,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)}),this.addListener(s,"click","close"),this.addListener(this.$statusIcon,"click",(function(){t.elementEditor.showStatusHud(t.$statusIcon)}))}this.handleWindowResize(),this.addListener(Garnish.$win,"resize","handleWindowResize"),this.$editorContainer.css(Craft.left,-this.editorWidthInPx+"px"),this.$previewContainer.css(Craft.right,-this.getIframeWidth()),this.fields=[];var l=$("#content .field").not($("#content .field .field"));if(l.length){this.$tempInput.insertBefore(l.get(0));for(var h=0;h<l.length;h++){var d=$(l[h]),c=this._getClone(d);this.$fieldPlaceholder.insertAfter(d),d.detach(),this.$fieldPlaceholder.replaceWith(c),d.appendTo(this.$editor),this.fields.push({$field:d,$clone:c})}}this.updateIframe(),this.elementEditor.on("update",this._updateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.trigger("open")}},_getDeviceTypeTranslation:function(t){var e;switch(t){case"phone":e=Craft.t("app","Mobile");break;case"tablet":e=Craft.t("app","Tablet");break;default:e=Craft.t("app","Desktop")}return e},_getDeviceOrientationTranslation:function(t){return"portrait"===t?Craft.t("app","Portrait"):Craft.t("app","Landscape")},_buildDeviceTypeFieldset:function(){var t=this;this.$deviceTypeContainer=$("<section/>",{class:"btngroup lp-device-type","aria-label":Craft.t("app","Device type")}).appendTo(this.$previewHeader),$("<button/>",{type:"button",class:"btn lp-device-type-btn--desktop active",title:Craft.t("app","Desktop"),"aria-label":Craft.t("app","Desktop"),"aria-pressed":"true",data:{width:"",height:"",deviceType:"desktop"}}).appendTo(this.$deviceTypeContainer),$("<button/>",{type:"button",class:"btn lp-device-type-btn--tablet",title:Craft.t("app","Tablet"),"aria-label":Craft.t("app","Tablet"),"aria-pressed":"false",data:{width:768,height:1024,deviceType:"tablet"}}).appendTo(this.$deviceTypeContainer),$("<button/>",{type:"button",class:"btn lp-device-type-btn--phone",title:Craft.t("app","Mobile"),"aria-label":Craft.t("app","Mobile"),"aria-pressed":"false",data:{width:375,height:667,deviceType:"phone"}}).appendTo(this.$deviceTypeContainer),this.deviceBtnGroup=new Craft.Listbox(this.$deviceTypeContainer,{onChange:function(e){t.switchDeviceType(e)}})},_activeTarget:function(){return this.elementEditor.settings.previewTargets[this.activeTarget]},_autoRefresh:function(){var t=this._activeTarget();return void 0===a(t.refresh)||!!t.refresh},switchTarget:function(t){this.activeTarget=t,this.$targetBtn.text(this.elementEditor.settings.previewTargets[t].label),this.$targetMenu.find("a.sel").removeClass("sel"),this.$targetMenu.find("a").eq(t).addClass("sel"),this.updateIframe(!0),this.trigger("switchTarget",{previewTarget:this.elementEditor.settings.previewTargets[t]})},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){var t=this;this.isActive&&!this.isVisible&&($("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,Garnish.getUserPreferredAnimationDuration(this.animationDuration),(function(){t.trigger("slideIn"),Garnish.$win.trigger("resize")})),this.$previewContainer.show().velocity("stop").animateRight(0,Garnish.getUserPreferredAnimationDuration(this.animationDuration)),this.isVisible=!0,Garnish.uiLayerManager.addLayer(this.$previewWrapper),Garnish.hideModalBackgroundLayers(),Craft.setFocusWithin(this.$previewWrapper),Craft.trapFocusWithin(this.$previewWrapper),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.close()})))},close:function(){var t=this;this.isActive&&this.isVisible&&(this.trigger("beforeClose"),$("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),Garnish.uiLayerManager.removeLayer(),Garnish.resetModalBackgroundLayerVisibility(),this.$tempInput.detach(),this.moveFieldsBack(),Garnish.prefersReducedMotion()?this.$shade.velocity("fadeOut"):this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,Garnish.getUserPreferredAnimationDuration(this.animationDuration),(function(){for(var e=0;e<t.fields.length;e++)t.fields[e].$newClone.remove();t.$editorContainer.hide(),t.trigger("slideOut")})),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),Garnish.getUserPreferredAnimationDuration(this.animationDuration),(function(){t.$iframeContainer.removeClass("lp-iframe-container--rotating"),t.$previewContainer.hide()})),this.elementEditor.off("update",this._updateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.elementEditor.$previewBtn&&this.elementEditor.$previewBtn.focus(),this.isActive=!1,this.isVisible=!1,this.trigger("close"))},moveFieldsBack:function(){for(var t=0;t<this.fields.length;t++){var e=this.fields[t];e.$newClone=this._getClone(e.$field),this.$fieldPlaceholder.insertAfter(e.$field),e.$field.detach(),this.$fieldPlaceholder.replaceWith(e.$newClone),e.$clone.replaceWith(e.$field)}Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll")},getIframeWidth:function(){return Garnish.$win.width()-this.editorWidthInPx},updateWidths:function(){this.$editorContainer.css("width",this.editorWidthInPx+"px"),this.$previewContainer.width(this.getIframeWidth()),this._devicePreviewIsActive()&&this.updateDevicePreview()},_useIframeResizer:function(){return!1!==Craft.previewIframeResizerOptions},updateIframe:function(t,e){var i=this;if(!this.isActive)return!1;t=!0===t,this.draftId===(this.draftId=this.elementEditor.settings.draftId)&&this.$iframe||(e=!0);var s=this._activeTarget();void 0===e&&(e=t||this._autoRefresh()),this.trigger("beforeUpdateIframe",{previewTarget:s,resetScroll:t,refresh:e}),e?this.elementEditor.getTokenizedPreviewUrl(s.url,"x-craft-live-preview").then((function(e){var s;t?(i.scrollTop=null,i.scrollLeft=null):i.iframeLoaded&&i.$iframe&&(i._useIframeResizer()?(i.iframeHeight=i.$iframe.height(),i.scrollTop=i.$iframeContainer.scrollTop(),i.scrollLeft=i.$iframeContainer.scrollLeft()):(s=Craft.isSameHost(e))&&i.$iframe[0].contentWindow&&(i.scrollTop=$(i.$iframe[0].contentWindow.document).scrollTop(),i.scrollLeft=$(i.$iframe[0].contentWindow.document).scrollLeft())),i.iframeLoaded=!1;var n=$("<iframe/>",{class:"lp-preview",frameborder:0,src:e,title:Craft.t("app","Preview")});i.$iframe?i.$iframe.replaceWith(n):n.appendTo(i.$devicePreviewContainer),i._useIframeResizer()?(t||null===i.iframeHeight||(n.height(i.iframeHeight),i.$iframeContainer.scrollTop(i.scrollTop),i.$iframeContainer.scrollLeft(i.scrollLeft)),iFrameResize($.extend({checkOrigin:!1,scrolling:!0,onInit:function(t){i.iframeLoaded=!0,i.iframeHeight=null,i.scrollTop=null,i.scrollLeft=null,t.scrolling="no"}},Craft.previewIframeResizerOptions||{}),n[0])):n.on("load",(function(){i.iframeLoaded=!0,!t&&s&&(null!==i.scrollTop&&$(n[0].contentWindow.document).scrollTop(i.scrollTop),null!==i.scrollLeft&&$(n[0].contentWindow.document).scrollLeft(i.scrollLeft))})),i.url=e,i.$iframe=n,i._devicePreviewIsActive()&&i.updateDevicePreview(),i.trigger("afterUpdateIframe",{previewTarget:i.elementEditor.settings.previewTargets[i.activeTarget],$iframe:i.$iframe}),i.slideIn()})):this.slideIn()},_devicePreviewIsActive:function(){return"desktop"!==this.currentDeviceType},_updateNotifier:function(){var t=this;this.$notifier.html="";var e="desktop"===this.currentDeviceType?"Previewing {type} device":"Previewing {type} device in {orientation}",i={type:this._getDeviceTypeTranslation(this.currentDeviceType)};"desktop"!==this.currentDeviceType&&(i=s(s({},i),{orientation:this._getDeviceOrientationTranslation(this.deviceOrientation)}));var n=Craft.t("app",e,i);setTimeout((function(){t.$notifier.text(n)}),200)},switchDeviceType:function(t){this.$iframeContainer.removeClass("lp-iframe-container--rotating");var e=t.data("deviceType");if(e===this.currentDeviceType)return!1;this.currentDeviceType=e,this.deviceWidth=t.data("width"),this.deviceHeight=t.data("height"),"desktop"===this.currentDeviceType?(this.$orientationBtn.addClass("disabled").attr("aria-disabled","true"),this.$iframeContainer.removeClass("lp-iframe-container--has-device-preview")):(this.$orientationBtn.removeClass("disabled").removeAttr("aria-disabled"),this.$iframeContainer.addClass("lp-iframe-container--has-device-preview")),"tablet"===this.currentDeviceType?this.$iframeContainer.addClass("lp-iframe-container--tablet"):this.$iframeContainer.removeClass("lp-iframe-container--tablet"),this._updateNotifier(),"desktop"!==this.currentDeviceType&&this.updateDevicePreview()},switchOrientation:function(){var t=this;if(!this._devicePreviewIsActive())return!1;this.deviceOrientation&&"portrait"!==this.deviceOrientation?this.deviceOrientation="portrait":this.deviceOrientation="landscape",Craft.setLocalStorage("LivePreview.orientation",this.deviceOrientation),this.$iframeContainer.addClass("lp-iframe-container--rotating"),this.updateDevicePreview(),this._updateNotifier(),setTimeout((function(){t.$iframeContainer.removeClass("lp-iframe-container--rotating")}),300)},updateDevicePreview:function(){var t=1,e=1,i=1,s=this.$previewContainer.height()-50-48,n=this.$previewContainer.width()-48,a=this.deviceMaskDimensions[this.currentDeviceType].height,r=this.deviceMaskDimensions[this.currentDeviceType].width;"landscape"===this.deviceOrientation?(n<a&&(t=n/a),s<r&&(e=s/r)):(s<a&&(t=s/a),n<r&&(e=n/r)),i=t,e<t&&(i=e);var o=-100/i/2,l="landscape"===this.deviceOrientation?"-90deg":"0deg";this.$deviceMask.css({width:this.deviceMaskDimensions[this.currentDeviceType].width+"px",height:this.deviceMaskDimensions[this.currentDeviceType].height+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%) rotate("+l+")"}),"landscape"===this.deviceOrientation?this.$devicePreviewContainer.css({width:this.deviceHeight+"px",height:this.deviceWidth+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%)",marginTop:0,marginLeft:"-"+12*i+"px"}):this.$devicePreviewContainer.css({width:this.deviceWidth+"px",height:this.deviceHeight+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%)",marginTop:"-"+12*i+"px",marginLeft:0})},_getClone:function(t){var e=t.clone();return Garnish.copyInputValues(t,e),e.attr("id",""),e.find("[id]").attr("id",""),e.find("[name]").prop("disabled",!0),e},_onDragStart:function(){this.dragStartEditorWidth=this.editorWidthInPx,this.$previewContainer.addClass("dragging")},_onDrag:function(){"ltr"===Craft.orientation?this.editorWidth=this.dragStartEditorWidth+this.dragger.mouseDistX:this.editorWidth=this.dragStartEditorWidth-this.dragger.mouseDistX,this.updateWidths()},_onDragStop:function(){this.$previewContainer.removeClass("dragging"),Craft.setLocalStorage("LivePreview.editorWidth",this.editorWidth)},destroy:function(){var t=this;Craft.Preview.instances=Craft.Preview.instances.filter((function(e){return e!==t})),this.base()}},{defaultEditorWidth:.33,minEditorWidthInPx:320,instances:[],refresh:function(){var e,i=t(Craft.Preview.instances);try{for(i.s();!(e=i.n()).done;)preview=e.value,preview.updateIframe()}catch(t){i.e(t)}finally{i.f()}var s,n=t(Craft.LivePreview.instances);try{for(n.s();!(s=n.n()).done;)preview=s.value,preview.forceUpdateIframe()}catch(t){n.e(t)}finally{n.f()}}})},6419:function(){Craft.PreviewFileModal=Garnish.Modal.extend({assetId:null,$spinner:null,$triggerElement:null,$bumperButtonStart:null,$bumperButtonEnd:null,elementSelect:null,type:null,loaded:null,requestId:0,init:function(t,e,i){var s=this;if(i=$.extend(this.defaultSettings,i),this.$triggerElement=Garnish.getFocusedElement(),i.onHide=this._onHide.bind(this),Craft.PreviewFileModal.openInstance){var n=Craft.PreviewFileModal.openInstance;return n.assetId!==t&&(n.loadAsset(t,i.startingWidth,i.startingHeight),n.elementSelect=e),this.destroy()}Craft.PreviewFileModal.openInstance=this,this.elementSelect=e,this.$container=$('<div class="modal previewmodal loading"/>').appendTo(Garnish.$bod),this.base(this.$container,$.extend({resizable:!0},i)),this.$container&&(this.$container.velocity("stop"),this.$container.show().css("opacity",1),this.$shade.velocity("stop"),this.$shade.show().css("opacity",1),Garnish.setFocusWithin(this.$container)),this.$bumperButtonStart=Craft.ui.createButton({html:Craft.t("app","Close Preview"),class:"skip-link"}),this.addListener(this.$bumperButtonStart,"click",(function(){s.hide()})),this.$bumperButtonEnd=this.$bumperButtonStart.clone(!0),this.loadAsset(t,i.startingWidth,i.startingHeight)},_onHide:function(){return Craft.PreviewFileModal.openInstance=null,this.elementSelect?this.elementSelect.focusItem(this.elementSelect.$focusedItem):this.$triggerElement&&this.$triggerElement.length&&this.$triggerElement.trigger("focus"),this.$shade.remove(),this.destroy()},_addBumperButtons:function(){this.$container.prepend(this.$bumperButtonStart).append(this.$bumperButtonEnd)},_addModalName:function(){var t="preview-heading";$("<h1/>",{class:"visually-hidden",id:t,text:Craft.t("app","Preview file")}).prependTo(this.$container),this.$container.attr("aria-labelledby",t)},selfDestruct:function(){var t=Craft.PreviewFileModal.openInstance;return t.hide(),t.$shade.remove(),t.destroy(),Craft.PreviewFileModal.openInstance=null,Craft.focalPoint.destruct(),Craft.focalPoint=null,!0},loadAsset:function(t,e,i){var s=this;this.assetId=t,this.$container.empty(),this.loaded=!1,this.desiredHeight=null,this.desiredWidth=null;var n=.66*Garnish.$win.height(),a=Math.min(n/3*4,Garnish.$win.width()-2*this.settings.minGutter);if(n=a/4*3,e&&i){var r=e/i;a=Math.min(e,Garnish.$win.width()-2*this.settings.minGutter),(a=(n=Math.min(a/r,Garnish.$win.height()-2*this.settings.minGutter))*r)>Math.min(e,Garnish.$win.width()-2*this.settings.minGutter)&&(n=(a=Math.min(e,Garnish.$win.width()-2*this.settings.minGutter))/r)}this._resizeContainer(a,n),this.$spinner=$('<div class="spinner centeralign"></div>').appendTo(this.$container);var o=this.$container.height()/2-this.$spinner.height()/2+"px",l=this.$container.width()/2-this.$spinner.width()/2+"px";this.$spinner.css({left:l,top:o,position:"absolute"}),this.requestId++;var h={assetId:t,requestId:this.requestId},d=function(){s.$container.removeClass("loading"),s.$spinner.remove(),s.loaded=!0};Craft.sendActionRequest("POST","assets/preview-file",{data:h}).then((function(t){if(d(),t.data.requestId==s.requestId){if(!t.data.previewHtml)return s.$container.addClass("zilch"),s.$container.append($("<p/>",{text:Craft.t("app","No preview available.")})),void s._addBumperButtons();s.$container.removeClass("zilch"),s.$container.attr("data-asset-id",s.assetId),s.$container.append(t.data.previewHtml),s._addBumperButtons(),s._addModalName(),Craft.appendHeadHtml(t.data.headHtml),Craft.appendBodyHtml(t.data.bodyHtml)}})).catch((function(t){var e=t.response;d(),Craft.cp.displayError(e.data.message),s.hide()}))},_resizeContainer:function(t,e){this.$container.css({width:t,"min-width":t,"max-width":t,height:e,"min-height":e,"max-height":e,top:(Garnish.$win.height()-e)/2,left:(Garnish.$win.width()-t)/2})}},{defaultSettings:{startingWidth:null,startingHeight:null}})},872:function(){Craft.ProgressBar=Garnish.Base.extend({$progressBar:null,$innerProgressBar:null,$progressBarStatus:null,_itemCount:0,_processedItemCount:0,_displaySteps:!1,init:function(t,e){e&&(this._displaySteps=!0),this.$progressBar=$('<div class="progressbar pending hidden"/>').appendTo(t),this.$innerProgressBar=$('<div class="progressbar-inner"/>').appendTo(this.$progressBar),this.$progressBarStatus=$('<div class="progressbar-status hidden" />').insertAfter(this.$progressBar),this.resetProgressBar()},resetProgressBar:function(){this.setProgressPercentage(100),this.$progressBar.addClass("pending"),this.setItemCount(1),this.setProcessedItemCount(0),this.$progressBarStatus.html(""),this._displaySteps&&this.$progressBar.addClass("has-status")},hideProgressBar:function(){this.$progressBar.addClass("hidden"),this.$progressBarStatus.addClass("hidden")},showProgressBar:function(){this.$progressBar.removeClass("hidden"),this.$progressBarStatus.removeClass("hidden")},setItemCount:function(t){this._itemCount=t},incrementItemCount:function(t){this._itemCount+=t},setProcessedItemCount:function(t){this._processedItemCount=t},incrementProcessedItemCount:function(t){this._processedItemCount+=t},updateProgressBar:function(){this._itemCount=Math.max(this._itemCount,1);var t=Math.min(100,Math.round(100*this._processedItemCount/this._itemCount));this.setProgressPercentage(t),this._displaySteps&&this.$progressBarStatus.html(this._processedItemCount+" / "+this._itemCount)},setProgressPercentage:function(t,e){0===t?this.$progressBar.addClass("pending"):(this.$progressBar.removeClass("pending"),e?this.$innerProgressBar.velocity("stop").velocity({width:t+"%"},"fast"):this.$innerProgressBar.velocity("stop").width(t+"%"))}})},1396:function(){Craft.PromptHandler=Garnish.Base.extend({modal:null,$modalContainerDiv:null,$prompt:null,$promptApplyToRemainingContainer:null,$promptApplyToRemainingCheckbox:null,$promptApplyToRemainingLabel:null,$pomptChoices:null,_prompts:[],_promptBatchCallback:$.noop,_promptBatchReturnData:[],_promptBatchNum:0,resetPrompts:function(){this._prompts=[],this._promptBatchCallback=$.noop,this._promptBatchReturnData=[],this._promptBatchNum=0},addPrompt:function(t){this._prompts.push(t)},getPromptCount:function(){return this._prompts.length},showBatchPrompts:function(t){this._promptBatchCallback=t,this._promptBatchReturnData=[],this._promptBatchNum=0,this._showNextPromptInBatch()},_showNextPromptInBatch:function(){var t=this._prompts[this._promptBatchNum].prompt,e=this._prompts.length-(this._promptBatchNum+1);this._showPrompt(t.message,t.choices,this._handleBatchPromptSelection.bind(this),e)},_handleBatchPromptSelection:function(t,e){var i=this._prompts[this._promptBatchNum],s=this._prompts.length-(this._promptBatchNum+1),n=$.extend(i,{choice:t});this._promptBatchReturnData.push(n),s?(this._promptBatchNum++,e?this._handleBatchPromptSelection(t,!0):this._showNextPromptInBatch()):"function"==typeof this._promptBatchCallback&&this._promptBatchCallback(this._promptBatchReturnData)},_showPrompt:function(t,e,i,s){this._promptCallback=i,null===this.modal&&(this.modal=new Garnish.Modal({closeOtherModals:!1})),null===this.$modalContainerDiv&&(this.$modalContainerDiv=$('<div class="modal fitted prompt-modal"></div>').addClass().appendTo(Garnish.$bod)),this.$prompt=$('<div class="body"></div>').appendTo(this.$modalContainerDiv.empty()),this.$promptMessage=$('<p class="prompt-msg"/>').appendTo(this.$prompt),this.$promptChoices=$('<div class="options"></div>').appendTo(this.$prompt),this.$promptApplyToRemainingContainer=$('<label class="assets-applytoremaining"/>').appendTo(this.$prompt).hide(),this.$promptApplyToRemainingCheckbox=$('<input type="checkbox"/>').appendTo(this.$promptApplyToRemainingContainer),this.$promptApplyToRemainingLabel=$("<span/>").appendTo(this.$promptApplyToRemainingContainer),this.$promptButtons=$('<div class="buttons right"/>').appendTo(this.$prompt),this.modal.setContainer(this.$modalContainerDiv),this.$promptMessage.html(t);for(var n=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$promptButtons),a=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","OK")}).appendTo(this.$promptButtons),r=0;r<e.length;r++){var o=$('<div><label><input type="radio" name="promptAction" value="'+e[r].value+'"/> '+e[r].title+"</label></div>").appendTo(this.$promptChoices).find("input");this.addListener(o,"click",(function(){a.removeClass("disabled")}))}this.addListener(a,"activate",(function(t){var e=$(t.currentTarget).parents(".modal").find("input[name=promptAction]:checked").val(),i=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice(e,i)})),this.addListener(n,"activate",(function(){var t=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice("cancel",t)})),s&&(this.$promptApplyToRemainingContainer.show(),this.$promptApplyToRemainingLabel.html(" "+Craft.t("app","Apply this to the {number} remaining conflicts?",{number:s}))),this.modal.show(),this.modal.removeListener(Garnish.Modal.$shade,"click"),this.addListener(Garnish.Modal.$shade,"click","_cancelPrompt")},_selectPromptChoice:function(t,e){var i=this;this.$prompt.fadeOut("fast",(function(){i.modal.hide(),i._promptCallback(t,e)}))},_cancelPrompt:function(){this._selectPromptChoice("cancel",!0)}})},8960:function(){Craft.Queue=Garnish.Base.extend({running:!1,paused:!1,pausedForVisibility:!1,jobs:null,get length(){return this.jobs.length},get isPaused(){return this.paused||this.pausedForVisibility},init:function(){var t=this;this.jobs=[],Garnish.$doc.on("visibilitychange",(function(){t.pausedForVisibility&&Craft.isVisible()&&(t.pausedForVisibility=!1,t._resume())}))},push:function(t){return this._add(t,"push")},unshift:function(t){return this._add(t,"unshift")},pause:function(){this.paused||(this.paused=!0,this.pausedForVisibility||this.trigger("pause"))},resume:function(){this.paused&&(this.paused=!1,this._resume())},_add:function(t,e){var i=this;return new Promise((function(s,n){i.jobs[e]((function(){return new Promise((function(e,i){t().then((function(t){s(t),e()})).catch((function(t){n(t),i()}))}))})),i.running||(i.trigger("beforeRun"),i.running=!0,i._exec())}))},clear:function(){this.jobs.length=0},_exec:function(){var t=this;if(!this.jobs.length)return this.running=!1,void this.trigger("afterRun");this.pausedForVisibility||Craft.isVisible()||(this.pausedForVisibility=!0,this.paused||this.trigger("pause")),this.paused||this.pausedForVisibility||(this.trigger("beforeExec"),this.jobs.shift()().finally((function(){t.trigger("afterExec"),t._exec()})))},_resume:function(){this.isPaused||(this.trigger("resume"),this._exec())}}),Craft.queue=new Craft.Queue},4070:function(){!function(t){Craft.SlidePicker=Garnish.Base.extend({min:null,max:null,totalSteps:null,value:null,label:null,describedBy:null,$container:null,$buttons:null,init:function(e,i){var s=this;this.setSettings(i,Craft.SlidePicker.defaults),this.$container=t("<div/>",{class:"slide-picker",role:"slider",tabindex:0}),this.refresh(),this.setValue(e,!1),this.addListener(this.$container,"keydown",(function(t){switch(t.keyCode){case Garnish.UP_KEY:s.setValue(s.value+s.settings.step),t.preventDefault();break;case Garnish.DOWN_KEY:s.setValue(s.value-s.settings.step),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?s.setValue(s.value+s.settings.step):s.setValue(s.value-s.settings.step),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?s.setValue(s.value-s.settings.step):s.setValue(s.value+s.settings.step),t.preventDefault();break;case Garnish.HOME_KEY:s.setValue(s.min),t.preventDefault();break;case Garnish.END_KEY:s.setValue(s.max),t.preventDefault()}}))},refresh:function(){var e=this;if(this.min=this._min(),this.max=this._max(),this.totalSteps=(this.max-this.min)/this.settings.step,this.label=this.settings.label,this.describedBy=this.settings.describedBy,!Number.isInteger(this.totalSteps))throw"Invalid SlidePicker config";this.$buttons&&this.$buttons.remove(),this.$container.attr("aria-valuemin",this.min),this.$container.attr("aria-valuemax",this.max),this.label&&this.$container.attr("aria-label",this.label),this.describedBy&&this.$container.attr("aria-describedby",this.describedBy),this.$buttons=t();for(var i=this.min;i<=this.max;i+=this.settings.step)this.$buttons=this.$buttons.add(t("<a/>",{title:this.settings.valueLabel(i),data:{value:i}}));if(this.$buttons.appendTo(this.$container),null!==this.value){var s=this.value;this.value=null,this.setValue(s,!1)}this.addListener(this.$buttons,"mouseover",(function(i){e.$buttons.removeClass("active-hover last-active-hover"),t(i.currentTarget).addClass("active-hover last-active-hover").prevAll().addClass("active-hover")})),this.addListener(this.$buttons,"mouseout",(function(){e.$buttons.removeClass("active-hover")})),this.addListener(this.$buttons,"click",(function(i){e.setValue(t.data(i.currentTarget,"value")),i.stopPropagation(),e.$container.focus()}))},setValue:function(t,e){if(t=Math.max(Math.min(t,this.max),this.min),this.value!==(this.value=t)){this.$container.attr({"aria-valuenow":this.value,"aria-valuetext":this.settings.valueLabel(this.value)}),this.$buttons.removeClass("last-active active");var i=this.$buttons.eq((this.value-this.min)/this.settings.step);i.add(i.prevAll()).addClass("active"),i.addClass("last-active"),!1!==e&&this.settings.onChange(t)}},_min:function(){return"function"==typeof this.settings.min?this.settings.min():this.settings.min},_max:function(){return"function"==typeof this.settings.max?this.settings.max():this.settings.max}},{defaults:{min:0,max:100,step:10,valueLabel:null,onChange:t.noop}})}(jQuery)},5763:function(){Craft.SlideRuleInput=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,$input:null,value:null,startPositionX:null,init:function(t,e){var i=this;this.setSettings(e,Craft.SlideRuleInput.defaultSettings),this.value=0,this.graduationsMin=-70,this.graduationsMax=70,this.slideMin=-45,this.slideMax=45,this.$container=$("#"+t),this.$overlay=$('<div class="overlay"></div>').appendTo(this.$container),this.$cursor=$('<div class="cursor"></div>').appendTo(this.$container),this.$graduations=$('<div class="graduations"></div>').appendTo(this.$container),this.$graduationsUl=$("<ul></ul>").appendTo(this.$graduations),this.$container.attr({role:"slider",tabindex:"0","aria-valuemin":this.slideMin,"aria-valuemax":this.slideMax,"aria-valuenow":"0","aria-valuetext":Craft.t("app","{num, number} {num, plural, =1{degree} other{degrees}}",{num:0})});for(var s=this.graduationsMin;s<=this.graduationsMax;s++){var n=$('<li class="graduation" data-graduation="'+s+'"><div class="label">'+s+"</div></li>").appendTo(this.$graduationsUl);s%5==0&&n.addClass("main-graduation"),0===s&&n.addClass("selected")}this.$options=this.$container.find(".graduation"),this.addListener(this.$container,"resize",this._handleResize.bind(this)),this.addListener(this.$container,"tapstart",this._handleTapStart.bind(this)),this.addListener(Garnish.$bod,"tapmove",this._handleTapMove.bind(this)),this.addListener(Garnish.$bod,"tapend",this._handleTapEnd.bind(this)),this.addListener(this.$container,"keydown",this._handleKeypress.bind(this)),setTimeout((function(){i.graduationsCalculatedWidth=10*(i.$options.length-1),i.$graduationsUl.css("left",-i.graduationsCalculatedWidth/2+i.$container.width()/2)}),50)},_handleResize:function(){var t=this.valueToPosition(this.value);this.$graduationsUl.css("left",t)},_handleKeypress:function(t){var e=parseInt(this.$container.attr("aria-valuenow"),10);switch(t.keyCode){case Garnish.UP_KEY:case Garnish.RIGHT_KEY:this.setValue(e+1);break;case Garnish.DOWN_KEY:case Garnish.LEFT_KEY:this.setValue(e-1);break;case Garnish.PAGE_UP_KEY:this.setValue(e+10);break;case Garnish.PAGE_DOWN_KEY:this.setValue(e-10);break;case Garnish.HOME_KEY:this.setValue(this.slideMin);break;case Garnish.END_KEY:this.setValue(this.slideMax)}this.onChange()},_handleTapStart:function(t,e){t.preventDefault(),this.startPositionX=e.position.x,this.startLeft=this.$graduationsUl.position().left,this.dragging=!0,this.onStart()},_handleTapMove:function(t,e){if(this.dragging){t.preventDefault();var i=this.startPositionX-e.position.x,s=this.startLeft-i,n=this.positionToValue(s);this.setValue(n),this.onChange()}},setValue:function(t){var e=this.valueToPosition(t);t<this.slideMin?(t=this.slideMin,e=this.valueToPosition(t)):t>this.slideMax&&(t=this.slideMax,e=this.valueToPosition(t)),this.$graduationsUl.css("left",e),t>=this.slideMin&&t<=this.slideMax&&(this.$options.removeClass("selected"),$.each(this.$options,(function(e,i){$(i).data("graduation")>0&&$(i).data("graduation")<=t&&$(i).addClass("selected"),$(i).data("graduation")<0&&$(i).data("graduation")>=t&&$(i).addClass("selected"),0==$(i).data("graduation")&&$(i).addClass("selected")}))),this.$container.attr({"aria-valuenow":t,"aria-valuetext":Craft.t("app","{num, number} {num, plural, =1{degree} other{degrees}}",{num:parseInt(t,10)})}),this.value=t},_handleTapEnd:function(t){this.dragging&&(t.preventDefault(),this.dragging=!1,this.onEnd())},positionToValue:function(t){var e=-1*this.graduationsMin,i=-1*(this.graduationsMin-this.graduationsMax);return(this.$graduations.width()/2+-1*t)/this.graduationsCalculatedWidth*i-e},valueToPosition:function(t){var e=-1*this.graduationsMin,i=-1*(this.graduationsMin-this.graduationsMax);return-((t+e)*this.graduationsCalculatedWidth/i-this.$graduations.width()/2)},onStart:function(){"function"==typeof this.settings.onChange&&this.settings.onStart(this)},onChange:function(){"function"==typeof this.settings.onChange&&this.settings.onChange(this)},onEnd:function(){"function"==typeof this.settings.onChange&&this.settings.onEnd(this)},defaultSettings:{onStart:$.noop,onChange:$.noop,onEnd:$.noop}})},5759:function(){!function(t){Craft.Slideout=Garnish.Base.extend({$outerContainer:null,$container:null,$shade:null,isOpen:!1,init:function(e,i){var s=this;this.setSettings(i,Craft.Slideout.defaults),Craft.useMobileStyles()||(this.$shade=t('<div class="slideout-shade"/>').appendTo(Garnish.$bod),this.settings.closeOnShadeClick&&this.addListener(this.$shade,"click",(function(t){t.stopPropagation(),s.close()}))),this.$outerContainer=t("<div/>",{class:"slideout-container hidden"}),this.$container=t("<".concat(this.settings.containerElement,"/>"),this.settings.containerAttributes).attr("data-slideout","").addClass("slideout").append(e).data("slideout",this).appendTo(this.$outerContainer),Garnish.addModalAttributes(this.$outerContainer),Craft.useMobileStyles()&&this.$container.addClass("so-mobile"),Craft.trapFocusWithin(this.$container),this.settings.autoOpen&&this.open()},open:function(){var t=this;this.isOpen||(this.setTriggerElement(document.activeElement),this._cancelTransitionListeners(),this.$shade&&this.$shade.appendTo(Garnish.$bod).show(),this.$outerContainer.appendTo(Garnish.$bod).removeClass("hidden"),Craft.useMobileStyles()?this.$container.css("top","100vh"):this.$container.css(Garnish.ltr?"left":"right","100vw"),this.$container.one("transitionend.slideout",(function(){Craft.setFocusWithin(t.$container)})),this.$shade&&(this.$shade[0].offsetWidth,this.$shade.addClass("so-visible")),this.$container[0].offsetWidth,Craft.Slideout.addPanel(this),this.enable(),Garnish.uiLayerManager.addLayer(this.$outerContainer),Garnish.hideModalBackgroundLayers(),this.settings.closeOnEsc&&Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.close()})),this.isOpen=!0,this.trigger("open"))},setTriggerElement:function(t){this.settings.triggerElement=t},close:function(){var t=this;this.isOpen&&(this.trigger("beforeClose"),this.disable(),this.isOpen=!1,this._cancelTransitionListeners(),this.$shade&&this.$shade.removeClass("so-visible").one("transitionend.slideout",(function(){t.$shade.hide()})),Craft.Slideout.removePanel(this),Garnish.uiLayerManager.removeLayer(),Garnish.resetModalBackgroundLayerVisibility(),this.$container.one("transitionend.slideout",(function(){t.$outerContainer.addClass("hidden"),t.trigger("close")})),this.settings.triggerElement&&this.settings.triggerElement.focus())},_cancelTransitionListeners:function(){this.$shade&&this.$shade.off("transitionend.slideout"),this.$container.off("transitionend.slideout")},destroy:function(){this.$shade&&(this.$shade.remove(),this.$shade=null),this.$outerContainer.remove(),this.$outerContainer=null,this.$container=null,this.base()}},{defaults:{containerElement:"div",containerAttributes:{},autoOpen:!0,closeOnEsc:!0,closeOnShadeClick:!0,triggerElement:null},openPanels:[],addPanel:function(t){Craft.Slideout.openPanels.unshift(t),Craft.useMobileStyles()?t.$container.css("top",0):Craft.Slideout.updateStyles()},removePanel:function(t){Craft.Slideout.openPanels=Craft.Slideout.openPanels.filter((function(e){return e!==t})),Craft.useMobileStyles()?t.$container.css("top","100vh"):(t.$container.css(Garnish.ltr?"left":"right","100vw"),Craft.Slideout.updateStyles())},updateStyles:function(){var t=Craft.Slideout.openPanels.length;Craft.Slideout.openPanels.forEach((function(e,i){e.$container.css(Garnish.ltr?"left":"right","".concat((t-i)/t*50,"vw"))})),0!==t?Garnish.$bod.addClass("no-scroll"):Garnish.$bod.removeClass("no-scroll")}})}(jQuery)},5185:function(){Craft.SlugGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){t=(t=t.replace(/<(.*?)>/g,"")).replace(/['"‘’“”\[\]\(\)\{\}:]/g,""),Craft.allowUppercaseInSlug||(t=t.toLowerCase()),Craft.limitAutoSlugsToAscii&&(t=Craft.asciiString(t,this.settings.charMap));var e=Craft.filterArray(XRegExp.matchChain(t,[XRegExp("[\\p{L}\\p{N}\\p{M}]+")]));return e.length?e.join(Craft.slugWordSeparator):""}})},8030:function(){Craft.Structure=Garnish.Base.extend({id:null,$container:null,state:null,structureDrag:null,init:function(t,e,i){this.id=t,this.$container=$(e),this.setSettings(i,Craft.Structure.defaults),this.$container.data("structure")&&(console.warn("Double-instantiating a structure on an element"),this.$container.data("structure").destroy()),this.$container.data("structure",this),this.state={},this.settings.storageKey&&$.extend(this.state,Craft.getLocalStorage(this.settings.storageKey,{})),void 0===this.state.collapsedElementIds&&(this.state.collapsedElementIds=[]);for(var s=this.$container.find("ul").prev(".row"),n=0;n<s.length;n++){var a=$(s[n]),r=a.parent(),o=$('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(a);-1!==$.inArray(a.children(".element").data("id"),this.state.collapsedElementIds)&&r.addClass("collapsed"),this.initToggle(o)}this.settings.sortable&&(this.structureDrag=new Craft.StructureDrag(this,this.settings.maxLevels)),this.settings.newChildUrl&&this.initNewChildMenus(this.$container.find(".add"))},initToggle:function(t){var e=this;t.on("click",(function(t){var i=$(t.currentTarget).closest("li"),s=i.children(".row").find(".element:first").data("id"),n=$.inArray(s,e.state.collapsedElementIds);i.hasClass("collapsed")?(i.removeClass("collapsed"),-1!==n&&e.state.collapsedElementIds.splice(n,1)):(i.addClass("collapsed"),-1===n&&e.state.collapsedElementIds.push(s)),e.settings.storageKey&&Craft.setLocalStorage(e.settings.storageKey,e.state)}))},initNewChildMenus:function(t){this.addListener(t,"click","onNewChildMenuClick")},onNewChildMenuClick:function(t){var e=$(t.currentTarget);if(!e.data("menubtn")){var i=e.parent().children(".element").data("id"),s=Craft.getUrl(this.settings.newChildUrl,"parentId="+i);$('<div class="menu"><ul><li><a href="'+s+'">'+Craft.t("app","New child")+"</a></li></ul></div>").insertAfter(e),new Garnish.MenuBtn(e).showMenu()}},getIndent:function(t){return Craft.Structure.baseIndent+(t-1)*Craft.Structure.nestedIndent},addElement:function(t){var e=$('<li data-level="1"/>').appendTo(this.$container),i=$('<div class="row" style="margin-'+Craft.left+": -"+Craft.Structure.baseIndent+"px; padding-"+Craft.left+": "+Craft.Structure.baseIndent+'px;">').appendTo(e);if(i.append(t),this.settings.sortable&&(i.append('<a class="move icon" title="'+Craft.t("app","Move")+'"></a>'),this.structureDrag.addItems(e)),this.settings.newChildUrl){var s=$('<a class="add icon" title="'+Craft.t("app","New child")+'"></a>').appendTo(i);this.initNewChildMenus(s)}i.css("margin-bottom",-30),i.velocity({"margin-bottom":0},"fast")},removeElement:function(t){var e,i=this,s=t.parent().parent();this.settings.sortable&&this.structureDrag.removeItems(s),s.siblings().length||(e=s.parent()),s.css("visibility","hidden").velocity({marginBottom:-s.height()},"fast",(function(){s.remove(),void 0!==e&&i._removeUl(e)}))},_removeUl:function(t){t.siblings(".row").children(".toggle").remove(),t.remove()},destroy:function(){this.$container.removeData("structure"),this.base()}},{baseIndent:8,nestedIndent:35,defaults:{storageKey:null,sortable:!1,newChildUrl:null,maxLevels:null}})},3096:function(){Craft.StructureDrag=Garnish.Drag.extend({structure:null,maxLevels:null,draggeeLevel:null,$helperLi:null,$targets:null,draggeeHeight:null,init:function(t,e){this.structure=t,this.maxLevels=e,this.$insertion=$('<li class="draginsertion"/>');var i=this.structure.$container.find("li");this.base(i,{handle:".element:first, .move:first",helper:this.getHelper.bind(this)})},getHelper:function(t){this.$helperLi=t;var e=$('<ul class="structure draghelper"/>').append(t);return t.css("padding-"+Craft.left,this.$draggee.css("padding-"+Craft.left)),t.find(".move").removeAttr("title"),e},onDragStart:function(){var t=this;this.$targets=$(),this.findTargets(this.structure.$container),this.draggeeLevel=0;var e=this.$draggee;do{this.draggeeLevel++,e=e.find("> ul > li")}while(e.length);this.draggeeHeight=this.$draggee.height(),this.$draggee.velocity({height:0},"fast",(function(){t.$draggee.addClass("hidden")})),this.base(),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.ESC_KEY&&this.cancelDrag()}))},findTargets:function(t){for(var e=t.children().not(this.$draggee),i=0;i<e.length;i++){var s=$(e[i]);this.$targets=this.$targets.add(s.children(".row")),s.hasClass("collapsed")||this.findTargets(s.children("ul"))}},onDrag:function(){for(this._.$closestTarget&&(this._.$closestTarget.removeClass("draghover"),this.$insertion.remove()),this._.$closestTarget=null,this._.closestTargetPos=null,this._.closestTargetYDiff=null,this._.closestTargetOffset=null,this._.closestTargetHeight=null,this._.i=0;this._.i<this.$targets.length&&(this._.$target=$(this.$targets[this._.i]),this._.targetOffset=this._.$target.offset(),this._.targetHeight=this._.$target.outerHeight(),this._.targetYMidpoint=this._.targetOffset.top+this._.targetHeight/2,this._.targetYDiff=Math.abs(this.mouseY-this._.targetYMidpoint),0===this._.i||this.mouseY>=this._.targetOffset.top+5&&this._.targetYDiff<this._.closestTargetYDiff);this._.i++)this._.$closestTarget=this._.$target,this._.closestTargetPos=this._.i,this._.closestTargetYDiff=this._.targetYDiff,this._.closestTargetOffset=this._.targetOffset,this._.closestTargetHeight=this._.targetHeight;if(this._.$closestTarget)if(0===this._.closestTargetPos&&this.mouseY<this._.closestTargetOffset.top+5)this.$insertion.prependTo(this.structure.$container);else if(this._.$closestTargetLi=this._.$closestTarget.parent(),this._.closestTargetLevel=this._.$closestTargetLi.data("level"),this._.closestTargetPos<this.$targets.length-1?(this._.$nextTargetLi=$(this.$targets[this._.closestTargetPos+1]).parent(),this._.nextTargetLevel=this._.$nextTargetLi.data("level")):(this._.$nextTargetLi=null,this._.nextTargetLevel=null),this._.hoveringBetweenRows=this.mouseY>=this._.closestTargetOffset.top+this._.closestTargetHeight-5,this._.$nextTargetLi&&this._.nextTargetLevel==this._.closestTargetLevel)this._.hoveringBetweenRows?(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel-1)&&this.$insertion.insertAfter(this._.$closestTargetLi):(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel)&&this._.$closestTarget.addClass("draghover");else if(this._.$nextTargetLi&&this._.nextTargetLevel>this._.closestTargetLevel)(!this.maxLevels||this.maxLevels>=this._.nextTargetLevel+this.draggeeLevel-1)&&(this._.hoveringBetweenRows?this.$insertion.insertBefore(this._.$nextTargetLi):(this._.$closestTarget.addClass("draghover"),this.$insertion.appendTo(this._.$closestTargetLi.children("ul"))));else if(this._.hoveringBetweenRows){for(this._.draggeeX=this.mouseX-this.targetItemMouseDiffX,"rtl"===Craft.orientation&&(this._.draggeeX+=this.$helperLi.width()),this._.$parentLis=this._.$closestTarget.parentsUntil(this.structure.$container,"li"),this._.$closestParentLi=null,this._.closestParentLiXDiff=null,this._.closestParentLevel=null,this._.i=0;this._.i<this._.$parentLis.length;this._.i++)this._.$parentLi=$(this._.$parentLis[this._.i]),this._.parentLiX=this._.$parentLi.offset().left,"rtl"===Craft.orientation&&(this._.parentLiX+=this._.$parentLi.width()),this._.parentLiXDiff=Math.abs(this._.parentLiX-this._.draggeeX),this._.parentLevel=this._.$parentLi.data("level"),(!this.maxLevels||this.maxLevels>=this._.parentLevel+this.draggeeLevel-1)&&(!this._.$closestParentLi||this._.parentLiXDiff<this._.closestParentLiXDiff&&(!this._.$nextTargetLi||this._.parentLevel>=this._.nextTargetLevel))&&(this._.$closestParentLi=this._.$parentLi,this._.closestParentLiXDiff=this._.parentLiXDiff,this._.closestParentLevel=this._.parentLevel);this._.$closestParentLi&&this.$insertion.insertAfter(this._.$closestParentLi)}else(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel)&&this._.$closestTarget.addClass("draghover")},cancelDrag:function(){this.$insertion.remove(),this._.$closestTarget&&this._.$closestTarget.removeClass("draghover"),this.onMouseUp()},onDragStop:function(){var t=this;if(this._.$closestTarget&&(this.$insertion.parent().length||this._.$closestTarget.hasClass("draghover"))){var e,i;if(this.$draggee.siblings().length||(e=this.$draggee.parent()),this.$insertion.parent().length){var s=this.$insertion.next().add(this.$insertion.prev());-1===$.inArray(this.$draggee[0],s)?(this.$insertion.replaceWith(this.$draggee),i=!0):(this.$insertion.remove(),i=!1)}else{var n=this._.$closestTargetLi.children("ul");if(e&&n.length&&n[0]===e[0])i=!1;else{if(n.length)this._.$closestTargetLi.hasClass("collapsed")&&this._.$closestTarget.children(".toggle").trigger("click");else{var a=$('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(this._.$closestTarget);this.structure.initToggle(a),n=$("<ul>").appendTo(this._.$closestTargetLi)}this.$draggee.appendTo(n),i=!0}}if(this._.$closestTarget.removeClass("draghover"),i){e&&this.structure._removeUl(e);var r,o=this.$draggee.parentsUntil(this.structure.$container,"li").length+1;o!=this.$draggee.data("level")&&(1==this.$draggee.data("level")?((r={})["padding-"+Craft.left]=38,this.$helperLi.velocity(r,"fast")):1==o&&((r={})["padding-"+Craft.left]=Craft.Structure.baseIndent,this.$helperLi.velocity(r,"fast")),this.setLevel(this.$draggee,o));var l=this.$draggee.children(".row").children(".element"),h={structureId:this.structure.id,elementId:l.data("id"),siteId:l.data("site-id"),prevId:this.$draggee.prev().children(".row").children(".element").data("id"),parentId:this.$draggee.parent("ul").parent("li").children(".row").children(".element").data("id")};Craft.sendActionRequest("POST","structures/move-element",{data:h}).then((function(t){Craft.cp.displaySuccess(Craft.t("app","New order saved."))}))}}this.$draggee.velocity("stop").removeClass("hidden").velocity({height:this.draggeeHeight},"fast",(function(){t.$draggee.css("height","auto")})),this.returnHelpersToDraggees(),this.base()},setLevel:function(t,e){t.data("level",e);var i=this.structure.getIndent(e),s={};s["margin-"+Craft.left]="-"+i+"px",s["padding-"+Craft.left]=i+"px",this.$draggee.children(".row").css(s);for(var n=t.children("ul").children(),a=0;a<n.length;a++)this.setLevel($(n[a]),e+1)}})},3331:function(){Craft.StructureTableSorter=Garnish.DragSort.extend({tableView:null,structureId:null,maxLevels:null,_basePadding:null,_helperMargin:null,_$firstRowCells:null,_$titleHelperCell:null,_titleHelperCellOuterWidth:null,_ancestors:null,_updateAncestorsFrame:null,_draggeeLevel:null,_draggeeLevelDelta:null,draggingLastElements:null,_loadingDraggeeLevelDelta:!1,_targetLevel:null,_targetLevelBounds:null,_positionChanged:null,init:function(t,e,i){this.tableView=t,this.structureId=this.tableView.$table.data("structure-id"),this.maxLevels=parseInt(this.tableView.$table.attr("data-max-levels")),this._basePadding=14+(this.tableView.elementIndex.actions?34:24),this._helperMargin=this.tableView.elementIndex.actions?54:0,i=$.extend({},Craft.StructureTableSorter.defaults,i,{handle:".move",collapseDraggees:!0,singleHelper:!0,helperSpacingY:2,magnetStrength:4,helper:this.getHelper.bind(this),helperLagBase:1.5,axis:Garnish.Y_AXIS}),this.base(e,i)},findDraggee:function(){var t=this;this._draggeeLevel=this._targetLevel=this.$targetItem.data("level"),this._draggeeLevelDelta=0;for(var e=$(this.$targetItem),i=this.$targetItem.next();i.length;){var s=i.data("level");if(s<=this._draggeeLevel)break;var n=s-this._draggeeLevel;n>this._draggeeLevelDelta&&(this._draggeeLevelDelta=n),e=e.add(i),i=i.next()}if(this.draggingLastElements=!i.length,this.maxLevels&&this.draggingLastElements&&this.tableView.getMorePending()){this._loadingDraggeeLevelDelta=!0;var a=this._getAjaxBaseData(this.$targetItem);Craft.sendActionRequest("POST","structures/get-element-level-delta",{data:a}).then((function(e){t._loadingDraggeeLevelDelta=!1,t.dragging&&(t._draggeeLevelDelta=e.data.delta,t.drag(!1))}))}return e},getHelper:function(t){var e=$('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),i=$('<div class="tableview"/>').appendTo(e),s=$('<table class="data"/>').appendTo(i),n=$("<tbody/>").appendTo(s);t.appendTo(n),this._$firstRowCells=this.tableView.$elementContainer.children("tr:first").children();for(var a=t.children(),r=0;r<a.length;r++){var o=$(a[r]);if(o.hasClass("checkbox-cell"))o.remove();else{var l=$(this._$firstRowCells[r]),h=l[0].getBoundingClientRect().width;l.css("width",h+"px"),o.css("width",h+"px"),Garnish.hasAttr(l,"data-titlecell")&&(this._$titleHelperCell=o,parseInt(l.css("padding-"+Craft.left)),this._titleHelperCellOuterWidth=h,o.css("padding-"+Craft.left,this._basePadding))}}return e},canInsertBefore:function(t){return!this._loadingDraggeeLevelDelta&&!1!==this._getLevelBounds(t.prev(),t)},canInsertAfter:function(t){return!this._loadingDraggeeLevelDelta&&!1!==this._getLevelBounds(t,t.next())},onDragStart:function(){this._ancestors=this._getAncestors(this.$targetItem,this.$targetItem.data("level")),this._setTargetLevelBounds(),this.tableView.maybeLoadMore(),this.base()},onDrag:function(){this.base(),this._updateIndent()},onInsertionPointChange:function(){this._setTargetLevelBounds(),this._updateAncestorsBeforeRepaint(),this.base()},onDragStop:function(){var t=this;if(this._positionChanged=!1,this.base(),this._targetLevel!=this._draggeeLevel){for(var e=this._targetLevel-this._draggeeLevel,i=0;i<this.$draggee.length;i++){var s=$(this.$draggee[i]),n=s.data("level")+e,a=this._basePadding+this._getLevelIndent(n);s.data("level",n),s.find(".element").data("level",n),s.children("[data-titlecell]:first").css("padding-"+Craft.left,a)}this._positionChanged=!0}if(this._positionChanged){for(var r=this._getAjaxBaseData(this.$draggee),o=this.$draggee.first().prev();o.length;){var l=o.data("level");if(l==this._targetLevel){r.prevId=o.data("id");break}if(l<this._targetLevel){r.parentId=o.data("id");var h=o.find("> th > .toggle");if(!h.hasClass("expanded")){h.addClass("expanded");var d=this.tableView._createSpinnerRowAfter(o);this.tableView.elementSelect&&this.tableView.elementSelect.removeItems(this.$targetItem),this.removeItems(this.$targetItem),this.$targetItem.remove(),this.tableView._totalVisible--}break}o=o.prev()}Craft.sendActionRequest("POST","structures/move-element",{data:r}).then((function(e){Craft.cp.displaySuccess(Craft.t("app","New position saved.")),t.onPositionChange(),d&&d.parent().length&&(d.remove(),t.tableView._expandElement(h,!0)),Craft.cp.runQueue()})).catch((function(e){e.response,Craft.cp.displayError(Craft.t("app","A server error occurred.")),t.tableView.elementIndex.updateElements()}))}},onSortChange:function(){this.tableView.elementSelect&&this.tableView.elementSelect.resetItemOrder(),this._positionChanged=!0,this.base()},onPositionChange:function(){var t=this;Garnish.requestAnimationFrame((function(){t.trigger("positionChange"),t.settings.onPositionChange()}))},onReturnHelpersToDraggees:function(){if(this._$firstRowCells.css("width",""),this.draggingLastElements&&this.tableView.getMorePending()){this.tableView._totalVisible+=this.newDraggeeIndexes[0]-this.oldDraggeeIndexes[0];var t=this.$draggee.last().nextAll();t.length&&(this.removeItems(t),t.remove(),this.tableView.maybeLoadMore())}this.base()},_getLevelBounds:function(t,e){if(e&&e.length?this._getLevelBounds._minLevel=e.data("level"):this._getLevelBounds._minLevel=1,t&&t.length?this._getLevelBounds._maxLevel=t.data("level")+1:this._getLevelBounds._maxLevel=1,this.maxLevels){if(1!=this._getLevelBounds._minLevel&&this._getLevelBounds._minLevel+this._draggeeLevelDelta>this.maxLevels)return!1;this._getLevelBounds._maxLevel+this._draggeeLevelDelta>this.maxLevels&&(this._getLevelBounds._maxLevel=this.maxLevels-this._draggeeLevelDelta,this._getLevelBounds._maxLevel<this._getLevelBounds._minLevel&&(this._getLevelBounds._maxLevel=this._getLevelBounds._minLevel))}return{min:this._getLevelBounds._minLevel,max:this._getLevelBounds._maxLevel}},_setTargetLevelBounds:function(){this._targetLevelBounds=this._getLevelBounds(this.$draggee.first().prev(),this.$draggee.last().next())},_updateIndent:function(t){this._updateIndent._mouseDist=this.realMouseX-this.mousedownX,"rtl"===Craft.orientation&&(this._updateIndent._mouseDist*=-1),this._updateIndent._indentationDist=Math.round(this._updateIndent._mouseDist/Craft.StructureTableSorter.LEVEL_INDENT),this._updateIndent._targetLevel=this._draggeeLevel+this._updateIndent._indentationDist,this._updateIndent._targetLevel<this._targetLevelBounds.min?(this._updateIndent._indentationDist+=this._targetLevelBounds.min-this._updateIndent._targetLevel,this._updateIndent._targetLevel=this._targetLevelBounds.min):this._updateIndent._targetLevel>this._targetLevelBounds.max&&(this._updateIndent._indentationDist-=this._updateIndent._targetLevel-this._targetLevelBounds.max,this._updateIndent._targetLevel=this._targetLevelBounds.max),this._targetLevel!==(this._targetLevel=this._updateIndent._targetLevel)&&this._updateAncestorsBeforeRepaint(),this._updateIndent._targetLevelMouseDiff=this._updateIndent._mouseDist-this._updateIndent._indentationDist*Craft.StructureTableSorter.LEVEL_INDENT,this._updateIndent._magnetImpact=Math.round(this._updateIndent._targetLevelMouseDiff/15),Math.abs(this._updateIndent._magnetImpact)>Craft.StructureTableSorter.MAX_GIVE&&(this._updateIndent._magnetImpact=(this._updateIndent._magnetImpact>0?1:-1)*Craft.StructureTableSorter.MAX_GIVE),this._updateIndent._closestLevelMagnetIndent=this._getLevelIndent(this._targetLevel)+this._updateIndent._magnetImpact,this.helpers[0].css("margin-"+Craft.left,this._updateIndent._closestLevelMagnetIndent+this._helperMargin),this._$titleHelperCell.css("width",this._titleHelperCellOuterWidth-this._updateIndent._closestLevelMagnetIndent)},_getLevelIndent:function(t){return(t-1)*Craft.StructureTableSorter.LEVEL_INDENT},_getAjaxBaseData:function(t){return{structureId:this.structureId,elementId:t.data("id"),siteId:t.find(".element:first").data("site-id")}},_getAncestors:function(t,e){if(this._getAncestors._ancestors=[],0!=e)for(this._getAncestors._level=e,this._getAncestors._$prevRow=t.prev();this._getAncestors._$prevRow.length&&!(this._getAncestors._$prevRow.data("level")<this._getAncestors._level&&(this._getAncestors._ancestors.unshift(this._getAncestors._$prevRow),this._getAncestors._level=this._getAncestors._$prevRow.data("level"),0==this._getAncestors._level));)this._getAncestors._$prevRow=this._getAncestors._$prevRow.prev();return this._getAncestors._ancestors},_updateAncestorsBeforeRepaint:function(){this._updateAncestorsFrame&&Garnish.cancelAnimationFrame(this._updateAncestorsFrame),this._updateAncestorsFrame=Garnish.requestAnimationFrame(this._updateAncestors.bind(this))},_updateAncestors:function(){for(this._updateAncestorsFrame=null,this._updateAncestors._i=0;this._updateAncestors._i<this._ancestors.length;this._updateAncestors._i++)this._updateAncestors._$ancestor=this._ancestors[this._updateAncestors._i],this._updateAncestors._$ancestor.data("descendants",this._updateAncestors._$ancestor.data("descendants")-1),0==this._updateAncestors._$ancestor.data("descendants")&&this._updateAncestors._$ancestor.find("> th > .toggle:first").remove();for(this._updateAncestors._newAncestors=this._getAncestors(this.$targetItem,this._targetLevel),this._updateAncestors._i=0;this._updateAncestors._i<this._updateAncestors._newAncestors.length;this._updateAncestors._i++)if(this._updateAncestors._$ancestor=this._updateAncestors._newAncestors[this._updateAncestors._i],this._updateAncestors._$ancestor.data("descendants",this._updateAncestors._$ancestor.data("descendants")+1),1==this._updateAncestors._$ancestor.data("descendants")){var t=this._updateAncestors._$ancestor.data("title");$('<button class="toggle expanded" type="button" aria-expanded="true" title="'+Craft.t("app","Show/hide children")+'" aria-label="'+Craft.t("app","Show {title} children",{title:t})+'"></button>').insertAfter(this._updateAncestors._$ancestor.find("> th .move:first"))}this._ancestors=this._updateAncestors._newAncestors,delete this._updateAncestors._i,delete this._updateAncestors._$ancestor,delete this._updateAncestors._newAncestors}},{HELPER_MARGIN:0,LEVEL_INDENT:44,MAX_GIVE:22,defaults:{onPositionChange:$.noop}})},53:function(){function t(t,i){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(t,i)||function(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}(t,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.TableElementIndexView=Craft.BaseElementIndexView.extend({$table:null,$tableCaption:null,$selectedSortHeader:null,$statusMessage:null,structureTableSort:null,_totalVisiblePostStructureTableDraggee:null,_morePendingPostStructureTableDraggee:!1,_broadcastListener:null,getElementContainer:function(){return this.$table=this.$container.find("table:first"),this.$table.children("tbody:first")},afterInit:function(){var t=this;this.$tableCaption=this.$table.find("caption"),this.$statusMessage=this.$table.parent().find("[data-status-message]"),this.initTableHeaders(),this.elementIndex.on("updateElements",(function(){t._updateScreenReaderStatus()})),"index"===this.elementIndex.settings.context&&"structure"===this.elementIndex.viewMode&&Garnish.hasAttr(this.$table,"data-structure-id")?this.structureTableSort=new Craft.StructureTableSorter(this,this.getAllElements()):this.structureTableSort=null,"structure"===this.elementIndex.viewMode&&this.addListener(this.$elementContainer,"click",(function(t){var e=$(t.target);e.hasClass("toggle")&&!1===this._collapseElement(e)&&this._expandElement(e)})),Craft.messageReceiver&&(this._broadcastListener=function(e){if("saveElement"===e.data.event){var i=t.$table.find('> tbody > tr[data-id="'.concat(e.data.id,'"]'));if(i.length){var s={elementType:t.elementIndex.elementType,source:t.elementIndex.sourceKey,id:e.data.id,siteId:t.elementIndex.siteId};Craft.sendActionRequest("POST","element-indexes/element-table-html",{data:s}).then((function(t){for(var e=t.data,s=0;s<i.length;s++){var n=i.eq(s);for(var a in n.find("> th[data-titlecell] .element").replaceWith(e.elementHtml),e.attributeHtml)e.attributeHtml.hasOwnProperty(a)&&n.find('> td[data-attr="'.concat(a,'"]')).html(e.attributeHtml[a])}Craft.cp.elementThumbLoader.load(i)}))}}},Craft.messageReceiver.addEventListener("message",this._broadcastListener))},initTableHeaders:function(){var e,i;if("structure"===this.elementIndex.viewMode)e="structure",i="asc";else{var s=t(this.elementIndex.getSortAttributeAndDirection(),2);e=s[0],i=s[1]}for(var n=this.$table.children("thead").children().children("[data-attribute]"),a=0;a<n.length;a++){var r=n.eq(a),o=r.attr("data-attribute"),l="none";o===e?(this.$selectedSortHeader=r,l="asc"===i?"ascending":"descending",r.addClass("ordered "+i),this.makeColumnSortable(r,!0)):this.elementIndex.getSortOption(o)&&this.makeColumnSortable(r),r.attr("aria-sort",l)}},makeColumnSortable:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];t.addClass("orderable");var i=t.html(),s=this.$tableCaption.find("[data-sort-instructions]"),n=$("<button/>",{id:"".concat(this.elementIndex.idPrefix,"-").concat(t.attr("data-attribute")),type:"button","aria-pressed":"false"}).html(i);s.length&&n.attr("aria-describedby",s.attr("id")),e?(n.attr("aria-pressed","true"),n.on("click",this._handleSelectedSortHeaderClick.bind(this))):n.on("click",this._handleUnselectedSortHeaderClick.bind(this)),t.empty().append(n)},isVerticalList:function(){return!0},getTotalVisible:function(){return this._isStructureTableDraggingLastElements()?this._totalVisiblePostStructureTableDraggee:this._totalVisible},setTotalVisible:function(t){this._isStructureTableDraggingLastElements()?this._totalVisiblePostStructureTableDraggee=t:this._totalVisible=t},getMorePending:function(){return this._isStructureTableDraggingLastElements()?this._morePendingPostStructureTableDraggee:this._morePending},setMorePending:function(t){this._isStructureTableDraggingLastElements()?this._morePendingPostStructureTableDraggee=t:this._morePending=this._morePendingPostStructureTableDraggee=t},getLoadMoreParams:function(){var t=this.base();return this._isStructureTableDraggingLastElements()&&(t.criteria.positionedAfter=this.structureTableSort.$targetItem.data("id")),t},appendElements:function(t){this.base(t),this.structureTableSort&&this.structureTableSort.addItems(t),Craft.cp.updateResponsiveTables()},_collapseElement:function(t,e){if(!e&&!t.hasClass("expanded"))return!1;t.removeClass("expanded"),t.attr("aria-expanded","false");for(var i=t.parent().parent(),s=i.data("id"),n=i.data("level"),a=i.next();a.length;){if(!Garnish.hasAttr(a,"data-spinnerrow")){if(a.data("level")<=n)break;this.elementSelect&&this.elementSelect.removeItems(a),this.structureTableSort&&this.structureTableSort.removeItems(a),this._totalVisible--}var r=a.next();a.remove(),a=r}this.elementIndex.instanceState.collapsedElementIds||(this.elementIndex.instanceState.collapsedElementIds=[]),this.elementIndex.instanceState.collapsedElementIds.push(s),this.elementIndex.setInstanceState("collapsedElementIds",this.elementIndex.instanceState.collapsedElementIds),this.maybeLoadMore()},_expandElement:function(t,e){var i=this;if(!e&&t.hasClass("expanded"))return!1;if(t.addClass("expanded"),t.attr("aria-expanded","true"),this.elementIndex.instanceState.collapsedElementIds){var s=t.parent().parent(),n=s.data("id"),a=$.inArray(n,this.elementIndex.instanceState.collapsedElementIds);if(-1!==a){this.elementIndex.instanceState.collapsedElementIds.splice(a,1),this.elementIndex.setInstanceState("collapsedElementIds",this.elementIndex.instanceState.collapsedElementIds);var r=this._createSpinnerRowAfter(s),o=$.extend(!0,{},this.settings.params);o.criteria.descendantOf=n,Craft.sendActionRequest("POST",this.settings.loadMoreElementsAction,{data:o}).then((function(t){if(r.parent().length){var e=$(t.data.html),s=i._totalVisible+e.length,n=i.settings.batchSize&&e.length===i.settings.batchSize;if(n){var a=r.nextAll();i.elementSelect&&i.elementSelect.removeItems(a),i.structureTableSort&&i.structureTableSort.removeItems(a),a.remove(),s-=a.length}else n=i._morePending;r.replaceWith(e),i.thumbLoader.load(e),(i.elementIndex.actions||i.settings.selectable)&&(i.elementSelect.addItems(e.filter(":not(.disabled)")),i.elementIndex.updateActionTriggers()),i.structureTableSort&&i.structureTableSort.addItems(e),Craft.appendHeadHtml(t.data.headHtml),Craft.appendBodyHtml(t.data.bodyHtml),Craft.cp.updateResponsiveTables(),i.setTotalVisible(s),i.setMorePending(n),i.maybeLoadMore()}})).catch((function(t){Craft.cp.displayError(),r.parent().length}))}}},_createSpinnerRowAfter:function(t){return $('<tr data-spinnerrow><td class="centeralign" colspan="'+t.children().length+'"><div class="spinner"/></td></tr>').insertAfter(t)},_isStructureTableDraggingLastElements:function(){return this.structureTableSort&&this.structureTableSort.dragging&&this.structureTableSort.draggingLastElements},_handleSelectedSortHeaderClick:function(t){var e=$(t.currentTarget).closest("th");if(!e.hasClass("loading")){var i="asc"===this.elementIndex.getSelectedSortDirection()?"desc":"asc";this.elementIndex.selectViewMode("table"),this.elementIndex.setSelectedSortDirection(i),this._handleSortHeaderClick(t,e)}},_handleUnselectedSortHeaderClick:function(t){var e=$(t.currentTarget).closest("th");if(!e.hasClass("loading")){var i=e.attr("data-attribute");this.elementIndex.selectViewMode("table"),this.elementIndex.setSelectedSortAttribute(i),this._handleSortHeaderClick(t,e)}},_handleSortHeaderClick:function(t,e){this.$selectedSortHeader&&this.$selectedSortHeader.removeClass("ordered asc desc"),e.addClass("ordered loading"),this.elementIndex.updateElements(),this.elementIndex.setIndexAvailable()},_updateScreenReaderStatus:function(){var e,i;if("structure"===this.elementIndex.viewMode)e="structure",i="asc";else{var s=t(this.elementIndex.getSortAttributeAndDirection(),2);e=s[0],i=s[1]}var n=this.elementIndex.getSortLabel(e);if(n){var a="asc"===i?Craft.t("app","Ascending"):Craft.t("app","Descending"),r=Craft.t("app","Table {name} sorted by {attribute}, {direction}",{name:this.$table.attr("data-name"),attribute:n,direction:a});this.$statusMessage.empty(),this.$statusMessage.text(r)}},_updateTableAttributes:function(t,e){var i=t.closest("tr");for(var s in e)e.hasOwnProperty(s)&&i.children('[data-attr="'+s+'"]:first').html(e[s])},destroy:function(){this._broadcastListener&&(Craft.messageReceiver.removeEventListener("message",this._broadcastListener),delete this._broadcastListener),this.base()}})},7745:function(){Craft.Tabs=Garnish.Base.extend({$container:null,$tablist:null,$menuBtn:null,$tabs:null,$firstTab:null,$lastTab:null,$selectedTab:null,$focusableTab:null,menu:null,init:function(t){var e=this;this.$container=$(t),this.$tablist=this.$container.find('> [role="tablist"]:first'),this.$tabs=this.$tablist.find('> [role="tab"]'),this.$firstTab=this.$tabs.first(),this.$lastTab=this.$tabs.last(),this.$selectedTab=this.$tabs.filter(".sel:first"),this.$focusableTab=this.$tabs.filter("[tabindex=0]:first"),this.$menuBtn=this.$container.find("> .menubtn:first").menubtn(),this.menu=this.$menuBtn.data("menubtn").menu,this.$container.data("tabs")&&(console.warn("Double-instantiating a tab manager on an element"),this.$container.data("tabs").destroy()),this.$container.data("tabs",this);for(var i=0;i<this.$tabs.length;i++){var s=this.$tabs.eq(i),n=s.attr("href");n&&"#"===n.charAt(0)&&(this.addListener(s,"keydown",(function(t){[Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)&&(t.preventDefault(),e.selectTab(t.currentTarget))})),this.addListener(s,"click",(function(t){t.preventDefault(),e.selectTab(t.currentTarget)}))),this.addListener(s,"keydown",(function(t){var i;[Garnish.LEFT_KEY,Garnish.RIGHT_KEY].includes(t.keyCode)&&$.contains(e.$tablist[0],t.currentTarget)?i=t.keyCode===("ltr"===Craft.orientation?Garnish.LEFT_KEY:Garnish.RIGHT_KEY)?(i=$(t.currentTarget).prevAll('[role="tab"]:not(.hidden):first')).length?i:e.$lastTab:(i=$(t.currentTarget).nextAll('[role="tab"]:not(.hidden):first')).length?i:e.$firstTab:t.keyCode!==Garnish.HOME_KEY&&t.keyCode!==Garnish.END_KEY||(i=t.keyCode===Garnish.HOME_KEY?e.$firstTab:e.$lastTab),i&&(t.preventDefault(),e.makeTabFocusable(i),i.focus(),e.scrollToTab(i))}))}this.updateMenuBtn(),Garnish.$win.on("resize",(function(){e.updateMenuBtn()})),this.menu.$options.on("click",(function(t){var e=$(t.currentTarget).attr("href");e&&"#"===e.charAt(0)&&t.preventDefault()})),this.menu.on("optionselect",(function(t){e.selectTab($(t.selectedOption).data("id"))}))},selectTab:function(t){var e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._getTab(t);if(i[0]!==this.$selectedTab[0]){this.deselectTab(),this.$selectedTab=i.addClass("sel").attr("aria-selected","true"),this.makeTabFocusable(i),e&&i.trigger("focus"),this.scrollToTab(i),this.menu.$options.removeClass("sel"),this.menu.$options.filter('[data-id="'.concat(i.data("id"),'"]')).addClass("sel"),this.trigger("selectTab",{$tab:i}),$("#content").trigger("scroll");var s=i.closest(".slideout-container");s.length&&s.find(".so-content").trigger("scroll")}},deselectTab:function(){var t=this.$selectedTab.removeClass("sel").attr("aria-selected","false");this.$selectedTab=null,this.trigger("deselectTab",{$tab:t})},makeTabFocusable:function(t){var e=this._getTab(t);e[0]!==this.$focusableTab[0]&&(this.$focusableTab.attr("tabindex","-1"),this.$focusableTab=e.attr("tabindex","0"))},scrollToTab:function(t){var e=this._getTab(t),i=this.$tablist.scrollLeft(),s=e.offset().left-this.$tablist.offset().left,n=!1;if(s<0)n=i+s-24;else{var a=e.outerWidth(),r=this.$tablist.prop("clientWidth");s+a>r&&(n=i+(s-(r-a))+24)}!1!==n&&this.$tablist.scrollLeft(n)},updateMenuBtn:function(){Math.floor(this.$tablist.prop("scrollWidth")-48)>this.$container.prop("clientWidth")?(this.$tablist.addClass("scrollable"),this.$menuBtn.removeClass("hidden")):(this.$tablist.removeClass("scrollable"),this.$menuBtn.addClass("hidden"))},_getTab:function(t){if(t instanceof jQuery)return t;if(t instanceof HTMLElement)return $(t);if("string"!=typeof t)throw"Invalid tab ID";var e=this.$tabs.filter('[data-id="'.concat(t,'"]'));if(!e.length)throw"Invalid tab ID: ".concat(t);return e},destroy:function(){this.$container.removeData("tabs"),this.base()}})},5074:function(){Craft.TagSelectInput=Craft.BaseElementSelectInput.extend({searchTimeout:null,searchMenu:null,$container:null,$elementsContainer:null,$elements:null,$addTagInput:null,$spinner:null,_ignoreBlur:!1,init:function(t){var e=this;if(!$.isPlainObject(t)){for(var i={},s=["id","name","tagGroupId","sourceElementId"],n=0;n<s.length&&void 0!==arguments[n];n++)i[s[n]]=arguments[n];t=i}this.base($.extend({},Craft.TagSelectInput.defaults,t)),this.$addTagInput=this.$container.children(".add").children(".text"),this.$spinner=this.$addTagInput.next(),this.addListener(this.$addTagInput,"input",(function(){e.searchTimeout&&clearTimeout(e.searchTimeout),e.searchTimeout=setTimeout(e.searchForTags.bind(e),500)})),this.addListener(this.$addTagInput,"keydown",(function(t){switch(t.keyCode===Garnish.RETURN_KEY&&t.preventDefault(),t.keyCode){case Garnish.RETURN_KEY:return t.preventDefault(),void(this.searchMenu&&this.selectTag(this.searchMenu.$options.filter(".hover")));case Garnish.DOWN_KEY:if(t.preventDefault(),this.searchMenu){var e=this.searchMenu.$options.filter(".hover");if(e.length){var i=e.parent().nextAll().find("a:not(.disabled)").first();i.length&&this.focusOption(i)}else this.focusOption(this.searchMenu.$options.eq(0))}return;case Garnish.UP_KEY:if(t.preventDefault(),this.searchMenu){var s=this.searchMenu.$options.filter(".hover");if(s.length){var n=s.parent().prevAll().find("a:not(.disabled)").last();n.length&&this.focusOption(n)}else this.focusOption(this.searchMenu.$options.eq(this.searchMenu.$options.length-1))}return}})),this.addListener(this.$addTagInput,"focus",(function(){this.searchMenu&&this.searchMenu.show()})),this.addListener(this.$addTagInput,"blur",(function(){var t=this;this._ignoreBlur?this._ignoreBlur=!1:setTimeout((function(){t.searchMenu&&t.searchMenu.hide()}),1)}))},focusOption:function(t){this.searchMenu.$options.removeClass("hover"),t.addClass("hover"),this.searchMenu.$menuList.attr("aria-activedescendant",t.attr("id"))},getAddElementsBtn:$.noop,getElementSortAxis:function(){return null},searchForTags:function(){var t=this;if(this.searchMenu&&this.killSearchMenu(),this.$addTagInput.val()){this.$spinner.removeClass("hidden");for(var e=[],i=0;i<this.$elements.length;i++){var s=$(this.$elements[i]).data("id");s&&e.push(s)}this.settings.sourceElementId&&!this.settings.allowSelfRelations&&e.push(this.settings.sourceElementId);var n={search:this.$addTagInput.val(),tagGroupId:this.settings.tagGroupId,excludeIds:e};Craft.sendActionRequest("POST","tags/search-for-tags",{data:n}).then((function(e){t.searchMenu&&t.killSearchMenu(),t.$spinner.addClass("hidden");for(var i,s=$('<div class="menu tagmenu"/>').appendTo(Garnish.$bod),a=$("<ul/>").appendTo(s),r=0;r<e.data.tags.length;r++)i=$("<li/>").appendTo(a),$('<a data-icon="tag"/>').appendTo(i).text(e.data.tags[r].title).data("id",e.data.tags[r].id).addClass(e.data.tags[r].exclude?"disabled":"");e.data.exactMatch||(i=$("<li/>").appendTo(a),$('<a data-icon="plus"/>').appendTo(i).text(n.search)),a.find("a:not(.disabled):first").addClass("hover"),t.searchMenu=new Garnish.Menu(s,{attachToElement:t.$addTagInput,onOptionSelect:t.selectTag.bind(t)}),t.addListener(s,"mousedown",(function(){t._ignoreBlur=!0})),t.searchMenu.show()})).catch((function(e){e.response,t.searchMenu&&t.killSearchMenu(),t.$spinner.addClass("hidden")}))}else this.$spinner.addClass("hidden")},selectTag:function(t){var e=this,i=$(t);if(!i.hasClass("disabled")){var s=i.data("id"),n=i.text(),a=$("<div/>",{class:"element small removable","data-id":s,"data-site-id":this.settings.targetSiteId,"data-label":n,"data-editable":"1"}).appendTo(this.$elementsContainer),r=$("<input/>",{type:"hidden",name:this.settings.name+"[]",value:s}).appendTo(a);$("<button/>",{class:"delete icon",title:Craft.t("app","Remove"),type:"button","aria-label":Craft.t("app","Remove {label}",{label:n})}).appendTo(a);var o=$("<div/>",{class:"label"}).appendTo(a);if($("<span/>",{class:"title",text:n}).appendTo(o),this.$elements=this.$elements.add(a),this.addElements(a),this.killSearchMenu(),this.$addTagInput.val(""),this.$addTagInput.trigger("focus"),!s){a.addClass("loading disabled");var l={groupId:this.settings.tagGroupId,title:n};Craft.sendActionRequest("POST","tags/create-tag",{data:l}).then((function(t){a.attr("data-id",t.data.id),r.val(t.data.id),a.removeClass("loading disabled")})).catch((function(t){t.response,e.removeElement(a),Craft.cp.displayError(Craft.t("app","A server error occurred."))}))}}},killSearchMenu:function(){this.searchMenu.hide(),this.searchMenu.destroy(),this.searchMenu=null}},{defaults:{tagGroupId:null}})},3958:function(){Craft.ThumbsElementIndexView=Craft.BaseElementIndexView.extend({getElementContainer:function(){return this.$container.children("ul")}})},1592:function(){Craft.ui={createButton:function(t){var e=$("<button/>",{type:t.type||"button",class:"btn"});return t.id&&e.attr("id",t.id),t.class&&e.addClass(t.class),t.ariaLabel&&e.attr("aria-label",t.ariaLabel),t.role&&e.attr("role",t.role),t.html?e.html(t.html):t.label?e.append($('<div class="label"/>').text(t.label)):e.addClass("btn-empty"),t.toggle&&e.attr("aria-expanded","false"),t.controls&&e.attr("aria-controls",t.controls),t.spinner&&e.append($('<div class="spinner spinner-absolute"/>')),e},createSubmitButton:function(t){var e=this.createButton(Object.assign({},t,{type:"submit",label:t.label||Craft.t("app","Submit")}));return e.addClass("submit"),e},createTextInput:function(t){t=$.extend({autocomplete:!1},t);var e=$("<input/>",{attr:{class:"text",type:t.type||"text",inputmode:t.inputmode,id:t.id,size:t.size,name:t.name,value:t.value,maxlength:t.maxlength,autofocus:this.getAutofocusValue(t.autofocus),autocomplete:"boolean"==typeof t.autocomplete?t.autocomplete?"on":"off":t.autocomplete,disabled:this.getDisabledValue(t.disabled),readonly:t.readonly,title:t.title,placeholder:t.placeholder,step:t.step,min:t.min,max:t.max}});return t.class&&e.addClass(t.class),t.placeholder&&e.addClass("nicetext"),"password"===t.type&&e.addClass("password"),t.disabled&&e.addClass("disabled"),t.size||e.addClass("fullwidth"),t.showCharsLeft&&t.maxlength&&e.attr("data-show-chars-left").css("padding-"+("ltr"===Craft.orientation?"right":"left"),7.2*t.maxlength.toString().length+14+"px"),(t.placeholder||t.showCharsLeft)&&new Garnish.NiceText(e),"password"===t.type?$('<div class="passwordwrapper"/>').append(e):e},createTextField:function(t){return t.id||(t.id="text"+Math.floor(1e9*Math.random())),this.createField(this.createTextInput(t),t)},createCopyTextInput:function(t){var e=t.id||"copytext"+Math.floor(1e9*Math.random()),i=t.buttonId||"".concat(e,"-btn"),s=$("<div/>",{class:"copytext"}),n=this.createTextInput($.extend({},t,{readonly:!0})).appendTo(s);return $("<button/>",{type:"button",id:i,class:"btn","data-icon":"clipboard",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard")}).appendTo(s).on("click",(function(){n[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),s.trigger("copy"),n[0].setSelectionRange(0,0)})),s},createCopyTextBtn:function(t){var e=t.id||"copytext"+Math.floor(1e9*Math.random()),i=t.value,s=$("<div/>",{id:e,class:"copytextbtn",role:"button",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard"),tabindex:"0"});t.class&&s.addClass(t.class);var n=$("<input/>",{value:i,readonly:!0,size:i.length,tabindex:"-1"}).appendTo(s),a=($("<span/>",{"data-icon":"clipboard","aria-hidden":"true"}).appendTo(s),function(){n[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),s.trigger("copy"),n[0].setSelectionRange(0,0),s.focus()});return s.on("click",(function(){a()})),s.on("keydown",(function(t){t.keyCode===Garnish.SPACE_KEY&&(a(),t.preventDefault())})),s},createCopyTextField:function(t){return t.id||(t.id="copytext"+Math.floor(1e9*Math.random())),this.createField(this.createCopyTextInput(t),t)},createCopyTextPrompt:function(t){var e=$("<div/>",{class:"modal fitted"}),i=$("<div/>",{class:"body"}).appendTo(e);this.createCopyTextField($.extend({size:Math.max(Math.min(t.value.length,50),25)},t)).appendTo(i);var s=i.find("label");s.length>0&&s.attr("id")&&e.attr("aria-labelledby",s.attr("id"));var n=new Garnish.Modal(e,{closeOtherModals:!1});return e.on("copy",(function(){n.hide()})),e},createTextarea:function(t){var e=$("<textarea/>",{class:"text",rows:t.rows||2,cols:t.cols||50,id:t.id,name:t.name,maxlength:t.maxlength,autofocus:t.autofocus&&!Garnish.isMobileBrowser(!0),disabled:!!t.disabled,placeholder:t.placeholder,html:t.value});return t.showCharsLeft&&e.attr("data-show-chars-left",""),t.class&&e.addClass(t.class),t.size||e.addClass("fullwidth"),e},createTextareaField:function(t){return t.id||(t.id="textarea"+Math.floor(1e9*Math.random())),this.createField(this.createTextarea(t),t)},createSelect:function(t){var e=$("<div/>",{class:"select"});t.class&&e.addClass(t.class);var i=$("<select/>",{id:t.id,name:t.name,autofocus:t.autofocus&&Garnish.isMobileBrowser(!0),disabled:t.disabled,"data-target-prefix":t.targetPrefix,"aria-labelledby":t.labelledBy}).appendTo(e);if($.isPlainObject(t.options)){var s=[];for(var n in t.options)if(t.options.hasOwnProperty(n)){var a=t.options[n];$.isPlainObject(a)?void 0!==a.optgroup?s.push(a):s.push({label:a.label,value:void 0!==a.value?a.value:n,disabled:void 0!==a.disabled&&a.disabled}):s.push({label:a,value:n})}t.options=s}for(var r=null,o=0;o<t.options.length;o++){var l=t.options[o];void 0!==l.optgroup?r=$("<optgroup/>",{label:l.label}).appendTo(i):$("<option/>",{value:l.value,selected:l.value==t.value,disabled:void 0!==l.disabled&&l.disabled,html:l.label}).appendTo(r||i)}return t.toggle&&(i.addClass("fieldtoggle"),new Craft.FieldToggle(i)),e},createSelectField:function(t){return t.id||(t.id="select"+Math.floor(1e9*Math.random())),this.createField(this.createSelect(t),t)},createCheckbox:function(t){var e=t.id||"checkbox"+Math.floor(1e9*Math.random()),i=$("<input/>",{type:"checkbox",value:void 0!==t.value?t.value:"1",id:e,class:"checkbox",name:t.name,checked:t.checked?"checked":null,autofocus:this.getAutofocusValue(t.autofocus),disabled:this.getDisabledValue(t.disabled),"data-target":t.toggle,"data-reverse-target":t.reverseToggle});t.class&&i.addClass(t.class),(t.toggle||t.reverseToggle)&&(i.addClass("fieldtoggle"),new Craft.FieldToggle(i));var s=$("<label/>",{for:e,html:t.label});return t.name&&(t.name.length<3||"[]"!==t.name.slice(-2))?$([$("<input/>",{type:"hidden",name:t.name,value:""})[0],i[0],s[0]]):$([i[0],s[0]])},createCheckboxField:function(t){t.id||(t.id="checkbox"+Math.floor(1e9*Math.random()));var e=$('<div class="field checkboxfield"/>',{id:"".concat(t.id,"-field")});return t.first&&e.addClass("first"),t.instructions&&e.addClass("has-instructions"),this.createCheckbox(t).appendTo(e),t.instructions&&$('<div class="instructions"/>').text(t.instructions).appendTo(e),e},createCheckboxSelect:function(t){var e,i,s=$('<fieldset class="checkbox-select"/>');t.class&&s.addClass(t.class),t.showAllOption?(e=t.allValue||"*",i=t.values==e,$("<div/>").appendTo(s).append(this.createCheckbox({id:t.id,class:"all",label:"<b>"+(t.allLabel||Craft.t("app","All"))+"</b>",name:t.name,value:e,checked:i,autofocus:t.autofocus}))):i=!1;for(var n=0;n<t.options.length;n++){var a=t.options[n];a.value!=e&&$("<div/>").appendTo(s).append(this.createCheckbox({label:a.label,name:t.name?t.name+"[]":null,value:a.value,checked:i||(t.values||[]).includes(a.value),disabled:i}))}return new Garnish.CheckboxSelect(s),s},createCheckboxSelectField:function(t){return t.fieldset=!0,t.id||(t.id="checkboxselect"+Math.floor(1e9*Math.random())),this.createField(this.createCheckboxSelect(t),t)},createLightswitch:function(t){var e=t.value||"1",i=t.indeterminateValue||"-",s=$("<button/>",{type:"button",class:"lightswitch","data-value":e,"data-indeterminate-value":i,id:t.id,role:"switch","aria-checked":t.on?"true":t.indeterminate?"mixed":"false","aria-labelledby":t.labelId,"data-target":t.toggle,"data-reverse-target":t.reverseToggle});return t.on?s.addClass("on"):t.indeterminate&&s.addClass("indeterminate"),t.small&&s.addClass("small"),t.disabled&&s.addClass("disabled"),$('<div class="lightswitch-container"><div class="handle"></div></div>').appendTo(s),t.name&&$("<input/>",{type:"hidden",name:t.name,value:t.on?e:t.indeterminate?i:"",disabled:t.disabled}).appendTo(s),(t.toggle||t.reverseToggle)&&(s.addClass("fieldtoggle"),new Craft.FieldToggle(s)),new Craft.LightSwitch(s,{onChange:t.onChange||$.noop}),s},createLightswitchField:function(t){return t.id||(t.id="lightswitch"+Math.floor(1e9*Math.random())),t.labelId||(t.labelId="".concat(t.id,"-label")),this.createField(this.createLightswitch(t),t).addClass("lightswitch-field")},createColorInput:function(t){var e=t.id||"color"+Math.floor(1e9*Math.random()),i=t.containerId||e+"-container",s=t.name||null,n=t.value||null,a=t.small||!1,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{id:i,class:"flex color-container"}),h=$("<div/>",{class:"color static"+(a?" small":"")}).appendTo(l),d=($("<div/>",{class:"color-preview",style:t.value?{backgroundColor:t.value}:null}).appendTo(h),$("<div/>",{class:"color-input-container"}).append($("<div/>",{class:"color-hex-indicator light code","aria-hidden":"true",text:"#"})).appendTo(l));return this.createTextInput({id:e,name:s,value:Craft.ltrim(n,"#"),size:10,class:"color-input",autofocus:r,disabled:o,"aria-label":Craft.t("app","Color hex value")}).appendTo(d),new Craft.ColorInput(l),l},createColorField:function(t){return t.fieldset=!0,o,t.id||(t.id="color"+Math.floor(1e9*Math.random())),this.createField(this.createColorInput(t),t)},createDateInput:function(t){var e=Garnish.isMobileBrowser(),i=(t.id||"date"+Math.floor(1e9*Math.random()))+"-date",s=t.name||null,n=s?s+"[date]":null,a=t.value&&"function"==typeof t.value.getMonth?t.value:null,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{class:"datewrapper"}),h=this.createTextInput({id:i,type:e?"date":"text",class:!(!e||a)&&"empty-value",name:n,value:a?e?a.toISOString().split("T")[0]:Craft.formatDate(a):"",placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return $('<div data-icon="date"></div>').appendTo(l),s&&$("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),e?h.datetimeinput():h.datepicker($.extend({defaultDate:a||new Date},Craft.datepickerOptions)),t.hasOuterContainer?l:$('<div class="datetimewrapper"/>').append(l).datetime()},createDateField:function(t){return t.id||(t.id="date"+Math.floor(1e9*Math.random())),this.createField(this.createDateInput(t),t)},createDateRangePicker:function(t){var e=new Date,i=new Date(e.getFullYear(),e.getMonth(),e.getDate());t=$.extend({class:"",options:["today","thisWeek","thisMonth","thisYear","past7Days","past30Days","past90Days","pastYear"],onChange:$.noop,selected:null,startDate:null,endDate:null},t);var s,n,a=$("<div/>",{class:"menu"}),r=$("<ul/>",{class:"padded"}).appendTo(a),o=$("<a/>").addClass("sel").text(Craft.t("app","All")).data("handle","all");$("<li/>").append(o).appendTo(r);for(var l=0;l<t.options.length;l++){var h=t.options[l];switch(h){case"today":s={label:Craft.t("app","Today"),startDate:i,endDate:i};break;case"thisWeek":var d=e.getDay()-Craft.datepickerOptions.firstDay;d<0&&(d+=7),s={label:Craft.t("app","This week"),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-d),endDate:i};break;case"thisMonth":s={label:Craft.t("app","This month"),startDate:new Date(e.getFullYear(),e.getMonth()),endDate:i};break;case"thisYear":s={label:Craft.t("app","This year"),startDate:new Date(e.getFullYear(),0),endDate:i};break;case"past7Days":s={label:Craft.t("app","Past {num} days",{num:7}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-7),endDate:i};break;case"past30Days":s={label:Craft.t("app","Past {num} days",{num:30}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-30),endDate:i};break;case"past90Days":s={label:Craft.t("app","Past {num} days",{num:90}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-90),endDate:i};break;case"pastYear":s={label:Craft.t("app","Past year"),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-365),endDate:i}}var c=$("<li/>"),u=$("<a/>",{text:s.label}).data("handle",h).data("startDate",s.startDate).data("endDate",s.endDate).data("startTime",s.startDate?s.startDate.getTime():null).data("endTime",s.endDate?s.endDate.getTime():null);t.selected&&h==t.selected&&(n=u[0]),c.append(u),c.appendTo(r)}$("<hr/>").appendTo(a);var p=$("<div/>",{class:"flex flex-nowrap padded"}).appendTo(a),f=this.createDateField({label:Craft.t("app","From")}).appendTo(p).find("input"),g=this.createDateField({label:Craft.t("app","To")}).appendTo(p).find("input"),m=f.add(g);m.on("keyup",(function(t){t.keyCode===Garnish.ESC_KEY&&$(this).data("datepicker")&&$(this).data("datepicker").dpDiv.is(":visible")&&t.stopPropagation()})),f.data("datepicker")&&f.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()})),g.data("datepicker")&&g.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()}));var v=new Garnish.Menu(a,{onOptionSelect:function(e){var i=$(e);C.text(i.text()),v.setPositionRelativeToAnchor(),a.find(".sel").removeClass("sel"),i.addClass("sel"),f.datepicker("setDate",i.data("startDate")),g.datepicker("setDate",i.data("endDate")),t.onChange(i.data("startDate")||null,i.data("endDate")||null,i.data("handle"))}});m.on("change",(function(){for(var e,i=f.datepicker("getDate"),s=g.datepicker("getDate"),n=i?i.getTime():null,o=s?s.getTime():null,l=r.find("a"),h=!1,d=0;d<l.length;d++)if(n===((e=l.eq(d)).data("startTime")||null)&&o===(e.data("endTime")||null)){v.selectOption(e[0]),h=!0,t.onChange(null,null,e.data("handle"));break}h||(a.find(".sel").removeClass("sel"),p.addClass("sel"),n||o?n&&o?C.text(f.val()+" - "+g.val()):n?C.text(Craft.t("app","From {date}",{date:f.val()})):C.text(Craft.t("app","To {date}",{date:g.val()})):C.text(Craft.t("app","All")),v.setPositionRelativeToAnchor(),t.onChange(i,s,"custom"))})),v.on("hide",(function(){f.datepicker("hide"),g.datepicker("hide")}));var b="btn menubtn";t.class&&(b=b+" "+t.class);var C=$("<button/>",{type:"button",class:b,"data-icon":"date",text:Craft.t("app","All")});return new Garnish.MenuBtn(C,v),n&&v.selectOption(n),t.startDate&&f.datepicker("setDate",t.startDate),t.endDate&&g.datepicker("setDate",t.endDate),(t.startDate||t.endDate)&&m.trigger("change"),C},createTimeInput:function(t){var e=Garnish.isMobileBrowser(),i=(t.id||"time"+Math.floor(1e9*Math.random()))+"-time",s=t.name||null,n=s?s+"[time]":null,a=t.value&&"function"==typeof t.value.getMonth?t.value:null,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{class:"timewrapper"}),h=this.createTextInput({id:i,type:e?"time":"text",class:!(!e||a)&&"empty-value",name:n,placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return $('<div data-icon="time"></div>').appendTo(l),s&&$("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),e?(a&&h.val(a.toISOString().split("T")[1]),h.datetimeinput()):(h.timepicker(Craft.timepickerOptions),a&&h.timepicker("setTime",3600*a.getHours()+60*a.getMinutes()+a.getSeconds())),t.hasOuterContainer?l:$('<div class="datetimewrapper"/>').append(l).datetime()},createTimeField:function(t){return t.id||(t.id="time"+Math.floor(1e9*Math.random())),this.createField(this.createTimeInput(t),t)},createField:function(t,e){var i=e.label&&"__blank__"!==e.label?e.label:null,s=$(e.fieldset?"<fieldset/>":"<div/>",{class:"field",id:e.fieldId||(e.id?e.id+"-field":null)});if(e.first&&s.addClass("first"),e.fieldClass&&s.addClass(e.fieldClass),i&&e.fieldset&&$("<legend/>",{text:i,class:"visually-hidden","data-label":i}).appendTo(s),i){var n=$('<div class="heading"/>').appendTo(s);$(e.fieldset?"<legend/>":"<label/>",{id:e.labelId||(e.id?"".concat(e.id,"-").concat(e.fieldset?"legend":"label"):null),class:e.required?"required":null,for:!e.fieldset&&e.id||null,text:i}).appendTo(n)}if(e.instructions&&$('<div class="instructions"/>').text(e.instructions).appendTo(s),$('<div class="input"/>').append(t).appendTo(s),e.tip){var a=$('<p class="notice has-icon"/>');$('<span class="icon" aria-hidden="true"/>').appendTo(a),$('<span class="visually-hidden"/>').text(Craft.t("app","Tip")+": ").appendTo(a),$("<span/>").text(e.tip).appendTo(a),a.appendTo(s)}if(e.warning){var r=$('<p class="warning has-icon"/>');$('<span class="icon" aria-hidden="true"/>').appendTo(r),$('<span class="visually-hidden"/>').text(Craft.t("app","Warning")+": ").appendTo(r),$("<span/>").text(e.warning).appendTo(r),r.appendTo(s)}return e.errors&&this.addErrorsToField(s,e.errors),s},createErrorList:function(t){var e=$('<ul class="errors"/>');return t&&this.addErrorsToList(e,t),e},addErrorsToList:function(t,e){for(var i=0;i<e.length;i++)$("<li/>").text(e[i]).appendTo(t)},addErrorsToField:function(t,e){if(e){t.addClass("has-errors"),t.children(".input").addClass("errors");var i=t.children("ul.errors");i.length||(i=this.createErrorList().appendTo(t)),this.addErrorsToList(i,e)}},clearErrorsFromField:function(t){t.removeClass("has-errors"),t.children(".input").removeClass("errors"),t.children("ul.errors").remove()},getAutofocusValue:function(t){return t&&!Garnish.isMobileBrowser(!0)?"autofocus":null},getDisabledValue:function(t){return t?"disabled":null}}},1752:function(){Craft.Uploader=Garnish.Base.extend({uploader:null,allowedKinds:null,$element:null,settings:null,_rejectedFiles:{},_extensionList:null,_totalFileCounter:0,_validFileCounter:0,init:function(t,e){this._rejectedFiles={size:[],type:[],limit:[]},this.$element=t,this.allowedKinds=null,this._extensionList=null,this._totalFileCounter=0,this._validFileCounter=0;var i=(e=$.extend({},Craft.Uploader.defaults,e)).events;for(var s in delete e.events,e.allowedKinds&&e.allowedKinds.length&&("string"==typeof e.allowedKinds&&(e.allowedKinds=[e.allowedKinds]),this.allowedKinds=e.allowedKinds,delete e.allowedKinds),e.autoUpload=!1,this.uploader=this.$element.fileupload(e),i)i.hasOwnProperty(s)&&this.uploader.on(s,i[s]);this.settings=e,this.uploader.on("fileuploadadd",this.onFileAdd.bind(this))},setParams:function(t){void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(t[Craft.csrfTokenName]=Craft.csrfTokenValue),this.uploader.fileupload("option",{formData:t})},getInProgress:function(){return this.uploader.fileupload("active")},isLastUpload:function(){return this.getInProgress()<2},onFileAdd:function(t,e){var i=this;t.stopPropagation();var s=!1;return this.allowedKinds&&(this._extensionList||this._createExtensionList(),s=!0),e.process().done((function(){var t=e.files[0],n=!0;if(s){var a=t.name.match(/\.([a-z0-4_]+)$/i)[1];-1===$.inArray(a.toLowerCase(),i._extensionList)&&(n=!1,i._rejectedFiles.type.push("“"+t.name+"”"))}t.size>i.settings.maxFileSize&&(i._rejectedFiles.size.push("“"+t.name+"”"),n=!1),n&&"function"==typeof i.settings.canAddMoreFiles&&!i.settings.canAddMoreFiles(i._validFileCounter)&&(i._rejectedFiles.limit.push("“"+t.name+"”"),n=!1),n&&(i._validFileCounter++,e.submit()),++i._totalFileCounter===e.originalFiles.length&&(i._totalFileCounter=0,i._validFileCounter=0,i.processErrorMessages())})),!0},processErrorMessages:function(){var t;this._rejectedFiles.type.length&&(t=1===this._rejectedFiles.type.length?"The file {files} could not be uploaded. The allowed file kinds are: {kinds}.":"The files {files} could not be uploaded. The allowed file kinds are: {kinds}.",t=Craft.t("app",t,{files:this._rejectedFiles.type.join(", "),kinds:this.allowedKinds.join(", ")}),this._rejectedFiles.type=[],Craft.cp.displayError(t)),this._rejectedFiles.size.length&&(t=1===this._rejectedFiles.size.length?"The file {files} could not be uploaded, because it exceeds the maximum upload size of {size}.":"The files {files} could not be uploaded, because they exceeded the maximum upload size of {size}.",t=Craft.t("app",t,{files:this._rejectedFiles.size.join(", "),size:this.humanFileSize(Craft.maxUploadSize)}),this._rejectedFiles.size=[],Craft.cp.displayError(t)),this._rejectedFiles.limit.length&&(t=1===this._rejectedFiles.limit.length?"The file {files} could not be uploaded, because the field limit has been reached.":"The files {files} could not be uploaded, because the field limit has been reached.",t=Craft.t("app",t,{files:this._rejectedFiles.limit.join(", ")}),this._rejectedFiles.limit=[],Craft.cp.displayError(t))},humanFileSize:function(t){var e=1024;if(t<e)return t+" B";var i=-1;do{t/=e,++i}while(t>=e);return t.toFixed(1)+" "+["kB","MB","GB","TB","PB","EB","ZB","YB"][i]},_createExtensionList:function(){this._extensionList=[];for(var t=0;t<this.allowedKinds.length;t++){var e=this.allowedKinds[t];if(void 0!==Craft.fileKinds[e])for(var i=0;i<Craft.fileKinds[e].extensions.length;i++){var s=Craft.fileKinds[e].extensions[i];this._extensionList.push(s)}}},destroy:function(){this.$element.fileupload("destroy"),this.base()}},{defaults:{dropZone:null,pasteZone:null,fileInput:null,sequentialUploads:!0,maxFileSize:Craft.maxUploadSize,allowedKinds:null,events:{},canAddMoreFiles:null,headers:{Accept:"application/json;q=0.9,*/*;q=0.8"},paramName:"assets-upload"}})},7e3:function(){Craft.UriFormatGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){t=(t=t.replace(/<(.*?)>/g,"")).toLowerCase(),t=(t=(t=Craft.asciiString(t)).replace(/^[^a-z]+/,"")).replace(/[^a-z0-9]+$/,"");var e=Craft.filterArray(t.split(/[^a-z0-9]+/)).join(Craft.slugWordSeparator);return e&&this.settings.suffix&&(e+=this.settings.suffix),e}})},8654:function(){Craft.UserIndex=Craft.BaseElementIndex.extend({init:function(t,e,i){this.on("selectSource",this.updateUrl.bind(this)),this.base(t,e,i)},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultSourceSlug)for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("slug")===defaultSourceSlug)return e.data("key")}return this.base()},updateUrl:function(){if("index"===this.settings.context){var t="users",e=this.$source.data("slug");e&&(t+="/".concat(e)),Craft.setPath(t)}}}),Craft.registerElementIndexClass("craft\\elements\\User",Craft.UserIndex)},9712:function(){Craft.VolumeFolderSelectorModal=Craft.BaseElementSelectorModal.extend({init:function(t){(t=Object.assign({},Craft.VolumeFolderSelectorModal.defaults,t,{showSiteMenu:!1})).indexSettings.disabledFolderIds=t.disabledFolderIds,this.base("craft\\elements\\Asset",t)},getElementIndexParams:function(){return Object.assign({},this.base(),{foldersOnly:!0})},hasSelection:function(){return this.base()||this.elementIndex&&this.elementIndex.sourcePath.length&&void 0!==this.elementIndex.sourcePath[this.elementIndex.sourcePath.length-1].folderId&&!this.settings.disabledFolderIds.includes(this.elementIndex.sourcePath[this.elementIndex.sourcePath.length-1].folderId)},getElementInfo:function(t){return[{folderId:t.length?parseInt(t.find(".element:first").data("folder-id")):this.elementIndex.sourcePath[this.elementIndex.sourcePath.length-1].folderId}]},getIndexSettings:function(){var t=this;return Object.assign(this.base(),{foldersOnly:!0,canSelectElement:function(e){var i=e.find(".element:first").data("folder-id");return i&&!t.settings.disabledFolderIds.includes(i)}})}},{defaults:{disabledFolderIds:[],indexSettings:{}}})},5537:function(){},9383:function(){},6558:function(t,e,i){var s=i(5537);s.__esModule&&(s=s.default),"string"==typeof s&&(s=[[t.id,s,""]]),s.locals&&(t.exports=s.locals),(0,i(9673).Z)("3790022a",s,!0,{})},2179:function(t,e,i){var s=i(9383);s.__esModule&&(s=s.default),"string"==typeof s&&(s=[[t.id,s,""]]),s.locals&&(t.exports=s.locals),(0,i(9673).Z)("80058a3c",s,!0,{})},9673:function(t,e,i){"use strict";function s(t,e){for(var i=[],s={},n=0;n<e.length;n++){var a=e[n],r=a[0],o={id:t+":"+n,css:a[1],media:a[2],sourceMap:a[3]};s[r]?s[r].parts.push(o):i.push(s[r]={id:r,parts:[o]})}return i}i.d(e,{Z:function(){return f}});var n="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!n)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var a={},r=n&&(document.head||document.getElementsByTagName("head")[0]),o=null,l=0,h=!1,d=function(){},c=null,u="data-vue-ssr-id",p="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());function f(t,e,i,n){h=i,c=n||{};var r=s(t,e);return g(r),function(e){for(var i=[],n=0;n<r.length;n++){var o=r[n];(l=a[o.id]).refs--,i.push(l)}for(e?g(r=s(t,e)):r=[],n=0;n<i.length;n++){var l;if(0===(l=i[n]).refs){for(var h=0;h<l.parts.length;h++)l.parts[h]();delete a[l.id]}}}}function g(t){for(var e=0;e<t.length;e++){var i=t[e],s=a[i.id];if(s){s.refs++;for(var n=0;n<s.parts.length;n++)s.parts[n](i.parts[n]);for(;n<i.parts.length;n++)s.parts.push(v(i.parts[n]));s.parts.length>i.parts.length&&(s.parts.length=i.parts.length)}else{var r=[];for(n=0;n<i.parts.length;n++)r.push(v(i.parts[n]));a[i.id]={id:i.id,refs:1,parts:r}}}}function m(){var t=document.createElement("style");return t.type="text/css",r.appendChild(t),t}function v(t){var e,i,s=document.querySelector("style["+u+'~="'+t.id+'"]');if(s){if(h)return d;s.parentNode.removeChild(s)}if(p){var n=l++;s=o||(o=m()),e=C.bind(null,s,n,!1),i=C.bind(null,s,n,!0)}else s=m(),e=_.bind(null,s),i=function(){s.parentNode.removeChild(s)};return e(t),function(s){if(s){if(s.css===t.css&&s.media===t.media&&s.sourceMap===t.sourceMap)return;e(t=s)}else i()}}var b,$=(b=[],function(t,e){return b[t]=e,b.filter(Boolean).join("\n")});function C(t,e,i,s){var n=i?"":s.css;if(t.styleSheet)t.styleSheet.cssText=$(e,n);else{var a=document.createTextNode(n),r=t.childNodes;r[e]&&t.removeChild(r[e]),r.length?t.insertBefore(a,r[e]):t.appendChild(a)}}function _(t,e){var i=e.css,s=e.media,n=e.sourceMap;if(s&&t.setAttribute("media",s),c.ssrId&&t.setAttribute(u,e.id),n&&(i+="\n/*# sourceURL="+n.sources[0]+" */",i+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(n))))+" */"),t.styleSheet)t.styleSheet.cssText=i;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(i))}}}},__webpack_module_cache__={};function __webpack_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var i=__webpack_module_cache__[t]={id:t,exports:{}};return __webpack_modules__[t](i,i.exports,__webpack_require__),i.exports}__webpack_require__.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return __webpack_require__.d(e,{a:e}),e},__webpack_require__.d=function(t,e){for(var i in e)__webpack_require__.o(e,i)&&!__webpack_require__.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},__webpack_require__.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};var __webpack_exports__={};!function(){"use strict";__webpack_require__(2179),__webpack_require__(6558),__webpack_require__(587),__webpack_require__(8960),__webpack_require__(5774),__webpack_require__(8495),__webpack_require__(5970),__webpack_require__(4993),__webpack_require__(8843),__webpack_require__(5759),__webpack_require__(8167),__webpack_require__(4211),__webpack_require__(7745),__webpack_require__(8895),__webpack_require__(463),__webpack_require__(3839),__webpack_require__(7452),__webpack_require__(6872),__webpack_require__(2495),__webpack_require__(1016),__webpack_require__(5077),__webpack_require__(4606),__webpack_require__(8391),__webpack_require__(9222);var t=jQuery,e=__webpack_require__.n(t);function i(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=n(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var s=0,a=function(){};return{s:a,n:function(){return s>=t.length?{done:!0}:{done:!1,value:t[s++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return o=t.done,t},e:function(t){l=!0,r=t},f:function(){try{o||null==i.return||i.return()}finally{if(l)throw r}}}}function s(t){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},s(t)}function n(t,e){if(t){if("string"==typeof t)return a(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?a(t,e):void 0}}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CP=Garnish.Base.extend({elementThumbLoader:null,authManager:null,$nav:null,$navToggle:null,$globalSidebar:null,$globalContainer:null,$mainContainer:null,$alerts:null,$crumbs:null,$breadcrumbList:null,$breadcrumbItems:null,$notificationContainer:null,$main:null,$primaryForm:null,$headerContainer:null,$header:null,$mainContent:null,$details:null,$sidebarContainer:null,$sidebarToggle:null,$sidebar:null,$contentContainer:null,$edition:null,$confirmUnloadForms:null,$deltaForms:null,$collapsibleTables:null,isMobile:null,fixedHeader:!1,breadcrumbListWidth:0,breadcrumbDisclosureItem:'<li class="breadcrumb-toggle-wrapper" data-disclosure-item><button data-disclosure-trigger aria-controls="breadcrumb-disclosure" aria-haspopup="true">'.concat(Craft.t("app","More…"),'</button><div id="breadcrumb-disclosure" class="menu menu--disclosure" data-disclosure-menu><ul></ul></div></li>'),tabManager:null,enableQueue:!0,totalJobs:0,jobInfo:null,displayedJobInfo:null,displayedJobInfoUnchanged:1,trackJobProgressTimeout:null,jobProgressIcon:null,checkingForUpdates:!1,forcingRefreshOnUpdatesCheck:!1,includingDetailsOnUpdatesCheck:!1,checkForUpdatesCallbacks:null,resizeTimeout:null,init:function(){var t=this;this.elementThumbLoader=new Craft.ElementThumbLoader,0!==Craft.remainingSessionTime&&(this.authManager=new Craft.AuthManager),this.$nav=e()("#nav"),this.$navToggle=e()("#primary-nav-toggle"),this.$globalSidebar=e()("#global-sidebar"),this.$globalContainer=e()("#global-container"),this.$mainContainer=e()("#main-container"),this.$alerts=e()("#alerts"),this.$crumbs=e()("#crumbs"),this.$breadcrumbList=e()(".breadcrumb-list"),this.$breadcrumbItems=e()(".breadcrumb-list li"),this.$notificationContainer=e()("#notifications"),this.$main=e()("#main"),this.$primaryForm=e()("#main-form"),this.$headerContainer=e()("#header-container"),this.$header=e()("#header"),this.$mainContent=e()("#main-content"),this.$details=e()("#details"),this.$sidebarContainer=e()("#sidebar-container"),this.$sidebarToggle=e()("#sidebar-toggle"),this.$sidebar=e()("#sidebar"),this.$contentContainer=e()("#content-container"),this.$collapsibleTables=e()("table.collapsible"),this.isMobile=Garnish.isMobileBrowser(),this.updateContentHeading();for(var i=this.$details.find(".meta > .field > .instructions"),s=0;s<i.length;s++){var a=i.eq(s),r=a.siblings(".heading").children("label");e()("<span/>",{class:"info",html:a.children().html()}).appendTo(r),a.remove()}if(!this.isMobile&&this.$header.length&&(this.addListener(Garnish.$win,"scroll","updateFixedHeader"),this.updateFixedHeader()),Garnish.$doc.ready((function(){t.addListener(Garnish.$win,"resize",(function(e){if(e.target===window){t.handleWindowResize(),clearTimeout(t.resizeTimeout);var i=t;t.resizeTimeout=setTimeout((function(){i.setSidebarNavAttributes()}),100)}})),t.handleWindowResize(),t.setSidebarNavAttributes(),Garnish.requestAnimationFrame(t.initSpecialForms.bind(t))})),this.$alerts.length&&this.initAlerts(),this.addListener(this.$navToggle,"click","toggleNav"),this.addListener(this.$sidebarToggle,"click","toggleSidebar"),this.$primaryForm.length||(this.$primaryForm=e()("form[data-saveshortcut]:first")),this.$primaryForm.length&&Garnish.hasAttr(this.$primaryForm,"data-saveshortcut")&&function(){var e=[],i=t.$primaryForm.data("actions");if(void 0===i)e.push([{keyCode:Garnish.S_KEY,ctrl:!0},{redirect:t.$primaryForm.data("saveshortcut-redirect"),retainScroll:Garnish.hasAttr(t.$primaryForm,"saveshortcut-scroll")}]);else for(var s=0;s<i.length;s++){var n=i[s];n.shortcut&&e.push([{keyCode:Garnish.S_KEY,ctrl:!0,shift:!!n.shift},{action:n.action,redirect:n.redirect,confirm:n.confirm,params:n.params,data:n.data,retainScroll:n.retainScroll}])}for(var a=function(i){Garnish.uiLayerManager.registerShortcut(e[i][0],(function(){t.submitPrimaryForm(e[i][1])}))},r=0;r<e.length;r++)a(r)}(),this.initTabs(),this.tabManager&&window.LOCATION_HASH){var o=this.tabManager.$tabs.filter('[href="#'.concat(window.LOCATION_HASH,'"]'));o.length&&this.tabManager.selectTab(o)}var l=Craft.getLocalStorage("scrollY");if(void 0!==l&&(Craft.removeLocalStorage("scrollY"),Garnish.$doc.ready((function(){Garnish.requestAnimationFrame((function(){window.scrollTo(0,l)}))}))),e().isTouchCapable()&&(this.$mainContainer.on("focus","input, textarea, .focusable-input",this._handleInputFocus.bind(this)),this.$mainContainer.on("blur","input, textarea, .focusable-input",this._handleInputBlur.bind(this))),Craft.announcements.length){var h,d,c=e()("#announcements-btn").removeClass("hidden"),u=Craft.announcements.some((function(t){return t.unread}));u&&(h=e()("<span/>",{class:"visually-hidden",html:Craft.t("app","Unread messages")}),c.addClass("unread").append(h)),this.addListener(c,"click",(function(){if(d)d.show();else{var t="";Craft.announcements.forEach((function(e){t+='<div class="announcement '.concat(e.unread?"unread":"",'" role="listitem">')+'<div class="announcement__header">'+'<h3 class="announcement__heading h2">'.concat(e.heading,"</h3>")+'<div class="announcement-label-container">'+'<div class="announcement-icon" aria-hidden="true">'.concat(e.icon,"</div>")+'<div class="announcement-label">'.concat(e.label,"</div>")+"</div></div>"+"<p>".concat(e.body,"</p>")+"</div>"})),d=new Garnish.HUD(c,'<h2 class="visually-hidden">'.concat(Craft.t("app","Announcements"),'</h2><div id="announcements" role="list">').concat(t,"</div>"),{onShow:function(){c.addClass("active")},onHide:function(){c.removeClass("active")}}),e()("a",d.$main).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===e()(this).attr("target")&&e()(this).attr("rel","noopener").attr("target","_blank")})),u&&(c.removeClass("unread"),h.remove(),Craft.sendActionRequest("POST","users/mark-announcements-as-read",{data:{ids:Craft.announcements.map((function(t){return t.id}))}}))}}))}var p=document.getElementById("footer");p&&new IntersectionObserver((function(t){var e=function(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,n,a=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(a.push(s.value),!e||a.length!==e);r=!0);}catch(t){o=!0,n=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}return a}}(t,e)||n(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(t,1)[0];e.target.classList.toggle("stuck",e.intersectionRatio<1)}),{rootMargin:"0px 0px -1px 0px",threshold:[1]}).observe(p),this.elementThumbLoader.load(this.$mainContent)},get $contentHeader(){var t=e()("#content-header");return t.length?t:e()("<header/>",{id:"content-header",class:"pane-header"}).prependTo(e()("#content"))},get $noticeContainer(){var t=e()("#content-notice");return t.length?t:e()('<div id="content-notice"/>').attr("role","status").prependTo(this.$contentHeader)},initSpecialForms:function(){var t=this;if(this.$confirmUnloadForms=e()("form[data-confirm-unload]"),this.$deltaForms=e()("form[data-delta]"),this.$confirmUnloadForms.length){for(var i=this.$confirmUnloadForms.add(this.$deltaForms),s=function(e){var s=i.eq(e),n=void 0;s.data("initialSerializedValue")||(n="function"==typeof s.data("serializer")?s.data("serializer")():s.serialize(),s.data("initialSerializedValue",n)),t.addListener(s,"submit",(function(t){if(Garnish.hasAttr(s,"data-confirm-unload")&&this.removeListener(Garnish.$win,"beforeunload"),Garnish.hasAttr(s,"data-delta")){var e;t.preventDefault(),e="function"==typeof s.data("serializer")?s.data("serializer")():s.serialize();var i=Craft.findDeltaData(s.data("initialSerializedValue"),e,s.data("delta-names"),null,s.data("initial-delta-values"),s.data("modified-delta-names"));Craft.createForm(i).appendTo(Garnish.$bod).submit()}}))},n=0;n<i.length;n++)s(n);this.addListener(Garnish.$win,"beforeunload",(function(t){var e=!1;if(void 0!==Craft.livePreview&&Craft.livePreview.inPreviewMode)e=!0;else for(var i=0;i<this.$confirmUnloadForms.length;i++){var s,n=this.$confirmUnloadForms.eq(i);if(s="function"==typeof n.data("serializer")?n.data("serializer")():n.serialize(),n.data("initialSerializedValue")!==s){e=!0;break}}if(e){var a=Craft.t("app","Any changes will be lost if you leave this page.");return t?t.originalEvent.returnValue=a:window.event.returnValue=a,a}}))}},_handleInputFocus:function(){this.updateFixedHeader()},_handleInputBlur:function(){this.updateFixedHeader()},submitPrimaryForm:function(t){this.trigger("beforeSaveShortcut"),"object"===s(t)&&e().isPlainObject(t)||(t={}),t.redirect||(t.redirect=this.$primaryForm.data("saveshortcut-redirect")),t.data||(t.data={}),t.data.saveShortcut=!0,Craft.submitForm(this.$primaryForm,t)},updateSidebarMenuLabel:function(){this.updateContentHeading()},updateContentHeading:function(){var t=this.$sidebar.find("a.sel:first"),i=t.children(".label");e()("#content-heading").text(i.length?i.text():t.text()),Garnish.$bod.removeClass("showing-sidebar")},toggleNav:function(){var t=this.navIsExpanded();null!==t&&(t?(this.disableGlobalSidebarLinks(),this.$navToggle.focus(),this.$navToggle.attr("aria-expanded","false"),Garnish.$bod.removeClass("showing-nav")):(this.enableGlobalSidebarLinks(),this.$globalSidebar.find(":focusable")[0].focus(),this.$navToggle.attr("aria-expanded","true"),Garnish.$bod.addClass("showing-nav")))},enableGlobalSidebarLinks:function(){var t=this.$globalSidebar.find(":focusable");e()(t).each((function(){e()(this).attr("tabindex","0")}))},disableGlobalSidebarLinks:function(){var t=this.$globalSidebar.find(":focusable");e()(t).each((function(){e()(this).attr("tabindex","-1")}))},setSidebarNavAttributes:function(){var t=this.navIsExpanded();null!==t&&(t?this.enableGlobalSidebarLinks():this.disableGlobalSidebarLinks())},navIsExpanded:function(){if(!this.$globalSidebar[0])return null;var t=getComputedStyle(this.$globalSidebar[0]).getPropertyValue("--is-always-visible").trim();return"true"===this.$navToggle.attr("aria-expanded")||"true"===t},toggleSidebar:function(){var t="true"===this.$sidebarToggle.attr("aria-expanded")?"false":"true";this.$sidebarToggle.attr("aria-expanded",t),Garnish.$bod.toggleClass("showing-sidebar")},initTabs:function(){this.tabManager&&(this.tabManager.destroy(),this.tabManager=null);var t=e()("#tabs");t.length&&(this.tabManager=new Craft.Tabs(t),this.tabManager.on("selectTab",(function(t){var i=t.$tab.attr("href");if(i&&"#"===i.charAt(0)&&e()(i).removeClass("hidden"),Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll"),i&&"#"===i.charAt(0)){var s=e()("#context-btn").menubtn().data("menubtn");if(s)for(var n=0;n<s.menu.$options.length;n++){var a=s.menu.$options[n];a.href&&(a.href=a.href.match(/^[^#]*/)[0]+i)}}"undefined"!=typeof history&&Garnish.requestAnimationFrame((function(){history.replaceState(void 0,void 0,i)}))})),this.tabManager.on("deselectTab",(function(t){var i=t.$tab.attr("href");i&&"#"===i.charAt(0)&&e()(t.$tab.attr("href")).addClass("hidden")})))},updateTabs:function(t){if(t){var i=e()(t).attr("id","tabs");this.tabManager?this.tabManager.$container.replaceWith(i):i.appendTo(this.$contentHeader),this.initTabs()}else this.tabManager&&(this.tabManager.$container.siblings().length?this.tabManager.$container.remove():this.tabManager.$container.parent().remove(),this.tabManager.destroy(),this.tabManager=null)},get $tabsContainer(){return this.tabManager?this.tabManager.$container:void 0},get $tabsList(){return this.tabManager?this.tabManager.$tablist:void 0},get $tabs(){return this.tabManager?this.tabManager.$tablist.find("> a"):void 0},get $selectedTab(){return this.tabManager?this.tabManager.$selectedTab:void 0},get selectedTabIndex(){return this.tabManager?this.tabManager.$tabs.index(this.tabManager.$selectedTab):void 0},get $focusableTab(){return this.tabManager?this.tabManager.$focusableTab:void 0},selectTab:function(t){this.tabManager&&this.tabManager.selectTab(t)},deselectTab:function(){this.tabManager&&this.tabManager.deselectTab()},handleWindowResize:function(){this.updateResponsiveTables(),this.handleBreadcrumbVisibility()},breadcrumbItemsWrap:function(){if(this.$breadcrumbItems[0]){this.$breadcrumbList.css("ltr"===Craft.orientation?"margin-right":"margin-left","");for(var t=this.$breadcrumbList[0].getBoundingClientRect().width,e=0,i=this.$breadcrumbList.find("li"),s=0;s<i.length;s++)e+=i.get(s).getBoundingClientRect().width;return this.breadcrumbListWidth=t,!(e<=t||e<t+1&&(this.$breadcrumbList.css("ltr"===Craft.orientation?"margin-right":"margin-left","-1px"),1))}},handleBreadcrumbVisibility:function(){if(this.breadcrumbItemsWrap()){0===this.$breadcrumbList.find("[data-disclosure-item]").length&&this.$breadcrumbList.append(this.breadcrumbDisclosureItem);var t,e=this.$breadcrumbList.find("[data-disclosure-item]")[0].offsetWidth,i=this.breadcrumbListWidth;this.$breadcrumbItems.each((function(s){if(!(e+this.offsetWidth<i))return!1;t=s,e+=this.offsetWidth}));var s=this.$breadcrumbItems.slice(0,t+1),n=this.$breadcrumbItems.slice(t+1);this.$breadcrumbList.html(""),this.$breadcrumbList.append(s),this.$breadcrumbList.append(this.breadcrumbDisclosureItem),this.$breadcrumbList.find("[data-disclosure-menu] ul").append(n),this.$breadcrumbList.find("[data-disclosure-trigger]").disclosureMenu()}},updateResponsiveTables:function(){for(this.updateResponsiveTables._i=0;this.updateResponsiveTables._i<this.$collapsibleTables.length;this.updateResponsiveTables._i++)this.updateResponsiveTables._$table=this.$collapsibleTables.eq(this.updateResponsiveTables._i),this.updateResponsiveTables._containerWidth=this.updateResponsiveTables._$table.parent().width(),this.updateResponsiveTables._check=!1,this.updateResponsiveTables._containerWidth>0&&(void 0===this.updateResponsiveTables._$table.data("lastContainerWidth")?this.updateResponsiveTables._check=!0:(this.updateResponsiveTables._isCollapsed=this.updateResponsiveTables._$table.hasClass("collapsed"),this.updateResponsiveTables._containerWidth>this.updateResponsiveTables._$table.data("lastContainerWidth")?this.updateResponsiveTables._isCollapsed&&(this.updateResponsiveTables._$table.removeClass("collapsed"),this.updateResponsiveTables._check=!0):this.updateResponsiveTables._isCollapsed||(this.updateResponsiveTables._check=!0)),this.updateResponsiveTables._check&&this.updateResponsiveTables._$table.width()-30>this.updateResponsiveTables._containerWidth&&this.updateResponsiveTables._$table.addClass("collapsed"),this.updateResponsiveTables._$table.data("lastContainerWidth",this.updateResponsiveTables._containerWidth))},updateFixedHeader:function(){if(!this.isMobile)if(this.$main.length&&this.$headerContainer[0].getBoundingClientRect().top<0){if(!this.fixedHeader){var t=this.$headerContainer.height();this.$contentContainer.css("min-height","calc(100vh - "+(t+14+48-1)+"px)"),this.$headerContainer.height(t),Garnish.$bod.addClass("fixed-header"),this.$contentContainer.outerHeight(),this.$details.outerHeight();var e={top:t+"px","max-height":"calc(100vh - "+t+"px)"};this.$sidebar.addClass("fixed").css(e),this.$details.addClass("fixed").css(e),this.fixedHeader=!0}}else this.fixedHeader&&(this.$headerContainer.height("auto"),Garnish.$bod.removeClass("fixed-header"),this.$contentContainer.css("min-height",""),this.$sidebar.removeClass("fixed").css({top:"","max-height":""}),this.$details.removeClass("fixed").css({top:"","max-height":""}),this.fixedHeader=!1)},displayNotification:function(t,e,i){var s=new Craft.CP.Notification(t,e,i);return this.trigger("displayNotification",{notificationType:t,message:e,notification:s}),s},displayNotice:function(t,e){return this.displayNotification("notice",t,Object.assign({icon:"info",iconLabel:Craft.t("app","Notice")},e))},displaySuccess:function(t,e){return this.displayNotification("success",t,Object.assign({icon:"check",iconLabel:Craft.t("app","Success")},e))},displayError:function(t,e){return t&&"object"!==s(t)||(e=t,t=Craft.t("app","A server error occurred.")),this.displayNotification("error",t,Object.assign({icon:"alert",iconLabel:Craft.t("app","Error")},e))},fetchAlerts:function(){return Craft.queue.push((function(){return new Promise((function(t,e){var i={path:Craft.path};Craft.sendActionRequest("POST","app/get-cp-alerts",{data:i}).then((function(e){var i=e.data;t(i.alerts)})).catch(e)}))}))},displayAlerts:function(t){if(this.$alerts.remove(),Garnish.isArray(t)&&t.length){this.$alerts=e()('<ul id="alerts"/>').prependTo(e()("#page-container"));var s,n=i(t);try{for(n.s();!(s=n.n()).done;){var a=s.value;e().isPlainObject(a)||(a={content:a,showIcon:!0});var r=a.content;a.showIcon&&(r='<span data-icon="alert" aria-label="'.concat(Craft.t("app","Error"),'"></span> ').concat(r)),e()("<li>".concat(r,"</li>")).appendTo(this.$alerts)}}catch(t){n.e(t)}finally{n.f()}var o=this.$alerts.outerHeight();this.$alerts.css("margin-top",-o).velocity({"margin-top":0},"fast"),this.initAlerts()}},initAlerts:function(){for(var t=this,i=this.$alerts.find('a[class^="shun:"]'),s=0;s<i.length;s++)this.addListener(i[s],"click",(function(i){i.preventDefault(),Craft.queue.push((function(){return new Promise((function(s,n){var a=e()(i.currentTarget),r={message:a.prop("className").substring(5)};Craft.sendActionRequest("POST","app/shun-cp-alert",{data:r}).then((function(){a.parent().remove(),s()})).catch((function(e){var i=e.response;t.displayError(i.data.message),n()}))}))}))}))},checkForUpdates:function(t,e,i){var s=this;if("function"==typeof e&&(i=e,e=!1),this.checkingForUpdates&&(!0===t&&!this.forcingRefreshOnUpdatesCheck||!0===e&&!this.includingDetailsOnUpdatesCheck)){var n=i;i=function(){s.checkForUpdates(t,e,n)}}"function"==typeof i&&(Garnish.isArray(this.checkForUpdatesCallbacks)||(this.checkForUpdatesCallbacks=[]),this.checkForUpdatesCallbacks.push(i)),this.checkingForUpdates||(this.checkingForUpdates=!0,this.forcingRefreshOnUpdatesCheck=!0===t,this.includingDetailsOnUpdatesCheck=!0===e,this._checkForUpdates(t,e).then((function(t){if(s.updateUtilitiesBadge(),s.checkingForUpdates=!1,Garnish.isArray(s.checkForUpdatesCallbacks)){var e=s.checkForUpdatesCallbacks;s.checkForUpdatesCallbacks=null;for(var i=0;i<e.length;i++)e[i](t)}s.trigger("checkForUpdates",{updateInfo:t})})))},_checkForUpdates:function(t,e){var i=this;return new Promise((function(s,n){t?i._getUpdates(e).then(s).catch(n):i._checkForCachedUpdates(e).then((function(t){t.cached?s(t):i._getUpdates(e).then((function(t){s(t)}))})).catch(n)}))},_checkForCachedUpdates:function(t){return new Promise((function(e,i){var s={onlyIfCached:!0,includeDetails:t};Craft.sendActionRequest("POST","app/check-for-updates",{data:s}).then((function(t){var i=t.data;e(i)})).catch((function(){e({cached:!1})}))}))},_getUpdates:function(t){var e=this;return new Promise((function(i,s){Craft.sendApiRequest("GET","updates").then((function(s){e._cacheUpdates(s,t).then((function(t){i(t)}))})).catch(s)}))},_cacheUpdates:function(t,e){return new Promise((function(i,s){var n={updates:t,includeDetails:e};Craft.sendActionRequest("POST","app/cache-updates",{data:n}).then((function(t){var e=t.data;i(e)})).catch(s)}))},updateUtilitiesBadge:function(){var t=e()("#nav-utilities").find("> a:not(.sel)");t.length&&Craft.queue.push((function(){return new Promise((function(i,s){Craft.sendActionRequest("POST","app/get-utilities-badge-count").then((function(s){var n=s.data,a=t.children(".badge"),r=t.children("[data-notification]");n.badgeCount?(a.length||(a=e()('<span class="badge" aria-hidden="true"/>').appendTo(t)),r.length||(r=e()('<span class="visually-hidden" data-notification/>').appendTo(t)),a.text(n.badgeCount),r.text(Craft.t("app","{num, number} {num, plural, =1{notification} other{notifications}}",{num:n.badgeCount}))):a.length&&r.length&&(a.remove(),r.remove()),i()})).catch(s)}))}))},runQueue:function(){var t=this;this.enableQueue&&(Craft.runQueueAutomatically?Craft.queue.push((function(){return new Promise((function(e,i){Craft.sendActionRequest("POST","queue/run").then((function(){t.trackJobProgress(!1,!0),e()})).catch(i)}))})):this.trackJobProgress(!1,!0))},trackJobProgress:function(t,e){if(e&&this.trackJobProgressTimeout&&(clearTimeout(this.trackJobProgressTimeout),this.trackJobProgressTimeout=null),!this.trackJobProgressTimeout&&this.enableQueue)if(!0===t){var i=Math.min(6e4,500*this.displayedJobInfoUnchanged);this.trackJobProgressTimeout=setTimeout(this._trackJobProgressInternal.bind(this),i)}else this._trackJobProgressInternal()},_trackJobProgressInternal:function(){var t=this;Craft.queue.push((function(){return new Promise((function(e,i){Craft.sendActionRequest("POST","queue/get-job-info?limit=50&dontExtendSession=1").then((function(i){var s=i.data;t.trackJobProgressTimeout=null,t.totalJobs=s.total,t.setJobInfo(s.jobs),t.jobInfo.length&&t.trackJobProgress(!0),e()})).catch(i)}))}))},setJobInfo:function(t){if(this.enableQueue){this.jobInfo=t;var e=this.displayedJobInfo;this.displayedJobInfo=this.getDisplayedJobInfo(),e&&this.displayedJobInfo&&e.id===this.displayedJobInfo.id&&e.progress===this.displayedJobInfo.progress&&e.progressLabel===this.displayedJobInfo.progressLabel&&e.status===this.displayedJobInfo.status?this.displayedJobInfoUnchanged++:this.displayedJobInfoUnchanged=1,this.updateJobIcon(),this.trigger("setJobInfo")}},getDisplayedJobInfo:function(){if(!this.enableQueue)return null;for(var t=[Craft.CP.JOB_STATUS_RESERVED,Craft.CP.JOB_STATUS_FAILED,Craft.CP.JOB_STATUS_WAITING],e=0;e<t.length;e++)for(var i=0;i<this.jobInfo.length;i++)if(this.jobInfo[i].status===t[e]&&(t[e]!==Craft.CP.JOB_STATUS_WAITING||!this.jobInfo[i].delay))return this.jobInfo[i];return null},updateJobIcon:function(){this.enableQueue&&this.$nav.length&&(this.displayedJobInfo?(this.jobProgressIcon||(this.jobProgressIcon=new r),this.displayedJobInfo.status===Craft.CP.JOB_STATUS_RESERVED||this.displayedJobInfo.status===Craft.CP.JOB_STATUS_WAITING?(this.jobProgressIcon.hideFailMode(),this.jobProgressIcon.setDescription(this.displayedJobInfo.description,this.displayedJobInfo.progressLabel),this.jobProgressIcon.setProgress(this.displayedJobInfo.progress)):this.displayedJobInfo.status===Craft.CP.JOB_STATUS_FAILED&&this.jobProgressIcon.showFailMode(Craft.t("app","Failed"))):this.jobProgressIcon&&(this.jobProgressIcon.hideFailMode(),this.jobProgressIcon.complete(),delete this.jobProgressIcon))},getSiteId:function(){var t=Craft.getLocalStorage("BaseElementIndex.siteId");if(void 0!==t){Craft.removeLocalStorage("BaseElementIndex.siteId");try{this.setSiteId(t)}catch(t){}}return Craft.siteId},setSiteId:function(t){var s=Craft.sites.find((function(e){return e.id===t}));if(!s)throw"Invalid site ID: ".concat(t);Craft.siteId=t,Craft.actionUrl=Craft.getUrl(Craft.actionUrl,{site:s.handle}),Craft.baseCpUrl=Craft.getUrl(Craft.baseCpUrl,{site:s.handle}),Craft.baseUrl=Craft.getUrl(Craft.baseUrl,{site:s.handle});var n=Craft.getUrl(document.location.href,{site:s.handle});history.replaceState({},"",n);var a,r=i(document.body.classList);try{for(r.s();!(a=r.n()).done;){var o=a.value;o.match(/^site--/)&&document.body.classList.remove(o)}}catch(t){r.e(t)}finally{r.f()}document.body.classList.add("site--".concat(s.handle)),e()("a").each((function(){this.hostname.length&&this.hostname===location.hostname&&-1!==this.href.indexOf(Craft.cpTrigger)&&(this.href=Craft.getUrl(this.href,{site:s.handle}))}))}},{notificationDuration:5e3,JOB_STATUS_WAITING:1,JOB_STATUS_RESERVED:2,JOB_STATUS_DONE:3,JOB_STATUS_FAILED:4}),Craft.CP.Notification=Garnish.Base.extend({type:null,message:null,settings:null,closing:!1,closeTimeout:null,_preventDelayedClose:!1,$container:null,$closeBtn:null,originalActiveElement:null,init:function(t,i,s){var n=this;this.type=t,this.message=i,this.settings=s||{},this.$container=e()("<div/>",{class:"notification","data-type":this.type}).appendTo(Craft.cp.$notificationContainer);var a=e()('<div class="notification-body"/>').appendTo(this.$container);if(this.settings.icon){var r=e()("<span/>",{class:"notification-icon","data-icon":this.settings.icon}).appendTo(a);this.settings.iconLabel?r.attr({"aria-label":this.settings.iconLabel,role:"img"}):r.attr("aria-hidden","true")}var o=e()('<div class="notification-main"/>').appendTo(a);e()("<div/>",{class:"notification-message",text:this.message}).appendTo(o);var l=e()("<div/>").appendTo(this.$container);this.$closeBtn=e()("<button/>",{type:"button",class:"notification-close-btn","aria-label":Craft.t("app","Close"),"data-icon":"remove"}).appendTo(l),this.settings.details&&e()('<div class="notification-details"/>').append(this.settings.details).appendTo(o).find("button,input").length&&(Garnish.uiLayerManager.addLayer(this.$container),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){n.close()})),this.originalActiveElement=document.activeElement,this.$container.attr("tabindex","-1").focus(),this.$container.on("keydown",(function(t){t.keyCode===Garnish.ESC_KEY&&(t.stopPropagation(),n.close())}))),this.$container.css({opacity:0,"margin-bottom":this._negMargin()}).velocity({opacity:1,"margin-bottom":0},{duration:"fast"}),Craft.initUiElements(this.$container),this.addListener(this.$closeBtn,"click","close"),Craft.notificationDuration&&this._initDelayedClose()},_initDelayedClose:function(){var t=this;this._preventDelayedClose||(Craft.isVisible()?(this.delayedClose(),this.$container.on("keypress keyup change focus blur click mousedown mouseup",(function(e){e.target!=t.$closeBtn[0]&&(t.$container.off("keypress keyup change focus blur click mousedown mouseup"),t.preventDelayedClose())}))):Garnish.$doc.one("visibilitychange",(function(){t._initDelayedClose()})))},_negMargin:function(){return"-".concat(this.$container.outerHeight()+12,"px")},close:function(){var t=this;this.closing||(this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null),this.closing=!0,this.originalActiveElement&&document.activeElement&&(document.activeElement===this.$container[0]||e().contains(this.$container[0],document.activeElement))&&e()(this.originalActiveElement).focus(),this.$container.velocity({opacity:0,"margin-bottom":this._negMargin()},{duration:"fast",complete:function(){t.$container.remove()}}))},delayedClose:function(){var t=this;this.closeTimeout=setTimeout((function(){t.close()}),Craft.notificationDuration),this.$container.one("mouseover",(function(){clearTimeout(t.closeTimeout),t.closeTimeout=null,t.$container.on("mouseout",(function(e){e.target==t.$container[0]&&(t.$container.off("mouseout"),t.delayedClose())}))}))},preventDelayedClose:function(){this._preventDelayedClose=!0,this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null),this.$container.off("mouseover mouseout")}}),Garnish.$scrollContainer=Garnish.$win,Craft.cp=new Craft.CP;var r=Garnish.Base.extend({$li:null,$a:null,$label:null,$progressLabel:null,progress:null,failMode:!1,_$bgCanvas:null,_$staticCanvas:null,_$hoverCanvas:null,_$failCanvas:null,_staticCtx:null,_hoverCtx:null,_canvasSize:null,_arcPos:null,_arcRadius:null,_lineWidth:null,_arcStartPos:0,_arcEndPos:0,_arcStartStepSize:null,_arcEndStepSize:null,_arcStep:null,_arcStepTimeout:null,_arcAnimateCallback:null,_progressBar:null,init:function(){this.$li=e()("<li/>").appendTo(Craft.cp.$nav.children("ul")),this.$a=e()("<a/>",{id:"job-icon",href:Craft.canAccessQueueManager?Craft.getUrl("utilities/queue-manager"):null}).appendTo(this.$li),this.$canvasContainer=e()('<span class="icon"/>').appendTo(this.$a);var t=e()('<span class="label"/>').appendTo(this.$a);this.$label=e()("<span/>").appendTo(t),this.$progressLabel=e()('<span class="progress-label"/>').appendTo(t).hide();var i=window.devicePixelRatio>1?2:1;this._canvasSize=18*i,this._arcPos=this._canvasSize/2,this._arcRadius=7*i,this._lineWidth=3*i,this._$bgCanvas=this._createCanvas("bg","#61666b"),this._$staticCanvas=this._createCanvas("static","#d7d9db"),this._$hoverCanvas=this._createCanvas("hover","#fff"),this._$failCanvas=this._createCanvas("fail","#da5a47").hide(),this._staticCtx=this._$staticCanvas[0].getContext("2d"),this._hoverCtx=this._$hoverCanvas[0].getContext("2d"),this._drawArc(this._$bgCanvas[0].getContext("2d"),0,1),this._drawArc(this._$failCanvas[0].getContext("2d"),0,1)},setDescription:function(t,e){this.$a.attr("title",t),this.$label.text(t),e?this.$progressLabel.text(e).show():this.$progressLabel.hide()},setProgress:function(t){0==t?(this._$staticCanvas.hide(),this._$hoverCanvas.hide()):(this._$staticCanvas.show(),this._$hoverCanvas.show(),this.progress&&t>this.progress?this._animateArc(0,t/100):this._setArc(0,t/100)),this.progress=t},complete:function(){var t=this;this._animateArc(0,1,(function(){t._$bgCanvas.velocity("fadeOut"),t._animateArc(1,1,(function(){t.$a.remove(),t.destroy()}))}))},showFailMode:function(t){this.failMode||(this.failMode=!0,this.progress=null,this._$bgCanvas.hide(),this._$staticCanvas.hide(),this._$hoverCanvas.hide(),this._$failCanvas.show(),this.setDescription(t))},hideFailMode:function(){this.failMode&&(this.failMode=!1,this._$bgCanvas.show(),this._$staticCanvas.show(),this._$hoverCanvas.show(),this._$failCanvas.hide())},_createCanvas:function(t,i){var s=e()('<canvas id="job-icon-'+t+'" width="'+this._canvasSize+'" height="'+this._canvasSize+'"/>').appendTo(this.$canvasContainer),n=s[0].getContext("2d");return n.strokeStyle=i,n.lineWidth=this._lineWidth,n.lineCap="round",s},_setArc:function(t,e){this._arcStartPos=t,this._arcEndPos=e,this._drawArc(this._staticCtx,t,e),this._drawArc(this._hoverCtx,t,e)},_drawArc:function(t,e,i){t.clearRect(0,0,this._canvasSize,this._canvasSize),t.beginPath(),t.arc(this._arcPos,this._arcPos,this._arcRadius,(1.5+2*e)*Math.PI,(1.5+2*i)*Math.PI),t.stroke(),t.closePath()},_animateArc:function(t,e,i){this._arcStepTimeout&&clearTimeout(this._arcStepTimeout),this._arcStep=0,this._arcStartStepSize=(t-this._arcStartPos)/10,this._arcEndStepSize=(e-this._arcEndPos)/10,this._arcAnimateCallback=i,this._takeNextArcStep()},_takeNextArcStep:function(){this._setArc(this._arcStartPos+this._arcStartStepSize,this._arcEndPos+this._arcEndStepSize),this._arcStep++,this._arcStep<10?this._arcStepTimeout=setTimeout(this._takeNextArcStep.bind(this),50):this._arcAnimateCallback&&this._arcAnimateCallback()}});__webpack_require__(3778),__webpack_require__(6617),__webpack_require__(9482),__webpack_require__(3352),__webpack_require__(691),__webpack_require__(1519),__webpack_require__(501),__webpack_require__(2318),__webpack_require__(4755),__webpack_require__(8468),__webpack_require__(5049),__webpack_require__(7998),__webpack_require__(4233),__webpack_require__(9699),__webpack_require__(1402),__webpack_require__(8201),__webpack_require__(9712),__webpack_require__(3347),__webpack_require__(9478),__webpack_require__(2387),__webpack_require__(7966),__webpack_require__(657),__webpack_require__(4487),__webpack_require__(6966),__webpack_require__(5080),__webpack_require__(7439),__webpack_require__(5328),__webpack_require__(6419),__webpack_require__(872),__webpack_require__(1396),__webpack_require__(4070),__webpack_require__(5763),__webpack_require__(5185),__webpack_require__(8030),__webpack_require__(3096),__webpack_require__(3331),__webpack_require__(53),__webpack_require__(5074),__webpack_require__(3958),__webpack_require__(1592),__webpack_require__(1752),__webpack_require__(7e3),__webpack_require__(8654)}()})();
 //# sourceMappingURL=cp.js.map
\ No newline at end of file

programming_language: JavaScript
filename: cp.js.map
change_type: ModificationType.MODIFY
diff: @@ -1 +1 @@
-{"version":3,"file":"cp.js","mappings":"oDAKAA,MAAMC,UAAYC,QAAQC,KAAKC,OAAO,CACpCC,SAAU,KACVC,eAAgB,KAEhBC,SAAU,KAEVC,KAAM,SAAUC,GAAS,WACvBC,KAAKL,SAAWM,EAAEF,GAGdC,KAAKL,SAASO,KAAK,eACrBC,QAAQC,KAAK,2DACbJ,KAAKL,SAASO,KAAK,aAAaG,WAGlCL,KAAKL,SAASO,KAAK,YAAaF,MAChCA,KAAKJ,eAAiBI,KAAKL,SAASW,KAAK,iBAAgB,WACjDN,KAAKL,SAASW,KAAK,kBACvB,KAEAN,KAAKJ,iBACPI,KAAKH,SAAWI,EAAED,KAAKJ,iBAGzBI,KAAKO,YAAYP,KAAKL,SAAU,QAAS,kBACzCK,KAAKO,YAAYP,KAAKL,SAAU,YAAY,SAACa,GAC3C,IAAMC,EAAMD,EAAME,QAEdD,IAAQjB,QAAQmB,WAAaF,IAAQjB,QAAQoB,aAC/CJ,EAAMK,iBACN,EAAKC,iBAET,GACF,EAEAA,eAAgB,WACyC,SAAxCd,KAAKL,SAASW,KAAK,iBAGhCN,KAAKe,WAAWf,KAAKH,UAErBG,KAAKgB,WAAWhB,KAAKH,SAEzB,EAEAmB,WAAY,SAAUC,GAAS,WAC7B,GAAIA,GAAWA,EAAQC,OAAQ,CAC7BlB,KAAKgB,WAAWG,eAAiBF,EAAQG,SAEzCH,EAAQI,YAAY,UAEpBrB,KAAKL,SACF0B,YAAY,aACZC,SAAS,YACThB,KAAK,gBAAiB,QAEzB,IAAK,IAAIiB,EAAI,EAAGA,EAAIN,EAAQC,OAAQK,KAClC,SAAEC,G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ACF5nH,KAAK+lH,QACL/lH,KAAK+lH,QACL/lH,KAAKgmH,YACJ,IAAiB,EAAXwB,GAAgB74G,KAAK8K,IAC3B,IAAe,EAATguG,GAAc94G,KAAK8K,IAE5B2tG,EAAInzG,SACJmzG,EAAIS,WACN,EAEAb,YAAa,SAAUc,EAAgBC,EAAc3oG,GAC/Cpf,KAAKumH,iBACPvvF,aAAah3B,KAAKumH,iBAGpBvmH,KAAKsmH,SAAW,EAChBtmH,KAAKomH,mBAAqB0B,EAAiB9nH,KAAKkmH,cAAgB,GAChElmH,KAAKqmH,iBAAmB0B,EAAe/nH,KAAKmmH,YAAc,GAC1DnmH,KAAKwmH,oBAAsBpnG,EAC3Bpf,KAAKgoH,kBACP,EAEAA,iBAAkB,WAChBhoH,KAAKinH,QACHjnH,KAAKkmH,aAAelmH,KAAKomH,kBACzBpmH,KAAKmmH,WAAanmH,KAAKqmH,iBAGzBrmH,KAAKsmH,WAEDtmH,KAAKsmH,SAAW,GAClBtmH,KAAKumH,gBAAkBxvF,WAAW/2B,KAAKgoH,iBAAiB3hH,KAAKrG,MAAO,IAC3DA,KAAKwmH,qBACdxmH,KAAKwmH,qBAET,I","sources":["webpack:///./js/Accordion.js","webpack:///./js/AddressesInput.js","webpack:///./js/AdminTable.js","webpack:///./js/AssetImageEditor.js","webpack:///./js/AssetIndex.js","webpack:///./js/AssetMover.js","webpack:///./js/AssetSelectInput.js","webpack:///./js/AssetSelectorModal.js","webpack:///./js/AssetsFieldSettings.js","webpack:///./js/AuthManager.js","webpack:///./js/BaseElementIndex.js","webpack:///./js/BaseElementIndexView.js","webpack:///./js/BaseElementSelectInput.js","webpack:///./js/BaseElementSelectorModal.js","webpack:///./js/BaseInputGenerator.js","webpack:///./js/CategoryIndex.js","webpack:///./js/CategorySelectInput.js","webpack:///./js/Chart.js","webpack:///./js/ColorInput.js","webpack:///./js/CpScreenSlideout.js","webpack:///./js/Craft.js","webpack:///./js/CustomizeSourcesModal.js","webpack:///./js/DataTableSorter.js","webpack:///./js/DeleteUserModal.js","webpack:///./js/DynamicGenerator.js","webpack:///./js/EditableTable.js","webpack:///./js/ElementActionTrigger.js","webpack:///./js/ElementEditor.js","webpack:///./js/ElementEditorSlideout.js","webpack:///./js/ElementFieldSettings.js","webpack:///./js/ElementThumbLoader.js","webpack:///./js/ElevatedSessionForm.js","webpack:///./js/ElevatedSessionManager.js","webpack:///./js/EntryIndex.js","webpack:///./js/FieldLayoutDesigner.js","webpack:///./js/FieldToggle.js","webpack:///./js/Grid.js","webpack:///./js/HandleGenerator.js","webpack:///./js/ImageUpload.js","webpack:///./js/InfoIcon.js","webpack:///./js/LightSwitch.js","webpack:///./js/Listbox.js","webpack:///./js/LivePreview.js","webpack:///./js/PasswordInput.js","webpack:///./js/Preview.js","webpack:///./js/PreviewFileModal.js","webpack:///./js/ProgressBar.js","webpack:///./js/PromptHandler.js","webpack:///./js/Queue.js","webpack:///./js/SlidePicker.js","webpack:///./js/SlideRuleInput.js","webpack:///./js/Slideout.js","webpack:///./js/SlugGenerator.js","webpack:///./js/Structure.js","webpack:///./js/StructureDrag.js","webpack:///./js/StructureTableSorter.js","webpack:///./js/TableElementIndexView.js","webpack:///./js/Tabs.js","webpack:///./js/TagSelectInput.js","webpack:///./js/ThumbsElementIndexView.js","webpack:///./js/UI.js","webpack:///./js/Uploader.js","webpack:///./js/UriFormatGenerator.js","webpack:///./js/UserIndex.js","webpack:///./js/VolumeFolderSelectorModal.js","webpack:///./css/charts.scss?4afb","webpack:///./css/craft.scss?1b58","webpack:///../../../../../node_modules/vue-style-loader/lib/listToStyles.js","webpack:///../../../../../node_modules/vue-style-loader/lib/addStylesClient.js","webpack:///webpack/bootstrap","webpack:///webpack/runtime/compat get default export","webpack:///webpack/runtime/define property getters","webpack:///webpack/runtime/hasOwnProperty shorthand","webpack:///external var \"jQuery\"","webpack:///./js/CP.js"],"sourcesContent":["/** global: Craft */\n/** global: Garnish */\n/**\n * Accordion\n */\nCraft.Accordion = Garnish.Base.extend({\n  $trigger: null,\n  targetSelector: null,\n\n  _$target: null,\n\n  init: function (trigger) {\n    this.$trigger = $(trigger);\n\n    // Is this already an accordion trigger?\n    if (this.$trigger.data('accordion')) {\n      console.warn('Double-instantiating an accordion trigger on an element');\n      this.$trigger.data('accordion').destroy();\n    }\n\n    this.$trigger.data('accordion', this);\n    this.targetSelector = this.$trigger.attr('aria-controls')\n      ? `#${this.$trigger.attr('aria-controls')}`\n      : null;\n\n    if (this.targetSelector) {\n      this._$target = $(this.targetSelector);\n    }\n\n    this.addListener(this.$trigger, 'click', 'onTriggerClick');\n    this.addListener(this.$trigger, 'keypress', (event) => {\n      const key = event.keyCode;\n\n      if (key === Garnish.SPACE_KEY || key === Garnish.RETURN_KEY) {\n        event.preventDefault();\n        this.onTriggerClick();\n      }\n    });\n  },\n\n  onTriggerClick: function () {\n    const isOpen = this.$trigger.attr('aria-expanded') === 'true';\n\n    if (isOpen) {\n      this.hideTarget(this._$target);\n    } else {\n      this.showTarget(this._$target);\n    }\n  },\n\n  showTarget: function ($target) {\n    if ($target && $target.length) {\n      this.showTarget._currentHeight = $target.height();\n\n      $target.removeClass('hidden');\n\n      this.$trigger\n        .removeClass('collapsed')\n        .addClass('expanded')\n        .attr('aria-expanded', 'true');\n\n      for (let i = 0; i < $target.length; i++) {\n        (($t) => {\n          if ($t.prop('nodeName') !== 'SPAN') {\n            $t.height('auto');\n            this.showTarget._targetHeight = $t.height();\n            $t.css({\n              height: this.showTarget._currentHeight,\n              overflow: 'hidden',\n            });\n\n            $t.velocity('stop');\n\n            $t.velocity(\n              {height: this.showTarget._targetHeight},\n              Garnish.getUserPreferredAnimationDuration('fast'),\n              function () {\n                $t.css({\n                  height: '',\n                  overflow: '',\n                });\n              }\n            );\n          }\n        })($target.eq(i));\n      }\n\n      delete this.showTarget._targetHeight;\n      delete this.showTarget._currentHeight;\n\n      // Trigger a resize event in case there are any grids in the target that need to initialize\n      Garnish.$win.trigger('resize');\n    }\n  },\n\n  hideTarget: function ($target) {\n    if ($target && $target.length) {\n      this.$trigger\n        .removeClass('expanded')\n        .addClass('collapsed')\n        .attr('aria-expanded', 'false');\n\n      for (let i = 0; i < $target.length; i++) {\n        (($t) => {\n          if ($t.hasClass('hidden')) {\n            return;\n          }\n          if ($t.prop('nodeName') === 'SPAN') {\n            $t.addClass('hidden');\n          } else {\n            $t.css('overflow', 'hidden');\n            $t.velocity('stop');\n            $t.velocity(\n              {height: 0},\n              Garnish.getUserPreferredAnimationDuration('fast'),\n              function () {\n                $t.addClass('hidden');\n              }\n            );\n          }\n        })($target.eq(i));\n      }\n    }\n  },\n\n  destroy: function () {\n    this.$trigger.removeData('accordion');\n    this.base();\n  },\n});\n","/** global: Craft */\n\n/**\n * AddressInput class\n */\nCraft.AddressesInput = Garnish.Base.extend(\n  {\n    $container: null,\n    $addBtn: null,\n    $addBtnItem: null,\n    $cards: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.AddressesInput.defaults);\n\n      // Is this already an address input?\n      if (this.$container.data('addresses')) {\n        console.warn('Double-instantiating an address input on an element');\n        this.$container.data('addresses').destroy();\n      }\n\n      this.$container.data('addresses', this);\n\n      this.$addBtn = this.$container.find('.address-cards__add-btn');\n      this.$addBtnItem = this.$addBtn.closest('li');\n      this.$cards = this.$container.find('> .address-card');\n\n      for (let i = 0; i < this.$cards.length; i++) {\n        this.initCard(this.$cards.eq(i));\n      }\n\n      this.updateAddButton();\n\n      this.addListener(this.$addBtn, 'click', () => {\n        this.createAddress();\n      });\n    },\n\n    initCard: function ($card) {\n      this.addListener($card, 'click', (ev) => {\n        if (!$(ev.target).closest('.menubtn').length) {\n          this.editAddress($card);\n        }\n      });\n\n      const $actionBtn = $card.find('.menubtn').disclosureMenu();\n      if ($actionBtn.length) {\n        const menu = $actionBtn.data('trigger');\n        const $menu = menu.$container;\n\n        // Activate edit button\n        const $editBtn = $menu.find('[data-action=\"edit\"]');\n        this.addListener($editBtn, 'click', (ev) => {\n          ev.stopPropagation();\n          this.editAddress($card);\n        });\n\n        // Activate delete button\n        const $deleteBtn = $menu.find('[data-action=\"delete\"]');\n        this.addListener($deleteBtn, 'click', (ev) => {\n          ev.preventDefault();\n          ev.stopPropagation();\n          if (\n            confirm(\n              Craft.t('app', 'Are you sure you want to delete this address?')\n            )\n          ) {\n            this.$addBtn.addClass('loading');\n            const addressId = $card.data('id');\n            const draftId = $card.data('draft-id');\n            Craft.sendActionRequest('POST', 'elements/delete', {\n              data: {\n                elementId: addressId,\n                draftId: draftId,\n              },\n            })\n              .then(() => {\n                $card.remove();\n                $menu.remove();\n                menu.destroy();\n                this.$cards = this.$cards.not($card);\n                this.updateAddButton();\n\n                this.trigger('deleteAddress', {\n                  addressId,\n                  draftId,\n                });\n              })\n              .finally(() => {\n                this.$addBtn.removeClass('loading');\n              });\n          }\n        });\n      }\n    },\n\n    editAddress: function ($card, settings) {\n      const slideout = Craft.createElementEditor(\n        'craft\\\\elements\\\\Address',\n        $card,\n        settings\n      );\n\n      slideout.on('submit', (ev) => {\n        this.trigger('saveAddress', {\n          data: ev.data,\n        });\n\n        Craft.sendActionRequest('POST', 'addresses/card-html', {\n          data: {\n            addressId: ev.data.id,\n          },\n        }).then((response) => {\n          const $newCard = $(response.data.html);\n          if ($card) {\n            $card.replaceWith($newCard);\n            this.$cards = this.$cards.not($card);\n          } else {\n            $newCard.insertBefore(this.$addBtnItem);\n          }\n          Craft.initUiElements($newCard);\n          this.initCard($newCard);\n          this.$cards = this.$cards.add($newCard);\n          this.updateAddButton();\n        });\n      });\n    },\n\n    updateAddButton: function () {\n      if (this.canCreateAddress()) {\n        this.$addBtn.removeClass('hidden');\n      } else {\n        this.$addBtn.addClass('hidden');\n      }\n    },\n\n    canCreateAddress: function () {\n      return (\n        !this.settings.maxAddresses ||\n        this.$cards.length < this.settings.maxAddresses\n      );\n    },\n\n    createAddress: function () {\n      if (!this.canCreateAddress()) {\n        throw 'No more addresses can be created.';\n      }\n\n      this.$addBtn.addClass('loading');\n\n      Craft.sendActionRequest('POST', 'elements/create', {\n        data: {\n          elementType: 'craft\\\\elements\\\\Address',\n          ownerId: this.settings.ownerId,\n        },\n      })\n        .then((ev) => {\n          this.editAddress(null, {\n            elementId: ev.data.element.id,\n            draftId: ev.data.element.draftId,\n          });\n        })\n        .finally(() => {\n          this.$addBtn.removeClass('loading');\n        });\n    },\n\n    destroy: function () {\n      this.$container.removeData('addresses');\n      this.base();\n    },\n  },\n  {\n    ownerId: null,\n    defaults: {\n      maxAddresses: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Admin table class\n */\nCraft.AdminTable = Garnish.Base.extend(\n  {\n    settings: null,\n    totalItems: null,\n    sorter: null,\n\n    $noItems: null,\n    $table: null,\n    $tbody: null,\n    $deleteBtns: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.AdminTable.defaults);\n\n      if (!this.settings.allowDeleteAll) {\n        this.settings.minItems = 1;\n      }\n\n      this.$noItems = $(this.settings.noItemsSelector);\n      this.$table = $(this.settings.tableSelector);\n      this.$tbody = this.$table.children('tbody');\n      this.totalItems = this.$tbody.children().length;\n\n      if (this.settings.sortable) {\n        this.sorter = new Craft.DataTableSorter(this.$table, {\n          onSortChange: this.reorderItems.bind(this),\n        });\n      }\n\n      this.$deleteBtns = this.$table.find('.delete:not(.disabled)');\n      this.addListener(this.$deleteBtns, 'click', 'handleDeleteBtnClick');\n      this.addListener(this.$deleteBtns, 'keydown', (event) => {\n        if (\n          event.keyCode === Garnish.SPACE_KEY ||\n          event.keyCode === Garnish.RETURN_KEY\n        ) {\n          event.preventDefault();\n          this.handleDeleteBtnClick(event);\n        }\n      });\n\n      this.updateUI();\n    },\n\n    addRow: function (row) {\n      if (this.settings.maxItems && this.totalItems >= this.settings.maxItems) {\n        // Sorry pal.\n        return;\n      }\n\n      var $row = $(row).appendTo(this.$tbody),\n        $deleteBtn = $row.find('.delete');\n\n      if (this.settings.sortable) {\n        this.sorter.addItems($row);\n      }\n\n      this.$deleteBtns = this.$deleteBtns.add($deleteBtn);\n\n      this.addListener($deleteBtn, 'click', 'handleDeleteBtnClick');\n      this.totalItems++;\n\n      this.updateUI();\n    },\n\n    reorderItems: function () {\n      if (!this.settings.sortable) {\n        return;\n      }\n\n      // Get the new field order\n      var ids = [];\n\n      for (var i = 0; i < this.sorter.$items.length; i++) {\n        var id = $(this.sorter.$items[i]).attr(this.settings.idAttribute);\n        ids.push(id);\n      }\n\n      // Send it to the server\n      var data = {\n        ids: JSON.stringify(ids),\n      };\n\n      Craft.sendActionRequest('POST', this.settings.reorderAction, {data})\n        .then((response) => {\n          this.onReorderItems(ids);\n          Craft.cp.displaySuccess(\n            Craft.t('app', this.settings.reorderSuccessMessage)\n          );\n        })\n        .catch(({response}) => {\n          Craft.cp.displayError(\n            Craft.t('app', this.settings.reorderFailMessage)\n          );\n        });\n    },\n\n    handleDeleteBtnClick: function (event) {\n      if (this.settings.minItems && this.totalItems <= this.settings.minItems) {\n        // Sorry pal.\n        return;\n      }\n\n      var $row = $(event.target).closest('tr');\n\n      if (this.confirmDeleteItem($row)) {\n        this.deleteItem($row);\n      }\n    },\n\n    confirmDeleteItem: function ($row) {\n      if (!this.settings.confirmDeleteMessage) {\n        return true;\n      }\n\n      var name = this.getItemName($row);\n      return confirm(\n        Craft.t('app', this.settings.confirmDeleteMessage, {name})\n      );\n    },\n\n    deleteItem: function ($row) {\n      var data = {\n        id: this.getItemId($row),\n      };\n\n      Craft.sendActionRequest('POST', this.settings.deleteAction, {data})\n        .then((response) => this.handleDeleteItemSuccess(response.data, $row))\n        .catch(({response}) =>\n          this.handleDeleteItemFailure(response.data, $row)\n        );\n    },\n\n    handleDeleteItemFailure: function (data, $row) {\n      var id = this.getItemId($row),\n        name = this.getItemName($row);\n\n      Craft.cp.displayError(\n        Craft.t('app', this.settings.deleteFailMessage, {name})\n      );\n    },\n\n    handleDeleteItemSuccess: function (data, $row) {\n      var id = this.getItemId($row),\n        name = this.getItemName($row);\n\n      if (this.sorter) {\n        this.sorter.removeItems($row);\n      }\n\n      $row.remove();\n      this.totalItems--;\n      this.updateUI();\n      this.onDeleteItem(id);\n\n      if (this.settings.deleteSuccessMessage) {\n        Craft.cp.displaySuccess(\n          Craft.t('app', this.settings.deleteSuccessMessage, {name})\n        );\n      }\n    },\n\n    onReorderItems: function (ids) {\n      this.settings.onReorderItems(ids);\n    },\n\n    onDeleteItem: function (id) {\n      this.settings.onDeleteItem(id);\n    },\n\n    getItemId: function ($row) {\n      return $row.attr(this.settings.idAttribute);\n    },\n\n    getItemName: function ($row) {\n      return Craft.escapeHtml($row.attr(this.settings.nameAttribute));\n    },\n\n    updateUI: function () {\n      // Show the \"No Whatever Exists\" message if there aren't any\n      if (this.totalItems === 0) {\n        this.$table.hide();\n        this.$noItems.removeClass('hidden');\n      } else {\n        this.$table.show();\n        this.$noItems.addClass('hidden');\n      }\n\n      // Disable the sort buttons if there's only one row\n      if (this.settings.sortable) {\n        var $moveButtons = this.$table.find('.move');\n\n        if (this.totalItems === 1) {\n          $moveButtons.addClass('disabled');\n        } else {\n          $moveButtons.removeClass('disabled');\n        }\n      }\n\n      // Disable the delete buttons if we've reached the minimum items\n      if (this.settings.minItems && this.totalItems <= this.settings.minItems) {\n        this.$deleteBtns.addClass('disabled');\n      } else {\n        this.$deleteBtns.removeClass('disabled');\n      }\n\n      // Hide the New Whatever button if we've reached the maximum items\n      if (this.settings.newItemBtnSelector) {\n        if (\n          this.settings.maxItems &&\n          this.totalItems >= this.settings.maxItems\n        ) {\n          $(this.settings.newItemBtnSelector).addClass('hidden');\n        } else {\n          $(this.settings.newItemBtnSelector).removeClass('hidden');\n        }\n      }\n    },\n  },\n  {\n    defaults: {\n      tableSelector: null,\n      noItemsSelector: null,\n      newItemBtnSelector: null,\n      idAttribute: 'data-id',\n      nameAttribute: 'data-name',\n      sortable: false,\n      allowDeleteAll: true,\n      minItems: 0,\n      maxItems: null,\n      reorderAction: null,\n      deleteAction: null,\n      reorderSuccessMessage: Craft.t('app', 'New order saved.'),\n      reorderFailMessage: Craft.t('app', 'Couldn’t save new order.'),\n      confirmDeleteMessage: Craft.t(\n        'app',\n        'Are you sure you want to delete “{name}”?'\n      ),\n      deleteSuccessMessage: Craft.t('app', '“{name}” deleted.'),\n      deleteFailMessage: Craft.t('app', 'Couldn’t delete “{name}”.'),\n      onReorderItems: $.noop,\n      onDeleteItem: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Asset image editor class\n */\n\nCraft.AssetImageEditor = Garnish.Modal.extend(\n  {\n    // jQuery objects\n    $body: null,\n    $footer: null,\n    $imageTools: null,\n    $buttons: null,\n    $cancelBtn: null,\n    $replaceBtn: null,\n    $saveBtn: null,\n    $focalPointBtn: null,\n    $editorContainer: null,\n    $straighten: null,\n    $croppingCanvas: null,\n    $spinner: null,\n    $constraintContainer: null,\n    $constraintRadioInputs: null,\n    $customConstraints: null,\n\n    // FabricJS objects\n    canvas: null,\n    image: null,\n    viewport: null,\n    focalPoint: null,\n    grid: null,\n    croppingCanvas: null,\n    clipper: null,\n    croppingRectangle: null,\n    cropperHandles: null,\n    cropperGrid: null,\n    croppingShade: null,\n\n    // Image state attributes\n    imageStraightenAngle: 0,\n    viewportRotation: 0,\n    originalWidth: 0,\n    originalHeight: 0,\n    imageVerticeCoords: null,\n    zoomRatio: 1,\n\n    // Editor state attributes\n    animationInProgress: false,\n    currentView: '',\n    assetId: null,\n    cacheBust: null,\n    draggingCropper: false,\n    scalingCropper: false,\n    draggingFocal: false,\n    previousMouseX: 0,\n    previousMouseY: 0,\n    shiftKeyHeld: false,\n    editorHeight: 0,\n    editorWidth: 0,\n    cropperState: false,\n    scaleFactor: 1,\n    flipData: {},\n    focalPointState: false,\n    maxImageSize: null,\n    lastLoadedDimensions: null,\n    imageIsLoading: false,\n    mouseMoveEvent: null,\n    croppingConstraint: false,\n    constraintOrientation: 'landscape',\n    showingCustomConstraint: false,\n    saving: false,\n\n    // Rendering proxy functions\n    renderImage: null,\n    renderCropper: null,\n\n    _queue: null,\n\n    init: function (assetId, settings) {\n      this._queue = new Craft.Queue();\n\n      this.cacheBust = Date.now();\n\n      this.setSettings(settings, Craft.AssetImageEditor.defaults);\n\n      if (this.settings.allowDegreeFractions === null) {\n        this.settings.allowDegreeFractions = Craft.isImagick;\n      }\n\n      if (Garnish.prefersReducedMotion()) {\n        this.settings.animationDuration = 1;\n      }\n\n      this.assetId = assetId;\n      this.flipData = {x: 0, y: 0};\n\n      // Build the modal\n      this.$container = $(\n        '<form class=\"modal fitted imageeditor\"></form>'\n      ).appendTo(Garnish.$bod);\n      this.$body = $('<div class=\"body\"></div>').appendTo(this.$container);\n      this.$footer = $('<div class=\"footer\"/>').appendTo(this.$container);\n\n      this.base(this.$container, this.settings);\n\n      this.$buttons = $('<div class=\"buttons right\"/>').appendTo(this.$footer);\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn cancel',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$buttons);\n\n      if (this.settings.allowSavingAsNew) {\n        this.$saveBtn = Craft.ui\n          .createButton({\n            class: 'save copy',\n            label: Craft.t('app', 'Save as a new asset'),\n            spinner: true,\n          })\n          .appendTo(this.$buttons);\n        this.addListener(this.$saveBtn, 'activate', this.saveImage);\n      }\n\n      this.$replaceBtn = Craft.ui\n        .createSubmitButton({\n          class: 'save replace',\n          label: Craft.t('app', 'Save'),\n          spinner: true,\n        })\n        .appendTo(this.$buttons);\n\n      this.addListener(this.$replaceBtn, 'activate', this.saveImage);\n      this.addListener(this.$cancelBtn, 'activate', this.hide);\n      this.removeListener(this.$shade, 'click');\n\n      this.maxImageSize = this.getMaxImageSize();\n      Craft.sendActionRequest('POST', 'assets/image-editor', {\n        data: {assetId},\n      }).then((response) => this.loadEditor(response.data));\n    },\n\n    /**\n     * Get the max image size that is viewable in the editor currently\n     */\n    getMaxImageSize: function () {\n      var browserViewportWidth =\n        Garnish.$doc.get(0).documentElement.clientWidth;\n      var browserViewportHeight =\n        Garnish.$doc.get(0).documentElement.clientHeight;\n\n      return (\n        Math.max(browserViewportHeight, browserViewportWidth) *\n        (window.devicePixelRatio > 1 ? 2 : 1)\n      );\n    },\n\n    /**\n     * Load the editor markup and start loading components and the image.\n     *\n     * @param {Object} data\n     */\n    loadEditor: function (data) {\n      if (!data.html) {\n        Craft.cp.displayError(\n          Craft.t('app', 'Could not load the image editor.')\n        );\n      }\n\n      this.$body.html(data.html);\n      this.$tabs = $('.tabs li', this.$body);\n      this.$viewsContainer = $('.views', this.$body);\n      this.$views = $('> div', this.$viewsContainer);\n      this.$imageTools = $('.image-container .image-tools', this.$body);\n      this.$editorContainer = $('.image-container .image', this.$body);\n      this.$constraintContainer = $('.constraint-group', this.$body);\n      this.$constraintRadioInputs = $(\n        '[name=\"constraint\"]',\n        this.$constraintContainer\n      );\n      this.$focalPointBtn = $('.focal-point', this.$body);\n      this.editorHeight = this.$editorContainer.innerHeight();\n      this.editorWidth = this.$editorContainer.innerWidth();\n\n      this._showSpinner();\n\n      this.updateSizeAndPosition();\n\n      $customConstraintWrapper = this.$constraintRadioInputs\n        .filter('[value=\"custom\"]')\n        .parent();\n\n      // Add custom constraint inputs to fieldset\n      this.$customConstraints = $('<div/>', {\n        class: 'constraint custom hidden',\n        'data-constraint': 'custom',\n      })\n        .append(\n          $('<input/>', {\n            type: 'text',\n            class: 'custom-constraint-w',\n            size: 3,\n            value: 1,\n            'aria-label': Craft.t('app', 'Width unit'),\n          })\n        )\n        .append(\n          $('<span/>', {\n            class: 'custom-constraint-spacer',\n            text: 'x',\n            'aria-hidden': 'true',\n          })\n        )\n        .append(\n          $('<input/>', {\n            type: 'text',\n            class: 'custom-constraint-h',\n            size: 3,\n            value: 1,\n            'aria-label': Craft.t('app', 'Height unit'),\n          })\n        )\n        .appendTo($customConstraintWrapper);\n\n      // Specify which get flipped on orientation change\n      this.$constraintRadioInputs\n        .filter(function () {\n          const regex = /^\\d*\\.\\d+$/;\n          const value = $(this).val();\n          return regex.test(value);\n        })\n        .addClass('flip');\n\n      // Load the canvas on which we'll host our image and set up the proxy render function\n      this.canvas = new fabric.StaticCanvas('image-canvas');\n\n      // Set up the cropping canvas jquery element for tracking all the nice events\n      this.$croppingCanvas = $('#cropping-canvas', this.$editorContainer);\n      this.$croppingCanvas.width(this.editorWidth);\n      this.$croppingCanvas.height(this.editorHeight);\n\n      this.canvas.enableRetinaScaling = true;\n      this.renderImage = () => {\n        Garnish.requestAnimationFrame(this.canvas.renderAll.bind(this.canvas));\n      };\n\n      // Load the image from URL\n      var imageUrl = Craft.getActionUrl('assets/edit-image', {\n        assetId: this.assetId,\n        size: this.maxImageSize,\n        cacheBust: this.cacheBust,\n      });\n\n      // Load image and set up the initial properties\n      fabric.Image.fromURL(imageUrl, (imageObject) => {\n        this.image = imageObject;\n        this.image.set({\n          originX: 'center',\n          originY: 'center',\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n        });\n        this.canvas.add(this.image);\n\n        this.originalHeight = this.image.getHeight();\n        this.originalWidth = this.image.getWidth();\n        this.zoomRatio = 1;\n\n        this.lastLoadedDimensions = this.getScaledImageDimensions();\n\n        // Set up the image bounding box, viewport and position everything\n        this._setFittedImageVerticeCoordinates();\n        this._repositionEditorElements();\n\n        // Set up the focal point\n        var focalState = {\n          imageDimensions: this.getScaledImageDimensions(),\n          offsetX: 0,\n          offsetY: 0,\n        };\n\n        var focal = false;\n        if (data.focalPoint) {\n          // Transform the focal point coordinates from relative to absolute\n          var focalData = data.focalPoint;\n\n          // Resolve for the current image dimensions.\n          var adjustedX = focalState.imageDimensions.width * focalData.x;\n          var adjustedY = focalState.imageDimensions.height * focalData.y;\n\n          focalState.offsetX = adjustedX - focalState.imageDimensions.width / 2;\n          focalState.offsetY =\n            adjustedY - focalState.imageDimensions.height / 2;\n\n          focal = true;\n        }\n\n        this.storeFocalPointState(focalState);\n\n        if (focal) {\n          this._createFocalPoint();\n        }\n\n        this._createViewport();\n        this.storeCropperState();\n\n        // Add listeners to buttons\n        this._addControlListeners();\n\n        // Add mouse event listeners\n        this.addListener(\n          this.$croppingCanvas,\n          'mousemove,touchmove',\n          this._handleMouseMove\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mousedown,touchstart',\n          this._handleMouseDown\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mouseup,touchend',\n          this._handleMouseUp\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mouseout,touchcancel',\n          this._handleMouseOut\n        );\n\n        this._hideSpinner();\n\n        // Render it, finally\n        this.renderImage();\n\n        // Make sure verything gets fired for the first tab\n        this.$tabs.first().trigger('click');\n      });\n    },\n\n    /**\n     * Reload the image to better fit the current available image editor viewport.\n     */\n    _reloadImage: function () {\n      if (this.imageIsLoading) {\n        return;\n      }\n\n      this.imageIsLoading = true;\n      this.maxImageSize = this.getMaxImageSize();\n\n      // Load the image from URL\n      var imageUrl = Craft.getActionUrl('assets/edit-image', {\n        assetId: this.assetId,\n        size: this.maxImageSize,\n        cacheBust: this.cacheBust,\n      });\n\n      this.image.setSrc(imageUrl, (imageObject) => {\n        this.originalHeight = imageObject.getHeight();\n        this.originalWidth = imageObject.getWidth();\n        this.lastLoadedDimensions = {\n          width: this.originalHeight,\n          height: this.originalWidth,\n        };\n        this.updateSizeAndPosition();\n        this.renderImage();\n        this.imageIsLoading = false;\n      });\n    },\n\n    /**\n     * Update the modal size and position on browser resize\n     */\n    updateSizeAndPosition: function () {\n      if (!this.$container) {\n        return;\n      }\n\n      // Fullscreen modal\n      var innerWidth = window.innerWidth;\n      var innerHeight = window.innerHeight;\n\n      this.$container.css({\n        width: innerWidth,\n        'min-width': innerWidth,\n        left: 0,\n\n        height: innerHeight,\n        'min-height': innerHeight,\n        top: 0,\n      });\n\n      this.$body.css({\n        height: innerHeight - (this.$footer.outerHeight() - 1),\n      });\n\n      if (innerWidth < innerHeight) {\n        this.$container.addClass('vertical');\n      } else {\n        this.$container.removeClass('vertical');\n      }\n\n      // If image is already loaded, make sure it looks pretty.\n      if (this.$editorContainer && this.image) {\n        this._repositionEditorElements();\n      }\n    },\n\n    /**\n     * Reposition the editor elements to accurately reflect the editor state with current dimensions\n     */\n    _repositionEditorElements: function () {\n      // Remember what the dimensions were before the resize took place\n      var previousEditorDimensions = {\n        width: this.editorWidth,\n        height: this.editorHeight,\n      };\n\n      this.editorHeight = this.$editorContainer.innerHeight();\n      this.editorWidth = this.$editorContainer.innerWidth();\n\n      this.canvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      var currentScaledDimensions = this.getScaledImageDimensions();\n\n      // If we're cropping now, we have to reposition the cropper correctly in case\n      // the area for image changes, forcing the image size to change as well.\n      if (this.currentView === 'crop') {\n        this.zoomRatio = this.getZoomToFitRatio(\n          this.getScaledImageDimensions()\n        );\n        var previouslyOccupiedArea = this._getBoundingRectangle(\n          this.imageVerticeCoords\n        );\n        this._setFittedImageVerticeCoordinates();\n        this._repositionCropper(previouslyOccupiedArea);\n      } else {\n        // Otherwise just recalculate the image zoom ratio\n        this.zoomRatio =\n          this.getZoomToCoverRatio(this.getScaledImageDimensions()) *\n          this.scaleFactor;\n      }\n\n      // Reposition the image relatively to the previous editor dimensions.\n      this._repositionImage(previousEditorDimensions);\n      this._repositionViewport();\n      this._repositionFocalPoint(previousEditorDimensions);\n      this._zoomImage();\n\n      this.renderImage();\n\n      if (\n        currentScaledDimensions.width / this.lastLoadedDimensions.width > 1.5 ||\n        currentScaledDimensions.height / this.lastLoadedDimensions.height > 1.5\n      ) {\n        this._reloadImage();\n      }\n    },\n\n    /**\n     * Reposition image based on how the editor dimensions have changed.\n     * This ensures keeping the image center offset, if there is any.\n     *\n     * @param {Object} previousEditorDimensions\n     */\n    _repositionImage: function (previousEditorDimensions) {\n      this.image.set({\n        left:\n          this.image.left -\n          (previousEditorDimensions.width - this.editorWidth) / 2,\n        top:\n          this.image.top -\n          (previousEditorDimensions.height - this.editorHeight) / 2,\n      });\n    },\n\n    /**\n     * Create the viewport for image editor.\n     */\n    _createViewport: function () {\n      this.viewport = new fabric.Rect({\n        width: this.image.width,\n        height: this.image.height,\n        fill: 'rgba(127,0,0,1)',\n        originX: 'center',\n        originY: 'center',\n        globalCompositeOperation: 'destination-in', // This clips everything outside of the viewport\n        left: this.image.left,\n        top: this.image.top,\n      });\n      this.canvas.add(this.viewport);\n      this.renderImage();\n    },\n\n    /**\n     * Create the focal point.\n     */\n    _createFocalPoint: function () {\n      var focalPointState = this.focalPointState;\n      var sizeFactor =\n        this.getScaledImageDimensions().width /\n        focalPointState.imageDimensions.width;\n\n      var focalX =\n        focalPointState.offsetX *\n        sizeFactor *\n        this.zoomRatio *\n        this.scaleFactor;\n      var focalY =\n        focalPointState.offsetY *\n        sizeFactor *\n        this.zoomRatio *\n        this.scaleFactor;\n\n      // Adjust by image margins\n      focalX += this.image.left;\n      focalY += this.image.top;\n\n      var deltaX = 0;\n      var deltaY = 0;\n\n      // When creating a fresh focal point, drop it dead in the center of the viewport, not the image.\n      if (\n        this.viewport &&\n        focalPointState.offsetX === 0 &&\n        focalPointState.offsetY === 0\n      ) {\n        if (this.currentView !== 'crop') {\n          deltaX = this.viewport.left - this.image.left;\n          deltaY = this.viewport.top - this.image.top;\n        } else {\n          // Unless we have a cropper showing, in which case drop it in the middle of the cropper\n          deltaX = this.clipper.left - this.image.left;\n          deltaY = this.clipper.top - this.image.top;\n        }\n\n        // Bump focal to middle of viewport\n        focalX += deltaX;\n        focalY += deltaY;\n\n        // Reflect changes in saved state\n        focalPointState.offsetX +=\n          deltaX / (sizeFactor * this.zoomRatio * this.scaleFactor);\n        focalPointState.offsetY +=\n          deltaY / (sizeFactor * this.zoomRatio * this.scaleFactor);\n      }\n\n      this.focalPoint = new fabric.Group(\n        [\n          new fabric.Circle({\n            radius: 8,\n            fill: 'rgba(0,0,0,0.5)',\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,0.8)',\n            left: 0,\n            top: 0,\n            originX: 'center',\n            originY: 'center',\n          }),\n          new fabric.Circle({\n            radius: 1,\n            fill: 'rgba(255,255,255,0)',\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,0.8)',\n            left: 0,\n            top: 0,\n            originX: 'center',\n            originY: 'center',\n          }),\n        ],\n        {\n          originX: 'center',\n          originY: 'center',\n          left: focalX,\n          top: focalY,\n        }\n      );\n\n      this.storeFocalPointState(focalPointState);\n      this.canvas.add(this.focalPoint);\n    },\n\n    /**\n     * Toggle focal point\n     */\n    toggleFocalPoint: function () {\n      if (!this.focalPoint) {\n        this._createFocalPoint();\n        this.$focalPointBtn.attr('aria-pressed', 'true');\n      } else {\n        this.canvas.remove(this.focalPoint);\n        this.focalPoint = null;\n        this.$focalPointBtn.attr('aria-pressed', 'false');\n      }\n\n      this.renderImage();\n    },\n\n    /**\n     * Reposition the viewport to handle editor resizing.\n     */\n    _repositionViewport: function () {\n      if (this.viewport) {\n        var dimensions = {\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n        };\n\n        // If we're cropping, nothing exciting happens for the viewport\n        if (this.currentView === 'crop') {\n          dimensions.width = this.editorWidth;\n          dimensions.height = this.editorHeight;\n        } else {\n          // If this is the first initial reposition, no cropper state yet\n          if (this.cropperState) {\n            // Recall the state\n            var state = this.cropperState;\n\n            var scaledImageDimensions = this.getScaledImageDimensions();\n            // Make sure we have the correct current image size\n            var sizeFactor =\n              scaledImageDimensions.width / state.imageDimensions.width;\n\n            // Set the viewport dimensions\n            dimensions.width = state.width * sizeFactor * this.zoomRatio;\n            dimensions.height = state.height * sizeFactor * this.zoomRatio;\n\n            // Adjust the image position to show the correct part of the image in the viewport\n            this.image.set({\n              left: this.editorWidth / 2 - state.offsetX * sizeFactor,\n              top: this.editorHeight / 2 - state.offsetY * sizeFactor,\n            });\n          } else {\n            $.extend(dimensions, this.getScaledImageDimensions());\n          }\n        }\n        this.viewport.set(dimensions);\n      }\n    },\n\n    _repositionFocalPoint: function (previousEditorDimensions) {\n      if (this.focalPoint) {\n        var offsetX = this.focalPoint.left - this.editorWidth / 2;\n        var offsetY = this.focalPoint.top - this.editorHeight / 2;\n\n        var currentWidth = this.image.width;\n        var newWidth = this.getScaledImageDimensions().width * this.zoomRatio;\n        var ratio = newWidth / currentWidth / this.scaleFactor;\n\n        offsetX -= (previousEditorDimensions.width - this.editorWidth) / 2;\n        offsetY -= (previousEditorDimensions.height - this.editorHeight) / 2;\n\n        offsetX *= ratio;\n        offsetY *= ratio;\n\n        this.focalPoint.set({\n          left: this.editorWidth / 2 + offsetX,\n          top: this.editorHeight / 2 + offsetY,\n        });\n      }\n    },\n\n    /**\n     * Return true if the image orientation has changed\n     */\n    hasOrientationChanged: function () {\n      return this.viewportRotation % 180 !== 0;\n    },\n\n    /**\n     * Return the current image dimensions that would be used in the current image area with no straightening or rotation applied.\n     */\n    getScaledImageDimensions: function () {\n      if (typeof this.getScaledImageDimensions._ === 'undefined') {\n        this.getScaledImageDimensions._ = {};\n      }\n\n      this.getScaledImageDimensions._.imageRatio =\n        this.originalHeight / this.originalWidth;\n      this.getScaledImageDimensions._.editorRatio =\n        this.editorHeight / this.editorWidth;\n\n      this.getScaledImageDimensions._.dimensions = {};\n      if (\n        this.getScaledImageDimensions._.imageRatio >\n        this.getScaledImageDimensions._.editorRatio\n      ) {\n        this.getScaledImageDimensions._.dimensions.height = Math.min(\n          this.editorHeight,\n          this.originalHeight\n        );\n        this.getScaledImageDimensions._.dimensions.width = Math.round(\n          this.originalWidth /\n            (this.originalHeight /\n              this.getScaledImageDimensions._.dimensions.height)\n        );\n      } else {\n        this.getScaledImageDimensions._.dimensions.width = Math.min(\n          this.editorWidth,\n          this.originalWidth\n        );\n        this.getScaledImageDimensions._.dimensions.height = Math.round(\n          this.originalHeight *\n            (this.getScaledImageDimensions._.dimensions.width /\n              this.originalWidth)\n        );\n      }\n\n      return this.getScaledImageDimensions._.dimensions;\n    },\n\n    /**\n     * Set the image dimensions to reflect the current zoom ratio.\n     */\n    _zoomImage: function () {\n      if (typeof this._zoomImage._ === 'undefined') {\n        this._zoomImage._ = {};\n      }\n\n      this._zoomImage._.imageDimensions = this.getScaledImageDimensions();\n      this.image.set({\n        width: this._zoomImage._.imageDimensions.width * this.zoomRatio,\n        height: this._zoomImage._.imageDimensions.height * this.zoomRatio,\n      });\n    },\n\n    /**\n     * Gets previous tab element from currently-active.\n     */\n    _getPrevTab: function () {\n      const activeTabIndex = this._getActiveTabIndex();\n\n      if (activeTabIndex < 0) return;\n\n      let newTabIndex;\n\n      if (activeTabIndex > 0) {\n        newTabIndex = activeTabIndex - 1;\n      } else {\n        newTabIndex = this.$tabs.length - 1;\n      }\n\n      return this.$tabs.eq(newTabIndex);\n    },\n\n    /**\n     * Gets next tab element from currently-active.\n     */\n    _getNextTab: function () {\n      const activeTabIndex = this._getActiveTabIndex();\n\n      if (activeTabIndex < 0) return;\n\n      let newTabIndex;\n\n      if (activeTabIndex < this.$tabs.length - 1) {\n        newTabIndex = activeTabIndex + 1;\n      } else {\n        newTabIndex = 0;\n      }\n\n      return this.$tabs.eq(newTabIndex);\n    },\n\n    /**\n     * Gets active tab element\n     */\n    _getActiveTab: function () {\n      return this.$tabs.filter('[aria-selected=\"true\"]');\n    },\n\n    /**\n     * Gets index of active tab among sibling tabs\n     */\n    _getActiveTabIndex: function () {\n      const $activeTab = this._getActiveTab();\n\n      if (!$activeTab.length) return;\n\n      return $activeTab.index();\n    },\n\n    /**\n     * Set up listeners for the controls.\n     */\n    _addControlListeners: function () {\n      // Tabs\n      this.addListener(this.$tabs, 'click', this._handleTabClick);\n      this.addListener(this.$tabs, 'keydown', (event) => {\n        switch (event.keyCode) {\n          case Garnish.LEFT_KEY:\n          case Garnish.UP_KEY:\n            event.preventDefault();\n            const $prevTab = this._getPrevTab();\n            this.activateTab($prevTab);\n            break;\n          case Garnish.RIGHT_KEY:\n          case Garnish.DOWN_KEY:\n            event.preventDefault();\n            const $nextTab = this._getNextTab();\n            this.activateTab($nextTab);\n            break;\n        }\n      });\n\n      // Focal point\n      this.addListener(this.$focalPointBtn, 'click', this.toggleFocalPoint);\n\n      // Rotate controls\n      this.addListener($('.rotate-left'), 'click', function () {\n        this.rotateImage(-90);\n      });\n      this.addListener($('.rotate-right'), 'click', function () {\n        this.rotateImage(90);\n      });\n      this.addListener($('.flip-vertical'), 'click', function () {\n        this.flipImage('y');\n      });\n      this.addListener($('.flip-horizontal'), 'click', function () {\n        this.flipImage('x');\n      });\n\n      // Straighten slider\n      this.straighteningInput = new Craft.SlideRuleInput('slide-rule', {\n        onStart: () => {\n          this._showGrid();\n        },\n        onChange: (slider) => {\n          this.straighten(slider);\n        },\n        onEnd: () => {\n          this._hideGrid();\n          this._cleanupFocalPointAfterStraighten();\n        },\n      });\n\n      // Cropper scale modifier key\n      this.addListener(Garnish.$doc, 'keydown', function (ev) {\n        if (ev.keyCode === Garnish.SHIFT_KEY) {\n          this.shiftKeyHeld = true;\n        }\n      });\n      this.addListener(Garnish.$doc, 'keyup', function (ev) {\n        if (ev.keyCode === Garnish.SHIFT_KEY) {\n          this.shiftKeyHeld = false;\n        }\n      });\n\n      this.addListener(\n        this.$constraintRadioInputs,\n        'change',\n        this._handleConstraintChange\n      );\n      this.addListener(\n        $('.orientation input', this.$container),\n        'click',\n        this._handleOrientationClick\n      );\n      this.addListener(\n        $('.constraint-group .custom input', this.$container),\n        'keyup',\n        this._applyCustomConstraint\n      );\n    },\n\n    /**\n     * Handle a constraint button click.\n     *\n     * @param {Object} ev\n     */\n    _handleConstraintClick: function (ev) {\n      var constraint = $(ev.currentTarget).data('constraint');\n      var $target = $(ev.currentTarget);\n      $target.siblings().removeClass('active');\n      $target.addClass('active');\n\n      if (constraint == 'custom') {\n        this._showCustomConstraint();\n        this._applyCustomConstraint();\n        return;\n      }\n\n      this._hideCustomConstraint();\n\n      this.setCroppingConstraint(constraint);\n      this.enforceCroppingConstraint();\n    },\n\n    /**\n     * Handle a constraint change.\n     *\n     * @param {Object} ev\n     */\n    _handleConstraintChange: function (ev) {\n      const constraint = $(ev.target).val();\n\n      if (constraint == 'custom') {\n        this._showCustomConstraint();\n        this._applyCustomConstraint();\n        return;\n      }\n\n      this._hideCustomConstraint();\n\n      this.setCroppingConstraint(constraint);\n      this.enforceCroppingConstraint();\n    },\n\n    /**\n     * Handle an orientation switch click.\n     *\n     * @param {Object} ev\n     */\n    _handleOrientationClick: function (ev) {\n      if (ev.currentTarget.value === this.constraintOrientation) {\n        return;\n      }\n      this.constraintOrientation = ev.currentTarget.value;\n\n      const $constraints = $('.flip', this.$constraintContainer);\n\n      for (var i = 0; i < $constraints.length; i++) {\n        var $constraint = $($constraints[i]);\n        const labelSelector = 'label[for=\"' + $constraint.attr('id') + '\"]';\n        const $label = $(labelSelector, this.$constraintContainer);\n        $constraint.val(1 / $constraint.val());\n        $label.html(\n          $label.text().split(':').reverse().join(':').replace(/\\s/g, '')\n        );\n      }\n\n      $constraints.filter(':checked').trigger('change');\n    },\n\n    /**\n     * Apply the custom ratio set in the inputs\n     */\n    _applyCustomConstraint: function () {\n      var constraint = this._getCustomConstraint();\n\n      if (constraint.w > 0 && constraint.h > 0) {\n        this.setCroppingConstraint(constraint.w / constraint.h);\n        this.enforceCroppingConstraint();\n      }\n    },\n\n    /**\n     * Get the custom constraint.\n     *\n     * @returns {{w: *, h: *}}\n     */\n    _getCustomConstraint: function () {\n      var w = parseFloat($('.custom-constraint-w').val());\n      var h = parseFloat($('.custom-constraint-h').val());\n      return {\n        w: isNaN(w) ? 0 : w,\n        h: isNaN(h) ? 0 : h,\n      };\n    },\n\n    /**\n     * Set the custom constraint.\n     *\n     * @param {number} w\n     * @param {number} h\n     */\n    _setCustomConstraint: function (w, h) {\n      $('.custom-constraint-w').val(parseFloat(w));\n      $('.custom-constraint-h').val(parseFloat(h));\n    },\n\n    /**\n     * Hide the custom constraint inputs.\n     */\n    _hideCustomConstraint: function () {\n      this.showingCustomConstraint = false;\n      this.$customConstraints.addClass('hidden');\n      $('.orientation', this.$container).removeClass('hidden');\n    },\n\n    /**\n     * Show the custom constraint inputs.\n     */\n    _showCustomConstraint: function () {\n      if (this.showingCustomConstraint) {\n        return;\n      }\n\n      this.showingCustomConstraint = true;\n      this.$customConstraints.removeClass('hidden');\n      $('.orientation', this.$container).addClass('hidden');\n    },\n\n    /**\n     * Handle tab click.\n     *\n     * @param {Object} ev\n     */\n    _handleTabClick: function (ev) {\n      if (!this.animationInProgress) {\n        var $tab = $(ev.currentTarget);\n        this.activateTab($tab);\n      }\n    },\n\n    /**\n     * Activate a tab.\n     *\n     * @param {(jQuery|HTMLElement|string)} tab\n     */\n\n    activateTab: function (tab) {\n      const view = $(tab).data('view');\n      this.$tabs.removeClass('selected').attr({\n        'aria-selected': 'false',\n        tabindex: '-1',\n      });\n      $(tab)\n        .addClass('selected')\n        .attr({\n          'aria-selected': 'true',\n          tabindex: '0',\n        })\n        .trigger('focus');\n      this.showView(view);\n    },\n\n    /**\n     * Show a view.\n     *\n     * @param {string} view\n     */\n    showView: function (view) {\n      if (this.currentView === view) {\n        return;\n      }\n\n      this.$views.addClass('hidden');\n      var $view = this.$views.filter('[data-view=\"' + view + '\"]');\n      $view.removeClass('hidden');\n\n      if (view === 'rotate') {\n        this.enableSlider();\n      } else {\n        this.disableSlider();\n      }\n\n      // Now that most likely our editor dimensions have changed, time to reposition stuff\n      this.updateSizeAndPosition();\n\n      // See if we have to enable or disable crop mode as we transition between tabs\n      if (this.currentView === 'crop' && view !== 'crop') {\n        this._queue.push(\n          () =>\n            new Promise((resolve, reject) => {\n              this.disableCropMode();\n              resolve();\n            })\n        );\n      } else if (this.currentView !== 'crop' && view === 'crop') {\n        this._queue.push(\n          () =>\n            new Promise((resolve, reject) => {\n              this.enableCropMode();\n              resolve();\n            })\n        );\n      }\n\n      // Mark the current view\n      this.currentView = view;\n    },\n\n    /**\n     * Store the current cropper state.\n     *\n     * Cropper state is always assumed to be saved at a zoom ratio of 1 to be used\n     * as the basis for recalculating the cropper position and dimensions.\n     *\n     * @param {Object} [state]\n     */\n    storeCropperState: function (state) {\n      if (typeof this.storeCropperState._ === 'undefined') {\n        this.storeCropperState._ = {};\n      }\n\n      // If we're asked to store a specific state.\n      if (state) {\n        this.cropperState = state;\n      } else if (this.clipper) {\n        this.storeCropperState._.zoomFactor = 1 / this.zoomRatio;\n\n        this.cropperState = {\n          offsetX:\n            (this.clipper.left - this.image.left) *\n            this.storeCropperState._.zoomFactor,\n          offsetY:\n            (this.clipper.top - this.image.top) *\n            this.storeCropperState._.zoomFactor,\n          height: this.clipper.height * this.storeCropperState._.zoomFactor,\n          width: this.clipper.width * this.storeCropperState._.zoomFactor,\n          imageDimensions: this.getScaledImageDimensions(),\n        };\n      } else {\n        this.storeCropperState._.dimensions = this.getScaledImageDimensions();\n        this.cropperState = {\n          offsetX: 0,\n          offsetY: 0,\n          height: this.storeCropperState._.dimensions.height,\n          width: this.storeCropperState._.dimensions.width,\n          imageDimensions: this.storeCropperState._.dimensions,\n        };\n      }\n    },\n\n    /**\n     * Store focal point coordinates in a manner that is not tied to zoom ratio and rotation.\n     */\n    storeFocalPointState: function (state) {\n      if (typeof this.storeFocalPointState._ === 'undefined') {\n        this.storeFocalPointState._ = {};\n      }\n\n      // If we're asked to store a specific state.\n      if (state) {\n        this.focalPointState = state;\n      } else if (this.focalPoint) {\n        this.storeFocalPointState._.zoomFactor = 1 / this.zoomRatio;\n        this.focalPointState = {\n          offsetX:\n            ((this.focalPoint.left - this.image.left) *\n              this.storeFocalPointState._.zoomFactor) /\n            this.scaleFactor,\n          offsetY:\n            ((this.focalPoint.top - this.image.top) *\n              this.storeFocalPointState._.zoomFactor) /\n            this.scaleFactor,\n          imageDimensions: this.getScaledImageDimensions(),\n        };\n      }\n    },\n\n    /**\n     * Rotate the image along with the viewport.\n     *\n     * @param {number} degrees\n     */\n    rotateImage: function (degrees) {\n      if (!this.animationInProgress) {\n        // We're not that kind of an establishment, sir.\n        if (degrees !== 90 && degrees !== -90) {\n          return false;\n        }\n\n        this.animationInProgress = true;\n        this.viewportRotation += degrees;\n\n        // Normalize the viewport rotation angle so it's between 0 and 359\n        this.viewportRotation = parseInt(\n          (this.viewportRotation + 360) % 360,\n          10\n        );\n\n        var newAngle = this.image.angle + degrees;\n        var scaledImageDimensions = this.getScaledImageDimensions();\n        var imageZoomRatio;\n\n        if (this.hasOrientationChanged()) {\n          imageZoomRatio = this.getZoomToCoverRatio({\n            height: scaledImageDimensions.width,\n            width: scaledImageDimensions.height,\n          });\n        } else {\n          imageZoomRatio = this.getZoomToCoverRatio(scaledImageDimensions);\n        }\n\n        // In cases when for some reason we've already zoomed in on the image,\n        // use existing zoom.\n        if (this.zoomRatio > imageZoomRatio) {\n          imageZoomRatio = this.zoomRatio;\n        }\n\n        var viewportProperties = {\n          angle: degrees === 90 ? '+=90' : '-=90',\n        };\n\n        var imageProperties = {\n          angle: newAngle,\n          width: scaledImageDimensions.width * imageZoomRatio,\n          height: scaledImageDimensions.height * imageZoomRatio,\n        };\n\n        var scaleFactor = 1;\n        if (this.scaleFactor < 1) {\n          scaleFactor = 1 / this.scaleFactor;\n          this.scaleFactor = 1;\n        } else {\n          if (this.viewport.width > this.editorHeight) {\n            scaleFactor = this.editorHeight / this.viewport.width;\n          } else if (this.viewport.height > this.editorWidth) {\n            scaleFactor = this.editorWidth / this.viewport.height;\n          }\n          this.scaleFactor = scaleFactor;\n        }\n\n        if (scaleFactor < 1) {\n          imageProperties.width *= scaleFactor;\n          imageProperties.height *= scaleFactor;\n        }\n\n        var state = this.cropperState;\n\n        // Make sure we reposition the image as well to focus on the same image area\n        var deltaX = state.offsetX;\n        var deltaY = state.offsetY;\n        var angleInRadians = degrees * (Math.PI / 180);\n\n        // Calculate how the cropper would need to move in a circle to maintain\n        // the focus on the same region if the image was rotated with zoom intact.\n        var newDeltaX =\n          deltaX * Math.cos(angleInRadians) - deltaY * Math.sin(angleInRadians);\n        var newDeltaY =\n          deltaX * Math.sin(angleInRadians) + deltaY * Math.cos(angleInRadians);\n\n        var sizeFactor =\n          scaledImageDimensions.width / state.imageDimensions.width;\n\n        var modifiedDeltaX =\n          newDeltaX * sizeFactor * this.zoomRatio * this.scaleFactor;\n        var modifiedDeltaY =\n          newDeltaY * sizeFactor * this.zoomRatio * this.scaleFactor;\n\n        imageProperties.left = this.editorWidth / 2 - modifiedDeltaX;\n        imageProperties.top = this.editorHeight / 2 - modifiedDeltaY;\n\n        state.offsetX = newDeltaX;\n        state.offsetY = newDeltaY;\n\n        var temp = state.width;\n        state.width = state.height;\n        state.height = temp;\n\n        this.storeCropperState(state);\n\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n        }\n\n        this.viewport.animate(viewportProperties, {\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            // If we're zooming the image in or out, better do the same to viewport\n            var temp = this.viewport.height * scaleFactor;\n            this.viewport.height = this.viewport.width * scaleFactor;\n            this.viewport.width = temp;\n            this.viewport.set({angle: 0});\n          },\n        });\n\n        // Animate the rotation and dimension change\n        this.image.animate(imageProperties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            var cleanAngle = parseFloat((this.image.angle + 360) % 360);\n            this.image.set({angle: cleanAngle});\n            this.animationInProgress = false;\n            if (this.focalPoint) {\n              this._adjustFocalPointByAngle(degrees);\n              this.straighten(this.straighteningInput);\n              this.canvas.add(this.focalPoint);\n            } else {\n              this._resetFocalPointPosition();\n            }\n          },\n        });\n      }\n    },\n\n    /**\n     * Flip an image along an axis.\n     *\n     * @param {string} axis\n     */\n    flipImage: function (axis) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        if (this.hasOrientationChanged()) {\n          axis = axis === 'y' ? 'x' : 'y';\n        }\n\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n        } else {\n          this._resetFocalPointPosition();\n        }\n\n        var editorCenter = {x: this.editorWidth / 2, y: this.editorHeight / 2};\n        this.straighteningInput.setValue(-this.imageStraightenAngle);\n        this.imageStraightenAngle = -this.imageStraightenAngle;\n        var properties = {\n          angle: this.viewportRotation + this.imageStraightenAngle,\n        };\n\n        var deltaY, deltaX;\n        var cropperState = this.cropperState;\n        var focalPointState = this.focalPointState;\n\n        // Reposition the image, viewport, and stored cropper and focal point states.\n        if (\n          (axis === 'y' && this.hasOrientationChanged()) ||\n          (axis !== 'y' && !this.hasOrientationChanged())\n        ) {\n          cropperState.offsetX = -cropperState.offsetX;\n          focalPointState.offsetX = -focalPointState.offsetX;\n          deltaX = this.image.left - editorCenter.x;\n          properties.left = editorCenter.x - deltaX;\n        } else {\n          cropperState.offsetY = -cropperState.offsetY;\n          focalPointState.offsetY = -focalPointState.offsetY;\n          deltaY = this.image.top - editorCenter.y;\n          properties.top = editorCenter.y - deltaY;\n        }\n\n        if (axis === 'y') {\n          properties.scaleY = this.image.scaleY * -1;\n          this.flipData.y = 1 - this.flipData.y;\n        } else {\n          properties.scaleX = this.image.scaleX * -1;\n          this.flipData.x = 1 - this.flipData.x;\n        }\n\n        this.storeCropperState(cropperState);\n        this.storeFocalPointState(focalPointState);\n\n        this.image.animate(properties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            this.animationInProgress = false;\n            if (this.focalPoint) {\n              // Well this is handy\n              this._adjustFocalPointByAngle(0);\n              this.canvas.add(this.focalPoint);\n            }\n          },\n        });\n      }\n    },\n\n    /**\n     * Perform the straightening with input slider.\n     *\n     * @param {Craft.SlideRuleInput} slider\n     */\n    straighten: function (slider) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        var previousAngle = this.image.angle;\n\n        this.imageStraightenAngle =\n          (this.settings.allowDegreeFractions\n            ? parseFloat(slider.value)\n            : Math.round(parseFloat(slider.value))) % 360;\n\n        // Straighten the image\n        this.image.set({\n          angle: this.viewportRotation + this.imageStraightenAngle,\n        });\n\n        // Set the new zoom ratio\n        this.zoomRatio =\n          this.getZoomToCoverRatio(this.getScaledImageDimensions()) *\n          this.scaleFactor;\n        this._zoomImage();\n\n        if (this.cropperState) {\n          this._adjustEditorElementsOnStraighten(previousAngle);\n        }\n\n        this.renderImage();\n\n        this.animationInProgress = false;\n      }\n    },\n\n    /**\n     * Adjust the cropped viewport when straightening the image to correct for\n     * bumping into edges, keeping focus on the cropped area center and to\n     * maintain the illusion that the image is being straightened relative to the viewport center.\n     *\n     * @param {integer} previousAngle integer the previous image angle before straightening\n     */\n    _adjustEditorElementsOnStraighten: function (previousAngle) {\n      var scaledImageDimensions = this.getScaledImageDimensions();\n      var angleDelta = this.image.angle - previousAngle;\n      var state = this.cropperState;\n\n      var currentZoomRatio = this.zoomRatio;\n      var adjustmentRatio = 1;\n\n      var deltaX, deltaY, newCenterX, newCenterY, sizeFactor;\n\n      do {\n        // Get the cropper center coordinates\n        var cropperCenterX = state.offsetX;\n        var cropperCenterY = state.offsetY;\n        var angleInRadians = angleDelta * (Math.PI / 180);\n\n        // Calculate how the cropper would need to move in a circle to maintain\n        // the focus on the same region if the image was rotated with zoom intact.\n        newCenterX =\n          cropperCenterX * Math.cos(angleInRadians) -\n          cropperCenterY * Math.sin(angleInRadians);\n        newCenterY =\n          cropperCenterX * Math.sin(angleInRadians) +\n          cropperCenterY * Math.cos(angleInRadians);\n\n        sizeFactor = scaledImageDimensions.width / state.imageDimensions.width;\n\n        // Figure out the final image offset to keep the viewport focused where we need it\n        deltaX = newCenterX * currentZoomRatio * sizeFactor;\n        deltaY = newCenterY * currentZoomRatio * sizeFactor;\n\n        // If the image would creep in the viewport, figure out how to math around it.\n        var imageVertices = this.getImageVerticeCoords(currentZoomRatio);\n        var rectangle = {\n          width: this.viewport.width,\n          height: this.viewport.height,\n          left: this.editorWidth / 2 - this.viewport.width / 2 + deltaX,\n          top: this.editorHeight / 2 - this.viewport.height / 2 + deltaY,\n        };\n        adjustmentRatio = this._getZoomRatioToFitRectangle(\n          rectangle,\n          imageVertices\n        );\n        currentZoomRatio = currentZoomRatio * adjustmentRatio;\n\n        // If we had to make adjustments, do the calculations again\n      } while (adjustmentRatio !== 1);\n\n      // Reposition the image correctly\n      this.image.set({\n        left: this.editorWidth / 2 - deltaX,\n        top: this.editorHeight / 2 - deltaY,\n      });\n\n      // Finally, store the new cropper state to reflect the rotation change.\n      state.offsetX = newCenterX;\n      state.offsetY = newCenterY;\n      state.width = this.viewport.width / currentZoomRatio / sizeFactor;\n      state.height = this.viewport.height / currentZoomRatio / sizeFactor;\n\n      this.storeCropperState(state);\n\n      // Zoom the image in and we're done.\n      this.zoomRatio = currentZoomRatio;\n\n      if (this.focalPoint) {\n        this._adjustFocalPointByAngle(angleDelta);\n\n        if (!this._isCenterInside(this.focalPoint, this.viewport)) {\n          this.focalPoint.set({opacity: 0});\n        } else {\n          this.focalPoint.set({opacity: 1});\n        }\n      } else if (angleDelta !== 0) {\n        this._resetFocalPointPosition();\n      }\n\n      this._zoomImage();\n    },\n\n    /**\n     * If focal point is active and outside of viewport after straightening, reset it.\n     */\n    _cleanupFocalPointAfterStraighten: function () {\n      if (\n        this.focalPoint &&\n        !this._isCenterInside(this.focalPoint, this.viewport)\n      ) {\n        this.focalPoint.set({opacity: 1});\n        var state = this.focalPointState;\n        state.offsetX = 0;\n        state.offsetY = 0;\n        this.storeFocalPointState(state);\n        this.toggleFocalPoint();\n      }\n    },\n\n    /**\n     * Reset focal point to the middle of image.\n     */\n    _resetFocalPointPosition: function () {\n      var state = this.focalPointState;\n      state.offsetX = 0;\n      state.offsetY = 0;\n      this.storeFocalPointState(state);\n    },\n\n    /**\n     * Returns true if a center of an object is inside another rectangle shaped object that is not rotated.\n     *\n     * @param {Object} object\n     * @param {Object} containingObject\n     * @returns {boolean}\n     */\n    _isCenterInside: function (object, containingObject) {\n      return (\n        object.left > containingObject.left - containingObject.width / 2 &&\n        object.top > containingObject.top - containingObject.height / 2 &&\n        object.left < containingObject.left + containingObject.width / 2 &&\n        object.top < containingObject.top + containingObject.height / 2\n      );\n    },\n\n    /**\n     * Adjust the focal point by an angle in degrees.\n     * @param {number} angle\n     */\n    _adjustFocalPointByAngle: function (angle) {\n      var angleInRadians = angle * (Math.PI / 180);\n      var state = this.focalPointState;\n\n      var focalX = state.offsetX;\n      var focalY = state.offsetY;\n\n      // Calculate how the focal point would need to move in a circle to keep on the same spot\n      // on the image if it was rotated with zoom intact.\n      var newFocalX =\n        focalX * Math.cos(angleInRadians) - focalY * Math.sin(angleInRadians);\n      var newFocalY =\n        focalX * Math.sin(angleInRadians) + focalY * Math.cos(angleInRadians);\n      var sizeFactor =\n        this.getScaledImageDimensions().width / state.imageDimensions.width;\n\n      var adjustedFocalX = newFocalX * sizeFactor * this.zoomRatio;\n      var adjustedFocalY = newFocalY * sizeFactor * this.zoomRatio;\n\n      this.focalPoint.left = this.image.left + adjustedFocalX;\n      this.focalPoint.top = this.image.top + adjustedFocalY;\n\n      state.offsetX = newFocalX;\n      state.offsetY = newFocalY;\n      this.storeFocalPointState(state);\n    },\n\n    /**\n     * Get the zoom ratio required to fit a rectangle within another rectangle, that is defined by vertices.\n     * If the rectangle fits, 1 will be returned.\n     *\n     * @param {Object} rectangle\n     * @param {Object} containingVertices\n     */\n    _getZoomRatioToFitRectangle: function (rectangle, containingVertices) {\n      var rectangleVertices = this._getRectangleVertices(rectangle);\n      var vertex;\n\n      // Check if any of the viewport vertices end up out of bounds\n      for (\n        var verticeIndex = 0;\n        verticeIndex < rectangleVertices.length;\n        verticeIndex++\n      ) {\n        vertex = rectangleVertices[verticeIndex];\n\n        if (!this.arePointsInsideRectangle([vertex], containingVertices)) {\n          break;\n        }\n\n        vertex = false;\n      }\n\n      // If there's no vertex set after loop, it means that all of them are inside the image rectangle\n      var adjustmentRatio;\n\n      if (!vertex) {\n        adjustmentRatio = 1;\n      } else {\n        // Find out which edge got crossed by the vertex\n        var edge = this._getEdgeCrossed(containingVertices, vertex);\n\n        var rectangleCenter = {\n          x: rectangle.left + rectangle.width / 2,\n          y: rectangle.top + rectangle.height / 2,\n        };\n\n        // Calculate how much further that edge needs to be.\n        // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points\n        var distanceFromVertexToEdge =\n          Math.abs(\n            (edge[1].y - edge[0].y) * vertex.x -\n              (edge[1].x - edge[0].x) * vertex.y +\n              edge[1].x * edge[0].y -\n              edge[1].y * edge[0].x\n          ) /\n          Math.sqrt(\n            Math.pow(edge[1].y - edge[0].y, 2) +\n              Math.pow(edge[1].x - edge[0].x, 2)\n          );\n        var distanceFromCenterToEdge =\n          Math.abs(\n            (edge[1].y - edge[0].y) * rectangleCenter.x -\n              (edge[1].x - edge[0].x) * rectangleCenter.y +\n              edge[1].x * edge[0].y -\n              edge[1].y * edge[0].x\n          ) /\n          Math.sqrt(\n            Math.pow(edge[1].y - edge[0].y, 2) +\n              Math.pow(edge[1].x - edge[0].x, 2)\n          );\n\n        // Adjust the zoom ratio\n        adjustmentRatio =\n          (distanceFromVertexToEdge + distanceFromCenterToEdge) /\n          distanceFromCenterToEdge;\n      }\n\n      return adjustmentRatio;\n    },\n\n    /**\n     * Save the image.\n     *\n     * @param {Object} ev\n     */\n    saveImage: function (ev) {\n      var $button = $(ev.currentTarget);\n      if (this.saving) {\n        return false;\n      }\n\n      this.saving = true;\n      $button.addClass('loading');\n      const replace = $button.hasClass('replace');\n\n      var postData = {\n        assetId: this.assetId,\n        viewportRotation: this.viewportRotation,\n        imageRotation: this.imageStraightenAngle,\n        replace: replace ? 1 : 0,\n      };\n\n      if (this.cropperState) {\n        var cropData = {};\n\n        cropData.height = this.cropperState.height;\n        cropData.width = this.cropperState.width;\n        cropData.offsetX = this.cropperState.offsetX;\n        cropData.offsetY = this.cropperState.offsetY;\n\n        postData.imageDimensions = this.cropperState.imageDimensions;\n\n        postData.cropData = cropData;\n      } else {\n        postData.imageDimensions = this.getScaledImageDimensions();\n      }\n\n      if (this.focalPoint) {\n        postData.focalPoint = this.focalPointState;\n      }\n\n      postData.flipData = this.flipData;\n      postData.zoom = this.zoomRatio;\n\n      Craft.sendActionRequest('POST', 'assets/save-image', {data: postData})\n        .then(({data}) => {\n          this.onSave(data);\n          if (replace && Craft.broadcaster) {\n            Craft.broadcaster.postMessage({\n              event: 'saveElement',\n              id: this.assetId,\n            });\n          }\n          this.hide();\n          Craft.cp.runQueue();\n\n          // Refresh Live Preview\n          Craft.Preview.refresh();\n        })\n        .catch(({response}) => {\n          Craft.cp.displayError(response.data.message);\n        })\n        .finally(() => {\n          this.$buttons.find('.btn').removeClass('loading');\n          this.saving = false;\n        });\n    },\n\n    /**\n     * Return image zoom ratio depending on the straighten angle to cover a viewport by given dimensions.\n     *\n     * @param {Object} dimensions\n     */\n    getZoomToCoverRatio: function (dimensions) {\n      // Convert the angle to radians\n      var angleInRadians =\n        Math.abs(this.imageStraightenAngle) * (Math.PI / 180);\n\n      // Calculate the dimensions of the scaled image using the magic of math\n      var scaledWidth =\n        Math.sin(angleInRadians) * dimensions.height +\n        Math.cos(angleInRadians) * dimensions.width;\n      var scaledHeight =\n        Math.sin(angleInRadians) * dimensions.width +\n        Math.cos(angleInRadians) * dimensions.height;\n\n      // Calculate the ratio\n      return Math.max(\n        scaledWidth / dimensions.width,\n        scaledHeight / dimensions.height\n      );\n    },\n\n    /**\n     * Return image zoom ratio depending on the straighten angle to fit inside a viewport by given dimensions.\n     *\n     * @param {Object} dimensions\n     */\n    getZoomToFitRatio: function (dimensions) {\n      // Get the bounding box for a rotated image\n      var boundingBox = this._getImageBoundingBox(dimensions);\n\n      // Scale the bounding box to fit\n      var scale = 1;\n      if (\n        boundingBox.height > this.editorHeight ||\n        boundingBox.width > this.editorWidth\n      ) {\n        var vertScale = this.editorHeight / boundingBox.height;\n        var horiScale = this.editorWidth / boundingBox.width;\n        scale = Math.min(horiScale, vertScale);\n      }\n\n      return scale;\n    },\n\n    /**\n     * Return the combined zoom ratio to fit a rectangle inside image that's been zoomed to fit.\n     */\n    getCombinedZoomRatio: function (dimensions) {\n      return (\n        this.getZoomToCoverRatio(dimensions) /\n        this.getZoomToFitRatio(dimensions)\n      );\n    },\n\n    /**\n     * Draw the grid.\n     *\n     * @private\n     */\n    _showGrid: function () {\n      if (!this.grid) {\n        var strokeOptions = {\n          strokeWidth: 1,\n          stroke: 'rgba(255,255,255,0.5)',\n        };\n\n        var lineCount = 8;\n        var gridWidth = this.viewport.width;\n        var gridHeight = this.viewport.height;\n        var xStep = gridWidth / (lineCount + 1);\n        var yStep = gridHeight / (lineCount + 1);\n\n        var grid = [\n          new fabric.Rect({\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,1)',\n            originX: 'center',\n            originY: 'center',\n            width: gridWidth,\n            height: gridHeight,\n            left: gridWidth / 2,\n            top: gridHeight / 2,\n            fill: 'rgba(255,255,255,0)',\n          }),\n        ];\n\n        var i;\n        for (i = 1; i <= lineCount; i++) {\n          grid.push(\n            new fabric.Line(\n              [i * xStep, 0, i * xStep, gridHeight],\n              strokeOptions\n            )\n          );\n        }\n        for (i = 1; i <= lineCount; i++) {\n          grid.push(\n            new fabric.Line([0, i * yStep, gridWidth, i * yStep], strokeOptions)\n          );\n        }\n\n        this.grid = new fabric.Group(grid, {\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n          originX: 'center',\n          originY: 'center',\n          angle: this.viewport.angle,\n        });\n\n        this.canvas.add(this.grid);\n        this.renderImage();\n      }\n    },\n\n    /**\n     * Hide the grid\n     */\n    _hideGrid: function () {\n      this.canvas.remove(this.grid);\n      this.grid = null;\n      this.renderImage();\n    },\n\n    /**\n     * Remove all the events when hiding the editor.\n     */\n    onFadeOut: function () {\n      this.destroy();\n    },\n\n    /**\n     * Make sure underlying content is not scrolled by accident.\n     */\n    show: function () {\n      this.base();\n      Garnish.$bod.addClass('no-scroll');\n    },\n\n    /**\n     * Allow the content to scroll.\n     */\n    hide: function () {\n      this.removeAllListeners();\n      this.straighteningInput.removeAllListeners();\n      Garnish.$bod.removeClass('no-scroll');\n      this.base();\n    },\n\n    /**\n     * onSave callback.\n     */\n    onSave: function (data) {\n      this.settings.onSave(data);\n      this.trigger('save');\n    },\n\n    /**\n     * Enable the rotation slider.\n     */\n    enableSlider: function () {\n      this.$imageTools.removeClass('hidden');\n    },\n\n    /**\n     * Disable the rotation slider.\n     */\n    disableSlider: function () {\n      this.$imageTools.addClass('hidden');\n    },\n\n    /**\n     * Switch to crop mode.\n     */\n    enableCropMode: function () {\n      var imageDimensions = this.getScaledImageDimensions();\n      this.zoomRatio = this.getZoomToFitRatio(imageDimensions);\n\n      var viewportProperties = {\n        width: this.editorWidth,\n        height: this.editorHeight,\n      };\n\n      var imageProperties = {\n        width: imageDimensions.width * this.zoomRatio,\n        height: imageDimensions.height * this.zoomRatio,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      };\n\n      var callback = () => {\n        this._setFittedImageVerticeCoordinates();\n\n        // Restore cropper\n        var state = this.cropperState;\n        var scaledImageDimensions = this.getScaledImageDimensions();\n        var sizeFactor =\n          scaledImageDimensions.width / state.imageDimensions.width;\n\n        // Restore based on the stored information\n        var cropperData = {\n          left: this.image.left + state.offsetX * sizeFactor * this.zoomRatio,\n          top: this.image.top + state.offsetY * sizeFactor * this.zoomRatio,\n          width: state.width * sizeFactor * this.zoomRatio,\n          height: state.height * sizeFactor * this.zoomRatio,\n        };\n\n        this._showCropper(cropperData);\n\n        if (this.focalPoint) {\n          sizeFactor =\n            scaledImageDimensions.width /\n            this.focalPointState.imageDimensions.width;\n          this.focalPoint.left =\n            this.image.left +\n            this.focalPointState.offsetX * sizeFactor * this.zoomRatio;\n          this.focalPoint.top =\n            this.image.top +\n            this.focalPointState.offsetY * sizeFactor * this.zoomRatio;\n          this.canvas.add(this.focalPoint);\n        }\n      };\n\n      this._editorModeTransition(callback, imageProperties, viewportProperties);\n    },\n\n    /**\n     * Switch out of crop mode.\n     */\n    disableCropMode: function () {\n      var viewportProperties = {};\n\n      this._hideCropper();\n      var imageDimensions = this.getScaledImageDimensions();\n      var targetZoom =\n        this.getZoomToCoverRatio(imageDimensions) * this.scaleFactor;\n      var inverseZoomFactor = targetZoom / this.zoomRatio;\n      this.zoomRatio = targetZoom;\n\n      var imageProperties = {\n        width: imageDimensions.width * this.zoomRatio,\n        height: imageDimensions.height * this.zoomRatio,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      };\n\n      var offsetX = this.clipper.left - this.image.left;\n      var offsetY = this.clipper.top - this.image.top;\n\n      var imageOffsetX = offsetX * inverseZoomFactor;\n      var imageOffsetY = offsetY * inverseZoomFactor;\n      imageProperties.left = this.editorWidth / 2 - imageOffsetX;\n      imageProperties.top = this.editorHeight / 2 - imageOffsetY;\n\n      // Calculate the cropper dimensions after all the zooming\n      viewportProperties.height = this.clipper.height * inverseZoomFactor;\n      viewportProperties.width = this.clipper.width * inverseZoomFactor;\n\n      if (\n        !this.focalPoint ||\n        (this.focalPoint &&\n          !this._isCenterInside(this.focalPoint, this.clipper))\n      ) {\n        if (this.focalPoint) {\n          this.toggleFocalPoint();\n        }\n\n        this._resetFocalPointPosition();\n      }\n\n      var callback = () => {\n        // Reposition focal point correctly\n        if (this.focalPoint) {\n          var sizeFactor =\n            this.getScaledImageDimensions().width /\n            this.focalPointState.imageDimensions.width;\n          this.focalPoint.left =\n            this.image.left +\n            this.focalPointState.offsetX * sizeFactor * this.zoomRatio;\n          this.focalPoint.top =\n            this.image.top +\n            this.focalPointState.offsetY * sizeFactor * this.zoomRatio;\n          this.canvas.add(this.focalPoint);\n        }\n      };\n\n      this._editorModeTransition(callback, imageProperties, viewportProperties);\n    },\n\n    /**\n     * @callback editorModeTransitionCallback\n     */\n    /**\n     * Transition between cropping end editor modes\n     *\n     * @param {editorModeTransitionCallback}\n     * @param {Object} imageProperties\n     * @param {Object} viewportProperties\n     * @private\n     */\n    _editorModeTransition: function (\n      callback,\n      imageProperties,\n      viewportProperties\n    ) {\n      this._queue.pause();\n\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        // Without this it looks semi-broken during animation\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n          this.renderImage();\n        }\n\n        this.image.animate(imageProperties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            callback();\n            this.animationInProgress = false;\n            this.renderImage();\n            this._queue.resume();\n          },\n        });\n\n        this.viewport.animate(viewportProperties, {\n          duration: this.settings.animationDuration,\n        });\n      }\n    },\n\n    _showSpinner: function () {\n      if (!this.$spinner) {\n        this.$spinner = $('<div class=\"spinner big spinner-absolute\"/>');\n      }\n      this.$spinner.appendTo(this.$container.find('.image'));\n    },\n\n    _hideSpinner: function () {\n      this.$spinner.remove();\n    },\n\n    /**\n     * Show the cropper.\n     *\n     * @param {Object} clipperData\n     */\n    _showCropper: function (clipperData) {\n      this._setupCropperLayer(clipperData);\n      this._redrawCropperElements();\n      this.renderCropper();\n    },\n\n    /**\n     * Hide the cropper.\n     */\n    _hideCropper: function () {\n      if (this.clipper) {\n        this.croppingCanvas.remove(this.clipper);\n        this.croppingCanvas.remove(this.croppingShade);\n        this.croppingCanvas.remove(this.cropperHandles);\n        this.croppingCanvas.remove(this.cropperGrid);\n        this.croppingCanvas.remove(this.croppingRectangle);\n\n        this.croppingCanvas = null;\n        this.renderCropper = null;\n      }\n    },\n\n    /**\n     * Draw the cropper.\n     *\n     * @param {Object} clipperData\n     */\n    _setupCropperLayer: function (clipperData) {\n      // Set up the canvas for cropper\n      this.croppingCanvas = new fabric.StaticCanvas('cropping-canvas', {\n        backgroundColor: 'rgba(0,0,0,0)',\n        hoverCursor: 'default',\n        selection: false,\n      });\n\n      this.croppingCanvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      this.renderCropper = () =>\n        Garnish.requestAnimationFrame(\n          this.croppingCanvas.renderAll.bind(this.croppingCanvas)\n        );\n\n      $('#cropping-canvas', this.$editorContainer).css({\n        position: 'absolute',\n        top: 0,\n        left: 0,\n      });\n\n      this.croppingShade = new fabric.Rect({\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n        originX: 'center',\n        originY: 'center',\n        width: this.editorWidth,\n        height: this.editorHeight,\n        fill: 'rgba(0,0,0,0.7)',\n      });\n\n      // Calculate the cropping rectangle size\n      var imageDimensions = this.getScaledImageDimensions();\n      var rectangleRatio =\n        this.imageStraightenAngle === 0\n          ? 1\n          : this.getCombinedZoomRatio(imageDimensions) * 1.2;\n      var rectWidth = imageDimensions.width / rectangleRatio;\n      var rectHeight = imageDimensions.height / rectangleRatio;\n\n      if (this.hasOrientationChanged()) {\n        var temp = rectHeight;\n        rectHeight = rectWidth;\n        rectWidth = temp;\n      }\n\n      // Set up the cropping viewport rectangle\n      this.clipper = new fabric.Rect({\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n        originX: 'center',\n        originY: 'center',\n        width: rectWidth,\n        height: rectHeight,\n        stroke: 'black',\n        fill: 'rgba(128,0,0,1)',\n        strokeWidth: 0,\n      });\n\n      // Set from clipper data\n      if (clipperData) {\n        this.clipper.set(clipperData);\n      }\n\n      this.clipper.globalCompositeOperation = 'destination-out';\n      this.croppingCanvas.add(this.croppingShade);\n      this.croppingCanvas.add(this.clipper);\n    },\n\n    /**\n     * Redraw the cropper boundaries\n     */\n    _redrawCropperElements: function () {\n      if (typeof this._redrawCropperElements._ === 'undefined') {\n        this._redrawCropperElements._ = {};\n      }\n\n      if (this.cropperHandles) {\n        this.croppingCanvas.remove(this.cropperHandles);\n        this.croppingCanvas.remove(this.cropperGrid);\n        this.croppingCanvas.remove(this.croppingRectangle);\n      }\n      this._redrawCropperElements._.lineOptions = {\n        strokeWidth: 4,\n        stroke: 'rgb(255,255,255)',\n        fill: false,\n      };\n\n      this._redrawCropperElements._.gridOptions = {\n        strokeWidth: 2,\n        stroke: 'rgba(255,255,255,0.5)',\n      };\n\n      // Draw the handles\n      this._redrawCropperElements._.pathGroup = [\n        new fabric.Path(\n          'M 0,10 L 0,0 L 10,0',\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M ' +\n            (this.clipper.width - 8) +\n            ',0 L ' +\n            (this.clipper.width + 4) +\n            ',0 L ' +\n            (this.clipper.width + 4) +\n            ',10',\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M ' +\n            (this.clipper.width + 4) +\n            ',' +\n            (this.clipper.height - 8) +\n            ' L' +\n            (this.clipper.width + 4) +\n            ',' +\n            (this.clipper.height + 4) +\n            ' L ' +\n            (this.clipper.width - 8) +\n            ',' +\n            (this.clipper.height + 4),\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M 10,' +\n            (this.clipper.height + 4) +\n            ' L 0,' +\n            (this.clipper.height + 4) +\n            ' L 0,' +\n            (this.clipper.height - 8),\n          this._redrawCropperElements._.lineOptions\n        ),\n      ];\n\n      this.cropperHandles = new fabric.Group(\n        this._redrawCropperElements._.pathGroup,\n        {\n          left: this.clipper.left,\n          top: this.clipper.top,\n          originX: 'center',\n          originY: 'center',\n        }\n      );\n\n      // Don't forget the rectangle\n      this.croppingRectangle = new fabric.Rect({\n        left: this.clipper.left,\n        top: this.clipper.top,\n        width: this.clipper.width,\n        height: this.clipper.height,\n        fill: 'rgba(0,0,0,0)',\n        stroke: 'rgba(255,255,255,0.8)',\n        strokeWidth: 2,\n        originX: 'center',\n        originY: 'center',\n      });\n\n      this.cropperGrid = new fabric.Group(\n        [\n          new fabric.Line(\n            [\n              this.clipper.width * 0.33,\n              0,\n              this.clipper.width * 0.33,\n              this.clipper.height,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              this.clipper.width * 0.66,\n              0,\n              this.clipper.width * 0.66,\n              this.clipper.height,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              0,\n              this.clipper.height * 0.33,\n              this.clipper.width,\n              this.clipper.height * 0.33,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              0,\n              this.clipper.height * 0.66,\n              this.clipper.width,\n              this.clipper.height * 0.66,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n        ],\n        {\n          left: this.clipper.left,\n          top: this.clipper.top,\n          originX: 'center',\n          originY: 'center',\n        }\n      );\n\n      this._redrawCropperElements._.cropTextTop =\n        this.croppingRectangle.top + this.clipper.height / 2 + 12;\n      this._redrawCropperElements._.cropTextBackgroundColor = 'rgba(0,0,0,0)';\n\n      if (\n        this._redrawCropperElements._.cropTextTop + 12 >\n        this.editorHeight - 2\n      ) {\n        this._redrawCropperElements._.cropTextTop -= 24;\n        this._redrawCropperElements._.cropTextBackgroundColor =\n          'rgba(0,0,0,0.5)';\n      }\n\n      this.croppingCanvas.add(this.cropperHandles);\n      this.croppingCanvas.add(this.cropperGrid);\n      this.croppingCanvas.add(this.croppingRectangle);\n    },\n\n    /**\n     * Reposition the cropper when the image editor dimensions change.\n     *\n     * @param {Object} previousImageArea\n     */\n    _repositionCropper: function (previousImageArea) {\n      if (!this.croppingCanvas) {\n        return;\n      }\n\n      // Get the current clipper offset relative to center\n      var currentOffset = {\n        x: this.clipper.left - this.croppingCanvas.width / 2,\n        y: this.clipper.top - this.croppingCanvas.height / 2,\n      };\n\n      // Resize the cropping canvas\n      this.croppingCanvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      // Check by what factor will the new final bounding box be different\n      var currentArea = this._getBoundingRectangle(this.imageVerticeCoords);\n      var areaFactor = currentArea.width / previousImageArea.width;\n\n      // Adjust the cropper size to scale along with the bounding box\n      this.clipper.width = Math.round(this.clipper.width * areaFactor);\n      this.clipper.height = Math.round(this.clipper.height * areaFactor);\n\n      // Adjust the coordinates: re-position clipper in relation to the new center to adjust\n      // for editor size changes and then multiply by the size factor to adjust for image size changes\n      this.clipper.left = this.editorWidth / 2 + currentOffset.x * areaFactor;\n      this.clipper.top = this.editorHeight / 2 + currentOffset.y * areaFactor;\n\n      // Resize the cropping shade\n      this.croppingShade.set({\n        width: this.editorWidth,\n        height: this.editorHeight,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      });\n\n      this._redrawCropperElements();\n      this.renderCropper();\n    },\n\n    /**\n     * Get the dimensions of a bounding rectangle by a set of four coordinates.\n     *\n     * @param {Object} coordinateSet\n     */\n    _getBoundingRectangle: function (coordinateSet) {\n      return {\n        width:\n          Math.max(\n            coordinateSet.a.x,\n            coordinateSet.b.x,\n            coordinateSet.c.x,\n            coordinateSet.d.x\n          ) -\n          Math.min(\n            coordinateSet.a.x,\n            coordinateSet.b.x,\n            coordinateSet.c.x,\n            coordinateSet.d.x\n          ),\n        height:\n          Math.max(\n            coordinateSet.a.y,\n            coordinateSet.b.y,\n            coordinateSet.c.y,\n            coordinateSet.d.y\n          ) -\n          Math.min(\n            coordinateSet.a.y,\n            coordinateSet.b.y,\n            coordinateSet.c.y,\n            coordinateSet.d.y\n          ),\n      };\n    },\n\n    /**\n     * Handle the mouse being clicked.\n     *\n     * @param {Object} ev\n     */\n    _handleMouseDown: function (ev) {\n      // Focal before resize before dragging\n      var focal = this.focalPoint && this._isMouseOver(ev, this.focalPoint);\n      var move = this.croppingCanvas && this._isMouseOver(ev, this.clipper);\n      var handle = this.croppingCanvas && this._cropperHandleHitTest(ev);\n\n      if (handle || move || focal) {\n        this.previousMouseX = ev.pageX;\n        this.previousMouseY = ev.pageY;\n\n        if (focal) {\n          this.draggingFocal = true;\n        } else if (handle) {\n          this.scalingCropper = handle;\n        } else if (move) {\n          this.draggingCropper = true;\n        }\n      }\n    },\n\n    /**\n     * Handle the mouse being moved.\n     *\n     * @param {Object} ev\n     */\n    _handleMouseMove: function (ev) {\n      if (this.mouseMoveEvent !== null) {\n        Garnish.requestAnimationFrame(this._handleMouseMoveInternal.bind(this));\n      }\n      this.mouseMoveEvent = ev;\n    },\n\n    _handleMouseMoveInternal: function () {\n      if (this.mouseMoveEvent === null) {\n        return;\n      }\n\n      if (this.focalPoint && this.draggingFocal) {\n        this._handleFocalDrag(this.mouseMoveEvent);\n        this.storeFocalPointState();\n        this.renderImage();\n      } else if (this.draggingCropper || this.scalingCropper) {\n        if (this.draggingCropper) {\n          this._handleCropperDrag(this.mouseMoveEvent);\n        } else {\n          this._handleCropperResize(this.mouseMoveEvent);\n        }\n\n        this._redrawCropperElements();\n\n        this.storeCropperState();\n        this.renderCropper();\n      } else {\n        this._setMouseCursor(this.mouseMoveEvent);\n      }\n\n      this.previousMouseX = this.mouseMoveEvent.pageX;\n      this.previousMouseY = this.mouseMoveEvent.pageY;\n\n      this.mouseMoveEvent = null;\n    },\n\n    /**\n     * Handle mouse being released.\n     */\n    _handleMouseUp: function () {\n      this.draggingCropper = false;\n      this.scalingCropper = false;\n      this.draggingFocal = false;\n    },\n\n    /**\n     * Handle mouse out\n     *\n     * @param {Object} ev\n     */\n    _handleMouseOut: function (ev) {\n      this._handleMouseUp(ev);\n      this.mouseMoveEvent = ev;\n      this._handleMouseMoveInternal();\n    },\n\n    /**\n     * Handle cropper being dragged.\n     *\n     * @param {Object} ev\n     */\n    _handleCropperDrag: function (ev) {\n      if (typeof this._handleCropperDrag._ === 'undefined') {\n        this._handleCropperDrag._ = {};\n      }\n\n      this._handleCropperDrag._.deltaX = ev.pageX - this.previousMouseX;\n      this._handleCropperDrag._.deltaY = ev.pageY - this.previousMouseY;\n\n      if (\n        this._handleCropperDrag._.deltaX === 0 &&\n        this._handleCropperDrag._.deltaY === 0\n      ) {\n        return false;\n      }\n\n      this._handleCropperDrag._.rectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      this._handleCropperDrag._.vertices = this._getRectangleVertices(\n        this._handleCropperDrag._.rectangle,\n        this._handleCropperDrag._.deltaX,\n        this._handleCropperDrag._.deltaY\n      );\n\n      // If this would drag it outside of the image\n      if (\n        !this.arePointsInsideRectangle(\n          this._handleCropperDrag._.vertices,\n          this.imageVerticeCoords\n        )\n      ) {\n        // Try to find the furthest point in the same general direction where we can drag it\n\n        // Delta iterator setup\n        this._handleCropperDrag._.dxi = 0;\n        this._handleCropperDrag._.dyi = 0;\n        this._handleCropperDrag._.xStep =\n          this._handleCropperDrag._.deltaX > 0 ? -1 : 1;\n        this._handleCropperDrag._.yStep =\n          this._handleCropperDrag._.deltaY > 0 ? -1 : 1;\n\n        // The furthest we can move\n        this._handleCropperDrag._.furthest = 0;\n        this._handleCropperDrag._.furthestDeltas = {};\n\n        // Loop through every combination of dragging it not so far\n        for (\n          this._handleCropperDrag._.dxi = Math.min(\n            Math.abs(this._handleCropperDrag._.deltaX),\n            10\n          );\n          this._handleCropperDrag._.dxi >= 0;\n          this._handleCropperDrag._.dxi--\n        ) {\n          for (\n            this._handleCropperDrag._.dyi = Math.min(\n              Math.abs(this._handleCropperDrag._.deltaY),\n              10\n            );\n            this._handleCropperDrag._.dyi >= 0;\n            this._handleCropperDrag._.dyi--\n          ) {\n            this._handleCropperDrag._.vertices = this._getRectangleVertices(\n              this._handleCropperDrag._.rectangle,\n              this._handleCropperDrag._.dxi *\n                (this._handleCropperDrag._.deltaX > 0 ? 1 : -1),\n              this._handleCropperDrag._.dyi *\n                (this._handleCropperDrag._.deltaY > 0 ? 1 : -1)\n            );\n\n            if (\n              this.arePointsInsideRectangle(\n                this._handleCropperDrag._.vertices,\n                this.imageVerticeCoords\n              )\n            ) {\n              if (\n                this._handleCropperDrag._.dxi + this._handleCropperDrag._.dyi >\n                this._handleCropperDrag._.furthest\n              ) {\n                this._handleCropperDrag._.furthest =\n                  this._handleCropperDrag._.dxi + this._handleCropperDrag._.dyi;\n                this._handleCropperDrag._.furthestDeltas = {\n                  x:\n                    this._handleCropperDrag._.dxi *\n                    (this._handleCropperDrag._.deltaX > 0 ? 1 : -1),\n                  y:\n                    this._handleCropperDrag._.dyi *\n                    (this._handleCropperDrag._.deltaY > 0 ? 1 : -1),\n                };\n              }\n            }\n          }\n        }\n\n        // REALLY can't drag along the cursor movement\n        if (this._handleCropperDrag._.furthest == 0) {\n          return;\n        } else {\n          this._handleCropperDrag._.deltaX =\n            this._handleCropperDrag._.furthestDeltas.x;\n          this._handleCropperDrag._.deltaY =\n            this._handleCropperDrag._.furthestDeltas.y;\n        }\n      }\n\n      this.clipper.set({\n        left: this.clipper.left + this._handleCropperDrag._.deltaX,\n        top: this.clipper.top + this._handleCropperDrag._.deltaY,\n      });\n    },\n\n    /**\n     * Handle focal point being dragged.\n     *\n     * @param {Object} ev\n     */\n    _handleFocalDrag: function (ev) {\n      if (typeof this._handleFocalDrag._ === 'undefined') {\n        this._handleFocalDrag._ = {};\n      }\n\n      if (this.focalPoint) {\n        this._handleFocalDrag._.deltaX = ev.pageX - this.previousMouseX;\n        this._handleFocalDrag._.deltaY = ev.pageY - this.previousMouseY;\n\n        if (\n          this._handleFocalDrag._.deltaX === 0 &&\n          this._handleFocalDrag._.deltaY === 0\n        ) {\n          return;\n        }\n\n        this._handleFocalDrag._.newX =\n          this.focalPoint.left + this._handleFocalDrag._.deltaX;\n        this._handleFocalDrag._.newY =\n          this.focalPoint.top + this._handleFocalDrag._.deltaY;\n\n        // Just make sure that the focal point stays inside the image\n        if (this.currentView === 'crop') {\n          if (\n            !this.arePointsInsideRectangle(\n              [\n                {\n                  x: this._handleFocalDrag._.newX,\n                  y: this._handleFocalDrag._.newY,\n                },\n              ],\n              this.imageVerticeCoords\n            )\n          ) {\n            return;\n          }\n        } else {\n          if (\n            !(\n              this.viewport.left -\n                this.viewport.width / 2 -\n                this._handleFocalDrag._.newX <\n                0 &&\n              this.viewport.left +\n                this.viewport.width / 2 -\n                this._handleFocalDrag._.newX >\n                0 &&\n              this.viewport.top -\n                this.viewport.height / 2 -\n                this._handleFocalDrag._.newY <\n                0 &&\n              this.viewport.top +\n                this.viewport.height / 2 -\n                this._handleFocalDrag._.newY >\n                0\n            )\n          ) {\n            return;\n          }\n        }\n\n        this.focalPoint.set({\n          left: this.focalPoint.left + this._handleFocalDrag._.deltaX,\n          top: this.focalPoint.top + this._handleFocalDrag._.deltaY,\n        });\n      }\n    },\n\n    /**\n     * Set the cropping constraint\n     * @param {string} constraint\n     */\n    setCroppingConstraint: function (constraint) {\n      // In case this caused the sidebar width to change.\n      this.updateSizeAndPosition();\n\n      switch (constraint) {\n        case 'none':\n          this.croppingConstraint = false;\n          break;\n\n        case 'original':\n          this.croppingConstraint = this.originalWidth / this.originalHeight;\n          break;\n\n        case 'current':\n          this.croppingConstraint = this.clipper.width / this.clipper.height;\n          break;\n\n        case 'custom':\n          break;\n        default:\n          this.croppingConstraint = parseFloat(constraint);\n\n          break;\n      }\n    },\n\n    /**\n     * Enforce the cropping constraint\n     */\n    enforceCroppingConstraint: function () {\n      if (typeof this.enforceCroppingConstraint._ === 'undefined') {\n        this.enforceCroppingConstraint._ = {};\n      }\n\n      if (this.animationInProgress || !this.croppingConstraint) {\n        return;\n      }\n\n      this.animationInProgress = true;\n\n      // Mock the clipping rectangle for collision tests\n      this.enforceCroppingConstraint._.rectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      // If wider than it should be\n      if (this.clipper.width > this.clipper.height * this.croppingConstraint) {\n        this.enforceCroppingConstraint._.previousHeight =\n          this.enforceCroppingConstraint._.rectangle.height;\n\n        // Make it taller!\n        this.enforceCroppingConstraint._.rectangle.height =\n          this.clipper.width / this.croppingConstraint;\n\n        // Getting really awkward having to convert between 0;0 being center or top-left corner.\n        this.enforceCroppingConstraint._.rectangle.top -=\n          (this.enforceCroppingConstraint._.rectangle.height -\n            this.enforceCroppingConstraint._.previousHeight) /\n          2;\n\n        // If the clipper would end up out of bounds, make it narrower instead.\n        if (\n          !this.arePointsInsideRectangle(\n            this._getRectangleVertices(\n              this.enforceCroppingConstraint._.rectangle\n            ),\n            this.imageVerticeCoords\n          )\n        ) {\n          this.enforceCroppingConstraint._.rectangle.width =\n            this.clipper.height * this.croppingConstraint;\n          this.enforceCroppingConstraint._.rectangle.height =\n            this.enforceCroppingConstraint._.rectangle.width /\n            this.croppingConstraint;\n        }\n      } else {\n        // Follow the same pattern, if taller than it should be.\n        this.enforceCroppingConstraint._.previousWidth =\n          this.enforceCroppingConstraint._.rectangle.width;\n        this.enforceCroppingConstraint._.rectangle.width =\n          this.clipper.height * this.croppingConstraint;\n        this.enforceCroppingConstraint._.rectangle.left -=\n          (this.enforceCroppingConstraint._.rectangle.width -\n            this.enforceCroppingConstraint._.previousWidth) /\n          2;\n\n        if (\n          !this.arePointsInsideRectangle(\n            this._getRectangleVertices(\n              this.enforceCroppingConstraint._.rectangle\n            ),\n            this.imageVerticeCoords\n          )\n        ) {\n          this.enforceCroppingConstraint._.rectangle.height =\n            this.clipper.width / this.croppingConstraint;\n          this.enforceCroppingConstraint._.rectangle.width =\n            this.enforceCroppingConstraint._.rectangle.height *\n            this.croppingConstraint;\n        }\n      }\n\n      this.enforceCroppingConstraint._.properties = {\n        height: this.enforceCroppingConstraint._.rectangle.height,\n        width: this.enforceCroppingConstraint._.rectangle.width,\n      };\n\n      // Make sure to redraw cropper handles and gridlines when resizing\n      this.clipper.animate(this.enforceCroppingConstraint._.properties, {\n        onChange: () => {\n          this._redrawCropperElements();\n          this.croppingCanvas.renderAll();\n        },\n        duration: this.settings.animationDuration,\n        onComplete: () => {\n          this._redrawCropperElements();\n          this.animationInProgress = false;\n          this.renderCropper();\n          this.storeCropperState();\n        },\n      });\n    },\n\n    /**\n     * Handle cropper being resized.\n     *\n     * @param {Object} ev\n     */\n    _handleCropperResize: function (ev) {\n      if (typeof this._handleCropperResize._ === 'undefined') {\n        this._handleCropperResize._ = {};\n      }\n\n      // Size deltas\n      this._handleCropperResize._.deltaX = ev.pageX - this.previousMouseX;\n      this._handleCropperResize._.deltaY = ev.pageY - this.previousMouseY;\n\n      if (this.scalingCropper === 'b' || this.scalingCropper === 't') {\n        this._handleCropperResize._.deltaX = 0;\n      }\n\n      if (this.scalingCropper === 'l' || this.scalingCropper === 'r') {\n        this._handleCropperResize._.deltaY = 0;\n      }\n\n      if (\n        this._handleCropperResize._.deltaX === 0 &&\n        this._handleCropperResize._.deltaY === 0\n      ) {\n        return;\n      }\n\n      // Translate from center-center origin to absolute coords\n      this._handleCropperResize._.startingRectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      this._handleCropperResize._.rectangle =\n        this._calculateNewCropperSizeByDeltas(\n          this._handleCropperResize._.startingRectangle,\n          this._handleCropperResize._.deltaX,\n          this._handleCropperResize._.deltaY,\n          this.scalingCropper\n        );\n\n      if (\n        this._handleCropperResize._.rectangle.height < 30 ||\n        this._handleCropperResize._.rectangle.width < 30\n      ) {\n        return;\n      }\n\n      if (\n        !this.arePointsInsideRectangle(\n          this._getRectangleVertices(this._handleCropperResize._.rectangle),\n          this.imageVerticeCoords\n        )\n      ) {\n        return;\n      }\n\n      // Translate back to center-center origin.\n      this.clipper.set({\n        top:\n          this._handleCropperResize._.rectangle.top +\n          this._handleCropperResize._.rectangle.height / 2,\n        left:\n          this._handleCropperResize._.rectangle.left +\n          this._handleCropperResize._.rectangle.width / 2,\n        width: this._handleCropperResize._.rectangle.width,\n        height: this._handleCropperResize._.rectangle.height,\n      });\n\n      this._redrawCropperElements();\n    },\n\n    _calculateNewCropperSizeByDeltas: function (\n      startingRectangle,\n      deltaX,\n      deltaY,\n      cropperDirection\n    ) {\n      if (typeof this._calculateNewCropperSizeByDeltas._ === 'undefined') {\n        this._calculateNewCropperSizeByDeltas._ = {};\n      }\n\n      // Center deltas\n      this._calculateNewCropperSizeByDeltas._.topDelta = 0;\n      this._calculateNewCropperSizeByDeltas._.leftDelta = 0;\n\n      this._calculateNewCropperSizeByDeltas._.rectangle = startingRectangle;\n      this._calculateNewCropperSizeByDeltas._.deltaX = deltaX;\n      this._calculateNewCropperSizeByDeltas._.deltaY = deltaY;\n\n      // Lock the aspect ratio if needed\n      if (this.croppingConstraint) {\n        this._calculateNewCropperSizeByDeltas._.change = 0;\n\n        // Take into account the mouse direction and figure out the \"real\" change in cropper size\n        switch (cropperDirection) {\n          case 't':\n            this._calculateNewCropperSizeByDeltas._.change =\n              -this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'b':\n            this._calculateNewCropperSizeByDeltas._.change =\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'r':\n            this._calculateNewCropperSizeByDeltas._.change =\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'l':\n            this._calculateNewCropperSizeByDeltas._.change =\n              -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tr':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? -this._calculateNewCropperSizeByDeltas._.deltaY\n                : this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tl':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? -this._calculateNewCropperSizeByDeltas._.deltaY\n                : -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'br':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? this._calculateNewCropperSizeByDeltas._.deltaY\n                : this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'bl':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? this._calculateNewCropperSizeByDeltas._.deltaY\n                : -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n        }\n\n        if (this.croppingConstraint > 1) {\n          this._calculateNewCropperSizeByDeltas._.deltaX =\n            this._calculateNewCropperSizeByDeltas._.change;\n          this._calculateNewCropperSizeByDeltas._.deltaY =\n            this._calculateNewCropperSizeByDeltas._.deltaX /\n            this.croppingConstraint;\n        } else {\n          this._calculateNewCropperSizeByDeltas._.deltaY =\n            this._calculateNewCropperSizeByDeltas._.change;\n          this._calculateNewCropperSizeByDeltas._.deltaX =\n            this._calculateNewCropperSizeByDeltas._.deltaY *\n            this.croppingConstraint;\n        }\n\n        this._calculateNewCropperSizeByDeltas._.rectangle.height +=\n          this._calculateNewCropperSizeByDeltas._.deltaY;\n        this._calculateNewCropperSizeByDeltas._.rectangle.width +=\n          this._calculateNewCropperSizeByDeltas._.deltaX;\n\n        // Make the cropper compress/expand relative to the correct edge to make it feel \"right\"\n        switch (cropperDirection) {\n          case 't':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX / 2;\n            break;\n          case 'b':\n            this._calculateNewCropperSizeByDeltas._.rectangle.left +=\n              -this._calculateNewCropperSizeByDeltas._.deltaX / 2;\n            break;\n          case 'r':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top +=\n              -this._calculateNewCropperSizeByDeltas._.deltaY / 2;\n            break;\n          case 'l':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY / 2;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tr':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'tl':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'bl':\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n        }\n      } else {\n        // Lock the aspect ratio\n        if (\n          this.shiftKeyHeld &&\n          (cropperDirection === 'tl' ||\n            cropperDirection === 'tr' ||\n            cropperDirection === 'bl' ||\n            cropperDirection === 'br')\n        ) {\n          this._calculateNewCropperSizeByDeltas._.ratio;\n          if (Math.abs(deltaX) > Math.abs(deltaY)) {\n            this._calculateNewCropperSizeByDeltas._.ratio =\n              startingRectangle.width / startingRectangle.height;\n            this._calculateNewCropperSizeByDeltas._.deltaY =\n              this._calculateNewCropperSizeByDeltas._.deltaX /\n              this._calculateNewCropperSizeByDeltas._.ratio;\n            this._calculateNewCropperSizeByDeltas._.deltaY *=\n              cropperDirection === 'tr' || cropperDirection === 'bl' ? -1 : 1;\n          } else {\n            this._calculateNewCropperSizeByDeltas._.ratio =\n              startingRectangle.width / startingRectangle.height;\n            this._calculateNewCropperSizeByDeltas._.deltaX =\n              this._calculateNewCropperSizeByDeltas._.deltaY *\n              this._calculateNewCropperSizeByDeltas._.ratio;\n            this._calculateNewCropperSizeByDeltas._.deltaX *=\n              cropperDirection === 'tr' || cropperDirection === 'bl' ? -1 : 1;\n          }\n        }\n\n        if (cropperDirection.match(/t/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.top +=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n          this._calculateNewCropperSizeByDeltas._.rectangle.height -=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n        }\n        if (cropperDirection.match(/b/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.height +=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n        }\n        if (cropperDirection.match(/r/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.width +=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n        }\n        if (cropperDirection.match(/l/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.left +=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n          this._calculateNewCropperSizeByDeltas._.rectangle.width -=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n        }\n      }\n\n      this._calculateNewCropperSizeByDeltas._.rectangle.top =\n        this._calculateNewCropperSizeByDeltas._.rectangle.top;\n      this._calculateNewCropperSizeByDeltas._.rectangle.left =\n        this._calculateNewCropperSizeByDeltas._.rectangle.left;\n      this._calculateNewCropperSizeByDeltas._.rectangle.width =\n        this._calculateNewCropperSizeByDeltas._.rectangle.width;\n      this._calculateNewCropperSizeByDeltas._.rectangle.height =\n        this._calculateNewCropperSizeByDeltas._.rectangle.height;\n\n      return this._calculateNewCropperSizeByDeltas._.rectangle;\n    },\n\n    /**\n     * Set mouse cursor by it's position over cropper.\n     *\n     * @param {Object} ev\n     */\n    _setMouseCursor: function (ev) {\n      if (typeof this._setMouseCursor._ === 'undefined') {\n        this._setMouseCursor._ = {};\n      }\n\n      if (Garnish.isMobileBrowser(true)) {\n        return;\n      }\n      this._setMouseCursor._.cursor = 'default';\n      this._setMouseCursor._.handle =\n        this.croppingCanvas && this._cropperHandleHitTest(ev);\n      if (this.focalPoint && this._isMouseOver(ev, this.focalPoint)) {\n        this._setMouseCursor._.cursor = 'pointer';\n      } else if (this._setMouseCursor._.handle) {\n        if (\n          this._setMouseCursor._.handle === 't' ||\n          this._setMouseCursor._.handle === 'b'\n        ) {\n          this._setMouseCursor._.cursor = 'ns-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'l' ||\n          this._setMouseCursor._.handle === 'r'\n        ) {\n          this._setMouseCursor._.cursor = 'ew-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'tl' ||\n          this._setMouseCursor._.handle === 'br'\n        ) {\n          this._setMouseCursor._.cursor = 'nwse-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'bl' ||\n          this._setMouseCursor._.handle === 'tr'\n        ) {\n          this._setMouseCursor._.cursor = 'nesw-resize';\n        }\n      } else if (this.croppingCanvas && this._isMouseOver(ev, this.clipper)) {\n        this._setMouseCursor._.cursor = 'move';\n      }\n\n      $('.body').css('cursor', this._setMouseCursor._.cursor);\n    },\n\n    /**\n     * Test whether the mouse cursor is on any cropper handles.\n     *\n     * @param {Object} ev\n     */\n    _cropperHandleHitTest: function (ev) {\n      if (typeof this._cropperHandleHitTest._ === 'undefined') {\n        this._cropperHandleHitTest._ = {};\n      }\n\n      this._cropperHandleHitTest._.parentOffset = this.$croppingCanvas.offset();\n      this._cropperHandleHitTest._.mouseX =\n        ev.pageX - this._cropperHandleHitTest._.parentOffset.left;\n      this._cropperHandleHitTest._.mouseY =\n        ev.pageY - this._cropperHandleHitTest._.parentOffset.top;\n\n      // Compensate for center origin coordinate-wise\n      this._cropperHandleHitTest._.lb =\n        this.clipper.left - this.clipper.width / 2;\n      this._cropperHandleHitTest._.rb =\n        this._cropperHandleHitTest._.lb + this.clipper.width;\n      this._cropperHandleHitTest._.tb =\n        this.clipper.top - this.clipper.height / 2;\n      this._cropperHandleHitTest._.bb =\n        this._cropperHandleHitTest._.tb + this.clipper.height;\n\n      // Left side top/bottom\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb - 3\n      ) {\n        if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.tb + 10 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.tb - 3\n        ) {\n          return 'tl';\n        } else if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.bb + 3 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.bb - 10\n        ) {\n          return 'bl';\n        }\n      }\n      // Right side top/bottom\n      if (\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.rb - 13 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb + 3\n      ) {\n        if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.tb + 10 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.tb - 3\n        ) {\n          return 'tr';\n        } else if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.bb + 2 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.bb - 10\n        ) {\n          return 'br';\n        }\n      }\n\n      // Left or right\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.lb + 3 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb - 3 &&\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb - 10 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb + 10\n      ) {\n        return 'l';\n      }\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb + 1 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.rb - 5 &&\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb - 10 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb + 10\n      ) {\n        return 'r';\n      }\n\n      // Top or bottom\n      if (\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.tb + 4 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb - 2 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb - 10\n      ) {\n        return 't';\n      }\n      if (\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb + 2 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.bb - 4 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb - 10\n      ) {\n        return 'b';\n      }\n\n      return false;\n    },\n\n    /**\n     * Test whether the mouse cursor is on a fabricJS object.\n     *\n     * @param {Object} event\n     * @param {Object} object\n     * @returns {boolean}\n     */\n    _isMouseOver: function (event, object) {\n      if (typeof this._isMouseOver._ === 'undefined') {\n        this._isMouseOver._ = {};\n      }\n\n      this._isMouseOver._.parentOffset = this.$croppingCanvas.offset();\n      this._isMouseOver._.mouseX =\n        event.pageX - this._isMouseOver._.parentOffset.left;\n      this._isMouseOver._.mouseY =\n        event.pageY - this._isMouseOver._.parentOffset.top;\n\n      // Compensate for center origin coordinate-wise\n      this._isMouseOver._.lb = object.left - object.width / 2;\n      this._isMouseOver._.rb = this._isMouseOver._.lb + object.width;\n      this._isMouseOver._.tb = object.top - object.height / 2;\n      this._isMouseOver._.bb = this._isMouseOver._.tb + object.height;\n\n      return (\n        this._isMouseOver._.mouseX >= this._isMouseOver._.lb &&\n        this._isMouseOver._.mouseX <= this._isMouseOver._.rb &&\n        this._isMouseOver._.mouseY >= this._isMouseOver._.tb &&\n        this._isMouseOver._.mouseY <= this._isMouseOver._.bb\n      );\n    },\n\n    /**\n     * Get vertices of a rectangle defined by left,top,height and width properties.\n     * Optionally it's possible to provide offsetX and offsetY values.\n     * Left and top properties of rectangle reference the top-left corner.\n     *\n     * @param {Object} rectangle\n     * @param {number} [offsetX]\n     * @param {number} [offsetY]\n     */\n    _getRectangleVertices: function (rectangle, offsetX, offsetY) {\n      if (typeof this._getRectangleVertices._ === 'undefined') {\n        this._getRectangleVertices._ = {};\n      }\n\n      if (typeof offsetX === 'undefined') {\n        offsetX = 0;\n      }\n      if (typeof offsetY === 'undefined') {\n        offsetY = 0;\n      }\n\n      this._getRectangleVertices._.topLeft = {\n        x: rectangle.left + offsetX,\n        y: rectangle.top + offsetY,\n      };\n\n      this._getRectangleVertices._.topRight = {\n        x: this._getRectangleVertices._.topLeft.x + rectangle.width,\n        y: this._getRectangleVertices._.topLeft.y,\n      };\n      this._getRectangleVertices._.bottomRight = {\n        x: this._getRectangleVertices._.topRight.x,\n        y: this._getRectangleVertices._.topRight.y + rectangle.height,\n      };\n      this._getRectangleVertices._.bottomLeft = {\n        x: this._getRectangleVertices._.topLeft.x,\n        y: this._getRectangleVertices._.bottomRight.y,\n      };\n\n      return [\n        this._getRectangleVertices._.topLeft,\n        this._getRectangleVertices._.topRight,\n        this._getRectangleVertices._.bottomRight,\n        this._getRectangleVertices._.bottomLeft,\n      ];\n    },\n\n    /**\n     * Set image vertice coordinates for an image that's been zoomed to fit.\n     */\n    _setFittedImageVerticeCoordinates: function () {\n      this.imageVerticeCoords = this.getImageVerticeCoords('fit');\n    },\n\n    /**\n     * Get image vertice coords by a zoom mode and taking into account the straightening angle.\n     * The zoomMode can be either \"cover\", \"fit\" or a discrete float value.\n     *\n     * @param {string} zoomMode\n     */\n    getImageVerticeCoords: function (zoomMode) {\n      var angleInRadians =\n        -1 *\n        ((this.hasOrientationChanged() ? 90 : 0) + this.imageStraightenAngle) *\n        (Math.PI / 180);\n\n      var imageDimensions = this.getScaledImageDimensions();\n\n      var ratio;\n\n      if (typeof zoomMode === 'number') {\n        ratio = zoomMode;\n      } else if (zoomMode === 'cover') {\n        ratio = this.getZoomToCoverRatio(imageDimensions);\n      } else {\n        ratio = this.getZoomToFitRatio(imageDimensions);\n      }\n\n      // Get the dimensions of the scaled image\n      var scaledHeight = imageDimensions.height * ratio;\n      var scaledWidth = imageDimensions.width * ratio;\n\n      // Calculate the segments of the containing box for the image.\n      // When referring to top/bottom or right/left segments, these are on the\n      // right-side and bottom projection of the containing box for the zoomed out image.\n      var topVerticalSegment = Math.cos(angleInRadians) * scaledHeight;\n      var bottomVerticalSegment = Math.sin(angleInRadians) * scaledWidth;\n      var rightHorizontalSegment = Math.cos(angleInRadians) * scaledWidth;\n      var leftHorizontalSegment = Math.sin(angleInRadians) * scaledHeight;\n\n      // Calculate the offsets from editor box for the image-containing box\n      var verticalOffset =\n        (this.editorHeight - (topVerticalSegment + bottomVerticalSegment)) / 2;\n      var horizontalOffset =\n        (this.editorWidth - (leftHorizontalSegment + rightHorizontalSegment)) /\n        2;\n\n      // Finally, calculate the image vertice coordinates\n      return {\n        a: {\n          x: horizontalOffset + rightHorizontalSegment,\n          y: verticalOffset,\n        },\n        b: {\n          x: this.editorWidth - horizontalOffset,\n          y: verticalOffset + topVerticalSegment,\n        },\n        c: {\n          x: horizontalOffset + leftHorizontalSegment,\n          y: this.editorHeight - verticalOffset,\n        },\n        d: {\n          x: horizontalOffset,\n          y: verticalOffset + bottomVerticalSegment,\n        },\n      };\n    },\n\n    /**\n     * Debug stuff by continuously rendering a fabric object on canvas.\n     *\n     * @param {Object} fabricObj\n     */\n    _debug: function (fabricObj) {\n      this.canvas.remove(this.debugger);\n      this.debugger = fabricObj;\n      this.canvas.add(this.debugger);\n    },\n\n    /**\n     * Given an array of points in the form of {x: int, y:int} and a rectangle in the form of\n     * {a:{x:int, y:int}, b:{x:int, y:int}, c:{x:int, y:int}} (the fourth vertice is unnecessary)\n     * return true if the point is in the rectangle.\n     *\n     * Adapted from: http://stackoverflow.com/a/2763387/2040791\n     *\n     * @param {Object} points\n     * @param {Object} rectangle\n     */\n    arePointsInsideRectangle: function (points, rectangle) {\n      if (typeof this.arePointsInsideRectangle._ === 'undefined') {\n        this.arePointsInsideRectangle._ = {};\n      }\n\n      // Pre-calculate the vectors and scalar products for two rectangle edges\n      this.arePointsInsideRectangle._.ab = this._getVector(\n        rectangle.a,\n        rectangle.b\n      );\n      this.arePointsInsideRectangle._.bc = this._getVector(\n        rectangle.b,\n        rectangle.c\n      );\n      this.arePointsInsideRectangle._.scalarAbAb = this._getScalarProduct(\n        this.arePointsInsideRectangle._.ab,\n        this.arePointsInsideRectangle._.ab\n      );\n      this.arePointsInsideRectangle._.scalarBcBc = this._getScalarProduct(\n        this.arePointsInsideRectangle._.bc,\n        this.arePointsInsideRectangle._.bc\n      );\n\n      for (\n        this.arePointsInsideRectangle._.i = 0;\n        this.arePointsInsideRectangle._.i < points.length;\n        this.arePointsInsideRectangle._.i++\n      ) {\n        this.arePointsInsideRectangle._.point =\n          points[this.arePointsInsideRectangle._.i];\n\n        // Calculate the vectors for two rectangle sides and for\n        // the vector from vertices a and b to the point P\n        this.arePointsInsideRectangle._.ap = this._getVector(\n          rectangle.a,\n          this.arePointsInsideRectangle._.point\n        );\n        this.arePointsInsideRectangle._.bp = this._getVector(\n          rectangle.b,\n          this.arePointsInsideRectangle._.point\n        );\n\n        // Calculate scalar or dot products for some vector combinations\n        this.arePointsInsideRectangle._.scalarAbAp = this._getScalarProduct(\n          this.arePointsInsideRectangle._.ab,\n          this.arePointsInsideRectangle._.ap\n        );\n        this.arePointsInsideRectangle._.scalarBcBp = this._getScalarProduct(\n          this.arePointsInsideRectangle._.bc,\n          this.arePointsInsideRectangle._.bp\n        );\n\n        this.arePointsInsideRectangle._.projectsOnAB =\n          0 <= this.arePointsInsideRectangle._.scalarAbAp &&\n          this.arePointsInsideRectangle._.scalarAbAp <=\n            this.arePointsInsideRectangle._.scalarAbAb;\n        this.arePointsInsideRectangle._.projectsOnBC =\n          0 <= this.arePointsInsideRectangle._.scalarBcBp &&\n          this.arePointsInsideRectangle._.scalarBcBp <=\n            this.arePointsInsideRectangle._.scalarBcBc;\n\n        if (\n          !(\n            this.arePointsInsideRectangle._.projectsOnAB &&\n            this.arePointsInsideRectangle._.projectsOnBC\n          )\n        ) {\n          return false;\n        }\n      }\n\n      return true;\n    },\n\n    /**\n     * Returns an object representing the vector between points a and b.\n     *\n     * @param {Object} a\n     * @param {Object} b\n     */\n    _getVector: function (a, b) {\n      return {x: b.x - a.x, y: b.y - a.y};\n    },\n\n    /**\n     * Returns the scalar product of two vectors\n     *\n     * @param {Object} a\n     * @param {Object} b\n     */\n    _getScalarProduct: function (a, b) {\n      return a.x * b.x + a.y * b.y;\n    },\n\n    /**\n     * Returns the magnitude of a vector_redrawCropperElements\n     * .\n     *\n     * @param {Object} vector\n     */\n    _getVectorMagnitude: function (vector) {\n      return Math.sqrt(vector.x * vector.x + vector.y * vector.y);\n    },\n\n    /**\n     * Returns the angle between two vectors in degrees with two decimal points\n     *\n     * @param {Object} a\n     * @param {Object} b\n     */\n    _getAngleBetweenVectors: function (a, b) {\n      return (\n        Math.round(\n          ((Math.acos(\n            Math.min(\n              1,\n              this._getScalarProduct(a, b) /\n                (this._getVectorMagnitude(a) * this._getVectorMagnitude(b))\n            )\n          ) *\n            180) /\n            Math.PI) *\n            100\n        ) / 100\n      );\n    },\n\n    /**\n     * Return the rectangle edge crossed by an imaginary line drawn from editor center to a vertex\n     *\n     * @param {Object} rectangle\n     * @param {Object} vertex\n     *\n     * @returns {*}\n     */\n    _getEdgeCrossed: function (rectangle, vertex) {\n      // Determine over which edge the vertex is\n      var edgePoints = [\n        [rectangle.a, rectangle.b],\n        [rectangle.b, rectangle.c],\n        [rectangle.c, rectangle.d],\n        [rectangle.d, rectangle.a],\n      ];\n\n      var centerPoint = {x: this.editorWidth / 2, y: this.editorHeight / 2};\n      var smallestDiff = 180;\n      var edgeCrossed = null;\n\n      // Test each edge\n      for (var edgeIndex = 0; edgeIndex < edgePoints.length; edgeIndex++) {\n        var edge = edgePoints[edgeIndex];\n        var toCenter = this._getVector(edge[0], centerPoint);\n        var edgeVector = this._getVector(edge[0], edge[1]);\n        var toVertex = this._getVector(edge[0], vertex);\n\n        // If the angle between toCenter/toVertex is the sum of\n        // angles between edgeVector/toCenter and edgeVector/toVertex, it means that\n        // the edgeVector is between the other two meaning that this is the offending vertex.\n        // To avoid the rounding errors, we'll take the closest match\n        var diff = Math.abs(\n          this._getAngleBetweenVectors(toCenter, toVertex) -\n            (this._getAngleBetweenVectors(toCenter, edgeVector) +\n              this._getAngleBetweenVectors(edgeVector, toVertex))\n        );\n\n        if (diff < smallestDiff) {\n          smallestDiff = diff;\n          edgeCrossed = edge;\n        }\n      }\n\n      return edgeCrossed;\n    },\n\n    /**\n     * Get the image bounding box by image scaled dimensions, taking ingo account the straightening angle.\n     *\n     * @param {Object} dimensions\n     */\n    _getImageBoundingBox: function (dimensions) {\n      var box = {};\n\n      var angleInRadians =\n        Math.abs(this.imageStraightenAngle) * (Math.PI / 180);\n\n      var proportion = dimensions.height / dimensions.width;\n      box.height =\n        dimensions.width *\n        (Math.sin(angleInRadians) + Math.cos(angleInRadians) * proportion);\n      box.width =\n        dimensions.width *\n        (Math.cos(angleInRadians) + Math.sin(angleInRadians) * proportion);\n\n      if (this.hasOrientationChanged()) {\n        var temp = box.width;\n        box.width = box.height;\n        box.height = temp;\n      }\n\n      return box;\n    },\n  },\n  {\n    defaults: {\n      animationDuration: 100,\n      allowSavingAsNew: true,\n      onSave: $.noop,\n      allowDegreeFractions: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset index class\n */\nCraft.AssetIndex = Craft.BaseElementIndex.extend(\n  {\n    $includeSubfoldersContainer: null,\n    $includeSubfoldersCheckbox: null,\n    showingIncludeSubfoldersCheckbox: false,\n\n    $uploadButton: null,\n    $uploadInput: null,\n    $progressBar: null,\n\n    uploader: null,\n    promptHandler: null,\n    progressBar: null,\n\n    $listedFolders: null,\n    itemDrag: null,\n\n    _uploadTotalFiles: 0,\n    _uploadFileProgress: {},\n    _currentUploaderSettings: {},\n\n    init: function (elementType, $container, settings) {\n      settings = Object.assign({}, Craft.AssetIndex.defaults, settings);\n      this.base(elementType, $container, settings);\n\n      if (this.settings.context === 'index') {\n        this.itemDrag = new Garnish.DragDrop({\n          activeDropTargetClass: 'sel',\n          minMouseDist: 10,\n          hideDraggee: false,\n          moveHelperToCursor: true,\n          activeDropTargetClass: 'active-drop-target',\n          handle: (item) => $(item).closest('tr,li'),\n          filter: () => {\n            const $container = this.itemDrag.$targetItem.closest('tr,li');\n            this.view.elementSelect.selectItem($container);\n            return this._findDraggableItems(this.view.getSelectedElements());\n          },\n          helper: ($item, index) =>\n            $('<div class=\"offset-drag-helper\"/>')\n              .append($item)\n              .css({\n                opacity: Math.max(0.9 - 0.05 * index, 0),\n                width: '',\n                height: '',\n              }),\n          dropTargets: () => {\n            // volume sources\n            let $dropTargets = $(\n              this.$visibleSources\n                .toArray()\n                .filter(\n                  (source) =>\n                    Garnish.hasAttr(source, 'data-folder-id') &&\n                    Garnish.hasAttr(source, 'data-can-move-peer-files-to')\n                )\n            );\n            if (this.sourcePath.length <= 1) {\n              // exclude the current source since we're already at the root of it\n              $dropTargets = $dropTargets.not(this.$source);\n            } else {\n              // parent folders in the source path\n              for (let i = 0; i < this.sourcePath.length - 1; i++) {\n                const step = this.sourcePath[i];\n                if (step.folderId) {\n                  $dropTargets = $dropTargets.add(step.$btn);\n                }\n              }\n            }\n            // folders in the elements listing\n            if (this.$listedFolders) {\n              $dropTargets = $dropTargets\n                .add(\n                  this.$listedFolders\n                    .filter('[data-folder-id]')\n                    .closest('tr,li')\n                )\n                .not(this.view.getSelectedElements());\n            }\n            return $dropTargets;\n          },\n          onDragStart: () => {\n            Garnish.$bod.addClass('dragging');\n            this.itemDrag.$draggee.closest('tr,li').addClass('draggee');\n          },\n          onDragStop: () => {\n            Garnish.$bod.removeClass('dragging');\n\n            const $draggee = this.itemDrag.$draggee;\n            const targetFolderId = this._targetFolderId(\n              this.itemDrag.$activeDropTarget\n            );\n\n            if (!targetFolderId) {\n              $draggee.closest('tr,li').removeClass('draggee');\n              this.itemDrag.returnHelpersToDraggees();\n              return;\n            }\n\n            this.itemDrag.fadeOutHelpers();\n\n            const $folders = $draggee.filter('[data-is-folder]');\n            const $assets = $draggee.not($folders);\n            const folderIds = $folders.toArray().map((item) => {\n              return parseInt($(item).data('folder-id'));\n            });\n            const assetIds = $assets.toArray().map((item) => {\n              return parseInt($(item).data('id'));\n            });\n\n            const mover = new Craft.AssetMover();\n            mover\n              .moveFolders(folderIds, targetFolderId)\n              .then((totalFoldersMoved) => {\n                mover\n                  .moveAssets(assetIds, targetFolderId)\n                  .then((totalAssetsMoved) => {\n                    const totalItemsMoved =\n                      totalFoldersMoved + totalAssetsMoved;\n                    if (totalItemsMoved) {\n                      Craft.cp.displayNotice(\n                        Craft.t(\n                          'app',\n                          '{totalItems, plural, =1{Item} other{Items}} moved.',\n                          {\n                            totalItems: totalItemsMoved,\n                          }\n                        )\n                      );\n                      Craft.elementIndex.updateElements(true);\n                    } else {\n                      $draggee.closest('tr,li').removeClass('draggee');\n                    }\n                  });\n              });\n          },\n        });\n\n        this.addListener(Garnish.$win, 'resize,scroll', '_positionProgressBar');\n      } else {\n        this.addListener(this.$main, 'scroll', '_positionProgressBar');\n\n        if (this.settings.modal) {\n          this.settings.modal.on(\n            'updateSizeAndPosition',\n            this._positionProgressBar.bind(this)\n          );\n        }\n      }\n    },\n\n    _findDraggableItems: function ($items) {\n      return $(\n        $items\n          .toArray()\n          .map((item) => $(item).find('.element:first')[0])\n          .filter((item) => item && Garnish.hasAttr(item, 'data-movable'))\n      );\n    },\n\n    _targetFolderId: function ($dropTarget) {\n      if (!$dropTarget || !$dropTarget.length) {\n        return false;\n      }\n\n      // source?\n      if ($dropTarget.is(this.$visibleSources)) {\n        return $dropTarget.data('folder-id');\n      }\n\n      // source path step?\n      for (let i = 0; i < this.sourcePath.length - 1; i++) {\n        const step = this.sourcePath[i];\n        if ($dropTarget.is(step.$btn)) {\n          return step.folderId;\n        }\n      }\n\n      // folder in the element listing?\n      return $dropTarget.find('.element:first').data('folder-id') || false;\n    },\n\n    afterInit: function () {\n      if (!this.settings.foldersOnly) {\n        this.initForFiles();\n      }\n\n      this.base();\n    },\n\n    /**\n     * Initialize the uploader.\n     *\n     * @private\n     */\n    initForFiles: function () {\n      if (!this.$uploadButton) {\n        this.$uploadButton = $('<button/>', {\n          type: 'button',\n          class: 'btn submit',\n          'data-icon': 'upload',\n          style: 'position: relative; overflow: hidden;',\n          text: Craft.t('app', 'Upload files'),\n        });\n        this.addButton(this.$uploadButton);\n\n        this.$uploadInput = $(\n          '<input type=\"file\" multiple=\"multiple\" name=\"assets-upload\" />'\n        )\n          .hide()\n          .insertBefore(this.$uploadButton);\n      }\n\n      this.promptHandler = new Craft.PromptHandler();\n      this.progressBar = new Craft.ProgressBar(this.$main, false);\n\n      var options = {\n        url: Craft.getActionUrl('assets/upload'),\n        fileInput: this.$uploadInput,\n        dropZone: this.$container,\n      };\n\n      options.events = {\n        fileuploadstart: this._onUploadStart.bind(this),\n        fileuploadprogressall: this._onUploadProgress.bind(this),\n        fileuploaddone: this._onUploadSuccess.bind(this),\n        fileuploadalways: this._onUploadAlways.bind(this),\n        fileuploadfail: this._onUploadFailure.bind(this),\n      };\n\n      if (\n        this.settings.criteria &&\n        typeof this.settings.criteria.kind !== 'undefined'\n      ) {\n        options.allowedKinds = this.settings.criteria.kind;\n      }\n\n      this._currentUploaderSettings = options;\n\n      this.uploader = new Craft.Uploader(this.$uploadButton, options);\n\n      this.$uploadButton.on('click', () => {\n        if (this.$uploadButton.hasClass('disabled')) {\n          return;\n        }\n        if (!this.isIndexBusy) {\n          this.$uploadButton\n            .parent()\n            .find('input[name=assets-upload]')\n            .trigger('click');\n        }\n      });\n    },\n\n    onSelectSource: function () {\n      if (!this.settings.foldersOnly) {\n        const folderId = this.$source.data('folder-id');\n        if (folderId && Garnish.hasAttr(this.$source, 'data-can-upload')) {\n          this.uploader.setParams({\n            folderId: this.$source.attr('data-folder-id'),\n          });\n          this.$uploadButton.removeClass('disabled');\n        } else {\n          this.$uploadButton.addClass('disabled');\n        }\n      }\n\n      this.base();\n    },\n\n    onSourcePathChange: function () {\n      if (!this.settings.foldersOnly && this.sourcePath.length) {\n        const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n        if (currentFolder.folderId) {\n          if (this.uploader) {\n            this.uploader.setParams({\n              folderId: currentFolder.folderId,\n            });\n          }\n\n          // will the user be allowed to move items in this folder?\n          const canMoveSubItems = !!currentFolder.canMoveSubItems;\n          this.settings.selectable =\n            this.settings.selectable || canMoveSubItems;\n          this.settings.multiSelect =\n            this.settings.multiSelect || canMoveSubItems;\n        }\n      }\n\n      this.base();\n    },\n\n    startSearching: function () {\n      // Does this source have subfolders?\n      if (\n        !this.settings.hideSidebar &&\n        this.sourcePath[this.sourcePath.length - 1].hasChildren\n      ) {\n        if (this.$includeSubfoldersContainer === null) {\n          var id =\n            'includeSubfolders-' + Math.floor(Math.random() * 1000000000);\n\n          this.$includeSubfoldersContainer = $(\n            '<div style=\"margin-bottom: -25px; opacity: 0;\"/>'\n          ).insertAfter(this.$search);\n          var $subContainer = $('<div style=\"padding-top: 5px;\"/>').appendTo(\n            this.$includeSubfoldersContainer\n          );\n          this.$includeSubfoldersCheckbox = $(\n            '<input type=\"checkbox\" id=\"' + id + '\" class=\"checkbox\"/>'\n          ).appendTo($subContainer);\n          $('<label class=\"light smalltext\" for=\"' + id + '\"/>')\n            .text(' ' + Craft.t('app', 'Search in subfolders'))\n            .appendTo($subContainer);\n\n          this.addListener(\n            this.$includeSubfoldersCheckbox,\n            'change',\n            function () {\n              this.setSelecetedSourceState(\n                'includeSubfolders',\n                this.$includeSubfoldersCheckbox.prop('checked')\n              );\n              this.updateElements();\n            }\n          );\n        } else {\n          this.$includeSubfoldersContainer\n            .velocity('stop')\n            .removeClass('hidden');\n        }\n\n        var checked = this.getSelectedSourceState('includeSubfolders', false);\n        this.$includeSubfoldersCheckbox.prop('checked', checked);\n\n        this.$includeSubfoldersContainer.velocity(\n          {\n            marginBottom: 0,\n            opacity: 1,\n          },\n          'fast'\n        );\n\n        this.showingIncludeSubfoldersCheckbox = true;\n      }\n\n      this.base();\n    },\n\n    stopSearching: function () {\n      if (this.showingIncludeSubfoldersCheckbox) {\n        this.$includeSubfoldersContainer.velocity('stop');\n\n        this.$includeSubfoldersContainer.velocity(\n          {\n            marginBottom: -25,\n            opacity: 0,\n          },\n          {\n            duration: 'fast',\n            complete: () => {\n              this.$includeSubfoldersContainer.addClass('hidden');\n            },\n          }\n        );\n\n        this.showingIncludeSubfoldersCheckbox = false;\n      }\n\n      this.base();\n    },\n\n    getViewSettings: function () {\n      const settings = {};\n\n      if (this.settings.context === 'index') {\n        // Allow folders to be selected\n        settings.canSelectElement = () => true;\n      }\n\n      return settings;\n    },\n\n    getViewParams: function () {\n      const data = Object.assign(this.base(), {\n        showFolders: this.settings.showFolders && !this.trashed,\n        foldersOnly: this.settings.foldersOnly,\n      });\n\n      if (\n        this.showingIncludeSubfoldersCheckbox &&\n        this.$includeSubfoldersCheckbox.prop('checked')\n      ) {\n        data.criteria.includeSubfolders = true;\n      }\n\n      return data;\n    },\n\n    /**\n     * React on upload submit.\n     *\n     * @private\n     */\n    _onUploadStart: function () {\n      this.setIndexBusy();\n\n      // Initial values\n      this._positionProgressBar();\n      this.progressBar.resetProgressBar();\n      this.progressBar.showProgressBar();\n\n      this.promptHandler.resetPrompts();\n    },\n\n    /**\n     * Update uploaded byte count.\n     */\n    _onUploadProgress: function (event, data) {\n      var progress = parseInt((data.loaded / data.total) * 100, 10);\n      this.progressBar.setProgressPercentage(progress);\n    },\n\n    /**\n     * On upload success.\n     *\n     * @param {Object} event\n     * @param {Object} data\n     * @private\n     */\n    _onUploadSuccess: function (event, data) {\n      const {result} = data;\n\n      // Add the uploaded file to the selected ones, if appropriate\n      this.selectElementAfterUpdate(result.assetId);\n\n      // If there is a prompt, add it to the queue\n      if (result.conflict) {\n        result.prompt = {\n          message: Craft.t('app', result.conflict, {file: result.filename}),\n          choices: [\n            {value: 'keepBoth', title: Craft.t('app', 'Keep both')},\n            {value: 'replace', title: Craft.t('app', 'Replace it')},\n          ],\n        };\n\n        this.promptHandler.addPrompt(result);\n      }\n\n      Craft.cp.runQueue();\n    },\n\n    /**\n     * On upload complete no matter what (success, fail, or abort).\n     */\n    _onUploadAlways: function () {\n      if (this.uploader.isLastUpload()) {\n        this.progressBar.hideProgressBar();\n        this.setIndexAvailable();\n\n        if (this.promptHandler.getPromptCount()) {\n          this.promptHandler.showBatchPrompts(this._uploadFollowup.bind(this));\n        } else {\n          this._updateAfterUpload();\n        }\n      }\n    },\n\n    /**\n     * On Upload Failure.\n     */\n    _onUploadFailure: function (event, data) {\n      const response = data.response();\n      let {message, filename} = response?.jqXHR?.responseJSON || {};\n\n      if (!message) {\n        message = filename\n          ? Craft.t('app', 'Upload failed for “{filename}”.', {filename})\n          : Craft.t('app', 'Upload failed.');\n      }\n\n      Craft.cp.displayError(message);\n    },\n\n    /**\n     * Update the elements after an upload, setting sort to dateModified descending, if not using index.\n     *\n     * @private\n     */\n    _updateAfterUpload: function () {\n      if (this.settings.context !== 'index') {\n        this.clearSearch();\n        this.setSelectedSortAttribute('dateCreated', 'desc');\n      }\n      this.updateElements();\n    },\n\n    /**\n     * Follow up to an upload that triggered at least one conflict resolution prompt.\n     *\n     * @param {Object} returnData\n     * @private\n     */\n    _uploadFollowup: function (returnData) {\n      this.setIndexBusy();\n      this.progressBar.resetProgressBar();\n\n      this.promptHandler.resetPrompts();\n\n      var finalCallback = () => {\n        this.progressBar.hideProgressBar();\n        this.setIndexAvailable();\n        this._updateAfterUpload();\n      };\n\n      this.progressBar.setItemCount(returnData.length);\n\n      var doFollowup = (parameterArray, parameterIndex, callback) => {\n        var data = {};\n        var action = null;\n\n        const followupAlways = () => {\n          parameterIndex++;\n          this.progressBar.incrementProcessedItemCount(1);\n          this.progressBar.updateProgressBar();\n\n          if (parameterIndex === parameterArray.length) {\n            callback();\n          } else {\n            doFollowup(parameterArray, parameterIndex, callback);\n          }\n        };\n        const followupSuccess = (data) => {\n          if (data.assetId) {\n            this.selectElementAfterUpdate(data.assetId);\n          }\n\n          followupAlways();\n        };\n        const followupFailure = (data) => {\n          Craft.cp.displayError(data.message);\n          followupAlways();\n        };\n\n        if (parameterArray[parameterIndex].choice === 'replace') {\n          action = 'assets/replace-file';\n          data.sourceAssetId = parameterArray[parameterIndex].assetId;\n\n          if (parameterArray[parameterIndex].conflictingAssetId) {\n            data.assetId = parameterArray[parameterIndex].conflictingAssetId;\n          } else {\n            data.targetFilename = parameterArray[parameterIndex].filename;\n          }\n        } else if (parameterArray[parameterIndex].choice === 'cancel') {\n          action = 'assets/delete-asset';\n          data.assetId = parameterArray[parameterIndex].assetId;\n        }\n\n        if (!action) {\n          // We don't really need to do another request, so let's pretend that already happened\n          followupSuccess({\n            assetId: parameterArray[parameterIndex].assetId,\n          });\n        } else {\n          Craft.sendActionRequest('POST', action, {data})\n            .then((response) => followupSuccess(response.data))\n            .catch(({response}) => followupFailure(response.data));\n        }\n      };\n\n      this.progressBar.showProgressBar();\n      doFollowup(returnData, 0, finalCallback);\n    },\n\n    /**\n     * Perform actions after updating elements\n     * @private\n     */\n    onUpdateElements: function () {\n      this._onUpdateElements(false, this.view.getAllElements());\n      this.view.on('appendElements', (ev) => {\n        this._onUpdateElements(true, ev.newElements);\n      });\n\n      this.base();\n    },\n\n    /**\n     * Do the after-update initializations\n     * @private\n     */\n    _onUpdateElements: function (append, $newElements) {\n      this.removeListener(this.$elements, 'keydown');\n      this.addListener(this.$elements, 'keydown', this._onKeyDown.bind(this));\n      this.view.elementSelect.on('focusItem', this._onElementFocus.bind(this));\n\n      this.$listedFolders = $newElements.find(\n        '.element[data-is-folder][data-folder-name]'\n      );\n      for (let i = 0; i < this.$listedFolders.length; i++) {\n        const $folder = this.$listedFolders.eq(i);\n        const $label = $folder.find('.label');\n        const $title = $label.find('.title');\n        const folderId = parseInt($folder.data('folder-id'));\n        const folderName = $folder.data('folder-name');\n        const label = Craft.t('app', '{name} folder', {\n          name: folderName,\n        });\n        if (this.settings.disabledFolderIds.includes(folderId)) {\n          $label.attr('aria-label', label);\n          $newElements.has($folder).addClass('disabled');\n          continue;\n        }\n        const sourcePath = $folder.data('source-path');\n        if (sourcePath) {\n          const $a = $('<a/>', {\n            href: Craft.getCpUrl(sourcePath[sourcePath.length - 1].uri),\n            html: $title.html(),\n            role: 'button',\n            'aria-label': label,\n          });\n          $label.empty().append($a);\n          this.addListener($a, 'activate', (ev) => {\n            this.sourcePath = sourcePath;\n            this.clearSearch(false);\n            this.updateElements().then(() => {\n              const firstFocusableEl = this.$elements.find(\n                ':focusable:not(.selectallcontainer)'\n              )[0];\n              if (firstFocusableEl) {\n                firstFocusableEl.focus();\n              }\n            });\n          });\n        }\n      }\n\n      if (this.itemDrag) {\n        const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n        const canMoveSubItems = !!(\n          currentFolder &&\n          currentFolder.folderId &&\n          currentFolder.canMoveSubItems\n        );\n        if (!canMoveSubItems || !append) {\n          this.itemDrag.removeAllItems();\n        }\n        if (canMoveSubItems) {\n          this.itemDrag.addItems(this._findDraggableItems($newElements));\n        }\n      }\n    },\n\n    /**\n     * Handle a keypress\n     * @private\n     */\n    _onKeyDown: function (ev) {\n      if (ev.keyCode === Garnish.SPACE_KEY && ev.shiftKey) {\n        if (Craft.PreviewFileModal.openInstance) {\n          Craft.PreviewFileModal.openInstance.selfDestruct();\n        } else {\n          var $element = this.view.elementSelect.$focusedItem.find('.element');\n\n          if ($element.length) {\n            this._loadPreview($element);\n          }\n        }\n\n        ev.stopPropagation();\n        return false;\n      }\n    },\n\n    /**\n     * Handle element being focused\n     * @private\n     */\n    _onElementFocus: function (ev) {\n      var $element = $(ev.item).find('.element');\n\n      if (Craft.PreviewFileModal.openInstance && $element.length) {\n        this._loadPreview($element);\n      }\n    },\n\n    /**\n     * Load the preview for an asset\n     * @private\n     */\n    _loadPreview: function ($element) {\n      var settings = {};\n\n      if ($element.data('image-width')) {\n        settings.startingWidth = $element.data('image-width');\n        settings.startingHeight = $element.data('image-height');\n      }\n\n      new Craft.PreviewFileModal(\n        $element.data('id'),\n        this.view.elementSelect,\n        settings\n      );\n    },\n\n    /**\n     * @returns {string}\n     */\n    getSourcePathLabel: function () {\n      return Craft.t('app', 'Volume path');\n    },\n\n    /**\n     * @returns {string}\n     */\n    getSourcePathActionLabel: function () {\n      return Craft.t('app', 'Folder actions');\n    },\n\n    getSourcePathActions: function () {\n      const actions = [];\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n\n      if (currentFolder.canCreate) {\n        actions.push({\n          label: Craft.t('app', 'New subfolder'),\n          onSelect: () => {\n            this._createSubfolder();\n          },\n        });\n      }\n\n      if (this.settings.context === 'index') {\n        if (currentFolder.canRename) {\n          actions.push({\n            label: Craft.t('app', 'Rename folder'),\n            onSelect: () => {\n              this._renameFolder();\n            },\n          });\n\n          if (\n            currentFolder.canMove &&\n            this.getMoveTargetSourceKeys(true).length\n          ) {\n            actions.push({\n              label: Craft.t('app', 'Move folder'),\n              onSelect: () => {\n                this._moveFolder();\n              },\n            });\n          }\n\n          if (currentFolder.canDelete) {\n            actions.push({\n              label: Craft.t('app', 'Delete folder'),\n              destructive: true,\n              onSelect: () => {\n                this._deleteFolder();\n              },\n            });\n          }\n        }\n      }\n\n      return actions;\n    },\n\n    _createSubfolder: function () {\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n      const subfolderName = prompt(\n        Craft.t('app', 'Enter the name of the folder')\n      );\n\n      if (subfolderName) {\n        const data = {\n          parentId: currentFolder.folderId,\n          folderName: subfolderName,\n        };\n\n        this.setIndexBusy();\n\n        Craft.sendActionRequest('POST', 'assets/create-folder', {data})\n          .then((response) => {\n            this.setIndexAvailable();\n            Craft.cp.displayNotice(Craft.t('app', 'Folder created.'));\n            this.updateElements(true);\n          })\n          .catch(({response}) => {\n            this.setIndexAvailable();\n            Craft.cp.displayError(response.data.message);\n          });\n      }\n    },\n\n    _deleteFolder: function () {\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n\n      if (\n        confirm(\n          Craft.t('app', 'Really delete folder “{folder}”?', {\n            folder: currentFolder.label,\n          })\n        )\n      ) {\n        const data = {\n          folderId: currentFolder.folderId,\n        };\n\n        this.setIndexBusy();\n\n        Craft.sendActionRequest('POST', 'assets/delete-folder', {data})\n          .then((response) => {\n            this.setIndexAvailable();\n            Craft.cp.displayNotice(Craft.t('app', 'Folder deleted.'));\n            this.sourcePath = this.sourcePath.slice(\n              0,\n              this.sourcePath.length - 1\n            );\n            this.updateElements();\n          })\n          .catch(({response}) => {\n            this.setIndexAvailable();\n            Craft.cp.displayError(response.data.message);\n          });\n      }\n    },\n\n    /**\n     * Rename\n     */\n    _renameFolder: function () {\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n      const newName = prompt(\n        Craft.t('app', 'Rename folder'),\n        currentFolder.label\n      );\n\n      if (!newName || newName === currentFolder.label) {\n        return;\n      }\n\n      this.setIndexBusy();\n\n      Craft.sendActionRequest('POST', 'assets/rename-folder', {\n        data: {\n          folderId: currentFolder.folderId,\n          newName: newName,\n        },\n      })\n        .then((response) => {\n          Craft.cp.displayNotice(Craft.t('app', 'Folder renamed.'));\n          const sourcePath = this.sourcePath.slice();\n          sourcePath[sourcePath.length - 1].label = response.data.newName;\n          sourcePath[sourcePath.length - 1].uri =\n            sourcePath[sourcePath.length - 2].uri + `/${response.data.newName}`;\n          this.sourcePath = sourcePath;\n        })\n        .catch(({response}) => {\n          Craft.cp.displayError(response.data.message);\n        })\n        .finally(() => {\n          this.setIndexAvailable();\n        });\n    },\n\n    getMoveTargetSourceKeys: function (peerFiles) {\n      const attr = peerFiles\n        ? 'data-can-move-peer-files-to'\n        : 'data-can-move-to';\n      return this.$sources\n        .toArray()\n        .filter((source) => {\n          const volumeHandle = $(source).data('volume-handle');\n          return (\n            volumeHandle &&\n            volumeHandle !== 'temp' &&\n            Garnish.hasAttr(source, attr)\n          );\n        })\n        .map((source) => $(source).data('key'));\n    },\n\n    _moveFolder: function () {\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n      const parentFolder = this.sourcePath[this.sourcePath.length - 2];\n\n      const disabledFolderIds = [currentFolder.folderId];\n      if (parentFolder) {\n        disabledFolderIds.push(parentFolder.folderId);\n      }\n\n      new Craft.VolumeFolderSelectorModal({\n        sources: this.getMoveTargetSourceKeys(true),\n        showTitle: true,\n        modalTitle: Craft.t('app', 'Move to'),\n        selectBtnLabel: Craft.t('app', 'Move'),\n        disabledFolderIds: disabledFolderIds,\n        indexSettings: {\n          defaultSource: this.sourceKey,\n          defaultSourcePath: this.sourcePath.slice(\n            0,\n            this.sourcePath.length - 1\n          ),\n        },\n        onSelect: ([targetFolder]) => {\n          this.$sourcePathActionsBtn.focus();\n          const mover = new Craft.AssetMover();\n          mover\n            .moveFolders([currentFolder.folderId], targetFolder.folderId)\n            .then((totalFoldersMoved) => {\n              if (totalFoldersMoved) {\n                Craft.cp.displayNotice(\n                  Craft.t(\n                    'app',\n                    '{totalItems, plural, =1{Item} other{Items}} moved.',\n                    {\n                      totalItems: totalFoldersMoved,\n                    }\n                  )\n                );\n                this.sourcePath = this.sourcePath.slice(\n                  0,\n                  this.sourcePath.length - 1\n                );\n                this.clearSearch(false);\n                this.updateElements();\n              }\n            });\n        },\n      });\n    },\n\n    _positionProgressBar: function () {\n      if (!this.progressBar) {\n        this.progressBar = new Craft.ProgressBar(this.$main, true);\n      }\n\n      var $container = $(),\n        scrollTop = 0,\n        offset = 0;\n\n      if (this.settings.context === 'index') {\n        $container = this.progressBar.$progressBar.closest('#content');\n        scrollTop = Garnish.$win.scrollTop();\n      } else {\n        $container = this.progressBar.$progressBar.closest('.main');\n        scrollTop = this.$main.scrollTop();\n      }\n\n      var containerTop = $container.offset().top;\n      var diff = scrollTop - containerTop;\n      var windowHeight = Garnish.$win.height();\n\n      if ($container.height() > windowHeight) {\n        offset = windowHeight / 2 - 6 + diff;\n      } else {\n        offset = $container.height() / 2 - 6;\n      }\n\n      if (this.settings.context !== 'index') {\n        offset = scrollTop + ($container.height() / 2 - 6);\n      }\n\n      this.progressBar.$progressBar.css({\n        top: offset,\n      });\n    },\n  },\n  {\n    defaults: {\n      showFolders: true,\n      foldersOnly: false,\n      disabledFolderIds: [],\n    },\n  }\n);\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\Asset', Craft.AssetIndex);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset mover class\n */\nCraft.AssetMover = Garnish.Base.extend({\n  moveAssets: function (assetIds, targetFolderId) {\n    const requests = assetIds.map((assetId) => {\n      return {\n        for: 'asset',\n        action: 'assets/move-asset',\n        params: {\n          assetId,\n          folderId: targetFolderId,\n        },\n      };\n    });\n    return this._batchMoveRequests(requests, {\n      conflictChoices: [\n        {\n          value: 'keepBoth',\n          title: Craft.t('app', 'Keep both'),\n        },\n        {\n          value: 'replace',\n          title: Craft.t('app', 'Replace it'),\n        },\n      ],\n      handleConflictChoice: function (prompt) {\n        const params = {\n          folderId: prompt.request.params.folderId,\n          assetId: prompt.assetId,\n        };\n        switch (prompt.choice) {\n          case 'replace':\n            params.force = true;\n            break;\n          case 'keepBoth':\n            params.filename = prompt.suggestedFilename;\n            break;\n        }\n        return {\n          action: 'assets/move-asset',\n          params,\n        };\n      },\n    });\n  },\n\n  moveFolders: function (folderIds, targetFolderId) {\n    return new Promise((resolve, reject) => {\n      const transferList = [];\n      const folderIdsToDelete = [];\n\n      const requests = folderIds.map((folderId) => {\n        return {\n          for: 'folder',\n          action: 'assets/move-folder',\n          params: {\n            folderId,\n            parentId: targetFolderId,\n          },\n          onSuccess: (response) => {\n            if (response.transferList.length) {\n              transferList.push(...response.transferList);\n            }\n            folderIdsToDelete.push(folderId);\n          },\n        };\n      });\n\n      this._batchMoveRequests(requests, {\n        conflictChoices: [\n          {\n            value: 'replace',\n            title: Craft.t(\n              'app',\n              'Replace the folder (all existing files will be deleted)'\n            ),\n          },\n          {\n            value: 'merge',\n            title: Craft.t(\n              'app',\n              'Merge the folder (any conflicting files will be replaced)'\n            ),\n          },\n        ],\n        handleConflictChoice: function (prompt) {\n          const params = {\n            folderId: prompt.folderId,\n            parentId: prompt.parentId,\n          };\n          switch (prompt.choice) {\n            case 'replace':\n              params.force = true;\n              break;\n            case 'merge':\n              params.merge = true;\n              break;\n          }\n          return {\n            action: 'assets/move-folder',\n            params,\n          };\n        },\n      })\n        .then((totalMoved) => {\n          this._processTransferList(transferList).then(() => {\n            this._deleteFolders(folderIdsToDelete).then(() => {\n              resolve(totalMoved);\n            });\n          });\n        })\n        .catch(reject);\n    });\n  },\n\n  _processTransferList: function (transferList) {\n    return this._batchRequests(\n      transferList.map((params) => {\n        return {\n          action: 'assets/move-asset',\n          params,\n        };\n      })\n    );\n  },\n\n  _deleteFolders: function (folderIds) {\n    return this._batchRequests(\n      folderIds.map((folderId) => {\n        return {\n          action: 'assets/delete-folder',\n          params: {folderId},\n        };\n      })\n    );\n  },\n\n  _batchMoveRequests: function (requests, settings) {\n    return new Promise((resolve) => {\n      let totalMoved = 0;\n\n      this._batchRequests(requests).then((responses) => {\n        Craft.elementIndex.promptHandler.resetPrompts();\n\n        // Loop through all the responses\n        for (const response of responses) {\n          if (response.success) {\n            totalMoved++;\n          }\n\n          // Push prompt into prompt array\n          if (response.conflict) {\n            Craft.elementIndex.promptHandler.addPrompt(\n              Object.assign({}, response, {\n                prompt: {\n                  message: response.conflict,\n                  choices: settings.conflictChoices,\n                },\n              })\n            );\n          }\n\n          if (response.error) {\n            Craft.cp.displayError(response.error);\n          }\n        }\n\n        if (!Craft.elementIndex.promptHandler.getPromptCount()) {\n          resolve(totalMoved);\n          return;\n        }\n\n        Craft.elementIndex.promptHandler.showBatchPrompts((prompts) => {\n          Craft.elementIndex.promptHandler.resetPrompts();\n          const nextRequests = [];\n          for (const prompt of prompts) {\n            if (prompt.choice === 'cancel') {\n              continue;\n            }\n            if (settings.handleConflictChoice) {\n              const nextRequest = settings.handleConflictChoice(prompt);\n              if (prompt.request && prompt.request.onSuccess) {\n                nextRequest.onSuccess = prompt.request.onSuccess;\n              }\n              nextRequests.push(nextRequest);\n            }\n          }\n          this._batchMoveRequests(nextRequests, settings).then(\n            (nextTotalMoved) => {\n              resolve(totalMoved + nextTotalMoved);\n            }\n          );\n        });\n      });\n    });\n  },\n\n  _batchRequests: function (requests) {\n    return new Promise((resolve) => {\n      if (!requests.length) {\n        resolve([]);\n        return;\n      }\n\n      Craft.elementIndex.setIndexBusy();\n      Craft.elementIndex._positionProgressBar();\n      Craft.elementIndex.progressBar.resetProgressBar();\n      Craft.elementIndex.progressBar.setItemCount(requests.length);\n      Craft.elementIndex.progressBar.showProgressBar();\n\n      const responses = [];\n      let activeRequests = requests.length;\n\n      for (const request of requests) {\n        Craft.sendActionRequest('POST', request.action, {\n          data: request.params,\n        })\n          .then((response) => {\n            responses.push(Object.assign({}, response.data, {request}));\n            if (response.data.success && request.onSuccess) {\n              request.onSuccess(response.data);\n            }\n          })\n          .catch((failure) => {\n            if (failure.response && failure.response.data) {\n              responses.push(\n                Object.assign({}, failure.response.data, {request})\n              );\n            }\n          })\n          .finally(() => {\n            // Was that the last one?\n            if (--activeRequests === 0) {\n              Craft.elementIndex.setIndexAvailable();\n              Craft.elementIndex.progressBar.hideProgressBar();\n              // If assets were just merged we should get the reference tags updated right away\n              Craft.cp.runQueue();\n              resolve(responses);\n            } else {\n              Craft.elementIndex.progressBar.incrementProcessedItemCount(1);\n              Craft.elementIndex.progressBar.updateProgressBar();\n            }\n          });\n      }\n    });\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset select input\n */\nCraft.AssetSelectInput = Craft.BaseElementSelectInput.extend({\n  $uploadBtn: null,\n  uploader: null,\n  progressBar: null,\n  openPreviewTimeout: null,\n\n  init: function () {\n    this.base.apply(this, arguments);\n\n    if (this.settings.canUpload) {\n      this._attachUploader();\n    }\n\n    this.updateAddElementsBtn();\n\n    this.addListener(\n      this.$elementsContainer,\n      'keydown',\n      this._onKeyDown.bind(this)\n    );\n    this.elementSelect.on('focusItem', this._onElementFocus.bind(this));\n  },\n\n  /**\n   * Handle a keypress\n   * @private\n   */\n  _onKeyDown: function (ev) {\n    if (ev.keyCode === Garnish.SPACE_KEY && ev.shiftKey) {\n      this.openPreview();\n      ev.stopPropagation();\n      return false;\n    }\n  },\n\n  onAddElements: function () {\n    this.$elements\n      .find('.elementthumb')\n      .addClass('open-preview')\n      .on('click', (ev) => {\n        this.clearOpenPreviewTimeout();\n        this.openPreviewTimeout = setTimeout(() => {\n          this.openPreview();\n          this.openPreviewTimeout = null;\n        }, 500);\n      })\n      .on('dblclick', (ev) => {\n        this.clearOpenPreviewTimeout();\n      });\n    this.base();\n  },\n\n  clearOpenPreviewTimeout: function () {\n    if (this.openPreviewTimeout) {\n      clearTimeout(this.openPreviewTimeout);\n      this.openPreviewTimeout = null;\n    }\n  },\n\n  openPreview: function () {\n    if (Craft.PreviewFileModal.openInstance) {\n      Craft.PreviewFileModal.openInstance.selfDestruct();\n    } else {\n      var $element = this.elementSelect.$focusedItem;\n\n      if ($element.length) {\n        this._loadPreview($element);\n      }\n    }\n  },\n\n  /**\n   * Handle element being focused\n   * @private\n   */\n  _onElementFocus: function (ev) {\n    var $element = $(ev.item);\n\n    if (Craft.PreviewFileModal.openInstance && $element.length) {\n      this._loadPreview($element);\n    }\n  },\n\n  /**\n   * Load the preview for an asset\n   * @private\n   */\n  _loadPreview: function ($element) {\n    var settings = {\n      minGutter: 50,\n    };\n\n    if ($element.data('image-width')) {\n      settings.startingWidth = $element.data('image-width');\n      settings.startingHeight = $element.data('image-height');\n    }\n\n    new Craft.PreviewFileModal(\n      $element.data('id'),\n      this.elementSelect,\n      settings\n    );\n  },\n\n  /**\n   * Attach the uploader with drag event handler\n   */\n  _attachUploader: function () {\n    this.progressBar = new Craft.ProgressBar(\n      $('<div class=\"progress-shade\"></div>').appendTo(this.$container)\n    );\n\n    var options = {\n      url: Craft.getActionUrl('assets/upload'),\n      dropZone: this.$container,\n      formData: {\n        fieldId: this.settings.fieldId,\n      },\n    };\n\n    if (this.settings.sourceElementId) {\n      options.formData.elementId = this.settings.sourceElementId;\n    }\n\n    if (this.settings.criteria.siteId) {\n      options.formData.siteId = this.settings.criteria.siteId;\n    }\n\n    if (this.$addElementBtn) {\n      this.$uploadBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn dashed',\n        'data-icon': 'upload',\n        'aria-label':\n          this.settings.limit == 1\n            ? Craft.t('app', 'Upload a file')\n            : Craft.t('app', 'Upload files'),\n        'aria-describedby': this.settings.describedBy,\n        text:\n          this.settings.limit == 1\n            ? Craft.t('app', 'Upload a file')\n            : Craft.t('app', 'Upload files'),\n      }).insertAfter(this.$addElementBtn);\n      options.fileInput = $('<input/>', {\n        type: 'file',\n        class: 'hidden',\n        multiple: this.settings.limit != 1,\n      }).insertAfter(this.$uploadBtn);\n\n      // Trigger a window resize in case the field is inside an element editor HUD\n      Garnish.$win.trigger('resize');\n    }\n\n    // If CSRF protection isn't enabled, these won't be defined.\n    if (\n      typeof Craft.csrfTokenName !== 'undefined' &&\n      typeof Craft.csrfTokenValue !== 'undefined'\n    ) {\n      // Add the CSRF token\n      options.formData[Craft.csrfTokenName] = Craft.csrfTokenValue;\n    }\n\n    if (typeof this.settings.criteria.kind !== 'undefined') {\n      options.allowedKinds = this.settings.criteria.kind;\n    }\n\n    options.canAddMoreFiles = this.canAddMoreFiles.bind(this);\n\n    options.events = {};\n    options.events.fileuploadstart = this._onUploadStart.bind(this);\n    options.events.fileuploadprogressall = this._onUploadProgress.bind(this);\n    options.events.fileuploaddone = this._onUploadComplete.bind(this);\n    options.events.fileuploadfail = this._onUploadFailure.bind(this);\n\n    this.uploader = new Craft.Uploader(this.$container, options);\n\n    if (this.$uploadBtn) {\n      this.$uploadBtn.on('click', (ev) => {\n        // We can't store a reference to the file input, because it gets replaced with a new input\n        // each time a new file is uploaded - see https://stackoverflow.com/a/25034721/1688568\n        this.$uploadBtn.next('input[type=file]').trigger('click');\n      });\n    }\n  },\n\n  enableAddElementsBtn: function () {\n    if (this.$uploadBtn) {\n      this.$uploadBtn.removeClass('hidden');\n    }\n\n    this.base();\n  },\n\n  disableAddElementsBtn: function () {\n    if (this.$uploadBtn) {\n      this.$uploadBtn.addClass('hidden');\n    }\n\n    this.base();\n  },\n\n  /**\n   * Add the freshly uploaded file to the input field.\n   */\n  selectUploadedFile: function (element) {\n    // Check if we're able to add new elements\n    if (!this.canAddMoreElements()) {\n      return;\n    }\n\n    var $newElement = element.$element;\n\n    // Make a couple tweaks\n    $newElement.addClass('removable');\n    $newElement.prepend(\n      '<input type=\"hidden\" name=\"' +\n        this.settings.name +\n        '[]\" value=\"' +\n        element.id +\n        '\">' +\n        '<a class=\"delete icon\" title=\"' +\n        Craft.t('app', 'Remove') +\n        '\"></a>'\n    );\n\n    $newElement.appendTo(this.$elementsContainer);\n\n    var margin = -($newElement.outerWidth() + 10);\n\n    this.$addElementBtn.css('margin-' + Craft.left, margin + 'px');\n\n    var animateCss = {};\n    animateCss['margin-' + Craft.left] = 0;\n    this.$addElementBtn.velocity(animateCss, 'fast');\n\n    this.addElements($newElement);\n\n    delete this.modal;\n  },\n\n  /**\n   * On upload start.\n   */\n  _onUploadStart: function () {\n    this.progressBar.$progressBar.css({\n      top: Math.round(this.$container.outerHeight() / 2) - 6,\n    });\n\n    this.$container.addClass('uploading');\n    this.progressBar.resetProgressBar();\n    this.progressBar.showProgressBar();\n  },\n\n  /**\n   * On upload progress.\n   */\n  _onUploadProgress: function (event, data) {\n    var progress = parseInt((data.loaded / data.total) * 100, 10);\n    this.progressBar.setProgressPercentage(progress);\n  },\n\n  /**\n   * On a file being uploaded.\n   */\n  _onUploadComplete: function (event, data) {\n    if (data.result.error) {\n      Craft.cp.displayError(data.result.error);\n      this.progressBar.hideProgressBar();\n      this.$container.removeClass('uploading');\n    } else {\n      var parameters = {\n        elementId: data.result.assetId,\n        siteId: this.settings.criteria.siteId,\n        thumbSize: this.settings.viewMode,\n      };\n\n      Craft.sendActionRequest('POST', 'elements/get-element-html', {\n        data: parameters,\n      })\n        .then((response) => {\n          var html = $(response.data.html);\n          Craft.appendHeadHtml(response.data.headHtml);\n          this.selectUploadedFile(Craft.getElementInfo(html));\n\n          // Last file\n          if (this.uploader.isLastUpload()) {\n            this.progressBar.hideProgressBar();\n            this.$container.removeClass('uploading');\n            this.$container.trigger('change');\n          }\n        })\n        .catch(({response}) => {\n          Craft.cp.displayError(response.data.message);\n        });\n\n      Craft.cp.runQueue();\n    }\n  },\n\n  /**\n   * On Upload Failure.\n   */\n  _onUploadFailure: function (event, data) {\n    const response = data.response();\n    let {message, filename} = response?.jqXHR?.responseJSON || {};\n\n    if (!message) {\n      message = filename\n        ? Craft.t('app', 'Upload failed for “{filename}”.', {filename})\n        : Craft.t('app', 'Upload failed.');\n    }\n\n    Craft.cp.displayError(message);\n    this.progressBar.hideProgressBar();\n    this.$container.removeClass('uploading');\n  },\n\n  /**\n   * We have to take into account files about to be added as well\n   */\n  canAddMoreFiles: function (slotsTaken) {\n    return (\n      !this.settings.limit ||\n      this.$elements.length + slotsTaken < this.settings.limit\n    );\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset selector modal class\n */\nCraft.AssetSelectorModal = Craft.BaseElementSelectorModal.extend(\n  {\n    $selectTransformBtn: null,\n    _selectedTransform: null,\n\n    init: function (elementType, settings) {\n      settings = $.extend({}, Craft.AssetSelectorModal.defaults, settings);\n\n      this.base(elementType, settings);\n\n      if (settings.transforms.length) {\n        this.createSelectTransformButton(settings.transforms);\n      }\n    },\n\n    createSelectTransformButton: function (transforms) {\n      if (!transforms || !transforms.length) {\n        return;\n      }\n\n      var $btnGroup = $('<div class=\"btngroup\"/>').appendTo(\n        this.$primaryButtons\n      );\n      this.$selectBtn.appendTo($btnGroup);\n\n      this.$selectTransformBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn menubtn disabled',\n        text: Craft.t('app', 'Select transform'),\n      }).appendTo($btnGroup);\n\n      var $menu = $('<div class=\"menu\" data-align=\"right\"></div>').insertAfter(\n          this.$selectTransformBtn\n        ),\n        $menuList = $('<ul></ul>').appendTo($menu);\n\n      for (var i = 0; i < transforms.length; i++) {\n        $(\n          '<li><a data-transform=\"' +\n            transforms[i].handle +\n            '\">' +\n            transforms[i].name +\n            '</a></li>'\n        ).appendTo($menuList);\n      }\n\n      var MenuButton = new Garnish.MenuBtn(this.$selectTransformBtn, {\n        onOptionSelect: this.onSelectTransform.bind(this),\n      });\n      MenuButton.disable();\n\n      this.$selectTransformBtn.data('menuButton', MenuButton);\n    },\n\n    onSelectionChange: function (ev) {\n      var $selectedElements = this.elementIndex.getSelectedElements(),\n        allowTransforms = false;\n\n      if ($selectedElements.length && this.settings.transforms.length) {\n        allowTransforms = true;\n\n        for (var i = 0; i < $selectedElements.length; i++) {\n          if (!$('.element.hasthumb:first', $selectedElements[i]).length) {\n            break;\n          }\n        }\n      }\n\n      var MenuBtn = null;\n\n      if (this.$selectTransformBtn) {\n        MenuBtn = this.$selectTransformBtn.data('menuButton');\n      }\n\n      if (allowTransforms) {\n        if (MenuBtn) {\n          MenuBtn.enable();\n        }\n\n        this.$selectTransformBtn.removeClass('disabled');\n      } else if (this.$selectTransformBtn) {\n        if (MenuBtn) {\n          MenuBtn.disable();\n        }\n\n        this.$selectTransformBtn.addClass('disabled');\n      }\n\n      this.base();\n    },\n\n    onSelectTransform: function (option) {\n      var transform = $(option).data('transform');\n      this.selectImagesWithTransform(transform);\n    },\n\n    selectImagesWithTransform: function (transform) {\n      // First we must get any missing transform URLs\n      if (\n        typeof Craft.AssetSelectorModal.transformUrls[transform] === 'undefined'\n      ) {\n        Craft.AssetSelectorModal.transformUrls[transform] = {};\n      }\n\n      var $selectedElements = this.elementIndex.getSelectedElements(),\n        imageIdsWithMissingUrls = [];\n\n      for (var i = 0; i < $selectedElements.length; i++) {\n        var $item = $($selectedElements[i]),\n          elementId = Craft.getElementInfo($item).id;\n\n        if (\n          typeof Craft.AssetSelectorModal.transformUrls[transform][\n            elementId\n          ] === 'undefined'\n        ) {\n          imageIdsWithMissingUrls.push(elementId);\n        }\n      }\n\n      if (imageIdsWithMissingUrls.length) {\n        this.showFooterSpinner();\n\n        this.fetchMissingTransformUrls(\n          imageIdsWithMissingUrls,\n          transform,\n          () => {\n            this.hideFooterSpinner();\n            this.selectImagesWithTransform(transform);\n          }\n        );\n      } else {\n        this._selectedTransform = transform;\n        this.selectElements();\n        this._selectedTransform = null;\n      }\n    },\n\n    fetchMissingTransformUrls: function (\n      imageIdsWithMissingUrls,\n      transform,\n      callback\n    ) {\n      var elementId = imageIdsWithMissingUrls.pop();\n\n      var data = {\n        assetId: elementId,\n        handle: transform,\n      };\n\n      Craft.sendActionRequest('POST', 'assets/generate-transform', {data})\n        .then((response) => {\n          Craft.AssetSelectorModal.transformUrls[transform][elementId] =\n            response.data.url || false;\n        })\n        .catch(() => {\n          Craft.AssetSelectorModal.transformUrls[transform][elementId] = false;\n        })\n        .finally(() => {\n          // More to load?\n          if (imageIdsWithMissingUrls.length) {\n            this.fetchMissingTransformUrls(\n              imageIdsWithMissingUrls,\n              transform,\n              callback\n            );\n          } else {\n            callback();\n          }\n        });\n    },\n\n    getElementInfo: function ($selectedElements) {\n      var info = this.base($selectedElements);\n\n      if (this._selectedTransform) {\n        for (var i = 0; i < info.length; i++) {\n          var elementId = info[i].id;\n\n          if (\n            typeof Craft.AssetSelectorModal.transformUrls[\n              this._selectedTransform\n            ][elementId] !== 'undefined' &&\n            Craft.AssetSelectorModal.transformUrls[this._selectedTransform][\n              elementId\n            ] !== false\n          ) {\n            info[i].url =\n              Craft.AssetSelectorModal.transformUrls[this._selectedTransform][\n                elementId\n              ];\n          }\n        }\n      }\n\n      return info;\n    },\n\n    onSelect: function (elementInfo) {\n      this.settings.onSelect(elementInfo, this._selectedTransform);\n    },\n  },\n  {\n    defaults: {\n      canSelectImageTransforms: false,\n      transforms: [],\n    },\n\n    transformUrls: {},\n  }\n);\n\n// Register it!\nCraft.registerElementSelectorModalClass(\n  'craft\\\\elements\\\\Asset',\n  Craft.AssetSelectorModal\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Assets field settings\n */\nCraft.AssetsFieldSettings = Garnish.Base.extend({\n  $useSingleFolderInput: null,\n  $sourceInputs: null,\n  $defaultUploadLocationSelect: null,\n  $defaultUploadLocationOptions: null,\n\n  init: function (\n    useSingleFolderToggleId,\n    sourcesFieldId,\n    defaultUploadLocationId\n  ) {\n    this.$useSingleFolderInput = $(`#${useSingleFolderToggleId}`);\n    this.$sourceInputs = $(`#${sourcesFieldId} input`);\n    this.$defaultUploadLocationSelect = $(`#${defaultUploadLocationId}`);\n    this.$defaultUploadLocationOptions =\n      this.$defaultUploadLocationSelect.children('option');\n    this.updateDefaultUploadLocationSelect();\n\n    // Give CheckboxSelect a chance to register its change event first\n    Garnish.requestAnimationFrame(() => {\n      this.addListener(\n        this.$useSingleFolderInput,\n        'change',\n        'updateDefaultUploadLocationSelect'\n      );\n      this.addListener(\n        this.$sourceInputs,\n        'change',\n        'updateDefaultUploadLocationSelect'\n      );\n    });\n  },\n\n  updateDefaultUploadLocationSelect: function () {\n    if (this.$useSingleFolderInput.prop('checked')) {\n      return;\n    }\n\n    const defaultUploadLocationVal = this.$defaultUploadLocationSelect.val();\n    let firstEnabledValue;\n\n    for (let i = 0; i < this.$sourceInputs.length; i++) {\n      const $input = this.$sourceInputs.eq(i);\n      const val = $input.val();\n      const checked = $input.prop('checked');\n      if (val === '*') {\n        if (checked) {\n          this.$defaultUploadLocationOptions.prop('disabled', false);\n          return;\n        }\n      } else {\n        this.getOption(val).prop('disabled', !checked);\n        if (checked && !firstEnabledValue) {\n          firstEnabledValue = val;\n        }\n      }\n    }\n\n    const $selectedOption = this.getOption(defaultUploadLocationVal);\n    if (\n      !$selectedOption.length ||\n      ($selectedOption.prop('disabled') && firstEnabledValue)\n    ) {\n      this.$defaultUploadLocationSelect.val(firstEnabledValue);\n    }\n  },\n\n  getOption: function (val) {\n    return this.$defaultUploadLocationOptions.filter(`[value=\"${val}\"]`);\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * AuthManager class\n */\nCraft.AuthManager = Garnish.Base.extend(\n  {\n    remainingSessionTime: null,\n    checkRemainingSessionTimer: null,\n    showLoginModalTimer: null,\n    decrementLogoutWarningInterval: null,\n\n    showingLogoutWarningModal: false,\n    showingLoginModal: false,\n\n    logoutWarningModal: null,\n    loginModal: null,\n\n    $logoutWarningPara: null,\n    $passwordInput: null,\n    $loginBtn: null,\n    $loginErrorPara: null,\n\n    submitLoginIfLoggedOut: false,\n\n    /**\n     * Init\n     */\n    init: function () {\n      if (Craft.username) {\n        this.updateRemainingSessionTime(Craft.remainingSessionTime);\n      }\n    },\n\n    /**\n     * Sets a timer for the next time to check the auth timeout.\n     */\n    setCheckRemainingSessionTimer: function (seconds) {\n      if (this.checkRemainingSessionTimer) {\n        clearTimeout(this.checkRemainingSessionTimer);\n      }\n\n      this.checkRemainingSessionTimer = setTimeout(\n        this.checkRemainingSessionTime.bind(this),\n        seconds * 1000\n      );\n    },\n\n    /**\n     * Pings the server to see how many seconds are left on the current user session, and handles the response.\n     */\n    checkRemainingSessionTime: function (extendSession) {\n      $.ajax({\n        url: Craft.getActionUrl(\n          'users/session-info',\n          extendSession ? null : 'dontExtendSession=1'\n        ),\n        type: 'GET',\n        dataType: 'json',\n        complete: (jqXHR, textStatus) => {\n          if (textStatus === 'success') {\n            if (\n              typeof jqXHR.responseJSON.csrfTokenValue !== 'undefined' &&\n              typeof Craft.csrfTokenValue !== 'undefined'\n            ) {\n              Craft.csrfTokenValue = jqXHR.responseJSON.csrfTokenValue;\n            }\n\n            this.updateRemainingSessionTime(jqXHR.responseJSON.timeout);\n            this.submitLoginIfLoggedOut = false;\n          } else {\n            this.updateRemainingSessionTime(-1);\n          }\n        },\n      });\n    },\n\n    /**\n     * Updates our record of the auth timeout, and handles it.\n     */\n    updateRemainingSessionTime: function (remainingSessionTime) {\n      this.remainingSessionTime = parseInt(remainingSessionTime);\n\n      // Are we within the warning window?\n      if (\n        this.remainingSessionTime !== -1 &&\n        this.remainingSessionTime < Craft.AuthManager.minSafeSessionTime\n      ) {\n        // Is there still time to renew the session?\n        if (this.remainingSessionTime) {\n          if (!this.showingLogoutWarningModal) {\n            // Show the warning modal\n            this.showLogoutWarningModal();\n          }\n\n          // Will the session expire before the next checkup?\n          if (this.remainingSessionTime < Craft.AuthManager.checkInterval) {\n            if (this.showLoginModalTimer) {\n              clearTimeout(this.showLoginModalTimer);\n            }\n\n            this.showLoginModalTimer = setTimeout(\n              this.showLoginModal.bind(this),\n              this.remainingSessionTime * 1000\n            );\n          }\n        } else {\n          if (this.showingLoginModal) {\n            if (this.submitLoginIfLoggedOut) {\n              this.submitLogin();\n            }\n          } else {\n            // Show the login modal\n            this.showLoginModal();\n          }\n        }\n\n        this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval);\n      } else {\n        // Everything's good!\n        this.hideLogoutWarningModal();\n        this.hideLoginModal();\n\n        // Will be be within the minSafeSessionTime before the next update?\n        if (\n          this.remainingSessionTime !== -1 &&\n          this.remainingSessionTime <\n            Craft.AuthManager.minSafeSessionTime +\n              Craft.AuthManager.checkInterval\n        ) {\n          this.setCheckRemainingSessionTimer(\n            this.remainingSessionTime - Craft.AuthManager.minSafeSessionTime + 1\n          );\n        } else {\n          this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval);\n        }\n      }\n    },\n\n    /**\n     * Shows the logout warning modal.\n     */\n    showLogoutWarningModal: function () {\n      var quickShow;\n\n      if (this.showingLoginModal) {\n        this.hideLoginModal(true);\n        quickShow = true;\n      } else {\n        quickShow = false;\n      }\n\n      this.showingLogoutWarningModal = true;\n\n      if (!this.logoutWarningModal) {\n        let $form = $(\n          '<form id=\"logoutwarningmodal\" class=\"modal alert fitted\"/>'\n        );\n        let $body = $('<div class=\"body\"/>').appendTo($form);\n        let $buttons = $('<div class=\"buttons right\"/>').appendTo($body);\n        let $logoutBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Sign out now'),\n        }).appendTo($buttons);\n        let $renewSessionBtn = $('<button/>', {\n          type: 'submit',\n          class: 'btn submit',\n          text: Craft.t('app', 'Keep me signed in'),\n        }).appendTo($buttons);\n\n        this.$logoutWarningPara = $('<p/>').prependTo($body);\n\n        this.logoutWarningModal = new Garnish.Modal($form, {\n          autoShow: false,\n          closeOtherModals: false,\n          hideOnEsc: false,\n          hideOnShadeClick: false,\n          shadeClass: 'modal-shade dark logoutwarningmodalshade',\n          onFadeIn: function () {\n            if (!Garnish.isMobileBrowser(true)) {\n              // Auto-focus the renew button\n              setTimeout(function () {\n                $renewSessionBtn.trigger('focus');\n              }, 100);\n            }\n          },\n        });\n\n        this.addListener($logoutBtn, 'activate', 'logout');\n        this.addListener($form, 'submit', 'renewSession');\n      }\n\n      if (quickShow) {\n        this.logoutWarningModal.quickShow();\n      } else {\n        this.logoutWarningModal.show();\n      }\n\n      this.updateLogoutWarningMessage();\n\n      this.decrementLogoutWarningInterval = setInterval(\n        this.decrementLogoutWarning.bind(this),\n        1000\n      );\n    },\n\n    /**\n     * Updates the logout warning message indicating that the session is about to expire.\n     */\n    updateLogoutWarningMessage: function () {\n      this.$logoutWarningPara.text(\n        Craft.t('app', 'Your session will expire in {time}.', {\n          time: Craft.secondsToHumanTimeDuration(this.remainingSessionTime),\n        })\n      );\n\n      this.logoutWarningModal.updateSizeAndPosition();\n    },\n\n    decrementLogoutWarning: function () {\n      if (this.remainingSessionTime > 0) {\n        this.remainingSessionTime--;\n        this.updateLogoutWarningMessage();\n      }\n\n      if (this.remainingSessionTime === 0) {\n        clearInterval(this.decrementLogoutWarningInterval);\n      }\n    },\n\n    /**\n     * Hides the logout warning modal.\n     */\n    hideLogoutWarningModal: function (quick) {\n      this.showingLogoutWarningModal = false;\n\n      if (this.logoutWarningModal) {\n        if (quick) {\n          this.logoutWarningModal.quickHide();\n        } else {\n          this.logoutWarningModal.hide();\n        }\n\n        if (this.decrementLogoutWarningInterval) {\n          clearInterval(this.decrementLogoutWarningInterval);\n        }\n      }\n    },\n\n    /**\n     * Shows the login modal.\n     */\n    showLoginModal: function () {\n      var quickShow;\n\n      if (this.showingLogoutWarningModal) {\n        this.hideLogoutWarningModal(true);\n        quickShow = true;\n      } else {\n        quickShow = false;\n      }\n\n      this.showingLoginModal = true;\n\n      if (!this.loginModal) {\n        var $form = $('<form id=\"loginmodal\" class=\"modal alert fitted\"/>'),\n          $body = $(\n            '<div class=\"body\"><h2>' +\n              Craft.t('app', 'Your session has ended.') +\n              '</h2><p>' +\n              Craft.t('app', 'Enter your password to log back in.') +\n              '</p></div>'\n          ).appendTo($form),\n          $inputContainer = $('<div class=\"inputcontainer\">').appendTo($body),\n          $inputsFlexContainer = $('<div class=\"flex\"/>').appendTo(\n            $inputContainer\n          ),\n          $passwordContainer = $('<div class=\"flex-grow\"/>').appendTo(\n            $inputsFlexContainer\n          ),\n          $buttonContainer = $('<div/>').appendTo($inputsFlexContainer),\n          $passwordWrapper = $('<div class=\"passwordwrapper\"/>').appendTo(\n            $passwordContainer\n          );\n\n        this.$passwordInput = $(\n          '<input type=\"password\" class=\"text password fullwidth\" autocomplete=\"current-password\" placeholder=\"' +\n            Craft.t('app', 'Password') +\n            '\"/>'\n        ).appendTo($passwordWrapper);\n        this.$loginBtn = Craft.ui\n          .createSubmitButton({\n            class: 'disabled',\n            label: Craft.t('app', 'Sign in'),\n            spinner: true,\n          })\n          .attr('aria-disabled', 'true')\n          .appendTo($buttonContainer);\n        this.$loginErrorPara = $('<p class=\"error\"/>').appendTo($body);\n\n        this.loginModal = new Garnish.Modal($form, {\n          autoShow: false,\n          closeOtherModals: false,\n          hideOnEsc: false,\n          hideOnShadeClick: false,\n          shadeClass: 'modal-shade dark loginmodalshade',\n          onFadeIn: () => {\n            if (!Garnish.isMobileBrowser(true)) {\n              // Auto-focus the password input\n              setTimeout(() => {\n                this.$passwordInput.trigger('focus');\n              }, 100);\n            }\n          },\n          onFadeOut: () => {\n            this.$passwordInput.val('');\n          },\n        });\n\n        new Craft.PasswordInput(this.$passwordInput, {\n          onToggleInput: ($newPasswordInput) => {\n            this.$passwordInput = $newPasswordInput;\n          },\n        });\n\n        this.addListener(this.$passwordInput, 'input', 'validatePassword');\n        this.addListener($form, 'submit', 'login');\n      }\n\n      if (quickShow) {\n        this.loginModal.quickShow();\n      } else {\n        this.loginModal.show();\n      }\n    },\n\n    /**\n     * Hides the login modal.\n     */\n    hideLoginModal: function (quick) {\n      this.showingLoginModal = false;\n\n      if (this.loginModal) {\n        if (quick) {\n          this.loginModal.quickHide();\n        } else {\n          this.loginModal.hide();\n        }\n      }\n    },\n\n    logout: function () {\n      $.get({\n        url: Craft.getActionUrl('users/logout'),\n        dataType: 'json',\n        success: () => {\n          Craft.redirectTo('');\n        },\n      });\n    },\n\n    renewSession: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      this.hideLogoutWarningModal();\n      this.checkRemainingSessionTime(true);\n    },\n\n    validatePassword: function () {\n      if (this.$passwordInput.val().length >= 6) {\n        this.$loginBtn.removeClass('disabled');\n        this.$loginBtn.removeAttr('aria-disabled');\n        return true;\n      } else {\n        this.$loginBtn.addClass('disabled');\n        this.$loginBtn.attr('aria-disabled', 'true');\n        return false;\n      }\n    },\n\n    login: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      if (this.validatePassword()) {\n        this.$loginBtn.addClass('loading');\n        this.clearLoginError();\n\n        if (typeof Craft.csrfTokenValue !== 'undefined') {\n          // Check the auth status one last time before sending this off,\n          // in case the user has already logged back in from another window/tab\n          this.submitLoginIfLoggedOut = true;\n          this.checkRemainingSessionTime();\n        } else {\n          this.submitLogin();\n        }\n      }\n    },\n\n    submitLogin: function () {\n      var data = {\n        loginName: Craft.username,\n        password: this.$passwordInput.val(),\n      };\n\n      Craft.sendActionRequest('POST', 'users/login', {data})\n        .then((response) => {\n          this.$loginBtn.removeClass('loading');\n          this.hideLoginModal();\n          this.checkRemainingSessionTime();\n        })\n        .catch(({response}) => {\n          this.$loginBtn.removeClass('loading');\n          this.showLoginError(response.data.message || null);\n          Garnish.shake(this.loginModal.$container);\n\n          if (!Garnish.isMobileBrowser(true)) {\n            this.$passwordInput.trigger('focus');\n          }\n        });\n    },\n\n    showLoginError: function (error) {\n      if (error === null || typeof error === 'undefined') {\n        error = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.$loginErrorPara.text(error);\n      this.loginModal.updateSizeAndPosition();\n    },\n\n    clearLoginError: function () {\n      this.showLoginError('');\n    },\n  },\n  {\n    checkInterval: 60,\n    minSafeSessionTime: 120,\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Element index class\n */\nCraft.BaseElementIndex = Garnish.Base.extend(\n  {\n    initialized: false,\n    elementType: null,\n    idPrefix: null,\n\n    instanceState: null,\n    sourceStates: null,\n    sourceStatesStorageKey: null,\n\n    searchTimeout: null,\n    sourceSelect: null,\n\n    $container: null,\n    $main: null,\n    isIndexBusy: false,\n\n    $sidebar: null,\n    showingSidebar: null,\n    sourceKey: null,\n    rootSourceKey: null,\n    sourceViewModes: null,\n    $source: null,\n    $rootSource: null,\n    sourcesByKey: null,\n    $visibleSources: null,\n\n    $sourceActionsContainer: null,\n    $sourceActionsBtn: null,\n\n    $toolbar: null,\n    toolbarOffset: null,\n\n    $searchContainer: null,\n    $search: null,\n    $filterBtn: null,\n    searching: false,\n    searchText: null,\n    sortByScore: null,\n    trashed: false,\n    drafts: false,\n    $clearSearchBtn: null,\n\n    $statusMenuBtn: null,\n    $statusMenuContainer: null,\n    statusMenu: null,\n    status: null,\n\n    $siteMenuBtn: null,\n    siteMenu: null,\n    siteId: null,\n\n    _sourcePath: null,\n    $sourcePathOuterContainer: null,\n    $sourcePathInnerContainer: null,\n    $sourcePathOverflowBtnContainer: null,\n    $sourcePathActionsBtn: null,\n\n    $elements: null,\n    $updateSpinner: null,\n    $viewModeBtnContainer: null,\n    viewModeBtns: null,\n    _viewMode: null,\n    view: null,\n    _autoSelectElements: null,\n    $countSpinner: null,\n    $countContainer: null,\n    $actionsContainer: null,\n    page: 1,\n    resultSet: null,\n    totalResults: null,\n    $exportBtn: null,\n\n    actions: null,\n    actionsHeadHtml: null,\n    actionsBodyHtml: null,\n    $selectAllContainer: null,\n    $selectAllCheckbox: null,\n    showingActionTriggers: false,\n    exporters: null,\n    exportersByType: null,\n    _$triggers: null,\n\n    _cancelToken: null,\n\n    viewMenus: null,\n    activeViewMenu: null,\n    filterHuds: null,\n\n    _activeElement: null,\n\n    get viewMode() {\n      if (this._viewMode === 'structure' && !this.canSortByStructure()) {\n        return 'table';\n      }\n      return this._viewMode;\n    },\n\n    set viewMode(viewMode) {\n      this._viewMode = viewMode;\n    },\n\n    /**\n     * Constructor\n     */\n    init: function (elementType, $container, settings) {\n      this.elementType = elementType;\n      this.$container = $container;\n      this.setSettings(settings, Craft.BaseElementIndex.defaults);\n\n      // Define an ID prefix that can be used for dynamically created elements\n      // ---------------------------------------------------------------------\n\n      this.idPrefix = Craft.randomString(10);\n\n      // Set the state objects\n      // ---------------------------------------------------------------------\n\n      this.instanceState = this.getDefaultInstanceState();\n\n      this.sourceStates = {};\n\n      // Instance states (selected source) are stored by a custom storage key defined in the settings\n      if (this.settings.storageKey) {\n        $.extend(\n          this.instanceState,\n          Craft.getLocalStorage(this.settings.storageKey),\n          {}\n        );\n      }\n\n      // Source states (view mode, etc.) are stored by the element type and context\n      this.sourceStatesStorageKey =\n        'BaseElementIndex.' + this.elementType + '.' + this.settings.context;\n      $.extend(\n        this.sourceStates,\n        Craft.getLocalStorage(this.sourceStatesStorageKey, {})\n      );\n\n      // Find the DOM elements\n      // ---------------------------------------------------------------------\n\n      this.$main = this.$container.find('.main');\n      this.$toolbar = this.$container.find(this.settings.toolbarSelector);\n      this.$statusMenuBtn = this.$toolbar.find('.statusmenubtn:first');\n      this.$statusMenuContainer = this.$statusMenuBtn.parent();\n      this.$siteMenuBtn = this.$container.find('.sitemenubtn:first');\n\n      this.$searchContainer = this.$toolbar.find('.search-container:first');\n      this.$search = this.$searchContainer.children('input:first');\n      this.$filterBtn = this.$searchContainer.children('.filter-btn:first');\n      this.$clearSearchBtn = this.$searchContainer.children('.clear-btn:first');\n\n      this.$sidebar = this.$container.find('.sidebar:first');\n      this.$sourceActionsContainer = this.$sidebar.find('#source-actions');\n\n      this.$elements = this.$container.find('.elements:first');\n      this.$updateSpinner = this.$elements.find('.spinner');\n\n      if (!this.$updateSpinner.length) {\n        this.$updateSpinner = $('<div/>', {\n          class: 'update-spinner spinner spinner-absolute',\n        }).appendTo(this.$elements);\n      }\n\n      this.$countSpinner = this.$container.find('#count-spinner');\n      this.$countContainer = this.$container.find('#count-container');\n      this.$actionsContainer = this.$container.find('#actions-container');\n      this.$exportBtn = this.$container.find('#export-btn');\n\n      // Hide sidebar if needed\n      if (this.settings.hideSidebar) {\n        this.$sidebar.hide();\n        $('.body, .content', this.$container).removeClass('has-sidebar');\n      }\n\n      // Initialize the sources\n      // ---------------------------------------------------------------------\n\n      if (!this.initSources()) {\n        return;\n      }\n\n      // Initialize the status menu\n      // ---------------------------------------------------------------------\n\n      if (this.$statusMenuBtn.length) {\n        this.statusMenu = this.$statusMenuBtn.menubtn().data('menubtn').menu;\n        this.statusMenu.on('optionselect', this._handleStatusChange.bind(this));\n      }\n\n      // Initialize the site menu\n      // ---------------------------------------------------------------------\n\n      // Is there a site menu?\n      if (this.$siteMenuBtn.length) {\n        this.siteMenu = this.$siteMenuBtn.menubtn().data('menubtn').menu;\n\n        // Figure out the initial site\n        var $option = this.siteMenu.$options.filter('.sel:first');\n\n        if (!$option.length) {\n          $option = this.siteMenu.$options.first();\n        }\n\n        if ($option.length) {\n          this._setSite($option.data('site-id'));\n        } else {\n          // No site options -- they must not have any site permissions\n          this.settings.criteria = {id: '0'};\n        }\n\n        this.siteMenu.on('optionselect', this._handleSiteChange.bind(this));\n\n        if (this.siteId) {\n          // Should we be using a different default site?\n          var defaultSiteId =\n            this.settings.defaultSiteId || Craft.cp.getSiteId();\n\n          if (defaultSiteId && defaultSiteId != this.siteId) {\n            // Is that one available here?\n            var $storedSiteOption = this.siteMenu.$options.filter(\n              '[data-site-id=\"' + defaultSiteId + '\"]:first'\n            );\n\n            if ($storedSiteOption.length) {\n              // Todo: switch this to siteMenu.selectOption($storedSiteOption) once Menu is updated to support that\n              $storedSiteOption.trigger('click');\n            }\n          }\n        }\n      } else if (\n        this.settings.criteria &&\n        this.settings.criteria.siteId &&\n        this.settings.criteria.siteId !== '*'\n      ) {\n        this._setSite(this.settings.criteria.siteId);\n      } else {\n        this._setSite(Craft.siteId);\n      }\n\n      // Don't let the criteria override the selected site\n      if (this.settings.criteria && this.settings.criteria.siteId) {\n        delete this.settings.criteria.siteId;\n      }\n\n      // Initialize the search input\n      // ---------------------------------------------------------------------\n\n      // Automatically update the elements after new search text has been sitting for a 1/2 second\n      this.addListener(this.$search, 'input', () => {\n        if (!this.searching && this.$search.val()) {\n          this.startSearching();\n        } else if (this.searching && !this.$search.val()) {\n          this.stopSearching();\n        }\n\n        if (this.searchTimeout) {\n          clearTimeout(this.searchTimeout);\n        }\n\n        this.searchTimeout = setTimeout(\n          this.updateElementsIfSearchTextChanged.bind(this),\n          500\n        );\n      });\n\n      // Update the elements when the Return key is pressed\n      this.addListener(this.$search, 'keypress', (ev) => {\n        if (ev.keyCode === Garnish.RETURN_KEY) {\n          ev.preventDefault();\n\n          if (this.searchTimeout) {\n            clearTimeout(this.searchTimeout);\n          }\n\n          this.updateElementsIfSearchTextChanged();\n        }\n      });\n\n      // Clear the search when the X button is clicked\n      this.addListener(this.$clearSearchBtn, 'click', () => {\n        this.clearSearch(true);\n\n        if (!Garnish.isMobileBrowser(true)) {\n          this.$search.trigger('focus');\n        }\n      });\n\n      // Auto-focus the Search box\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$search.trigger('focus');\n      }\n\n      // View menus\n      this.viewMenus = {};\n\n      // Filter HUDs\n      this.filterHuds = {};\n      this.addListener(this.$filterBtn, 'click', 'showFilterHud');\n\n      // Set the default status\n      // ---------------------------------------------------------------------\n\n      const queryParams =\n        this.settings.context === 'index' ? Craft.getQueryParams() : {};\n\n      if (queryParams.status) {\n        let selector;\n        switch (queryParams.status) {\n          case 'trashed':\n            selector = '[data-trashed]';\n            break;\n          case 'drafts':\n            selector = '[data-drafts]';\n            break;\n          default:\n            selector = `[data-status=\"${queryParams.status}\"]`;\n        }\n\n        const $option = this.statusMenu.$options.filter(selector);\n        if ($option.length) {\n          this.statusMenu.selectOption($option[0]);\n        } else {\n          Craft.setQueryParam('status', null);\n        }\n      }\n\n      // Initialize the Export button\n      // ---------------------------------------------------------------------\n\n      this.addListener(this.$exportBtn, 'click', '_showExportHud');\n\n      // Let everyone know that the UI is initialized\n      // ---------------------------------------------------------------------\n\n      this.initialized = true;\n      this.afterInit();\n\n      // Select the initial source + source path\n      // ---------------------------------------------------------------------\n\n      this.selectDefaultSource();\n\n      const sourcePath = this.getDefaultSourcePath();\n      if (sourcePath !== null) {\n        this.sourcePath = sourcePath;\n      }\n      if (this.settings.context === 'index') {\n        this.addListener(Garnish.$win, 'resize', 'handleResize');\n      }\n      this.handleResize();\n\n      // Respect initial search\n      // ---------------------------------------------------------------------\n      // Has to go after selecting the default source because selecting a source\n      // clears out search params\n\n      if (queryParams.search) {\n        this.startSearching();\n        this.searchText = queryParams.search;\n      }\n\n      // Select the default sort attribute/direction\n      // ---------------------------------------------------------------------\n\n      if (queryParams.sort) {\n        const lastDashPos = queryParams.sort.lastIndexOf('-');\n        if (lastDashPos !== -1) {\n          const attr = queryParams.sort.substring(0, lastDashPos);\n          const dir = queryParams.sort.substring(lastDashPos + 1);\n          this.setSelectedSortAttribute(attr, dir);\n        }\n      }\n\n      // Load the first batch of elements!\n      // ---------------------------------------------------------------------\n\n      // Default to whatever page is in the URL\n      this.setPage(Craft.pageNum);\n\n      this.updateElements(true);\n    },\n\n    afterInit: function () {\n      this.onAfterInit();\n    },\n\n    handleResize: function () {\n      if (this.sourcePath.length && this.settings.showSourcePath) {\n        this._updateSourcePathVisibility();\n      }\n    },\n\n    _createCancelToken: function () {\n      this._cancelToken = axios.CancelToken.source();\n      return this._cancelToken.token;\n    },\n\n    _cancelRequests: function () {\n      if (this._cancelToken) {\n        this._cancelToken.cancel();\n      }\n    },\n\n    getSourceContainer: function () {\n      return this.$sidebar.find('nav > ul');\n    },\n\n    get $sources() {\n      if (!this.sourceSelect) {\n        return undefined;\n      }\n\n      return this.sourceSelect.$items;\n    },\n\n    getSite: function () {\n      if (!this.siteId) {\n        return undefined;\n      }\n      return Craft.sites.find((s) => s.id == this.siteId);\n    },\n\n    initSources: function () {\n      var $sources = this._getSourcesInList(this.getSourceContainer(), true);\n\n      // No source, no party.\n      if ($sources.length === 0) {\n        return false;\n      }\n\n      // The source selector\n      if (!this.sourceSelect) {\n        this.sourceSelect = new Garnish.Select(this.$sidebar.find('nav'), {\n          multi: false,\n          allowEmpty: false,\n          vertical: true,\n          onSelectionChange: this._handleSourceSelectionChange.bind(this),\n        });\n      }\n\n      this.sourcesByKey = {};\n\n      for (let i = 0; i < $sources.length; i++) {\n        this.initSource($($sources[i]));\n      }\n\n      return true;\n    },\n\n    selectDefaultSource: function () {\n      // The `source` query param should always take precedence\n      let sourceKey;\n      if (this.settings.context === 'index') {\n        sourceKey = Craft.getQueryParam('source');\n      }\n\n      if (!sourceKey) {\n        sourceKey = this.getDefaultSourceKey();\n      }\n\n      let $source;\n\n      if (sourceKey) {\n        $source = this.getSourceByKey(sourceKey);\n\n        // Make sure it's visible\n        if (this.$visibleSources.index($source) === -1) {\n          $source = null;\n        }\n      }\n\n      if (!sourceKey || !$source) {\n        // Select the first source by default\n        $source = this.$visibleSources.first();\n      }\n\n      return this.selectSource($source);\n    },\n\n    refreshSources: function () {\n      this.sourceSelect.removeAllItems();\n\n      this.setIndexBusy();\n\n      Craft.sendActionRequest('POST', this.settings.refreshSourcesAction, {\n        data: {\n          context: this.settings.context,\n          elementType: this.elementType,\n        },\n      })\n        .then((response) => {\n          this.setIndexAvailable();\n          this.getSourceContainer().replaceWith(response.data.html);\n          this.initSources();\n          this.selectDefaultSource();\n        })\n        .catch((e) => {\n          if (!axios.isCancel(e)) {\n            this.setIndexAvailable();\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n          }\n        });\n    },\n\n    initSource: function ($source) {\n      this.sourceSelect.addItems($source);\n      this.initSourceToggle($source);\n      this.sourcesByKey[$source.data('key')] = $source;\n\n      if (\n        $source.data('hasNestedSources') &&\n        this.instanceState.expandedSources.indexOf($source.data('key')) !== -1\n      ) {\n        this._expandSource($source);\n      }\n    },\n\n    initSourceToggle: function ($source) {\n      // Remove handlers for the same thing. Just in case.\n      this.deinitSourceToggle($source);\n\n      var $toggle = this._getSourceToggle($source);\n\n      if ($toggle.length) {\n        this.addListener($source, 'dblclick', '_handleSourceDblClick');\n        this.addListener($toggle, 'click', '_handleSourceToggleClick');\n        $source.data('hasNestedSources', true);\n      } else {\n        $source.data('hasNestedSources', false);\n      }\n    },\n\n    deinitSource: function ($source) {\n      this.sourceSelect.removeItems($source);\n      this.deinitSourceToggle($source);\n      delete this.sourcesByKey[$source.data('key')];\n    },\n\n    deinitSourceToggle: function ($source) {\n      if ($source.data('hasNestedSources')) {\n        this.removeListener($source, 'dblclick');\n        this.removeListener(this._getSourceToggle($source), 'click');\n      }\n\n      $source.removeData('hasNestedSources');\n    },\n\n    getDefaultInstanceState: function () {\n      return {\n        selectedSource: null,\n        expandedSources: [],\n      };\n    },\n\n    getDefaultSourceKey: function () {\n      let sourceKey = null;\n\n      if (this.settings.defaultSource) {\n        let $lastSource = null;\n        let refreshSources = false;\n\n        for (const segment of this.settings.defaultSource.split('/')) {\n          if ($lastSource) {\n            this._expandSource($lastSource);\n            refreshSources = true;\n          }\n\n          const testSourceKey =\n            (sourceKey !== null ? `${sourceKey}/` : '') + segment;\n          const $source = this.getSourceByKey(testSourceKey);\n\n          if (!$source) {\n            if ($lastSource) {\n              this._collapseSource($lastSource);\n            }\n            break;\n          }\n\n          $lastSource = $source;\n          sourceKey = testSourceKey;\n        }\n\n        if (refreshSources) {\n          // Make sure that the modal is aware of the newly expanded sources\n          this._setSite(this.siteId);\n        }\n      }\n\n      return sourceKey ?? this.instanceState.selectedSource;\n    },\n\n    /**\n     * @returns {Object[]|null}\n     */\n    getDefaultSourcePath: function () {\n      // @link https://github.com/craftcms/cms/issues/13006\n      if (\n        this.settings.defaultSourcePath !== null &&\n        this.settings.defaultSourcePath[0] !== undefined &&\n        this.settings.defaultSourcePath[0].canView === true &&\n        ((this.sourcePath.length > 0 &&\n          this.sourcePath[0].handle ===\n            this.settings.defaultSourcePath[0].handle) ||\n          this.sourcePath.length === 0)\n      ) {\n        return this.settings.defaultSourcePath;\n      } else {\n        return null;\n      }\n    },\n\n    getDefaultExpandedSources: function () {\n      return this.instanceState.expandedSources;\n    },\n\n    /**\n     * @returns {Object[]}\n     */\n    get sourcePath() {\n      return this._sourcePath || [];\n    },\n\n    /**\n     * @param {Object[]|null} sourcePath\n     */\n    set sourcePath(sourcePath) {\n      this._sourcePath = sourcePath && sourcePath.length ? sourcePath : null;\n\n      if (this.$sourcePathOuterContainer) {\n        this.$sourcePathOuterContainer.remove();\n        this.$sourcePathOuterContainer = null;\n        this.$sourcePathInnerContainer = null;\n        this.$sourcePathOverflowBtnContainer = null;\n        this.$sourcePathActionsBtn = null;\n      }\n\n      if (this._sourcePath && this.settings.showSourcePath) {\n        const actions = this.getSourcePathActions();\n\n        this.$sourcePathOuterContainer = $('<div/>', {\n          class: 'source-path',\n        }).insertBefore(this.$elements);\n        this.$sourcePathInnerContainer = $('<div/>', {\n          class: 'chevron-btns',\n        }).appendTo(this.$sourcePathOuterContainer);\n        const $nav = $('<nav/>', {\n          'aria-label': this.getSourcePathLabel(),\n        }).appendTo(this.$sourcePathInnerContainer);\n        const $ol = $('<ol/>').appendTo($nav);\n\n        let $overflowBtn, overflowMenuId, $overflowUl;\n\n        if (sourcePath.length > 1) {\n          this.$sourcePathOverflowBtnContainer = $('<li/>', {\n            class: 'first-step hidden',\n          }).appendTo($ol);\n\n          overflowMenuId = 'menu' + Math.floor(Math.random() * 1000000);\n          $overflowBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn',\n            title: Craft.t('app', 'More items'),\n            'aria-label': Craft.t('app', 'More items'),\n            'data-disclosure-trigger': true,\n            'aria-controls': overflowMenuId,\n          })\n            .append(\n              $('<span/>', {class: 'btn-body'}).append(\n                $('<span/>', {class: 'label'}).append(\n                  $('<span/>', {'data-icon': 'ellipsis', 'aria-hidden': 'true'})\n                )\n              )\n            )\n            .append($('<span/>', {class: 'chevron-right'}))\n            .appendTo(this.$sourcePathOverflowBtnContainer);\n\n          const $overflowMenu = $('<div/>', {\n            id: overflowMenuId,\n            class: 'menu menu--disclosure',\n          }).appendTo(this.$sourcePathOverflowBtnContainer);\n          $overflowUl = $('<ul/>').appendTo($overflowMenu);\n\n          $overflowBtn.disclosureMenu();\n        }\n\n        for (let i = 0; i < sourcePath.length; i++) {\n          ((i) => {\n            const step = sourcePath[i];\n\n            if ($overflowUl && i < sourcePath.length - 1) {\n              step.$overflowLi = $('<li/>', {\n                class: 'hidden',\n              }).appendTo($overflowUl);\n\n              $('<a/>', {\n                class: 'flex flex-nowrap',\n                href: '#',\n                type: 'button',\n                role: 'button',\n                html: step.icon\n                  ? `<span data-icon=\"${step.icon}\" aria-hidden=\"true\"></span><span>${step.label}</span>`\n                  : step.label,\n              })\n                .appendTo(step.$overflowLi)\n                .on('click', (ev) => {\n                  ev.preventDefault();\n                  $overflowBtn.data('trigger').hide();\n                  this.selectSourcePathStep(i);\n                });\n            }\n\n            const isFirst = i === 0;\n            const isLast = i === sourcePath.length - 1;\n\n            step.$li = $('<li/>').appendTo($ol);\n\n            if (isFirst) {\n              step.$li.addClass('first-step');\n            }\n\n            step.$btn = $('<a/>', {\n              href: step.uri ? Craft.getCpUrl(step.uri) : '#',\n              class: 'btn',\n              role: 'button',\n            });\n\n            if (step.icon) {\n              step.$btn.attr('aria-label', step.label);\n            }\n\n            const $btnBody = $('<span/>', {\n              class: 'btn-body',\n            }).appendTo(step.$btn);\n\n            step.$label = $('<span/>', {\n              class: 'label',\n              html: step.icon\n                ? `<span data-icon=\"${step.icon}\" aria-hidden=\"true\"></span>`\n                : step.label,\n            }).appendTo($btnBody);\n\n            step.$btn.append($('<span class=\"chevron-left\"/>'));\n\n            if (!isLast || !actions.length) {\n              step.$btn.append($('<span class=\"chevron-right\"/>'));\n            } else {\n              step.$btn.addClass('has-action-menu');\n            }\n\n            if (isLast) {\n              step.$btn.addClass('current-step').attr('aria-current', 'page');\n            }\n\n            step.$btn.appendTo(step.$li);\n\n            this.addListener(step.$btn, 'activate', () => {\n              this.selectSourcePathStep(i);\n            });\n          })(i);\n        }\n\n        // Action menu\n        if (actions && actions.length) {\n          const actionBtnLabel = this.getSourcePathActionLabel();\n          const menuId = 'menu' + Math.floor(Math.random() * 1000000);\n          this.$sourcePathActionsBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn current-step',\n            title: actionBtnLabel,\n            'aria-label': actionBtnLabel,\n            'data-disclosure-trigger': true,\n            'aria-controls': menuId,\n          })\n            .append(\n              $('<span/>', {class: 'btn-body'}).append(\n                $('<span/>', {class: 'label'})\n              )\n            )\n            .append($('<span/>', {class: 'chevron-right'}))\n            .appendTo(this.$sourcePathInnerContainer);\n\n          const groupedActions = [\n            actions.filter((a) => !a.destructive && !a.administrative),\n            actions.filter((a) => a.destructive && !a.administrative),\n            actions.filter((a) => a.administrative),\n          ].filter((group) => group.length);\n\n          const $menu = $('<div/>', {\n            id: menuId,\n            class: 'menu menu--disclosure',\n          }).appendTo(this.$sourcePathInnerContainer);\n\n          groupedActions.forEach((group, index) => {\n            if (index !== 0) {\n              $('<hr/>').appendTo($menu);\n            }\n            this._buildSourcePathActionList(group).appendTo($menu);\n          });\n\n          this.$sourcePathActionsBtn.disclosureMenu();\n          this._updateSourcePathVisibility();\n        }\n\n        // Update the URL if we're on the index page\n        if (\n          this.settings.context === 'index' &&\n          typeof sourcePath[sourcePath.length - 1].uri !== 'undefined' &&\n          typeof history != 'undefined'\n        ) {\n          history.replaceState(\n            {},\n            '',\n            Craft.getCpUrl(sourcePath[sourcePath.length - 1].uri)\n          );\n        }\n      }\n\n      this.onSourcePathChange();\n    },\n\n    /**\n     * @returns {string}\n     */\n    getSourcePathLabel: function () {\n      return '';\n    },\n\n    /**\n     * @returns {Object[]}\n     */\n    getSourcePathActions: function () {\n      return [];\n    },\n\n    /**\n     * @returns {string}\n     */\n    getSourcePathActionLabel: function () {\n      return '';\n    },\n\n    _updateSourcePathVisibility: function () {\n      const firstStep = this.sourcePath[0];\n      const lastStep = this.sourcePath[this.sourcePath.length - 1];\n\n      // reset the source path styles\n      if (this.$sourcePathOverflowBtnContainer) {\n        this.$sourcePathOverflowBtnContainer.addClass('hidden');\n        firstStep.$li.addClass('first-step');\n      }\n\n      for (const step of this.sourcePath) {\n        if (step.$overflowLi) {\n          step.$overflowLi.addClass('hidden');\n        }\n        step.$li.removeClass('hidden');\n      }\n\n      lastStep.$label.css('width', '');\n      lastStep.$btn.removeAttr('title');\n\n      let overage = this._checkSourcePathOverage();\n      if (!overage) {\n        return;\n      }\n\n      // show the overflow menu, if we have one\n      if (this.$sourcePathOverflowBtnContainer) {\n        this.$sourcePathOverflowBtnContainer.removeClass('hidden');\n        firstStep.$li.removeClass('first-step');\n\n        for (let i = 0; i < this.sourcePath.length - 1; i++) {\n          const step = this.sourcePath[i];\n          step.$overflowLi.removeClass('hidden');\n          step.$li.addClass('hidden');\n\n          // are we done yet?\n          overage = this._checkSourcePathOverage();\n          if (!overage) {\n            return;\n          }\n        }\n      }\n\n      // if we're still here, truncation is the only remaining strategy\n      if (!lastStep.icon) {\n        const width = lastStep.$label[0].getBoundingClientRect().width;\n        lastStep.$label.width(Math.floor(width - overage));\n        lastStep.$btn.attr('title', lastStep.label);\n      }\n    },\n\n    _checkSourcePathOverage: function () {\n      const outerWidth =\n        this.$sourcePathOuterContainer[0].getBoundingClientRect().width;\n      const innerWidth =\n        this.$sourcePathInnerContainer[0].getBoundingClientRect().width;\n      return Math.max(innerWidth - outerWidth, 0);\n    },\n\n    _buildSourcePathActionList: function (actions) {\n      const $ul = $('<ul/>');\n\n      actions.forEach((action) => {\n        const $a = $('<a/>', {\n          href: '#',\n          type: 'button',\n          role: 'button',\n          'aria-label': action.label,\n          text: action.label,\n        }).on('click', (ev) => {\n          ev.preventDefault();\n          this.$sourcePathActionsBtn.data('trigger').hide();\n          if (action.onSelect) {\n            action.onSelect();\n          }\n        });\n\n        if (action.destructive) {\n          $a.addClass('error');\n        }\n\n        $('<li/>').append($a).appendTo($ul);\n      });\n\n      return $ul;\n    },\n\n    onSourcePathChange: function () {\n      this.settings.onSourcePathChange();\n      this.trigger('sourcePathChange');\n    },\n\n    selectSourcePathStep: function (num) {\n      this.sourcePath = this.sourcePath.slice(0, num + 1);\n      this.sourcePath[num].$btn.focus();\n      this.clearSearch(false);\n      this.updateElements();\n    },\n\n    startSearching: function () {\n      // Show the clear button\n      this.$clearSearchBtn.removeClass('hidden');\n      this.searching = true;\n      this.sortByScore = true;\n\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n    },\n\n    clearSearch: function (updateElements) {\n      if (!this.searching) {\n        return;\n      }\n\n      this.$search.val('');\n\n      if (this.searchTimeout) {\n        clearTimeout(this.searchTimeout);\n      }\n\n      this.stopSearching();\n\n      if (updateElements) {\n        this.updateElementsIfSearchTextChanged();\n      } else {\n        this.searchText = null;\n      }\n    },\n\n    stopSearching: function () {\n      // Hide the clear button\n      this.$clearSearchBtn.addClass('hidden');\n      this.searching = false;\n      this.sortByScore = false;\n\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n    },\n\n    setInstanceState: function (key, value) {\n      if (typeof key === 'object') {\n        $.extend(this.instanceState, key);\n      } else {\n        this.instanceState[key] = value;\n      }\n\n      this.storeInstanceState();\n    },\n\n    storeInstanceState: function () {\n      if (this.settings.storageKey) {\n        Craft.setLocalStorage(this.settings.storageKey, this.instanceState);\n      }\n    },\n\n    getSourceState: function (sourceKey, key, defaultValue) {\n      // account for when all sources are disabled\n      if (sourceKey == undefined) {\n        return null;\n      }\n\n      sourceKey = sourceKey.replace(/\\/.*/, '');\n\n      if (typeof this.sourceStates[sourceKey] === 'undefined') {\n        // Set it now so any modifications to it by whoever's calling this will be stored.\n        this.sourceStates[sourceKey] = {};\n      }\n\n      if (typeof key === 'undefined') {\n        return this.sourceStates[sourceKey];\n      } else if (typeof this.sourceStates[sourceKey][key] !== 'undefined') {\n        return this.sourceStates[sourceKey][key];\n      } else {\n        return typeof defaultValue !== 'undefined' ? defaultValue : null;\n      }\n    },\n\n    getSelectedSourceState: function (key, defaultValue) {\n      return this.getSourceState(\n        this.instanceState.selectedSource,\n        key,\n        defaultValue\n      );\n    },\n\n    setSelecetedSourceState: function (key, value) {\n      var viewState = this.getSelectedSourceState();\n\n      // account for when all sources are disabled\n      if (viewState == null) {\n        viewState = [];\n      }\n\n      if (typeof key === 'object') {\n        for (let k in key) {\n          if (key.hasOwnProperty(k)) {\n            if (key[k] !== null) {\n              viewState[k] = key[k];\n            } else {\n              delete viewState[k];\n            }\n          }\n        }\n      } else if (value !== null) {\n        viewState[key] = value;\n      } else {\n        delete viewState[key];\n      }\n\n      // account for when all sources are disabled\n      let sourceKey = '*';\n      if (this.instanceState.selectedSource != undefined) {\n        // otherwise do what we used to do\n        sourceKey = this.instanceState.selectedSource.replace(/\\/.*/, '');\n      }\n\n      this.sourceStates[sourceKey] = viewState;\n\n      // Clean up sourceStates while we're at it\n      for (let i in this.sourceStates) {\n        if (this.sourceStates.hasOwnProperty(i) && i.includes('/')) {\n          delete this.sourceStates[i];\n        }\n      }\n\n      // Store it in localStorage too\n      Craft.setLocalStorage(this.sourceStatesStorageKey, this.sourceStates);\n    },\n\n    /**\n     * @deprecated in 4.3.0.\n     */\n    storeSortAttributeAndDirection: function () {},\n\n    /**\n     * Sets the page number.\n     */\n    setPage: function (page) {\n      if (this.settings.context !== 'index') {\n        return;\n      }\n\n      page = Math.max(page, 1);\n      this.page = page;\n\n      const url = Craft.getPageUrl(this.page);\n      history.replaceState({}, '', url);\n    },\n\n    _resetCount: function () {\n      this.resultSet = null;\n      this.totalResults = null;\n    },\n\n    updateSourceMenu: function () {\n      if (!this.$sourceActionsContainer.length) {\n        return;\n      }\n\n      if (this.$sourceActionsBtn) {\n        this.$sourceActionsBtn.data('trigger').destroy();\n        this.$sourceActionsContainer.empty();\n        $('#source-actions-menu').remove();\n        this.$sourceActionsBtn = null;\n      }\n\n      const actions = this.getSourceActions();\n      if (!actions.length) {\n        return;\n      }\n\n      const groupedActions = [\n        actions.filter((a) => !a.destructive && !a.administrative),\n        actions.filter((a) => a.destructive && !a.administrative),\n        actions.filter((a) => a.administrative),\n      ].filter((group) => group.length);\n\n      this.$sourceActionsBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn settings icon menubtn',\n        title: Craft.t('app', 'Source settings'),\n        'aria-label': Craft.t('app', 'Source settings'),\n        'aria-controls': 'source-actions-menu',\n      }).appendTo(this.$sourceActionsContainer);\n\n      const $menu = $('<div/>', {\n        id: 'source-actions-menu',\n        class: 'menu menu--disclosure',\n      }).appendTo(this.$sourceActionsContainer);\n\n      groupedActions.forEach((group, index) => {\n        if (index !== 0) {\n          $('<hr/>').appendTo($menu);\n        }\n\n        this._buildActionList(group).appendTo($menu);\n      });\n\n      this.$sourceActionsBtn.disclosureMenu();\n    },\n\n    _buildActionList: function (actions) {\n      const $ul = $('<ul/>');\n\n      actions.forEach((action) => {\n        const $button = $('<button/>', {\n          type: 'button',\n          class: 'menu-option',\n          text: action.label,\n        }).on('click', () => {\n          this.$sourceActionsBtn.data('trigger').hide();\n          if (action.onSelect) {\n            action.onSelect();\n          }\n        });\n\n        if (action.destructive) {\n          $button.addClass('error');\n        }\n\n        $('<li/>').append($button).appendTo($ul);\n      });\n\n      return $ul;\n    },\n\n    getSourceActions: function () {\n      let actions = [];\n\n      if (Craft.userIsAdmin && Craft.allowAdminChanges) {\n        actions.push({\n          label: Craft.t('app', 'Customize sources'),\n          administrative: true,\n          onSelect: () => {\n            this.createCustomizeSourcesModal();\n          },\n        });\n      }\n\n      return actions;\n    },\n\n    updateViewMenu: function () {\n      if (\n        !this.activeViewMenu ||\n        this.activeViewMenu !== this.viewMenus[this.rootSourceKey]\n      ) {\n        if (this.activeViewMenu) {\n          this.activeViewMenu.hideTrigger();\n        }\n        if (!this.viewMenus[this.rootSourceKey]) {\n          this.viewMenus[this.rootSourceKey] = new ViewMenu(\n            this,\n            this.$rootSource\n          );\n        }\n        this.activeViewMenu = this.viewMenus[this.rootSourceKey];\n        this.activeViewMenu.showTrigger();\n      }\n    },\n\n    /**\n     * Returns any additional settings that should be passed to the view instance.\n     */\n    getViewSettings: function () {\n      return {};\n    },\n\n    /**\n     * Returns the data that should be passed to the elementIndex/getElements controller action\n     * when loading elements.\n     */\n    getViewParams: function () {\n      var criteria = {\n        siteId: this.siteId,\n        search: this.searchText,\n        offset: this.settings.batchSize * (this.page - 1),\n        limit: this.settings.batchSize,\n      };\n\n      // Only set drafts/draftOf/trashed params when needed, so we don't potentially override a source's criteria\n      if (\n        this.settings.canHaveDrafts &&\n        (this.drafts || (this.settings.context === 'index' && !this.status))\n      ) {\n        criteria.drafts = this.drafts || null;\n        criteria.savedDraftsOnly = true;\n        if (!this.drafts) {\n          criteria.draftOf = false;\n        }\n      }\n      if (this.trashed) {\n        criteria.trashed = true;\n      }\n\n      if (!Garnish.hasAttr(this.$source, 'data-override-status')) {\n        criteria.status = this.status;\n      }\n\n      $.extend(criteria, this.settings.criteria);\n\n      if (this.sourcePath.length) {\n        const currentStep = this.sourcePath[this.sourcePath.length - 1];\n        if (typeof currentStep.criteria !== 'undefined') {\n          $.extend(criteria, currentStep.criteria);\n        }\n      }\n\n      var params = {\n        context: this.settings.context,\n        elementType: this.elementType,\n        source: this.instanceState.selectedSource,\n        condition: this.settings.condition,\n        referenceElementId: this.settings.referenceElementId,\n        referenceElementSiteId: this.settings.referenceElementSiteId,\n        criteria: criteria,\n        disabledElementIds: this.settings.disabledElementIds,\n        viewState: $.extend({}, this.getSelectedSourceState()),\n        paginated: this._isViewPaginated() ? 1 : 0,\n      };\n\n      // override viewState.mode in case it's different from what's stored\n      params.viewState.mode = this.viewMode;\n\n      if (this.viewMode === 'structure') {\n        params.viewState.mode = 'table';\n        params.viewState.order = 'structure';\n        params.viewState.sort = 'asc';\n\n        if (typeof this.instanceState.collapsedElementIds === 'undefined') {\n          this.instanceState.collapsedElementIds = [];\n        }\n        params.collapsedElementIds = this.instanceState.collapsedElementIds;\n      } else {\n        // Possible that the order/sort isn't entirely accurate if we're sorting by Score\n        const [sortAttribute, sortDirection] =\n          this.getSortAttributeAndDirection();\n        params.viewState.order = sortAttribute;\n        params.viewState.sort = sortDirection;\n      }\n\n      if (\n        this.filterHuds[this.siteId] &&\n        this.filterHuds[this.siteId][this.sourceKey] &&\n        this.filterHuds[this.siteId][this.sourceKey].serialized\n      ) {\n        params.filters =\n          this.filterHuds[this.siteId][this.sourceKey].serialized;\n      }\n\n      // Give plugins a chance to hook in here\n      this.trigger('registerViewParams', {\n        params: params,\n      });\n\n      return params;\n    },\n\n    updateElements: function (preservePagination, pageChanged) {\n      return new Promise((resolve, reject) => {\n        // Ignore if we're not fully initialized yet\n        if (!this.initialized) {\n          reject('The element index isn’t initialized yet.');\n          return;\n        }\n\n        // Cancel any ongoing requests\n        this._cancelRequests();\n\n        this.setIndexBusy();\n\n        // Kill the old view class\n        if (this.view) {\n          this.view.destroy();\n          delete this.view;\n        }\n\n        if (preservePagination !== true) {\n          this.setPage(1);\n          this._resetCount();\n        }\n\n        var params = this.getViewParams();\n\n        Craft.sendActionRequest('POST', this.settings.updateElementsAction, {\n          data: params,\n          cancelToken: this._createCancelToken(),\n        })\n          .then((response) => {\n            this.setIndexAvailable();\n\n            if (this.settings.context === 'index') {\n              if (Craft.cp.fixedHeader) {\n                const headerContainerHeight =\n                  Craft.cp.$headerContainer.height();\n                const maxScrollTop =\n                  this.$main.offset().top - headerContainerHeight;\n                if (maxScrollTop < Garnish.$scrollContainer.scrollTop()) {\n                  Garnish.$scrollContainer.scrollTop(maxScrollTop);\n                }\n              }\n            } else {\n              this.$main.scrollTop(0);\n            }\n\n            this._updateView(params, response.data);\n\n            if (pageChanged) {\n              const $elementContainer = this.view.getElementContainer();\n              Garnish.firstFocusableElement($elementContainer).trigger('focus');\n            }\n\n            resolve();\n          })\n          .catch((e) => {\n            if (!axios.isCancel(e)) {\n              this.setIndexAvailable();\n              Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n            }\n            reject(e);\n          });\n      });\n    },\n\n    updateElementsIfSearchTextChanged: function () {\n      if (\n        this.searchText !==\n        (this.searchText = this.searching ? this.$search.val() : null)\n      ) {\n        if (this.settings.context === 'index') {\n          Craft.setQueryParam('search', this.$search.val());\n        }\n        this.updateElements();\n      }\n    },\n\n    showActionTriggers: function () {\n      // Ignore if they're already shown\n      if (this.showingActionTriggers) {\n        return;\n      }\n\n      if (!this._$triggers) {\n        this._createTriggers();\n      } else {\n        this._$triggers.appendTo(this.$actionsContainer);\n      }\n\n      this.showingActionTriggers = true;\n    },\n\n    submitAction: function (action, actionParams) {\n      // Make sure something's selected\n      var selectedElementIds = this.view.getSelectedElementIds(),\n        totalSelected = selectedElementIds.length;\n\n      if (totalSelected === 0) {\n        return;\n      }\n\n      if (typeof action === 'string') {\n        action = this._findAction(action);\n      }\n\n      if (action.confirm && !confirm(action.confirm)) {\n        return;\n      }\n\n      // Cancel any ongoing requests\n      this._cancelRequests();\n\n      // Get ready to submit\n      var viewParams = this.getViewParams();\n\n      actionParams = actionParams ? Craft.expandPostArray(actionParams) : {};\n      var params = $.extend(viewParams, action.settings || {}, actionParams, {\n        elementAction: action.type,\n        elementIds: selectedElementIds,\n      });\n\n      // Do it\n      this.setIndexBusy();\n      this._autoSelectElements = selectedElementIds;\n\n      if (action.download) {\n        if (Craft.csrfTokenName) {\n          params[Craft.csrfTokenName] = Craft.csrfTokenValue;\n        }\n        Craft.downloadFromUrl(\n          'POST',\n          Craft.getActionUrl(this.settings.submitActionsAction),\n          params\n        )\n          .then((response) => {\n            this.setIndexAvailable();\n          })\n          .catch((e) => {\n            this.setIndexAvailable();\n          });\n      } else {\n        Craft.sendActionRequest('POST', this.settings.submitActionsAction, {\n          data: params,\n          cancelToken: this._createCancelToken(),\n        })\n          .then((response) => {\n            // Update the count text too\n            this._resetCount();\n            this._updateView(viewParams, response.data);\n\n            if (typeof response.data.badgeCounts !== 'undefined') {\n              this._updateBadgeCounts(response.data.badgeCounts);\n            }\n\n            if (response.data.message) {\n              Craft.cp.displaySuccess(response.data.message);\n            }\n\n            this.afterAction(action, params);\n          })\n          .catch(({response}) => {\n            Craft.cp.displayError(response.data.message);\n          })\n          .finally(() => {\n            this.setIndexAvailable();\n          });\n      }\n    },\n\n    _findAction: function (actionClass) {\n      for (var i = 0; i < this.actions.length; i++) {\n        if (this.actions[i].type === actionClass) {\n          return this.actions[i];\n        }\n      }\n      throw `Invalid element action: ${actionClass}`;\n    },\n\n    afterAction: function (action, params) {\n      // There may be a new background job that needs to be run\n      Craft.cp.runQueue();\n\n      this.onAfterAction(action, params);\n    },\n\n    hideActionTriggers: function () {\n      // Ignore if there aren't any\n      if (!this.showingActionTriggers) {\n        return;\n      }\n\n      this._$triggers.detach();\n\n      this.showingActionTriggers = false;\n    },\n\n    updateActionTriggers: function () {\n      // Do we have an action UI to update?\n      if (this.actions) {\n        var totalSelected = this.view.getSelectedElements().length;\n\n        if (totalSelected !== 0) {\n          if (totalSelected === this.view.getEnabledElements().length) {\n            this.$selectAllCheckbox.removeClass('indeterminate');\n            this.$selectAllCheckbox.addClass('checked');\n            this.$selectAllCheckbox.attr('aria-checked', 'true');\n          } else {\n            this.$selectAllCheckbox.addClass('indeterminate');\n            this.$selectAllCheckbox.removeClass('checked');\n            this.$selectAllCheckbox.attr('aria-checked', 'mixed');\n          }\n\n          this.showActionTriggers();\n        } else {\n          this.$selectAllCheckbox.removeClass('indeterminate checked');\n          this.$selectAllCheckbox.attr('aria-checked', 'false');\n          this.hideActionTriggers();\n        }\n      }\n    },\n\n    getSelectedElements: function () {\n      return this.view ? this.view.getSelectedElements() : $();\n    },\n\n    getSelectedElementIds: function () {\n      return this.view ? this.view.getSelectedElementIds() : [];\n    },\n\n    setStatus: function (status) {\n      // Find the option (and make sure it actually exists)\n      var $option = this.statusMenu.$options.filter(\n        'a[data-status=\"' + status + '\"]:first'\n      );\n\n      if ($option.length) {\n        this.statusMenu.selectOption($option[0]);\n      }\n    },\n\n    /**\n     * Returns the selected sort attribute for a source\n     * @param {jQuery} [$source]\n     * @returns {string}\n     */\n    getSelectedSortAttribute: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n\n      if ($source) {\n        const attribute = this.getSourceState($source.data('key'), 'order');\n\n        // Make sure it's valid\n        if (this.getSortOption(attribute, $source)) {\n          return attribute;\n        }\n      }\n\n      return this.getDefaultSort()[0];\n    },\n\n    /**\n     * Returns the selected sort direction for a source\n     * @param {jQuery} [$source]\n     * @returns {string}\n     */\n    getSelectedSortDirection: function ($source) {\n      $source = $source || this.$source;\n      if ($source) {\n        const direction = this.getSourceState($source.data('key'), 'sort');\n\n        // Make sure it's valid\n        if (['asc', 'desc'].includes(direction)) {\n          return direction;\n        }\n      }\n\n      return this.getDefaultSort()[1];\n    },\n\n    /**\n     * @deprecated in 4.3.0. Use setSelectedSortAttribute() instead.\n     */\n    setSortAttribute: function (attr) {\n      this.setSelectedSortAttribute(attr);\n    },\n\n    /**\n     * Sets the selected sort attribute and direction.\n     *\n     * If direction isn’t provided, the attribute’s default direction will be used.\n     *\n     * @param {string} attr\n     * @param {string} [dir]\n     */\n    setSelectedSortAttribute: function (attr, dir) {\n      // If score, keep track of that separately\n      if (attr === 'score') {\n        this.sortByScore = true;\n        if (this.activeViewMenu) {\n          this.activeViewMenu.updateSortField();\n        }\n        return;\n      }\n\n      this.sortByScore = false;\n\n      // Make sure it's valid\n      const sortOption = this.getSortOption(attr);\n      if (!sortOption) {\n        console.warn(`Invalid sort option: ${attr}`);\n        return;\n      }\n\n      if (!dir) {\n        dir = sortOption.defaultDir;\n      }\n\n      const history = [];\n\n      // Remember the previous choices\n      const attributes = [attr];\n\n      // Only include the last attribute if it changed\n      const lastAttr = this.getSelectedSourceState('order');\n      if (lastAttr && lastAttr !== attr) {\n        history.push([lastAttr, this.getSelectedSourceState('sort')]);\n        attributes.push(lastAttr);\n      }\n\n      const oldHistory = this.getSelectedSourceState('orderHistory', []);\n      for (let i = 0; i < oldHistory.length; i++) {\n        const [a] = oldHistory[i];\n        if (a && !attributes.includes(a)) {\n          history.push(oldHistory[i]);\n          attributes.push(a);\n        } else {\n          break;\n        }\n      }\n\n      this.setSelecetedSourceState({\n        order: attr,\n        sort: dir,\n        orderHistory: history,\n      });\n\n      // Update the view menu\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n\n      if (this.settings.context === 'index') {\n        // Update the query string\n        Craft.setQueryParam('sort', `${attr}-${dir}`);\n      }\n    },\n\n    /**\n     * @deprecated in 4.3.0. Use setSelectedSortAttribute() or setSelectedSortDirection() instead.\n     */\n    setSortDirection: function (dir) {\n      this.setSelectedSortDirection(dir);\n    },\n\n    /**\n     * Sets the selected sort direction, maintaining the current sort attribute.\n     * @param {string} dir\n     */\n    setSelectedSortDirection: function (dir) {\n      this.setSelectedSortAttribute(this.getSelectedSortAttribute(), dir);\n    },\n\n    /**\n     * Returns whether we can use the structure view for the current state.\n     * @returns {boolean}\n     */\n    canSortByStructure: function () {\n      return !this.trashed && !this.drafts && !this.searching;\n    },\n\n    /**\n     * Returns the actual sort attribute, which may be different from what's selected.\n     * @returns {string[]}\n     */\n    getSortAttributeAndDirection: function () {\n      if (this.searching && this.sortByScore) {\n        return ['score', 'desc'];\n      }\n\n      return [this.getSelectedSortAttribute(), this.getSelectedSortDirection()];\n    },\n\n    getSortLabel: function (attr) {\n      const sortOption = this.getSortOption(attr);\n      return sortOption ? sortOption.label : null;\n    },\n\n    getSelectedViewMode: function () {\n      return this.getSelectedSourceState('mode') || 'table';\n    },\n\n    /**\n     * Returns the nesting level for a given source, where 1 = the root level\n     * @param {jQuery} $source\n     * @returns {number}\n     */\n    getSourceLevel: function ($source) {\n      return $source.parentsUntil('nav', 'ul.nested').length + 1;\n    },\n\n    /**\n     * Returns a source’s parent, or null if it’s the root source\n     * @param {jQuery} $source\n     * @returns {?jQuery}\n     */\n    getParentSource: function ($source) {\n      const $parent = $source.parent().parent().siblings('a');\n      return $parent.length ? $parent : null;\n    },\n\n    /**\n     * Returns the root level source for a given source.\n     * @param {jQuery} $source\n     * @returns {jQuery}\n     */\n    getRootSource: function ($source) {\n      let $parent;\n      while (($parent = this.getParentSource($source))) {\n        $source = $parent;\n      }\n      return $source;\n    },\n\n    getSourceByKey: function (key) {\n      return this.sourcesByKey[key] || null;\n    },\n\n    selectSource: function (source) {\n      const $source = $(source);\n\n      // return false if there truly are no sources;\n      // don't attempt to check only default/visible sources\n      if (!this.sourcesByKey || !Object.keys(this.sourcesByKey).length) {\n        return false;\n      }\n\n      if (\n        this.$source &&\n        this.$source[0] &&\n        this.$source[0] === $source[0] &&\n        $source.data('key') === this.sourceKey\n      ) {\n        return false;\n      }\n\n      // Hide action triggers if they're currently being shown\n      this.hideActionTriggers();\n\n      this.$source = $source;\n      this.$rootSource = this.getRootSource($source);\n      this.sourceKey = $source.data('key');\n      this.rootSourceKey = this.$rootSource.data('key');\n      this.setInstanceState('selectedSource', this.sourceKey);\n      this.sourceSelect.selectItem($source);\n\n      Craft.cp.updateContentHeading();\n\n      if (this.searching) {\n        // Clear the search value without causing it to update elements\n        this.searchText = null;\n        this.$search.val('');\n        if (this.settings.context === 'index') {\n          Craft.setQueryParam('search', null);\n        }\n        this.stopSearching();\n      }\n\n      // Status menu\n      // ----------------------------------------------------------------------\n\n      if (this.$statusMenuBtn.length) {\n        if (Garnish.hasAttr(this.$source, 'data-override-status')) {\n          this.$statusMenuContainer.addClass('hidden');\n        } else {\n          this.$statusMenuContainer.removeClass('hidden');\n        }\n\n        if (this.trashed) {\n          // Swap to the initial status\n          var $firstOption = this.statusMenu.$options.first();\n          this.setStatus($firstOption.data('status'));\n        }\n      }\n\n      // View mode buttons\n      // ----------------------------------------------------------------------\n\n      // Clear out any previous view mode data\n      if (this.$viewModeBtnContainer) {\n        this.$viewModeBtnContainer.remove();\n      }\n\n      this.viewModeBtns = {};\n      this.viewMode = null;\n\n      // Get the new list of view modes\n      this.sourceViewModes = this.getViewModesForSource();\n\n      // Create the buttons if there's more than one mode available to this source\n      if (this.sourceViewModes.length > 1) {\n        this.$viewModeBtnContainer = $(\n          '<section class=\"btngroup btngroup--exclusive\"/>'\n        )\n          .attr('aria-label', Craft.t('app', 'View'))\n          .insertAfter(this.$searchContainer);\n\n        for (var i = 0; i < this.sourceViewModes.length; i++) {\n          let sourceViewMode = this.sourceViewModes[i];\n\n          let $viewModeBtn = $('<button/>', {\n            type: 'button',\n            class:\n              'btn' +\n              (typeof sourceViewMode.className !== 'undefined'\n                ? ` ${sourceViewMode.className}`\n                : ''),\n            'data-view': sourceViewMode.mode,\n            'data-icon': sourceViewMode.icon,\n            'aria-label': sourceViewMode.title,\n            'aria-pressed': 'false',\n            title: sourceViewMode.title,\n          }).appendTo(this.$viewModeBtnContainer);\n\n          this.viewModeBtns[sourceViewMode.mode] = $viewModeBtn;\n\n          this.addListener(\n            $viewModeBtn,\n            'click',\n            {mode: sourceViewMode.mode},\n            function (ev) {\n              this.selectViewMode(ev.data.mode);\n              this.updateElements();\n            }\n          );\n        }\n      }\n\n      // Figure out which mode we should start with\n      var viewMode = this.getSelectedSourceState('mode');\n\n      // Maintain the structure view for source states that were saved with an older Craft version\n      if (\n        viewMode === 'table' &&\n        this.getSourceState($source.data('key'), 'order') === 'structure'\n      ) {\n        viewMode = 'structure';\n      }\n\n      if (!viewMode || !this.doesSourceHaveViewMode(viewMode)) {\n        // Try to keep using the current view mode\n        if (this.viewMode && this.doesSourceHaveViewMode(this.viewMode)) {\n          viewMode = this.viewMode;\n        }\n        // Just use the first one\n        else {\n          viewMode = this.sourceViewModes[0].mode;\n        }\n      }\n\n      this.selectViewMode(viewMode);\n\n      this.updateSourceMenu();\n      this.updateViewMenu();\n      this.updateFilterBtn();\n\n      this.sourcePath = this.$source.data('default-source-path');\n\n      this.onSelectSource();\n\n      if (this.settings.context === 'index') {\n        const urlParams = Craft.getQueryParams();\n        urlParams.source = this.sourceKey;\n        Craft.setUrl(Craft.getUrl(Craft.path, urlParams));\n      }\n\n      return true;\n    },\n\n    selectSourceByKey: function (key) {\n      var $source = this.getSourceByKey(key);\n\n      if ($source) {\n        return this.selectSource($source);\n      } else {\n        return false;\n      }\n    },\n\n    /**\n     * Returns the available sort attributes for a source (or the selected root source)\n     * @param {jQuery} [$source]\n     * @returns {Object[]}\n     */\n    getSortOptions: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      const sortOptions = ($source ? $source.data('sort-opts') : null) || [];\n\n      // Make sure there's at least one attribute\n      if (!sortOptions.length) {\n        sortOptions.push({\n          label: Craft.t('app', 'Title'),\n          attr: 'title',\n          defaultDir: 'asc',\n        });\n      }\n\n      return sortOptions;\n    },\n\n    /**\n     * Returns info about a sort attribute.\n     * @param {string} attribute\n     * @param {jQuery} [$source]\n     * @returns {?Object}\n     */\n    getSortOption: function (attribute, $source) {\n      return (\n        this.getSortOptions($source).find((o) => o.attr === attribute) || null\n      );\n    },\n\n    /**\n     * Returns the default sort attribute and direction for a source.\n     * @param {jQuery} [$source]\n     * @returns {string[]}\n     */\n    getDefaultSort: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      if ($source) {\n        let defaultSort = $source.data('default-sort');\n        if (defaultSort) {\n          if (typeof defaultSort === 'string') {\n            defaultSort = [defaultSort];\n          }\n\n          // Make sure it's valid\n          const sortOption = this.getSortOption(defaultSort[0], $source);\n          if (sortOption) {\n            // Fill in the default direction if it's not specified\n            if (!defaultSort[1]) {\n              defaultSort[1] = sortOption.defaultDir;\n            }\n\n            return defaultSort;\n          }\n        }\n      }\n\n      // Default to the first sort option\n      const sortOptions = this.getSortOptions($source);\n      return [sortOptions[0].attr, sortOptions[0].defaultDir];\n    },\n\n    /**\n     * Returns the available table columns for a source (or the selected root source)\n     * @param {jQuery} [$source]\n     * @returns {Object[]}\n     */\n    getTableColumnOptions: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      return ($source ? $source.data('table-col-opts') : null) || [];\n    },\n\n    /**\n     * Returns info about a table column.\n     * @param {string} attribute\n     * @param {jQuery} [$source]\n     * @returns {?Object}\n     */\n    getTableColumnOption: function (attribute, $source) {\n      return (\n        this.getTableColumnOptions($source).find((o) => o.attr === attribute) ||\n        null\n      );\n    },\n\n    /**\n     * Returns the default table columns for a source (or the selected root source)\n     * @param {jQuery} [$source]\n     * @returns {string[]}\n     */\n    getDefaultTableColumns: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      return ($source ? $source.data('default-table-cols') : null) || [];\n    },\n\n    /**\n     * Returns the selected sort attribute for a source\n     * @param {jQuery} [$source]\n     * @returns {string[]}\n     */\n    getSelectedTableColumns: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      if ($source) {\n        const attributes = this.getSourceState(\n          $source.data('key'),\n          'tableColumns'\n        );\n\n        if (attributes) {\n          // Only return the valid ones\n          return attributes.filter(\n            (a) => !!this.getTableColumnOption(a, $source)\n          );\n        }\n      }\n\n      return this.getDefaultTableColumns($source);\n    },\n\n    setSelectedTableColumns: function (attributes) {\n      this.setSelecetedSourceState({\n        tableColumns: attributes,\n      });\n\n      // Update the view menu\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateTableColumnField();\n      }\n    },\n\n    getViewModesForSource: function () {\n      var viewModes = [];\n\n      if (Garnish.hasAttr(this.$source, 'data-has-structure')) {\n        viewModes.push({\n          mode: 'structure',\n          title: Craft.t('app', 'Display in a structured table'),\n          icon: Craft.orientation === 'rtl' ? 'structurertl' : 'structure',\n        });\n      }\n\n      viewModes.push({\n        mode: 'table',\n        title: Craft.t('app', 'Display in a table'),\n        icon: 'list',\n      });\n\n      if (this.$source && Garnish.hasAttr(this.$source, 'data-has-thumbs')) {\n        viewModes.push({\n          mode: 'thumbs',\n          title: Craft.t('app', 'Display as thumbnails'),\n          icon: 'grid',\n        });\n      }\n\n      return viewModes;\n    },\n\n    doesSourceHaveViewMode: function (viewMode) {\n      for (var i = 0; i < this.sourceViewModes.length; i++) {\n        if (this.sourceViewModes[i].mode === viewMode) {\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    selectViewMode: function (viewMode, force) {\n      // Make sure that the current source supports it\n      if (!force && !this.doesSourceHaveViewMode(viewMode)) {\n        viewMode = this.sourceViewModes[0].mode;\n      }\n\n      // Has anything changed?\n      if (viewMode === this._viewMode) {\n        return;\n      }\n\n      // Deselect the previous view mode\n      if (\n        this._viewMode &&\n        typeof this.viewModeBtns[this._viewMode] !== 'undefined'\n      ) {\n        this.viewModeBtns[this._viewMode]\n          .removeClass('active')\n          .attr('aria-pressed', 'false');\n      }\n\n      this._viewMode = viewMode;\n      this.setSelecetedSourceState('mode', this._viewMode);\n\n      if (typeof this.viewModeBtns[this._viewMode] !== 'undefined') {\n        this.viewModeBtns[this._viewMode]\n          .addClass('active')\n          .attr('aria-pressed', 'true');\n      }\n\n      // Update the view menu\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n    },\n\n    createView: function (mode, settings) {\n      var viewClass = this.getViewClass(mode);\n      return new viewClass(this, this.$elements, settings);\n    },\n\n    getViewClass: function (mode) {\n      switch (mode) {\n        case 'table':\n        case 'structure':\n          return Craft.TableElementIndexView;\n        case 'thumbs':\n          return Craft.ThumbsElementIndexView;\n        default:\n          throw `View mode \"${mode}\" not supported.`;\n      }\n    },\n\n    rememberDisabledElementId: function (id) {\n      var index = $.inArray(id, this.settings.disabledElementIds);\n\n      if (index === -1) {\n        this.settings.disabledElementIds.push(id);\n      }\n    },\n\n    forgetDisabledElementId: function (id) {\n      var index = $.inArray(id, this.settings.disabledElementIds);\n\n      if (index !== -1) {\n        this.settings.disabledElementIds.splice(index, 1);\n      }\n    },\n\n    enableElements: function ($elements) {\n      $elements\n        .removeClass('disabled')\n        .parents('.disabled')\n        .removeClass('disabled');\n\n      for (var i = 0; i < $elements.length; i++) {\n        var id = $($elements[i]).data('id');\n        this.forgetDisabledElementId(id);\n      }\n\n      this.onEnableElements($elements);\n    },\n\n    disableElements: function ($elements) {\n      $elements.removeClass('sel').addClass('disabled');\n\n      for (var i = 0; i < $elements.length; i++) {\n        var id = $($elements[i]).data('id');\n        this.rememberDisabledElementId(id);\n      }\n\n      this.onDisableElements($elements);\n    },\n\n    getElementById: function (id) {\n      return this.view.getElementById(id);\n    },\n\n    enableElementsById: function (ids) {\n      ids = $.makeArray(ids);\n\n      for (var i = 0; i < ids.length; i++) {\n        var id = ids[i],\n          $element = this.getElementById(id);\n\n        if ($element && $element.length) {\n          this.enableElements($element);\n        } else {\n          this.forgetDisabledElementId(id);\n        }\n      }\n    },\n\n    disableElementsById: function (ids) {\n      ids = $.makeArray(ids);\n\n      for (var i = 0; i < ids.length; i++) {\n        var id = ids[i],\n          $element = this.getElementById(id);\n\n        if ($element && $element.length) {\n          this.disableElements($element);\n        } else {\n          this.rememberDisabledElementId(id);\n        }\n      }\n    },\n\n    selectElementAfterUpdate: function (id) {\n      if (this._autoSelectElements === null) {\n        this._autoSelectElements = [];\n      }\n\n      this._autoSelectElements.push(id);\n    },\n\n    addButton: function ($button) {\n      this.getButtonContainer().append($button);\n    },\n\n    isShowingSidebar: function () {\n      if (this.showingSidebar === null) {\n        this.showingSidebar =\n          this.$sidebar.length && !this.$sidebar.hasClass('hidden');\n      }\n\n      return this.showingSidebar;\n    },\n\n    getButtonContainer: function () {\n      // Is there a predesignated place where buttons should go?\n      if (this.settings.buttonContainer) {\n        return $(this.settings.buttonContainer);\n      } else {\n        var $container = $('#action-buttons');\n\n        if (!$container.length) {\n          $container = $('<div id=\"action-buttons\"/>').appendTo($('#header'));\n        }\n\n        return $container;\n      }\n    },\n\n    setIndexBusy: function () {\n      this.$elements.addClass('busy');\n      this.$updateSpinner.appendTo(this.$elements);\n      this.isIndexBusy = true;\n\n      // Blur the active element, if it's within the element listing pane\n      if (\n        document.activeElement &&\n        this.$elements[0].contains(document.activeElement)\n      ) {\n        this._activeElement = document.activeElement;\n        document.activeElement.blur();\n      }\n\n      let elementsHeight = this.$elements.height();\n      let windowHeight = window.innerHeight;\n      let scrollTop = $(document).scrollTop();\n\n      if (this.settings.context == 'modal') {\n        windowHeight = this.$elements.parents('.modal').height();\n        scrollTop = this.$elements.scrollParent().scrollTop();\n      }\n\n      if (elementsHeight > windowHeight) {\n        let positionTop = Math.floor(scrollTop + windowHeight / 2) - 100;\n        positionTop = Math.floor((positionTop / elementsHeight) * 100);\n\n        document.documentElement.style.setProperty(\n          '--elements-busy-top-position',\n          positionTop + '%'\n        );\n      }\n    },\n\n    setIndexAvailable: function () {\n      this.$elements.removeClass('busy');\n      this.$updateSpinner.remove();\n      this.isIndexBusy = false;\n\n      // Refocus the previously-focused element\n      if (this._activeElement) {\n        if (\n          !document.activeElement ||\n          document.activeElement === document.body\n        ) {\n          if (document.body.contains(this._activeElement)) {\n            this._activeElement.focus();\n          } else if (this._activeElement.id) {\n            $(`#${this._activeElement.id}`).focus();\n          }\n        }\n        this._activeElement = null;\n      }\n    },\n\n    createCustomizeSourcesModal: function () {\n      // Recreate it each time\n      var modal = new Craft.CustomizeSourcesModal(this, {\n        hideOnEsc: false,\n        hideOnShadeClick: false,\n        onHide: function () {\n          modal.destroy();\n        },\n      });\n\n      return modal;\n    },\n\n    disable: function () {\n      if (this.sourceSelect) {\n        this.sourceSelect.disable();\n      }\n\n      if (this.view) {\n        this.view.disable();\n      }\n\n      this.base();\n    },\n\n    enable: function () {\n      if (this.sourceSelect) {\n        this.sourceSelect.enable();\n      }\n\n      if (this.view) {\n        this.view.enable();\n      }\n\n      this.base();\n    },\n\n    onAfterInit: function () {\n      this.settings.onAfterInit();\n      this.trigger('afterInit');\n    },\n\n    onSelectSource: function () {\n      this.settings.onSelectSource(this.sourceKey);\n      this.trigger('selectSource', {sourceKey: this.sourceKey});\n    },\n\n    onSelectSite: function () {\n      this.settings.onSelectSite(this.siteId);\n      this.trigger('selectSite', {siteId: this.siteId});\n    },\n\n    onUpdateElements: function () {\n      this.settings.onUpdateElements();\n      this.trigger('updateElements');\n    },\n\n    onSelectionChange: function () {\n      this.settings.onSelectionChange();\n      this.trigger('selectionChange');\n    },\n\n    onEnableElements: function ($elements) {\n      this.settings.onEnableElements($elements);\n      this.trigger('enableElements', {elements: $elements});\n    },\n\n    onDisableElements: function ($elements) {\n      this.settings.onDisableElements($elements);\n      this.trigger('disableElements', {elements: $elements});\n    },\n\n    onAfterAction: function (action, params) {\n      this.settings.onAfterAction(action, params);\n      this.trigger('afterAction', {action: action, params: params});\n    },\n\n    // UI state handlers\n    // -------------------------------------------------------------------------\n\n    _handleSourceSelectionChange: function () {\n      // If the selected source was just removed (maybe because its parent was collapsed),\n      // there won't be a selected source\n      if (!this.sourceSelect.totalSelected) {\n        this.sourceSelect.selectItem(this.$visibleSources.first());\n        return;\n      }\n\n      if (this.selectSource(this.sourceSelect.$selectedItems)) {\n        this.updateElements();\n      }\n    },\n\n    _handleActionTriggerSubmit: function (ev) {\n      ev.preventDefault();\n\n      var $form = $(ev.currentTarget);\n\n      // Make sure Craft.ElementActionTrigger isn't overriding this\n      if ($form.hasClass('disabled') || $form.data('custom-handler')) {\n        return;\n      }\n\n      this.submitAction($form.data('action'), Garnish.getPostData($form));\n    },\n\n    _handleMenuActionTriggerSubmit: function (ev) {\n      var $option = $(ev.option);\n\n      // Make sure Craft.ElementActionTrigger isn't overriding this\n      if ($option.hasClass('disabled') || $option.data('custom-handler')) {\n        return;\n      }\n\n      this.submitAction($option.data('action'));\n    },\n\n    _handleStatusChange: function (ev) {\n      this.statusMenu.$options.removeClass('sel');\n      var $option = $(ev.selectedOption).addClass('sel');\n      this.$statusMenuBtn.html($option.html());\n\n      this.trashed = false;\n      this.drafts = false;\n      this.status = null;\n      let queryParam = null;\n\n      if (Garnish.hasAttr($option, 'data-trashed')) {\n        this.trashed = true;\n        queryParam = 'trashed';\n      } else if (Garnish.hasAttr($option, 'data-drafts')) {\n        this.drafts = true;\n        queryParam = 'drafts';\n      } else {\n        this.status = queryParam = $option.data('status') || null;\n      }\n\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n\n      if (this.settings.context === 'index') {\n        Craft.setQueryParam('status', queryParam);\n      }\n\n      this.updateElements();\n    },\n\n    _handleSiteChange: function (ev) {\n      this.siteMenu.$options.removeClass('sel');\n      var $option = $(ev.selectedOption).addClass('sel');\n      this.$siteMenuBtn.html($option.html());\n      this._setSite($option.data('site-id'));\n      if (this.initialized) {\n        this.updateElements();\n      }\n      this.onSelectSite();\n    },\n\n    _setSite: function (siteId) {\n      let firstSite = this.siteId === null;\n      this.siteId = siteId;\n\n      this.updateSourceVisibility();\n\n      if (\n        this.initialized &&\n        !firstSite &&\n        (!this.$source || !this.$source.length) &&\n        this.$visibleSources.length\n      ) {\n        this.selectSource(this.$visibleSources[0]);\n      }\n\n      // Hide any empty-nester headings\n      var $headings = this.getSourceContainer().children('.heading');\n      var $heading;\n\n      for (let i = 0; i < $headings.length; i++) {\n        $heading = $headings.eq(i);\n        if ($heading.has('> ul > li:not(.hidden)').length !== 0) {\n          $heading.removeClass('hidden');\n        } else {\n          $heading.addClass('hidden');\n        }\n      }\n\n      if (this.initialized) {\n        if (this.settings.context === 'index') {\n          // Remember this site for later\n          Craft.cp.setSiteId(siteId);\n        }\n\n        this.updateFilterBtn();\n      }\n    },\n\n    updateSourceVisibility: function () {\n      this.$visibleSources = $();\n\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = this.$sources.eq(i);\n\n        if (\n          !Garnish.hasAttr($source, 'data-disabled') &&\n          (typeof $source.data('sites') === 'undefined' ||\n            $source\n              .data('sites')\n              .toString()\n              .split(',')\n              .indexOf(this.siteId.toString()) !== -1)\n        ) {\n          $source.parent().removeClass('hidden');\n          this.$visibleSources = this.$visibleSources.add($source);\n        } else {\n          $source.parent().addClass('hidden');\n\n          // Is this the currently selected source?\n          if (this.$source && this.$source.get(0) === $source.get(0)) {\n            this.$source = null;\n            this.$rootSource = null;\n            this.sourceKey = null;\n            this.rootSourceKey = null;\n          }\n        }\n      }\n    },\n\n    _handleSelectionChange: function () {\n      this.updateActionTriggers();\n      this.onSelectionChange();\n    },\n\n    _handleSourceDblClick: function (ev) {\n      this._toggleSource($(ev.currentTarget));\n      ev.stopPropagation();\n    },\n\n    _handleSourceToggleClick: function (ev) {\n      this._toggleSource($(ev.currentTarget).prev('a'));\n      ev.stopPropagation();\n    },\n\n    // Source managemnet\n    // -------------------------------------------------------------------------\n\n    _getSourcesInList: function ($list, topLevel) {\n      let $sources = $list.find('> li:not(.heading) > a');\n      if (topLevel) {\n        $sources = $sources.add($list.find('> li.heading > ul > li > a'));\n      }\n      return $sources;\n    },\n\n    _getChildSources: function ($source) {\n      var $list = $source.siblings('ul');\n      return this._getSourcesInList($list);\n    },\n\n    _getSourceToggle: function ($source) {\n      return $source.siblings('.toggle');\n    },\n\n    _toggleSource: function ($source) {\n      if ($source.parent('li').hasClass('expanded')) {\n        this._collapseSource($source);\n      } else {\n        this._expandSource($source);\n      }\n    },\n\n    _expandSource: function ($source) {\n      $source.next('.toggle').attr({\n        'aria-expanded': 'true',\n        'aria-label': Craft.t('app', 'Hide nested sources'),\n      });\n      $source.parent('li').addClass('expanded');\n\n      var $childSources = this._getChildSources($source);\n      for (let i = 0; i < $childSources.length; i++) {\n        this.initSource($($childSources[i]));\n        if (this.$visibleSources) {\n          this.$visibleSources = this.$visibleSources.add($childSources[i]);\n        }\n      }\n\n      var key = $source.data('key');\n      if (this.instanceState.expandedSources.indexOf(key) === -1) {\n        this.instanceState.expandedSources.push(key);\n        this.storeInstanceState();\n      }\n    },\n\n    _collapseSource: function ($source) {\n      $source.next('.toggle').attr({\n        'aria-expanded': 'false',\n        'aria-label': Craft.t('app', 'Show nested sources'),\n      });\n      $source.parent('li').removeClass('expanded');\n\n      var $childSources = this._getChildSources($source);\n      for (let i = 0; i < $childSources.length; i++) {\n        this.deinitSource($($childSources[i]));\n        this.$visibleSources = this.$visibleSources.not($childSources[i]);\n      }\n\n      var i = this.instanceState.expandedSources.indexOf($source.data('key'));\n      if (i !== -1) {\n        this.instanceState.expandedSources.splice(i, 1);\n        this.storeInstanceState();\n      }\n    },\n\n    // View\n    // -------------------------------------------------------------------------\n\n    _isViewPaginated: function () {\n      return this.settings.context === 'index' && this.viewMode !== 'structure';\n    },\n\n    _updateView: function (params, response) {\n      // Cleanup\n      // -------------------------------------------------------------\n\n      // Get rid of the old action triggers regardless of whether the new batch has actions or not\n      if (this.actions) {\n        this.hideActionTriggers();\n        this.actions =\n          this.actionsHeadHtml =\n          this.actionsBodyHtml =\n          this._$triggers =\n            null;\n      }\n\n      // Update the count text\n      // -------------------------------------------------------------\n\n      if (this.$countContainer.length) {\n        this.$countSpinner.removeClass('hidden');\n        this.$countContainer.html('');\n\n        this._countResults()\n          .then((total) => {\n            this.$countSpinner.addClass('hidden');\n\n            let itemLabel = Craft.elementTypeNames[this.elementType]\n              ? Craft.elementTypeNames[this.elementType][2]\n              : this.settings.elementTypeName.toLowerCase();\n            let itemsLabel = Craft.elementTypeNames[this.elementType]\n              ? Craft.elementTypeNames[this.elementType][3]\n              : this.settings.elementTypePluralName.toLowerCase();\n\n            if (!this._isViewPaginated()) {\n              let countLabel = Craft.t(\n                'app',\n                '{total, number} {total, plural, =1{{item}} other{{items}}}',\n                {\n                  total: total,\n                  item: itemLabel,\n                  items: itemsLabel,\n                }\n              );\n              this.$countContainer.text(countLabel);\n            } else {\n              let first = Math.min(\n                this.settings.batchSize * (this.page - 1) + 1,\n                total\n              );\n              let last = Math.min(first + (this.settings.batchSize - 1), total);\n              let countLabel = Craft.t(\n                'app',\n                '{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}',\n                {\n                  first: first,\n                  last: last,\n                  total: total,\n                  item: itemLabel,\n                  items: itemsLabel,\n                }\n              );\n\n              let $paginationContainer = $(\n                '<div class=\"flex pagination\"/>'\n              ).appendTo(this.$countContainer);\n              let totalPages = Math.max(\n                Math.ceil(total / this.settings.batchSize),\n                1\n              );\n\n              const $paginationNav = $('<nav/>', {\n                class: 'flex',\n                'aria-label': Craft.t('app', '{element} pagination', {\n                  element: itemLabel,\n                }),\n              }).appendTo($paginationContainer);\n\n              let $prevBtn = $('<button/>', {\n                role: 'button',\n                class:\n                  'page-link prev-page' + (this.page > 1 ? '' : ' disabled'),\n                disabled: this.page === 1,\n                title: Craft.t('app', 'Previous Page'),\n              }).appendTo($paginationNav);\n              let $nextBtn = $('<button/>', {\n                role: 'button',\n                class:\n                  'page-link next-page' +\n                  (this.page < totalPages ? '' : ' disabled'),\n                disabled: this.page === totalPages,\n                title: Craft.t('app', 'Next Page'),\n              }).appendTo($paginationNav);\n\n              $('<div/>', {\n                class: 'page-info',\n                text: countLabel,\n              }).appendTo($paginationContainer);\n\n              if (this.page > 1) {\n                this.addListener($prevBtn, 'click', function () {\n                  this.removeListener($prevBtn, 'click');\n                  this.removeListener($nextBtn, 'click');\n                  this.setPage(this.page - 1);\n                  this.updateElements(true, true);\n                });\n              }\n\n              if (this.page < totalPages) {\n                this.addListener($nextBtn, 'click', function () {\n                  this.removeListener($prevBtn, 'click');\n                  this.removeListener($nextBtn, 'click');\n                  this.setPage(this.page + 1);\n                  this.updateElements(true, true);\n                });\n              }\n            }\n          })\n          .catch(() => {\n            this.$countSpinner.addClass('hidden');\n          });\n      }\n\n      // Update the view with the new container + elements HTML\n      // -------------------------------------------------------------\n\n      this.$elements.html(response.html);\n      Craft.appendHeadHtml(response.headHtml);\n      Craft.appendBodyHtml(response.bodyHtml);\n\n      // Batch actions setup\n      // -------------------------------------------------------------\n\n      this.$selectAllContainer = this.$elements.find(\n        '.selectallcontainer:first'\n      );\n\n      if (response.actions && response.actions.length) {\n        if (this.$selectAllContainer.length) {\n          this.actions = response.actions;\n          this.actionsHeadHtml = response.actionsHeadHtml;\n          this.actionsBodyHtml = response.actionsBodyHtml;\n\n          // Create the select all checkbox\n          this.$selectAllCheckbox = $('<div class=\"checkbox\"/>')\n            .prependTo(this.$selectAllContainer)\n            .attr({\n              role: 'checkbox',\n              tabindex: '0',\n              'aria-checked': 'false',\n              'aria-label': Craft.t('app', 'Select all'),\n            });\n\n          this.addListener(this.$selectAllCheckbox, 'click', function () {\n            if (this.view.getSelectedElements().length === 0) {\n              this.view.selectAllElements();\n            } else {\n              this.view.deselectAllElements();\n            }\n          });\n\n          this.addListener(this.$selectAllCheckbox, 'keydown', function (ev) {\n            if (ev.keyCode === Garnish.SPACE_KEY) {\n              ev.preventDefault();\n\n              $(ev.currentTarget).trigger('click');\n            }\n          });\n        }\n      } else {\n        if (!this.$selectAllContainer.siblings().length) {\n          this.$selectAllContainer.parent('.header').remove();\n        }\n        this.$selectAllContainer.remove();\n      }\n\n      // Exporters setup\n      // -------------------------------------------------------------\n\n      this.exporters = response.exporters;\n      this.exportersByType = Craft.index(this.exporters || [], (e) => e.type);\n\n      if (this.exporters && this.exporters.length) {\n        this.$exportBtn.removeClass('hidden');\n      } else {\n        this.$exportBtn.addClass('hidden');\n      }\n\n      // Create the view\n      // -------------------------------------------------------------\n\n      // Should we make the view selectable?\n      const selectable = this.actions || this.settings.selectable;\n      const settings = Object.assign(\n        {\n          context: this.settings.context,\n          batchSize:\n            this.settings.context !== 'index' || this.viewMode === 'structure'\n              ? this.settings.batchSize\n              : null,\n          params: params,\n          selectable: selectable,\n          multiSelect: this.actions || this.settings.multiSelect,\n          canSelectElement: this.settings.canSelectElement,\n          checkboxMode: !!this.actions,\n          onSelectionChange: this._handleSelectionChange.bind(this),\n        },\n        this.getViewSettings()\n      );\n\n      this.view = this.createView(this.getSelectedViewMode(), settings);\n\n      // Auto-select elements\n      // -------------------------------------------------------------\n\n      if (this._autoSelectElements) {\n        if (selectable) {\n          for (var i = 0; i < this._autoSelectElements.length; i++) {\n            this.view.selectElementById(this._autoSelectElements[i]);\n          }\n        }\n\n        this._autoSelectElements = null;\n      }\n\n      // Trigger the event\n      // -------------------------------------------------------------\n\n      this.onUpdateElements();\n    },\n\n    _updateBadgeCounts: function (badgeCounts) {\n      for (let sourceKey in badgeCounts) {\n        if (badgeCounts.hasOwnProperty(sourceKey)) {\n          const $source = this.getSourceByKey(sourceKey);\n          if ($source) {\n            let $badge = $source.children('.badge');\n            if (badgeCounts[sourceKey] !== null) {\n              if (!$badge.length) {\n                $badge = $('<span class=\"badge\"/>').appendTo($source);\n              }\n              $badge.text(badgeCounts[sourceKey]);\n            } else if ($badge) {\n              $badge.remove();\n            }\n          }\n        }\n      }\n    },\n\n    _countResults: function () {\n      return new Promise((resolve, reject) => {\n        if (this.totalResults !== null) {\n          resolve(this.totalResults);\n        } else {\n          var params = this.getViewParams();\n          delete params.criteria.offset;\n          delete params.criteria.limit;\n\n          // Make sure we've got an active result set ID\n          if (this.resultSet === null) {\n            this.resultSet = Math.floor(Math.random() * 100000000);\n          }\n          params.resultSet = this.resultSet;\n\n          Craft.sendActionRequest('POST', this.settings.countElementsAction, {\n            data: params,\n            cancelToken: this._createCancelToken(),\n          })\n            .then((response) => {\n              if (response.data.resultSet == this.resultSet) {\n                this.totalResults = response.data.count;\n                resolve(response.data.count);\n              } else {\n                reject();\n              }\n            })\n            .catch(reject);\n        }\n      });\n    },\n\n    _createTriggers: function () {\n      var triggers = [],\n        safeMenuActions = [],\n        destructiveMenuActions = [];\n\n      var i;\n\n      for (i = 0; i < this.actions.length; i++) {\n        var action = this.actions[i];\n\n        if (action.trigger) {\n          var $form = $(\n            '<form id=\"' +\n              Craft.formatInputId(action.type) +\n              '-actiontrigger\"/>'\n          )\n            .data('action', action)\n            .append(action.trigger);\n\n          $form.find('.btn').addClass('secondary');\n\n          this.addListener($form, 'submit', '_handleActionTriggerSubmit');\n          triggers.push($form);\n        } else {\n          if (!action.destructive) {\n            safeMenuActions.push(action);\n          } else {\n            destructiveMenuActions.push(action);\n          }\n        }\n      }\n\n      var $btn;\n\n      if (safeMenuActions.length || destructiveMenuActions.length) {\n        var $menuTrigger = $('<form/>');\n\n        $btn = $('<button/>', {\n          type: 'button',\n          class: 'btn secondary menubtn',\n          'data-icon': 'settings',\n          title: Craft.t('app', 'Actions'),\n        }).appendTo($menuTrigger);\n\n        var $menu = $('<ul class=\"menu\"/>').appendTo($menuTrigger),\n          $safeList = this._createMenuTriggerList(safeMenuActions, false),\n          $destructiveList = this._createMenuTriggerList(\n            destructiveMenuActions,\n            true\n          );\n\n        if ($safeList) {\n          $safeList.appendTo($menu);\n        }\n\n        if ($safeList && $destructiveList) {\n          $('<hr/>').appendTo($menu);\n        }\n\n        if ($destructiveList) {\n          $destructiveList.appendTo($menu);\n        }\n\n        triggers.push($menuTrigger);\n      }\n\n      this._$triggers = $();\n\n      for (i = 0; i < triggers.length; i++) {\n        var $div = $('<div/>').append(triggers[i]);\n        this._$triggers = this._$triggers.add($div);\n      }\n\n      this._$triggers.appendTo(this.$actionsContainer);\n      Craft.appendHeadHtml(this.actionsHeadHtml);\n      Craft.appendBodyHtml(this.actionsBodyHtml);\n\n      Craft.initUiElements(this._$triggers);\n\n      if ($btn) {\n        $btn\n          .data('menubtn')\n          .on('optionSelect', this._handleMenuActionTriggerSubmit.bind(this));\n      }\n    },\n\n    _showExportHud: function () {\n      this.$exportBtn.addClass('active');\n      this.$exportBtn.attr('aria-expanded', 'true');\n\n      var $form = $('<form/>', {\n        class: 'export-form',\n      });\n\n      var typeOptions = [];\n      for (var i = 0; i < this.exporters.length; i++) {\n        typeOptions.push({\n          label: this.exporters[i].name,\n          value: this.exporters[i].type,\n        });\n      }\n      var $typeField = Craft.ui\n        .createSelectField({\n          label: Craft.t('app', 'Export Type'),\n          options: typeOptions,\n          class: 'fullwidth',\n        })\n        .appendTo($form);\n\n      var $formatField = Craft.ui\n        .createSelectField({\n          label: Craft.t('app', 'Format'),\n          options: [\n            {label: 'CSV', value: 'csv'},\n            {label: 'JSON', value: 'json'},\n            {label: 'XML', value: 'xml'},\n          ],\n          class: 'fullwidth',\n        })\n        .appendTo($form);\n\n      let $typeSelect = $typeField.find('select');\n      this.addListener($typeSelect, 'change', () => {\n        let type = $typeSelect.val();\n        if (this.exportersByType[type].formattable) {\n          $formatField.removeClass('hidden');\n        } else {\n          $formatField.addClass('hidden');\n        }\n      });\n      $typeSelect.trigger('change');\n\n      // Only show the Limit field if there aren't any selected elements\n      var selectedElementIds = this.view.getSelectedElementIds();\n\n      if (!selectedElementIds.length) {\n        var $limitField = Craft.ui\n          .createTextField({\n            label: Craft.t('app', 'Limit'),\n            placeholder: Craft.t('app', 'No limit'),\n            type: 'number',\n            min: 1,\n          })\n          .appendTo($form);\n      }\n\n      const $submitBtn = Craft.ui\n        .createSubmitButton({\n          class: 'fullwidth',\n          label: Craft.t('app', 'Export'),\n          spinner: true,\n        })\n        .appendTo($form);\n\n      const $exportSubmit = new Garnish.MultiFunctionBtn($submitBtn);\n\n      var hud = new Garnish.HUD(this.$exportBtn, $form);\n\n      hud.on('hide', () => {\n        this.$exportBtn.removeClass('active');\n        this.$exportBtn.attr('aria-expanded', 'false');\n      });\n\n      var submitting = false;\n\n      this.addListener($form, 'submit', function (ev) {\n        ev.preventDefault();\n        if (submitting) {\n          return;\n        }\n\n        submitting = true;\n        $exportSubmit.busyEvent();\n\n        var params = this.getViewParams();\n        delete params.criteria.offset;\n        delete params.criteria.limit;\n        delete params.collapsedElementIds;\n\n        params.type = $typeField.find('select').val();\n        params.format = $formatField.find('select').val();\n\n        if (selectedElementIds.length) {\n          params.criteria.id = selectedElementIds;\n        } else {\n          var limit = parseInt($limitField.find('input').val());\n          if (limit && !isNaN(limit)) {\n            params.criteria.limit = limit;\n          }\n        }\n\n        if (Craft.csrfTokenValue) {\n          params[Craft.csrfTokenName] = Craft.csrfTokenValue;\n        }\n\n        Craft.downloadFromUrl(\n          'POST',\n          Craft.getActionUrl('element-indexes/export'),\n          params\n        )\n          .catch((e) => {\n            if (!axios.isCancel(e)) {\n              Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n            }\n          })\n          .finally(() => {\n            submitting = false;\n            $exportSubmit.successEvent();\n          });\n      });\n    },\n\n    _createMenuTriggerList: function (actions, destructive) {\n      if (actions && actions.length) {\n        var $ul = $('<ul/>');\n\n        for (var i = 0; i < actions.length; i++) {\n          $('<li/>')\n            .append(\n              $('<a/>', {\n                id: Craft.formatInputId(actions[i].type) + '-actiontrigger',\n                class: destructive ? 'error' : null,\n                data: {\n                  action: actions[i],\n                },\n                text: actions[i].name,\n              })\n            )\n            .appendTo($ul);\n        }\n\n        return $ul;\n      }\n    },\n\n    showFilterHud: function () {\n      if (!this.filterHuds[this.siteId]) {\n        this.filterHuds[this.siteId] = {};\n      }\n      if (!this.filterHuds[this.siteId][this.sourceKey]) {\n        this.filterHuds[this.siteId][this.sourceKey] = new FilterHud(\n          this,\n          this.sourceKey,\n          this.siteId\n        );\n        this.updateFilterBtn();\n      } else {\n        this.filterHuds[this.siteId][this.sourceKey].show();\n      }\n    },\n\n    updateFilterBtn: function () {\n      this.$filterBtn.removeClass('active');\n\n      if (\n        this.filterHuds[this.siteId] &&\n        this.filterHuds[this.siteId][this.sourceKey]\n      ) {\n        this.$filterBtn\n          .attr(\n            'aria-controls',\n            this.filterHuds[this.siteId][this.sourceKey].id\n          )\n          .attr(\n            'aria-expanded',\n            this.filterHuds[this.siteId][this.sourceKey].showing\n              ? 'true'\n              : 'false'\n          );\n\n        if (\n          this.filterHuds[this.siteId][this.sourceKey].showing ||\n          this.filterHuds[this.siteId][this.sourceKey].hasRules()\n        ) {\n          this.$filterBtn.addClass('active');\n        }\n      } else {\n        this.$filterBtn.attr('aria-controls', null);\n      }\n    },\n  },\n  {\n    defaults: {\n      context: 'index',\n      modal: null,\n      storageKey: null,\n      condition: null,\n      referenceElementId: null,\n      referenceElementSiteId: null,\n      criteria: null,\n      batchSize: 100,\n      disabledElementIds: [],\n      selectable: false,\n      multiSelect: false,\n      canSelectElement: null,\n      buttonContainer: null,\n      hideSidebar: false,\n      toolbarSelector: '.toolbar:first',\n      refreshSourcesAction: 'element-indexes/get-source-tree-html',\n      updateElementsAction: 'element-indexes/get-elements',\n      countElementsAction: 'element-indexes/count-elements',\n      submitActionsAction: 'element-indexes/perform-action',\n      defaultSiteId: null,\n      defaultSource: null,\n      defaultSourcePath: null,\n      showSourcePath: true,\n      canHaveDrafts: false,\n\n      elementTypeName: Craft.t('app', 'Element'),\n      elementTypePluralName: Craft.t('app', 'Elements'),\n\n      onAfterInit: $.noop,\n      onSelectSource: $.noop,\n      onSelectSite: $.noop,\n      onUpdateElements: $.noop,\n      onSelectionChange: $.noop,\n      onSourcePathChange: $.noop,\n      onEnableElements: $.noop,\n      onDisableElements: $.noop,\n      onAfterAction: $.noop,\n    },\n  }\n);\n\nconst ViewMenu = Garnish.Base.extend({\n  elementIndex: null,\n  $source: null,\n  sourceKey: null,\n  menu: null,\n  id: null,\n\n  $trigger: null,\n  $container: null,\n  $sortField: null,\n  $sortAttributeSelect: null,\n  $sortDirectionPicker: null,\n  sortDirectionListbox: null,\n  $tableColumnsField: null,\n  $tableColumnsContainer: null,\n  $revertContainer: null,\n  $revertBtn: null,\n  $closeBtn: null,\n\n  init: function (elementIndex, $source) {\n    this.elementIndex = elementIndex;\n    this.$source = $source;\n    this.sourceKey = $source.data('key');\n    this.id = `view-menu-${Math.floor(Math.random() * 1000000000)}`;\n\n    this.$trigger = $('<button/>', {\n      type: 'button',\n      class: 'btn menubtn hidden',\n      text: Craft.t('app', 'View'),\n      'aria-label': Craft.t('app', 'View settings'),\n      'aria-controls': this.id,\n      'data-icon': 'sliders',\n    }).appendTo(this.elementIndex.$toolbar);\n\n    this.$container = $('<div/>', {\n      id: this.id,\n      class: 'menu menu--disclosure element-index-view-menu',\n      'data-align': 'right',\n    }).appendTo(Garnish.$bod);\n\n    this._buildMenu();\n\n    this.addListener(this.$container, 'mousedown', (ev) => {\n      ev.stopPropagation();\n    });\n\n    this.menu = new Garnish.DisclosureMenu(this.$trigger);\n\n    this.menu.on('show', () => {\n      this.$trigger.addClass('active');\n    });\n\n    this.menu.on('hide', () => {\n      this.$trigger.removeClass('active');\n\n      // Move all checked table column checkboxes to the top once it's fully faded out\n      setTimeout(() => {\n        this.tidyTableColumnField();\n      }, Garnish.FX_DURATION);\n    });\n  },\n\n  showTrigger: function () {\n    this.$trigger.removeClass('hidden');\n  },\n\n  hideTrigger: function () {\n    this.$trigger.data('trigger').hide();\n    this.$trigger.addClass('hidden');\n    this.menu.hide();\n  },\n\n  updateSortField: function () {\n    if (this.$sortField) {\n      if (this.elementIndex.viewMode === 'structure') {\n        this.$sortField.addClass('hidden');\n        this.$tableColumnsField.addClass('first-child');\n      } else {\n        this.$sortField.removeClass('hidden');\n        this.$tableColumnsField.removeClass('first-child');\n      }\n    }\n\n    let [attribute, direction] =\n      this.elementIndex.getSortAttributeAndDirection();\n\n    // Add/remove a score option\n    const $scoreOption = this.$sortAttributeSelect.children(\n      'option[value=\"score\"]'\n    );\n\n    // If searching by score, just keep showing the actual selection\n    if (this.elementIndex.searching) {\n      if (!$scoreOption.length) {\n        this.$sortAttributeSelect.prepend(\n          $('<option/>', {\n            value: 'score',\n            text: Craft.t('app', 'Score'),\n          })\n        );\n      }\n    } else if ($scoreOption.length) {\n      $scoreOption.remove();\n    }\n\n    this.$sortAttributeSelect.val(attribute);\n    this.sortDirectionListbox.select(direction === 'asc' ? 0 : 1);\n\n    if (attribute === 'score') {\n      this.sortDirectionListbox.disable();\n      this.$sortDirectionPicker.addClass('disabled');\n    } else {\n      this.sortDirectionListbox.enable();\n      this.$sortDirectionPicker.removeClass('disabled');\n    }\n  },\n\n  updateTableColumnField: function () {\n    const attributes = this.elementIndex.getSelectedTableColumns();\n    let $lastContainer, lastIndex;\n\n    attributes.forEach((attribute) => {\n      const $checkbox = this.$tableColumnsContainer.find(\n        `input[value=\"${attribute}\"]`\n      );\n      if (!$checkbox.prop('checked')) {\n        $checkbox.prop('checked', true);\n      }\n      const $container = $checkbox.parent();\n\n      // Do we need to move it up?\n      if ($lastContainer && $container.index() < lastIndex) {\n        $container.insertAfter($lastContainer);\n      }\n\n      $lastContainer = $container;\n      lastIndex = $container.index();\n    });\n\n    // See if we need to uncheck any checkboxes\n    const $checkboxes = this._getTableColumnCheckboxes();\n    for (let i = 0; i < $checkboxes.length; i++) {\n      const $checkbox = $checkboxes.eq(i);\n      if ($checkbox.prop('checked') && !attributes.includes($checkbox.val())) {\n        $checkbox.prop('checked', false);\n      }\n    }\n  },\n\n  tidyTableColumnField: function () {\n    const defaultOrder = this.elementIndex\n      .getTableColumnOptions(this.$source)\n      .map((column) => column.attr)\n      .reduce((obj, attr, index) => {\n        return {...obj, [attr]: index};\n      }, {});\n\n    this.$tableColumnsContainer\n      .children()\n      .sort((a, b) => {\n        const checkboxA = $(a).children('input[type=\"checkbox\"]')[0];\n        const checkboxB = $(b).children('input[type=\"checkbox\"]')[0];\n        if (checkboxA.checked && checkboxB.checked) {\n          return 0;\n        }\n        if (checkboxA.checked || checkboxB.checked) {\n          return checkboxA.checked ? -1 : 1;\n        }\n        return defaultOrder[checkboxA.value] < defaultOrder[checkboxB.value]\n          ? -1\n          : 1;\n      })\n      .appendTo(this.$tableColumnsContainer);\n  },\n\n  revert: function () {\n    this.elementIndex.setSelecetedSourceState({\n      order: null,\n      sort: null,\n      tableColumns: null,\n    });\n\n    this.updateSortField();\n    this.updateTableColumnField();\n    this.tidyTableColumnField();\n\n    this.$revertBtn.remove();\n    this.$revertBtn = null;\n\n    this.$closeBtn.focus();\n    this.elementIndex.updateElements();\n  },\n\n  _buildMenu: function () {\n    const $metaContainer = $('<div class=\"meta\"/>').appendTo(this.$container);\n    this.$sortField = this._createSortField().appendTo($metaContainer);\n    this.$tableColumnsField =\n      this._createTableColumnsField().appendTo($metaContainer);\n    this.updateSortField();\n\n    this.$sortAttributeSelect.focus();\n\n    const $footerContainer = $('<div/>', {\n      class: 'flex menu-footer',\n    }).appendTo(this.$container);\n\n    this.$revertContainer = $('<div/>', {\n      class: 'flex-grow',\n    }).appendTo($footerContainer);\n\n    // Only create the revert button if there's a custom view state\n    if (\n      this.elementIndex.getSelectedSourceState('order') ||\n      this.elementIndex.getSelectedSourceState('sort') ||\n      this.elementIndex.getSelectedSourceState('tableColumns')\n    ) {\n      this._createRevertBtn();\n    }\n\n    this.$closeBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Close'),\n    })\n      .appendTo($footerContainer)\n      .on('click', () => {\n        this.menu.hide();\n      });\n  },\n\n  _createSortField: function () {\n    const $container = $('<div class=\"flex\"/>');\n\n    const $sortAttributeSelectContainer = Craft.ui\n      .createSelect({\n        options: this.elementIndex.getSortOptions(this.$source).map((o) => {\n          return {\n            label: o.label,\n            value: o.attr,\n          };\n        }),\n      })\n      .addClass('fullwidth')\n      .appendTo($('<div class=\"flex-grow\"/>').appendTo($container));\n\n    this.$sortAttributeSelect = $sortAttributeSelectContainer\n      .children('select')\n      .attr({\n        'aria-label': Craft.t('app', 'Sort attribute'),\n      });\n\n    this.$sortDirectionPicker = $('<section/>', {\n      class: 'btngroup btngroup--exclusive',\n      'aria-label': Craft.t('app', 'Sort direction'),\n    })\n      .append(\n        $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          title: Craft.t('app', 'Sort ascending'),\n          'aria-label': Craft.t('app', 'Sort ascending'),\n          'aria-pressed': 'false',\n          'data-icon': 'asc',\n          'data-dir': 'asc',\n        })\n      )\n      .append(\n        $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          title: Craft.t('app', 'Sort descending'),\n          'aria-label': Craft.t('app', 'Sort descending'),\n          'aria-pressed': 'false',\n          'data-icon': 'desc',\n          'data-dir': 'desc',\n        })\n      )\n      .appendTo($container);\n\n    this.sortDirectionListbox = new Craft.Listbox(this.$sortDirectionPicker, {\n      onChange: ($selectedOption) => {\n        const direction = $selectedOption.data('dir');\n        if (direction !== this.elementIndex.getSelectedSortDirection()) {\n          this.elementIndex.setSelectedSortAttribute(\n            this.$sortAttributeSelect.val(),\n            $selectedOption.data('dir')\n          );\n\n          if (!this.elementIndex.sortByScore) {\n            // In case it's actually the structure view\n            this.elementIndex.selectViewMode(this.elementIndex.viewMode);\n          }\n\n          this.elementIndex.updateElements();\n          this._createRevertBtn();\n        }\n      },\n    });\n\n    this.$sortAttributeSelect.on('change', () => {\n      this.elementIndex.setSelectedSortAttribute(\n        this.$sortAttributeSelect.val(),\n        null,\n        false\n      );\n\n      // In case it's actually the structure view\n      this.elementIndex.selectViewMode(this.elementIndex.viewMode);\n\n      this.elementIndex.updateElements();\n      this._createRevertBtn();\n    });\n\n    const $field = Craft.ui.createField($container, {\n      label: Craft.t('app', 'Sort by'),\n      fieldset: true,\n    });\n    $field.addClass('sort-field');\n    return $field;\n  },\n\n  _getTableColumnCheckboxes: function () {\n    return this.$tableColumnsContainer.find('input[type=\"checkbox\"]');\n  },\n\n  _createTableColumnsField: function () {\n    const columns = this.elementIndex.getTableColumnOptions(this.$source);\n\n    if (!columns.length) {\n      return $();\n    }\n\n    this.$tableColumnsContainer = $('<div/>');\n\n    columns.forEach((column) => {\n      $('<div class=\"element-index-view-menu-table-column\"/>')\n        .append('<div class=\"icon move\"/>')\n        .append(\n          Craft.ui.createCheckbox({\n            label: Craft.escapeHtml(column.label),\n            value: column.attr,\n          })\n        )\n        .appendTo(this.$tableColumnsContainer);\n    });\n\n    this.updateTableColumnField();\n    this.tidyTableColumnField();\n\n    new Garnish.DragSort(this.$tableColumnsContainer.children(), {\n      handle: '.move',\n      axis: 'y',\n      onSortChange: () => {\n        this._onTableColumnChange();\n      },\n    });\n\n    this._getTableColumnCheckboxes().on('change', (ev) => {\n      this._onTableColumnChange();\n    });\n\n    const $field = Craft.ui.createField(this.$tableColumnsContainer, {\n      label: Craft.t('app', 'Table Columns'),\n      fieldset: true,\n    });\n    $field.addClass('table-columns-field');\n    return $field;\n  },\n\n  _onTableColumnChange: function () {\n    const columns = [];\n    const $selectedCheckboxes =\n      this._getTableColumnCheckboxes().filter(':checked');\n    for (let i = 0; i < $selectedCheckboxes.length; i++) {\n      columns.push($selectedCheckboxes.eq(i).val());\n    }\n\n    // Only commit the change if it's different from the current column selections\n    // (maybe an unchecked column was dragged, etc.)\n    if (\n      Craft.compare(\n        columns,\n        this.elementIndex.getSelectedTableColumns(this.$source)\n      )\n    ) {\n      return;\n    }\n\n    this.elementIndex.setSelectedTableColumns(columns, false);\n    this.elementIndex.updateElements();\n    this._createRevertBtn();\n  },\n\n  _createRevertBtn: function () {\n    if (this.$revertBtn) {\n      return;\n    }\n\n    this.$revertBtn = $('<button/>', {\n      type: 'button',\n      class: 'light',\n      text: Craft.t('app', 'Use defaults'),\n    })\n      .appendTo(this.$revertContainer)\n      .on('click', () => {\n        this.revert();\n      });\n  },\n\n  destroy: function () {\n    this.menu.destroy();\n    delete this.menu;\n    this.base();\n  },\n});\n\nconst FilterHud = Garnish.HUD.extend({\n  elementIndex: null,\n  sourceKey: null,\n  siteId: null,\n  id: null,\n  loading: true,\n  serialized: null,\n  $clearBtn: null,\n  cleared: false,\n\n  init: function (elementIndex, sourceKey, siteId) {\n    this.elementIndex = elementIndex;\n    this.sourceKey = sourceKey;\n    this.siteId = siteId;\n    this.id = `filter-${Math.floor(Math.random() * 1000000000)}`;\n\n    const $loadingContent = $('<div/>')\n      .append(\n        $('<div/>', {\n          class: 'spinner',\n        })\n      )\n      .append(\n        $('<div/>', {\n          text: Craft.t('app', 'Loading'),\n          class: 'visually-hidden',\n          'aria-role': 'alert',\n        })\n      );\n\n    this.base(this.elementIndex.$filterBtn, $loadingContent, {\n      hudClass: 'hud element-filter-hud loading',\n    });\n\n    this.$hud.attr({\n      id: this.id,\n      'aria-live': 'polite',\n      'aria-busy': 'false',\n    });\n    this.$tip.remove();\n    this.$tip = null;\n\n    this.$body.on('submit', (ev) => {\n      ev.preventDefault();\n      this.hide();\n    });\n\n    Craft.sendActionRequest('POST', 'element-indexes/filter-hud', {\n      data: {\n        elementType: this.elementIndex.elementType,\n        source: this.sourceKey,\n        condition: this.elementIndex.settings.condition,\n        id: `${this.id}-filters`,\n      },\n    })\n      .then((response) => {\n        this.loading = false;\n        this.$hud.removeClass('loading');\n        $loadingContent.remove();\n\n        this.$main.append(response.data.hudHtml);\n        Craft.appendHeadHtml(response.data.headHtml);\n        Craft.appendBodyHtml(response.data.bodyHtml);\n\n        const $btnContainer = $('<div/>', {\n          class: 'flex flex-nowrap',\n        }).appendTo(this.$main);\n        $('<div/>', {\n          class: 'flex-grow',\n        }).appendTo($btnContainer);\n        this.$clearBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Cancel'),\n        }).appendTo($btnContainer);\n        $('<button/>', {\n          type: 'submit',\n          class: 'btn secondary',\n          text: Craft.t('app', 'Apply'),\n        }).appendTo($btnContainer);\n        this.$clearBtn.on('click', () => {\n          this.clear();\n        });\n\n        this.$hud.find('.condition-container').on('htmx:beforeRequest', () => {\n          this.setBusy();\n        });\n\n        this.$hud.find('.condition-container').on('htmx:load', () => {\n          this.setReady();\n          this.updateSizeAndPosition(true);\n        });\n        this.setFocus();\n      })\n      .catch(() => {\n        Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n      });\n\n    this.$hud.css('position', 'fixed');\n\n    this.addListener(Garnish.$win, 'scroll,resize', () => {\n      this.updateSizeAndPosition(true);\n    });\n  },\n\n  addListener: function (elem, events, data, func) {\n    if (elem === this.$main && events === 'resize') {\n      return;\n    }\n    this.base(elem, events, data, func);\n  },\n\n  setBusy: function () {\n    this.$hud.attr('aria-busy', 'true');\n\n    $('<div/>', {\n      class: 'visually-hidden',\n      text: Craft.t('app', 'Loading'),\n    }).insertAfter(this.$main.find('.htmx-indicator'));\n  },\n\n  setReady: function () {\n    this.$hud.attr('aria-busy', 'false');\n  },\n\n  setFocus: function () {\n    Garnish.setFocusWithin(this.$main);\n  },\n\n  clear: function () {\n    this.cleared = true;\n    this.hide();\n  },\n\n  updateSizeAndPositionInternal: function () {\n    const searchOffset =\n      this.elementIndex.$searchContainer[0].getBoundingClientRect();\n\n    // Ensure HUD is scrollable if content falls off-screen\n    const windowHeight = Garnish.$win.height();\n    let hudHeight;\n    const availableSpace = windowHeight - searchOffset.bottom;\n\n    if (this.$body.height() > availableSpace) {\n      hudHeight = windowHeight - searchOffset.bottom - 10;\n    }\n\n    this.$hud.css({\n      width: this.elementIndex.$searchContainer.outerWidth() - 2,\n      top: searchOffset.top + this.elementIndex.$searchContainer.outerHeight(),\n      left: searchOffset.left + 1,\n      height: hudHeight ? `${hudHeight}px` : 'unset',\n      overflowY: hudHeight ? 'scroll' : 'unset',\n    });\n  },\n\n  onShow: function () {\n    this.base();\n\n    // Cancel => Clear\n    if (this.$clearBtn) {\n      this.$clearBtn.text(Craft.t('app', 'Clear'));\n    }\n\n    this.elementIndex.updateFilterBtn();\n    this.setFocus();\n  },\n\n  onHide: function () {\n    this.base();\n\n    // If something changed, update the elements\n    if (this.serialized !== (this.serialized = this.serialize())) {\n      this.elementIndex.updateElements();\n    }\n\n    if (this.cleared) {\n      this.destroy();\n    } else {\n      this.$hud.detach();\n      this.$shade.detach();\n    }\n\n    this.elementIndex.updateFilterBtn();\n    this.elementIndex.$filterBtn.focus();\n  },\n\n  hasRules: function () {\n    return this.$main.has('.condition-rule').length !== 0;\n  },\n\n  serialize: function () {\n    return !this.cleared && this.hasRules() ? this.$body.serialize() : null;\n  },\n\n  destroy: function () {\n    this.base();\n    delete this.elementIndex.filterHuds[this.siteId][this.sourceKey];\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Base Element Index View\n */\nCraft.BaseElementIndexView = Garnish.Base.extend(\n  {\n    $container: null,\n    $loadingMoreSpinner: null,\n    $elementContainer: null,\n    $scroller: null,\n\n    elementIndex: null,\n    elementSelect: null,\n\n    loadingMore: false,\n\n    _totalVisible: null,\n    _morePending: null,\n    _handleEnableElements: null,\n    _handleDisableElements: null,\n\n    get thumbLoader() {\n      console.warn(\n        'Craft.BaseElementIndexView::thumbLoader is deprecated. Craft.cp.elementThumbLoader should be used instead.'\n      );\n      return Craft.cp.elementThumbLoader;\n    },\n\n    init: function (elementIndex, container, settings) {\n      this.elementIndex = elementIndex;\n      this.$container = $(container);\n      this.setSettings(settings, Craft.BaseElementIndexView.defaults);\n\n      // Create a \"loading-more\" spinner\n      this.$loadingMoreSpinner = $(\n        '<div class=\"centeralign hidden\">' +\n          '<div class=\"spinner loadingmore\"></div>' +\n          '</div>'\n      ).insertAfter(this.$container);\n\n      // Get the actual elements container and its child elements\n      this.$elementContainer = this.getElementContainer();\n      var $elements = this.$elementContainer.children();\n\n      this.setTotalVisible($elements.length);\n      this.setMorePending(\n        this.settings.batchSize && $elements.length == this.settings.batchSize\n      );\n\n      // Load thumbnails\n      Craft.cp.elementThumbLoader.load($elements);\n\n      if (this.settings.selectable) {\n        this.elementSelect = new Garnish.Select(\n          this.$elementContainer,\n          $(\n            $elements\n              .toArray()\n              .filter((element) => this.canSelectElement($(element)))\n          ),\n          {\n            multi: this.settings.multiSelect,\n            vertical: this.isVerticalList(),\n            handle:\n              this.settings.context === 'index'\n                ? '.checkbox, .element:first'\n                : null,\n            filter: ':not(a):not(.toggle)',\n            checkboxMode: this.settings.checkboxMode,\n            onSelectionChange: this.onSelectionChange.bind(this),\n          }\n        );\n\n        this._handleEnableElements = (ev) => {\n          this.elementSelect.addItems(ev.elements);\n        };\n\n        this._handleDisableElements = (ev) => {\n          this.elementSelect.removeItems(ev.elements);\n        };\n\n        this.elementIndex.on('enableElements', this._handleEnableElements);\n        this.elementIndex.on('disableElements', this._handleDisableElements);\n      }\n\n      // Enable inline element editing if this is an index page\n      if (this.settings.context === 'index') {\n        this._handleElementEditing = (ev) => {\n          var $target = $(ev.target);\n\n          if ($target.prop('nodeName') === 'A') {\n            // Let the link do its thing\n            return;\n          }\n\n          var $element;\n\n          if ($target.hasClass('element')) {\n            $element = $target;\n          } else {\n            $element = $target.closest('.element');\n\n            if (!$element.length) {\n              return;\n            }\n          }\n\n          if (Garnish.hasAttr($element, 'data-editable')) {\n            Craft.createElementEditor($element.data('type'), $element);\n          }\n        };\n\n        if (!this.elementIndex.trashed) {\n          this.addListener(\n            this.$elementContainer,\n            'dblclick,taphold',\n            this._handleElementEditing\n          );\n        }\n      }\n\n      // Give sub-classes a chance to do post-initialization stuff here\n      this.afterInit();\n\n      // Set up lazy-loading\n      if (this.settings.batchSize) {\n        if (this.settings.context === 'index') {\n          this.$scroller = Garnish.$scrollContainer;\n        } else {\n          this.$scroller = this.elementIndex.$main;\n        }\n\n        this.$scroller.scrollTop(0);\n        this.addListener(this.$scroller, 'scroll', 'maybeLoadMore');\n        this.maybeLoadMore();\n      }\n    },\n\n    canSelectElement: function ($element) {\n      if ($element.hasClass('disabled')) {\n        return false;\n      }\n      if (this.settings.canSelectElement) {\n        return this.settings.canSelectElement($element);\n      }\n      return !!$element.data('id');\n    },\n\n    getElementContainer: function () {\n      throw 'Classes that extend Craft.BaseElementIndexView must supply a getElementContainer() method.';\n    },\n\n    afterInit: function () {},\n\n    getAllElements: function () {\n      return this.$elementContainer.children();\n    },\n\n    getEnabledElements: function () {\n      return this.$elementContainer.children(':not(.disabled)');\n    },\n\n    getElementById: function (id) {\n      var $element = this.$elementContainer.children(\n        '[data-id=\"' + id + '\"]:first'\n      );\n\n      if ($element.length) {\n        return $element;\n      } else {\n        return null;\n      }\n    },\n\n    getSelectedElements: function () {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      return this.elementSelect.$selectedItems;\n    },\n\n    getSelectedElementIds: function () {\n      let $selectedElements;\n      try {\n        $selectedElements = this.getSelectedElements();\n      } catch (e) {}\n\n      let ids = [];\n      if ($selectedElements) {\n        for (var i = 0; i < $selectedElements.length; i++) {\n          ids.push($selectedElements.eq(i).data('id'));\n        }\n      }\n      return ids;\n    },\n\n    selectElement: function ($element) {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      this.elementSelect.selectItem($element, true);\n      return true;\n    },\n\n    selectElementById: function (id) {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      var $element = this.getElementById(id);\n\n      if ($element) {\n        this.elementSelect.selectItem($element, true);\n        return true;\n      } else {\n        return false;\n      }\n    },\n\n    selectAllElements: function () {\n      this.elementSelect.selectAll();\n    },\n\n    deselectAllElements: function () {\n      this.elementSelect.deselectAll();\n    },\n\n    getElementCheckbox: function (element) {\n      return $(element).find('[role=\"checkbox\"]');\n    },\n\n    isVerticalList: function () {\n      return false;\n    },\n\n    getTotalVisible: function () {\n      return this._totalVisible;\n    },\n\n    setTotalVisible: function (totalVisible) {\n      this._totalVisible = totalVisible;\n    },\n\n    getMorePending: function () {\n      return this._morePending;\n    },\n\n    setMorePending: function (morePending) {\n      this._morePending = morePending;\n    },\n\n    /**\n     * Checks if the user has reached the bottom of the scroll area, and if so, loads the next batch of elemets.\n     */\n    maybeLoadMore: function () {\n      if (this.canLoadMore()) {\n        this.loadMore();\n      }\n    },\n\n    /**\n     * Returns whether the user has reached the bottom of the scroll area.\n     */\n    canLoadMore: function () {\n      if (!this.getMorePending() || !this.settings.batchSize) {\n        return false;\n      }\n\n      // Check if the user has reached the bottom of the scroll area\n      var containerHeight;\n\n      if (this.$scroller[0] === Garnish.$win[0]) {\n        var winHeight = Garnish.$win.innerHeight(),\n          winScrollTop = Garnish.$win.scrollTop(),\n          containerOffset = this.$container.offset().top;\n        containerHeight = this.$container.height();\n\n        return winHeight + winScrollTop >= containerOffset + containerHeight;\n      } else {\n        var containerScrollHeight = this.$scroller.prop('scrollHeight'),\n          containerScrollTop = this.$scroller.scrollTop();\n        containerHeight = this.$scroller.outerHeight();\n\n        return (\n          containerScrollHeight - containerScrollTop <= containerHeight + 15\n        );\n      }\n    },\n\n    /**\n     * Loads the next batch of elements.\n     */\n    loadMore: function () {\n      if (\n        !this.getMorePending() ||\n        this.loadingMore ||\n        !this.settings.batchSize\n      ) {\n        return;\n      }\n\n      this.loadingMore = true;\n      this.$loadingMoreSpinner.removeClass('hidden');\n      this.removeListener(this.$scroller, 'scroll');\n\n      Craft.sendActionRequest('POST', this.settings.loadMoreElementsAction, {\n        data: this.getLoadMoreParams(),\n      })\n        .then((response) => {\n          this.loadingMore = false;\n          this.$loadingMoreSpinner.addClass('hidden');\n\n          let $newElements = $(response.data.html);\n\n          this.appendElements($newElements);\n          Craft.appendHeadHtml(response.data.headHtml);\n          Craft.appendBodyHtml(response.data.bodyHtml);\n\n          if (this.elementSelect) {\n            this.elementSelect.addItems($newElements.filter(':not(.disabled)'));\n            this.elementIndex.updateActionTriggers();\n          }\n\n          this.setTotalVisible(this.getTotalVisible() + $newElements.length);\n          this.setMorePending($newElements.length == this.settings.batchSize);\n\n          // Is there room to load more right now?\n          this.addListener(this.$scroller, 'scroll', 'maybeLoadMore');\n          this.maybeLoadMore();\n        })\n        .catch((e) => {\n          this.loadingMore = false;\n          this.$loadingMoreSpinner.addClass('hidden');\n        });\n    },\n\n    getLoadMoreParams: function () {\n      // Use the same params that were passed when initializing this view\n      var params = $.extend(true, {}, this.settings.params);\n      params.criteria.offset = this.getTotalVisible();\n      return params;\n    },\n\n    appendElements: function ($newElements) {\n      $newElements.appendTo(this.$elementContainer);\n      Craft.cp.elementThumbLoader.load($newElements);\n      this.onAppendElements($newElements);\n    },\n\n    onAppendElements: function ($newElements) {\n      this.settings.onAppendElements($newElements);\n      this.trigger('appendElements', {\n        newElements: $newElements,\n      });\n    },\n\n    onSelectionChange: function () {\n      this.settings.onSelectionChange();\n      this.trigger('selectionChange');\n\n      // Update checkboxes\n      if (this.settings.checkboxMode) {\n        const $items = this.elementSelect.$items.each((index, item) => {\n          if (this.elementSelect.isSelected(item)) {\n            this.getElementCheckbox(item).attr('aria-checked', 'true');\n          } else {\n            this.getElementCheckbox(item).attr('aria-checked', 'false');\n          }\n        });\n      }\n    },\n\n    disable: function () {\n      if (this.elementSelect) {\n        this.elementSelect.disable();\n      }\n    },\n\n    enable: function () {\n      if (this.elementSelect) {\n        this.elementSelect.enable();\n      }\n    },\n\n    destroy: function () {\n      // Remove the \"loading-more\" spinner, since we added that outside of the view container\n      this.$loadingMoreSpinner.remove();\n\n      // Delete the element select\n      if (this.elementSelect) {\n        this.elementIndex.off('enableElements', this._handleEnableElements);\n        this.elementIndex.off('disableElements', this._handleDisableElements);\n\n        this.elementSelect.destroy();\n        delete this.elementSelect;\n      }\n\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      context: 'index',\n      batchSize: null,\n      params: null,\n      selectable: false,\n      multiSelect: false,\n      canSelectElement: null,\n      checkboxMode: false,\n      loadMoreElementsAction: 'element-indexes/get-more-elements',\n      onAppendElements: $.noop,\n      onSelectionChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Select input\n */\nCraft.BaseElementSelectInput = Garnish.Base.extend(\n  {\n    elementSelect: null,\n    elementSort: null,\n    modal: null,\n    elementEditor: null,\n\n    $container: null,\n    $form: null,\n    $elementsContainer: null,\n    $elements: null,\n    $addElementBtn: null,\n    $spinner: null,\n\n    _initialized: false,\n\n    get thumbLoader() {\n      console.warn(\n        'Craft.BaseElementSelectInput::thumbLoader is deprecated. Craft.cp.elementThumbLoader should be used instead.'\n      );\n      return Craft.cp.elementThumbLoader;\n    },\n\n    init: function (settings) {\n      // Normalize the settings and set them\n      // ---------------------------------------------------------------------\n\n      // Are they still passing in a bunch of arguments?\n      if (!$.isPlainObject(settings)) {\n        // Loop through all of the old arguments and apply them to the settings\n        var normalizedSettings = {},\n          args = [\n            'id',\n            'name',\n            'elementType',\n            'sources',\n            'criteria',\n            'sourceElementId',\n            'limit',\n            'modalStorageKey',\n            'fieldId',\n          ];\n\n        for (var i = 0; i < args.length; i++) {\n          if (typeof arguments[i] !== 'undefined') {\n            normalizedSettings[args[i]] = arguments[i];\n          } else {\n            break;\n          }\n        }\n\n        settings = normalizedSettings;\n      }\n\n      this.setSettings(settings, Craft.BaseElementSelectInput.defaults);\n\n      // Apply the storage key prefix\n      if (this.settings.modalStorageKey) {\n        this.modalStorageKey =\n          'BaseElementSelectInput.' + this.settings.modalStorageKey;\n      }\n\n      // No reason for this to be sortable if we're only allowing 1 selection\n      if (this.settings.limit == 1 || this.settings.maintainHierarchy) {\n        this.settings.sortable = false;\n      }\n\n      this.$container = this.getContainer();\n      this.$form = this.$container.closest('form');\n\n      // Store a reference to this class\n      this.$container.data('elementSelect', this);\n\n      this.$elementsContainer = this.getElementsContainer();\n      this.$addElementBtn = this.getAddElementsBtn();\n      this.$spinner = this.getSpinner();\n\n      this.initElementSelect();\n      this.initElementSort();\n      this.resetElements();\n\n      if (this.$addElementBtn) {\n        this.addListener(this.$addElementBtn, 'activate', 'showModal');\n      }\n\n      Garnish.requestAnimationFrame(() => {\n        this._initialized = true;\n      });\n    },\n\n    get totalSelected() {\n      return this.$elements.length;\n    },\n\n    getContainer: function () {\n      return $('#' + this.settings.id);\n    },\n\n    getElementsContainer: function () {\n      return this.$container.children('.elements');\n    },\n\n    getElements: function () {\n      return this.$elementsContainer.find('.element');\n    },\n\n    getAddElementsBtn: function () {\n      return this.$container.find('.btn.add:first');\n    },\n\n    getSpinner: function () {\n      return this.$container.find('.spinner');\n    },\n\n    initElementSelect: function () {\n      if (this.settings.selectable) {\n        this.elementSelect = new Garnish.Select({\n          multi: this.settings.sortable,\n          filter: ':not(.delete)',\n        });\n      }\n    },\n\n    initElementSort: function () {\n      if (this.settings.sortable) {\n        this.elementSort = new Garnish.DragSort({\n          container: this.$elementsContainer,\n          filter: this.settings.selectable\n            ? () => {\n                // Only return all the selected items if the target item is selected\n                if (this.elementSort.$targetItem.hasClass('sel')) {\n                  return this.elementSelect.getSelectedItems();\n                } else {\n                  return this.elementSort.$targetItem;\n                }\n              }\n            : null,\n          ignoreHandleSelector: '.delete',\n          axis: this.getElementSortAxis(),\n          collapseDraggees: true,\n          magnetStrength: 4,\n          helperLagBase: 1.5,\n          onSortChange: this.settings.selectable\n            ? () => {\n                this.elementSelect.resetItemOrder();\n              }\n            : null,\n        });\n      }\n    },\n\n    getElementSortAxis: function () {\n      return this.settings.viewMode === 'list' ? 'y' : null;\n    },\n\n    canAddMoreElements: function () {\n      return (\n        !this.settings.limit || this.$elements.length < this.settings.limit\n      );\n    },\n\n    updateAddElementsBtn: function () {\n      if (this.canAddMoreElements()) {\n        this.enableAddElementsBtn();\n      } else {\n        this.disableAddElementsBtn();\n      }\n    },\n\n    enableAddElementsBtn: function () {\n      if (this.$addElementBtn) {\n        this.$addElementBtn.removeClass('hidden');\n      }\n\n      this.updateButtonContainer();\n    },\n\n    disableAddElementsBtn: function () {\n      if (this.$addElementBtn) {\n        this.$addElementBtn.addClass('hidden');\n      }\n\n      this.updateButtonContainer();\n    },\n\n    showSpinner: function () {\n      if (this.$spinner) {\n        this.$spinner.removeClass('hidden');\n      }\n\n      this.updateButtonContainer();\n    },\n\n    hideSpinner: function () {\n      if (this.$spinner) {\n        this.$spinner.addClass('hidden');\n      }\n\n      this.updateButtonContainer();\n    },\n\n    updateButtonContainer: function () {\n      const $container =\n        this.$addElementBtn && this.$addElementBtn.parent('.flex');\n      if ($container && $container.length) {\n        if ($container.children(':not(.hidden)').length) {\n          $container.removeClass('hidden');\n        } else {\n          $container.addClass('hidden');\n        }\n      }\n    },\n\n    focusNextLogicalElement: function () {\n      if (this.canAddMoreElements()) {\n        // If can add more elements, focus ADD button\n        let $btn = this.$addElementBtn;\n\n        if ($btn) {\n          $btn.get(0).focus();\n        }\n      } else {\n        // If can't add more elements, focus on the final remove\n        this.focusLastRemoveBtn();\n      }\n    },\n\n    focusLastRemoveBtn: function () {\n      const $removeBtns = this.$container.find('.delete');\n\n      if (!$removeBtns.length) return;\n\n      $removeBtns.last()[0].focus();\n    },\n\n    resetElements: function () {\n      if (this.$elements !== null) {\n        this.removeElements(this.$elements);\n      } else {\n        this.$elements = $();\n      }\n\n      this.addElements(this.getElements());\n    },\n\n    addElements: function ($elements) {\n      Craft.cp.elementThumbLoader.load($elements);\n\n      if (this.settings.selectable) {\n        this.elementSelect.addItems($elements);\n      }\n\n      if (this.settings.sortable) {\n        this.elementSort.addItems($elements);\n      }\n\n      if (this.settings.editable) {\n        this._handleShowElementEditor = (ev) => {\n          var $element = $(ev.currentTarget);\n          if (\n            Garnish.hasAttr($element, 'data-editable') &&\n            !$element.hasClass('disabled') &&\n            !$element.hasClass('loading')\n          ) {\n            this.elementEditor = this.createElementEditor($element);\n          }\n        };\n\n        this.addListener($elements, 'dblclick', this._handleShowElementEditor);\n\n        if ($.isTouchCapable()) {\n          this.addListener($elements, 'taphold', this._handleShowElementEditor);\n        }\n      }\n\n      $elements.find('.delete').on('click dblclick', (ev) => {\n        this.removeElement($(ev.currentTarget).closest('.element'));\n        // Prevent this from acting as one of a double-click\n        ev.stopPropagation();\n      });\n\n      $elements.on('keydown', (ev) => {\n        if ([Garnish.BACKSPACE_KEY, Garnish.DELETE_KEY].includes(ev.keyCode)) {\n          ev.stopPropagation();\n          ev.preventDefault();\n          const $elements = this.elementSelect.getSelectedItems();\n          for (let i = 0; i < $elements.length; i++) {\n            this.removeElement($elements.eq(i));\n          }\n        }\n      });\n\n      this.$elements = this.$elements.add($elements);\n\n      this.updateAddElementsBtn();\n\n      this.onAddElements();\n    },\n\n    createElementEditor: function ($element, settings) {\n      settings = Object.assign(\n        {\n          elementSelectInput: this,\n          prevalidate: this.settings.prevalidate,\n        },\n        settings\n      );\n\n      return Craft.createElementEditor(\n        this.settings.elementType,\n        $element,\n        settings\n      );\n    },\n\n    replaceElement: function (elementId, replacementId) {\n      return new Promise((resolve, reject) => {\n        const $existing = this.$elements.filter(`[data-id=\"${elementId}\"]`);\n\n        if (!$existing.length) {\n          reject(`No element selected with an ID of ${elementId}.`);\n          return;\n        }\n\n        this.showSpinner();\n\n        const data = {\n          elementId: replacementId,\n          siteId: this.settings.criteria.siteId,\n          thumbSize: this.settings.viewMode,\n        };\n\n        Craft.sendActionRequest('POST', 'elements/get-element-html', {data})\n          .then((response) => {\n            this.removeElement($existing);\n            const elementInfo = Craft.getElementInfo(response.data.html);\n            this.selectElements([elementInfo]);\n            resolve();\n          })\n          .catch(({response}) => {\n            if (response && response.data && response.data.message) {\n              Craft.cp.displayError(response.data.message);\n            } else {\n              Craft.cp.displayError();\n            }\n\n            reject(response.data.message);\n          })\n          .finally(() => {\n            this.hideSpinner();\n          });\n      });\n    },\n\n    removeElements: function ($elements) {\n      if (this.settings.selectable) {\n        this.elementSelect.removeItems($elements);\n      }\n\n      if (this.modal) {\n        var ids = [];\n\n        for (var i = 0; i < $elements.length; i++) {\n          var id = $elements.eq(i).data('id');\n\n          if (id) {\n            ids.push(id);\n          }\n        }\n\n        if (ids.length) {\n          this.modal.elementIndex.enableElementsById(ids);\n        }\n      }\n\n      // Disable the hidden input in case the form is submitted before this element gets removed from the DOM\n      $elements.children('input').prop('disabled', true);\n\n      // Move the focus to the next element in the list, if there is one\n      let $nextDeleteBtn;\n      if (this.settings.selectable) {\n        const lastElementIndex = this.$elements.index($elements.last());\n        $nextDeleteBtn = this.$elements\n          .eq(lastElementIndex + 1)\n          .find('.delete');\n      }\n      if ($nextDeleteBtn.length) {\n        $nextDeleteBtn.focus();\n      } else {\n        this.focusNextLogicalElement();\n      }\n\n      this.$elements = this.$elements.not($elements);\n      this.updateAddElementsBtn();\n\n      this.onRemoveElements();\n    },\n\n    removeElement: function ($element) {\n      if (this.settings.maintainHierarchy) {\n        // Find any descendants this element might have\n        const $allElements = $element.add(\n          $element.parent().siblings('ul').find('.element')\n        );\n\n        // Remove any inputs from the form data\n        $('[name]', $allElements).removeAttr('name');\n\n        // Remove our record of them all at once\n        this.removeElements($allElements);\n\n        // Animate them away one at a time\n        for (let i = 0; i < $allElements.length; i++) {\n          this._animateStructureElementAway($allElements, i);\n        }\n      } else {\n        // Remove any inputs from the form data\n        $('[name]', $element).removeAttr('name');\n        this.removeElements($element);\n        this.animateElementAway($element, () => {\n          $element.remove();\n        });\n      }\n    },\n\n    animateElementAway: function ($element, callback) {\n      $element.css('z-index', 0);\n\n      var animateCss = {\n        opacity: -1,\n      };\n      animateCss['margin-' + Craft.left] = -(\n        $element.outerWidth() + parseInt($element.css('margin-' + Craft.right))\n      );\n\n      if (this.settings.viewMode === 'list' || this.$elements.length === 0) {\n        animateCss['margin-bottom'] = -(\n          $element.outerHeight() + parseInt($element.css('margin-bottom'))\n        );\n      }\n\n      $element.velocity(\n        animateCss,\n        Craft.BaseElementSelectInput.REMOVE_FX_DURATION,\n        () => {\n          if (callback) {\n            callback();\n          }\n        }\n      );\n    },\n\n    showModal: function () {\n      // Make sure we haven't reached the limit\n      if (!this.canAddMoreElements()) {\n        return;\n      }\n\n      if (!this.modal) {\n        this.modal = this.createModal();\n      } else {\n        this.modal.show();\n      }\n    },\n\n    createModal: function () {\n      return Craft.createElementSelectorModal(\n        this.settings.elementType,\n        this.getModalSettings()\n      );\n    },\n\n    getModalSettings: function () {\n      return $.extend(\n        {\n          closeOtherModals: false,\n          storageKey: this.modalStorageKey,\n          sources: this.settings.sources,\n          condition: this.settings.condition,\n          referenceElementId: this.settings.referenceElementId,\n          referenceElementSiteId: this.settings.referenceElementSiteId,\n          criteria: this.settings.criteria,\n          multiSelect: this.settings.limit != 1,\n          hideOnSelect: !this.settings.maintainHierarchy,\n          showSiteMenu: this.settings.showSiteMenu,\n          disabledElementIds: this.getDisabledElementIds(),\n          onSelect: this.onModalSelect.bind(this),\n          onHide: this.onModalHide.bind(this),\n          triggerElement: this.$addElementBtn,\n          modalTitle: Craft.t('app', 'Choose'),\n        },\n        this.settings.modalSettings\n      );\n    },\n\n    getSelectedElementIds: function () {\n      var ids = [];\n\n      for (var i = 0; i < this.$elements.length; i++) {\n        ids.push(this.$elements.eq(i).data('id'));\n      }\n\n      return ids;\n    },\n\n    getDisabledElementIds: function () {\n      var ids = this.getSelectedElementIds();\n\n      if (!this.settings.allowSelfRelations && this.settings.sourceElementId) {\n        ids.push(this.settings.sourceElementId);\n      }\n\n      if (this.settings.disabledElementIds) {\n        ids.push(...this.settings.disabledElementIds);\n      }\n\n      return ids;\n    },\n\n    onModalSelect: function (elements) {\n      if (this.settings.maintainHierarchy) {\n        this.selectStructuredElements(elements);\n      } else {\n        if (this.settings.limit) {\n          // Cut off any excess elements\n          var slotsLeft = this.settings.limit - this.$elements.length;\n\n          if (elements.length > slotsLeft) {\n            elements = elements.slice(0, slotsLeft);\n          }\n        }\n\n        this.selectElements(elements);\n        this.updateDisabledElementsInModal();\n      }\n    },\n\n    onModalHide: function () {\n      // If the modal has a condition and a reference element, recreate it each time it’s opened\n      // in case something about the edited element is going to affect the condition\n      if (\n        this.modal &&\n        this.settings.condition &&\n        this.settings.referenceElementId\n      ) {\n        this.modal.destroy();\n        this.modal = null;\n      }\n\n      // If can add more elements, do default behavior of focus on \"Add\" button\n      if (this.canAddMoreElements()) return;\n\n      setTimeout(() => {\n        this.focusNextLogicalElement();\n      }, 200);\n    },\n\n    selectElements: function (elements) {\n      for (let i = 0; i < elements.length; i++) {\n        let elementInfo = elements[i],\n          $element = this.createNewElement(elementInfo);\n\n        this.appendElement($element);\n        this.addElements($element);\n        this.animateElementIntoPlace(elementInfo.$element, $element);\n\n        // Override the element reference with the new one\n        elementInfo.$element = $element;\n      }\n\n      this.onSelectElements(elements);\n    },\n\n    selectStructuredElements: function (elements) {\n      // Disable the modal\n      this.modal.disable();\n      this.modal.disableCancelBtn();\n      this.modal.disableSelectBtn();\n      this.modal.showFooterSpinner();\n\n      // Get the new element HTML\n      var selectedElementIds = this.getSelectedElementIds();\n\n      for (var i = 0; i < elements.length; i++) {\n        selectedElementIds.push(elements[i].id);\n      }\n\n      var data = {\n        elementIds: selectedElementIds,\n        siteId: elements[0].siteId,\n        containerId: this.settings.id,\n        name: this.settings.name,\n        branchLimit: this.settings.branchLimit,\n        selectionLabel: this.settings.selectionLabel,\n        elementType: this.settings.elementType,\n      };\n\n      const onResponse = () => {\n        this.modal.enable();\n        this.modal.enableCancelBtn();\n        this.modal.enableSelectBtn();\n        this.modal.hideFooterSpinner();\n      };\n      Craft.sendActionRequest(\n        'POST',\n        'relational-fields/structured-input-html',\n        {data}\n      )\n        .then((response) => {\n          onResponse();\n          var $newInput = $(response.data.html),\n            $newElementsContainer = $newInput.children('.elements');\n\n          this.$elementsContainer.replaceWith($newElementsContainer);\n          this.$elementsContainer = $newElementsContainer;\n          this.resetElements();\n\n          var filteredElements = [];\n\n          for (var i = 0; i < elements.length; i++) {\n            var element = elements[i],\n              $element = this.getElementById(element.id);\n\n            if ($element) {\n              this.animateElementIntoPlace(element.$element, $element);\n              filteredElements.push(element);\n            }\n          }\n\n          this.updateDisabledElementsInModal();\n          this.modal.hide();\n          this.onSelectElements(filteredElements);\n        })\n        .catch(({response}) => {\n          onResponse();\n        });\n    },\n\n    createNewElement: function (elementInfo) {\n      var $element = elementInfo.$element.clone();\n      var removeText = Craft.t('app', 'Remove {label}', {\n        label: Craft.escapeHtml(elementInfo.label),\n      });\n      // Make a couple tweaks\n      Craft.setElementSize(\n        $element,\n        this.settings.viewMode === 'large' ? 'large' : 'small'\n      );\n      $element\n        .addClass('removable')\n        .prepend(\n          $('<input/>', {\n            type: 'hidden',\n            name: this.settings.name + (this.settings.single ? '' : '[]'),\n            value: elementInfo.id,\n          })\n        )\n        .prepend(\n          $('<button/>', {\n            type: 'button',\n            class: 'delete icon',\n            title: Craft.t('app', 'Remove'),\n            'aria-label': removeText,\n          })\n        );\n\n      return $element;\n    },\n\n    appendElement: function ($element) {\n      $element.appendTo(this.$elementsContainer);\n    },\n\n    animateElementIntoPlace: function ($modalElement, $inputElement) {\n      var origOffset = $modalElement.offset(),\n        destOffset = $inputElement.offset(),\n        $helper = $inputElement.clone().appendTo(Garnish.$bod);\n\n      $inputElement.css('visibility', 'hidden');\n\n      $helper.css({\n        position: 'absolute',\n        zIndex: 10000,\n        top: origOffset.top,\n        left: origOffset.left,\n      });\n\n      var animateCss = {\n        top: destOffset.top,\n        left: destOffset.left,\n      };\n\n      $helper.velocity(\n        animateCss,\n        Craft.BaseElementSelectInput.ADD_FX_DURATION,\n        function () {\n          $helper.remove();\n          $inputElement.css('visibility', 'visible');\n        }\n      );\n    },\n\n    updateDisabledElementsInModal: function () {\n      if (this.modal.elementIndex) {\n        this.modal.elementIndex.disableElementsById(\n          this.getDisabledElementIds()\n        );\n      }\n    },\n\n    getElementById: function (id) {\n      for (var i = 0; i < this.$elements.length; i++) {\n        var $element = this.$elements.eq(i);\n\n        if ($element.data('id') == id) {\n          return $element;\n        }\n      }\n    },\n\n    onSelectElements: function (elements) {\n      this.trigger('selectElements', {elements});\n      this.settings.onSelectElements(elements);\n      this.$container.trigger('change');\n    },\n\n    onAddElements: function () {\n      this.trigger('addElements');\n      this.settings.onAddElements();\n      this.$container.trigger('change');\n    },\n\n    onRemoveElements: function () {\n      this.trigger('removeElements');\n      this.settings.onRemoveElements();\n      this.$container.trigger('change');\n    },\n\n    _animateStructureElementAway: function ($allElements, i) {\n      let callback;\n\n      // Is this the last one?\n      if (i === $allElements.length - 1) {\n        callback = () => {\n          const $li = $allElements.first().parent().parent();\n          const $ul = $li.parent();\n\n          if ($ul[0] === this.$elementsContainer[0] || $li.siblings().length) {\n            $li.remove();\n          } else {\n            $ul.remove();\n          }\n        };\n      }\n\n      const func = () => {\n        this.animateElementAway($allElements.eq(i), callback);\n      };\n\n      if (i === 0) {\n        func();\n      } else {\n        setTimeout(func, 100 * i);\n      }\n    },\n  },\n  {\n    ADD_FX_DURATION: 200,\n    REMOVE_FX_DURATION: 200,\n\n    defaults: {\n      id: null,\n      name: null,\n      fieldId: null,\n      elementType: null,\n      sources: null,\n      condition: null,\n      referenceElementId: null,\n      referenceElementSiteId: null,\n      criteria: {},\n      allowSelfRelations: false,\n      sourceElementId: null,\n      disabledElementIds: null,\n      viewMode: 'list',\n      single: false,\n      maintainHierarchy: false,\n      branchLimit: null,\n      limit: null,\n      showSiteMenu: false,\n      modalStorageKey: null,\n      modalSettings: {},\n      onAddElements: $.noop,\n      onSelectElements: $.noop,\n      onRemoveElements: $.noop,\n      sortable: true,\n      selectable: true,\n      editable: true,\n      prevalidate: false,\n      editorSettings: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element selector modal class\n */\nCraft.BaseElementSelectorModal = Garnish.Modal.extend(\n  {\n    elementType: null,\n    elementIndex: null,\n\n    supportSidebarToggleView: false,\n\n    $body: null,\n    $content: null,\n    $footer: null,\n    $selectBtn: null,\n    $sidebar: null,\n    $sources: null,\n    $sourceToggles: null,\n    $sidebarToggleBtn: null,\n    $sidebarCloseBtn: null,\n    $mainHeading: null,\n    $main: null,\n    $search: null,\n    $elements: null,\n    $tbody: null,\n    $primaryButtons: null,\n    $secondaryButtons: null,\n    $cancelBtn: null,\n\n    init: function (elementType, settings) {\n      this.elementType = elementType;\n      this.setSettings(settings, Craft.BaseElementSelectorModal.defaults);\n      const headingId = 'elementSelectorModalHeading-' + Date.now();\n\n      // Build the modal\n      const $container = $('<div/>', {\n        class: 'modal elementselectormodal',\n        'aria-labelledby': headingId,\n      }).appendTo(Garnish.$bod);\n      const $headingContainer = $('<div/>', {\n        class: this.settings.showTitle ? 'header' : 'visually-hidden',\n      }).appendTo($container);\n      $('<h1/>', {\n        id: headingId,\n        text: this.settings.modalTitle,\n      }).appendTo($headingContainer);\n      const $body = $('<div/>', {\n        class: 'body',\n      })\n        .append($('<div/>', {class: 'spinner big'}))\n        .appendTo($container);\n      this.$footer = $('<div/>', {\n        class: 'footer',\n      }).appendTo($container);\n\n      if (this.settings.fullscreen) {\n        $container.addClass('fullscreen');\n        this.settings.minGutter = 0;\n      }\n\n      this.base($container, this.settings);\n\n      this.$secondaryButtons = $(\n        '<div class=\"buttons left secondary-buttons\"/>'\n      ).appendTo(this.$footer);\n      this.$primaryButtons = $('<div class=\"buttons right\"/>').appendTo(\n        this.$footer\n      );\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$primaryButtons);\n      this.$selectBtn = Craft.ui\n        .createSubmitButton({\n          class: 'disabled',\n          label: this.settings.selectBtnLabel,\n          spinner: true,\n        })\n        .attr('aria-disabled', 'true')\n        .appendTo(this.$primaryButtons);\n\n      this.$body = $body;\n\n      this.addListener(this.$cancelBtn, 'activate', 'cancel');\n      this.addListener(this.$selectBtn, 'activate', 'selectElements');\n    },\n\n    updateModalBottomPadding: function () {\n      const footerHeight = this.$footer.outerHeight();\n      const bottomPadding = parseInt(this.$container.css('padding-bottom'));\n\n      if (footerHeight !== bottomPadding) {\n        this.$container.css('padding-bottom', footerHeight);\n      }\n    },\n\n    updateSidebarView: function () {\n      if (!this.supportSidebarToggleView) return;\n\n      if (this.sidebarShouldBeHidden()) {\n        if (!this.$sidebarToggleBtn) this.buildSidebarToggleView();\n      } else {\n        if (this.$sidebarToggleBtn) this.resetView();\n      }\n    },\n\n    sidebarShouldBeHidden: function () {\n      const contentWidth = this.$container.outerWidth();\n      return contentWidth < 550;\n    },\n\n    resetView: function () {\n      if (this.$mainHeader) {\n        this.$mainHeader.remove();\n      }\n\n      if (this.$sidebarHeader) {\n        this.$sidebarHeader.remove();\n      }\n\n      this.$sidebarToggleBtn = null;\n      this.$body.addClass('has-sidebar');\n      this.$content.addClass('has-sidebar');\n      this.$sidebar.removeClass('hidden');\n    },\n\n    buildSidebarToggleView: function () {\n      if (this.$sidebarToggleBtn || !this.sidebarShouldBeHidden()) return;\n\n      this.$sidebarHeader = $('<div class=\"sidebar-header\"/>').prependTo(\n        this.$sidebar\n      );\n\n      this.$sidebarCloseBtn = Craft.ui\n        .createButton({\n          class: 'nav-close close-btn',\n        })\n        .attr('aria-label', Craft.t('app', 'Close'))\n        .removeClass('btn')\n        .appendTo(this.$sidebarHeader);\n\n      this.$mainHeader = $('<div class=\"main-header\"/>').prependTo(this.$main);\n      this.$mainHeading = $(\n        `<h2 class=\"main-heading\">${this.getActiveSourceName()}</h2>`\n      ).appendTo(this.$mainHeader);\n\n      const buttonConfig = {\n        toggle: true,\n        controls: 'modal-sidebar',\n        class: 'nav-toggle',\n      };\n      this.$sidebarToggleBtn = Craft.ui\n        .createButton(buttonConfig)\n        .removeClass('btn')\n        .attr('aria-label', Craft.t('app', 'Show sidebar'))\n        .appendTo(this.$mainHeader);\n\n      this.$sidebar.attr('id', 'modal-sidebar');\n\n      this.closeSidebar();\n\n      this.addListener(this.$sidebarToggleBtn, 'click', () => {\n        this.toggleSidebar();\n      });\n\n      this.addListener(this.$sidebarCloseBtn, 'click', () => {\n        this.toggleSidebar();\n      });\n    },\n\n    sidebarIsOpen: function () {\n      return this.$sidebarToggleBtn.attr('aria-expanded') === 'true';\n    },\n\n    toggleSidebar: function () {\n      if (this.sidebarIsOpen()) {\n        this.closeSidebar();\n      } else {\n        this.openSidebar();\n      }\n    },\n\n    openSidebar: function () {\n      this.$body.addClass('has-sidebar');\n      this.$content.addClass('has-sidebar');\n      this.$sidebar.removeClass('hidden');\n      this.$sidebarToggleBtn.attr('aria-expanded', 'true');\n      this.$sidebar.find(':focusable').first().focus();\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.closeSidebar();\n\n        // If the focus is currently inside the sidebar, refocus the toggle\n        const $focusedEl = Garnish.getFocusedElement();\n        if ($.contains(this.$sidebar.get(0), $focusedEl.get(0)))\n          this.$sidebarToggleBtn.focus();\n      });\n    },\n\n    closeSidebar: function () {\n      if (!this.$sidebarToggleBtn) return;\n\n      if (this.sidebarIsOpen()) {\n        Garnish.uiLayerManager.removeLayer();\n        this.$sidebar.addClass('hidden');\n        this.$sidebarToggleBtn.attr('aria-expanded', 'false');\n      }\n\n      this.$body.removeClass('has-sidebar');\n      this.$content.removeClass('has-sidebar');\n    },\n\n    getActiveSourceName: function () {\n      return this.$sidebar.find('.sel').text();\n    },\n\n    onFadeIn: function () {\n      if (!this.elementIndex) {\n        this._createElementIndex();\n      } else {\n        // make sure we're able to scroll the entire elementIndex if more elements were added\n        // after modal was first initialised\n        this.updateModalBottomPadding();\n\n        // Auto-focus the Search box\n        if (!Garnish.isMobileBrowser(true)) {\n          this.elementIndex.$search.trigger('focus');\n        }\n      }\n\n      this.base();\n    },\n\n    onSelectionChange: function () {\n      this.updateSelectBtnState();\n    },\n\n    onSelectSource: function () {\n      this.updateHeading();\n      this.updateModalBottomPadding();\n    },\n\n    updateHeading: function () {\n      if (!this.$mainHeading) return;\n\n      this.$mainHeading.text(this.getActiveSourceName());\n    },\n\n    updateSelectBtnState: function () {\n      if (this.$selectBtn) {\n        if (this.hasSelection()) {\n          this.enableSelectBtn();\n        } else {\n          this.disableSelectBtn();\n        }\n      }\n    },\n\n    hasSelection: function () {\n      return (\n        this.elementIndex && this.elementIndex.getSelectedElements().length\n      );\n    },\n\n    enableSelectBtn: function () {\n      this.$selectBtn.removeClass('disabled').attr('aria-disabled', 'false');\n    },\n\n    disableSelectBtn: function () {\n      this.$selectBtn.addClass('disabled').attr('aria-disabled', 'true');\n    },\n\n    enableCancelBtn: function () {\n      this.$cancelBtn.removeClass('disabled');\n    },\n\n    disableCancelBtn: function () {\n      this.$cancelBtn.addClass('disabled');\n    },\n\n    showFooterSpinner: function () {\n      this.$selectBtn.addClass('loading');\n    },\n\n    hideFooterSpinner: function () {\n      this.$selectBtn.removeClass('loading');\n    },\n\n    cancel: function () {\n      if (!this.$cancelBtn.hasClass('disabled')) {\n        this.hide();\n      }\n    },\n\n    selectElements: function () {\n      if (this.hasSelection()) {\n        // TODO: This code shouldn't know about views' elementSelect objects\n        if (this.elementIndex.view && this.elementIndex.view.elementSelect) {\n          this.elementIndex.view.elementSelect.clearMouseUpTimeout();\n        }\n\n        var $selectedElements = this.elementIndex.getSelectedElements(),\n          elementInfo = this.getElementInfo($selectedElements);\n\n        this.onSelect(elementInfo);\n\n        if (this.settings.disableElementsOnSelect) {\n          this.elementIndex.disableElements(\n            this.elementIndex.getSelectedElements()\n          );\n        }\n\n        if (this.settings.hideOnSelect) {\n          this.hide();\n        }\n      }\n    },\n\n    getElementInfo: function ($selectedElements) {\n      var info = [];\n\n      for (var i = 0; i < $selectedElements.length; i++) {\n        var $element = $($selectedElements[i]);\n        var elementInfo = Craft.getElementInfo($element);\n\n        info.push(elementInfo);\n      }\n\n      return info;\n    },\n\n    onShow: function () {\n      this.updateSelectBtnState();\n\n      // Add listeners again since they get removed during modal close\n      this.addListener(Garnish.$win, 'resize', this.updateSidebarView);\n      this.addListener(Garnish.$win, 'resize', this.updateModalBottomPadding);\n\n      this.updateModalBottomPadding();\n      this.updateSidebarView();\n      this.base();\n    },\n\n    onHide: function () {\n      this.closeSidebar();\n      this.base();\n    },\n\n    onSelect: function (elementInfo) {\n      this.settings.onSelect(elementInfo);\n    },\n\n    disable: function () {\n      if (this.elementIndex) {\n        this.elementIndex.disable();\n      }\n\n      this.base();\n    },\n\n    enable: function () {\n      if (this.elementIndex) {\n        this.elementIndex.enable();\n      }\n\n      this.base();\n    },\n\n    getElementIndexParams: function () {\n      // Get the modal body HTML based on the settings\n      const params = {\n        context: 'modal',\n        elementType: this.elementType,\n        sources: this.settings.sources,\n      };\n\n      if (\n        this.settings.showSiteMenu !== null &&\n        this.settings.showSiteMenu !== 'auto'\n      ) {\n        params.showSiteMenu = this.settings.showSiteMenu ? '1' : '0';\n      }\n\n      return params;\n    },\n\n    _createElementIndex: function () {\n      Craft.sendActionRequest('POST', this.settings.bodyAction, {\n        data: this.getElementIndexParams(),\n      }).then((response) => {\n        this.$body.html(response.data.html);\n\n        if (this.$body.has('.sidebar:not(.hidden)').length) {\n          this.$body.addClass('has-sidebar');\n          this.supportSidebarToggleView = true;\n        }\n\n        // Initialize the element index\n        this.elementIndex = Craft.createElementIndex(\n          this.elementType,\n          this.$body,\n          this.getIndexSettings()\n        );\n\n        this.$main = this.elementIndex.$main;\n        this.$sidebar = this.elementIndex.$sidebar;\n        this.$content = this.$body.find('.content');\n\n        this.updateSidebarView();\n        this.updateModalBottomPadding();\n\n        // Double-clicking or double-tapping should select the elements\n        this.addListener(\n          this.elementIndex.$elements,\n          'doubletap',\n          function (ev, touchData) {\n            // Make sure the touch targets are the same\n            // (they may be different if Command/Ctrl/Shift-clicking on multiple elements quickly)\n            // and make sure the element is actually selectable\n            if (\n              touchData.firstTap.target === touchData.secondTap.target &&\n              this.elementIndex.view.elementSelect.getItemIndex(\n                touchData.firstTap.target\n              ) != -1\n            ) {\n              this.selectElements();\n            }\n          }\n        );\n\n        this.on('updateSizeAndPosition', () => {\n          this.elementIndex.handleResize();\n        });\n\n        this.updateSelectBtnState();\n      });\n    },\n\n    getIndexSettings: function () {\n      return Object.assign(\n        {\n          context: 'modal',\n          modal: this,\n          storageKey: this.settings.storageKey,\n          condition: this.settings.condition,\n          referenceElementId: this.settings.referenceElementId,\n          referenceElementSiteId: this.settings.referenceElementSiteId,\n          criteria: this.settings.criteria,\n          disabledElementIds: this.settings.disabledElementIds,\n          selectable: true,\n          multiSelect: this.settings.multiSelect,\n          buttonContainer: this.$secondaryButtons,\n          onSelectionChange: () => {\n            if (this.elementIndex) {\n              this.onSelectionChange();\n            }\n          },\n          onSourcePathChange: () => {\n            if (this.elementIndex) {\n              this.onSelectionChange();\n            }\n          },\n          onSelectSource: this.onSelectSource.bind(this),\n          hideSidebar: this.settings.hideSidebar,\n          defaultSiteId: this.settings.defaultSiteId,\n          defaultSource: this.settings.defaultSource,\n          defaultSourcePath: this.settings.defaultSourcePath,\n          showSourcePath: this.settings.showSourcePath,\n        },\n        this.settings.indexSettings\n      );\n    },\n  },\n  {\n    defaults: {\n      fullscreen: false,\n      resizable: true,\n      storageKey: null,\n      sources: null,\n      condition: null,\n      referenceElementId: null,\n      referenceElementSiteId: null,\n      criteria: null,\n      multiSelect: false,\n      showSiteMenu: null,\n      disabledElementIds: [],\n      disableElementsOnSelect: false,\n      hideOnSelect: true,\n      modalTitle: Craft.t('app', 'Select element'),\n      showTitle: false,\n      selectBtnLabel: Craft.t('app', 'Select'),\n      onCancel: $.noop,\n      onSelect: $.noop,\n      hideSidebar: false,\n      defaultSiteId: null,\n      defaultSource: null,\n      defaultSourcePath: null,\n      showSourcePath: true,\n      bodyAction: 'element-selector-modals/body',\n      indexSettings: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Input Generator\n */\nCraft.BaseInputGenerator = Garnish.Base.extend({\n  $source: null,\n  $target: null,\n  $form: null,\n  settings: null,\n\n  listening: null,\n  timeout: null,\n\n  init: function (source, target, settings) {\n    this.$source = $(source);\n    this.$target = $(target);\n    this.$form = this.$source.closest('form');\n\n    this.setSettings(settings);\n\n    this.startListening();\n  },\n\n  setNewSource: function (source) {\n    var listening = this.listening;\n    this.stopListening();\n\n    this.$source = $(source);\n\n    if (listening) {\n      this.startListening();\n    }\n  },\n\n  startListening: function () {\n    if (this.listening) {\n      return;\n    }\n\n    this.listening = true;\n\n    this.addListener(this.$source, 'input', 'onSourceTextChange');\n    this.addListener(this.$target, 'input', 'onTargetTextChange');\n    this.addListener(this.$form, 'submit', 'onFormSubmit');\n  },\n\n  stopListening: function () {\n    if (!this.listening) {\n      return;\n    }\n\n    this.listening = false;\n\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.removeAllListeners(this.$source);\n    this.removeAllListeners(this.$target);\n    this.removeAllListeners(this.$form);\n  },\n\n  onSourceTextChange: function () {\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.timeout = setTimeout(this.updateTarget.bind(this), 250);\n  },\n\n  onTargetTextChange: function () {\n    if (this.$target.get(0) === document.activeElement) {\n      this.stopListening();\n    }\n  },\n\n  onFormSubmit: function () {\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.updateTarget();\n  },\n\n  updateTarget: function () {\n    if (!this.$target.is(':visible')) {\n      return;\n    }\n\n    var sourceVal = this.$source.val();\n\n    if (typeof sourceVal === 'undefined') {\n      // The source input may not exist anymore\n      return;\n    }\n\n    var targetVal = this.generateTargetValue(sourceVal);\n\n    this.$target.val(targetVal);\n\n    for (let i = 0; i < this.$target.length; i++) {\n      this.$target[i].dispatchEvent(\n        new InputEvent('input', {\n          inputType: 'insertText',\n        })\n      );\n      this.$target[i].dispatchEvent(new Event('input'));\n    }\n\n    // If the target already has focus, select its whole value to mimic\n    // the behavior if the value had already been generated and they just tabbed in\n    if (this.$target.is(':focus')) {\n      Craft.selectFullValue(this.$target);\n    }\n  },\n\n  generateTargetValue: function (sourceVal) {\n    return sourceVal;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Category index class\n */\nCraft.CategoryIndex = Craft.BaseElementIndex.extend({\n  editableGroups: null,\n  $newCategoryBtnGroup: null,\n  $newCategoryBtn: null,\n\n  init: function (elementType, $container, settings) {\n    this.editableGroups = [];\n    this.on('selectSource', this.updateButton.bind(this));\n    this.on('selectSite', this.updateButton.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  afterInit: function () {\n    // Find which of the visible groups the user has permission to create new categories in\n    this.editableGroups = Craft.editableCategoryGroups.filter(\n      (g) => !!this.getSourceByKey(`group:${g.uid}`)\n    );\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific category group in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultGroupHandle !== 'undefined'\n    ) {\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = $(this.$sources[i]);\n        if ($source.data('handle') === defaultGroupHandle) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateButton: function () {\n    if (!this.$source) {\n      return;\n    }\n\n    // Get the handle of the selected source\n    const selectedSourceHandle = this.$source.data('handle');\n\n    // Update the New Category button\n    // ---------------------------------------------------------------------\n\n    if (this.editableGroups.length) {\n      // Remove the old button, if there is one\n      if (this.$newCategoryBtnGroup) {\n        this.$newCategoryBtnGroup.remove();\n      }\n\n      // Determine if they are viewing a group that they have permission to create categories in\n      const selectedGroup = this.editableGroups.find(\n        (g) => g.handle === selectedSourceHandle\n      );\n\n      this.$newCategoryBtnGroup = $(\n        '<div class=\"btngroup submit\" data-wrapper/>'\n      );\n      let $menuBtn;\n      const menuId = 'new-category-menu-' + Craft.randomString(10);\n\n      // If they are, show a primary \"New category\" button, and a dropdown of the other groups (if any).\n      // Otherwise only show a menu button\n      if (selectedGroup) {\n        const visibleLabel =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New category')\n            : Craft.t('app', 'New {group} category', {\n                group: selectedGroup.name,\n              });\n        const ariaLabel =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New category in the {group} category group', {\n                group: selectedGroup.name,\n              })\n            : visibleLabel;\n\n        const role = this.settings.context === 'index' ? 'link' : null;\n\n        this.$newCategoryBtn = Craft.ui\n          .createButton({\n            label: visibleLabel,\n            ariaLabel: ariaLabel,\n            spinner: true,\n            role: role,\n          })\n          .addClass('submit add icon')\n          .appendTo(this.$newCategoryBtnGroup);\n\n        this.addListener(this.$newCategoryBtn, 'click mousedown', (ev) => {\n          // If this is the element index, check for Ctrl+clicks and middle button clicks\n          if (\n            this.settings.context === 'index' &&\n            ((ev.type === 'click' && Garnish.isCtrlKeyPressed(ev)) ||\n              (ev.type === 'mousedown' && ev.originalEvent.button === 1))\n          ) {\n            window.open(Craft.getUrl(`categories/${selectedGroup.handle}/new`));\n          } else if (ev.type === 'click') {\n            this._createCategory(selectedGroup.id);\n          }\n        });\n\n        if (this.editableGroups.length > 1) {\n          $menuBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn submit menubtn btngroup-btn-last',\n            'aria-controls': menuId,\n            'data-disclosure-trigger': '',\n            'aria-label': Craft.t(\n              'app',\n              'New category, choose a category group'\n            ),\n          }).appendTo(this.$newCategoryBtnGroup);\n        }\n      } else {\n        this.$newCategoryBtn = $menuBtn = Craft.ui\n          .createButton({\n            label: Craft.t('app', 'New category'),\n            ariaLabel: Craft.t('app', 'New category, choose a category group'),\n            spinner: true,\n          })\n          .addClass('submit add icon menubtn btngroup-btn-last')\n          .attr('aria-controls', menuId)\n          .attr('data-disclosure-trigger', '')\n          .appendTo(this.$newCategoryBtnGroup);\n      }\n\n      this.addButton(this.$newCategoryBtnGroup);\n\n      if ($menuBtn) {\n        const $menuContainer = $('<div/>', {\n          id: menuId,\n          class: 'menu menu--disclosure',\n        }).appendTo(this.$newCategoryBtnGroup);\n        const $ul = $('<ul/>').appendTo($menuContainer);\n\n        for (const group of this.editableGroups) {\n          const anchorRole =\n            this.settings.context === 'index' ? 'link' : 'button';\n          if (this.settings.context === 'index' || group !== selectedGroup) {\n            const $li = $('<li/>').appendTo($ul);\n            const $a = $('<a/>', {\n              role: anchorRole === 'button' ? 'button' : null,\n              href: '#', // Allows for click listener and tab order\n              type: anchorRole === 'button' ? 'button' : null,\n              text: Craft.t('app', 'New {group} category', {\n                group: group.name,\n              }),\n            }).appendTo($li);\n            this.addListener($a, 'click', () => {\n              $menuBtn.data('trigger').hide();\n              this._createCategory(group.id);\n            });\n\n            if (anchorRole === 'button') {\n              this.addListener($a, 'keydown', (event) => {\n                if (event.keyCode === Garnish.SPACE_KEY) {\n                  event.preventDefault();\n                  $menuBtn.data('trigger').hide();\n                  this._createCategory(group.id);\n                }\n              });\n            }\n          }\n        }\n\n        new Garnish.DisclosureMenu($menuBtn);\n      }\n    }\n\n    // Update the URL if we're on the Categories index\n    // ---------------------------------------------------------------------\n\n    if (this.settings.context === 'index') {\n      let uri = 'categories';\n\n      if (selectedSourceHandle) {\n        uri += '/' + selectedSourceHandle;\n      }\n\n      Craft.setPath(uri);\n    }\n  },\n\n  _createCategory: function (groupId) {\n    if (this.$newCategoryBtn.hasClass('loading')) {\n      console.warn('New category creation already in progress.');\n      return;\n    }\n\n    // Find the group\n    const group = this.editableGroups.find((s) => s.id === groupId);\n\n    if (!group) {\n      throw `Invalid category group ID: ${groupId}`;\n    }\n\n    this.$newCategoryBtn.addClass('loading');\n\n    Craft.sendActionRequest('POST', 'elements/create', {\n      data: {\n        elementType: this.elementType,\n        siteId: this.siteId,\n        groupId: groupId,\n      },\n    })\n      .then((ev) => {\n        if (this.settings.context === 'index') {\n          document.location.href = Craft.getUrl(ev.data.cpEditUrl, {fresh: 1});\n        } else {\n          const slideout = Craft.createElementEditor(this.elementType, {\n            siteId: this.siteId,\n            elementId: ev.data.element.id,\n            draftId: ev.data.element.draftId,\n            params: {\n              fresh: 1,\n            },\n          });\n          slideout.on('submit', () => {\n            // Make sure the right group is selected\n            const groupSourceKey = `group:${group.uid}`;\n\n            if (this.sourceKey !== groupSourceKey) {\n              this.selectSourceByKey(groupSourceKey);\n            }\n\n            this.clearSearch();\n            this.selectElementAfterUpdate(ev.data.element.id);\n            this.updateElements();\n          });\n        }\n      })\n      .finally(() => {\n        this.$newCategoryBtn.removeClass('loading');\n      });\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass(\n  'craft\\\\elements\\\\Category',\n  Craft.CategoryIndex\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Category select input\n * @deprecated in 4.3.0. Use Craft.BaseElementSelectInput instead.\n */\nCraft.CategorySelectInput = Craft.BaseElementSelectInput.extend({\n  setSettings: function () {\n    this.base.apply(this, arguments);\n    this.settings.sortable = false;\n  },\n\n  getModalSettings: function () {\n    var settings = this.base();\n    settings.hideOnSelect = false;\n    return settings;\n  },\n\n  getElements: function () {\n    return this.$elementsContainer.find('.element');\n  },\n\n  onModalSelect: function (elements) {\n    // Disable the modal\n    this.modal.disable();\n    this.modal.disableCancelBtn();\n    this.modal.disableSelectBtn();\n    this.modal.showFooterSpinner();\n\n    // Get the new category HTML\n    var selectedCategoryIds = this.getSelectedElementIds();\n\n    for (var i = 0; i < elements.length; i++) {\n      selectedCategoryIds.push(elements[i].id);\n    }\n\n    var data = {\n      categoryIds: selectedCategoryIds,\n      siteId: elements[0].siteId,\n      id: this.settings.id,\n      name: this.settings.name,\n      branchLimit: this.settings.branchLimit,\n      selectionLabel: this.settings.selectionLabel,\n    };\n\n    const onResponse = () => {\n      this.modal.enable();\n      this.modal.enableCancelBtn();\n      this.modal.enableSelectBtn();\n      this.modal.hideFooterSpinner();\n    };\n    Craft.sendActionRequest('POST', 'categories/input-html', {data})\n      .then((response) => {\n        onResponse();\n        var $newInput = $(response.data.html),\n          $newElementsContainer = $newInput.children('.elements');\n\n        this.$elementsContainer.replaceWith($newElementsContainer);\n        this.$elementsContainer = $newElementsContainer;\n        this.resetElements();\n\n        var filteredElements = [];\n\n        for (var i = 0; i < elements.length; i++) {\n          var element = elements[i],\n            $element = this.getElementById(element.id);\n\n          if ($element) {\n            this.animateElementIntoPlace(element.$element, $element);\n            filteredElements.push(element);\n          }\n        }\n\n        this.updateDisabledElementsInModal();\n        this.modal.hide();\n        this.onSelectElements(filteredElements);\n      })\n      .catch(({response}) => {\n        onResponse();\n      });\n  },\n\n  removeElement: function ($element) {\n    // Find any descendants this category might have\n    const $allCategories = $element.add(\n      $element.parent().siblings('ul').find('.element')\n    );\n\n    // Remove our record of them all at once\n    this.removeElements($allCategories);\n\n    // Animate them away one at a time\n    for (let i = 0; i < $allCategories.length; i++) {\n      this._animateCategoryAway($allCategories, i);\n    }\n  },\n\n  _animateCategoryAway: function ($allCategories, i) {\n    let callback;\n\n    // Is this the last one?\n    if (i === $allCategories.length - 1) {\n      callback = () => {\n        const $li = $allCategories.first().parent().parent();\n        const $ul = $li.parent();\n\n        if ($ul[0] === this.$elementsContainer[0] || $li.siblings().length) {\n          $li.remove();\n        } else {\n          $ul.remove();\n        }\n      };\n    }\n\n    const func = () => {\n      this.animateElementAway($allCategories.eq(i), callback);\n    };\n\n    if (i === 0) {\n      func();\n    } else {\n      setTimeout(func, 100 * i);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Craft Charts\n */\n\nCraft.charts = {};\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.DataTable\n */\nCraft.charts.DataTable = Garnish.Base.extend({\n  columns: null,\n  rows: null,\n\n  init: function (data) {\n    let columns = data.columns;\n    let rows = data.rows;\n\n    rows.forEach((d) => {\n      $.each(d, function (cellIndex) {\n        var column = columns[cellIndex];\n\n        var parseTime;\n\n        switch (column.type) {\n          case 'date':\n            parseTime = d3.timeParse('%Y-%m-%d');\n            d[cellIndex] = parseTime(d[cellIndex]);\n            break;\n\n          case 'datetime':\n            parseTime = d3.timeParse('%Y-%m-%d %H:00:00');\n            d[cellIndex] = parseTime(d[cellIndex]);\n            break;\n\n          case 'percent':\n            d[cellIndex] = d[cellIndex] / 100;\n            break;\n\n          case 'number':\n            d[cellIndex] = +d[cellIndex];\n            break;\n\n          default:\n          // do nothing\n        }\n      });\n    });\n\n    this.columns = columns;\n    this.rows = rows;\n  },\n});\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Tip\n */\n\nCraft.charts.Tip = Garnish.Base.extend({\n  $container: null,\n  $tip: null,\n\n  init: function ($container) {\n    this.$container = $container;\n\n    this.$tip = $('<div class=\"tooltip\"></div>').appendTo(this.$container);\n\n    this.hide();\n  },\n\n  setContent: function (html) {\n    this.$tip.html(html);\n  },\n\n  setPosition: function (position) {\n    this.$tip.css('left', `${position.left}px`);\n    this.$tip.css('top', `${position.top}px`);\n  },\n\n  show: function () {\n    this.$tip.css('display', 'block');\n  },\n\n  hide: function () {\n    this.$tip.css('display', 'none');\n  },\n});\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.BaseChart\n */\nCraft.charts.BaseChart = Garnish.Base.extend(\n  {\n    $container: null,\n    $chart: null,\n\n    chartBaseClass: 'cp-chart',\n    dataTable: null,\n\n    formatLocale: null,\n    timeFormatLocale: null,\n    orientation: null,\n\n    svg: null,\n    width: null,\n    height: null,\n\n    init: function (container, settings) {\n      this.$container = container;\n\n      this.setSettings(Craft.charts.BaseChart.defaults);\n      this.setSettings(settings);\n\n      var globalSettings = {\n        formats: window.d3Formats,\n        formatLocaleDefinition: window.d3FormatLocaleDefinition,\n        timeFormatLocaleDefinition: window.d3TimeFormatLocaleDefinition,\n      };\n\n      this.setSettings(globalSettings);\n\n      d3.select(window).on('resize', () => {\n        this.resize();\n      });\n    },\n\n    setSettings: function (settings, defaults) {\n      var baseSettings =\n        typeof this.settings === 'undefined' ? {} : this.settings;\n      this.settings = $.extend(true, {}, baseSettings, defaults, settings);\n    },\n\n    draw: function (dataTable, settings) {\n      // Settings and chart attributes\n\n      this.setSettings(settings);\n\n      this.dataTable = dataTable;\n      this.formatLocale = d3.formatLocale(this.settings.formatLocaleDefinition);\n      this.timeFormatLocale = d3.timeFormatLocale(\n        this.settings.timeFormatLocaleDefinition\n      );\n      this.orientation = this.settings.orientation;\n\n      // Set (or reset) the chart element\n\n      if (this.$chart) {\n        this.$chart.remove();\n      }\n\n      var className = this.chartBaseClass;\n\n      if (this.settings.chartClass) {\n        className += ' ' + this.settings.chartClass;\n      }\n\n      this.$chart = $(`<div class=\"${className}\" />`).appendTo(this.$container);\n    },\n\n    resize: function () {\n      this.draw(this.dataTable, this.settings);\n    },\n\n    onAfterDrawTicks: function () {\n      // White border for ticks' text\n      $('.tick', this.$chart).each(function (tickKey, tick) {\n        var $tickText = $('text', tick);\n\n        var $clone = $tickText.clone();\n        $clone.appendTo(tick);\n\n        $tickText.attr('stroke', '#ffffff');\n        $tickText.attr('stroke-width', 3);\n      });\n    },\n  },\n  {\n    defaults: {\n      formatLocaleDefinition: null,\n      timeFormatLocaleDefinition: null,\n      formats: {\n        numberFormat: ',.2f',\n        percentFormat: ',.2%',\n        currencyFormat: '$,.2f',\n        shortDateFormats: {\n          day: '%-m/%-d',\n          month: '%-m/%y',\n          year: '%Y',\n        },\n      },\n      margin: {top: 0, right: 0, bottom: 0, left: 0},\n      chartClass: null,\n      colors: ['#0594D1', '#DE3800', '#FF9A00', '#009802', '#9B009B'],\n    },\n  }\n);\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Area\n */\nCraft.charts.Area = Craft.charts.BaseChart.extend(\n  {\n    tip: null,\n    drawingArea: null,\n\n    init: function (container, settings) {\n      this.base(container, Craft.charts.Area.defaults);\n\n      this.setSettings(settings);\n    },\n\n    draw: function (dataTable, settings) {\n      this.base(dataTable, settings);\n\n      if (this.tip) {\n        this.tip = null;\n      }\n\n      var margin = this.getChartMargin();\n\n      this.width = this.$chart.width() - margin.left - margin.right;\n      this.height = this.$chart.height() - margin.top - margin.bottom;\n\n      // Append SVG to chart element\n\n      var svg = {\n        width: this.width + (margin.left + margin.right),\n        height: this.height + (margin.top + margin.bottom),\n        translateX: this.orientation !== 'rtl' ? margin.left : margin.right,\n        translateY: margin.top,\n      };\n\n      this.svg = d3\n        .select(this.$chart.get(0))\n        .append('svg')\n        .attr('width', svg.width)\n        .attr('height', svg.height);\n\n      this.drawingArea = this.svg\n        .append('g')\n        .attr('transform', `translate(${svg.translateX},${svg.translateY})`);\n\n      // Draw elements\n\n      this.drawTicks();\n      this.drawAxes();\n      this.drawChart();\n      this.drawTipTriggers();\n    },\n\n    drawTicks: function () {\n      // Draw X ticks\n\n      var x = this.getX(true);\n      var xTicks = 3;\n      var xAxis = d3\n        .axisBottom(x)\n        .tickFormat(this.getXFormatter())\n        .ticks(xTicks);\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'x ticks-axis')\n        .attr('transform', `translate(0, ${this.height})`)\n        .call(xAxis);\n\n      // Draw Y ticks\n\n      var y = this.getY();\n      var yTicks = 2;\n      var yAxis;\n\n      if (this.orientation !== 'rtl') {\n        yAxis = d3\n          .axisLeft(y)\n          .tickFormat(this.getYFormatter())\n          .tickValues(this.getYTickValues())\n          .ticks(yTicks);\n\n        this.drawingArea.append('g').attr('class', 'y ticks-axis').call(yAxis);\n      } else {\n        yAxis = d3\n          .axisRight(y)\n          .tickFormat(this.getYFormatter())\n          .tickValues(this.getYTickValues())\n          .ticks(yTicks);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'y ticks-axis')\n          .attr('transform', `translate(${this.width},0)`)\n          .call(yAxis);\n      }\n\n      // On after draw ticks\n\n      this.onAfterDrawTicks();\n    },\n\n    drawAxes: function () {\n      if (this.settings.xAxis.showAxis) {\n        var x = this.getX();\n        var xAxis = d3.axisBottom(x).ticks(0).tickSizeOuter(0);\n        this.drawingArea\n          .append('g')\n          .attr('class', 'x axis')\n          .attr('transform', `translate(0, ${this.height})`)\n          .call(xAxis);\n      }\n\n      if (this.settings.yAxis.showAxis) {\n        var y = this.getY();\n        var chartPadding = 0;\n        var yAxis;\n\n        if (this.orientation === 'rtl') {\n          yAxis = d3.axisLeft(y).ticks(0);\n          this.drawingArea\n            .append('g')\n            .attr('class', 'y axis')\n            .attr('transform', `translate(${this.width - chartPadding}, 0)`)\n            .call(yAxis);\n        } else {\n          yAxis = d3.axisRight(y).ticks(0);\n          this.drawingArea\n            .append('g')\n            .attr('class', 'y axis')\n            .attr('transform', `translate(${chartPadding}, 0)`)\n            .call(yAxis);\n        }\n      }\n    },\n\n    drawChart: function () {\n      var x = this.getX(true);\n      var y = this.getY();\n\n      // X & Y grid lines\n\n      if (this.settings.xAxis.gridlines) {\n        var xLineAxis = d3.axisBottom(x);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'x grid-line')\n          .attr('transform', `translate(0,${this.height})`)\n          .call(xLineAxis.tickSize(-this.height, 0, 0).tickFormat(''));\n      }\n\n      var yTicks = 2;\n\n      if (this.settings.yAxis.gridlines) {\n        var yLineAxis = d3.axisLeft(y);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'y grid-line')\n          .attr('transform', 'translate(0 , 0)')\n          .call(\n            yLineAxis\n              .tickSize(-this.width, 0)\n              .tickFormat('')\n              .tickValues(this.getYTickValues())\n              .ticks(yTicks)\n          );\n      }\n\n      // Line\n\n      var line = d3\n        .line()\n        .x(function (d) {\n          return x(d[0]);\n        })\n        .y(function (d) {\n          return y(d[1]);\n        });\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'chart-line')\n        .append('path')\n        .datum(this.dataTable.rows)\n        .style('fill', 'none')\n        .style('stroke', this.settings.colors[0])\n        .style('stroke-width', '3px')\n        .attr('d', line);\n\n      // Area\n\n      var area = d3\n        .area()\n        .x(function (d) {\n          return x(d[0]);\n        })\n        .y0(this.height)\n        .y1(function (d) {\n          return y(d[1]);\n        });\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'chart-area')\n        .append('path')\n        .datum(this.dataTable.rows)\n        .style('fill', this.settings.colors[0])\n        .style('fill-opacity', '0.3')\n        .attr('d', area);\n\n      // Plots\n\n      if (this.settings.plots) {\n        this.drawingArea\n          .append('g')\n          .attr('class', 'plots')\n          .selectAll('circle')\n          .data(this.dataTable.rows)\n          .enter()\n          .append('circle')\n          .style('fill', this.settings.colors[0])\n          .attr('class', (d, index) => `plot plot-${index}`)\n          .attr('r', 4)\n          .attr('cx', (d) => x(d[0]))\n          .attr('cy', (d) => y(d[1]));\n      }\n    },\n\n    drawTipTriggers: function () {\n      if (this.settings.tips) {\n        if (!this.tip) {\n          this.tip = new Craft.charts.Tip(this.$chart);\n        }\n\n        // Define xAxisTickInterval\n\n        var chartMargin = this.getChartMargin();\n        var tickSizeOuter = 6;\n        var length =\n          this.drawingArea.select('.x path.domain').node().getTotalLength() -\n          chartMargin.left -\n          chartMargin.right -\n          tickSizeOuter * 2;\n        var xAxisTickInterval = length / (this.dataTable.rows.length - 1);\n\n        // Tip trigger width\n\n        var tipTriggerWidth = Math.max(0, xAxisTickInterval);\n\n        // Draw triggers\n\n        var x = this.getX(true);\n        var y = this.getY();\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'tip-triggers')\n          .selectAll('rect')\n          .data(this.dataTable.rows)\n          .enter()\n          .append('rect')\n          .attr('class', 'tip-trigger')\n          .style('fill', 'transparent')\n          .style('fill-opacity', '1')\n          .attr('width', tipTriggerWidth)\n          .attr('height', this.height)\n          .attr('x', (d) => x(d[0]) - tipTriggerWidth / 2)\n          .on('mouseover', (d, index) => {\n            // Expand plot\n\n            this.drawingArea.select('.plot-' + index).attr('r', 5);\n\n            // Set tip content\n\n            var $content = $('<div />');\n            var $xValue = $('<div class=\"x-value\" />').appendTo($content);\n            var $yValue = $('<div class=\"y-value\" />').appendTo($content);\n\n            $xValue.html(this.getXFormatter()(d[0]));\n            $yValue.html(this.getYFormatter()(d[1]));\n\n            var content = $content.get(0);\n\n            this.tip.setContent(content);\n\n            // Set tip position\n\n            var margin = this.getChartMargin();\n\n            var offset = 24;\n            var top = y(d[1]) + offset;\n            var left;\n\n            if (this.orientation !== 'rtl') {\n              left = x(d[0]) + margin.left + offset;\n\n              var calcLeft =\n                this.$chart.offset().left + left + this.tip.$tip.width();\n              var maxLeft =\n                this.$chart.offset().left + this.$chart.width() - offset;\n\n              if (calcLeft > maxLeft) {\n                left = x(d[0]) - (this.tip.$tip.width() + offset);\n              }\n            } else {\n              left = x(d[0]) - (this.tip.$tip.width() + margin.left + offset);\n            }\n\n            if (left < 0) {\n              left = x(d[0]) + margin.left + offset;\n            }\n\n            var position = {\n              top: top,\n              left: left,\n            };\n\n            this.tip.setPosition(position);\n\n            // Show tip\n\n            this.tip.show();\n          })\n          .on('mouseout', (d, index) => {\n            // Unexpand Plot\n            this.drawingArea.select('.plot-' + index).attr('r', 4);\n\n            // Hide tip\n            this.tip.hide();\n          });\n      }\n    },\n\n    getChartMargin: function () {\n      var margin = this.settings.margin;\n\n      // Estimate the max width of y ticks and set it as the left margin\n\n      var values = this.getYTickValues();\n      var yTicksMaxWidth = 0;\n\n      $.each(values, (key, value) => {\n        var characterWidth = 8;\n\n        var formatter = this.getYFormatter();\n\n        var formattedValue = formatter(value);\n        var computedTickWidth = formattedValue.length * characterWidth;\n\n        if (computedTickWidth > yTicksMaxWidth) {\n          yTicksMaxWidth = computedTickWidth;\n        }\n      });\n\n      yTicksMaxWidth += 10;\n\n      margin.left = yTicksMaxWidth;\n\n      return margin;\n    },\n\n    getX: function (padded) {\n      var xDomainMin = d3.min(this.dataTable.rows, function (d) {\n        return d[0];\n      });\n\n      var xDomainMax = d3.max(this.dataTable.rows, function (d) {\n        return d[0];\n      });\n\n      var xDomain = [xDomainMin, xDomainMax];\n\n      if (this.orientation === 'rtl') {\n        xDomain = [xDomainMax, xDomainMin];\n      }\n\n      var left = 0;\n      var right = 0;\n\n      if (padded) {\n        left = 0;\n        right = 0;\n      }\n\n      var x = d3.scaleTime().range([left, this.width - right]);\n\n      x.domain(xDomain);\n\n      return x;\n    },\n\n    getY: function () {\n      var yDomain = [0, this.getYMaxValue()];\n\n      var y = d3.scaleLinear().range([this.height, 0]);\n\n      y.domain(yDomain);\n\n      return y;\n    },\n\n    getXFormatter: function () {\n      var formatter;\n\n      if (this.settings.xAxis.formatter !== $.noop) {\n        formatter = this.settings.xAxis.formatter(this);\n      } else {\n        formatter = Craft.charts.utils.getTimeFormatter(\n          this.timeFormatLocale,\n          this.settings\n        );\n      }\n\n      return formatter;\n    },\n\n    getYFormatter: function () {\n      var formatter;\n\n      if (this.settings.yAxis.formatter !== $.noop) {\n        formatter = this.settings.yAxis.formatter(this);\n      } else {\n        formatter = Craft.charts.utils.getNumberFormatter(\n          this.formatLocale,\n          this.dataTable.columns[1].type,\n          this.settings\n        );\n      }\n\n      return formatter;\n    },\n\n    getYMaxValue: function () {\n      return d3.max(this.dataTable.rows, function (d) {\n        return d[1];\n      });\n    },\n\n    getYTickValues: function () {\n      var maxValue = this.getYMaxValue();\n\n      if (maxValue > 1) {\n        return [maxValue / 2, maxValue];\n      } else {\n        return [0, maxValue];\n      }\n    },\n  },\n  {\n    defaults: {\n      chartClass: 'area',\n      margin: {top: 25, right: 5, bottom: 25, left: 0},\n      plots: true,\n      tips: true,\n      xAxis: {\n        gridlines: false,\n        showAxis: true,\n        formatter: $.noop,\n      },\n      yAxis: {\n        gridlines: true,\n        showAxis: false,\n        formatter: $.noop,\n      },\n    },\n  }\n);\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Utils\n */\nCraft.charts.utils = {\n  getDuration: function (seconds) {\n    var secondsNum = parseInt(seconds, 10);\n\n    var duration = {\n      hours: Math.floor(secondsNum / 3600),\n      minutes: Math.floor((secondsNum - duration.hours * 3600) / 60),\n      seconds: secondsNum - duration.hours * 3600 - duration.minutes * 60,\n    };\n\n    if (duration.hours < 10) {\n      duration.hours = `0${duration.hours}`;\n    }\n\n    if (duration.minutes < 10) {\n      duration.minutes = `0${duration.minutes}`;\n    }\n\n    if (duration.seconds < 10) {\n      duration.seconds = `0${duration.seconds}`;\n    }\n\n    return `${duration.hours}:${duration.minutes}:${duration.seconds}`;\n  },\n\n  getTimeFormatter: function (timeFormatLocale, chartSettings) {\n    switch (chartSettings.dataScale) {\n      case 'year':\n        return timeFormatLocale.format('%Y');\n\n      case 'month':\n        return timeFormatLocale.format(\n          chartSettings.formats.shortDateFormats.month\n        );\n\n      case 'hour':\n        return timeFormatLocale.format(\n          `${chartSettings.formats.shortDateFormats.day} %H:00:00`\n        );\n\n      default:\n        return timeFormatLocale.format(\n          chartSettings.formats.shortDateFormats.day\n        );\n    }\n  },\n\n  getNumberFormatter: function (formatLocale, type, chartSettings) {\n    switch (type) {\n      case 'currency':\n        return formatLocale.format(chartSettings.formats.currencyFormat);\n\n      case 'percent':\n        return formatLocale.format(chartSettings.formats.percentFormat);\n\n      case 'time':\n        return Craft.charts.utils.getDuration;\n\n      case 'number':\n        return formatLocale.format(chartSettings.formats.numberFormat);\n    }\n  },\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Color input\n */\nCraft.ColorInput = Garnish.Base.extend(\n  {\n    $container: null,\n    $input: null,\n    $colorContainer: null,\n    $colorPreview: null,\n    $colorInput: null,\n\n    init: function (container) {\n      this.$container = $(container);\n      this.$input = this.$container.find('.color-input');\n      this.$colorContainer = this.$container.children('.color');\n      this.$colorPreview = this.$colorContainer.children('.color-preview');\n\n      this.createColorInput();\n      this.handleTextChange();\n\n      this.addListener(this.$input, 'input', 'handleTextChange');\n    },\n\n    createColorInput: function () {\n      var input = document.createElement('input');\n      input.setAttribute('type', 'color');\n\n      if (input.type !== 'color') {\n        // The browser doesn't support input[type=color]\n        return;\n      }\n\n      this.$colorContainer.removeClass('static');\n      this.$colorInput = $(input)\n        .addClass('color-preview-input')\n        .attr({\n          'aria-controls': this.$input.attr('id'),\n          'aria-label': Craft.t('app', 'Color picker'),\n        })\n        .appendTo(this.$colorPreview);\n\n      this.addListener(this.$colorInput, 'click', function (ev) {\n        ev.stopPropagation();\n      });\n\n      this.addListener(this.$colorContainer, 'click', function () {\n        this.$colorInput.trigger('click');\n      });\n\n      this.addListener(this.$colorInput, 'input', 'updateColor');\n    },\n\n    updateColor: function () {\n      this.$input.val(this.$colorInput.val());\n      this.handleTextChange();\n    },\n\n    handleTextChange: function () {\n      let val = this.$input.val();\n\n      if (val !== (val = Craft.trim(val))) {\n        this.$input.val(val);\n      }\n\n      // Chop off the #\n      if (val.length && val[0] === '#') {\n        val = val.substring(1);\n        this.$input.val(val);\n      }\n\n      // If empty, set the preview to transparent\n      if (!val.length) {\n        this.$colorPreview.css('background-color', '');\n        return;\n      }\n\n      // Now normalize it for the UI stuff\n      if (val.length === 3) {\n        val = val[0].repeat(2) + val[1].repeat(2) + val[2].repeat(2);\n      }\n\n      if (val.match(/^[0-9a-f]{6}$/i)) {\n        this.$colorPreview.css('background-color', `#${val}`);\n        if (this.$colorInput) {\n          this.$colorInput.val(`#${val}`);\n        }\n      } else {\n        this.$colorPreview.css('background-color', '');\n      }\n    },\n  },\n  {\n    _browserSupportsColorInputs: null,\n\n    doesBrowserSupportColorInputs: function () {\n      if (Craft.ColorInput._browserSupportsColorInputs === null) {\n      }\n\n      return Craft.ColorInput._browserSupportsColorInputs;\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * CP Screen Slideout\n */\nCraft.CpScreenSlideout = Craft.Slideout.extend(\n  {\n    action: null,\n\n    namespace: null,\n\n    showingLoadSpinner: false,\n    hasTabs: false,\n    hasCpLink: false,\n    hasSidebar: false,\n\n    $header: null,\n    $toolbar: null,\n    $tabContainer: null,\n    $loadSpinner: null,\n    $editLink: null,\n    $sidebarBtn: null,\n\n    $body: null,\n    $content: null,\n\n    $sidebar: null,\n\n    $footer: null,\n    $noticeContainer: null,\n    $cancelBtn: null,\n    $saveBtn: null,\n\n    tabManager: null,\n    showingSidebar: false,\n\n    cancelToken: null,\n    ignoreFailedRequest: false,\n    fieldsWithErrors: null,\n\n    init: function (action, settings) {\n      this.action = action;\n      this.setSettings(settings, Craft.CpScreenSlideout.defaults);\n\n      this.fieldsWithErrors = [];\n\n      // Header\n      this.$header = $('<header/>', {class: 'pane-header'});\n      this.$toolbar = $('<div/>', {class: 'so-toolbar'}).appendTo(this.$header);\n      this.$tabContainer = $('<div/>', {class: 'pane-tabs'}).appendTo(\n        this.$toolbar\n      );\n      this.$loadSpinner = $('<div/>', {\n        class: 'spinner',\n        title: Craft.t('app', 'Loading'),\n        'aria-label': Craft.t('app', 'Loading'),\n      }).appendTo(this.$toolbar);\n      this.$editLink = $('<a/>', {\n        target: '_blank',\n        class: 'btn header-btn hidden',\n        title: Craft.t('app', 'Open the full edit page in a new tab'),\n        'aria-label': Craft.t('app', 'Open the full edit page in a new tab'),\n        'data-icon': 'external',\n      }).appendTo(this.$toolbar);\n      this.$sidebarBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn header-btn hidden sidebar-btn',\n        title: Craft.t('app', 'Show sidebar'),\n        'aria-label': Craft.t('app', 'Show sidebar'),\n        'data-icon': `sidebar-${Garnish.ltr ? 'right' : 'left'}`,\n        'aria-expanded': 'false',\n      }).appendTo(this.$toolbar);\n\n      this.addListener(this.$sidebarBtn, 'click', (ev) => {\n        ev.preventDefault();\n        if (!this.showingSidebar) {\n          this.showSidebar();\n        } else {\n          this.hideSidebar();\n        }\n      });\n\n      // Body\n      this.$body = $('<div/>', {class: 'so-body'});\n\n      // Content\n      this.$content = $('<div/>', {class: 'so-content'}).appendTo(this.$body);\n\n      // Sidebar\n      this.$sidebar = $('<div/>', {\n        class: 'so-sidebar details hidden',\n      }).appendTo(this.$body);\n\n      // Footer\n      this.$footer = $('<div/>', {class: 'so-footer hidden'});\n      this.$noticeContainer = $('<div/>', {class: 'so-notice'}).appendTo(\n        this.$footer\n      );\n      $('<div/>', {class: 'flex-grow'}).appendTo(this.$footer);\n      const $btnContainer = $('<div/>', {class: 'flex flex-nowrap'}).appendTo(\n        this.$footer\n      );\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo($btnContainer);\n      this.$saveBtn = Craft.ui\n        .createSubmitButton({\n          label: Craft.t('app', 'Save'),\n          spinner: true,\n        })\n        .appendTo($btnContainer);\n\n      let $contents = this.$header.add(this.$body).add(this.$footer);\n\n      this.base($contents, {\n        containerElement: 'form',\n        containerAttributes: {\n          id: `cp-screen-${Math.floor(Math.random() * 100000000)}`,\n          action: '',\n          method: 'post',\n          novalidate: '',\n          class: 'cp-screen',\n        },\n        closeOnEsc: false,\n        closeOnShadeClick: false,\n      });\n\n      this.$container.data('cpScreen', this);\n      this.on('beforeClose', () => {\n        this.hideSidebar();\n      });\n\n      // Register shortcuts & events\n      Garnish.uiLayerManager.registerShortcut(\n        {\n          keyCode: Garnish.S_KEY,\n          ctrl: true,\n        },\n        (ev) => {\n          this.handleSubmit(ev);\n        }\n      );\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.closeMeMaybe();\n      });\n      this.addListener(this.$cancelBtn, 'click', () => {\n        this.closeMeMaybe();\n      });\n      this.addListener(this.$shade, 'click', () => {\n        this.closeMeMaybe();\n      });\n      this.addListener(this.$container, 'click', (ev) => {\n        const $target = $(event.target);\n\n        if (\n          this.showingSidebar &&\n          !$target.closest(this.$sidebarBtn).length &&\n          !$target.closest(this.$sidebar).length\n        ) {\n          this.hideSidebar();\n        }\n      });\n      this.addListener(this.$container, 'submit', 'handleSubmit');\n\n      this.load();\n    },\n\n    /**\n     * @param {Object} [data={}]\n     * @param {boolean} [refreshInitialData=true]\n     * @returns {Promise}\n     */\n    load: function (data, refreshInitialData) {\n      return new Promise((resolve, reject) => {\n        this.trigger('beforeLoad');\n        this.showLoadSpinner();\n\n        if (this.cancelToken) {\n          this.ignoreFailedRequest = true;\n          this.cancelToken.cancel();\n        }\n\n        this.cancelToken = axios.CancelToken.source();\n\n        Craft.sendActionRequest(\n          'GET',\n          this.action,\n          $.extend(\n            {\n              params: Object.assign({}, this.getParams(), this.settings.params),\n              cancelToken: this.cancelToken.token,\n              headers: {\n                'X-Craft-Container-Id': this.$container.attr('id'),\n              },\n            },\n            this.settings.requestOptions\n          )\n        )\n          .then((response) => {\n            this.update(response.data)\n              .then(() => {\n                if (refreshInitialData !== false) {\n                  this.$container.data('delta-names', response.data.deltaNames);\n                  this.$container.data(\n                    'initial-delta-values',\n                    response.data.initialDeltaValues\n                  );\n                  this.$container.data(\n                    'initialSerializedValue',\n                    this.$container.serialize()\n                  );\n                }\n                resolve();\n              })\n              .catch((e) => {\n                reject(e);\n              });\n          })\n          .catch((e) => {\n            if (!this.ignoreFailedRequest) {\n              Craft.cp.displayError();\n              reject(e);\n            }\n            this.ignoreFailedRequest = false;\n          })\n          .finally(() => {\n            this.hideLoadSpinner();\n            this.cancelToken = null;\n          });\n      });\n    },\n\n    getParams: function () {\n      return {};\n    },\n\n    updateHeaderVisibility: function () {\n      // Should the header be shown regardless of viewport size?\n      const forceShow =\n        this.settings.showHeader ||\n        this.hasTabs ||\n        this.hasCpLink ||\n        this.showingLoadSpinner;\n\n      if (forceShow || this.hasSidebar) {\n        this.$header.removeClass('hidden');\n      } else {\n        this.$header.addClass('hidden');\n      }\n\n      if (forceShow) {\n        this.$header.addClass('so-visible');\n      } else {\n        this.$header.removeClass('so-visible');\n      }\n    },\n\n    showLoadSpinner: function () {\n      this.$loadSpinner.removeClass('hidden');\n      this.showingLoadSpinner = true;\n      this.updateHeaderVisibility();\n    },\n\n    hideLoadSpinner: function () {\n      this.$loadSpinner.addClass('hidden');\n      this.showingLoadSpinner = false;\n      this.updateHeaderVisibility();\n    },\n\n    /**\n     * @param {Object} data\n     * @returns {Promise}\n     */\n    update: function (data) {\n      return new Promise((resolve) => {\n        this.namespace = data.namespace;\n        this.$content.html(data.content);\n\n        if (data.submitButtonLabel) {\n          this.$saveBtn.text(data.submitButtonLabel);\n        }\n\n        this.updateTabs(data.tabs);\n\n        if (data.formAttributes) {\n          Craft.setElementAttributes(this.$container, data.formAttributes);\n        }\n\n        if (data.editUrl) {\n          this.$editLink.removeClass('hidden').attr('href', data.editUrl);\n          this.hasCpLink = true;\n        } else {\n          this.$editLink.addClass('hidden');\n          this.hasCpLink = false;\n        }\n\n        if (data.sidebar) {\n          this.$container.addClass('has-sidebar');\n          this.$sidebarBtn.removeClass('hidden');\n          this.$sidebar.html(data.sidebar);\n\n          // Open outbound links in new windows\n          this.$sidebar.find('a').each(function () {\n            if (\n              this.hostname.length &&\n              typeof $(this).attr('target') === 'undefined'\n            ) {\n              $(this).attr('target', '_blank');\n            }\n          });\n\n          this.hasSidebar = true;\n        } else {\n          this.$container.removeClass('has-sidebar');\n          this.$sidebarBtn.addClass('hidden');\n          this.$sidebar.addClass('hidden').html('');\n          this.hasSidebar = false;\n        }\n\n        if (data.notice) {\n          this.$noticeContainer.html(data.notice);\n        } else {\n          this.$noticeContainer.empty();\n        }\n\n        this.updateHeaderVisibility();\n        this.$footer.removeClass('hidden');\n\n        Garnish.requestAnimationFrame(() => {\n          Craft.appendHeadHtml(data.headHtml);\n          Craft.appendBodyHtml(data.bodyHtml);\n\n          Craft.initUiElements(this.$content);\n          Craft.cp.elementThumbLoader.load($(this.$content));\n\n          if (data.sidebar) {\n            Craft.initUiElements(this.$sidebar);\n            Craft.cp.elementThumbLoader.load(this.$sidebar);\n          }\n\n          if (!Garnish.isMobileBrowser()) {\n            Craft.setFocusWithin(this.$content);\n          }\n\n          resolve();\n          this.trigger('load');\n        });\n      });\n    },\n\n    updateTabs: function (tabs) {\n      if (this.tabManager) {\n        this.tabManager.destroy();\n        this.tabManager = null;\n        this.$tabContainer.html('');\n      }\n\n      this.hasTabs = !!tabs;\n\n      if (this.hasTabs) {\n        const $tabContainer = $(tabs);\n        this.$tabContainer.replaceWith($tabContainer);\n        this.$tabContainer = $tabContainer;\n        this.tabManager = new Craft.Tabs(this.$tabContainer);\n        this.tabManager.on('deselectTab', (ev) => {\n          $(ev.$tab.attr('href')).addClass('hidden');\n        });\n        this.tabManager.on('selectTab', (ev) => {\n          $(ev.$tab.attr('href')).removeClass('hidden');\n          Garnish.$win.trigger('resize');\n          this.$body.trigger('scroll');\n        });\n      }\n    },\n\n    showSidebar: function () {\n      if (this.showingSidebar) {\n        return;\n      }\n\n      this.$body.scrollTop(0).addClass('no-scroll');\n\n      this.$sidebar\n        .off('transitionend.so')\n        .css(this._closedSidebarStyles())\n        .removeClass('hidden');\n\n      // Hack to force CSS animations\n      this.$sidebar[0].offsetWidth;\n\n      this.$sidebar.css(this._openedSidebarStyles());\n\n      if (!Garnish.isMobileBrowser()) {\n        this.$sidebar.one('transitionend.so', () => {\n          Craft.setFocusWithin(this.$sidebar);\n        });\n      }\n\n      Craft.trapFocusWithin(this.$sidebar);\n\n      this.$sidebarBtn.addClass('active').attr({\n        'aria-expanded': 'true',\n      });\n\n      Garnish.$win.trigger('resize');\n      this.$sidebar.trigger('scroll');\n\n      Garnish.uiLayerManager.addLayer();\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.hideSidebar();\n      });\n\n      this.showingSidebar = true;\n    },\n\n    hideSidebar: function () {\n      if (!this.showingSidebar) {\n        return;\n      }\n\n      this.$body.removeClass('no-scroll');\n\n      this.$sidebar\n        .off('transitionend.so')\n        .css(this._closedSidebarStyles())\n        .one('transitionend.so', () => {\n          this.$sidebar.addClass('hidden');\n          this.$sidebarBtn.focus();\n        });\n\n      this.$sidebarBtn.removeClass('active').attr({\n        'aria-expanded': 'false',\n      });\n\n      Garnish.uiLayerManager.removeLayer();\n\n      this.showingSidebar = false;\n    },\n\n    _openedSidebarStyles: function () {\n      return {\n        [Garnish.ltr ? 'right' : 'left']: '0',\n      };\n    },\n\n    _closedSidebarStyles: function () {\n      return {\n        [Garnish.ltr ? 'right' : 'left']: '-350px',\n      };\n    },\n\n    showSubmitSpinner: function () {\n      this.$saveBtn.addClass('loading');\n    },\n\n    hideSubmitSpinner: function () {\n      this.$saveBtn.removeClass('loading');\n    },\n\n    handleSubmit: function (ev) {\n      ev.preventDefault();\n      this.submit();\n    },\n\n    submit: function () {\n      this.showSubmitSpinner();\n\n      const data = Craft.findDeltaData(\n        this.$container.data('initialSerializedValue'),\n        this.$container.serialize(),\n        this.$container.data('delta-names'),\n        null,\n        this.$container.data('initial-delta-values')\n      );\n\n      Craft.sendActionRequest('POST', null, {\n        data,\n        headers: {\n          'X-Craft-Namespace': this.namespace,\n        },\n      })\n        .then((response) => {\n          this.handleSubmitResponse(response);\n        })\n        .catch((error) => {\n          this.handleSubmitError(error);\n        })\n        .finally(() => {\n          this.hideSubmitSpinner();\n        });\n    },\n\n    handleSubmitResponse: function (response) {\n      this.clearErrors();\n      const data = response.data || {};\n      if (data.message) {\n        Craft.cp.displaySuccess(data.message, data.notificationSettings);\n      }\n      this.trigger('submit', {\n        response: response,\n        data: (data.modelName && data[data.modelName]) || {},\n      });\n      if (this.settings.closeOnSubmit) {\n        this.close();\n      }\n    },\n\n    handleSubmitError: function (error) {\n      if (\n        !error.isAxiosError ||\n        !error.response ||\n        !error.response.status === 400\n      ) {\n        Craft.cp.displayError();\n        throw error;\n      }\n\n      const data = error.response.data || {};\n      Craft.cp.displayError(data.message);\n      if (data.errors) {\n        this.showErrors(data.errors);\n      }\n    },\n\n    /**\n     * @param {string[]} errors\n     */\n    showErrors: function (errors) {\n      this.clearErrors();\n\n      Object.entries(errors).forEach(([name, fieldErrors]) => {\n        const $field = this.$container.find(`[data-attribute=\"${name}\"]`);\n        if ($field) {\n          Craft.ui.addErrorsToField($field, fieldErrors);\n          this.fieldsWithErrors.push($field);\n        }\n      });\n    },\n\n    clearErrors: function () {\n      this.fieldsWithErrors.forEach(($field) => {\n        Craft.ui.clearErrorsFromField($field);\n      });\n    },\n\n    isDirty: function () {\n      return (\n        typeof this.$container.data('initialSerializedValue') !== 'undefined' &&\n        this.$container.serialize() !==\n          this.$container.data('initialSerializedValue')\n      );\n    },\n\n    closeMeMaybe: function () {\n      if (!this.isOpen) {\n        return;\n      }\n\n      if (\n        !this.isDirty() ||\n        confirm(\n          Craft.t(\n            'app',\n            'Are you sure you want to close this screen? Any changes will be lost.'\n          )\n        )\n      ) {\n        this.close();\n      }\n    },\n\n    close: function () {\n      this.base();\n\n      if (this.cancelToken) {\n        this.ignoreFailedRequest = true;\n        this.cancelToken.cancel();\n      }\n    },\n  },\n  {\n    defaults: {\n      params: {},\n      requestOptions: {},\n      showHeader: null,\n      closeOnSubmit: true,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n// Use old jQuery prefilter behavior\n// see https://jquery.com/upgrade-guide/3.5/\nvar rxhtmlTag =\n  /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\\/\\0>\\x20\\t\\r\\n\\f]*)[^>]*)\\/>/gi;\njQuery.htmlPrefilter = function (html) {\n  return html.replace(rxhtmlTag, '<$1></$2>');\n};\n\n// Set all the standard Craft.* stuff\n$.extend(Craft, {\n  navHeight: 48,\n\n  /**\n   * @callback indexKeyCallback\n   * @param {Object} currentValue\n   * @param {number} [index]\n   * @returns {string}\n   */\n  /**\n   * Indexes an array of objects by a specified key\n   *\n   * @param {Object[]} arr\n   * @param {(string|indexKeyCallback)} key\n   */\n  index: function (arr, key) {\n    if (!$.isArray(arr)) {\n      throw 'The first argument passed to Craft.index() must be an array.';\n    }\n\n    return arr.reduce((index, obj, i) => {\n      index[typeof key === 'string' ? obj[key] : key(obj, i)] = obj;\n      return index;\n    }, {});\n  },\n\n  /**\n   * Groups an array of objects by a specified key\n   *\n   * @param {Object[]} arr\n   * @param {(string|indexKeyCallback)} key\n   */\n  group: function (arr, key) {\n    if (!$.isArray(arr)) {\n      throw 'The first argument passed to Craft.group() must be an array.';\n    }\n\n    let index = {};\n\n    return arr.reduce((grouped, obj, i) => {\n      const thisKey = typeof key === 'string' ? obj[key] : key(obj, i);\n      if (!index.hasOwnProperty(thisKey)) {\n        index[thisKey] = [[], thisKey];\n        grouped.push(index[thisKey]);\n      }\n      index[thisKey][0].push(obj);\n      return grouped;\n    }, []);\n  },\n\n  /**\n   * Get a translated message.\n   *\n   * @param {string} category\n   * @param {string} message\n   * @param {Object} params\n   * @returns {string}\n   */\n  t: function (category, message, params) {\n    if (\n      typeof Craft.translations[category] !== 'undefined' &&\n      typeof Craft.translations[category][message] !== 'undefined'\n    ) {\n      message = Craft.translations[category][message];\n    }\n\n    if (params) {\n      return this.formatMessage(message, params);\n    }\n\n    return message;\n  },\n\n  formatMessage: function (pattern, args) {\n    let tokens;\n    if ((tokens = this._tokenizePattern(pattern)) === false) {\n      throw 'Message pattern is invalid.';\n    }\n    for (let i = 0; i < tokens.length; i++) {\n      let token = tokens[i];\n      if (typeof token === 'object') {\n        if ((tokens[i] = this._parseToken(token, args)) === false) {\n          throw 'Message pattern is invalid.';\n        }\n      }\n    }\n    return tokens.join('');\n  },\n\n  _tokenizePattern: function (pattern) {\n    let depth = 1,\n      start,\n      pos;\n    // Get an array of the string characters (factoring in 3+ byte chars)\n    const chars = [...pattern];\n    if ((start = pos = chars.indexOf('{')) === -1) {\n      return [pattern];\n    }\n    let tokens = [chars.slice(0, pos).join('')];\n    while (true) {\n      let open = chars.indexOf('{', pos + 1);\n      let close = chars.indexOf('}', pos + 1);\n      if (open === -1) {\n        open = false;\n      }\n      if (close === -1) {\n        close = false;\n      }\n      if (open === false && close === false) {\n        break;\n      }\n      if (open === false) {\n        open = chars.length;\n      }\n      if (close > open) {\n        depth++;\n        pos = open;\n      } else {\n        depth--;\n        pos = close;\n      }\n      if (depth === 0) {\n        tokens.push(\n          chars\n            .slice(start + 1, pos)\n            .join('')\n            .split(',', 3)\n        );\n        start = pos + 1;\n        tokens.push(chars.slice(start, open).join(''));\n        start = open;\n      }\n\n      if (depth !== 0 && (open === false || close === false)) {\n        break;\n      }\n    }\n    if (depth !== 0) {\n      return false;\n    }\n\n    return tokens;\n  },\n\n  _parseToken: function (token, args) {\n    // parsing pattern based on ICU grammar:\n    // http://icu-project.org/apiref/icu4c/classMessageFormat.html#details\n    const param = Craft.trim(token[0]);\n    if (typeof args[param] === 'undefined') {\n      return `{${token.join(',')}}`;\n    }\n    const arg = args[param];\n    const type =\n      typeof token[1] !== 'undefined' ? Craft.trim(token[1]) : 'none';\n    switch (type) {\n      case 'number':\n        return (() => {\n          let format =\n            typeof token[2] !== 'undefined' ? Craft.trim(token[2]) : null;\n          if (format !== null && format !== 'integer') {\n            throw `Message format 'number' is only supported for integer values.`;\n          }\n          let number = Craft.formatNumber(arg);\n          let pos;\n          if (format === null && (pos = `${arg}`.indexOf('.')) !== -1) {\n            number += `.${arg.substring(pos + 1)}`;\n          }\n          return number;\n        })();\n      case 'none':\n        return arg;\n      case 'select':\n        return (() => {\n          /* http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html\n                        selectStyle = (selector '{' message '}')+\n                        */\n          if (typeof token[2] === 'undefined') {\n            return false;\n          }\n          let select = this._tokenizePattern(token[2]);\n          let c = select.length;\n          let message = false;\n          for (let i = 0; i + 1 < c; i++) {\n            if (Garnish.isArray(select[i]) || !Garnish.isArray(select[i + 1])) {\n              return false;\n            }\n            let selector = Craft.trim(select[i++]);\n            if (\n              (message === false && selector === 'other') ||\n              selector == arg\n            ) {\n              message = select[i].join(',');\n            }\n          }\n          if (message === false) {\n            return false;\n          }\n          return this.formatMessage(message, args);\n        })();\n      case 'plural':\n        return (() => {\n          /* http://icu-project.org/apiref/icu4c/classicu_1_1PluralFormat.html\n                        pluralStyle = [offsetValue] (selector '{' message '}')+\n                        offsetValue = \"offset:\" number\n                        selector = explicitValue | keyword\n                        explicitValue = '=' number  // adjacent, no white space in between\n                        keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+\n                        message: see MessageFormat\n                        */\n          if (typeof token[2] === 'undefined') {\n            return false;\n          }\n          let plural = this._tokenizePattern(token[2]);\n          const c = plural.length;\n          let message = false;\n          let offset = 0;\n          for (let i = 0; i + 1 < c; i++) {\n            if (\n              typeof plural[i] === 'object' ||\n              typeof plural[i + 1] !== 'object'\n            ) {\n              return false;\n            }\n            let selector = Craft.trim(plural[i++]);\n            let selectorChars = [...selector];\n\n            if (i === 1 && selector.substring(0, 7) === 'offset:') {\n              let pos = [...selector.replace(/[\\n\\r\\t]/g, ' ')].indexOf(' ', 7);\n              if (pos === -1) {\n                throw 'Message pattern is invalid.';\n              }\n              offset = parseInt(\n                Craft.trim(selectorChars.slice(7, pos).join(''))\n              );\n              selector = Craft.trim(\n                selectorChars\n                  .slice(pos + 1, pos + 1 + selectorChars.length)\n                  .join('')\n              );\n            }\n            if (\n              (message === false && selector === 'other') ||\n              (selector[0] === '=' &&\n                parseInt(\n                  selectorChars.slice(1, 1 + selectorChars.length).join('')\n                ) === arg) ||\n              (selector === 'one' && arg - offset === 1)\n            ) {\n              message = (\n                typeof plural[i] === 'string' ? [plural[i]] : plural[i]\n              )\n                .map((p) => {\n                  return p.replace('#', arg - offset);\n                })\n                .join(',');\n            }\n          }\n          if (message === false) {\n            return false;\n          }\n          return this.formatMessage(message, args);\n        })();\n      default:\n        throw `Message format '${type}' is not supported.`;\n    }\n  },\n\n  formatDate: function (date) {\n    if (typeof date !== 'object') {\n      date = new Date(date);\n    }\n\n    return $.datepicker.formatDate(Craft.datepickerOptions.dateFormat, date);\n  },\n\n  /**\n   * Formats a number.\n   *\n   * @param {string} number\n   * @param {string} [format] D3 format\n   * @returns {string}\n   */\n  formatNumber: function (number, format) {\n    if (typeof format == 'undefined') {\n      format = ',.0f';\n    }\n\n    var formatter = d3.formatLocale(d3FormatLocaleDefinition).format(format);\n\n    return formatter(number);\n  },\n\n  /**\n   * @param {string} key\n   * @param {boolean} shift\n   * @param {boolean} alt\n   */\n  shortcutText: function (key, shift, alt) {\n    if (Craft.clientOs === 'Mac') {\n      return (alt ? '⌥' : '') + (shift ? '⇧' : '') + '⌘' + key;\n    }\n    return 'Ctrl+' + (alt ? 'Alt+' : '') + (shift ? 'Shift+' : '') + key;\n  },\n\n  /**\n   * Escapes some HTML.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  escapeHtml: function (str) {\n    return $('<div/>').text(str).html();\n  },\n\n  /**\n   * Escapes special regular expression characters.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  escapeRegex: function (str) {\n    // h/t https://stackoverflow.com/a/9310752\n    return str.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n  },\n\n  /**\n   * Returns the text in a string that might contain HTML tags.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  getText: function (str) {\n    return $('<div/>').html(str).text();\n  },\n\n  /**\n   * Encodes a URI copmonent. Mirrors PHP's rawurlencode().\n   *\n   * @param {string} str\n   * @returns {string}\n   * @see http://stackoverflow.com/questions/1734250/what-is-the-equivalent-of-javascripts-encodeuricomponent-in-php\n   */\n  encodeUriComponent: function (str) {\n    str = encodeURIComponent(str);\n\n    var differences = {\n      '!': '%21',\n      '*': '%2A',\n      \"'\": '%27',\n      '(': '%28',\n      ')': '%29',\n    };\n\n    for (var chr in differences) {\n      var re = new RegExp('\\\\' + chr, 'g');\n      str = str.replace(re, differences[chr]);\n    }\n\n    return str;\n  },\n\n  /**\n   * Selects the full value of a given text input.\n   *\n   * @param {(jQuery|HTMLElement|string)} input\n   */\n  selectFullValue: function (input) {\n    var $input = $(input);\n    var val = $input.val();\n\n    // Does the browser support setSelectionRange()?\n    if (typeof $input[0].setSelectionRange !== 'undefined') {\n      // Select the whole value\n      var length = val.length * 2;\n      $input[0].setSelectionRange(0, length);\n    } else {\n      // Refresh the value to get the cursor positioned at the end\n      $input.val(val);\n    }\n  },\n\n  /**\n   * Formats an ID out of an input name.\n   *\n   * @param {string} inputName\n   * @returns {string}\n   */\n  formatInputId: function (inputName) {\n    return this.rtrim(inputName.replace(/[^\\w\\-]+/g, '-'), '-');\n  },\n\n  /**\n   * @param {string} [path]\n   * @param {(Object|string)} [params]\n   * @param {string} [baseUrl]\n   * @returns {string}\n   */\n  getUrl: function (path, params, baseUrl) {\n    if (typeof path !== 'string') {\n      path = '';\n    }\n\n    // Normalize the params\n    let anchor = null;\n    if ($.isPlainObject(params)) {\n      if (typeof params['#'] !== 'undefined') {\n        anchor = params['#'];\n        delete params['#'];\n      }\n    } else if (typeof params === 'string') {\n      let anchorPos = params.indexOf('#');\n      if (anchorPos !== -1) {\n        anchor = params.substring(anchorPos + 1);\n        params = params.substring(0, anchorPos);\n      }\n      params = Object.fromEntries(new URLSearchParams(params).entries());\n    } else {\n      params = {};\n    }\n\n    // Was there already an anchor on the path?\n    let anchorPos = path.indexOf('#');\n    if (anchorPos !== -1) {\n      // Only keep it if the params didn't specify a new anchor\n      if (!anchor) {\n        anchor = path.substring(anchorPos + 1);\n      }\n      path = path.substring(0, anchorPos);\n    }\n\n    // Were there already any query string params in the path?\n    let qsPos = path.indexOf('?');\n    if (qsPos !== -1) {\n      params = $.extend(\n        Object.fromEntries(\n          new URLSearchParams(path.substring(qsPos + 1)).entries()\n        ),\n        params\n      );\n      path = path.substring(0, qsPos);\n    }\n\n    // Return path if it appears to be an absolute URL.\n    if (path.search('://') !== -1 || path[0] === '/') {\n      return (\n        path +\n        (!$.isEmptyObject(params) ? `?${$.param(params)}` : '') +\n        (anchor ? `#${anchor}` : '')\n      );\n    }\n\n    path = Craft.trim(path, '/');\n\n    // Put it all together\n    let url;\n\n    if (baseUrl) {\n      url = baseUrl;\n\n      if (path && Craft.pathParam) {\n        // Does baseUrl already contain a path?\n        var pathMatch = url.match(\n          new RegExp('[&?]' + Craft.escapeRegex(Craft.pathParam) + '=[^&]+')\n        );\n        if (pathMatch) {\n          url = url.replace(\n            pathMatch[0],\n            Craft.rtrim(pathMatch[0], '/') + '/' + path\n          );\n          path = '';\n        }\n      }\n    } else {\n      url = Craft.baseUrl;\n    }\n\n    // Does the base URL already have a query string?\n    qsPos = url.indexOf('?');\n    if (qsPos !== -1) {\n      params = $.extend(\n        Object.fromEntries(\n          new URLSearchParams(url.substring(qsPos + 1)).entries()\n        ),\n        params\n      );\n      url = url.substring(0, qsPos);\n    }\n\n    if (!Craft.omitScriptNameInUrls && path) {\n      if (Craft.usePathInfo || !Craft.pathParam) {\n        // Make sure that the script name is in the URL\n        if (url.search(Craft.scriptName) === -1) {\n          url = Craft.rtrim(url, '/') + '/' + Craft.scriptName;\n        }\n      } else {\n        // Move the path into the query string params\n\n        // Is the path param already set?\n        if (typeof params[Craft.pathParam] !== 'undefined') {\n          let basePath = Craft.rtrim(params[Craft.pathParam]);\n          path = basePath + (path ? '/' + path : '');\n        }\n\n        params[Craft.pathParam] = path;\n        path = null;\n      }\n    }\n\n    if (path) {\n      url = Craft.rtrim(url, '/') + '/' + path;\n    }\n\n    if (!$.isEmptyObject(params)) {\n      url += `?${$.param(params)}`;\n    }\n\n    if (anchor) {\n      url += `#${anchor}`;\n    }\n\n    return url;\n  },\n\n  /**\n   * @param {string} [path]\n   * @param {(Object|string)} [params]\n   * @returns {string}\n   */\n  getCpUrl: function (path, params) {\n    return this.getUrl(path, params, Craft.baseCpUrl);\n  },\n\n  /**\n   * @param {string} [path]\n   * @param {(Object|string)} [params]\n   * @returns {string}\n   */\n  getSiteUrl: function (path, params) {\n    return this.getUrl(path, params, Craft.baseSiteUrl);\n  },\n\n  /**\n   * Returns an action URL.\n   *\n   * @param {string} action\n   * @param {(Object|string)} [params]\n   * @returns {string}\n   */\n  getActionUrl: function (action, params) {\n    return Craft.getUrl(action, params, Craft.actionUrl);\n  },\n\n  /**\n   * Redirects the window to a given URL.\n   *\n   * @param {string} url\n   */\n  redirectTo: function (url) {\n    document.location.href = this.getUrl(url);\n  },\n\n  /**\n   * Replaces the page’s current URL.\n   *\n   * The location hash will be left intact, unless the given URL specifies one.\n   *\n   * @param {string} url\n   */\n  setUrl: function (url) {\n    if (typeof history === 'undefined') {\n      return;\n    }\n\n    if (!url.match(/#/)) {\n      url += document.location.hash;\n    }\n\n    history.replaceState({}, '', url);\n  },\n\n  /**\n   * Replaces the page’s current URL based on the given path, leaving the current query string and hash intact.\n   *\n   * @param {string} path\n   */\n  setPath: function (path) {\n    this.path = path;\n    this.setUrl(Craft.getUrl(path, document.location.search));\n  },\n\n  /**\n   * Replaces the page’s current URL based on the given query param name and value, leaving the current URI, other query params, and hash intact.\n   *\n   * @param {string} name\n   * @param {*} value\n   */\n  setQueryParam(name, value) {\n    const baseUrl = document.location.origin + document.location.pathname;\n    const params = this.getQueryParams();\n\n    if (typeof value !== 'undefined' && value !== null && value !== false) {\n      params[name] = value;\n    } else {\n      delete params[name];\n    }\n\n    this.setUrl(Craft.getUrl(baseUrl, params));\n  },\n\n  /**\n   * Returns the current URL with a certain page added to it.\n   *\n   * @param {int} page\n   * @returns {string}\n   */\n  getPageUrl: function (page) {\n    let url = document.location.origin + document.location.pathname;\n    url = Craft.rtrim(url, '/');\n\n    let qs = document.location.search\n      ? document.location.search.substring(1)\n      : '';\n\n    // query string-based pagination?\n    if (Craft.pageTrigger[0] === '?') {\n      const pageParam = Craft.pageTrigger.substring(1);\n      // remove the existing page param\n      if (document.location.search) {\n        const params = Object.fromEntries(new URLSearchParams(qs).entries());\n        delete params[pageParam];\n        qs = $.param(params);\n      }\n      if (page !== 1) {\n        qs += (qs !== '' ? '&' : '') + `${pageParam}=${page}`;\n      }\n    } else {\n      // Remove the existing page segment(s)\n      url = url.replace(\n        new RegExp('/' + Craft.escapeRegex(Craft.pageTrigger) + '\\\\d+$'),\n        ''\n      );\n\n      if (page !== 1) {\n        url += `/${Craft.pageTrigger}${page}`;\n      }\n    }\n\n    return url + (qs ? `?${qs}` : '') + document.location.hash;\n  },\n\n  /**\n   * Returns a hidden CSRF token input, if CSRF protection is enabled.\n   *\n   * @returns {string}\n   */\n  getCsrfInput: function () {\n    if (Craft.csrfTokenName) {\n      return (\n        '<input type=\"hidden\" name=\"' +\n        Craft.csrfTokenName +\n        '\" value=\"' +\n        Craft.csrfTokenValue +\n        '\"/>'\n      );\n    } else {\n      return '';\n    }\n  },\n\n  /**\n   * @callback postActionRequestCallback\n   * @param {?Object} response\n   * @param {string} textStatus\n   * @param {Object} jqXHR\n   */\n  /**\n   * Posts an action request to the server.\n   *\n   * @param {string} action\n   * @param {Object} [data]\n   * @param {postActionRequestCallback} [callback]\n   * @param {Object} [options]\n   * @returns {Object}\n   * @deprecated in 3.4.6. sendActionRequest() should be used instead\n   */\n  postActionRequest: function (action, data, callback, options) {\n    // Make 'data' optional\n    if (typeof data === 'function') {\n      options = callback;\n      callback = data;\n      data = {};\n    }\n\n    options = options || {};\n\n    if (options.contentType && options.contentType.match(/\\bjson\\b/)) {\n      if (typeof data === 'object') {\n        data = JSON.stringify(data);\n      }\n      options.contentType = 'application/json; charset=utf-8';\n    }\n\n    var jqXHR = $.ajax(\n      $.extend(\n        {\n          url: Craft.getActionUrl(action),\n          type: 'POST',\n          dataType: 'json',\n          headers: this._actionHeaders(),\n          data: data,\n          success: callback,\n          error: function (jqXHR, textStatus, errorThrown) {\n            // Ignore incomplete requests, likely due to navigating away from the page\n            // h/t https://stackoverflow.com/a/22107079/1688568\n            if (jqXHR.readyState !== 4) {\n              return;\n            }\n\n            if (jqXHR.status !== 400) {\n              if (typeof Craft.cp !== 'undefined') {\n                Craft.cp.displayError();\n              } else {\n                alert(Craft.t('app', 'A server error occurred.'));\n              }\n            }\n\n            if (callback) {\n              callback(\n                jqXHR.status === 400 ? jqXHR.responseJSON : null,\n                textStatus,\n                jqXHR\n              );\n            }\n          },\n        },\n        options\n      )\n    );\n\n    // Call the 'send' callback\n    if (typeof options.send === 'function') {\n      options.send(jqXHR);\n    }\n\n    return jqXHR;\n  },\n\n  _actionHeaders: function () {\n    let headers = {\n      'X-Registered-Asset-Bundles': Object.keys(\n        Craft.registeredAssetBundles\n      ).join(','),\n      'X-Registered-Js-Files': Object.keys(Craft.registeredJsFiles).join(','),\n    };\n\n    if (Craft.csrfTokenValue) {\n      headers['X-CSRF-Token'] = Craft.csrfTokenValue;\n    }\n\n    return headers;\n  },\n\n  /**\n   * Sends a request to a Craft/plugin action\n   * @param {string} method The request action to use ('GET' or 'POST')\n   * @param {?string} [action] The action to request\n   * @param {Object} [options] Axios request options\n   * @returns {Promise}\n   * @since 3.4.6\n   */\n  sendActionRequest: function (method, action, options = {}) {\n    if ($.isPlainObject(action)) {\n      options = action;\n      action = null;\n    }\n\n    if (method.toUpperCase() === 'POST' && action && options.data) {\n      // Avoid conflicting `action` params\n      if (typeof options.data === 'string') {\n        const namespace =\n          options && options.headers && options.headers['X-Craft-Namespace'];\n        const actionName = this.namespaceInputName('action', namespace);\n        options.data += `&${actionName}=${action}`;\n      } else {\n        delete options.data.action;\n      }\n    }\n\n    return new Promise((resolve, reject) => {\n      options = options ? $.extend({}, options) : {};\n      options.method = method;\n      options.url = action ? Craft.getActionUrl(action) : Craft.getCpUrl();\n      options.headers = $.extend(\n        {\n          'X-Requested-With': 'XMLHttpRequest',\n        },\n        options.headers || {},\n        this._actionHeaders()\n      );\n      options.params = $.extend({}, options.params || {}, {\n        // Force Safari to not load from cache\n        v: new Date().getTime(),\n      });\n      axios.request(options).then(resolve).catch(reject);\n    });\n  },\n\n  /**\n   * Sends a request to the Craftnet API.\n   * @param {string} method The request action to use ('GET' or 'POST')\n   * @param {string} uri The API endpoint URI\n   * @param {Object} options Axios request options\n   * @returns {Promise}\n   * @since 3.3.16\n   */\n  sendApiRequest: function (method, uri, options) {\n    return new Promise((resolve, reject) => {\n      options = options ? $.extend({}, options) : {};\n      let cancelToken = options.cancelToken || null;\n\n      // Get the latest headers\n      this._getApiHeaders(cancelToken)\n        .then((apiHeaders) => {\n          // Send the API request\n          options.method = method;\n          options.baseURL = Craft.baseApiUrl;\n          options.url = uri;\n          options.headers = $.extend(apiHeaders, options.headers || {});\n          options.params = $.extend(\n            Craft.apiParams || {},\n            options.params || {},\n            {\n              // Force Safari to not load from cache\n              v: new Date().getTime(),\n            }\n          );\n\n          // Force the API to process the Craft headers if this is the first API request\n          if (!this._apiHeaders) {\n            options.params.processCraftHeaders = 1;\n          }\n\n          if (Craft.httpProxy) {\n            options.proxy = Craft.httpProxy;\n          }\n\n          axios\n            .request(options)\n            .then((apiResponse) => {\n              // Process the response headers\n              this._processApiHeaders(apiResponse.headers, cancelToken)\n                .then(() => {\n                  // Finally return the API response data\n                  resolve(apiResponse.data);\n                })\n                .catch(reject);\n            })\n            .catch(reject);\n        })\n        .catch(reject);\n    });\n  },\n\n  _loadingApiHeaders: false,\n  _apiHeaders: null,\n  _apiHeaderWaitlist: [],\n\n  /**\n   * Returns the headers that should be sent with API requests.\n   *\n   * @param {Object} [cancelToken]\n   * @returns {Promise}\n   */\n  _getApiHeaders: function (cancelToken) {\n    return new Promise((resolve, reject) => {\n      // Are we already loading them?\n      if (this._loadingApiHeaders) {\n        this._apiHeaderWaitlist.push([resolve, reject]);\n        return;\n      }\n\n      // Are the headers already cached?\n      if (this._apiHeaders) {\n        resolve(this._apiHeaders);\n        return;\n      }\n\n      this._loadingApiHeaders = true;\n      this.sendActionRequest('POST', 'app/api-headers', {\n        cancelToken: cancelToken,\n      })\n        .then((response) => {\n          // Make sure we even are waiting for these anymore\n          if (!this._loadingApiHeaders) {\n            reject(e);\n            return;\n          }\n\n          resolve(response.data);\n        })\n        .catch((e) => {\n          this._rejectApiRequests(reject, e);\n        });\n    });\n  },\n\n  _processApiHeaders: function (headers, cancelToken) {\n    return new Promise((resolve, reject) => {\n      // Have we already processed them?\n      if (this._apiHeaders) {\n        resolve();\n        return;\n      }\n\n      this.sendActionRequest('POST', 'app/process-api-response-headers', {\n        data: {\n          headers: headers,\n        },\n        cancelToken: cancelToken,\n      })\n        .then((response) => {\n          // Make sure we even are waiting for these anymore\n          if (!this._loadingApiHeaders) {\n            reject(e);\n            return;\n          }\n\n          this._apiHeaders = response.data;\n          this._loadingApiHeaders = false;\n\n          resolve();\n\n          // Was anything else waiting for them?\n          while (this._apiHeaderWaitlist.length) {\n            this._apiHeaderWaitlist.shift()[0](this._apiHeaders);\n          }\n        })\n        .catch((e) => {\n          this._rejectApiRequests(reject, e);\n        });\n    });\n  },\n\n  _rejectApiRequests: function (reject, e) {\n    this._loadingApiHeaders = false;\n    reject(e);\n    while (this._apiHeaderWaitlist.length) {\n      this._apiHeaderWaitlist.shift()[1](e);\n    }\n  },\n\n  /**\n   * Clears the cached API headers.\n   */\n  clearCachedApiHeaders: function () {\n    this._apiHeaders = null;\n    this._loadingApiHeaders = false;\n\n    // Reject anything in the header waitlist\n    while (this._apiHeaderWaitlist.length) {\n      this._apiHeaderWaitlist.shift()[1]();\n    }\n  },\n\n  /**\n   * Requests a URL and downloads the response.\n   *\n   * @param {string} method the request method to use\n   * @param {string} url the URL\n   * @param {(string|Object)} [body] the request body, if method = POST\n   * @returns {Promise}\n   */\n  downloadFromUrl: function (method, url, body) {\n    return new Promise((resolve, reject) => {\n      // h/t https://nehalist.io/downloading-files-from-post-requests/\n      let request = new XMLHttpRequest();\n      request.open(method, url, true);\n      if (typeof body === 'object') {\n        request.setRequestHeader(\n          'Content-Type',\n          'application/json; charset=UTF-8'\n        );\n        body = JSON.stringify(body);\n      } else {\n        request.setRequestHeader(\n          'Content-Type',\n          'application/x-www-form-urlencoded; charset=UTF-8'\n        );\n      }\n      request.responseType = 'blob';\n\n      request.onload = () => {\n        // Only handle status code 200\n        if (request.status === 200) {\n          // Try to find out the filename from the content disposition `filename` value\n          let disposition = request.getResponseHeader('content-disposition');\n          let matches = /\"([^\"]*)\"/.exec(disposition);\n          let filename =\n            matches != null && matches[1] ? matches[1] : 'Download';\n\n          // Encode the download into an anchor href\n          let contentType = request.getResponseHeader('content-type');\n          let blob = new Blob([request.response], {type: contentType});\n          let link = document.createElement('a');\n          link.href = window.URL.createObjectURL(blob);\n          link.download = filename;\n          document.body.appendChild(link);\n          link.click();\n          document.body.removeChild(link);\n\n          resolve();\n        } else {\n          reject();\n        }\n      };\n\n      request.send(body);\n    });\n  },\n\n  /**\n   * Converts a comma-delimited string into an array.\n   *\n   * @param {string} str\n   * @returns array\n   */\n  stringToArray: function (str) {\n    if (typeof str !== 'string') {\n      return str;\n    }\n\n    var arr = str.split(',');\n    for (var i = 0; i < arr.length; i++) {\n      arr[i] = $.trim(arr[i]);\n    }\n    return arr;\n  },\n\n  /**\n   * @callback findDeltaDataCallback\n   * @param {string} deltaName\n   * @param {Array} params\n   */\n  /**\n   * Compares old and new post data, and removes any values that haven't\n   * changed within the given list of delta namespaces.\n   *\n   * @param {string} oldData\n   * @param {string} newData\n   * @param {Object} deltaNames\n   * @param {findDeltaDataCallback} [callback] Callback function that should be called whenever a new group of modified params has been found\n   * @param {Object} [initialDeltaValues] Initial delta values. If undefined, `Craft.initialDeltaValues` will be used.\n   * @param {Object} [modifiedDeltaNames} List of delta names that should be considered modified regardles of their param values\n   * @returns {string}\n   */\n  findDeltaData: function (\n    oldData,\n    newData,\n    deltaNames,\n    callback,\n    initialDeltaValues,\n    modifiedDeltaNames\n  ) {\n    // Make sure oldData and newData are always strings. This is important because further below String.split is called.\n    oldData = typeof oldData === 'string' ? oldData : '';\n    newData = typeof newData === 'string' ? newData : '';\n    deltaNames = $.isArray(deltaNames) ? deltaNames : [];\n    initialDeltaValues = $.isPlainObject(initialDeltaValues)\n      ? initialDeltaValues\n      : {};\n    modifiedDeltaNames = $.isArray(modifiedDeltaNames)\n      ? modifiedDeltaNames\n      : [];\n\n    // Sort the delta namespaces from least -> most specific\n    deltaNames.sort(function (a, b) {\n      if (a.length === b.length) {\n        return 0;\n      }\n      return a.length > b.length ? 1 : -1;\n    });\n\n    // Group all of the old & new params by namespace\n    var groupedOldParams = this._groupParamsByDeltaNames(\n      oldData.split('&'),\n      deltaNames,\n      false,\n      initialDeltaValues\n    );\n    var groupedNewParams = this._groupParamsByDeltaNames(\n      newData.split('&'),\n      deltaNames,\n      true,\n      false\n    );\n\n    // Figure out which of the new params should actually be posted\n    var params = groupedNewParams.__root__;\n    for (var n = 0; n < deltaNames.length; n++) {\n      if (\n        Craft.inArray(deltaNames[n], modifiedDeltaNames) ||\n        (typeof groupedNewParams[deltaNames[n]] === 'object' &&\n          (typeof groupedOldParams[deltaNames[n]] !== 'object' ||\n            JSON.stringify(groupedOldParams[deltaNames[n]]) !==\n              JSON.stringify(groupedNewParams[deltaNames[n]])))\n      ) {\n        params = params.concat(groupedNewParams[deltaNames[n]]);\n        params.push('modifiedDeltaNames[]=' + deltaNames[n]);\n        if (callback) {\n          callback(deltaNames[n], groupedNewParams[deltaNames[n]]);\n        }\n      }\n    }\n\n    return params.join('&');\n  },\n\n  /**\n   * @param {Object} params\n   * @param {Object} deltaNames\n   * @param {boolean} withRoot\n   * @param {(boolean|Object)} initialValues\n   * @returns {Object}\n   * @private\n   */\n  _groupParamsByDeltaNames: function (\n    params,\n    deltaNames,\n    withRoot,\n    initialValues\n  ) {\n    const grouped = {};\n\n    if (withRoot) {\n      grouped.__root__ = [];\n    }\n\n    const encodeURIComponentExceptEqualChar = (o) =>\n      encodeURIComponent(o).replace('%3D', '=');\n\n    params = params.map((p) => decodeURIComponent(p));\n\n    paramLoop: for (let p = 0; p < params.length; p++) {\n      // loop through the delta names from most -> least specific\n      for (let n = deltaNames.length - 1; n >= 0; n--) {\n        const paramName = params[p].substring(0, deltaNames[n].length + 1);\n        if (\n          paramName === deltaNames[n] + '=' ||\n          paramName === deltaNames[n] + '['\n        ) {\n          if (typeof grouped[deltaNames[n]] === 'undefined') {\n            grouped[deltaNames[n]] = [];\n          }\n          grouped[deltaNames[n]].push(\n            encodeURIComponentExceptEqualChar(params[p])\n          );\n          continue paramLoop;\n        }\n      }\n\n      if (withRoot) {\n        grouped.__root__.push(encodeURIComponentExceptEqualChar(params[p]));\n      }\n    }\n\n    if (initialValues) {\n      const serializeParam = (name, value) => {\n        if ($.isArray(value) || $.isPlainObject(value)) {\n          value = $.param(value);\n        } else if (typeof value === 'string') {\n          value = encodeURIComponent(value);\n        } else if (value === null) {\n          value = '';\n        }\n        return `${encodeURIComponent(name)}=${value}`;\n      };\n\n      for (let name in initialValues) {\n        if (initialValues.hasOwnProperty(name)) {\n          if ($.isPlainObject(initialValues[name])) {\n            grouped[name] = [];\n            for (let subName in initialValues[name]) {\n              if (initialValues[name].hasOwnProperty(subName)) {\n                grouped[name].push(\n                  serializeParam(\n                    `${name}[${subName}]`,\n                    initialValues[name][subName]\n                  )\n                );\n              }\n            }\n          } else {\n            grouped[name] = [serializeParam(name, initialValues[name])];\n          }\n        }\n      }\n    }\n\n    return grouped;\n  },\n\n  /**\n   * Expands an object of POST array-style strings into an actual array.\n   *\n   * @param {Object} arr\n   * @returns {Array}\n   */\n  expandPostArray: function (arr) {\n    var expanded = {};\n    var i;\n\n    for (var key in arr) {\n      if (!arr.hasOwnProperty(key)) {\n        continue;\n      }\n\n      var value = arr[key],\n        m = key.match(/^(\\w+)(\\[.*)?/),\n        keys;\n\n      if (m[2]) {\n        // Get all of the nested keys\n        keys = m[2].match(/\\[[^\\[\\]]*\\]/g);\n\n        // Chop off the brackets\n        for (i = 0; i < keys.length; i++) {\n          keys[i] = keys[i].substring(1, keys[i].length - 1);\n        }\n      } else {\n        keys = [];\n      }\n\n      keys.unshift(m[1]);\n\n      var parentElem = expanded;\n\n      for (i = 0; i < keys.length; i++) {\n        if (i < keys.length - 1) {\n          if (typeof parentElem[keys[i]] !== 'object') {\n            // Figure out what this will be by looking at the next key\n            if (!keys[i + 1] || parseInt(keys[i + 1]) == keys[i + 1]) {\n              parentElem[keys[i]] = [];\n            } else {\n              parentElem[keys[i]] = {};\n            }\n          }\n\n          parentElem = parentElem[keys[i]];\n        } else {\n          // Last one. Set the value\n          if (!keys[i]) {\n            keys[i] = parentElem.length;\n          }\n\n          parentElem[keys[i]] = value;\n        }\n      }\n    }\n\n    return expanded;\n  },\n\n  /**\n   * Creates a form element populated with hidden inputs based on a string of serialized form data.\n   *\n   * @param {string} data\n   * @returns {(jQuery|HTMLElement)}\n   */\n  createForm: function (data) {\n    var $form = $('<form/>', {\n      attr: {\n        method: 'post',\n        action: '',\n        'accept-charset': 'UTF-8',\n      },\n    });\n\n    if (typeof data === 'string') {\n      var values = data.split('&');\n      var chunks;\n      for (var i = 0; i < values.length; i++) {\n        chunks = values[i].split('=', 2);\n        $('<input/>', {\n          type: 'hidden',\n          name: decodeURIComponent(chunks[0]),\n          value: decodeURIComponent(chunks[1] || ''),\n        }).appendTo($form);\n      }\n    }\n\n    return $form;\n  },\n\n  /**\n   * Compares two variables and returns whether they are equal in value.\n   * Recursively compares array and object values.\n   *\n   * @param {*} obj1\n   * @param {*} obj2\n   * @param {boolean} [sortObjectKeys] Whether object keys should be sorted before being compared. Default is true.\n   * @returns boolean\n   */\n  compare: function (obj1, obj2, sortObjectKeys) {\n    // Compare the types\n    if (typeof obj1 !== typeof obj2) {\n      return false;\n    }\n\n    if (typeof obj1 === 'object' && obj1 !== null && obj2 !== null) {\n      // Compare the lengths\n      if (obj1.length !== obj2.length) {\n        return false;\n      }\n\n      // Is one of them an array but the other is not?\n      if (obj1 instanceof Array !== obj2 instanceof Array) {\n        return false;\n      }\n\n      // If they're actual objects (not arrays), compare the keys\n      if (!(obj1 instanceof Array)) {\n        if (typeof sortObjectKeys === 'undefined' || sortObjectKeys === true) {\n          if (\n            !Craft.compare(\n              Craft.getObjectKeys(obj1).sort(),\n              Craft.getObjectKeys(obj2).sort()\n            )\n          ) {\n            return false;\n          }\n        } else {\n          if (\n            !Craft.compare(Craft.getObjectKeys(obj1), Craft.getObjectKeys(obj2))\n          ) {\n            return false;\n          }\n        }\n      }\n\n      // Compare each value\n      for (var i in obj1) {\n        if (!obj1.hasOwnProperty(i)) {\n          continue;\n        }\n\n        if (!Craft.compare(obj1[i], obj2[i])) {\n          return false;\n        }\n      }\n\n      // All clear\n      return true;\n    } else {\n      return obj1 === obj2;\n    }\n  },\n\n  /**\n   * Returns an array of an object's keys.\n   *\n   * @param {Object} obj\n   * @returns {string[]}\n   */\n  getObjectKeys: function (obj) {\n    var keys = [];\n\n    for (var key in obj) {\n      if (!obj.hasOwnProperty(key)) {\n        continue;\n      }\n\n      keys.push(key);\n    }\n\n    return keys;\n  },\n\n  /**\n   * Takes an array or string of chars, and places a backslash before each one, returning the combined string.\n   *\n   * Userd by ltrim() and rtrim()\n   *\n   * @param {(string|Object)} chars\n   * @returns {string}\n   */\n  escapeChars: function (chars) {\n    if (!Garnish.isArray(chars)) {\n      chars = chars.split();\n    }\n\n    var escaped = '';\n\n    for (var i = 0; i < chars.length; i++) {\n      escaped += '\\\\' + chars[i];\n    }\n\n    return escaped;\n  },\n\n  /**\n   * Trim characters off of the beginning of a string.\n   *\n   * @param {string} str\n   * @param {(string|Object)} [chars] The characters to trim off. Defaults to a space if left blank.\n   * @returns {string}\n   */\n  ltrim: function (str, chars) {\n    if (!str) {\n      return str;\n    }\n    if (typeof chars === 'undefined') {\n      chars = ' \\t\\n\\r\\0\\x0B';\n    }\n    var re = new RegExp('^[' + Craft.escapeChars(chars) + ']+');\n    return str.replace(re, '');\n  },\n\n  /**\n   * Trim characters off of the end of a string.\n   *\n   * @param {string} str\n   * @param {(string|Object)} [chars] The characters to trim off. Defaults to a space if left blank.\n   * @returns {string}\n   */\n  rtrim: function (str, chars) {\n    if (!str) {\n      return str;\n    }\n    if (typeof chars === 'undefined') {\n      chars = ' \\t\\n\\r\\0\\x0B';\n    }\n    var re = new RegExp('[' + Craft.escapeChars(chars) + ']+$');\n    return str.replace(re, '');\n  },\n\n  /**\n   * Trim characters off of the beginning and end of a string.\n   *\n   * @param {string} str\n   * @param {(string|Object)} [chars] The characters to trim off. Defaults to a space if left blank.\n   * @returns {string}\n   */\n  trim: function (str, chars) {\n    str = Craft.ltrim(str, chars);\n    str = Craft.rtrim(str, chars);\n    return str;\n  },\n\n  /**\n   * Returns whether a string starts with another string.\n   *\n   * @param {string} str\n   * @param {string} substr\n   * @returns {boolean}\n   */\n  startsWith: function (str, substr) {\n    return str.substring(0, substr.length) === substr;\n  },\n\n  /**\n   * @callback filterArrayCallback\n   * @param {*} value\n   * @param {number} index\n   * @return {boolean}\n   */\n  /**\n   * Filters an array.\n   *\n   * @param {Object} arr\n   * @param {filterArrayCallback} [callback] A user-defined callback function. If null, we'll just remove any elements that equate to false.\n   * @returns {Array}\n   */\n  filterArray: function (arr, callback) {\n    var filtered = [];\n\n    for (var i = 0; i < arr.length; i++) {\n      var include;\n\n      if (typeof callback === 'function') {\n        include = callback(arr[i], i);\n      } else {\n        include = arr[i];\n      }\n\n      if (include) {\n        filtered.push(arr[i]);\n      }\n    }\n\n    return filtered;\n  },\n\n  /**\n   * Returns whether an element is in an array (unlike jQuery.inArray(), which returns the element’s index, or -1).\n   *\n   * @param {*} elem\n   * @param {(Object|Array)} arr\n   * @returns {boolean}\n   */\n  inArray: function (elem, arr) {\n    if ($.isPlainObject(arr)) {\n      arr = Object.values(arr);\n    }\n    return arr.includes(elem);\n  },\n\n  /**\n   * Removes an element from an array.\n   *\n   * @param {*} elem\n   * @param {Array} arr\n   * @returns {boolean} Whether the element could be found or not.\n   */\n  removeFromArray: function (elem, arr) {\n    var index = $.inArray(elem, arr);\n    if (index !== -1) {\n      arr.splice(index, 1);\n      return true;\n    } else {\n      return false;\n    }\n  },\n\n  /**\n   * Returns the last element in an array.\n   *\n   * @param {Array} arr\n   * @returns {*}\n   */\n  getLast: function (arr) {\n    if (!arr.length) {\n      return null;\n    } else {\n      return arr[arr.length - 1];\n    }\n  },\n\n  /**\n   * Makes the first character of a string uppercase.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  uppercaseFirst: function (str) {\n    return str.charAt(0).toUpperCase() + str.slice(1);\n  },\n\n  /**\n   * Makes the first character of a string lowercase.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  lowercaseFirst: function (str) {\n    return str.charAt(0).toLowerCase() + str.slice(1);\n  },\n\n  parseUrl: function (url) {\n    var m = url.match(\n      /^(?:(https?):\\/\\/|\\/\\/)([^\\/\\:]*)(?:\\:(\\d+))?(\\/[^\\?]*)?(?:\\?([^#]*))?(#.*)?/\n    );\n    if (!m) {\n      return {};\n    }\n    return {\n      scheme: m[1],\n      host: m[2] + (m[3] ? ':' + m[3] : ''),\n      hostname: m[2],\n      port: m[3] || null,\n      path: m[4] || '/',\n      query: m[5] || null,\n      hash: m[6] || null,\n    };\n  },\n\n  getQueryParams: function () {\n    return Object.fromEntries(\n      new URLSearchParams(window.location.search).entries()\n    );\n  },\n\n  getQueryParam: function (name) {\n    // h/t https://stackoverflow.com/a/901144/1688568\n    const params = new Proxy(new URLSearchParams(window.location.search), {\n      get: (searchParams, prop) => searchParams.get(prop),\n    });\n    return params[name];\n  },\n\n  isSameHost: function (url) {\n    var requestUrlInfo = this.parseUrl(document.location.href);\n    if (!requestUrlInfo) {\n      return false;\n    }\n    var urlInfo = this.parseUrl(url);\n    if (!urlInfo) {\n      return false;\n    }\n    return requestUrlInfo.host === urlInfo.host;\n  },\n\n  /**\n   * Converts a number of seconds into a human-facing time duration.\n   */\n  secondsToHumanTimeDuration: function (seconds, showSeconds) {\n    if (typeof showSeconds === 'undefined') {\n      showSeconds = true;\n    }\n\n    var secondsInWeek = 604800,\n      secondsInDay = 86400,\n      secondsInHour = 3600,\n      secondsInMinute = 60;\n\n    var weeks = Math.floor(seconds / secondsInWeek);\n    seconds = seconds % secondsInWeek;\n\n    var days = Math.floor(seconds / secondsInDay);\n    seconds = seconds % secondsInDay;\n\n    var hours = Math.floor(seconds / secondsInHour);\n    seconds = seconds % secondsInHour;\n\n    var minutes;\n\n    if (showSeconds) {\n      minutes = Math.floor(seconds / secondsInMinute);\n      seconds = seconds % secondsInMinute;\n    } else {\n      minutes = Math.round(seconds / secondsInMinute);\n      seconds = 0;\n    }\n\n    var timeComponents = [];\n\n    if (weeks) {\n      timeComponents.push(\n        weeks +\n          ' ' +\n          (weeks === 1 ? Craft.t('app', 'week') : Craft.t('app', 'weeks'))\n      );\n    }\n\n    if (days) {\n      timeComponents.push(\n        days +\n          ' ' +\n          (days === 1 ? Craft.t('app', 'day') : Craft.t('app', 'days'))\n      );\n    }\n\n    if (hours) {\n      timeComponents.push(\n        hours +\n          ' ' +\n          (hours === 1 ? Craft.t('app', 'hour') : Craft.t('app', 'hours'))\n      );\n    }\n\n    if (minutes || (!showSeconds && !weeks && !days && !hours)) {\n      timeComponents.push(\n        minutes +\n          ' ' +\n          (minutes === 1 ? Craft.t('app', 'minute') : Craft.t('app', 'minutes'))\n      );\n    }\n\n    if (seconds || (showSeconds && !weeks && !days && !hours && !minutes)) {\n      timeComponents.push(\n        seconds +\n          ' ' +\n          (seconds === 1 ? Craft.t('app', 'second') : Craft.t('app', 'seconds'))\n      );\n    }\n\n    return timeComponents.join(', ');\n  },\n\n  /**\n   * Converts extended ASCII characters to ASCII.\n   *\n   * @param {string} str\n   * @param {Object} [charMap]\n   * @returns {string}\n   */\n  asciiString: function (str, charMap) {\n    // Normalize NFD chars to NFC\n    str = str.normalize('NFC');\n\n    var asciiStr = '';\n    var char;\n\n    for (var i = 0; i < str.length; i++) {\n      char = str.charAt(i);\n      asciiStr +=\n        typeof (charMap || Craft.asciiCharMap)[char] === 'string'\n          ? (charMap || Craft.asciiCharMap)[char]\n          : char;\n    }\n\n    return asciiStr;\n  },\n\n  uuid: function () {\n    if (typeof crypto.randomUUID === 'function') {\n      return crypto.randomUUID();\n    }\n\n    // h/t https://stackoverflow.com/a/2117523/1688568\n    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>\n      (\n        c ^\n        (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))\n      ).toString(16)\n    );\n  },\n\n  /**\n   * @param {string} name\n   * @param {string} [namespace]\n   * @returns {string}\n   */\n  namespaceInputName: function (name, namespace) {\n    if (!namespace) {\n      return name;\n    }\n\n    return name.replace(/([^'\"\\[\\]]+)([^'\"]*)/, `${namespace}[$1]$2`);\n  },\n\n  /**\n   * @param {string} id\n   * @param {string} [namespace]\n   * @returns {string}\n   */\n  namespaceId: function (id, namespace) {\n    return Craft.formatInputId(namespace ? `${namespace}-${id}` : id);\n  },\n\n  randomString: function (length) {\n    // h/t https://stackoverflow.com/a/1349426/1688568\n    var result = '';\n    var characters =\n      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n    for (var i = 0; i < length; i++) {\n      result += characters.charAt(Math.floor(Math.random() * 62));\n    }\n    return result;\n  },\n\n  /**\n   * Creates a validation error list.\n   *\n   * @param {Object} errors\n   * @returns {jQuery}\n   */\n  createErrorList: function (errors) {\n    var $ul = $(document.createElement('ul')).addClass('errors');\n\n    for (var i = 0; i < errors.length; i++) {\n      var $li = $(document.createElement('li'));\n      $li.appendTo($ul);\n      $li.html(errors[i]);\n    }\n\n    return $ul;\n  },\n\n  /**\n   * Appends HTML to the page `<head>`.\n   *\n   * @param {string} html\n   */\n  appendHeadHtml: function (html) {\n    if (!html) {\n      return;\n    }\n\n    // Prune out any link tags that are already included\n    var $existingCss = $('link[href]');\n\n    if ($existingCss.length) {\n      var existingCss = [];\n      var href;\n\n      for (var i = 0; i < $existingCss.length; i++) {\n        href = $existingCss.eq(i).attr('href').replace(/&/g, '&amp;');\n        existingCss.push(Craft.escapeRegex(href));\n      }\n\n      const regexp = new RegExp(\n        '<link\\\\s[^>]*href=\"(?:' + existingCss.join('|') + ')\".*?></link>',\n        'g'\n      );\n\n      html = html.replace(regexp, '');\n    }\n\n    $('head').append(html);\n  },\n\n  /**\n   * Appends HTML to the page `<body>`.\n   *\n   * @param {string} html\n   */\n  appendBodyHtml: function (html) {\n    if (!html) {\n      return;\n    }\n\n    // Prune out any script tags that are already included\n    var $existingJs = $('script[src]');\n\n    if ($existingJs.length) {\n      var existingJs = [];\n      var src;\n\n      for (var i = 0; i < $existingJs.length; i++) {\n        src = $existingJs.eq(i).attr('src').replace(/&/g, '&amp;');\n        existingJs.push(Craft.escapeRegex(src));\n      }\n\n      var regexp = new RegExp(\n        '<script\\\\s[^>]*src=\"(?:' + existingJs.join('|') + ')\".*?></script>',\n        'g'\n      );\n\n      html = html.replace(regexp, '');\n    }\n\n    Garnish.$bod.append(html);\n  },\n\n  /**\n   * Appends HTML to the page `<body>`.\n   *\n   * @deprecated in 4.0.0. `appendBodyHtml()` should be used instead\n   */\n  appendFootHtml: function (html) {\n    console.warn(\n      'Craft.appendFootHtml() is deprecated. Craft.appendBodyHtml() should be used instead.'\n    );\n    this.appendBodyHtml(html);\n  },\n\n  /**\n   * Initializes any common UI elements in a given container.\n   *\n   * @param {Object} $container\n   */\n  initUiElements: function ($container) {\n    $('.grid', $container).grid();\n    $('.info', $container).infoicon();\n    $('.checkbox-select', $container).checkboxselect();\n    $('.fieldtoggle', $container).fieldtoggle();\n    $('.lightswitch', $container).lightswitch();\n    $('.nicetext', $container).nicetext();\n    $('.formsubmit', $container).formsubmit();\n    $('.menubtn:not([data-disclosure-trigger])', $container).menubtn();\n    $('[data-disclosure-trigger]', $container).disclosureMenu();\n    $('.datetimewrapper', $container).datetime();\n    $(\n      '.datewrapper > input[type=\"date\"], .timewrapper > input[type=\"time\"]',\n      $container\n    ).datetimeinput();\n\n    // Open outbound links in new windows\n    // hat tip: https://stackoverflow.com/a/2911045/1688568\n    $('a', $container).each(function () {\n      if (\n        this.hostname.length &&\n        this.hostname !== location.hostname &&\n        typeof $(this).attr('target') === 'undefined'\n      ) {\n        $(this).attr('rel', 'noopener').attr('target', '_blank');\n      }\n    });\n  },\n\n  _elementIndexClasses: {},\n  _elementSelectorModalClasses: {},\n  _elementEditorClasses: {},\n\n  /**\n   * Registers an element index class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementIndexClass: function (elementType, func) {\n    if (typeof this._elementIndexClasses[elementType] !== 'undefined') {\n      throw (\n        'An element index class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementIndexClasses[elementType] = func;\n  },\n\n  /**\n   * Registers an element selector modal class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementSelectorModalClass: function (elementType, func) {\n    if (typeof this._elementSelectorModalClasses[elementType] !== 'undefined') {\n      throw (\n        'An element selector modal class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementSelectorModalClasses[elementType] = func;\n  },\n\n  /**\n   * Registers an element editor class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementEditorClass: function (elementType, func) {\n    if (typeof this._elementEditorClasses[elementType] !== 'undefined') {\n      throw (\n        'An element editor class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementEditorClasses[elementType] = func;\n  },\n\n  /**\n   * Creates a new element index for a given element type.\n   *\n   * @param {string} elementType\n   * @param {jQuery} $container\n   * @param {Object} settings\n   * @returns {BaseElementIndex}\n   */\n  createElementIndex: function (elementType, $container, settings) {\n    var func;\n\n    if (typeof this._elementIndexClasses[elementType] !== 'undefined') {\n      func = this._elementIndexClasses[elementType];\n    } else {\n      func = Craft.BaseElementIndex;\n    }\n\n    return new func(elementType, $container, settings);\n  },\n\n  /**\n   * Creates a new element selector modal for a given element type.\n   *\n   * @param {string} elementType\n   * @param {Object} settings\n   */\n  createElementSelectorModal: function (elementType, settings) {\n    var func;\n\n    if (typeof this._elementSelectorModalClasses[elementType] !== 'undefined') {\n      func = this._elementSelectorModalClasses[elementType];\n    } else {\n      func = Craft.BaseElementSelectorModal;\n    }\n\n    return new func(elementType, settings);\n  },\n\n  /**\n   * Creates a new element editor slideout for a given element type.\n   *\n   * @param {string} elementType\n   * @param {(jQuery|HTMLElement|string)} element\n   * @param {Object} settings\n   */\n  createElementEditor: function (elementType, element, settings) {\n    // Param mapping\n    if (typeof settings === 'undefined' && $.isPlainObject(element)) {\n      // (settings)\n      settings = element;\n      element = null;\n    } else if (typeof settings !== 'object') {\n      settings = {};\n    }\n\n    if (!settings.elementType) {\n      settings.elementType = elementType;\n    }\n\n    return new Craft.ElementEditorSlideout(element, settings);\n  },\n\n  /**\n   * Retrieves a value from localStorage if it exists.\n   *\n   * @param {string} key\n   * @param {*} defaultValue\n   */\n  getLocalStorage: function (key, defaultValue) {\n    key = 'Craft-' + Craft.systemUid + '.' + key;\n\n    if (\n      typeof localStorage !== 'undefined' &&\n      typeof localStorage[key] !== 'undefined'\n    ) {\n      return JSON.parse(localStorage[key]);\n    } else {\n      return defaultValue;\n    }\n  },\n\n  /**\n   * Saves a value to localStorage.\n   *\n   * @param {string} key\n   * @param {*} value\n   */\n  setLocalStorage: function (key, value) {\n    if (typeof localStorage !== 'undefined') {\n      key = 'Craft-' + Craft.systemUid + '.' + key;\n\n      // localStorage might be filled all the way up.\n      // Especially likely if this is a private window in Safari 8+, where localStorage technically exists,\n      // but has a max size of 0 bytes.\n      try {\n        localStorage[key] = JSON.stringify(value);\n      } catch (e) {}\n    }\n  },\n\n  /**\n   * Removes a value from localStorage.\n   * @param {string} key\n   */\n  removeLocalStorage: function (key) {\n    if (typeof localStorage !== 'undefined') {\n      localStorage.removeItem(`Craft-${Craft.systemUid}.${key}`);\n    }\n  },\n\n  /**\n   * Returns a cookie value, if it exists, otherwise returns `false`\n   * @returns {(string|boolean)}\n   */\n  getCookie: function (name) {\n    // Adapted from https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie\n    return document.cookie.replace(\n      new RegExp(\n        `(?:(?:^|.*;\\\\s*)Craft-${Craft.systemUid}:${name}\\\\s*\\\\=\\\\s*([^;]*).*$)|^.*$`\n      ),\n      '$1'\n    );\n  },\n\n  /**\n   * Sets a cookie value.\n   * @param {string} name\n   * @param {string} value\n   * @param {Object} [options]\n   * @param {string} [options.path] The cookie path.\n   * @param {string} [options.domain] The cookie domain. Defaults to the `defaultCookieDomain` config setting.\n   * @param {number} [options.maxAge] The max age of the cookie (in seconds)\n   * @param {Date} [options.expires] The expiry date of the cookie. Defaults to none (session-based cookie).\n   * @param {boolean} [options.secure] Whether this is a secure cookie. Defaults to the `useSecureCookies`\n   * config setting.\n   * @param {string} [options.sameSite] The SameSite value (`lax` or `strict`). Defaults to the\n   * `sameSiteCookieValue` config setting.\n   */\n  setCookie: function (name, value, options) {\n    options = $.extend({}, this.defaultCookieOptions, options);\n    let cookie = `Craft-${Craft.systemUid}:${name}=${encodeURIComponent(\n      value\n    )}`;\n    if (options.path) {\n      cookie += `;path=${options.path}`;\n    }\n    if (options.domain) {\n      cookie += `;domain=${options.domain}`;\n    }\n    if (options.maxAge) {\n      cookie += `;max-age-in-seconds=${options.maxAge}`;\n    } else if (options.expires) {\n      cookie += `;expires=${options.expires.toUTCString()}`;\n    }\n    if (options.secure) {\n      cookie += ';secure';\n    }\n    document.cookie = cookie;\n  },\n\n  /**\n   * Removes a cookie\n   * @param {string} name\n   */\n  removeCookie: function (name) {\n    this.setCookie(name, '', new Date('1970-01-01T00:00:00'));\n  },\n\n  /**\n   * Returns element information from its DOM element.\n   *\n   * @param {(jQuery|HTMLElement|string)} element\n   * @returns {Object}\n   */\n  getElementInfo: function (element) {\n    var $element = $(element);\n\n    if (!$element.hasClass('element')) {\n      $element = $element.find('.element:first');\n    }\n\n    return {\n      id: $element.data('id'),\n      siteId: $element.data('site-id'),\n      label: $element.data('label'),\n      status: $element.data('status'),\n      url: $element.data('url'),\n      hasThumb: $element.hasClass('hasthumb'),\n      $element: $element,\n    };\n  },\n\n  /**\n   * Changes an element to the requested size.\n   *\n   * @param {(jQuery|HTMLElement|string))} element\n   * @param {string} size\n   */\n  setElementSize: function (element, size) {\n    var $element = $(element);\n\n    if (size !== 'small' && size !== 'large') {\n      size = 'small';\n    }\n\n    if ($element.hasClass(size)) {\n      return;\n    }\n\n    var otherSize = size === 'small' ? 'large' : 'small';\n\n    $element.addClass(size).removeClass(otherSize);\n\n    if ($element.hasClass('hasthumb')) {\n      var $oldImg = $element.find('> .elementthumb > img'),\n        imgSize = size === 'small' ? '30' : '100',\n        $newImg = $('<img/>', {\n          sizes: imgSize + 'px',\n          srcset: $oldImg.attr('srcset') || $oldImg.attr('data-pfsrcset'),\n        });\n\n      $oldImg.replaceWith($newImg);\n\n      picturefill({\n        elements: [$newImg[0]],\n      });\n    }\n  },\n\n  /**\n   * Submits a form.\n   * @param {Object} $form\n   * @param {Object} [options]\n   * @param {string} [options.action] The `action` param value override\n   * @param {string} [options.redirect] The `redirect` param value override\n   * @param {string} [options.confirm] A confirmation message that should be shown to the user before submit\n   * @param {Object} [options.params] Additional params that should be added to the form, defined as name/value pairs\n   * @param {Object} [options.data] Additional data to be passed to the submit event\n   * @param {boolean} [options.retainScroll] Whether the scroll position should be stored and reapplied on the next page load\n   */\n  submitForm: function ($form, options) {\n    if (typeof options === 'undefined') {\n      options = {};\n    }\n\n    if (options.confirm && !confirm(options.confirm)) {\n      return;\n    }\n\n    if (options.action) {\n      $('<input/>', {\n        type: 'hidden',\n        name: 'action',\n        val: options.action,\n      }).appendTo($form);\n    }\n\n    if (options.redirect) {\n      $('<input/>', {\n        type: 'hidden',\n        name: 'redirect',\n        val: options.redirect,\n      }).appendTo($form);\n    }\n\n    if (options.params) {\n      for (let name in options.params) {\n        let value = options.params[name];\n        $('<input/>', {\n          type: 'hidden',\n          name: name,\n          val: value,\n        }).appendTo($form);\n      }\n    }\n\n    if (options.retainScroll) {\n      this.setLocalStorage('scrollY', window.scrollY);\n    }\n\n    $form.trigger($.extend({type: 'submit'}, options.data));\n  },\n\n  /**\n   * Traps focus within a container, so when focus is tabbed out of it, it’s cycled back into it.\n   * @param {Object} container\n   */\n  trapFocusWithin: function (container) {\n    Garnish.trapFocusWithin(container);\n  },\n\n  /**\n   * Sets focus to the first focusable element within a container.\n   * @param {Object} container\n   */\n  setFocusWithin: function (container) {\n    Garnish.setFocusWithin(container);\n  },\n\n  /**\n   * Reduces an input’s value to characters that match the given regex pattern.\n   * @param {jQuery|HTMLElement} input\n   * @param {RegExp} regex\n   */\n  filterInputVal: function (input, regex) {\n    const $input = $(input);\n    const val = $input.val();\n    let selectionStart = $input[0].selectionStart;\n    let newVal = '';\n    for (let i = 0; i < val.length; i++) {\n      if (val[i].match(regex)) {\n        newVal += val[i];\n      } else if (i < selectionStart) {\n        selectionStart--;\n      }\n    }\n    if (newVal !== val) {\n      $input.val(newVal);\n      $input[0].setSelectionRange(selectionStart, selectionStart);\n    }\n  },\n\n  /**\n   * Reduces an input’s value to numeric characters.\n   * @param {jQuery|HTMLElement} input\n   * @param {RegExp} regex\n   */\n  filterNumberInputVal: function (input) {\n    this.filterInputVal(input, /[0-9.,\\-]/);\n  },\n\n  /**\n   * Sets/removes attributes on an element.\n   *\n   * Attributes set to `null` or `false` will be removed.\n   *\n   * @param {(jQuery|HTMLElement|string)} element\n   * @param {Object} attributes\n   */\n  setElementAttributes: function (element, attributes) {\n    const $element = $(element);\n\n    for (let name in attributes) {\n      if (!attributes.hasOwnProperty(name)) {\n        continue;\n      }\n\n      let value = attributes[name];\n\n      if (value === null || value === false) {\n        $element.removeAttr(name);\n      } else if (value === true) {\n        $element.attr(name, '');\n      } else if ($.isArray(value) || $.isPlainObject(value)) {\n        if (Craft.dataAttributes.includes(name)) {\n          // Make sure it's an object\n          value = Object.assign({}, value);\n          for (let n in value) {\n            if (!value.hasOwnProperty(n)) {\n              continue;\n            }\n            let subValue = value[n];\n            if (subValue === null || subValue === false) {\n              continue;\n            }\n            if ($.isPlainObject(subValue) || $.isArray(subValue)) {\n              subValue = JSON.stringify(subValue);\n            } else if (subValue === true) {\n              subValue = '';\n            } else {\n              subValue = this.escapeHtml(subValue);\n            }\n            $element.attr(`${name}-${n}`, subValue);\n          }\n        } else if (name === 'class') {\n          // Make sure it's an array\n          if ($.isPlainObject(value)) {\n            value = Object.values(value);\n          }\n          for (let c of value) {\n            $element.addClass(c);\n          }\n        } else if (name === 'style') {\n          $element.css(value);\n        } else {\n          $element.attr(name, JSON.stringify(value));\n        }\n      } else {\n        $element.attr(name, this.escapeHtml(value));\n      }\n    }\n  },\n\n  isVisible: function () {\n    return (\n      typeof document.visibilityState === 'undefined' ||\n      document.visibilityState === 'visible'\n    );\n  },\n\n  useMobileStyles: function () {\n    return Garnish.isMobileBrowser() || document.body.clientWidth < 600;\n  },\n});\n\n// -------------------------------------------\n//  Broadcast channel\n// -------------------------------------------\n\nCraft.pageId = Craft.uuid();\n\nif (typeof BroadcastChannel !== 'undefined') {\n  const channelName = `CraftCMS:${Craft.appId}`;\n  Craft.broadcaster = new BroadcastChannel(channelName);\n  Craft.messageReceiver = new BroadcastChannel(channelName);\n\n  Craft.messageReceiver.addEventListener('message', (ev) => {\n    if (ev.data.event === 'saveElement') {\n      // Are there any instances of the same element on the page?\n      const $elements = $(\n        `div.element[data-id=\"${ev.data.id}\"][data-settings]`\n      );\n      if (!$elements.length) {\n        return;\n      }\n      const data = {\n        type: $elements.data('type'),\n        id: ev.data.id,\n        instances: [],\n      };\n      for (let i = 0; i < $elements.length; i++) {\n        const $element = $elements.eq(i);\n        data.instances.push(\n          Object.assign(\n            {\n              siteId: $element.data('site-id'),\n            },\n            $element.data('settings')\n          )\n        );\n      }\n      Craft.sendActionRequest('POST', 'app/render-element', {data}).then(\n        ({data}) => {\n          for (let i = 0; i < $elements.length; i++) {\n            const $element = $elements.eq(i);\n            if (data.elementHtml[i]) {\n              const $replacement = $(data.elementHtml[i]);\n              for (let attribute of $replacement[0].attributes) {\n                if (attribute.name === 'class') {\n                  $element.addClass(attribute.value);\n                } else {\n                  $element.attr(attribute.name, attribute.value);\n                }\n              }\n              const $inputs = $element.find('input,button').detach();\n              $element.html($replacement.html());\n              if ($inputs.length) {\n                $inputs.prependTo($element);\n              }\n            }\n          }\n          Craft.cp.elementThumbLoader.load($elements);\n        }\n      );\n    }\n  });\n}\n\n// -------------------------------------------\n//  Custom jQuery plugins\n// -------------------------------------------\n\n$.extend($.fn, {\n  animateLeft: function (pos, duration, easing, complete) {\n    if (Craft.orientation === 'ltr') {\n      return this.velocity({left: pos}, duration, easing, complete);\n    } else {\n      return this.velocity({right: pos}, duration, easing, complete);\n    }\n  },\n\n  animateRight: function (pos, duration, easing, complete) {\n    if (Craft.orientation === 'ltr') {\n      return this.velocity({right: pos}, duration, easing, complete);\n    } else {\n      return this.velocity({left: pos}, duration, easing, complete);\n    }\n  },\n\n  /**\n   * Disables elements by adding a .disabled class and preventing them from receiving focus.\n   */\n  disable: function () {\n    return this.each(function () {\n      var $elem = $(this);\n      $elem.addClass('disabled');\n\n      if ($elem.data('activatable')) {\n        $elem.removeAttr('tabindex');\n      }\n    });\n  },\n\n  /**\n   * Enables elements by removing their .disabled class and allowing them to receive focus.\n   */\n  enable: function () {\n    return this.each(function () {\n      var $elem = $(this);\n      $elem.removeClass('disabled');\n\n      if ($elem.data('activatable')) {\n        $elem.attr('tabindex', '0');\n      }\n    });\n  },\n\n  /**\n   * Sets the element as the container of a grid.\n   */\n  grid: function () {\n    return this.each(function () {\n      var $container = $(this),\n        settings = {};\n\n      if ($container.data('item-selector')) {\n        settings.itemSelector = $container.data('item-selector');\n      }\n      if ($container.data('cols')) {\n        settings.cols = parseInt($container.data('cols'));\n      }\n      if ($container.data('max-cols')) {\n        settings.maxCols = parseInt($container.data('max-cols'));\n      }\n      if ($container.data('min-col-width')) {\n        settings.minColWidth = parseInt($container.data('min-col-width'));\n      }\n      if ($container.data('mode')) {\n        settings.mode = $container.data('mode');\n      }\n      if ($container.data('fill-mode')) {\n        settings.fillMode = $container.data('fill-mode');\n      }\n      if ($container.data('col-class')) {\n        settings.colClass = $container.data('col-class');\n      }\n      if ($container.data('snap-to-grid')) {\n        settings.snapToGrid = !!$container.data('snap-to-grid');\n      }\n\n      new Craft.Grid(this, settings);\n    });\n  },\n\n  infoicon: function () {\n    return this.each(function () {\n      new Craft.InfoIcon(this);\n    });\n  },\n\n  /**\n   * Sets the element as a container for a checkbox select.\n   */\n  checkboxselect: function () {\n    return this.each(function () {\n      if (!$.data(this, 'checkboxselect')) {\n        new Garnish.CheckboxSelect(this);\n      }\n    });\n  },\n\n  /**\n   * Sets the element as a field toggle trigger.\n   */\n  fieldtoggle: function () {\n    return this.each(function () {\n      if (!$.data(this, 'fieldtoggle')) {\n        new Craft.FieldToggle(this);\n      }\n    });\n  },\n\n  lightswitch: function (settings, settingName, settingValue) {\n    // param mapping\n    if (settings === 'settings') {\n      if (typeof settingName === 'string') {\n        settings = {};\n        settings[settingName] = settingValue;\n      } else {\n        settings = settingName;\n      }\n\n      return this.each(function () {\n        var obj = $.data(this, 'lightswitch');\n        if (obj) {\n          obj.setSettings(settings);\n        }\n      });\n    } else {\n      if (!$.isPlainObject(settings)) {\n        settings = {};\n      }\n\n      return this.each(function () {\n        var thisSettings = $.extend({}, settings);\n\n        if (Garnish.hasAttr(this, 'data-value')) {\n          thisSettings.value = $(this).attr('data-value');\n        }\n\n        if (Garnish.hasAttr(this, 'data-indeterminate-value')) {\n          thisSettings.indeterminateValue = $(this).attr(\n            'data-indeterminate-value'\n          );\n        }\n\n        if (!$.data(this, 'lightswitch')) {\n          new Craft.LightSwitch(this, thisSettings);\n        }\n      });\n    }\n  },\n\n  nicetext: function () {\n    return this.each(function () {\n      if (!$.data(this, 'nicetext')) {\n        new Garnish.NiceText(this);\n      }\n    });\n  },\n\n  formsubmit: function () {\n    // Secondary form submit buttons\n    return this.on('click', function (ev) {\n      let $btn = $(ev.currentTarget);\n      let params = $btn.data('params') || {};\n      if ($btn.data('param')) {\n        params[$btn.data('param')] = $btn.data('value');\n      }\n\n      let $anchor = $btn.data('menu') ? $btn.data('menu').$anchor : $btn;\n      let $form = $anchor.attr('data-form')\n        ? $('#' + $anchor.attr('data-form'))\n        : $anchor.closest('form');\n\n      Craft.submitForm($form, {\n        confirm: $btn.data('confirm'),\n        action: $btn.data('action'),\n        redirect: $btn.data('redirect'),\n        params: params,\n        data: $.extend(\n          {\n            customTrigger: $btn,\n          },\n          $btn.data('event-data')\n        ),\n      });\n    });\n  },\n\n  menubtn: function () {\n    return this.each(function () {\n      var $btn = $(this);\n\n      if (!$btn.data('menubtn') && $btn.next().hasClass('menu')) {\n        var settings = {};\n\n        if ($btn.data('menu-anchor')) {\n          settings.menuAnchor = $btn.data('menu-anchor');\n        }\n\n        new Garnish.MenuBtn($btn, settings);\n      }\n    });\n  },\n\n  disclosureMenu: function () {\n    return this.each(function () {\n      const $trigger = $(this);\n      // Only instantiate if it's not already a disclosure trigger, and it references a disclosure content\n      if (!$trigger.data('trigger') && $trigger.attr('aria-controls')) {\n        new Garnish.DisclosureMenu($trigger);\n      }\n    });\n  },\n\n  datetime: function () {\n    return this.each(function () {\n      let $wrapper = $(this);\n      let $inputs = $wrapper.find('input:not([name$=\"[timezone]\"])');\n      let checkValue = () => {\n        let hasValue = false;\n        for (let i = 0; i < $inputs.length; i++) {\n          if ($inputs.eq(i).val()) {\n            hasValue = true;\n            break;\n          }\n        }\n        if (hasValue) {\n          if (!$wrapper.children('.clear-btn').length) {\n            let $btn = $('<button/>', {\n              type: 'button',\n              class: 'clear-btn',\n              title: Craft.t('app', 'Clear'),\n              'aria-label': Craft.t('app', 'Clear'),\n            })\n              .appendTo($wrapper)\n              .on('click', () => {\n                for (let i = 0; i < $inputs.length; i++) {\n                  $inputs.eq(i).val('').trigger('input').trigger('change');\n                }\n                $btn.remove();\n                $inputs.first().filter('[type=\"text\"]').focus();\n              });\n          }\n        } else {\n          $wrapper.children('.clear-btn').remove();\n        }\n      };\n      $inputs.on('change', checkValue);\n      checkValue();\n    });\n  },\n\n  datetimeinput: function () {\n    return this.each(function () {\n      const $input = $(this);\n      const checkValue = () => {\n        if ($input.val() === '') {\n          $input.addClass('empty-value');\n        } else {\n          $input.removeClass('empty-value');\n        }\n      };\n      $input.on('input', checkValue);\n      checkValue();\n    });\n  },\n});\n\n// Override Garnish.NiceText.charsLeftHtml() to be more accessible\nGarnish.NiceText.charsLeftHtml = (charsLeft) => {\n  return Craft.t(\n    'app',\n    '<span class=\"visually-hidden\">Characters left:</span> {chars, number}',\n    {\n      chars: charsLeft,\n    }\n  );\n};\n\nGarnish.$doc.ready(function () {\n  Craft.initUiElements();\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Customize Sources modal\n */\nCraft.CustomizeSourcesModal = Garnish.Modal.extend({\n  elementIndex: null,\n  $elementIndexSourcesContainer: null,\n\n  $sidebar: null,\n  $sidebarToggleBtn: null,\n  $sourcesContainer: null,\n  $sourcesHeader: null,\n  $sourcesHeading: null,\n  $sourceSettingsContainer: null,\n  $sourceSettingsHeader: null,\n  $addSourceMenu: null,\n  addSourceMenu: null,\n  $footer: null,\n  $footerBtnContainer: null,\n  $saveBtn: null,\n  $cancelBtn: null,\n  $loadingSpinner: null,\n\n  sourceSort: null,\n  sources: null,\n  selectedSource: null,\n\n  elementTypeName: null,\n  baseSortOptions: null,\n  availableTableAttributes: null,\n  customFieldAttributes: null,\n\n  conditionBuilderHtml: null,\n  conditionBuilderJs: null,\n  userGroups: null,\n\n  init: function (elementIndex, settings) {\n    this.base();\n\n    this.setSettings(settings, {\n      resizable: true,\n    });\n\n    this.elementIndex = elementIndex;\n    this.$elementIndexSourcesContainer = this.elementIndex.$sidebar\n      .children('nav')\n      .children('ul');\n\n    const $container = $(\n      '<form class=\"modal customize-sources-modal\"/>'\n    ).appendTo(Garnish.$bod);\n\n    this.$sidebar = $('<div class=\"cs-sidebar block-types\"/>')\n      .appendTo($container)\n      .attr({\n        role: 'navigation',\n        'aria-label': Craft.t('app', 'Source'),\n      });\n    this.$sourcesContainer = $('<div class=\"sources\">').appendTo(this.$sidebar);\n    this.$sourceSettingsContainer = $('<div class=\"source-settings\">').appendTo(\n      $container\n    );\n\n    this.$footer = $('<div class=\"footer\"/>').appendTo($container);\n    this.$footerBtnContainer = $('<div class=\"buttons right\"/>').appendTo(\n      this.$footer\n    );\n    this.$cancelBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Cancel'),\n    }).appendTo(this.$footerBtnContainer);\n    this.$saveBtn = Craft.ui\n      .createSubmitButton({\n        class: 'disabled',\n        label: Craft.t('app', 'Save'),\n        spinner: true,\n      })\n      .appendTo(this.$footerBtnContainer);\n\n    this.$loadingSpinner = $('<div class=\"spinner\"/>').appendTo(\n      this.$sourceSettingsContainer\n    );\n\n    this.setContainer($container);\n    this.show();\n\n    Craft.sendActionRequest(\n      'POST',\n      'element-index-settings/get-customize-sources-modal-data',\n      {\n        data: {\n          elementType: this.elementIndex.elementType,\n        },\n      }\n    )\n      .then((response) => {\n        this.$saveBtn.removeClass('disabled');\n        this.buildModal(response.data);\n      })\n      .finally(() => {\n        this.$loadingSpinner.remove();\n        Garnish.setFocusWithin(this.$sidebar);\n      });\n\n    this.addListener(this.$cancelBtn, 'click', 'hide');\n    this.addListener(this.$saveBtn, 'click', 'save');\n    this.addListener(this.$container, 'submit', 'save');\n  },\n\n  buildModal: function (response) {\n    this.baseSortOptions = response.baseSortOptions;\n    this.defaultSortOptions = response.defaultSortOptions;\n    this.availableTableAttributes = response.availableTableAttributes;\n    this.customFieldAttributes = response.customFieldAttributes;\n    this.elementTypeName = response.elementTypeName;\n    this.conditionBuilderHtml = response.conditionBuilderHtml;\n    this.conditionBuilderJs = response.conditionBuilderJs;\n    this.userGroups = response.userGroups;\n\n    if (response.headHtml) {\n      Craft.appendHeadHtml(response.headHtml);\n    }\n    if (response.bodyHtml) {\n      Craft.appendBodyHtml(response.bodyHtml);\n    }\n\n    // Create the source item sorter\n    this.sourceSort = new Garnish.DragSort({\n      handle: '.move',\n      axis: 'y',\n    });\n\n    // Create the sources\n    this.sources = [];\n\n    for (let i = 0; i < response.sources.length; i++) {\n      this.sources.push(this.addSource(response.sources[i]));\n    }\n\n    if (!this.selectedSource && typeof this.sources[0] !== 'undefined') {\n      this.sources[0].select();\n    }\n\n    const $menuBtnContainer = $(\n      '<div class=\"buttons left\" data-wrapper/>'\n    ).appendTo(this.$footer);\n    const $menuBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn menubtn add icon',\n      'aria-label': Craft.t('app', 'Add…'),\n      'aria-controls': 'add-source-menu',\n      title: Craft.t('app', 'Add…'),\n      'data-disclosure-trigger': '',\n    }).appendTo($menuBtnContainer);\n\n    this.$addSourceMenu = $('<div/>', {\n      id: 'add-source-menu',\n      class: 'menu menu--disclosure',\n    }).appendTo($menuBtnContainer);\n\n    const addSource = (sourceData) => {\n      const source = this.addSource(sourceData, true);\n      Garnish.scrollContainerToElement(this.$sidebar, source.$item);\n      source.select();\n      this.addSourceMenu.hide();\n    };\n\n    const $newHeadingBtn = $('<button/>', {\n      type: 'button',\n      class: 'menu-option',\n      text: Craft.t('app', 'New heading'),\n    }).on('click', () => {\n      addSource({\n        type: 'heading',\n      });\n      this.focusLabelInput();\n    });\n\n    const $newCustomSourceBtn = $('<button/>', {\n      type: 'button',\n      class: 'menu-option',\n      text: Craft.t('app', 'New custom source'),\n      'data-type': 'custom',\n    }).on('click', () => {\n      const sortOptions = this.baseSortOptions.slice(0);\n      sortOptions.push(this.defaultSortOptions);\n\n      addSource({\n        type: 'custom',\n        key: `custom:${Craft.uuid()}`,\n        sortOptions: sortOptions,\n        defaultSort: [sortOptions[0].attr, sortOptions[1].defaultDir],\n        tableAttributes: [],\n        availableTableAttributes: [],\n      });\n      this.focusLabelInput();\n    });\n\n    const $ul = $('<ul/>')\n      .append($('<li/>').append($newHeadingBtn))\n      .appendTo(this.$addSourceMenu);\n\n    if (response.conditionBuilderHtml) {\n      $('<li/>').append($newCustomSourceBtn).appendTo($ul);\n    }\n\n    if (Craft.useMobileStyles()) {\n      this.buildSidebarToggleView();\n    }\n\n    // Add resize listener to enable/disable sidebar toggle view\n    this.addListener(Garnish.$win, 'resize', this.updateSidebarView);\n\n    this.addSourceMenu = new Garnish.DisclosureMenu($menuBtn);\n  },\n\n  focusLabelInput: function () {\n    this.selectedSource.$labelInput.trigger('focus');\n  },\n\n  getSourceName: function () {\n    return this.selectedSource\n      ? this.selectedSource.sourceData.label\n      : this.sources[0].sourceData.label;\n  },\n\n  updateSidebarView: function () {\n    if (Craft.useMobileStyles()) {\n      if (!this.$sidebarToggleBtn) this.buildSidebarToggleView();\n    } else {\n      if (this.$sidebarToggleBtn) this.resetView();\n    }\n  },\n\n  resetView: function () {\n    if (this.$sourceSettingsHeader) {\n      this.$sourceSettingsHeader.remove();\n    }\n\n    if (this.$sourcesHeader) {\n      this.$sourcesHeader.remove();\n    }\n\n    this.$sidebarToggleBtn = null;\n    this.$container.removeClass('sidebar-hidden');\n  },\n\n  updateHeading: function () {\n    if (!this.$sourcesHeading) return;\n\n    this.$sourcesHeading.text(this.getSourceName());\n  },\n\n  buildSidebarToggleView: function () {\n    this.$sourcesHeader = $('<div class=\"sources-header\"/>')\n      .addClass('sidebar-header')\n      .prependTo(this.$sourcesContainer);\n\n    this.$sidebarCloseBtn = Craft.ui\n      .createButton({\n        class: 'nav-close close-btn',\n      })\n      .attr('aria-label', Craft.t('app', 'Close'))\n      .removeClass('btn')\n      .appendTo(this.$sourcesHeader);\n\n    this.$sourcesHeading = $('<h1 class=\"main-heading\"/>').text(\n      this.getSourceName()\n    );\n\n    this.$sourceSettingsHeader = $('<div class=\"source-settings-header\"/>')\n      .addClass('main-header')\n      .append(this.$sourcesHeading)\n      .prependTo(this.$sourceSettingsContainer);\n\n    // Toggle sidebar button\n    const buttonConfig = {\n      toggle: true,\n      controls: 'modal-sidebar',\n      class: 'nav-toggle',\n    };\n\n    this.$sidebarToggleBtn = Craft.ui\n      .createButton(buttonConfig)\n      .removeClass('btn')\n      .attr('aria-label', Craft.t('app', 'Show sidebar'))\n      .appendTo(this.$sourceSettingsHeader);\n\n    this.closeSidebar();\n\n    // Add listeners\n    this.addListener(this.$sidebarToggleBtn, 'click', () => {\n      this.toggleSidebar();\n    });\n\n    this.addListener(this.$sidebarCloseBtn, 'click', () => {\n      this.toggleSidebar();\n      this.$sidebarToggleBtn.trigger('focus');\n    });\n  },\n\n  toggleSidebar: function () {\n    if (this.sidebarIsOpen()) {\n      this.closeSidebar();\n    } else {\n      this.openSidebar();\n    }\n  },\n\n  openSidebar: function () {\n    this.$container.removeClass('sidebar-hidden');\n    this.$sidebarToggleBtn.attr('aria-expanded', 'true');\n    this.$sidebar.find(':focusable').first().focus();\n\n    Garnish.uiLayerManager.addLayer(this.$sidebar);\n\n    Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n      this.closeSidebar();\n\n      if (Garnish.focusIsInside(this.$sidebar)) {\n        this.$sidebarToggleBtn.focus();\n      }\n    });\n  },\n\n  closeSidebar: function () {\n    this.$container.addClass('sidebar-hidden');\n\n    if (this.$sidebarToggleBtn) {\n      this.$sidebarToggleBtn.attr('aria-expanded', 'false');\n    }\n\n    // if sidebar is topmost layer, remove layer\n    if (Garnish.uiLayerManager.currentLayer.$container.hasClass('cs-sidebar')) {\n      Garnish.uiLayerManager.removeLayer();\n    }\n  },\n\n  sidebarIsOpen: function () {\n    return this.$sidebarToggleBtn.attr('aria-expanded') === 'true';\n  },\n\n  addSource: function (sourceData, isNew) {\n    const $item = $('<div class=\"customize-sources-item\"/>').appendTo(\n      this.$sourcesContainer\n    );\n    const $itemLabel = $('<div class=\"label customize-sources-item__btn\"/>')\n      .attr({\n        tabindex: '0',\n        role: 'button',\n      })\n      .appendTo($item);\n    const $itemInput = $('<input type=\"hidden\"/>').appendTo($item);\n    $(\n      `<a class=\"move icon customize-sources-item__move\" title=\"${Craft.t(\n        'app',\n        'Reorder'\n      )}\" role=\"button\"></a>`\n    ).appendTo($item);\n\n    let source;\n\n    if (sourceData.type === 'heading') {\n      $item.addClass('heading');\n      $itemInput.attr('name', 'sourceOrder[][heading]');\n      source = new Craft.CustomizeSourcesModal.Heading(\n        this,\n        $item,\n        $itemLabel,\n        $itemInput,\n        sourceData,\n        isNew\n      );\n      source.updateItemLabel(sourceData.heading);\n    } else {\n      $itemInput.attr('name', 'sourceOrder[][key]').val(sourceData.key);\n      if (sourceData.type === 'native') {\n        source = new Craft.CustomizeSourcesModal.Source(\n          this,\n          $item,\n          $itemLabel,\n          $itemInput,\n          sourceData,\n          isNew\n        );\n      } else {\n        source = new Craft.CustomizeSourcesModal.CustomSource(\n          this,\n          $item,\n          $itemLabel,\n          $itemInput,\n          sourceData,\n          isNew\n        );\n      }\n      source.updateItemLabel(sourceData.label);\n\n      // Select this by default?\n      if (sourceData.key === this.elementIndex.rootSourceKey) {\n        source.select();\n      }\n    }\n\n    this.sourceSort.addItems($item);\n    return source;\n  },\n\n  save: function (ev) {\n    if (ev) {\n      ev.preventDefault();\n    }\n\n    if (\n      this.$saveBtn.hasClass('disabled') ||\n      this.$saveBtn.hasClass('loading')\n    ) {\n      return;\n    }\n\n    this.$saveBtn.addClass('loading');\n\n    Craft.sendActionRequest(\n      'POST',\n      'element-index-settings/save-customize-sources-modal-settings',\n      {\n        data:\n          this.$container.serialize() +\n          `&elementType=${this.elementIndex.elementType}`,\n      }\n    )\n      .then(({data}) => {\n        // Figure out which source to select\n        let sourceKey = null;\n        if (\n          this.selectedSource &&\n          this.selectedSource.sourceData.key &&\n          !data.disabledSourceKeys.includes(this.selectedSource.sourceData.key)\n        ) {\n          sourceKey = this.selectedSource.sourceData.key;\n        } else if (!this.elementIndex.sourceKey) {\n          sourceKey = this.elementIndex.$visibleSources.first().data('key');\n        }\n\n        if (sourceKey) {\n          this.elementIndex.selectSourceByKey(sourceKey);\n        }\n\n        window.location.reload();\n      })\n      .catch(() => {\n        Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n      })\n      .finally(() => {\n        this.$saveBtn.removeClass('loading');\n      });\n  },\n\n  appendIndexSourceItem: function ($sourceItem, $lastSourceItem) {\n    if (!$lastSourceItem) {\n      $sourceItem.prependTo(this.$elementIndexSourcesContainer);\n    } else {\n      const isHeading = $sourceItem.hasClass('heading');\n      if ($lastSourceItem.hasClass('heading') && !isHeading) {\n        // First source to be placed below a new heading\n        $sourceItem.appendTo($lastSourceItem.children('ul'));\n      } else {\n        if (isHeading) {\n          // New heading. Swap $lastSourceItem with the top level <li> if it's nested\n          const $lastTopLevelSource = $lastSourceItem\n            .parentsUntil(this.$elementIndexSourcesContainer, 'li')\n            .last();\n          if ($lastTopLevelSource.length) {\n            $lastSourceItem = $lastTopLevelSource;\n          }\n        }\n        $sourceItem.insertAfter($lastSourceItem);\n      }\n    }\n  },\n\n  destroy: function () {\n    for (let i = 0; i < this.sources.length; i++) {\n      this.sources[i].destroy();\n    }\n\n    if (this.addSourceMenu) {\n      this.addSourceMenu.destroy();\n      this.$addSourceMenu.remove();\n    }\n\n    delete this.sources;\n    this.base();\n  },\n});\n\nCraft.CustomizeSourcesModal.BaseSource = Garnish.Base.extend({\n  modal: null,\n\n  $item: null,\n  $itemLabel: null,\n  $itemInput: null,\n  $settingsContainer: null,\n\n  sourceData: null,\n  isNew: null,\n\n  init: function (modal, $item, $itemLabel, $itemInput, sourceData, isNew) {\n    this.modal = modal;\n    this.$item = $item;\n    this.$itemLabel = $itemLabel;\n    this.$itemInput = $itemInput;\n    this.sourceData = sourceData;\n    this.isNew = isNew;\n\n    this.$item.data('source', this);\n\n    this.addListener(this.$itemLabel, 'click', 'select');\n    this.addListener(this.$itemLabel, 'keypress', (e) =>\n      Garnish.handleActivatingKeypress(e, this.select.bind(this))\n    );\n  },\n\n  isHeading: function () {\n    return false;\n  },\n\n  isNative: function () {\n    return false;\n  },\n\n  isSelected: function () {\n    return this.modal.selectedSource === this;\n  },\n\n  select: function () {\n    if (this.isSelected()) {\n      return;\n    }\n\n    if (this.modal.selectedSource) {\n      this.modal.selectedSource.deselect();\n    }\n\n    this.$item.addClass('sel');\n    this.$itemLabel.attr({\n      'aria-current': 'true',\n    });\n    this.modal.selectedSource = this;\n    this.modal.updateHeading();\n\n    if (!this.$settingsContainer) {\n      this.$settingsContainer = $('<div/>').appendTo(\n        this.modal.$sourceSettingsContainer\n      );\n      this.createSettings(this.$settingsContainer);\n    } else {\n      this.$settingsContainer.removeClass('hidden');\n    }\n\n    this.modal.$sourceSettingsContainer.scrollTop(0);\n  },\n\n  createSettings: function () {},\n\n  getIndexSourceItem: function () {},\n\n  deselect: function () {\n    this.$item.removeClass('sel');\n    this.$itemLabel.attr({\n      'aria-current': 'false',\n    });\n    this.modal.selectedSource = null;\n    this.$settingsContainer.addClass('hidden');\n  },\n\n  updateItemLabel: function (val) {\n    if (val) {\n      this.$itemLabel.text(val);\n    } else {\n      this.$itemLabel.html('&nbsp;');\n    }\n  },\n\n  destroy: function () {\n    this.modal.sourceSort.removeItems(this.$item);\n    this.modal.sources.splice($.inArray(this, this.modal.sources), 1);\n\n    if (this.isSelected()) {\n      this.deselect();\n\n      if (this.modal.sources.length) {\n        this.modal.sources[0].select();\n      }\n\n      Garnish.setFocusWithin(this.modal.$sourceSettingsContainer);\n    }\n\n    this.$item.data('source', null);\n    this.$item.remove();\n\n    if (this.$settingsContainer) {\n      this.$settingsContainer.remove();\n    }\n\n    this.base();\n  },\n});\n\nCraft.CustomizeSourcesModal.Source =\n  Craft.CustomizeSourcesModal.BaseSource.extend({\n    $sortAttributeSelect: null,\n    $sortDirectionPicker: null,\n    $sortDirectionInput: null,\n    sortDirectionListbox: null,\n\n    isNative: function () {\n      return true;\n    },\n\n    createSettings: function ($container) {\n      Craft.ui\n        .createLightswitchField({\n          label: Craft.t('app', 'Enabled'),\n          name: `sources[${this.sourceData.key}][enabled]`,\n          on: !this.sourceData.disabled,\n        })\n        .appendTo($container);\n      this.createSortField($container);\n      this.createTableAttributesField($container);\n    },\n\n    createSortField: function ($container) {\n      const $inputContainer = $('<div class=\"flex\"/>');\n\n      const $sortAttributeSelectContainer = Craft.ui\n        .createSelect({\n          name: `sources[${this.sourceData.key}][defaultSort][0]`,\n          options: this.sourceData.sortOptions.map((o) => {\n            return {\n              label: o.label,\n              value: o.attr,\n            };\n          }),\n          value: this.sourceData.defaultSort[0],\n        })\n        .addClass('fullwidth')\n        .appendTo($('<div/>').appendTo($inputContainer));\n\n      this.$sortAttributeSelect = $sortAttributeSelectContainer\n        .children('select')\n        .attr('aria-label', Craft.t('app', 'Sort attribute'));\n\n      this.$sortDirectionPicker = $('<section/>', {\n        class: 'btngroup btngroup--exclusive',\n        'aria-label': Craft.t('app', 'Sort direction'),\n      })\n        .append(\n          $('<button/>', {\n            type: 'button',\n            class: 'btn',\n            title: Craft.t('app', 'Sort ascending'),\n            'aria-label': Craft.t('app', 'Sort ascending'),\n            'aria-pressed': 'false',\n            'data-icon': 'asc',\n            'data-dir': 'asc',\n          })\n        )\n        .append(\n          $('<button/>', {\n            type: 'button',\n            class: 'btn',\n            title: Craft.t('app', 'Sort descending'),\n            'aria-label': Craft.t('app', 'Sort descending'),\n            'aria-pressed': 'false',\n            'data-icon': 'desc',\n            'data-dir': 'desc',\n          })\n        )\n        .appendTo($inputContainer);\n\n      this.$sortDirectionInput = $('<input/>', {\n        type: 'hidden',\n        name: `sources[${this.sourceData.key}][defaultSort][1]`,\n      }).appendTo($inputContainer);\n\n      this.sortDirectionListbox = new Craft.Listbox(this.$sortDirectionPicker, {\n        onChange: ($selectedOption) => {\n          this.$sortDirectionInput.val($selectedOption.data('dir'));\n        },\n      });\n\n      this.$sortAttributeSelect.on('change', () => {\n        this.handleSortAttributeChange();\n      });\n\n      this.handleSortAttributeChange(true);\n\n      Craft.ui\n        .createField($inputContainer, {\n          label: Craft.t('app', 'Default Sort'),\n          fieldset: true,\n        })\n        .appendTo($container)\n        .addClass('sort-field');\n    },\n\n    handleSortAttributeChange: function (useDefaultDir) {\n      const attr = this.$sortAttributeSelect.val();\n\n      if (attr === 'structure') {\n        this.sortDirectionListbox.select(0);\n        this.sortDirectionListbox.disable();\n        this.$sortDirectionPicker.addClass('disabled');\n      } else {\n        this.sortDirectionListbox.enable();\n        this.$sortDirectionPicker.removeClass('disabled');\n\n        const dir = useDefaultDir\n          ? this.sourceData.defaultSort[1]\n          : this.sourceData.sortOptions.find((o) => o.attr === attr).defaultDir;\n        this.sortDirectionListbox.select(dir === 'asc' ? 0 : 1);\n      }\n    },\n\n    createTableAttributesField: function ($container) {\n      const availableTableAttributes = this.availableTableAttributes();\n\n      if (\n        !this.sourceData.tableAttributes.length &&\n        !availableTableAttributes.length\n      ) {\n        return;\n      }\n\n      const $columnCheckboxes = $('<div/>');\n      const selectedAttributes = [];\n\n      $(\n        `<input type=\"hidden\" name=\"sources[${this.sourceData.key}][tableAttributes][]\" value=\"\"/>`\n      ).appendTo($columnCheckboxes);\n\n      // Add the selected columns, in the selected order\n      for (let i = 0; i < this.sourceData.tableAttributes.length; i++) {\n        let [key, label] = this.sourceData.tableAttributes[i];\n        $columnCheckboxes.append(\n          this.createTableColumnOption(key, label, true)\n        );\n        selectedAttributes.push(key);\n      }\n\n      // Add the rest\n      for (let i = 0; i < availableTableAttributes.length; i++) {\n        const [key, label] = availableTableAttributes[i];\n        if (!Craft.inArray(key, selectedAttributes)) {\n          $columnCheckboxes.append(\n            this.createTableColumnOption(key, label, false)\n          );\n        }\n      }\n\n      new Garnish.DragSort($columnCheckboxes.children(), {\n        handle: '.move',\n        axis: 'y',\n      });\n\n      Craft.ui\n        .createField($columnCheckboxes, {\n          label: Craft.t('app', 'Default Table Columns'),\n          instructions: Craft.t(\n            'app',\n            'Choose which table columns should be visible for this source by default.'\n          ),\n        })\n        .appendTo($container);\n    },\n\n    availableTableAttributes: function () {\n      const attributes = this.modal.availableTableAttributes.slice(0);\n      attributes.push(...this.sourceData.availableTableAttributes);\n      return attributes;\n    },\n\n    createTableColumnOption: function (key, label, checked) {\n      return $('<div class=\"customize-sources-table-column\"/>')\n        .append('<div class=\"icon move\"/>')\n        .append(\n          Craft.ui.createCheckbox({\n            label: Craft.escapeHtml(label),\n            name: `sources[${this.sourceData.key}][tableAttributes][]`,\n            value: key,\n            checked: checked,\n          })\n        );\n    },\n\n    getIndexSourceItem: function () {\n      const $source = this.modal.elementIndex.getSourceByKey(\n        this.sourceData.key\n      );\n\n      if ($source) {\n        return $source.closest('li');\n      }\n    },\n  });\n\nCraft.CustomizeSourcesModal.CustomSource =\n  Craft.CustomizeSourcesModal.Source.extend({\n    $labelInput: null,\n\n    createSettings: function ($container) {\n      const $labelField = Craft.ui\n        .createTextField({\n          label: Craft.t('app', 'Label'),\n          name: `sources[${this.sourceData.key}][label]`,\n          value: this.sourceData.label,\n        })\n        .appendTo($container);\n      this.$labelInput = $labelField.find('.text');\n      const defaultId = `condition${Math.floor(Math.random() * 1000000)}`;\n\n      const swapPlaceholders = (str) =>\n        str\n          .replace(/__ID__/g, defaultId)\n          .replace(\n            /__SOURCE_KEY__(?=-)/g,\n            Craft.formatInputId(this.sourceData.key)\n          )\n          .replace(/__SOURCE_KEY__/g, this.sourceData.key);\n\n      const conditionBuilderHtml =\n        this.sourceData.conditionBuilderHtml ||\n        swapPlaceholders(this.modal.conditionBuilderHtml);\n      const conditionBuilderJs =\n        this.sourceData.conditionBuilderJs ||\n        swapPlaceholders(this.modal.conditionBuilderJs);\n\n      Craft.ui\n        .createField($('<div/>').append(conditionBuilderHtml), {\n          id: 'criteria',\n          label: Craft.t('app', '{type} Criteria', {\n            type: this.modal.elementTypeName,\n          }),\n        })\n        .appendTo($container);\n      Craft.appendBodyHtml(conditionBuilderJs);\n\n      this.createSortField($container);\n      this.createTableAttributesField($container);\n\n      if (this.modal.userGroups.length) {\n        Craft.ui\n          .createCheckboxSelectField({\n            label: Craft.t('app', 'User Groups'),\n            instructions: Craft.t(\n              'app',\n              'Choose which user groups should have access to this source.'\n            ),\n            name: `sources[${this.sourceData.key}][userGroups]`,\n            options: this.modal.userGroups,\n            values: this.sourceData.userGroups || '*',\n            showAllOption: true,\n          })\n          .appendTo($container);\n      }\n\n      $container.append('<hr/>');\n\n      this.$deleteBtn = $('<a class=\"error delete\"/>')\n        .attr({\n          role: 'button',\n          tabindex: '0',\n        })\n        .text(Craft.t('app', 'Delete custom source'))\n        .appendTo($container);\n\n      this.addListener(this.$labelInput, 'input', 'handleLabelInputChange');\n      this.addListener(this.$deleteBtn, 'click', 'destroy');\n      this.addListener(this.$deleteBtn, 'keypress', (e) => {\n        Garnish.handleActivatingKeypress(e, this.destroy.bind(this));\n      });\n    },\n\n    availableTableAttributes: function () {\n      const attributes = this.base();\n      if (this.isNew) {\n        attributes.push(...this.modal.customFieldAttributes);\n      }\n      return attributes;\n    },\n\n    handleLabelInputChange: function () {\n      this.updateItemLabel(this.$labelInput.val());\n    },\n\n    getIndexSourceItem: function () {\n      let $source = this.base();\n      let $label;\n\n      if ($source) {\n        $label = $source.find('.label');\n      } else {\n        $label = $('<span/>', {class: 'label'});\n        $source = $('<li/>').append(\n          $('<a/>', {\n            'data-key': this.sourceData.key,\n          }).append($label)\n        );\n      }\n\n      if (this.$labelInput) {\n        let label = Craft.trim(this.$labelInput.val());\n        if (label === '') {\n          label = Craft.t('app', '(blank)');\n        }\n        $label.text(label);\n      }\n\n      return $source;\n    },\n  });\n\nCraft.CustomizeSourcesModal.Heading =\n  Craft.CustomizeSourcesModal.BaseSource.extend({\n    $labelInput: null,\n    $deleteBtn: null,\n\n    isHeading: function () {\n      return true;\n    },\n\n    createSettings: function ($container) {\n      const $labelField = Craft.ui\n        .createTextField({\n          label: Craft.t('app', 'Heading'),\n          instructions: Craft.t(\n            'app',\n            'This can be left blank if you just want an unlabeled separator.'\n          ),\n          value: this.sourceData.heading || '',\n        })\n        .appendTo($container);\n      this.$labelInput = $labelField.find('.text');\n\n      $container.append('<hr/>');\n\n      this.$deleteBtn = $('<a class=\"error delete\"/>')\n        .text(Craft.t('app', 'Delete heading'))\n        .attr({\n          role: 'button',\n          tabindex: '0',\n        })\n        .appendTo($container);\n\n      this.addListener(this.$labelInput, 'input', 'handleLabelInputChange');\n      this.addListener(this.$deleteBtn, 'click', 'destroy');\n      this.addListener(this.$deleteBtn, 'keypress', (e) => {\n        Garnish.handleActivatingKeypress(e, this.destroy.bind(this));\n      });\n    },\n\n    handleLabelInputChange: function () {\n      this.updateItemLabel(this.$labelInput.val());\n    },\n\n    updateItemLabel: function (val) {\n      this.$itemLabel.html(\n        (val\n          ? Craft.escapeHtml(val)\n          : `<em>${Craft.t('app', '(blank)')}</em>`) + '&nbsp;'\n      );\n      this.$itemInput.val(val);\n    },\n\n    getIndexSourceItem: function () {\n      const label =\n        (this.$labelInput ? this.$labelInput.val() : null) ||\n        this.sourceData.heading ||\n        '';\n      return $('<li class=\"heading\"/>')\n        .append($('<span/>').text(label))\n        .append('<ul/>');\n    },\n  });\n","/** global: Craft */\n/** global: Garnish */\n/**\n * DataTableSorter\n */\nCraft.DataTableSorter = Garnish.DragSort.extend(\n  {\n    $table: null,\n\n    init: function (table, settings) {\n      this.$table = $(table);\n      var $rows = this.$table.children('tbody').children(':not(.filler)');\n\n      settings = $.extend({}, Craft.DataTableSorter.defaults, settings);\n\n      settings.container = this.$table.children('tbody');\n      settings.helper = this.getHelper.bind(this);\n      settings.caboose = '<tr/>';\n      settings.axis = Garnish.Y_AXIS;\n      settings.magnetStrength = 4;\n      settings.helperLagBase = 1.5;\n\n      this.base($rows, settings);\n    },\n\n    getHelper: function ($helperRow) {\n      var $helper = $(\n          '<div class=\"' + this.settings.helperClass + '\"/>'\n        ).appendTo(Garnish.$bod),\n        $table = $('<table/>').appendTo($helper),\n        $tbody = $('<tbody/>').appendTo($table);\n\n      $helperRow.appendTo($tbody);\n\n      // Copy the table width and classes\n      $table.width(this.$table.width());\n      $table.prop('className', this.$table.prop('className'));\n\n      // Copy the column widths\n      var $firstRow = this.$table.find('tr:first'),\n        $cells = $firstRow.children(),\n        $helperCells = $helperRow.children();\n\n      for (var i = 0; i < $helperCells.length; i++) {\n        $($helperCells[i]).width($($cells[i]).width());\n      }\n\n      return $helper;\n    },\n  },\n  {\n    defaults: {\n      handle: '.move',\n      helperClass: 'datatablesorthelper',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Delete User Modal\n */\nCraft.DeleteUserModal = Garnish.Modal.extend(\n  {\n    id: null,\n    userId: null,\n\n    $deleteActionRadios: null,\n    $deleteSubmitBtn: null,\n\n    userSelect: null,\n    _deleting: false,\n\n    init: function (userId, settings) {\n      this.id = Math.floor(Math.random() * 1000000000);\n      this.userId = userId;\n      settings = $.extend(Craft.DeleteUserModal.defaults, settings);\n\n      let $form = $(\n        '<form class=\"modal fitted deleteusermodal\" method=\"post\" accept-charset=\"UTF-8\">' +\n          Craft.getCsrfInput() +\n          '<input type=\"hidden\" name=\"action\" value=\"users/delete-user\"/>' +\n          (!Garnish.isArray(this.userId)\n            ? '<input type=\"hidden\" name=\"userId\" value=\"' + this.userId + '\"/>'\n            : '') +\n          (settings.redirect\n            ? '<input type=\"hidden\" name=\"redirect\" value=\"' +\n              settings.redirect +\n              '\"/>'\n            : '') +\n          '</form>'\n      ).appendTo(Garnish.$bod);\n      let $body = $(\n        '<div class=\"body\">' +\n          '<div class=\"content-summary\">' +\n          '<p>' +\n          Craft.t('app', 'What do you want to do with their content?') +\n          '</p>' +\n          '<ul class=\"bullets\"></ul>' +\n          '</div>' +\n          '<div class=\"options\">' +\n          '<label><input type=\"radio\" name=\"contentAction\" value=\"transfer\"/> ' +\n          Craft.t('app', 'Transfer it to:') +\n          '</label>' +\n          '<div id=\"transferselect' +\n          this.id +\n          '\" class=\"elementselect\">' +\n          '<div class=\"elements\"></div>' +\n          '<button type=\"button\" class=\"btn add icon dashed\">' +\n          Craft.t('app', 'Choose a user') +\n          '</button>' +\n          '</div>' +\n          '</div>' +\n          '<div>' +\n          '<label class=\"error\"><input type=\"radio\" name=\"contentAction\" value=\"delete\"/> ' +\n          Craft.t('app', 'Delete their content') +\n          '</label>' +\n          '</div>' +\n          '</div>'\n      ).appendTo($form);\n      let $buttons = $('<div class=\"buttons right\"/>').appendTo($body);\n      let $cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo($buttons);\n\n      if (settings.contentSummary.length) {\n        for (let i = 0; i < settings.contentSummary.length; i++) {\n          $body\n            .find('ul')\n            .append($('<li/>', {text: settings.contentSummary[i]}));\n        }\n      } else {\n        $body.find('ul').remove();\n      }\n\n      this.$deleteActionRadios = $body.find('input[type=radio]');\n      this.$deleteSubmitBtn = Craft.ui\n        .createSubmitButton({\n          class: 'disabled',\n          label: this._submitBtnLabel(false),\n          spinner: true,\n        })\n        .appendTo($buttons);\n\n      var idParam;\n\n      if (Garnish.isArray(this.userId)) {\n        idParam = ['and'];\n\n        for (let i = 0; i < this.userId.length; i++) {\n          idParam.push('not ' + this.userId[i]);\n        }\n      } else {\n        idParam = 'not ' + this.userId;\n      }\n\n      this.userSelect = new Craft.BaseElementSelectInput({\n        id: 'transferselect' + this.id,\n        name: 'transferContentTo',\n        elementType: 'craft\\\\elements\\\\User',\n        criteria: {\n          id: idParam,\n        },\n        limit: 1,\n        modalSettings: {\n          closeOtherModals: false,\n        },\n        onSelectElements: () => {\n          this.updateSizeAndPosition();\n\n          if (!this.$deleteActionRadios.first().prop('checked')) {\n            this.$deleteActionRadios.first().trigger('click');\n          } else {\n            this.validateDeleteInputs();\n          }\n        },\n        onRemoveElements: this.validateDeleteInputs.bind(this),\n        selectable: false,\n        editable: false,\n      });\n\n      this.addListener($cancelBtn, 'click', 'hide');\n\n      this.addListener(\n        this.$deleteActionRadios,\n        'change',\n        'validateDeleteInputs'\n      );\n      this.addListener($form, 'submit', 'handleSubmit');\n\n      this.base($form, settings);\n    },\n\n    _submitBtnLabel: function (withContent) {\n      let message = withContent\n        ? 'Delete {num, plural, =1{user} other{users}} and content'\n        : 'Delete {num, plural, =1{user} other{users}}';\n\n      return Craft.t('app', message, {\n        num: Garnish.isArray(this.userId) ? this.userId.length : 1,\n      });\n    },\n\n    validateDeleteInputs: function () {\n      var validates = false;\n\n      if (this.$deleteActionRadios.eq(1).prop('checked')) {\n        validates = true;\n        this.$deleteSubmitBtn.find('.label').text(this._submitBtnLabel(true));\n      } else {\n        this.$deleteSubmitBtn.find('.label').text(this._submitBtnLabel(false));\n        if (this.$deleteActionRadios.eq(0).prop('checked')) {\n          validates = !!this.userSelect.totalSelected;\n        }\n      }\n\n      this.updateSizeAndPosition();\n\n      if (validates) {\n        this.$deleteSubmitBtn.removeClass('disabled');\n      } else {\n        this.$deleteSubmitBtn.addClass('disabled');\n      }\n\n      return validates;\n    },\n\n    handleSubmit: function (ev) {\n      if (this._deleting || !this.validateDeleteInputs()) {\n        ev.preventDefault();\n        return;\n      }\n\n      this.$deleteSubmitBtn.addClass('loading');\n      this.disable();\n      this.userSelect.disable();\n      this._deleting = true;\n\n      // Let the onSubmit callback prevent the form from getting submitted\n      try {\n        if (this.settings.onSubmit() === false) {\n          ev.preventDefault();\n        }\n      } catch (e) {\n        ev.preventDefault();\n        this.$deleteSubmitBtn.removeClass('loading');\n        throw e;\n      }\n    },\n\n    onFadeIn: function () {\n      // Auto-focus the first radio\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$deleteActionRadios.first().trigger('focus');\n      }\n\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      contentSummary: [],\n      onSubmit: $.noop,\n      redirect: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.DynamicGenerator = Craft.BaseInputGenerator.extend({\n  callback: $.noop,\n\n  init: function (source, target, callback) {\n    this.callback = callback;\n    this.base(source, target);\n  },\n\n  generateTargetValue: function (sourceVal) {\n    return this.callback(sourceVal);\n  },\n});\n","/* jshint -W083 */\n/**\n * Editable table class\n */\nCraft.EditableTable = Garnish.Base.extend(\n  {\n    initialized: false,\n\n    id: null,\n    baseName: null,\n    columns: null,\n    sorter: null,\n    biggestId: -1,\n\n    $table: null,\n    $tbody: null,\n    $addRowBtn: null,\n    $tableParent: null,\n    $statusMessage: null,\n\n    rowCount: 0,\n    hasMaxRows: false,\n    hasMinRows: false,\n\n    radioCheckboxes: null,\n\n    init: function (id, baseName, columns, settings) {\n      this.id = id;\n      this.baseName = baseName;\n      this.columns = columns;\n      this.setSettings(settings, Craft.EditableTable.defaults);\n      this.radioCheckboxes = {};\n\n      this.$table = $('#' + id);\n      this.$tbody = this.$table.children('tbody');\n      this.$tableParent = this.$table.parent();\n      this.$statusMessage = this.$tableParent.find('[data-status-message]');\n      this.rowCount = this.$tbody.find('tr').length;\n\n      // Is this already an editable table?\n      if (this.$table.data('editable-table')) {\n        console.warn('Double-instantiating an editable table on an element');\n        this.$table.data('editable-table').destroy();\n      }\n\n      this.$table.data('editable-table', this);\n\n      this.sorter = new Craft.DataTableSorter(this.$table, {\n        helperClass: 'editabletablesorthelper',\n        copyDraggeeInputValuesToHelper: true,\n        onSortChange: () => {\n          this.updateAllRows();\n        },\n      });\n\n      if (this.isVisible()) {\n        this.initialize();\n      } else {\n        // Give everything a chance to initialize\n        window.setTimeout(this.initializeIfVisible.bind(this), 500);\n      }\n\n      if (this.settings.minRows && this.rowCount < this.settings.minRows) {\n        for (var i = this.rowCount; i < this.settings.minRows; i++) {\n          this.addRow();\n        }\n      }\n    },\n\n    isVisible: function () {\n      return this.$table.parent().height() > 0;\n    },\n\n    initialize: function () {\n      if (this.initialized) {\n        return false;\n      }\n\n      this.initialized = true;\n      this.removeListener(Garnish.$win, 'resize');\n\n      var $rows = this.$tbody.children();\n\n      for (var i = 0; i < $rows.length; i++) {\n        this.createRowObj($rows[i]);\n      }\n\n      const $container = this.$table.parent('.input');\n      if ($container.length && this.$table.width() > $container.width()) {\n        $container.css('overflow-x', 'auto');\n      }\n\n      this.$addRowBtn = this.$table.next('.add');\n      this.updateAddRowButton();\n      this.addListener(this.$addRowBtn, 'activate', 'addRow');\n      return true;\n    },\n    initializeIfVisible: function () {\n      this.removeListener(Garnish.$win, 'resize');\n\n      if (this.isVisible()) {\n        this.initialize();\n      } else {\n        this.addListener(Garnish.$win, 'resize', 'initializeIfVisible');\n      }\n    },\n    updateAddRowButton: function () {\n      if (!this.canAddRow()) {\n        this.$addRowBtn.css('opacity', '0.2');\n        this.$addRowBtn.css('pointer-events', 'none');\n        this.$addRowBtn.attr('aria-disabled', 'true');\n      } else {\n        this.$addRowBtn.css('opacity', '1');\n        this.$addRowBtn.css('pointer-events', 'auto');\n        this.$addRowBtn.attr('aria-disabled', 'false');\n      }\n    },\n    updateAllRows: function () {\n      if (this.settings.staticRows) {\n        return;\n      }\n      const $rows = this.$table.find('> tbody > tr');\n      for (let i = 0; i < $rows.length; i++) {\n        this.updateRow($rows.eq(i));\n      }\n    },\n    updateRow: function ($row) {\n      if (this.settings.staticRows) {\n        return;\n      }\n\n      const $deleteBtn = $row.find('button.delete');\n\n      if ($deleteBtn.length) {\n        $deleteBtn.attr(\n          'aria-label',\n          Craft.t('app', 'Delete row {index}', {\n            index: $row.index() + 1,\n          })\n        );\n        if (this.canDeleteRow()) {\n          $deleteBtn.removeAttr('disabled').removeClass('disabled');\n        } else {\n          $deleteBtn.attr('disabled', 'disabled').addClass('disabled');\n        }\n      }\n    },\n    /**\n     * @deprecated\n     */\n    updateDeleteRowButton: function (rowId) {\n      this.updateRow(this.$table.find(`tr[data-id=\"${rowId}\"]`));\n    },\n    updateStatusMessage: function () {\n      this.$statusMessage.empty();\n      let message;\n\n      if (!this.canAddRow()) {\n        message = Craft.t(\n          'app',\n          'Row could not be added. Maximum number of rows reached.'\n        );\n      } else {\n        message = Craft.t(\n          'app',\n          'Row could not be deleted. Minimum number of rows reached.'\n        );\n      }\n\n      setTimeout(() => {\n        this.$statusMessage.text(message);\n      }, 250);\n    },\n    canDeleteRow: function () {\n      if (!this.settings.allowDelete) {\n        return false;\n      }\n\n      return this.rowCount > this.settings.minRows;\n    },\n    deleteRow: function (row) {\n      if (!this.canDeleteRow()) {\n        this.updateStatusMessage();\n        return;\n      }\n\n      this.sorter.removeItems(row.$tr);\n      row.$tr.remove();\n\n      this.rowCount--;\n\n      this.updateAllRows();\n      this.updateAddRowButton();\n\n      if (this.rowCount === 0) {\n        this.$table.addClass('hidden');\n        this.$addRowBtn.trigger('focus');\n      } else {\n        // Focus element in previous row\n        this.$tbody.find(':focusable').last().trigger('focus');\n      }\n\n      // onDeleteRow callback\n      this.settings.onDeleteRow(row.$tr);\n\n      row.destroy();\n    },\n    canAddRow: function () {\n      if (!this.settings.allowAdd) {\n        return false;\n      }\n\n      if (this.settings.maxRows) {\n        return this.rowCount < this.settings.maxRows;\n      }\n\n      return true;\n    },\n    addRow: function (focus, prepend) {\n      if (!this.canAddRow()) {\n        this.updateStatusMessage();\n        return;\n      }\n\n      var rowId = this.settings.rowIdPrefix + (this.biggestId + 1),\n        $tr = this.createRow(\n          rowId,\n          this.columns,\n          this.baseName,\n          $.extend({}, this.settings.defaultValues)\n        );\n\n      if (prepend) {\n        $tr.prependTo(this.$tbody);\n      } else {\n        $tr.appendTo(this.$tbody);\n      }\n\n      var row = this.createRowObj($tr);\n      this.sorter.addItems($tr);\n\n      // Focus the first input in the row\n      if (focus !== false) {\n        $tr\n          .find('input:visible,textarea:visible,select:visible')\n          .first()\n          .trigger('focus');\n      }\n\n      this.rowCount++;\n      this.updateAllRows();\n      this.updateAddRowButton();\n      this.$table.removeClass('hidden');\n\n      // onAddRow callback\n      this.settings.onAddRow($tr);\n\n      return row;\n    },\n\n    createRow: function (rowId, columns, baseName, values) {\n      return Craft.EditableTable.createRow(\n        rowId,\n        columns,\n        baseName,\n        values,\n        this.settings.allowReorder,\n        this.settings.allowDelete\n      );\n    },\n\n    createRowObj: function ($tr) {\n      return new Craft.EditableTable.Row(this, $tr);\n    },\n\n    focusOnPrevRow: function ($tr, tdIndex, blurTd) {\n      var $prevTr = $tr.prev('tr');\n      var prevRow;\n\n      if ($prevTr.length) {\n        prevRow = $prevTr.data('editable-table-row');\n      } else {\n        prevRow = this.addRow(false, true);\n      }\n\n      // Focus on the same cell in the previous row\n      if (!prevRow) {\n        return;\n      }\n\n      if (!prevRow.$tds[tdIndex]) {\n        return;\n      }\n\n      if ($(prevRow.$tds[tdIndex]).hasClass('disabled')) {\n        if ($prevTr) {\n          this.focusOnPrevRow($prevTr, tdIndex, blurTd);\n        }\n        return;\n      }\n\n      var $input = $('textarea,input.text', prevRow.$tds[tdIndex]);\n      if ($input.length) {\n        $(blurTd).trigger('blur');\n        $input.trigger('focus');\n      }\n    },\n\n    focusOnNextRow: function ($tr, tdIndex, blurTd) {\n      var $nextTr = $tr.next('tr');\n      var nextRow;\n\n      if ($nextTr.length) {\n        nextRow = $nextTr.data('editable-table-row');\n      } else {\n        nextRow = this.addRow(false);\n      }\n\n      // Focus on the same cell in the next row\n      if (!nextRow) {\n        return;\n      }\n\n      if (!nextRow.$tds[tdIndex]) {\n        return;\n      }\n\n      if ($(nextRow.$tds[tdIndex]).hasClass('disabled')) {\n        if ($nextTr) {\n          this.focusOnNextRow($nextTr, tdIndex, blurTd);\n        }\n        return;\n      }\n\n      var $input = $('textarea,input.text', nextRow.$tds[tdIndex]);\n      if ($input.length) {\n        $(blurTd).trigger('blur');\n        $input.trigger('focus');\n      }\n    },\n\n    importData: function (data, row, tdIndex) {\n      let lines = data.split(/\\r?\\n|\\r/);\n      for (let i = 0; i < lines.length; i++) {\n        let values = lines[i].split('\\t');\n        for (let j = 0; j < values.length; j++) {\n          let value = values[j];\n          row.$tds\n            .eq(tdIndex + j)\n            .find('textarea,input[type!=hidden]')\n            .val(value)\n            .trigger('input');\n        }\n\n        // move onto the next row\n        let $nextTr = row.$tr.next('tr');\n        if ($nextTr.length) {\n          row = $nextTr.data('editable-table-row');\n        } else {\n          row = this.addRow(false);\n        }\n      }\n    },\n\n    destroy: function () {\n      this.$table.removeData('editable-table');\n      this.base();\n    },\n  },\n  {\n    textualColTypes: [\n      'autosuggest',\n      'color',\n      'date',\n      'email',\n      'multiline',\n      'number',\n      'singleline',\n      'template',\n      'time',\n      'url',\n    ],\n    defaults: {\n      rowIdPrefix: '',\n      defaultValues: {},\n      allowAdd: false,\n      allowReorder: false,\n      allowDelete: false,\n      minRows: null,\n      maxRows: null,\n      onAddRow: $.noop,\n      onDeleteRow: $.noop,\n    },\n\n    createRow: function (\n      rowId,\n      columns,\n      baseName,\n      values,\n      allowReorder,\n      allowDelete\n    ) {\n      var $tr = $('<tr/>', {\n        'data-id': rowId,\n      });\n\n      for (var colId in columns) {\n        if (!columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        var col = columns[colId],\n          value = typeof values[colId] !== 'undefined' ? values[colId] : '',\n          $cell;\n\n        if (col.type === 'heading') {\n          $cell = $('<th/>', {\n            scope: 'row',\n            class: col['class'],\n            html: value,\n          });\n        } else {\n          var name = baseName + '[' + rowId + '][' + colId + ']';\n\n          $cell = $('<td/>', {\n            class: `${col.class} ${col.type}-cell`,\n            width: col.width,\n          });\n\n          if (Craft.inArray(col.type, Craft.EditableTable.textualColTypes)) {\n            $cell.addClass('textual');\n          }\n\n          if (col.code) {\n            $cell.addClass('code');\n          }\n\n          switch (col.type) {\n            case 'checkbox':\n              $('<div class=\"checkbox-wrapper\"/>')\n                .append(\n                  Craft.ui.createCheckbox({\n                    name: name,\n                    value: col.value || '1',\n                    checked: !!value,\n                  })\n                )\n                .appendTo($cell);\n              break;\n\n            case 'color':\n              Craft.ui\n                .createColorInput({\n                  name: name,\n                  value: value,\n                  small: true,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'date':\n              Craft.ui\n                .createDateInput({\n                  name: name,\n                  value: value,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'lightswitch':\n              Craft.ui\n                .createLightswitch({\n                  name: name,\n                  value: col.value || '1',\n                  on: !!value,\n                  small: true,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'select':\n              Craft.ui\n                .createSelect({\n                  name: name,\n                  options: col.options,\n                  value:\n                    value ||\n                    (function () {\n                      for (var key in col.options) {\n                        if (\n                          col.options.hasOwnProperty(key) &&\n                          col.options[key].default\n                        ) {\n                          return typeof col.options[key].value !== 'undefined'\n                            ? col.options[key].value\n                            : key;\n                        }\n                      }\n                      return null;\n                    })(),\n                  class: 'small',\n                })\n                .appendTo($cell);\n              break;\n\n            case 'time':\n              Craft.ui\n                .createTimeInput({\n                  name: name,\n                  value: value,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'email':\n            case 'url':\n              Craft.ui\n                .createTextInput({\n                  name: name,\n                  value: value,\n                  type: col.type,\n                  placeholder: col.placeholder || null,\n                })\n                .appendTo($cell);\n              break;\n\n            default:\n              $('<textarea/>', {\n                name: name,\n                rows: col.rows || 1,\n                val: value,\n                placeholder: col.placeholder,\n              }).appendTo($cell);\n          }\n        }\n\n        $cell.appendTo($tr);\n      }\n\n      if (allowReorder) {\n        $('<td/>', {\n          class: 'thin action',\n        })\n          .append(\n            $('<a/>', {\n              class: 'move icon',\n              title: Craft.t('app', 'Reorder'),\n              role: 'button',\n              type: 'button',\n            })\n          )\n          .appendTo($tr);\n      }\n\n      if (allowDelete) {\n        $('<td/>', {\n          class: 'thin action',\n        })\n          .append(\n            $('<button/>', {\n              class: 'delete icon',\n              title: Craft.t('app', 'Delete'),\n              type: 'button',\n            })\n          )\n          .appendTo($tr);\n      }\n\n      return $tr;\n    },\n  }\n);\n\n/**\n * Editable table row class\n */\nCraft.EditableTable.Row = Garnish.Base.extend(\n  {\n    table: null,\n    id: null,\n    niceTexts: null,\n\n    $tr: null,\n    $tds: null,\n    tds: null,\n    $textareas: null,\n    $deleteBtn: null,\n\n    init: function (table, tr) {\n      this.table = table;\n      this.$tr = $(tr);\n      this.$tds = this.$tr.children();\n      this.tds = [];\n      this.id = this.$tr.attr('data-id');\n\n      this.$tr.data('editable-table-row', this);\n\n      // Get the row ID, sans prefix\n      var id = parseInt(\n        this.id.substring(this.table.settings.rowIdPrefix.length)\n      );\n\n      if (id > this.table.biggestId) {\n        this.table.biggestId = id;\n      }\n\n      this.$textareas = $();\n      this.niceTexts = [];\n      var textareasByColId = {};\n\n      var i = 0;\n      var colId, col, td, $textarea, $checkbox;\n\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        col = this.table.columns[colId];\n        td = this.tds[colId] = this.$tds[i];\n\n        if (Craft.inArray(col.type, Craft.EditableTable.textualColTypes)) {\n          $textarea = $('textarea', td);\n          this.$textareas = this.$textareas.add($textarea);\n\n          this.addListener($textarea, 'focus', 'onTextareaFocus');\n          this.addListener($textarea, 'mousedown', 'ignoreNextTextareaFocus');\n\n          this.niceTexts.push(\n            new Garnish.NiceText($textarea, {\n              onHeightChange: this.onTextareaHeightChange.bind(this),\n            })\n          );\n\n          this.addListener(\n            $textarea,\n            'keypress',\n            {tdIndex: i, type: col.type},\n            'handleKeypress'\n          );\n          this.addListener(\n            $textarea,\n            'input',\n            {type: col.type},\n            'validateValue'\n          );\n          $textarea.trigger('input');\n\n          if (col.type !== 'multiline') {\n            this.addListener(\n              $textarea,\n              'paste',\n              {tdIndex: i, type: col.type},\n              'handlePaste'\n            );\n          }\n\n          textareasByColId[colId] = $textarea;\n        } else if (col.type === 'checkbox') {\n          $checkbox = $('input[type=\"checkbox\"]', td);\n\n          if (col.radioMode) {\n            if (typeof this.table.radioCheckboxes[colId] === 'undefined') {\n              this.table.radioCheckboxes[colId] = [];\n            }\n            this.table.radioCheckboxes[colId].push($checkbox[0]);\n            this.addListener(\n              $checkbox,\n              'change',\n              {colId},\n              'onRadioCheckboxChange'\n            );\n          }\n\n          if (col.toggle) {\n            this.addListener($checkbox, 'change', {colId}, function (ev) {\n              this.applyToggleCheckbox(ev.data.colId);\n            });\n          }\n        }\n\n        if (!$(td).hasClass('disabled')) {\n          this.addListener(td, 'click', {td}, function (ev) {\n            if (ev.target === ev.data.td) {\n              $(ev.data.td).find('textarea,input,select,.lightswitch').focus();\n            }\n          });\n        }\n\n        i++;\n      }\n\n      // Now that all of the text cells have been nice-ified, let's normalize the heights\n      this.onTextareaHeightChange();\n\n      // See if we need to apply any checkbox toggles now that we've indexed all the TDs\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n        col = this.table.columns[colId];\n        if (col.type === 'checkbox' && col.toggle) {\n          this.applyToggleCheckbox(colId);\n        }\n      }\n\n      // Now look for any autopopulate columns\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        col = this.table.columns[colId];\n\n        if (\n          col.autopopulate &&\n          typeof textareasByColId[col.autopopulate] !== 'undefined' &&\n          !textareasByColId[colId].val()\n        ) {\n          new Craft.HandleGenerator(\n            textareasByColId[colId],\n            textareasByColId[col.autopopulate],\n            {\n              allowNonAlphaStart: true,\n            }\n          );\n        }\n      }\n\n      var $deleteBtn = this.$tr.children().last().find('.delete');\n      this.addListener($deleteBtn, 'click', 'deleteRow');\n\n      var $inputs = this.$tr.find('input,textarea,select,.lightswitch');\n      this.addListener($inputs, 'focus', function (ev) {\n        $(ev.currentTarget).closest('td:not(.disabled)').addClass('focus');\n      });\n      this.addListener($inputs, 'blur', function (ev) {\n        $(ev.currentTarget).closest('td').removeClass('focus');\n      });\n    },\n\n    onTextareaFocus: function (ev) {\n      this.onTextareaHeightChange();\n\n      var $textarea = $(ev.currentTarget);\n\n      if ($textarea.data('ignoreNextFocus')) {\n        $textarea.data('ignoreNextFocus', false);\n        return;\n      }\n\n      window.setTimeout(function () {\n        Craft.selectFullValue($textarea);\n      }, 0);\n    },\n\n    onRadioCheckboxChange: function (ev) {\n      if (ev.currentTarget.checked) {\n        for (\n          var i = 0;\n          i < this.table.radioCheckboxes[ev.data.colId].length;\n          i++\n        ) {\n          var checkbox = this.table.radioCheckboxes[ev.data.colId][i];\n          checkbox.checked = checkbox === ev.currentTarget;\n        }\n      }\n    },\n\n    applyToggleCheckbox: function (checkboxColId) {\n      var checkboxCol = this.table.columns[checkboxColId];\n      var checked = $('input[type=\"checkbox\"]', this.tds[checkboxColId]).prop(\n        'checked'\n      );\n      var colId, colIndex, neg;\n      for (var i = 0; i < checkboxCol.toggle.length; i++) {\n        colId = checkboxCol.toggle[i];\n        colIndex = this.table.colum;\n        neg = colId[0] === '!';\n        if (neg) {\n          colId = colId.substring(1);\n        }\n        if ((checked && !neg) || (!checked && neg)) {\n          $(this.tds[colId])\n            .removeClass('disabled')\n            .find('textarea, input')\n            .prop('disabled', false);\n        } else {\n          $(this.tds[colId])\n            .addClass('disabled')\n            .find('textarea, input')\n            .prop('disabled', true);\n        }\n      }\n    },\n\n    ignoreNextTextareaFocus: function (ev) {\n      $.data(ev.currentTarget, 'ignoreNextFocus', true);\n    },\n\n    handleKeypress: function (ev) {\n      var keyCode = ev.keyCode ? ev.keyCode : ev.charCode;\n      var ctrl = Garnish.isCtrlKeyPressed(ev);\n\n      // Going to the next/previous row?\n      if (\n        keyCode === Garnish.RETURN_KEY &&\n        (ev.data.type !== 'multiline' || ctrl)\n      ) {\n        ev.preventDefault();\n        if (ev.shiftKey) {\n          this.table.focusOnPrevRow(\n            this.$tr,\n            ev.data.tdIndex,\n            ev.currentTarget\n          );\n        } else {\n          this.table.focusOnNextRow(\n            this.$tr,\n            ev.data.tdIndex,\n            ev.currentTarget\n          );\n        }\n        return;\n      }\n    },\n\n    handlePaste: function (ev) {\n      let data = Craft.trim(\n        ev.originalEvent.clipboardData.getData('Text'),\n        ' \\n\\r'\n      );\n      if (!data.match(/[\\t\\r\\n]/)) {\n        return;\n      }\n      ev.preventDefault();\n      this.table.importData(data, this, ev.data.tdIndex);\n    },\n\n    validateValue: function (ev) {\n      if (ev.data.type === 'multiline') {\n        return;\n      }\n\n      if (ev.data.type === 'number') {\n        Craft.filterNumberInputVal(ev.currentTarget);\n        return;\n      }\n\n      // Strip any newlines\n      const safeValue = ev.currentTarget.value.replace(/[\\r\\n]/g, '');\n      if (safeValue !== ev.currentTarget.value) {\n        ev.currentTarget.value = safeValue;\n      }\n    },\n\n    onTextareaHeightChange: function () {\n      // Keep all the textareas' heights in sync\n      var tallestTextareaHeight = -1;\n\n      for (var i = 0; i < this.niceTexts.length; i++) {\n        if (this.niceTexts[i].height > tallestTextareaHeight) {\n          tallestTextareaHeight = this.niceTexts[i].height;\n        }\n      }\n\n      this.$textareas.css('min-height', tallestTextareaHeight);\n\n      // If the <td> is still taller, go with that instead\n      var tdHeight = this.$textareas\n        .filter(':visible')\n        .first()\n        .parent()\n        .height();\n\n      if (tdHeight > tallestTextareaHeight) {\n        this.$textareas.css('min-height', tdHeight);\n      }\n    },\n\n    deleteRow: function () {\n      this.table.deleteRow(this);\n    },\n  },\n  {\n    /** @deprecated */\n    numericKeyCodes: [\n      9 /* (tab) */, 8 /* (delete) */, 37, 38, 39, 40 /* (arrows) */, 45,\n      91 /* (minus) */, 46, 190 /* period */, 48, 49, 50, 51, 52, 53, 54, 55,\n      56, 57 /* (0-9) */,\n    ],\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Action Trigger\n */\nCraft.ElementActionTrigger = Garnish.Base.extend(\n  {\n    maxLevels: null,\n    newChildUrl: null,\n    $trigger: null,\n    $selectedItems: null,\n    triggerEnabled: true,\n\n    init: function (settings) {\n      if (!$.isPlainObject(settings)) {\n        settings = {};\n      }\n\n      // batch => bulk\n      if (typeof settings.batch !== 'undefined') {\n        settings.bulk = settings.batch;\n        delete settings.batch;\n      }\n      Object.defineProperty(settings, 'batch', {\n        get() {\n          return this.bulk;\n        },\n        set(v) {\n          this.bulk = v;\n        },\n      });\n\n      this.setSettings(settings, Craft.ElementActionTrigger.defaults);\n\n      this.$trigger = $(\n        '#' + settings.type.replace(/[\\[\\]\\\\]+/g, '-') + '-actiontrigger'\n      );\n\n      // Do we have a custom handler?\n      if (this.settings.activate) {\n        // Prevent the element index's click handler\n        this.$trigger.data('custom-handler', true);\n\n        // Is this a custom trigger?\n        if (this.$trigger.prop('nodeName') === 'FORM') {\n          this.addListener(this.$trigger, 'submit', 'handleTriggerActivation');\n        } else {\n          this.addListener(\n            this.$trigger,\n            'activate',\n            'handleTriggerActivation'\n          );\n        }\n      }\n\n      this.updateTrigger();\n      Craft.elementIndex.on('selectionChange', this.updateTrigger.bind(this));\n    },\n\n    updateTrigger: function () {\n      // Ignore if the last element was just unselected\n      if (Craft.elementIndex.getSelectedElements().length === 0) {\n        return;\n      }\n\n      if (this.validateSelection()) {\n        this.enableTrigger();\n      } else {\n        this.disableTrigger();\n      }\n    },\n\n    /**\n     * Determines if this action can be performed on the currently selected elements.\n     *\n     * @returns {boolean}\n     */\n    validateSelection: function () {\n      this.$selectedItems = Craft.elementIndex.getSelectedElements();\n\n      if (!this.settings.bulk && this.$selectedItems.length > 1) {\n        return false;\n      }\n\n      if (this.settings.requireId && this.$selectedItems.is('[data-id=\"\"]')) {\n        return false;\n      }\n\n      if (typeof this.settings.validateSelection === 'function') {\n        return this.settings.validateSelection(this.$selectedItems);\n      }\n\n      return true;\n    },\n\n    enableTrigger: function () {\n      if (this.triggerEnabled) {\n        return;\n      }\n\n      this.$trigger.removeClass('disabled').removeAttr('aria-disabled');\n      this.triggerEnabled = true;\n    },\n\n    disableTrigger: function () {\n      if (!this.triggerEnabled) {\n        return;\n      }\n\n      this.$trigger.addClass('disabled').attr('aria-disabled', 'true');\n      this.triggerEnabled = false;\n    },\n\n    handleTriggerActivation: function () {\n      if (this.triggerEnabled) {\n        this.settings.activate(this.$selectedItems);\n      }\n    },\n  },\n  {\n    defaults: {\n      type: null,\n      bulk: true,\n      requireId: true,\n      validateSelection: null,\n      activate: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Element Editor\n */\nCraft.ElementEditor = Garnish.Base.extend(\n  {\n    isFullPage: null,\n    $container: null,\n    $tabContainer: null,\n    $contentContainer: null,\n    $revisionBtn: null,\n    $revisionLabel: null,\n    $spinner: null,\n    $expandSiteStatusesBtn: null,\n    $statusIcon: null,\n    $previewBtn: null,\n\n    $editMetaBtn: null,\n    metaHud: null,\n    $nameTextInput: null,\n    $saveMetaBtn: null,\n\n    $siteStatusPane: null,\n    $globalLightswitch: null,\n    $siteLightswitches: null,\n    $additionalSiteField: null,\n\n    siteIds: null,\n    newSiteIds: null,\n\n    enableAutosave: null,\n    lastSerializedValue: null,\n    listeningForChanges: false,\n    pauseLevel: 0,\n    timeout: null,\n    cancelToken: null,\n    ignoreFailedRequest: false,\n    queue: null,\n    submittingForm: false,\n\n    duplicatedElements: null,\n    failed: false,\n    httpStatus: null,\n    httpError: null,\n\n    openingPreview: false,\n    preview: null,\n    activatedPreviewToken: false,\n    previewTokenQueue: null,\n    previewLinks: null,\n    scrollY: null,\n\n    hiddenTipsStorageKey: 'Craft-' + Craft.systemUid + '.TipField.hiddenTips',\n\n    get tipDismissBtn() {\n      return this.$container.find('.tip-dismiss-btn');\n    },\n\n    get slideout() {\n      return this.$container.data('slideout');\n    },\n\n    init: function (container, settings) {\n      this.$container = $(container);\n\n      if (this.$container.prop('tagName') !== 'FORM') {\n        throw 'Element editors may only be used with forms.';\n      }\n\n      if (this.$container.data('elementEditor')) {\n        console.warn('Double-instantiating an element editor on an element.');\n        this.$container.data('elementEditor').destroy();\n      }\n\n      this.$container.data('elementEditor', this);\n      this.$container.attr('data-element-editor', '');\n\n      this.setSettings(settings, Craft.ElementEditor.defaults);\n\n      this.isFullPage = this.$container[0] === Craft.cp.$primaryForm[0];\n\n      if (this.isFullPage) {\n        this.$tabContainer = $('#tabs');\n        this.$contentContainer = $('#content');\n      } else {\n        this.$tabContainer = this.slideout.$tabContainer;\n        this.$contentContainer = this.slideout.$content;\n      }\n\n      this.queue = this._createQueue();\n      this.previewTokenQueue = this._createQueue();\n\n      this.duplicatedElements = {};\n      this.enableAutosave = Craft.autosaveDrafts;\n      this.previewLinks = [];\n\n      this.siteIds = Object.keys(this.settings.siteStatuses).map((siteId) => {\n        return parseInt(siteId);\n      });\n\n      this.$revisionBtn = this.$container.find('.context-btn');\n      this.$revisionLabel = this.$container.find('.revision-label');\n      this.$previewBtn = this.$container.find('.preview-btn');\n\n      const $spinnerContainer = this.isFullPage\n        ? $('#page-title')\n        : this.slideout.$toolbar;\n      this.$spinner = $('<div/>', {\n        class: 'revision-spinner spinner hidden',\n        title: Craft.t('app', 'Saving'),\n      }).appendTo($spinnerContainer);\n      this.$statusIcon = $('<div/>', {\n        class: `revision-status ${this.isFullPage ? 'invisible' : 'hidden'}`,\n      }).appendTo($spinnerContainer);\n      this.$statusMessage = $('<div/>', {\n        class: 'revision-status-message visually-hidden',\n        'aria-live': 'polite',\n      }).appendTo($spinnerContainer);\n\n      this.$expandSiteStatusesBtn = $('.expand-status-btn');\n\n      if (this.settings.canEditMultipleSites) {\n        this.addListener(\n          this.$expandSiteStatusesBtn,\n          'click',\n          'expandSiteStatuses'\n        );\n      }\n\n      if (this.settings.previewTargets.length && this.isFullPage) {\n        if (this.settings.enablePreview) {\n          this.addListener(this.$previewBtn, 'click', 'openPreview');\n        }\n\n        const $previewBtnContainer = this.$container.find(\n          '.preview-btn-container'\n        );\n\n        if (this.settings.previewTargets.length === 1) {\n          const [target] = this.settings.previewTargets;\n          this.createPreviewLink(target)\n            .addClass('view-btn btn')\n            .attr('aria-label', Craft.t('app', 'View'))\n            .appendTo($previewBtnContainer);\n        } else {\n          this.createShareMenu($previewBtnContainer);\n        }\n      }\n\n      // If this is a revision, we're done here\n      if (this.settings.revisionId) {\n        return;\n      }\n\n      // Override the serializer to use our own\n      this.$container.data('serializer', () => this.serializeForm(true));\n      this.$container.data('initialSerializedValue', this.serializeForm(true));\n\n      if (this.isFullPage) {\n        this.addListener(this.$container, 'submit', 'handleSubmit');\n      }\n\n      if (this.settings.isProvisionalDraft) {\n        this.initForProvisionalDraft();\n      } else if (this.settings.draftId && !this.settings.isUnpublishedDraft) {\n        this.initForDraft();\n      } else if (!this.settings.canSaveCanonical) {\n        // Override the save shortcut to create a draft too\n        this.addListener(this.$container, 'submit.saveShortcut', (ev) => {\n          if (ev.saveShortcut) {\n            ev.preventDefault();\n            this.createDraft();\n            this.removeListener(this.$container, 'submit.saveShortcut');\n          }\n        });\n      }\n\n      this.listenForChanges();\n\n      this.addListener(this.$statusIcon, 'click', () => {\n        this.showStatusHud(this.$statusIcon);\n      });\n\n      // handle closing tips\n      this.handleDismissibleTips();\n\n      if (this.isFullPage && Craft.messageReceiver) {\n        // Listen on Craft.broadcaster to ignore any messages sent by this very page\n        Craft.broadcaster.addEventListener('message', (ev) => {\n          if (\n            (ev.data.event === 'saveDraft' &&\n              ev.data.canonicalId === this.settings.canonicalId &&\n              (ev.data.draftId === this.settings.draftId ||\n                (ev.data.isProvisionalDraft && !this.settings.draftId))) ||\n            (ev.data.event === 'saveElement' &&\n              ev.data.id === this.settings.canonicalId &&\n              !this.settings.draftId)\n          ) {\n            Craft.setLocalStorage('scrollY', window.scrollY);\n            window.location.reload();\n          } else if (\n            ev.data.event === 'deleteDraft' &&\n            ev.data.canonicalId === this.settings.canonicalId &&\n            ev.data.draftId === this.settings.draftId\n          ) {\n            const url = new URL(window.location.href);\n            url.searchParams.delete('draftId');\n            if (url.href !== document.location.href) {\n              window.location.href = url;\n            } else {\n              Craft.setLocalStorage('scrollY', window.scrollY);\n              window.location.reload();\n            }\n          }\n        });\n      }\n    },\n\n    _createQueue: function () {\n      const queue = new Craft.Queue();\n      queue.on('beforeRun', () => {\n        this.showSpinner();\n      });\n      queue.on('afterRun', () => {\n        this.hideSpinner();\n      });\n      return queue;\n    },\n\n    get namespace() {\n      if (this.isFullPage) {\n        return null;\n      }\n\n      return this.slideout.namespace;\n    },\n\n    namespaceInputName(name) {\n      return Craft.namespaceInputName(name, this.namespace);\n    },\n\n    namespaceId(id) {\n      return Craft.namespaceId(id, this.namespace);\n    },\n\n    listenForChanges: function () {\n      if (\n        this.listeningForChanges ||\n        this.pauseLevel > 0 ||\n        !this.enableAutosave ||\n        !this.settings.canCreateDrafts\n      ) {\n        return;\n      }\n\n      this.listeningForChanges = true;\n\n      // Listen for events on the body when editing a full page form, so we don’t miss events from Live Preview\n      const $target = this.isFullPage ? Garnish.$bod : this.$container;\n\n      this.addListener(\n        $target,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup',\n        (ev) => {\n          if ($(ev.target).is(this.statusIcons())) {\n            return;\n          }\n          clearTimeout(this.timeout);\n          // If they are typing, wait half a second before checking the form\n          if (['keypress', 'keyup', 'change'].includes(ev.type)) {\n            this.timeout = setTimeout(this.checkForm.bind(this), 500);\n          } else {\n            this.checkForm();\n          }\n        }\n      );\n    },\n\n    stopListeningForChanges: function () {\n      if (!this.listeningForChanges) {\n        return;\n      }\n\n      this.removeListener(\n        Garnish.$bod,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup'\n      );\n      clearTimeout(this.timeout);\n      this.listeningForChanges = false;\n    },\n\n    pause: function () {\n      this.pauseLevel++;\n      this.stopListeningForChanges();\n    },\n\n    resume: function () {\n      if (this.pauseLevel === 0) {\n        throw 'Craft.ElementEditor::resume() should only be called after pause().';\n      }\n\n      // Only actually resume operation if this has been called the same\n      // number of times that pause() was called\n      this.pauseLevel--;\n      if (this.pauseLevel === 0) {\n        if (this.enableAutosave) {\n          this.checkForm();\n          this.listenForChanges();\n        }\n      }\n    },\n\n    initForProvisionalDraft: function () {\n      let $discardButton = this.$container.find('.discard-changes-btn');\n\n      if (!$discardButton.length) {\n        let initialHeight, scrollTop;\n\n        let $noticeContainer;\n        if (this.isFullPage) {\n          initialHeight = $('#content').height();\n          scrollTop = Garnish.$win.scrollTop();\n          $noticeContainer = Craft.cp.$noticeContainer;\n        } else {\n          $noticeContainer = this.$container.find('.so-notice');\n        }\n\n        const $notice = $('<div/>', {\n          class: 'draft-notice',\n        })\n          .append(\n            $('<div/>', {\n              class: 'draft-icon',\n              'aria-hidden': 'true',\n              'data-icon': 'edit',\n            })\n          )\n          .append(\n            $('<p/>', {\n              text: Craft.t('app', 'Showing your unsaved changes.'),\n            })\n          )\n          .appendTo($noticeContainer);\n\n        $discardButton = $('<button/>', {\n          type: 'button',\n          class: 'discard-changes-btn btn',\n          text: Craft.t('app', 'Discard'),\n        }).appendTo($notice);\n\n        if (this.isFullPage) {\n          const heightDiff = $('#content').height() - initialHeight;\n          Garnish.$win.scrollTop(scrollTop + heightDiff);\n\n          // If there isn’t enough content to simulate the same scroll position, slide it down instead\n          if (Garnish.$win.scrollTop() === scrollTop) {\n            // Disable pointer events until half a second after the animation is complete\n            Craft.cp.$contentContainer.css('pointer-events', 'none');\n\n            $('#content-header').css('min-height', 'auto');\n            const height = $noticeContainer.height();\n            $noticeContainer\n              .css({height: height - heightDiff, overflow: 'hidden'})\n              .velocity({height: height}, 'fast', () => {\n                $('#content-header').css('min-height', '');\n                $noticeContainer.css({height: '', overflow: ''});\n\n                setTimeout(() => {\n                  Craft.cp.$contentContainer.css('pointer-events', '');\n                }, 300);\n              });\n          }\n        }\n      }\n\n      this.addListener(\n        $discardButton,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup',\n        (ev) => {\n          ev.stopPropagation();\n        }\n      );\n\n      this.addListener($discardButton, 'click', () => {\n        if (\n          confirm(\n            Craft.t('app', 'Are you sure you want to discard your changes?')\n          )\n        ) {\n          this.queue.unshift(\n            () =>\n              new Promise((resolve, reject) => {\n                if (this.isFullPage) {\n                  Craft.submitForm(this.$container, {\n                    action: 'elements/delete-draft',\n                    redirect: this.settings.hashedCpEditUrl,\n                    params: {\n                      draftId: this.settings.draftId,\n                      provisional: 1,\n                    },\n                  });\n                } else {\n                  Craft.sendActionRequest('POST', 'elements/delete-draft', {\n                    data: {\n                      elementId: this.settings.canonicalId,\n                      draftId: this.settings.draftId,\n                      provisional: 1,\n                    },\n                  })\n                    .then((response) => {\n                      Craft.cp.displaySuccess(response.data.message);\n                      this.slideout.close();\n                    })\n                    .catch(reject);\n                }\n              })\n          );\n        }\n      });\n    },\n\n    initForDraft: function () {\n      // Create the edit draft button\n      this.createEditMetaBtn();\n\n      if (this.settings.canSaveCanonical) {\n        Garnish.uiLayerManager.registerShortcut(\n          {\n            keyCode: Garnish.S_KEY,\n            ctrl: true,\n            alt: true,\n          },\n          () => {\n            Craft.submitForm(this.$container, {\n              action: 'elements/apply-draft',\n              redirect: this.settings.hashedCpEditUrl,\n            });\n          },\n          0\n        );\n      }\n    },\n\n    expandSiteStatuses: function () {\n      this.removeListener(this.$expandSiteStatusesBtn, 'click');\n      this.$expandSiteStatusesBtn.velocity({opacity: 0}, 'fast', () => {\n        this.$expandSiteStatusesBtn.remove();\n      });\n\n      const $enabledForSiteField = this.$container.find(\n        `.enabled-for-site-${this.settings.siteId}-field`\n      );\n      this.$siteStatusPane = $enabledForSiteField.parent();\n\n      // If this is a revision, just show the site statuses statically and be done\n      if (this.settings.revisionId) {\n        this._getOtherSupportedSites().forEach((s) =>\n          this._createSiteStatusField(s)\n        );\n        return;\n      }\n\n      $enabledForSiteField.addClass('nested');\n      const $globalField = Craft.ui\n        .createLightswitchField({\n          label: Craft.t('app', 'Enabled for all sites'),\n          name: this.namespaceInputName('enabled'),\n        })\n        .insertBefore($enabledForSiteField);\n      $globalField.find('label').css('font-weight', 'bold');\n      this.$globalLightswitch = $globalField.find('.lightswitch');\n\n      if (!this.settings.revisionId) {\n        this._showField($globalField);\n      }\n\n      // Figure out what the \"Enabled everywhere\" lightswitch would have been set to when the page first loaded\n      const siteStatusValues = Object.values(this.settings.siteStatuses);\n      const hasEnabled = siteStatusValues.includes(true);\n      const hasDisabled = siteStatusValues.includes(false);\n      const originalEnabledValue =\n        hasEnabled && hasDisabled ? '-' : hasEnabled ? '1' : '';\n      const originalSerializedStatus =\n        encodeURIComponent(\n          this.namespaceInputName(`enabledForSite[${this.settings.siteId}]`)\n        ) +\n        '=' +\n        (this.settings.enabledForSite ? '1' : '');\n\n      this.$siteLightswitches = $enabledForSiteField\n        .find('.lightswitch')\n        .on('change', this._updateGlobalStatus.bind(this));\n\n      this._getOtherSupportedSites().forEach((s) =>\n        this._createSiteStatusField(s)\n      );\n\n      let serializedStatuses =\n        encodeURIComponent(this.namespaceInputName('enabled')) +\n        `=${originalEnabledValue}`;\n      for (let i = 0; i < this.$siteLightswitches.length; i++) {\n        const $input = this.$siteLightswitches.eq(i).data('lightswitch').$input;\n        serializedStatuses +=\n          '&' + encodeURIComponent($input.attr('name')) + '=' + $input.val();\n      }\n\n      this.$container.data(\n        'initialSerializedValue',\n        this.$container\n          .data('initialSerializedValue')\n          .replace(originalSerializedStatus, serializedStatuses)\n      );\n\n      if (this.lastSerializedValue) {\n        this.lastSerializedValue = this.lastSerializedValue.replace(\n          originalSerializedStatus,\n          serializedStatuses\n        );\n      }\n\n      // Are there additional sites that can be added?\n      if (\n        this.settings.additionalSites &&\n        this.settings.additionalSites.length &&\n        this.isFullPage\n      ) {\n        this._createAddlSiteField();\n      }\n\n      // Focus on first lightswitch\n      this.$globalLightswitch.focus();\n\n      this.$globalLightswitch.on('change', this._updateSiteStatuses.bind(this));\n      this._updateGlobalStatus();\n    },\n\n    /**\n     * @returns {Array}\n     */\n    _getOtherSupportedSites: function () {\n      return Craft.sites.filter(\n        (s) => s.id != this.settings.siteId && this.siteIds.includes(s.id)\n      );\n    },\n\n    _showField: function ($field) {\n      const height = $field.height();\n      $field\n        .css({\n          overflow: 'hidden',\n          'min-height': 'auto',\n        })\n        .height(0)\n        .velocity({height}, 'fast', () => {\n          $field.css({\n            overflow: '',\n            height: '',\n            'min-height': '',\n          });\n        });\n    },\n\n    _removeField: function ($field) {\n      $field\n        .css({\n          overflow: 'hidden',\n          'min-height': 'auto',\n        })\n        .velocity({height: 0}, 'fast', () => {\n          $field.remove();\n        });\n    },\n\n    _updateGlobalStatus: function () {\n      let allEnabled = true,\n        allDisabled = true;\n      this.$siteLightswitches.each(function () {\n        const enabled = $(this).data('lightswitch').on;\n        if (enabled) {\n          allDisabled = false;\n        } else {\n          allEnabled = false;\n        }\n        if (!allEnabled && !allDisabled) {\n          return false;\n        }\n      });\n      if (allEnabled) {\n        this.$globalLightswitch.data('lightswitch').turnOn(true);\n      } else if (allDisabled) {\n        this.$globalLightswitch.data('lightswitch').turnOff(true);\n      } else {\n        this.$globalLightswitch.data('lightswitch').turnIndeterminate(true);\n      }\n    },\n\n    _updateSiteStatuses: function () {\n      const enabled = this.$globalLightswitch.data('lightswitch').on;\n      this.$siteLightswitches.each(function () {\n        if (enabled) {\n          $(this).data('lightswitch').turnOn(true);\n        } else {\n          $(this).data('lightswitch').turnOff(true);\n        }\n      });\n    },\n\n    _createSiteStatusField: function (site, status) {\n      const $field = Craft.ui.createLightswitchField({\n        fieldClass: `enabled-for-site-${site.id}-field`,\n        label: site.name,\n        name: this.namespaceInputName(`enabledForSite[${site.id}]`),\n        on:\n          typeof status != 'undefined'\n            ? status\n            : this.settings.siteStatuses.hasOwnProperty(site.id)\n            ? this.settings.siteStatuses[site.id]\n            : true,\n        disabled: !!this.settings.revisionId,\n      });\n\n      if (this.$additionalSiteField) {\n        $field.insertBefore(this.$additionalSiteField);\n      } else {\n        $field.appendTo(this.$siteStatusPane);\n      }\n\n      if (!this.settings.revisionId) {\n        $field.addClass('nested');\n        const $lightswitch = $field\n          .find('.lightswitch')\n          .on('change', this._updateGlobalStatus.bind(this));\n        this.$siteLightswitches = this.$siteLightswitches.add($lightswitch);\n      }\n\n      this._showField($field);\n\n      return $field;\n    },\n\n    _createAddlSiteField: function () {\n      const additionalSites = Craft.sites.filter((site) => {\n        return (\n          !this.siteIds.includes(site.id) &&\n          this.settings.additionalSites.some((s) => s.siteId == site.id)\n        );\n      });\n\n      if (!additionalSites.length) {\n        return;\n      }\n\n      const selectLabelId = 'add-site-label';\n\n      const $addlSiteSelectLabel = $('<span/>', {\n        text: Craft.t('app', 'Add a site...'),\n        class: 'visually-hidden',\n        id: selectLabelId,\n      });\n\n      const $addlSiteSelectContainer = Craft.ui\n        .createSelect({\n          options: [\n            {label: Craft.t('app', 'Add a site…')},\n            ...additionalSites.map((s) => {\n              return {label: s.name, value: s.id};\n            }),\n          ],\n          labelledBy: selectLabelId,\n        })\n        .addClass('fullwidth');\n\n      this.$additionalSiteField = Craft.ui\n        .createField($addlSiteSelectContainer, {})\n        .addClass('nested add')\n        .appendTo(this.$siteStatusPane);\n\n      $addlSiteSelectLabel.prependTo(this.$additionalSiteField);\n\n      const $addlSiteSelect = $addlSiteSelectContainer.find('select');\n\n      $addlSiteSelect.on('change', () => {\n        const siteId = parseInt($addlSiteSelect.val());\n        const site = Craft.sites.find((s) => s.id === siteId);\n\n        if (!site) {\n          return;\n        }\n\n        const addlSiteInfo = this.settings.additionalSites.find(\n          (s) => s.siteId == site.id\n        );\n        this._createSiteStatusField(site, addlSiteInfo.enabledByDefault);\n        this._updateGlobalStatus();\n\n        $addlSiteSelect.val('').find(`option[value=\"${siteId}\"]`).remove();\n\n        if (this.newSiteIds === null) {\n          this.newSiteIds = [];\n        }\n\n        this.siteIds.push(siteId);\n        this.newSiteIds.push(siteId);\n\n        // Was that the last site?\n        if ($addlSiteSelect.find('option').length === 1) {\n          this._removeField(this.$additionalSiteField);\n        }\n      });\n\n      this._showField(this.$additionalSiteField);\n    },\n\n    showStatusHud: function (target) {\n      let bodyHtml;\n\n      if (!this.failed) {\n        bodyHtml = `<p>${this._saveSuccessMessage()}</p>`;\n      } else {\n        bodyHtml = `<p class=\"error\"><strong>${this._saveFailMessage()}</strong></p>`;\n\n        if (this.httpError) {\n          bodyHtml += `<p class=\"http-error code\">${Craft.escapeHtml(\n            this.httpError\n          )}</p>`;\n        }\n\n        if (this.httpStatus === 400) {\n          bodyHtml += `<button class=\"btn refresh-btn\">${Craft.t(\n            'app',\n            'Refresh'\n          )}</button>`;\n        }\n      }\n\n      const hud = new Garnish.HUD(target, bodyHtml, {\n        hudClass: 'hud revision-status-hud',\n        onHide: function () {\n          hud.destroy();\n        },\n      });\n\n      hud.$mainContainer.find('.refresh-btn').on('click', () => {\n        window.location.reload();\n      });\n    },\n\n    /**\n     * @returns {string}\n     */\n    _saveSuccessMessage: function () {\n      return this.settings.isProvisionalDraft ||\n        this.settings.isUnpublishedDraft\n        ? Craft.t('app', 'Your changes have been stored.')\n        : Craft.t('app', 'The draft has been saved.');\n    },\n\n    /**\n     * @returns {string}\n     */\n    _saveFailMessage: function () {\n      return this.settings.isProvisionalDraft ||\n        this.settings.isUnpublishedDraft\n        ? Craft.t('app', 'Your changes could not be stored.')\n        : Craft.t('app', 'The draft could not be saved.');\n    },\n\n    spinners: function () {\n      return this.preview\n        ? this.$spinner.add(this.preview.$spinner)\n        : this.$spinner;\n    },\n\n    showSpinner: function () {\n      this.spinners().removeClass('hidden');\n    },\n\n    hideSpinner: function () {\n      this.spinners().addClass('hidden');\n    },\n\n    statusIcons: function () {\n      return this.preview\n        ? this.$statusIcon.add(this.preview.$statusIcon)\n        : this.$statusIcon;\n    },\n\n    statusMessage: function () {\n      return this.preview\n        ? this.$statusMessage.add(this.preview.$statusMessage)\n        : this.$statusMessage;\n    },\n\n    createEditMetaBtn: function () {\n      const $btnGroup = this.$container.find('.context-btngroup');\n      this.$editMetaBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn edit icon',\n        'aria-expanded': 'false',\n        'aria-label': Craft.t('app', 'Edit draft settings'),\n        title: Craft.t('app', 'Edit draft settings'),\n      }).appendTo($btnGroup);\n      $btnGroup.find('.btngroup-btn-last').removeClass('btngroup-btn-last');\n      this.addListener(this.$editMetaBtn, 'click', 'showMetaHud');\n    },\n\n    createPreviewLink: function (target, label) {\n      const $a = $('<a/>', {\n        href: this.getTokenizedPreviewUrl(target.url, null, false),\n        text: label || Craft.t('app', 'View'),\n        target: '_blank',\n        data: {\n          targetUrl: target.url,\n          targetLabel: target.label,\n        },\n      });\n\n      this.addListener($a, 'click', () => {\n        setTimeout(() => {\n          this.activatePreviewToken();\n        }, 1);\n      });\n\n      this.previewLinks.push($a);\n      return $a;\n    },\n\n    updatePreviewLinks: function () {\n      this.previewLinks.forEach(($a) => {\n        this.updatePreviewLinkHref($a);\n        if (this.activatedPreviewToken) {\n          this.removeListener($a, 'click');\n        }\n      });\n    },\n\n    updatePreviewLinkHref: function ($a) {\n      $a.attr(\n        'href',\n        this.getTokenizedPreviewUrl($a.data('targetUrl'), null, false)\n      );\n    },\n\n    activatePreviewToken: function () {\n      if (this.settings.isLive) {\n        // don't do anything yet, but leave the event in case we need it later\n        return;\n      }\n\n      this.activatedPreviewToken = true;\n      this.updatePreviewLinks();\n    },\n\n    createShareMenu: function ($container) {\n      const $btn = $('<button/>', {\n        type: 'button',\n        class: 'view-btn btn menubtn',\n        text: Craft.t('app', 'View'),\n      }).appendTo($container);\n\n      const $menu = $('<div/>', {class: 'menu'}).appendTo($container);\n      const $ul = $('<ul/>').appendTo($menu);\n\n      this.settings.previewTargets.forEach((target) => {\n        $('<li/>')\n          .append(this.createPreviewLink(target, target.label))\n          .appendTo($ul);\n      });\n\n      new Garnish.MenuBtn($btn);\n    },\n\n    getPreviewTokenParams: function () {\n      const params = {\n        elementType: this.settings.elementType,\n        canonicalId: this.settings.canonicalId,\n        siteId: this.settings.siteId,\n        revisionId: this.settings.revisionId,\n        previewToken: this.settings.previewToken,\n      };\n\n      if (this.settings.draftId && !this.settings.isProvisionalDraft) {\n        params.draftId = this.settings.draftId;\n      }\n\n      return params;\n    },\n\n    getPreviewToken: function () {\n      return this.previewTokenQueue.push(() => {\n        return new Promise((resolve, reject) => {\n          if (this.activatedPreviewToken) {\n            resolve(this.settings.previewToken);\n            return;\n          }\n\n          Craft.sendActionRequest('POST', 'preview/create-token', {\n            data: this.getPreviewTokenParams(),\n          })\n            .then(() => {\n              this.activatePreviewToken();\n              resolve(this.settings.previewToken);\n            })\n            .catch(reject);\n        });\n      });\n    },\n\n    /**\n     * @param {string} url\n     * @param {?string} [randoParam]\n     * @param {boolean} [asPromise=false]\n     * @returns {(Promise|string)}\n     */\n    getTokenizedPreviewUrl: function (url, randoParam, asPromise) {\n      if (typeof asPromise === 'undefined') {\n        asPromise = true;\n      }\n\n      const params = {};\n\n      if (randoParam || !this.settings.isLive) {\n        // Randomize the URL so CDNs don't return cached pages\n        params[randoParam || 'x-craft-preview'] = Craft.randomString(10);\n      }\n\n      if (this.settings.siteToken) {\n        params[Craft.siteToken] = this.settings.siteToken;\n      }\n\n      // No need for a token if we're looking at a live element\n      if (this.settings.isLive) {\n        const previewUrl = Craft.getUrl(url, params);\n\n        if (asPromise) {\n          return new Promise((resolve) => {\n            resolve(previewUrl);\n          });\n        }\n\n        return previewUrl;\n      }\n\n      if (!this.settings.previewToken) {\n        throw 'Missing preview token';\n      }\n\n      params[Craft.tokenParam] = this.settings.previewToken;\n      const previewUrl = Craft.getUrl(url, params);\n\n      if (this.activatedPreviewToken) {\n        if (asPromise) {\n          return new Promise((resolve) => {\n            resolve(previewUrl);\n          });\n        }\n\n        return previewUrl;\n      }\n\n      if (asPromise) {\n        return new Promise((resolve, reject) => {\n          this.getPreviewToken()\n            .then(() => {\n              resolve(previewUrl);\n            })\n            .catch(reject);\n        });\n      }\n\n      const createTokenParams = this.getPreviewTokenParams();\n      createTokenParams.redirect = previewUrl;\n      return Craft.getActionUrl('preview/create-token', createTokenParams);\n    },\n\n    getPreview: function () {\n      if (!this.preview) {\n        this.preview = new Craft.Preview(this);\n        if (!this.enableAutosave) {\n          this.preview.on('open', () => {\n            this.enableAutosave = true;\n            this.listenForChanges();\n          });\n          this.preview.on('close', () => {\n            this.enableAutosave = false;\n            this.stopListeningForChanges();\n\n            // Hide the status icon if the save was successful\n            const $statusIcons = this.statusIcons();\n            if ($statusIcons.hasClass('checkmark-icon')) {\n              $statusIcons.addClass('hidden');\n            }\n          });\n        }\n        this.preview.on('close', () => {\n          if (this.scrollY) {\n            window.scrollTo(0, this.scrollY);\n            this.scrollY = null;\n          }\n        });\n      }\n      return this.preview;\n    },\n\n    openPreview: function () {\n      if (Garnish.hasAttr(this.$previewBtn, 'aria-disabled')) {\n        return;\n      }\n\n      this.$previewBtn.attr('aria-disabled', true);\n      this.$previewBtn.addClass('loading');\n\n      this.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            this.openingPreview = true;\n            this.ensureIsDraftOrRevision(true)\n              .then(() => {\n                this.scrollY = window.scrollY;\n                this.$previewBtn.removeAttr('aria-disabled');\n                this.$previewBtn.removeClass('loading');\n                this.getPreview().open();\n                this.openingPreview = false;\n                resolve();\n              })\n              .catch(reject);\n          })\n      );\n    },\n\n    ensureIsDraftOrRevision: function (onlyIfChanged) {\n      return new Promise((resolve, reject) => {\n        if (!this.settings.draftId && !this.settings.revisionId) {\n          if (\n            onlyIfChanged &&\n            this.serializeForm(true) ===\n              this.$container.data('initialSerializedValue')\n          ) {\n            resolve();\n            return;\n          }\n\n          this.createDraft().then(resolve).catch(reject);\n        } else {\n          resolve();\n        }\n      });\n    },\n\n    serializeForm: function (removeActionParams) {\n      let data = this.$container.serialize();\n\n      if (this.isPreviewActive()) {\n        // Replace the temp input with the preview form data\n        data = data.replace(\n          '__PREVIEW_FIELDS__=1',\n          this.preview.$editor.serialize()\n        );\n      }\n\n      if (removeActionParams && !this.settings.isUnpublishedDraft) {\n        // Remove action and redirect params\n        const actionName = this.namespaceInputName('action');\n        const redirectName = this.namespaceInputName('redirect');\n        data = data.replace(\n          new RegExp(`&${Craft.escapeRegex(actionName)}=[^&]*`),\n          ''\n        );\n        data = data.replace(\n          new RegExp(`&${Craft.escapeRegex(redirectName)}=[^&]*`),\n          ''\n        );\n      }\n\n      return data;\n    },\n\n    /**\n     * @param {boolean} [force=false]\n     * @returns {Promise}\n     */\n    checkForm: function (force) {\n      return this.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            // If this isn't a draft and there's no active preview, then there's nothing to check\n            if (\n              this.settings.revisionId ||\n              this.pauseLevel > 0 ||\n              !this.enableAutosave ||\n              !this.settings.canCreateDrafts\n            ) {\n              resolve();\n              return;\n            }\n\n            clearTimeout(this.timeout);\n            this.timeout = null;\n\n            // If we haven't had a chance to fetch the initial data yet, try again in a bit\n            if (\n              typeof this.$container.data('initialSerializedValue') ===\n              'undefined'\n            ) {\n              this.timeout = setTimeout(this.checkForm.bind(this), 500);\n              return;\n            }\n\n            // Has anything changed?\n            const data = this.serializeForm(true);\n            if (\n              !force &&\n              data ===\n                (this.lastSerializedValue ||\n                  this.$container.data('initialSerializedValue'))\n            ) {\n              resolve();\n              return;\n            }\n\n            this.saveDraft(data)\n              .then(resolve)\n              .catch((e) => {\n                console.warn('Couldn’t save draft:', e);\n                reject(e);\n              });\n          })\n      );\n    },\n\n    isPreviewActive: function () {\n      return this.preview && this.preview.isActive;\n    },\n\n    createDraft: function () {\n      return this.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            this.saveDraft(this.serializeForm(true))\n              .then(resolve)\n              .catch(reject);\n          })\n      );\n    },\n\n    /**\n     * @param {Object} data\n     * @returns {Promise}\n     */\n    saveDraft: function (data) {\n      return new Promise((resolve, reject) => {\n        // Ignore if we're already submitting the main form\n        if (this.submittingForm) {\n          reject('Form already being submitted.');\n          return;\n        }\n\n        this.lastSerializedValue = data;\n        this.failed = false;\n        this.httpStatus = null;\n        this.httpError = null;\n        this.cancelToken = axios.CancelToken.source();\n\n        this.statusIcons()\n          .velocity('stop')\n          .css('opacity', '')\n          .removeClass('hidden invisible checkmark-icon alert-icon fade-out')\n          .addClass('hidden');\n\n        // Clear previous status message\n        this.statusMessage().empty();\n\n        if (this.$saveMetaBtn) {\n          this.$saveMetaBtn.addClass('active');\n        }\n\n        // Prep the data to be saved, keeping track of the first input name for each delta group\n        let modifiedFieldNames = [];\n        let preparedData = this.prepareData(\n          data,\n          !this.settings.isUnpublishedDraft\n            ? (deltaName, params) => {\n                if (params.length) {\n                  modifiedFieldNames.push(\n                    decodeURIComponent(params[0].split('=')[0])\n                  );\n                }\n              }\n            : null\n        );\n\n        const extraData = {\n          [this.namespaceInputName('visibleLayoutElements')]:\n            this.settings.visibleLayoutElements,\n        };\n\n        // Are we saving a provisional draft?\n        if (this.settings.isProvisionalDraft || !this.settings.draftId) {\n          extraData[this.namespaceInputName('provisional')] = 1;\n        }\n\n        const selectedTabId = this.$contentContainer\n          .children('[data-layout-tab]:not(.hidden)')\n          .data('id');\n        if (selectedTabId) {\n          extraData[this.namespaceInputName('selectedTab')] = selectedTabId;\n        }\n\n        preparedData += `&${$.param(extraData)}`;\n\n        Craft.sendActionRequest('POST', 'elements/save-draft', {\n          cancelToken: this.cancelToken.token,\n          headers: this._saveHeaders,\n          data: preparedData,\n        })\n          .then((response) => {\n            // capture the new selected tab ID, in case it just changed\n            const newSelectedTabId = this.$contentContainer\n              .children('[data-layout-tab]:not(.hidden)')\n              .data('id');\n\n            this._afterSaveDraft();\n\n            const createdProvisionalDraft = !this.settings.draftId;\n\n            if (createdProvisionalDraft) {\n              this.settings.isProvisionalDraft = true;\n              this.$revisionLabel.append(\n                $('<span/>', {\n                  text: ` — ${Craft.t('app', 'Edited')}`,\n                })\n              );\n            }\n\n            if (this.isFullPage) {\n              if (response.data.title) {\n                this.$container.find('.screen-title').text(response.data.title);\n              }\n\n              if (response.data.docTitle) {\n                document.title = response.data.docTitle;\n              }\n            }\n\n            if (!this.settings.isProvisionalDraft) {\n              this.$revisionLabel.text(response.data.draftName);\n              this.settings.draftName = response.data.draftName;\n            }\n\n            let revisionMenu = this.$revisionBtn.data('menubtn')\n              ? this.$revisionBtn.data('menubtn').menu\n              : null;\n\n            // Did we just add a site?\n            if (this.newSiteIds) {\n              // Do we need to create the revision menu?\n              if (!revisionMenu) {\n                this.$revisionBtn.removeClass('disabled').addClass('menubtn');\n                new Garnish.MenuBtn(this.$revisionBtn);\n                revisionMenu = this.$revisionBtn.data('menubtn').menu;\n                revisionMenu.$container.removeClass('hidden');\n              }\n              this.newSiteIds.forEach((siteId) => {\n                const $option = revisionMenu.$options.filter(\n                  `[data-site-id=${siteId}]`\n                );\n                const siteSettings = this.settings.additionalSites.find(\n                  (s) => s.siteId == siteId\n                );\n                if (\n                  !siteSettings ||\n                  typeof siteSettings.enabledByDefault === 'undefined' ||\n                  siteSettings.enabledByDefault\n                ) {\n                  $option\n                    .find('.status')\n                    .removeClass('disabled')\n                    .addClass('enabled');\n                }\n                const $li = $option.parent().removeClass('hidden');\n                $li.closest('.site-group').removeClass('hidden');\n              });\n              revisionMenu.$container\n                .find('.revision-hr')\n                .removeClass('hidden');\n              this.newSiteIds = null;\n            }\n\n            if (this.settings.isProvisionalDraft) {\n              if (createdProvisionalDraft) {\n                // Replace the action\n                this.$container\n                  .find('input.action-input')\n                  .attr('value', 'elements/apply-draft');\n\n                // Update the editor settings\n                this.settings.draftId = response.data.draftId;\n                this.settings.isLive = false;\n                this.previewToken = null;\n\n                this.initForProvisionalDraft();\n              }\n            } else if (revisionMenu) {\n              revisionMenu.$options\n                .filter('.sel')\n                .find('.draft-name')\n                .text(response.data.draftName);\n              revisionMenu.$options\n                .filter('.sel')\n                .find('.draft-meta')\n                .text(\n                  response.data.creator\n                    ? Craft.t('app', 'Saved {timestamp} by {creator}', {\n                        timestamp: response.data.timestamp,\n                        creator: response.data.creator,\n                      })\n                    : Craft.t('app', 'Saved {timestamp}', {\n                        timestamp: response.data.timestamp,\n                      })\n                );\n            }\n\n            // Did the controller send us updated preview targets?\n            if (\n              response.data.previewTargets &&\n              JSON.stringify(response.data.previewTargets) !==\n                JSON.stringify(this.settings.previewTargets)\n            ) {\n              this.updatePreviewTargets(response.data.previewTargets);\n            }\n\n            if (createdProvisionalDraft) {\n              this.updatePreviewLinks();\n              this.trigger('createProvisionalDraft');\n            }\n\n            if (this.$nameTextInput) {\n              this.checkMetaValues();\n            }\n\n            for (const oldId in response.data.duplicatedElements) {\n              if (\n                oldId != this.settings.canonicalId &&\n                response.data.duplicatedElements.hasOwnProperty(oldId)\n              ) {\n                this.duplicatedElements[oldId] =\n                  response.data.duplicatedElements[oldId];\n              }\n            }\n\n            // Add missing field modified indicators\n            const selectors = response.data.modifiedAttributes\n              .map((attr) => {\n                attr = this.namespaceInputName(attr);\n                return `[name=\"${attr}\"],[name^=\"${attr}[\"]`;\n              })\n              .concat(modifiedFieldNames.map((name) => `[name=\"${name}\"]`));\n\n            const $fields = $(selectors.join(','))\n              .parents()\n              .filter('.flex-fields > .field:not(:has(> .status-badge))');\n            for (let i = 0; i < $fields.length; i++) {\n              $fields.eq(i).prepend(\n                $('<div/>', {\n                  class: 'status-badge modified',\n                  title: Craft.t('app', 'This field has been modified.'),\n                }).append(\n                  $('<span/>', {\n                    class: 'visually-hidden',\n                    html: Craft.t('app', 'This field has been modified.'),\n                  })\n                )\n              );\n            }\n\n            // Keep track of whether anything changed while we were waiting.\n            // If not, we can safely update lastSerializedValue after swapping out the fields\n            const noChanges = this.serializeForm(true) === data;\n\n            // Update the visible elements\n            let $allTabContainers = $();\n            const visibleLayoutElements = {};\n            let changedElements = false;\n\n            for (let i = 0; i < response.data.missingElements.length; i++) {\n              const tabInfo = response.data.missingElements[i];\n              let $tabContainer = this.$contentContainer.children(\n                `[data-layout-tab=\"${tabInfo.uid}\"]`\n              );\n\n              if (!$tabContainer.length) {\n                $tabContainer = $('<div/>', {\n                  id: this.namespaceId(tabInfo.id),\n                  class: 'flex-fields',\n                  'data-id': tabInfo.id,\n                  'data-layout-tab': tabInfo.uid,\n                });\n                if (tabInfo.id !== selectedTabId) {\n                  $tabContainer.addClass('hidden');\n                }\n                $tabContainer.appendTo(this.$contentContainer);\n              }\n\n              $allTabContainers = $allTabContainers.add($tabContainer);\n\n              for (let j = 0; j < tabInfo.elements.length; j++) {\n                const elementInfo = tabInfo.elements[j];\n\n                if (elementInfo.html !== false) {\n                  if (!visibleLayoutElements[tabInfo.uid]) {\n                    visibleLayoutElements[tabInfo.uid] = [];\n                  }\n                  visibleLayoutElements[tabInfo.uid].push(elementInfo.uid);\n\n                  if (typeof elementInfo.html === 'string') {\n                    const $oldElement = $tabContainer.children(\n                      `[data-layout-element=\"${elementInfo.uid}\"]`\n                    );\n                    const $newElement = $(elementInfo.html);\n                    if ($oldElement.length) {\n                      $oldElement.replaceWith($newElement);\n                    } else {\n                      $newElement.appendTo($tabContainer);\n                    }\n                    Craft.initUiElements($newElement);\n                    changedElements = true;\n                  }\n                } else {\n                  const $oldElement = $tabContainer.children(\n                    `[data-layout-element=\"${elementInfo.uid}\"]`\n                  );\n                  if (\n                    !$oldElement.length ||\n                    !Garnish.hasAttr(\n                      $oldElement,\n                      'data-layout-element-placeholder'\n                    )\n                  ) {\n                    const $placeholder = $('<div/>', {\n                      class: 'hidden',\n                      'data-layout-element': elementInfo.uid,\n                      'data-layout-element-placeholder': '',\n                    });\n\n                    if ($oldElement.length) {\n                      $oldElement.replaceWith($placeholder);\n                    } else {\n                      $placeholder.appendTo($tabContainer);\n                    }\n\n                    changedElements = true;\n                  }\n                }\n              }\n            }\n\n            // Remove any unused tab content containers\n            // (`[data-layout-tab=\"\"]` == unconditional containers, so ignore those)\n            const $unusedTabContainers = this.$contentContainer\n              .children('[data-layout-tab]')\n              .not($allTabContainers)\n              .not('[data-layout-tab=\"\"]');\n            if ($unusedTabContainers.length) {\n              $unusedTabContainers.remove();\n              changedElements = true;\n            }\n\n            // Make the first tab visible if no others are\n            if (!$allTabContainers.filter(':not(.hidden)').length) {\n              $allTabContainers.first().removeClass('hidden');\n            }\n\n            this.settings.visibleLayoutElements = visibleLayoutElements;\n\n            // Update the tabs\n            let tabManager;\n            if (this.isFullPage) {\n              Craft.cp.updateTabs(response.data.tabs);\n              tabManager = Craft.cp.tabManager;\n            } else {\n              this.slideout.updateTabs(response.data.tabs);\n              tabManager = this.slideout.tabManager;\n            }\n\n            // was a new tab selected after the autosave request was kicked off?\n            if (\n              selectedTabId &&\n              newSelectedTabId &&\n              selectedTabId !== newSelectedTabId\n            ) {\n              const $newSelectedTab = tabManager.$tabs.filter(\n                `[data-id=\"${newSelectedTabId}\"]`\n              );\n              if ($newSelectedTab.length) {\n                // if the new tab is visible - switch to it\n                tabManager.selectTab($newSelectedTab);\n              } else {\n                // if the new tab is not visible (e.g. hidden by a condition)\n                // switch to the first tab\n                tabManager.selectTab(tabManager.$tabs.first());\n              }\n            }\n\n            Craft.appendHeadHtml(response.data.headHtml);\n            Craft.appendBodyHtml(response.data.bodyHtml);\n\n            // Did any layout elements get added or removed?\n            if (changedElements) {\n              if (response.data.initialDeltaValues) {\n                Object.assign(\n                  this.$container.data('initial-delta-values'),\n                  response.data.initialDeltaValues\n                );\n              }\n\n              if (noChanges) {\n                // Update our record of the last serialized value to avoid a pointless resave\n                this.lastSerializedValue = this.serializeForm(true);\n              }\n            }\n\n            // re-grab dismissible tips, re-attach listener, hide on re-load\n            this.handleDismissibleTips();\n\n            this.afterUpdate(data);\n\n            if (Craft.broadcaster) {\n              Craft.broadcaster.postMessage({\n                pageId: Craft.pageId,\n                event: 'saveDraft',\n                canonicalId: this.settings.canonicalId,\n                draftId: this.settings.draftId,\n                isProvisionalDraft: this.settings.isProvisionalDraft,\n              });\n            }\n\n            resolve();\n          })\n          .catch((e) => {\n            this._afterSaveDraft();\n\n            if (!this.ignoreFailedRequest) {\n              this.failed = true;\n              if (e && e.response) {\n                this.httpStatus = e.response.status;\n                this.httpError = e.response.data\n                  ? e.response.data.message\n                  : null;\n              }\n              this._showFailStatus();\n              reject(e);\n            }\n\n            this.ignoreFailedRequest = false;\n          });\n      });\n    },\n\n    _afterSaveDraft: function () {\n      if (this.$saveMetaBtn) {\n        this.$saveMetaBtn.removeClass('active');\n      }\n    },\n\n    _showFailStatus: function () {\n      this.statusIcons()\n        .velocity('stop')\n        .css('opacity', '')\n        .removeClass('hidden checkmark-icon')\n        .addClass('alert-icon');\n\n      this.setStatusMessage(this._saveFailMessage());\n    },\n\n    /**\n     * @param {string} data\n     * @param {findDeltaDataCallback} [deltaCallback] Callback function that should be passed to `Craft.findDeltaData()`\n     * @returns {string}\n     */\n    prepareData: function (data, deltaCallback) {\n      // Filter out anything that hasn't changed since the last time the form was submitted\n      data = Craft.findDeltaData(\n        this.$container.data('initialSerializedValue'),\n        data,\n        this.$container.data('delta-names'),\n        deltaCallback,\n        this.$container.data('initial-delta-values'),\n        this.$container.data('modified-delta-names')\n      );\n\n      // Swap out element IDs with their duplicated ones\n      data = this.swapDuplicatedElementIds(data);\n\n      const extraData = {};\n\n      // Add the draft info\n      if (this.settings.draftId) {\n        extraData[this.namespaceInputName('draftId')] = this.settings.draftId;\n\n        if (this.settings.isProvisionalDraft) {\n          extraData[this.namespaceInputName('provisional')] = 1;\n        }\n      }\n\n      if (this.settings.draftName !== null) {\n        extraData[this.namespaceInputName('draftName')] =\n          this.settings.draftName;\n      }\n\n      if (!$.isEmptyObject(extraData)) {\n        data += `&${$.param(extraData)}`;\n      }\n\n      return data;\n    },\n\n    get _saveHeaders() {\n      const headers = {\n        'content-type': 'application/x-www-form-urlencoded',\n      };\n\n      if (this.namespace) {\n        headers['X-Craft-Namespace'] = this.namespace;\n      }\n\n      return headers;\n    },\n\n    /**\n     * @param {string} data\n     * @returns {string}\n     */\n    swapDuplicatedElementIds: function (data) {\n      const idsRE = Object.keys(this.duplicatedElements).join('|');\n      if (idsRE === '') {\n        return data;\n      }\n      const lb = encodeURIComponent('[');\n      const rb = encodeURIComponent(']');\n      let namespacedFields = this.namespaceInputName('fields');\n\n      if (this.isFullPage) {\n        namespacedFields = Craft.escapeRegex(namespacedFields);\n      } else {\n        // don't escape namespaced input names, but URI encode them (for cases like: cnuvbcxlgq[fields])\n        namespacedFields = encodeURIComponent(namespacedFields);\n      }\n\n      // Keep replacing field IDs until data stops changing\n      while (true) {\n        if (\n          data ===\n          (data = data\n            // &fields[...][X]\n            .replace(\n              new RegExp(\n                `(&${namespacedFields}${lb}[^=]+${rb}${lb})(${idsRE})(${rb})`,\n                'g'\n              ),\n              (m, pre, id, post) => {\n                if (!this._filterFieldInputName(pre)) {\n                  return m;\n                }\n                return pre + this.duplicatedElements[id] + post;\n              }\n            )\n            // &fields[...=X\n            .replace(\n              new RegExp(`&(${namespacedFields}${lb}[^=]+)=(${idsRE})\\\\b`, 'g'),\n              (m, name, id) => {\n                // Ignore param names that end in `[enabled]`, `[type]`, etc.\n                // (`[sortOrder]` should pass here, which could be set to a specific order index, but *not* `[sortOrder][]`!)\n                if (\n                  !this._filterFieldInputName(name) ||\n                  name.match(\n                    new RegExp(`${lb}(enabled|sortOrder|type|typeId)${rb}$`)\n                  )\n                ) {\n                  return m;\n                }\n                return `&${name}=${this.duplicatedElements[id]}`;\n              }\n            ))\n        ) {\n          break;\n        }\n      }\n      return data;\n    },\n\n    _filterFieldInputName: function (name) {\n      // Find the last referenced field handle\n      const lb = encodeURIComponent('[');\n      const rb = encodeURIComponent(']');\n      const nestedNames = name.match(\n        new RegExp(`(\\\\bfields|${lb}fields${rb})${lb}.+?${rb}`, 'g')\n      );\n      if (!nestedNames) {\n        throw `Unexpected input name: ${name}`;\n      }\n      const lastHandle = nestedNames[nestedNames.length - 1].match(\n        new RegExp(`(?:\\\\bfields|${lb}fields${rb})${lb}(.+?)${rb}`)\n      )[1];\n      return Craft.fieldsWithoutContent.includes(lastHandle);\n    },\n\n    updatePreviewTargets: function (previewTargets) {\n      previewTargets.forEach((newTarget) => {\n        const currentTarget = this.settings.previewTargets.find(\n          (t) => t.label === newTarget.label\n        );\n        if (currentTarget) {\n          currentTarget.url = newTarget.url;\n        }\n\n        const $previewLink = this.previewLinks.find(\n          ($a) => $a.data('targetLabel') === newTarget.label\n        );\n        if ($previewLink) {\n          $previewLink.data('targetUrl', newTarget.url);\n          this.updatePreviewLinkHref($previewLink);\n        }\n      });\n    },\n\n    afterUpdate: function (data) {\n      this.$container.data('initialSerializedValue', data);\n      this.$container.data('initial-delta-values', {});\n\n      const $statusIcons = this.statusIcons()\n        .velocity('stop')\n        .css('opacity', '')\n        .removeClass('hidden')\n        .addClass('checkmark-icon');\n\n      this.setStatusMessage(this._saveSuccessMessage());\n\n      if (!Craft.autosaveDrafts) {\n        // Fade the icon out after a couple seconds, since it won't be accurate as content continues to change\n        $statusIcons.velocity('stop').velocity(\n          {\n            opacity: 0,\n          },\n          {\n            delay: 2000,\n            complete: () => {\n              $statusIcons.addClass('hidden');\n            },\n          }\n        );\n      }\n\n      this.trigger('update');\n    },\n\n    setStatusMessage: function (message) {\n      this.statusIcons().attr('title', message);\n      this.statusMessage()\n        .empty()\n        .append(\n          $('<span/>', {\n            class: 'visually-hidden',\n            text: message,\n          })\n        );\n    },\n\n    showMetaHud: function () {\n      if (!this.metaHud) {\n        this.createMetaHud();\n        this.onMetaHudShow();\n      } else {\n        this.metaHud.show();\n      }\n\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$nameTextInput.trigger('focus');\n      }\n    },\n\n    createMetaHud: function () {\n      const $hudBody = $('<div/>');\n\n      // Add the Name field\n      const $nameField = $(\n        '<div class=\"field\"><div class=\"heading\"><label for=\"draft-name\">' +\n          Craft.t('app', 'Draft Name') +\n          '</label></div></div>'\n      ).appendTo($hudBody);\n      const $nameInputContainer = $('<div class=\"input\"/>').appendTo(\n        $nameField\n      );\n      this.$nameTextInput = $(\n        '<input type=\"text\" class=\"text fullwidth\" id=\"draft-name\"/>'\n      )\n        .appendTo($nameInputContainer)\n        .val(this.settings.draftName);\n\n      // HUD footer\n      const $footer = $('<div class=\"hud-footer flex flex-center\"/>').appendTo(\n        $hudBody\n      );\n\n      $('<div class=\"flex-grow\"></div>').appendTo($footer);\n      this.$saveMetaBtn = $('<button/>', {\n        type: 'submit',\n        class: 'btn submit disabled',\n        'aria-disabled': 'true',\n        text: Craft.t('app', 'Save'),\n      }).appendTo($footer);\n\n      this.metaHud = new Garnish.HUD(this.$editMetaBtn, $hudBody, {\n        onSubmit: this.saveMeta.bind(this),\n      });\n\n      this.addListener(this.$nameTextInput, 'input', 'checkMetaValues');\n\n      this.metaHud.on('show', this.onMetaHudShow.bind(this));\n      this.metaHud.on('hide', this.onMetaHudHide.bind(this));\n      this.metaHud.on('escape', this.onMetaHudEscape.bind(this));\n    },\n\n    onMetaHudShow: function () {\n      this.$editMetaBtn.addClass('active');\n      this.$editMetaBtn.attr('aria-expanded', 'true');\n    },\n\n    onMetaHudHide: function () {\n      this.$editMetaBtn.removeClass('active');\n      this.$editMetaBtn.attr('aria-expanded', 'false');\n\n      if (Garnish.focusIsInside(this.metaHud.$body)) {\n        this.$editMetaBtn.trigger('focus');\n      }\n    },\n\n    onMetaHudEscape: function () {\n      this.$nameTextInput.val(this.settings.draftName);\n    },\n\n    checkMetaValues: function () {\n      if (\n        this.$nameTextInput.val() &&\n        this.$nameTextInput.val() !== this.settings.draftName\n      ) {\n        this.$saveMetaBtn.removeClass('disabled');\n        this.$saveMetaBtn.removeAttr('aria-disabled');\n        return true;\n      }\n\n      this.$saveMetaBtn.addClass('disabled');\n      this.$saveMetaBtn.attr('aria-disabled', 'true');\n      return false;\n    },\n\n    shakeMetaHud: function () {\n      Garnish.shake(this.metaHud.$hud);\n    },\n\n    saveMeta: function () {\n      return new Promise((resolve, reject) => {\n        if (!this.checkMetaValues()) {\n          this.shakeMetaHud();\n          reject();\n          return;\n        }\n\n        this.settings.draftName = this.$nameTextInput.val();\n        this.metaHud.hide();\n        this.checkForm(true).then(resolve).catch(reject);\n      });\n    },\n\n    handleSubmit: function (ev) {\n      ev.preventDefault();\n      ev.stopPropagation();\n\n      // Prevent double form submits\n      if (this.submittingForm) {\n        return;\n      }\n\n      // If this a draft and was this a normal save (either via submit button or save shortcut),\n      // then trigger an autosave\n      if (\n        this.settings.draftId &&\n        !this.settings.isUnpublishedDraft &&\n        !this.settings.isProvisionalDraft &&\n        (typeof ev.autosave === 'undefined' || ev.autosave) &&\n        (ev.saveShortcut ||\n          (ev.customTrigger &&\n            ev.customTrigger.data('action') === 'elements/save-draft')) &&\n        this.enableAutosave\n      ) {\n        this.checkForm(true);\n        return;\n      }\n\n      this.submittingForm = true;\n\n      // Prevent the normal unload confirmation dialog\n      Craft.cp.$confirmUnloadForms = Craft.cp.$confirmUnloadForms.not(\n        this.$container\n      );\n\n      // Abort the current save request if there is one\n      if (this.cancelToken) {\n        this.ignoreFailedRequest = true;\n        this.cancelToken.cancel();\n      }\n\n      this.trigger('beforeSubmit');\n\n      // Duplicate the form with normalized data\n      const data = this.prepareData(this.serializeForm(false));\n\n      if (this.isFullPage) {\n        this.stopListeningForChanges();\n        const $form = Craft.createForm(data);\n        $form.appendTo(Garnish.$bod);\n        $form.submit();\n      } else {\n        this.slideout.showSubmitSpinner();\n        Craft.sendActionRequest('POST', null, {\n          headers: this._saveHeaders,\n          data,\n        })\n          .then((response) => {\n            this.slideout.handleSubmitResponse(response);\n          })\n          .catch((error) => {\n            this.slideout.handleSubmitError(error);\n          })\n          .finally(() => {\n            this.submittingForm = false;\n            this.slideout.hideSubmitSpinner();\n          });\n      }\n    },\n\n    handleDismissibleTips: function () {\n      this.addListener(this.tipDismissBtn, 'click', (e) => {\n        this.hideTip(e);\n      });\n    },\n\n    getHiddenTipsUids: function () {\n      return Craft.getLocalStorage('dismissedTips', []);\n    },\n\n    setHiddenTipsUids: function (uids) {\n      Craft.setLocalStorage('dismissedTips', uids);\n    },\n\n    hideTip: function (ev) {\n      const targetElement = ev.target;\n      if (targetElement) {\n        const $targetParent = $(targetElement).closest('.readable');\n        if ($targetParent.length) {\n          const layoutElementUid = $targetParent.data('layout-element');\n          $targetParent.remove();\n          // add info to local storage\n          if (typeof Storage !== 'undefined') {\n            const hiddenTips = this.getHiddenTipsUids();\n            if (!hiddenTips.includes(layoutElementUid)) {\n              hiddenTips.push(layoutElementUid);\n              this.setHiddenTipsUids(hiddenTips);\n            }\n          }\n        }\n      }\n    },\n  },\n  {\n    defaults: {\n      additionalSites: [],\n      canCreateDrafts: false,\n      canEditMultipleSites: false,\n      canSaveCanonical: false,\n      canonicalId: null,\n      draftId: null,\n      draftName: null,\n      elementType: null,\n      enablePreview: false,\n      enabled: false,\n      enabledForSite: false,\n      hashedCpEditUrl: null,\n      isLive: false,\n      isProvisionalDraft: false,\n      isUnpublishedDraft: false,\n      previewTargets: [],\n      previewToken: null,\n      revisionId: null,\n      siteId: null,\n      siteStatuses: null,\n      siteToken: null,\n      visibleLayoutElements: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Editor Slideout\n */\nCraft.ElementEditorSlideout = Craft.CpScreenSlideout.extend(\n  {\n    $element: null,\n\n    init: function (element, settings) {\n      this.$element = $(element);\n\n      settings = Object.assign(\n        {},\n        Craft.ElementEditorSlideout.defaults,\n        settings,\n        {\n          showHeader: true,\n        }\n      );\n      this.base('elements/edit', settings);\n\n      this.on('load', () => {\n        const editor = this.$container.data('elementEditor');\n        if (editor) {\n          editor.on('beforeSubmit', () => {\n            Object.keys(this.settings.saveParams).forEach((name) => {\n              $('<input/>', {\n                class: 'hidden',\n                name: editor.namespaceInputName(name),\n                value: this.settings.saveParams[name],\n              }).appendTo(this.$container);\n            });\n          });\n        }\n      });\n\n      this.on('submit', (ev) => {\n        if (Craft.broadcaster) {\n          Craft.broadcaster.postMessage({\n            event: 'saveElement',\n            id: ev.response.data.element.id,\n          });\n        }\n\n        // Pass the response data off to onSaveElement() for backwards compatibility\n        if (this.settings.onSaveElement) {\n          const data = Object.assign(\n            {},\n            ev.response.data,\n            ev.response.data.element\n          );\n          delete data.element;\n          delete data.modelName;\n          delete data.message;\n          this.settings.onSaveElement(data);\n        }\n\n        // Refresh Live Preview\n        Craft.Preview.refresh();\n      });\n    },\n\n    getParams: function () {\n      const params = {};\n\n      if (this.settings.elementType) {\n        params.elementType = this.settings.elementType;\n      }\n\n      if (this.settings.elementId) {\n        params.elementId = this.settings.elementId;\n      } else if (this.$element && this.$element.data('id')) {\n        params.elementId = this.$element.data('id');\n      }\n\n      if (this.settings.draftId) {\n        params.draftId = this.settings.draftId;\n      } else if (this.$element && this.$element.data('draft-id')) {\n        params.draftId = this.$element.data('draft-id');\n      } else if (this.settings.revisionId) {\n        params.revisionId = this.settings.revisionId;\n      } else if (this.$element && this.$element.data('revision-id')) {\n        params.revisionId = this.$element.data('revision-id');\n      }\n\n      if (this.settings.siteId) {\n        params.siteId = this.settings.siteId;\n      } else if (this.$element && this.$element.data('site-id')) {\n        params.siteId = this.$element.data('site-id');\n      }\n\n      if (this.settings.prevalidate) {\n        params.prevalidate = 1;\n      }\n\n      return params;\n    },\n\n    handleSubmit: function (ev) {\n      this.$container.data('elementEditor').handleSubmit(ev);\n    },\n  },\n  {\n    defaults: {\n      elementId: null,\n      draftId: null,\n      revisionId: null,\n      elementType: null,\n      siteId: null,\n      prevalidate: false,\n      saveParams: {},\n      onSaveElement: null,\n      validators: [],\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\nCraft.ElementFieldSettings = Garnish.Base.extend({\n  allowMultipleSources: null,\n  $maintainHierarchyField: null,\n  $maintainHierarchyInput: null,\n  $sourcesField: null,\n  $sourceSelect: null,\n  $branchLimitField: null,\n  $maxRelationsField: null,\n  $minRelationsField: null,\n\n  init: function (\n    allowMultipleSources,\n    maintainHierarchyFieldId,\n    sourcesFieldId,\n    branchLimitFieldId,\n    minRelationsFieldId,\n    maxRelationsFieldId\n  ) {\n    this.allowMultipleSources = allowMultipleSources;\n    this.$maintainHierarchyField = $(`#${maintainHierarchyFieldId}`);\n    this.$maintainHierarchyInput = this.$maintainHierarchyField.find(\n      'input[type=\"checkbox\"]'\n    );\n    this.$sourcesField = $(`#${sourcesFieldId}`);\n    if (!this.allowMultipleSources) {\n      this.$sourceSelect = this.$sourcesField.find('select');\n    }\n    this.$branchLimitField = $(`#${branchLimitFieldId}`);\n    this.$minRelationsField = $(`#${minRelationsFieldId}`);\n    this.$maxRelationsField = $(`#${maxRelationsFieldId}`);\n\n    this.updateLimitFields();\n    this.addListener(\n      this.$maintainHierarchyInput,\n      'change',\n      'updateLimitFields'\n    );\n\n    if (this.allowMultipleSources) {\n      this.$sourcesField.find('[type=checkbox]').each(\n        function (index, checkbox) {\n          this.addListener(\n            $(checkbox),\n            'change',\n            'updateMaintainHierarchyField'\n          );\n        }.bind(this)\n      );\n    } else {\n      this.addListener(\n        this.$sourceSelect,\n        'change',\n        'updateMaintainHierarchyField'\n      );\n    }\n    this.updateMaintainHierarchyField();\n  },\n\n  updateLimitFields: function () {\n    if (\n      !this.$maintainHierarchyField.hasClass('hidden') &&\n      this.$maintainHierarchyInput.is(':checked')\n    ) {\n      this.$minRelationsField.addClass('hidden');\n      this.$maxRelationsField.addClass('hidden');\n      this.$branchLimitField.removeClass('hidden');\n    } else {\n      this.$branchLimitField.addClass('hidden');\n      this.$minRelationsField.removeClass('hidden');\n      this.$maxRelationsField.removeClass('hidden');\n    }\n  },\n\n  updateMaintainHierarchyField: function () {\n    let showField;\n    if (this.allowMultipleSources) {\n      const $checkedInputs = this.$sourcesField.find(\n        '[type=\"checkbox\"]:checked'\n      );\n      showField =\n        $checkedInputs.length === 1 && $checkedInputs.data('structure-id');\n    } else {\n      showField = this.$sourceSelect\n        .children('option:selected')\n        .data('structure-id');\n    }\n\n    if (showField) {\n      this.$maintainHierarchyField.removeClass('hidden');\n    } else {\n      this.$maintainHierarchyField.addClass('hidden');\n    }\n\n    this.updateLimitFields();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Base Element Index View\n */\nCraft.ElementThumbLoader = Garnish.Base.extend(\n  {\n    queue: null,\n    workers: [],\n\n    init: function () {\n      this.queue = [];\n\n      for (var i = 0; i < 3; i++) {\n        this.workers.push(new Craft.ElementThumbLoader.Worker(this));\n      }\n    },\n\n    load: function ($elements) {\n      // Only immediately load the visible images\n      let $thumbs = $elements.find('.elementthumb');\n      for (let i = 0; i < $thumbs.length; i++) {\n        let $thumb = $thumbs.eq(i);\n        let $scrollParent = $thumb.scrollParent();\n        if ($scrollParent.prop('nodeName') === 'FIELDSET') {\n          $scrollParent = $scrollParent.scrollParent();\n        }\n        if ($scrollParent[0] === document.body) {\n          $scrollParent = Garnish.$doc;\n        }\n        if (this.isVisible($thumb, $scrollParent)) {\n          this.addToQueue($thumb[0]);\n        } else {\n          let key = 'thumb' + Math.floor(Math.random() * 1000000);\n          Craft.ElementThumbLoader.invisibleThumbs[key] = [\n            this,\n            $thumb,\n            $scrollParent,\n          ];\n          $scrollParent.on(\n            `scroll.${key}`,\n            {\n              $thumb: $thumb,\n              $scrollParent: $scrollParent,\n              key: key,\n            },\n            (ev) => {\n              if (this.isVisible(ev.data.$thumb, ev.data.$scrollParent)) {\n                delete Craft.ElementThumbLoader.invisibleThumbs[ev.data.key];\n                $scrollParent.off(`scroll.${ev.data.key}`);\n                this.addToQueue(ev.data.$thumb[0]);\n              }\n            }\n          );\n        }\n      }\n    },\n\n    addToQueue: function (thumb) {\n      this.queue.push(thumb);\n\n      // See if there are any inactive workers\n      for (var i = 0; i < this.workers.length; i++) {\n        if (!this.workers[i].active) {\n          this.workers[i].loadNext();\n        }\n      }\n    },\n\n    isVisible: function ($thumb, $scrollParent) {\n      let thumbOffset = $thumb.offset().top;\n      let scrollParentOffset, scrollParentHeight;\n      if ($scrollParent[0] === document) {\n        scrollParentOffset = $scrollParent.scrollTop();\n        scrollParentHeight = Garnish.$win.height();\n      } else {\n        scrollParentOffset = $scrollParent.offset().top;\n        scrollParentHeight = $scrollParent.height();\n      }\n      return (\n        thumbOffset > scrollParentOffset &&\n        thumbOffset < scrollParentOffset + scrollParentHeight + 1000\n      );\n    },\n\n    destroy: function () {\n      for (var i = 0; i < this.workers.length; i++) {\n        this.workers[i].destroy();\n      }\n\n      this.base();\n    },\n  },\n  {\n    invisibleThumbs: {},\n    retryAll: function () {\n      for (let key in Craft.ElementThumbLoader.invisibleThumbs) {\n        let [queue, $thumb, $scrollParent] =\n          Craft.ElementThumbLoader.invisibleThumbs[key];\n        delete Craft.ElementThumbLoader.invisibleThumbs[key];\n        $scrollParent.off(`scroll.${key}`);\n        queue.load($thumb.parent());\n      }\n    },\n  }\n);\n\nCraft.ElementThumbLoader.Worker = Garnish.Base.extend({\n  loader: null,\n  active: false,\n\n  init: function (loader) {\n    this.loader = loader;\n  },\n\n  loadNext: function () {\n    var container = this.loader.queue.shift();\n    if (typeof container === 'undefined') {\n      this.active = false;\n      return;\n    }\n\n    this.active = true;\n    var $container = $(container);\n    if ($container.find('img').length) {\n      this.loadNext();\n      return;\n    }\n    var $img = $('<img/>', {\n      sizes: $container.attr('data-sizes'),\n      srcset: $container.attr('data-srcset'),\n      alt: $container.attr('data-alt') || '',\n    });\n    this.addListener($img, 'load,error', 'loadNext');\n    $img.appendTo($container);\n    picturefill({\n      elements: [$img[0]],\n    });\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Elevated Session Form\n */\nCraft.ElevatedSessionForm = Garnish.Base.extend({\n  $form: null,\n  inputs: null,\n\n  init: function (form, inputs) {\n    this.$form = $(form);\n\n    // Only check specific inputs?\n    if (typeof inputs !== 'undefined') {\n      this.inputs = [];\n      inputs = $.makeArray(inputs);\n\n      for (var i = 0; i < inputs.length; i++) {\n        var $inputs = $(inputs[i]);\n\n        for (var j = 0; j < $inputs.length; j++) {\n          var $input = $inputs.eq(j);\n\n          this.inputs.push({\n            input: $input,\n            val: Garnish.getInputPostVal($input),\n          });\n        }\n      }\n    }\n\n    this.addListener(this.$form, 'submit', 'handleFormSubmit');\n  },\n\n  handleFormSubmit: function (ev) {\n    // Ignore if we're in the middle of getting the elevated session timeout\n    if (Craft.elevatedSessionManager.fetchingTimeout) {\n      ev.preventDefault();\n      ev.stopImmediatePropagation();\n      return;\n    }\n\n    // Are we only interested in certain inputs?\n    if (this.inputs) {\n      var inputsChanged = false;\n      var $input;\n\n      for (var i = 0; i < this.inputs.length; i++) {\n        $input = this.inputs[i].input;\n        // Is this a password input?\n        if ($input.data('passwordInput')) {\n          $input = $input.data('passwordInput').$currentInput;\n        }\n\n        // Has this input's value changed?\n        if (Garnish.getInputPostVal($input) !== this.inputs[i].val) {\n          inputsChanged = true;\n          break;\n        }\n      }\n\n      if (!inputsChanged) {\n        // No need to interrupt the submit\n        return;\n      }\n    }\n\n    // Prevent the form from submitting until the user has an elevated session\n    ev.preventDefault();\n    ev.stopImmediatePropagation();\n    Craft.elevatedSessionManager.requireElevatedSession(\n      this.submitForm.bind(this)\n    );\n  },\n\n  submitForm: function () {\n    // Don't let handleFormSubmit() interrupt this time\n    this.disable();\n    this.$form.trigger('submit');\n    this.enable();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Elevated Session Manager\n */\nCraft.ElevatedSessionManager = Garnish.Base.extend(\n  {\n    fetchingTimeout: false,\n\n    passwordModal: null,\n    $passwordInput: null,\n    $submitBtn: null,\n    $errorPara: null,\n\n    callback: null,\n\n    /**\n     * @callback requireElevatedSessionCallback\n     */\n    /**\n     * Requires that the user has an elevated session.\n     *\n     * @param {requireElevatedSessionCallback} callback The callback function that should be called once the user has an elevated session\n     */\n    requireElevatedSession: function (callback) {\n      this.callback = callback;\n\n      // Check the time remaining on the user’s elevated session (if any)\n      this.fetchingTimeout = true;\n\n      Craft.sendActionRequest('POST', 'users/get-elevated-session-timeout')\n        .then((response) => {\n          this.fetchingTimeout = false;\n          if (\n            response.data.timeout === false ||\n            response.data.timeout >=\n              Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout\n          ) {\n            this.callback();\n          } else {\n            // Show the password modal\n            this.showPasswordModal();\n          }\n        })\n        .catch(() => {\n          this.fetchingTimeout = false;\n        });\n    },\n\n    showPasswordModal: function () {\n      if (!this.passwordModal) {\n        var $passwordModal = $(\n            '<form id=\"elevatedsessionmodal\" class=\"modal secure fitted\"/>'\n          ),\n          $body = $(\n            '<div class=\"body\"><p>' +\n              Craft.t('app', 'Enter your password to continue.') +\n              '</p></div>'\n          ).appendTo($passwordModal),\n          $inputContainer = $('<div class=\"inputcontainer\">').appendTo($body),\n          $inputsFlexContainer = $('<div class=\"flex\"/>').appendTo(\n            $inputContainer\n          ),\n          $passwordContainer = $('<div class=\"flex-grow\"/>').appendTo(\n            $inputsFlexContainer\n          ),\n          $buttonContainer = $('<td/>').appendTo($inputsFlexContainer),\n          $passwordWrapper = $('<div class=\"passwordwrapper\"/>').appendTo(\n            $passwordContainer\n          );\n\n        this.$passwordInput = $(\n          '<input type=\"password\" class=\"text password fullwidth\" placeholder=\"' +\n            Craft.t('app', 'Password') +\n            '\" autocomplete=\"current-password\"/>'\n        ).appendTo($passwordWrapper);\n        this.$submitBtn = Craft.ui\n          .createSubmitButton({\n            class: 'disabled',\n            label: Craft.t('app', 'Submit'),\n            spinner: true,\n          })\n          .appendTo($buttonContainer);\n        this.$errorPara = $('<p class=\"error\"/>').appendTo($body);\n\n        this.passwordModal = new Garnish.Modal($passwordModal, {\n          closeOtherModals: false,\n          onFadeIn: () => {\n            setTimeout(this.focusPasswordInput.bind(this), 100);\n          },\n          onFadeOut: () => {\n            this.$passwordInput.val('');\n          },\n        });\n\n        new Craft.PasswordInput(this.$passwordInput, {\n          onToggleInput: ($newPasswordInput) => {\n            this.$passwordInput = $newPasswordInput;\n          },\n        });\n\n        this.addListener(this.$passwordInput, 'input', 'validatePassword');\n        this.addListener($passwordModal, 'submit', 'submitPassword');\n      } else {\n        this.passwordModal.show();\n      }\n    },\n\n    focusPasswordInput: function () {\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$passwordInput.trigger('focus');\n      }\n    },\n\n    validatePassword: function () {\n      if (this.$passwordInput.val().length >= 6) {\n        this.$submitBtn.removeClass('disabled');\n        return true;\n      } else {\n        this.$submitBtn.addClass('disabled');\n        return false;\n      }\n    },\n\n    submitPassword: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      if (!this.validatePassword()) {\n        return;\n      }\n\n      this.$submitBtn.addClass('loading');\n      this.clearLoginError();\n\n      var data = {\n        currentPassword: this.$passwordInput.val(),\n      };\n\n      Craft.sendActionRequest('POST', 'users/start-elevated-session', {data})\n        .then((response) => {\n          this.$submitBtn.removeClass('loading');\n          this.passwordModal.hide();\n          this.callback();\n        })\n        .catch(({response}) => {\n          this.$submitBtn.removeClass('loading');\n          this.showPasswordError(\n            response.data.message || Craft.t('app', 'Incorrect password.')\n          );\n          Garnish.shake(this.passwordModal.$container);\n          this.focusPasswordInput();\n        });\n    },\n\n    showPasswordError: function (error) {\n      if (error === null || typeof error === 'undefined') {\n        error = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.$errorPara.text(error);\n      this.passwordModal.updateSizeAndPosition();\n    },\n\n    clearLoginError: function () {\n      this.showPasswordError('');\n    },\n  },\n  {\n    minSafeElevatedSessionTimeout: 5,\n  }\n);\n\n// Instantiate it\nCraft.elevatedSessionManager = new Craft.ElevatedSessionManager();\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Entry index class\n */\nCraft.EntryIndex = Craft.BaseElementIndex.extend({\n  publishableSections: null,\n  $newEntryBtnGroup: null,\n  $newEntryBtn: null,\n\n  init: function (elementType, $container, settings) {\n    this.publishableSections = [];\n    this.on('selectSource', this.updateButton.bind(this));\n    this.on('selectSite', this.updateButton.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  afterInit: function () {\n    // Find which of the visible sections the user has permission to create new entries in\n    this.publishableSections = Craft.publishableSections.filter(\n      (s) => !!this.getSourceByKey(`section:${s.uid}`)\n    );\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific section in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultSectionHandle !== 'undefined'\n    ) {\n      if (defaultSectionHandle === 'singles') {\n        return 'singles';\n      }\n\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = $(this.$sources[i]);\n        if ($source.data('handle') === defaultSectionHandle) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateButton: function () {\n    if (!this.$source) {\n      return;\n    }\n\n    let handle;\n\n    // Get the handle of the selected source\n    if (this.$source.data('key') === 'singles') {\n      handle = 'singles';\n    } else {\n      handle = this.$source.data('handle');\n    }\n\n    // Update the New Entry button\n    // ---------------------------------------------------------------------\n\n    if (this.publishableSections.length) {\n      // Remove the old button, if there is one\n      if (this.$newEntryBtnGroup) {\n        this.$newEntryBtnGroup.remove();\n      }\n\n      // Determine if they are viewing a section that they have permission to create entries in\n      const selectedSection = this.publishableSections.find(\n        (s) => s.handle === handle\n      );\n\n      this.$newEntryBtnGroup = $('<div class=\"btngroup submit\" data-wrapper/>');\n      let $menuBtn;\n      const menuId = 'new-entry-menu-' + Craft.randomString(10);\n\n      // If they are, show a primary \"New entry\" button, and a dropdown of the other sections (if any).\n      // Otherwise only show a menu button\n      if (selectedSection) {\n        const visibleLabel =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New entry')\n            : Craft.t('app', 'New {section} entry', {\n                section: selectedSection.name,\n              });\n\n        const ariaLabel =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New entry in the {section} section', {\n                section: selectedSection.name,\n              })\n            : visibleLabel;\n\n        // In index contexts, the button functions as a link\n        // In non-index contexts, the button triggers a slideout editor\n        const role = this.settings.context === 'index' ? 'link' : null;\n\n        this.$newEntryBtn = Craft.ui\n          .createButton({\n            label: visibleLabel,\n            ariaLabel: ariaLabel,\n            spinner: true,\n            role: role,\n          })\n          .addClass('submit add icon')\n          .appendTo(this.$newEntryBtnGroup);\n\n        this.addListener(this.$newEntryBtn, 'click mousedown', (ev) => {\n          // If this is the element index, check for Ctrl+clicks and middle button clicks\n          if (\n            this.settings.context === 'index' &&\n            ((ev.type === 'click' && Garnish.isCtrlKeyPressed(ev)) ||\n              (ev.type === 'mousedown' && ev.originalEvent.button === 1))\n          ) {\n            window.open(Craft.getUrl(`entries/${selectedSection.handle}/new`));\n          } else if (ev.type === 'click') {\n            this._createEntry(selectedSection.id);\n          }\n        });\n\n        if (this.publishableSections.length > 1) {\n          $menuBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn submit menubtn btngroup-btn-last',\n            'aria-controls': menuId,\n            'data-disclosure-trigger': '',\n            'aria-label': Craft.t('app', 'New entry, choose a section'),\n          }).appendTo(this.$newEntryBtnGroup);\n        }\n      } else {\n        this.$newEntryBtn = $menuBtn = Craft.ui\n          .createButton({\n            label: Craft.t('app', 'New entry'),\n            ariaLabel: Craft.t('app', 'New entry, choose a section'),\n            spinner: true,\n          })\n          .addClass('submit add icon menubtn btngroup-btn-last')\n          .attr('aria-controls', menuId)\n          .attr('data-disclosure-trigger', '')\n          .appendTo(this.$newEntryBtnGroup);\n      }\n\n      this.addButton(this.$newEntryBtnGroup);\n\n      if ($menuBtn) {\n        const $menuContainer = $('<div/>', {\n          id: menuId,\n          class: 'menu menu--disclosure',\n        }).appendTo(this.$newEntryBtnGroup);\n        const $ul = $('<ul/>').appendTo($menuContainer);\n\n        for (const section of this.publishableSections) {\n          const anchorRole =\n            this.settings.context === 'index' ? 'link' : 'button';\n          if (\n            (this.settings.context === 'index' &&\n              $.inArray(this.siteId, section.sites) !== -1) ||\n            (this.settings.context !== 'index' && section !== selectedSection)\n          ) {\n            const $li = $('<li/>').appendTo($ul);\n            const $a = $('<a/>', {\n              role: anchorRole === 'button' ? 'button' : null,\n              href: '#', // Allows for click listener and tab order\n              type: anchorRole === 'button' ? 'button' : null,\n              text: Craft.t('app', 'New {section} entry', {\n                section: section.name,\n              }),\n            }).appendTo($li);\n            this.addListener($a, 'click', () => {\n              $menuBtn.data('trigger').hide();\n              this._createEntry(section.id);\n            });\n\n            if (anchorRole === 'button') {\n              this.addListener($a, 'keydown', (event) => {\n                if (event.keyCode === Garnish.SPACE_KEY) {\n                  event.preventDefault();\n                  $menuBtn.data('trigger').hide();\n                  this._createEntry(section.id);\n                }\n              });\n            }\n          }\n        }\n\n        new Garnish.DisclosureMenu($menuBtn);\n      }\n    }\n\n    // Update the URL if we're on the Entries index\n    // ---------------------------------------------------------------------\n\n    if (this.settings.context === 'index') {\n      let uri = 'entries';\n\n      if (handle) {\n        uri += '/' + handle;\n      }\n\n      Craft.setPath(uri);\n    }\n  },\n\n  _createEntry: function (sectionId) {\n    if (this.$newEntryBtn.hasClass('loading')) {\n      console.warn('New entry creation already in progress.');\n      return;\n    }\n\n    // Find the section\n    const section = this.publishableSections.find((s) => s.id === sectionId);\n\n    if (!section) {\n      throw `Invalid section ID: ${sectionId}`;\n    }\n\n    this.$newEntryBtn.addClass('loading');\n\n    Craft.sendActionRequest('POST', 'entries/create', {\n      data: {\n        siteId: this.siteId,\n        section: section.handle,\n      },\n    })\n      .then(({data}) => {\n        if (this.settings.context === 'index') {\n          document.location.href = Craft.getUrl(data.cpEditUrl, {fresh: 1});\n        } else {\n          const slideout = Craft.createElementEditor(this.elementType, {\n            siteId: this.siteId,\n            elementId: data.entry.id,\n            draftId: data.entry.draftId,\n            params: {\n              fresh: 1,\n            },\n          });\n          slideout.on('submit', () => {\n            // Make sure the right section is selected\n            const sectionSourceKey = `section:${section.uid}`;\n\n            if (this.sourceKey !== sectionSourceKey) {\n              this.selectSourceByKey(sectionSourceKey);\n            }\n\n            this.clearSearch();\n            this.setSelectedSortAttribute('dateCreated', 'desc');\n            this.selectElementAfterUpdate(data.entry.id);\n            this.updateElements();\n          });\n        }\n      })\n      .finally(() => {\n        this.$newEntryBtn.removeClass('loading');\n      });\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\Entry', Craft.EntryIndex);\n","/** global: Craft */\n/** global: Garnish */\nCraft.FieldLayoutDesigner = Garnish.Base.extend(\n  {\n    $container: null,\n    $configInput: null,\n    $tabContainer: null,\n    $newTabBtn: null,\n    $sidebar: null,\n    $libraryToggle: null,\n    $selectedLibrary: null,\n    $fieldLibrary: null,\n    $uiLibrary: null,\n    $uiLibraryElements: null,\n    $fieldSearch: null,\n    $clearFieldSearchBtn: null,\n    $fieldGroups: null,\n    $fields: null,\n\n    tabGrid: null,\n    elementDrag: null,\n\n    _config: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.FieldLayoutDesigner.defaults);\n\n      this.$configInput = this.$container.children('input[data-config-input]');\n      this._config = JSON.parse(this.$configInput.val());\n      if (!this._config.tabs) {\n        this._config.tabs = [];\n      }\n\n      let $workspace = this.$container.children('.fld-workspace');\n      this.$tabContainer = $workspace.children('.fld-tabs');\n      this.$newTabBtn = $workspace.children('.fld-new-tab-btn');\n      this.$sidebar = this.$container.children('.fld-sidebar');\n\n      this.$fieldLibrary = this.$selectedLibrary =\n        this.$sidebar.children('.fld-field-library');\n      let $fieldSearchContainer = this.$fieldLibrary.children('.search');\n      this.$fieldSearch = $fieldSearchContainer.children('input');\n      this.$clearFieldSearchBtn = $fieldSearchContainer.children('.clear');\n      this.$fieldGroups = this.$sidebar.find('.fld-field-group');\n      this.$fields = this.$fieldGroups.children('.fld-element');\n      this.$uiLibrary = this.$sidebar.children('.fld-ui-library');\n      this.$uiLibraryElements = this.$uiLibrary.children();\n\n      // Set up the layout grids\n      this.tabGrid = new Craft.Grid(this.$tabContainer, {\n        itemSelector: '.fld-tab',\n        minColWidth: 24 * 11,\n        fillMode: 'grid',\n        snapToGrid: 24,\n      });\n\n      let $tabs = this.$tabContainer.children();\n      for (let i = 0; i < $tabs.length; i++) {\n        this.initTab($($tabs[i]));\n      }\n\n      this.elementDrag = new Craft.FieldLayoutDesigner.ElementDrag(this);\n\n      if (this.settings.customizableTabs) {\n        this.tabDrag = new Craft.FieldLayoutDesigner.TabDrag(this);\n\n        this.addListener(this.$newTabBtn, 'activate', 'addTab');\n      }\n\n      // Set up the sidebar\n      if (this.settings.customizableUi) {\n        let $libraryPicker = this.$sidebar.children('.btngroup');\n        new Craft.Listbox($libraryPicker, {\n          onChange: ($selectedOption) => {\n            this.$selectedLibrary.addClass('hidden');\n            this.$selectedLibrary =\n              this[`$${$selectedOption.data('library')}Library`].removeClass(\n                'hidden'\n              );\n          },\n        });\n      }\n\n      this.addListener(this.$fieldSearch, 'input', () => {\n        let val = this.$fieldSearch.val().toLowerCase().replace(/['\"]/g, '');\n        if (!val) {\n          this.$fieldLibrary.find('.filtered').removeClass('filtered');\n          this.$clearFieldSearchBtn.addClass('hidden');\n          return;\n        }\n\n        this.$clearFieldSearchBtn.removeClass('hidden');\n        let $matches = this.$fields\n          .filter(`[data-keywords*=\"${val}\"]`)\n          .add(\n            this.$fieldGroups\n              .filter(`[data-name*=\"${val}\"]`)\n              .children('.fld-element')\n          )\n          .removeClass('filtered');\n        this.$fields.not($matches).addClass('filtered');\n\n        // hide any groups that don't have any results\n        for (let i = 0; i < this.$fieldGroups.length; i++) {\n          let $group = this.$fieldGroups.eq(i);\n          if ($group.find('.fld-element:not(.hidden):not(.filtered)').length) {\n            $group.removeClass('filtered');\n          } else {\n            $group.addClass('filtered');\n          }\n        }\n      });\n\n      this.addListener(this.$fieldSearch, 'keydown', (ev) => {\n        switch (ev.keyCode) {\n          case Garnish.ESC_KEY:\n            this.$fieldSearch.val('').trigger('input');\n            break;\n          case Garnish.RETURN_KEY:\n            // they most likely don't want to submit the form from here\n            ev.preventDefault();\n            break;\n        }\n      });\n\n      // Clear the search when the X button is clicked\n      this.addListener(this.$clearFieldSearchBtn, 'click', () => {\n        this.$fieldSearch.val('').trigger('input');\n      });\n    },\n\n    initTab: function ($tab) {\n      return new Craft.FieldLayoutDesigner.Tab(this, $tab);\n    },\n\n    removeFieldByHandle: function (attribute) {\n      this.$fields\n        .filter(`[data-attribute=\"${attribute}\"]:first`)\n        .removeClass('hidden')\n        .closest('.fld-field-group')\n        .removeClass('hidden');\n    },\n\n    addTab: function () {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      const name = Craft.escapeHtml(\n        prompt(Craft.t('app', 'Give your tab a name.'))\n      );\n\n      if (!name) {\n        return;\n      }\n\n      const $tab = $(`\n<div class=\"fld-tab\">\n  <div class=\"tabs\">\n    <div class=\"tab sel draggable\">\n      <span>${name}</span>\n      <a class=\"settings icon\" title=\"${Craft.t('app', 'Settings')}\"></a>\n    </div>\n  </div>\n  <div class=\"fld-tabcontent\"></div>\n</div>\n`).appendTo(this.$tabContainer);\n\n      this.tabGrid.addItems($tab);\n      this.tabDrag.addItems($tab);\n\n      const tab = this.initTab($tab);\n      tab.updatePositionInConfig();\n    },\n\n    get config() {\n      return this._config;\n    },\n\n    set config(config) {\n      this._config = config;\n      this.$configInput.val(JSON.stringify(config));\n    },\n\n    updateConfig: function (callback) {\n      const config = callback(this.config);\n      if (config !== false) {\n        this.config = config;\n      }\n    },\n  },\n  {\n    defaults: {\n      customizableTabs: true,\n      customizableUi: true,\n    },\n\n    createSlideout: function (contents, js) {\n      const $body = $('<div/>', {class: 'fld-element-settings-body'});\n      $('<div/>', {class: 'fields', html: contents}).appendTo($body);\n      const $footer = $('<div/>', {class: 'fld-element-settings-footer'});\n      $('<div/>', {class: 'flex-grow'}).appendTo($footer);\n      const $cancelBtn = Craft.ui\n        .createButton({\n          label: Craft.t('app', 'Close'),\n          spinner: true,\n        })\n        .appendTo($footer);\n      Craft.ui\n        .createSubmitButton({\n          class: 'secondary',\n          label: Craft.t('app', 'Apply'),\n          spinner: true,\n        })\n        .appendTo($footer);\n      const $contents = $body.add($footer);\n\n      const slideout = new Craft.Slideout($contents, {\n        containerElement: 'form',\n        containerAttributes: {\n          action: '',\n          method: 'post',\n          novalidate: '',\n          class: 'fld-element-settings',\n        },\n      });\n      slideout.on('open', () => {\n        // Hold off a sec until it's positioned...\n        Garnish.requestAnimationFrame(() => {\n          // Focus on the first text input\n          slideout.$container.find('.text:first').trigger('focus');\n        });\n      });\n\n      $cancelBtn.on('click', () => {\n        slideout.close();\n      });\n\n      if (js) {\n        eval(js);\n      }\n\n      Craft.initUiElements(slideout.$container);\n\n      return slideout;\n    },\n  }\n);\n\nCraft.FieldLayoutDesigner.Tab = Garnish.Base.extend({\n  designer: null,\n  uid: null,\n  $container: null,\n  slideout: null,\n  destroyed: false,\n\n  init: function (designer, $container) {\n    this.designer = designer;\n    this.$container = $container;\n    this.$container.data('fld-tab', this);\n    this.uid = this.$container.data('uid');\n\n    // New tab?\n    if (!this.uid) {\n      this.uid = Craft.uuid();\n      this.config = {\n        uid: this.uid,\n        name: this.$container.find('.tabs .tab span').text(),\n        elements: [],\n      };\n      this.$container.data(\n        'settings-namespace',\n        this.designer.$container\n          .data('new-tab-settings-namespace')\n          .replace(/\\bTAB_UID\\b/g, this.uid)\n      );\n      this.$container.data(\n        'settings-html',\n        this.designer.$container\n          .data('new-tab-settings-html')\n          .replace(/\\bTAB_UID\\b/g, this.uid)\n          .replace(/\\bTAB_NAME\\b/g, this.config.name)\n      );\n      this.$container.data(\n        'settings-js',\n        this.designer.$container\n          .data('new-tab-settings-js')\n          .replace(/\\bTAB_UID\\b/g, this.uid)\n      );\n    }\n\n    if (this.designer.settings.customizableTabs) {\n      this.settingsNamespace = this.$container.data('settings-namespace');\n      this.createMenu();\n    }\n\n    // initialize the elements\n    const $elements = this.$container.children('.fld-tabcontent').children();\n\n    for (let i = 0; i < $elements.length; i++) {\n      this.initElement($($elements[i]));\n    }\n  },\n\n  createMenu: function () {\n    const $editBtn = this.$container.find('.tabs .settings');\n\n    $('<div class=\"menu\" data-align=\"center\"/>')\n      .insertAfter($editBtn)\n      .append(\n        $('<ul/>')\n          .append(\n            $('<li/>').append(\n              $('<a/>', {\n                'data-action': 'settings',\n                text: Craft.t('app', 'Settings'),\n              })\n            )\n          )\n          .append(\n            $('<li/>').append(\n              $('<a/>', {\n                'data-action': 'remove',\n                text: Craft.t('app', 'Remove'),\n              })\n            )\n          )\n      )\n      .append($('<hr/>'))\n      .append(\n        $('<ul/>')\n          .append(\n            $('<li/>').append(\n              $('<a/>', {\n                'data-action': 'moveLeft',\n                text: Craft.t('app', 'Move to the left'),\n              })\n            )\n          )\n          .append(\n            $('<li/>').append(\n              $('<a/>', {\n                'data-action': 'moveRight',\n                text: Craft.t('app', 'Move to the right'),\n              })\n            )\n          )\n      );\n\n    let menuBtn = new Garnish.MenuBtn($editBtn, {\n      onOptionSelect: this.onTabOptionSelect.bind(this),\n    });\n\n    menuBtn.menu.on('show', () => {\n      if (this.$container.prev('.fld-tab').length) {\n        menuBtn.menu.$container\n          .find('[data-action=moveLeft]')\n          .removeClass('disabled');\n      } else {\n        menuBtn.menu.$container\n          .find('[data-action=moveLeft]')\n          .addClass('disabled');\n      }\n\n      if (this.$container.next('.fld-tab').length) {\n        menuBtn.menu.$container\n          .find('[data-action=moveRight]')\n          .removeClass('disabled');\n      } else {\n        menuBtn.menu.$container\n          .find('[data-action=moveRight]')\n          .addClass('disabled');\n      }\n    });\n  },\n\n  onTabOptionSelect: function (option) {\n    if (!this.designer.settings.customizableTabs) {\n      return;\n    }\n\n    let $option = $(option);\n    let action = $option.data('action');\n\n    switch (action) {\n      case 'settings':\n        if (!this.slideout) {\n          this.createSettings();\n        } else {\n          this.slideout.open();\n        }\n        break;\n      case 'remove':\n        this.destroy();\n        break;\n      case 'moveLeft':\n        let $prev = this.$container.prev('.fld-tab');\n        if ($prev.length) {\n          this.$container.insertBefore($prev);\n          this.updatePositionInConfig();\n        }\n        break;\n      case 'moveRight':\n        let $next = this.$container.next('.fld-tab');\n        if ($next.length) {\n          this.$container.insertAfter($next);\n          this.updatePositionInConfig();\n        }\n        break;\n    }\n  },\n\n  createSettings: function () {\n    const settingsHtml = this.$container.data('settings-html');\n    const settingsJs = this.$container.data('settings-js');\n    this.slideout = Craft.FieldLayoutDesigner.createSlideout(\n      settingsHtml,\n      settingsJs\n    );\n\n    this.slideout.$container.on('submit', (ev) => {\n      ev.preventDefault();\n      this.applySettings();\n    });\n  },\n\n  applySettings: function () {\n    if (!this.slideout.$container.find('[name$=\"[name]\"]').val()) {\n      Craft.cp.displayError(Craft.t('app', 'You must specify a tab name.'));\n      return;\n    }\n\n    // update the UI\n    let $submitBtn = this.slideout.$container\n      .find('button[type=submit]')\n      .addClass('loading');\n\n    const config = $.extend({}, this.config);\n    delete config.elements;\n\n    Craft.sendActionRequest('POST', 'fields/apply-layout-tab-settings', {\n      data: {\n        config: config,\n        settingsNamespace: this.settingsNamespace,\n        settings: this.slideout.$container.serialize(),\n      },\n    })\n      .then((response) => {\n        this.updateConfig((config) =>\n          $.extend(response.data.config, {elements: config.elements})\n        );\n        const $label = this.$container.find('.tabs .tab span');\n        const $indicator = $label.children('.fld-indicator');\n        if (response.data.hasConditions) {\n          if (!$indicator.length) {\n            $label.append(\n              $('<div/>', {\n                class: 'fld-indicator',\n                title: Craft.t('app', 'This tab is conditional'),\n                'aria-label': Craft.t('app', 'This tab is conditional'),\n                'data-icon': 'condition',\n                role: 'img',\n              })\n            );\n          }\n        } else if ($indicator.length) {\n          $indicator.remove();\n        }\n        this.slideout.close();\n      })\n      .catch((e) => {\n        Craft.cp.displayError();\n        console.error(e);\n      })\n      .finally(() => {\n        $submitBtn.removeClass('loading');\n        this.slideout.close();\n      });\n  },\n\n  initElement: function ($element) {\n    return new Craft.FieldLayoutDesigner.Element(this, $element);\n  },\n\n  get index() {\n    return this.designer.config.tabs.findIndex((c) => c.uid === this.uid);\n  },\n\n  get config() {\n    if (!this.uid) {\n      throw 'Tab is missing its UID';\n    }\n    let config = this.designer.config.tabs.find((c) => c.uid === this.uid);\n    if (!config) {\n      config = {\n        uid: this.uid,\n        elements: [],\n      };\n      this.config = config;\n    }\n    return config;\n  },\n\n  set config(config) {\n    if (this.destroyed) {\n      return;\n    }\n\n    // Is the name changing?\n    if (config.name && config.name !== this.config.name) {\n      this.$container.find('.tabs .tab span').text(config.name);\n    }\n\n    const designerConfig = this.designer.config;\n    const index = this.index;\n    if (index !== -1) {\n      designerConfig.tabs[index] = config;\n    } else {\n      const newIndex = $.inArray(\n        this.$container[0],\n        this.$container.parent().children('.fld-tab')\n      );\n      designerConfig.tabs.splice(newIndex, 0, config);\n    }\n    this.designer.config = designerConfig;\n  },\n\n  updateConfig: function (callback) {\n    if (this.destroyed) {\n      return;\n    }\n\n    const config = callback(this.config);\n    if (config !== false) {\n      this.config = config;\n    }\n  },\n\n  updatePositionInConfig: function () {\n    if (this.destroyed) {\n      return;\n    }\n\n    this.designer.updateConfig((config) => {\n      const tabConfig = this.config;\n      const oldIndex = this.index;\n      const newIndex = $.inArray(\n        this.$container[0],\n        this.$container.parent().children('.fld-tab')\n      );\n      if (oldIndex !== -1) {\n        config.tabs.splice(oldIndex, 1);\n      }\n      config.tabs.splice(newIndex, 0, tabConfig);\n      return config;\n    });\n  },\n\n  destroy: function () {\n    if (this.destroyed) {\n      return;\n    }\n\n    this.destroyed = true;\n\n    this.designer.updateConfig((config) => {\n      const index = this.index;\n      if (index === -1) {\n        return false;\n      }\n      config.tabs.splice(index, 1);\n      return config;\n    });\n\n    // First destroy the tab's elements\n    let $elements = this.$container.find('.fld-element');\n    for (let i = 0; i < $elements.length; i++) {\n      $elements.eq(i).data('fld-element').destroy();\n    }\n\n    this.designer.tabGrid.removeItems(this.$container);\n    this.designer.tabDrag.removeItems(this.$container);\n    this.$container.remove();\n\n    this.base();\n  },\n});\n\nCraft.FieldLayoutDesigner.Element = Garnish.Base.extend({\n  tab: null,\n  $container: null,\n  $settingsContainer: null,\n  $editBtn: null,\n\n  uid: null,\n  isField: false,\n  attribute: null,\n  requirable: false,\n  hasCustomWidth: false,\n  hasSettings: false,\n  settingsNamespace: null,\n  slideout: null,\n\n  init: function (tab, $container) {\n    this.tab = tab;\n    this.$container = $container;\n    this.$container.data('fld-element', this);\n    this.uid = this.$container.data('uid');\n\n    // New element?\n    if (!this.uid) {\n      this.uid = Craft.uuid();\n      this.config = $.extend(this.$container.data('config'), {uid: this.uid});\n    }\n\n    this.isField = this.$container.hasClass('fld-field');\n    this.requirable =\n      this.isField && Garnish.hasAttr(this.$container, 'data-requirable');\n\n    if (this.isField) {\n      this.attribute = this.$container.data('attribute');\n    }\n\n    this.settingsNamespace = this.$container\n      .data('settings-namespace')\n      .replace(/\\bELEMENT_UID\\b/g, this.uid);\n    let settingsHtml = (this.$container.data('settings-html') || '').replace(\n      /\\bELEMENT_UID\\b/g,\n      this.uid\n    );\n    let isRequired =\n      this.requirable && this.$container.hasClass('fld-required');\n    this.hasCustomWidth =\n      this.tab.designer.settings.customizableUi &&\n      Garnish.hasAttr(this.$container, 'data-has-custom-width');\n    this.hasSettings = settingsHtml || this.requirable;\n\n    if (this.hasSettings) {\n      // create the setting container\n      this.$settingsContainer = $('<div/>', {\n        class: 'hidden',\n      });\n\n      // create the edit button\n      this.$editBtn = $('<a/>', {\n        role: 'button',\n        tabindex: 0,\n        class: 'settings icon',\n        title: Craft.t('app', 'Edit'),\n      });\n\n      const showSettings = () => {\n        if (!this.slideout) {\n          this.createSettings(settingsHtml, isRequired);\n        } else {\n          this.slideout.open();\n        }\n      };\n\n      this.$editBtn.on('click', showSettings);\n      this.$container.on('dblclick', showSettings);\n    }\n\n    this.initUi();\n\n    // cleanup\n    this.$container.attr('data-keywords', null);\n    this.$container.attr('data-settings-html', null);\n  },\n\n  initUi: function () {\n    if (this.hasCustomWidth) {\n      let widthSlider = new Craft.SlidePicker(this.config.width || 100, {\n        min: 25,\n        max: 100,\n        step: 25,\n        valueLabel: (width) => {\n          return Craft.t('app', '{pct} width', {pct: `${width}%`});\n        },\n        onChange: (width) => {\n          this.updateConfig((config) => {\n            config.width = width;\n            return config;\n          });\n        },\n      });\n      widthSlider.$container.appendTo(this.$container);\n    }\n\n    if (this.hasSettings) {\n      this.$editBtn.appendTo(this.$container);\n    }\n  },\n\n  createSettings: function (settingsHtml, isRequired) {\n    const settingsJs = (this.$container.data('settings-js') || '').replace(\n      /\\bELEMENT_UID\\b/g,\n      this.uid\n    );\n    this.slideout = Craft.FieldLayoutDesigner.createSlideout(\n      settingsHtml,\n      settingsJs\n    );\n\n    this.slideout.$container.on('submit', (ev) => {\n      ev.preventDefault();\n      this.applySettings();\n    });\n\n    if (this.requirable) {\n      const $fieldsContainer = this.slideout.$container.find('.fields:first');\n      Craft.ui\n        .createLightswitchField({\n          label: Craft.t('app', 'Required'),\n          name: `${this.settingsNamespace}[required]`,\n          on: isRequired,\n        })\n        .prependTo($fieldsContainer);\n    }\n\n    this.trigger('createSettings');\n  },\n\n  applySettings: function () {\n    // update the UI\n    let $submitBtn = this.slideout.$container\n      .find('button[type=submit]')\n      .addClass('loading');\n\n    Craft.sendActionRequest('POST', 'fields/apply-layout-element-settings', {\n      data: {\n        config: this.config,\n        settingsNamespace: this.settingsNamespace,\n        settings: this.slideout.$container.serialize(),\n      },\n    })\n      .then((response) => {\n        this.config = response.data.config;\n        this.$editBtn.detach();\n        this.$container.html($(response.data.selectorHtml).html());\n        this.initUi();\n      })\n      .catch((e) => {\n        Craft.cp.displayError();\n        console.error(e);\n      })\n      .finally(() => {\n        $submitBtn.removeClass('loading');\n        this.updateRequiredClass();\n        this.slideout.close();\n      });\n  },\n\n  updateRequiredClass: function () {\n    if (!this.requirable) {\n      return;\n    }\n\n    if (this.config.required) {\n      this.$container.addClass('fld-required');\n    } else {\n      this.$container.removeClass('fld-required');\n    }\n  },\n\n  get index() {\n    const tabConfig = this.tab.config;\n    if (typeof tabConfig === 'undefined') {\n      return -1;\n    }\n    return tabConfig.elements.findIndex((c) => c.uid === this.uid);\n  },\n\n  get config() {\n    if (!this.uid) {\n      throw 'Tab is missing its UID';\n    }\n    let config = this.tab.config.elements.find((c) => c.uid === this.uid);\n    if (!config) {\n      config = {\n        uid: this.uid,\n      };\n      this.config = config;\n    }\n    return config;\n  },\n\n  set config(config) {\n    const tabConfig = this.tab.config;\n    const index = this.index;\n    if (index !== -1) {\n      tabConfig.elements[index] = config;\n    } else {\n      const newIndex = $.inArray(\n        this.$container[0],\n        this.$container.parent().children('.fld-element')\n      );\n      tabConfig.elements.splice(newIndex, 0, config);\n    }\n    this.tab.config = tabConfig;\n  },\n\n  updateConfig: function (callback) {\n    const config = callback(this.config);\n    if (config !== false) {\n      this.config = config;\n    }\n  },\n\n  updatePositionInConfig: function () {\n    this.tab.updateConfig((config) => {\n      const elementConfig = this.config;\n      const oldIndex = this.index;\n      const newIndex = $.inArray(\n        this.$container[0],\n        this.$container.parent().children('.fld-element')\n      );\n      if (oldIndex !== -1) {\n        config.elements.splice(oldIndex, 1);\n      }\n      config.elements.splice(newIndex, 0, elementConfig);\n      return config;\n    });\n  },\n\n  destroy: function () {\n    this.tab.updateConfig((config) => {\n      const index = this.index;\n      if (index === -1) {\n        return false;\n      }\n      config.elements.splice(index, 1);\n      return config;\n    });\n\n    this.tab.designer.elementDrag.removeItems(this.$container);\n    this.$container.remove();\n\n    if (this.isField) {\n      this.tab.designer.removeFieldByHandle(this.attribute);\n    }\n\n    this.base();\n  },\n});\n\nCraft.FieldLayoutDesigner.BaseDrag = Garnish.Drag.extend({\n  designer: null,\n  $insertion: null,\n  showingInsertion: false,\n  $caboose: null,\n\n  /**\n   * Constructor\n   */\n  init: function (designer, settings) {\n    this.designer = designer;\n    this.base(this.findItems(), settings);\n  },\n\n  /**\n   * On Drag Start\n   */\n  onDragStart: function () {\n    this.base();\n\n    // Create the insertion\n    this.$insertion = this.createInsertion();\n\n    // Add the caboose\n    this.$caboose = this.createCaboose();\n    this.$items = $().add(this.$items.add(this.$caboose));\n\n    Garnish.$bod.addClass('dragging');\n  },\n\n  removeCaboose: function () {\n    this.$items = this.$items.not(this.$caboose);\n    this.$caboose.remove();\n  },\n\n  swapDraggeeWithInsertion: function () {\n    this.$insertion.insertBefore(this.$draggee);\n    this.$draggee.detach();\n    this.$items = $().add(this.$items.not(this.$draggee).add(this.$insertion));\n    this.showingInsertion = true;\n  },\n\n  swapInsertionWithDraggee: function () {\n    this.$insertion.replaceWith(this.$draggee);\n    this.$items = $().add(this.$items.not(this.$insertion).add(this.$draggee));\n    this.showingInsertion = false;\n  },\n\n  /**\n   * Sets the item midpoints up front so we don't have to keep checking on every mouse move\n   */\n  setMidpoints: function () {\n    for (let i = 0; i < this.$items.length; i++) {\n      let $item = $(this.$items[i]);\n      let offset = $item.offset();\n\n      // Skip library elements\n      if ($item.hasClass('unused')) {\n        continue;\n      }\n\n      $item.data('midpoint', {\n        left: offset.left + $item.outerWidth() / 2,\n        top: offset.top + $item.outerHeight() / 2,\n      });\n    }\n  },\n\n  /**\n   * Returns the closest item to the cursor.\n   */\n  getClosestItem: function () {\n    this.getClosestItem._closestItem = null;\n    this.getClosestItem._closestItemMouseDiff = null;\n\n    for (\n      this.getClosestItem._i = 0;\n      this.getClosestItem._i < this.$items.length;\n      this.getClosestItem._i++\n    ) {\n      this.getClosestItem._$item = $(this.$items[this.getClosestItem._i]);\n\n      this.getClosestItem._midpoint =\n        this.getClosestItem._$item.data('midpoint');\n      if (!this.getClosestItem._midpoint) {\n        continue;\n      }\n\n      this.getClosestItem._mouseDiff = Garnish.getDist(\n        this.getClosestItem._midpoint.left,\n        this.getClosestItem._midpoint.top,\n        this.mouseX,\n        this.mouseY\n      );\n\n      if (\n        this.getClosestItem._closestItem === null ||\n        this.getClosestItem._mouseDiff <\n          this.getClosestItem._closestItemMouseDiff\n      ) {\n        this.getClosestItem._closestItem = this.getClosestItem._$item[0];\n        this.getClosestItem._closestItemMouseDiff =\n          this.getClosestItem._mouseDiff;\n      }\n    }\n\n    return this.getClosestItem._closestItem;\n  },\n\n  checkForNewClosestItem: function () {\n    // Is there a new closest item?\n    this.checkForNewClosestItem._closestItem = this.getClosestItem();\n\n    if (this.checkForNewClosestItem._closestItem === this.$insertion[0]) {\n      return;\n    }\n\n    if (\n      this.showingInsertion &&\n      $.inArray(this.$insertion[0], this.$items) <\n        $.inArray(this.checkForNewClosestItem._closestItem, this.$items) &&\n      $.inArray(this.checkForNewClosestItem._closestItem, this.$caboose) === -1\n    ) {\n      this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem);\n    } else {\n      this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem);\n    }\n\n    this.$items = $().add(this.$items.add(this.$insertion));\n    this.showingInsertion = true;\n    this.designer.tabGrid.refreshCols(true);\n    this.setMidpoints();\n  },\n\n  /**\n   * On Drag Stop\n   */\n  onDragStop: function () {\n    if (this.showingInsertion) {\n      this.swapInsertionWithDraggee();\n    }\n\n    this.removeCaboose();\n\n    this.designer.tabGrid.refreshCols(true);\n\n    // return the helpers to the draggees\n    let offset = this.$draggee.offset();\n    if (!offset || (offset.top === 0 && offset.left === 0)) {\n      this.$draggee\n        .css({\n          display: this.draggeeDisplay,\n          visibility: 'visible',\n          opacity: 0,\n        })\n        .velocity({opacity: 1}, Garnish.FX_DURATION);\n      this.helpers[0].velocity({opacity: 0}, Garnish.FX_DURATION, () => {\n        this._showDraggee();\n      });\n    } else {\n      this.returnHelpersToDraggees();\n    }\n\n    this.base();\n\n    Garnish.$bod.removeClass('dragging');\n  },\n});\n\nCraft.FieldLayoutDesigner.TabDrag = Craft.FieldLayoutDesigner.BaseDrag.extend({\n  /**\n   * Constructor\n   */\n  init: function (designer) {\n    let settings = {\n      handle: '.tab',\n    };\n\n    this.base(designer, settings);\n  },\n\n  findItems: function () {\n    return this.designer.$tabContainer.find('> div.fld-tab');\n  },\n\n  /**\n   * On Drag Start\n   */\n  onDragStart: function () {\n    this.base();\n    this.swapDraggeeWithInsertion();\n    this.setMidpoints();\n  },\n\n  swapDraggeeWithInsertion: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$draggee);\n    this.designer.tabGrid.addItems(this.$insertion);\n  },\n\n  swapInsertionWithDraggee: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$insertion);\n    this.designer.tabGrid.addItems(this.$draggee);\n  },\n\n  /**\n   * On Drag\n   */\n  onDrag: function () {\n    this.checkForNewClosestItem();\n    this.base();\n  },\n\n  /**\n   * On Drag Stop\n   */\n  onDragStop: function () {\n    this.base();\n\n    // \"show\" the tab, but make it invisible\n    this.$draggee.css({\n      display: this.draggeeDisplay,\n      visibility: 'hidden',\n    });\n\n    this.$draggee.data('fld-tab').updatePositionInConfig();\n  },\n\n  /**\n   * Creates the caboose\n   */\n  createCaboose: function () {\n    let $caboose = $('<div class=\"fld-tab fld-tab-caboose\"/>').appendTo(\n      this.designer.$tabContainer\n    );\n    this.designer.tabGrid.addItems($caboose);\n    return $caboose;\n  },\n\n  /**\n   * Removes the caboose\n   */\n  removeCaboose: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$caboose);\n  },\n\n  /**\n   * Creates the insertion\n   */\n  createInsertion: function () {\n    let $tab = this.$draggee.find('.tab');\n\n    return $(`\n<div class=\"fld-tab fld-insertion\" style=\"height: ${this.$draggee.height()}px;\">\n  <div class=\"tabs\"><div class=\"tab sel draggable\" style=\"width: ${$tab.outerWidth()}px; height: ${\n      $tab.outerHeight() + 2\n    }px;\"></div></div>\n  <div class=\"fld-tabcontent\" style=\"height: ${\n    this.$draggee.find('.fld-tabcontent').height() - 2\n  }px;\"></div>\n</div>\n`);\n  },\n});\n\nCraft.FieldLayoutDesigner.ElementDrag =\n  Craft.FieldLayoutDesigner.BaseDrag.extend({\n    draggingLibraryElement: false,\n    draggingField: false,\n    originalTab: null,\n\n    /**\n     * On Drag Start\n     */\n    onDragStart: function () {\n      this.base();\n\n      // Are we dragging an element from the library?\n      this.draggingLibraryElement = this.$draggee.hasClass('unused');\n\n      // Is it a field?\n      this.draggingField = this.$draggee.hasClass('fld-field');\n\n      // keep UI elements visible\n      if (this.draggingLibraryElement && !this.draggingField) {\n        this.$draggee.css({\n          display: this.draggeeDisplay,\n          visibility: 'visible',\n        });\n      }\n\n      // Swap the draggee with the insertion if dragging a selected item\n      if (!this.draggingLibraryElement) {\n        this.originalTab = this.$draggee.closest('.fld-tab').data('fld-tab');\n        this.swapDraggeeWithInsertion();\n      } else {\n        this.originalTab = null;\n      }\n\n      this.setMidpoints();\n    },\n\n    /**\n     * On Drag\n     */\n    onDrag: function () {\n      if (this.isDraggeeMandatory() || this.isHoveringOverTab()) {\n        this.checkForNewClosestItem();\n      } else if (this.showingInsertion) {\n        this.$insertion.remove();\n        this.$items = $().add(this.$items.not(this.$insertion));\n        this.showingInsertion = false;\n        this.designer.tabGrid.refreshCols(true);\n        this.setMidpoints();\n      }\n\n      this.base();\n    },\n\n    isDraggeeMandatory: function () {\n      return Garnish.hasAttr(this.$draggee, 'data-mandatory');\n    },\n\n    isHoveringOverTab: function () {\n      for (let i = 0; i < this.designer.tabGrid.$items.length; i++) {\n        if (\n          Garnish.hitTest(\n            this.mouseX,\n            this.mouseY,\n            this.designer.tabGrid.$items.eq(i)\n          )\n        ) {\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    findItems: function () {\n      // Return all of the used + unused fields\n      return this.designer.$tabContainer\n        .find('.fld-element')\n        .add(this.designer.$sidebar.find('.fld-element'));\n    },\n\n    /**\n     * Creates the caboose\n     */\n    createCaboose: function () {\n      let $caboose = $();\n      let $fieldContainers = this.designer.$tabContainer.find(\n        '> .fld-tab > .fld-tabcontent'\n      );\n\n      for (let i = 0; i < $fieldContainers.length; i++) {\n        $caboose = $caboose.add($('<div/>').appendTo($fieldContainers[i]));\n      }\n\n      return $caboose;\n    },\n\n    /**\n     * Creates the insertion\n     */\n    createInsertion: function () {\n      return $(\n        `<div class=\"fld-element fld-insertion\" style=\"height: ${this.$draggee.outerHeight()}px;\"/>`\n      );\n    },\n\n    /**\n     * On Drag Stop\n     */\n    onDragStop: function () {\n      let showingInsertion = this.showingInsertion;\n      if (showingInsertion) {\n        if (this.draggingLibraryElement) {\n          // Create a new element based on that one\n          const $element = this.$draggee.clone().removeClass('unused');\n\n          if (this.draggingField) {\n            // Hide the library field\n            this.$draggee\n              .css({visibility: 'inherit', display: 'field'})\n              .addClass('hidden');\n\n            // Hide the group too?\n            if (\n              this.$draggee.siblings('.fld-field:not(.hidden)').length === 0\n            ) {\n              this.$draggee.closest('.fld-field-group').addClass('hidden');\n            }\n          }\n\n          // Set this.$draggee to the clone, as if we were dragging that all along\n          this.$draggee = $element;\n\n          // Remember it for later\n          this.addItems($element);\n        }\n      } else if (!this.draggingLibraryElement) {\n        let $libraryElement = this.draggingField\n          ? this.designer.$fields.filter(\n              `[data-attribute=\"${this.$draggee.data('attribute')}\"]:first`\n            )\n          : this.designer.$uiLibraryElements.filter(\n              `[data-type=\"${this.$draggee.data('type')}\"]:first`\n            );\n\n        if (this.draggingField) {\n          // show the field in the library\n          $libraryElement.removeClass('hidden');\n          $libraryElement.closest('.fld-field-group').removeClass('hidden');\n        }\n\n        // Destroy the original element\n        this.$draggee.data('fld-element').destroy();\n\n        // Set this.$draggee to the library element, as if we were dragging that all along\n        this.$draggee = $libraryElement;\n      }\n\n      this.base();\n\n      this.$draggee.css({\n        display: this.draggeeDisplay,\n        visibility:\n          this.draggingField || showingInsertion ? 'hidden' : 'visible',\n      });\n\n      if (showingInsertion) {\n        const tab = this.$draggee.closest('.fld-tab').data('fld-tab');\n        let element;\n\n        if (this.draggingLibraryElement) {\n          element = tab.initElement(this.$draggee);\n        } else {\n          element = this.$draggee.data('fld-element');\n\n          // New tab?\n          if (tab !== this.originalTab) {\n            const config = element.config;\n\n            this.originalTab.updateConfig((config) => {\n              const index = element.index;\n              if (index === -1) {\n                return false;\n              }\n              config.elements.splice(index, 1);\n              return config;\n            });\n\n            this.$draggee.data('fld-element').tab = tab;\n            element.config = config;\n          }\n        }\n\n        element.updatePositionInConfig();\n      }\n    },\n  });\n","/** global: Craft */\n/** global: Garnish */\n/**\n * FieldToggle\n */\nCraft.FieldToggle = Garnish.Base.extend({\n  $toggle: null,\n  targetPrefix: null,\n  targetSelector: null,\n  reverseTargetSelector: null,\n\n  _$target: null,\n  _$reverseTarget: null,\n  type: null,\n\n  init: function (toggle) {\n    this.$toggle = $(toggle);\n\n    // Is this already a field toggle?\n    if (this.$toggle.data('fieldtoggle')) {\n      console.warn('Double-instantiating a field toggle on an element');\n      this.$toggle.data('fieldtoggle').destroy();\n    }\n\n    this.$toggle.data('fieldtoggle', this);\n\n    this.type = this.getType();\n\n    if (this.type === 'select' || this.type === 'fieldset') {\n      this.targetPrefix = this.$toggle.attr('data-target-prefix') || '';\n    } else {\n      this.targetSelector = this.normalizeTargetSelector(\n        this.$toggle.data('target')\n      );\n      this.reverseTargetSelector = this.normalizeTargetSelector(\n        this.$toggle.data('reverse-target')\n      );\n    }\n\n    this.findTargets();\n\n    switch (this.type) {\n      case 'link':\n        this.addListener(this.$toggle, 'click', 'onToggleChange');\n        break;\n      case 'fieldset':\n        this.addListener(\n          this.$toggle.find('input'),\n          'change',\n          'onToggleChange'\n        );\n        break;\n      default:\n        this.addListener(this.$toggle, 'change', 'onToggleChange');\n        this.onToggleChange();\n    }\n  },\n\n  normalizeTargetSelector: function (selector) {\n    if (selector && !selector.match(/^[#\\.]/)) {\n      selector = '#' + selector;\n    }\n\n    return selector;\n  },\n\n  getType: function () {\n    let nodeName = this.$toggle.prop('nodeName');\n    if (\n      (nodeName === 'INPUT' && this.$toggle.attr('type') === 'checkbox') ||\n      this.$toggle.attr('role') === 'checkbox' ||\n      this.$toggle.attr('role') === 'switch'\n    ) {\n      return 'checkbox';\n    }\n\n    switch (nodeName) {\n      case 'SELECT':\n        if (Garnish.hasAttr(this.$toggle, 'data-boolean-menu')) {\n          return 'booleanMenu';\n        }\n        return 'select';\n      case 'A':\n        return 'link';\n      default:\n        return 'fieldset';\n    }\n  },\n\n  findTargets: function () {\n    if (this.type === 'select' || this.type === 'fieldset') {\n      var toggleVal = this.getToggleVal();\n      this._$target = $(\n        this.normalizeTargetSelector(this.targetPrefix + this.getToggleVal())\n      );\n    } else {\n      if (this.targetSelector) {\n        this._$target = $(this.targetSelector);\n      }\n\n      if (this.reverseTargetSelector) {\n        this._$reverseTarget = $(this.reverseTargetSelector);\n      }\n    }\n  },\n\n  getToggleVal: function () {\n    switch (this.type) {\n      case 'checkbox':\n        if (typeof this.$toggle.prop('checked') !== 'undefined') {\n          return this.$toggle.prop('checked');\n        }\n        return this.$toggle.attr('aria-checked') === 'true';\n\n      case 'booleanMenu':\n        const boolean = this.$toggle.data('boolean');\n        if (typeof boolean !== 'undefined') {\n          return boolean;\n        }\n        const val = this.$toggle.val();\n        return val && val !== '0';\n\n      default:\n        let postVal;\n        if (this.type === 'fieldset') {\n          postVal = this.$toggle.find('input:checked:first').val();\n        } else {\n          postVal = Garnish.getInputPostVal(this.$toggle);\n        }\n\n        // Normalize the value\n        return typeof postVal === 'undefined' || postVal === null\n          ? null\n          : postVal.replace(/[^\\w]+/g, '-');\n    }\n  },\n\n  onToggleChange: function () {\n    if (this.type === 'select' || this.type === 'fieldset') {\n      this.hideTarget(this._$target);\n      this.findTargets();\n      this.showTarget(this._$target);\n    } else {\n      this.findTargets();\n\n      if (this.type === 'link') {\n        this.onToggleChange._show =\n          this.$toggle.hasClass('collapsed') ||\n          !this.$toggle.hasClass('expanded');\n      } else {\n        this.onToggleChange._show = !!this.getToggleVal();\n      }\n\n      if (this.onToggleChange._show) {\n        this.showTarget(this._$target);\n        this.hideTarget(this._$reverseTarget);\n      } else {\n        this.hideTarget(this._$target);\n        this.showTarget(this._$reverseTarget);\n      }\n\n      delete this.onToggleChange._show;\n    }\n  },\n\n  showTarget: function ($target) {\n    if ($target && $target.length) {\n      this.showTarget._currentHeight = $target.height();\n\n      $target.removeClass('hidden');\n\n      if (this.type !== 'select' && this.type !== 'fieldset') {\n        if (this.type === 'link') {\n          this.$toggle.removeClass('collapsed');\n          this.$toggle.addClass('expanded');\n        }\n\n        for (let i = 0; i < $target.length; i++) {\n          (($t) => {\n            if ($t.prop('nodeName') !== 'SPAN') {\n              $t.height('auto');\n              this.showTarget._targetHeight = $t.height();\n              $t.css({\n                height: this.showTarget._currentHeight,\n                overflow: 'hidden',\n              });\n\n              $t.velocity('stop');\n\n              $t.velocity(\n                {height: this.showTarget._targetHeight},\n                'fast',\n                function () {\n                  $t.css({\n                    height: '',\n                    overflow: '',\n                  });\n                }\n              );\n            }\n          })($target.eq(i));\n        }\n\n        delete this.showTarget._targetHeight;\n      }\n\n      delete this.showTarget._currentHeight;\n\n      // Trigger a resize event in case there are any grids in the target that need to initialize\n      Garnish.$win.trigger('resize');\n    }\n  },\n\n  hideTarget: function ($target) {\n    if ($target && $target.length) {\n      if (this.type === 'select' || this.type === 'fieldset') {\n        $target.addClass('hidden');\n      } else {\n        if (this.type === 'link') {\n          this.$toggle.removeClass('expanded');\n          this.$toggle.addClass('collapsed');\n        }\n\n        for (let i = 0; i < $target.length; i++) {\n          (($t) => {\n            if ($t.hasClass('hidden')) {\n              return;\n            }\n            if ($t.prop('nodeName') === 'SPAN') {\n              $t.addClass('hidden');\n            } else {\n              $t.css('overflow', 'hidden');\n              $t.velocity('stop');\n              $t.velocity({height: 0}, 'fast', function () {\n                $t.addClass('hidden');\n              });\n            }\n          })($target.eq(i));\n        }\n      }\n    }\n  },\n\n  destroy: function () {\n    this.$toggle.removeData('fieldtoggle');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.Grid = Garnish.Base.extend(\n  {\n    $container: null,\n\n    $items: null,\n    items: null,\n    totalCols: null,\n    colGutterDrop: null,\n    colPctWidth: null,\n\n    possibleItemColspans: null,\n    possibleItemPositionsByColspan: null,\n\n    itemPositions: null,\n    itemColspansByPosition: null,\n\n    layouts: null,\n    layout: null,\n    itemHeights: null,\n    leftPadding: null,\n\n    _refreshingCols: false,\n    _refreshColsAfterRefresh: false,\n    _forceRefreshColsAfterRefresh: false,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n\n      // Is this already a grid?\n      if (this.$container.data('grid')) {\n        console.warn('Double-instantiating a grid on an element');\n        this.$container.data('grid').destroy();\n      }\n\n      this.$container.data('grid', this);\n\n      this.setSettings(settings, Craft.Grid.defaults);\n\n      // Set the refreshCols() proxy that container resizes will trigger\n      this.handleContainerHeightProxy = () => {\n        this.refreshCols(false, true);\n      };\n\n      this.$items = this.$container.children(this.settings.itemSelector);\n      this.setItems();\n      this.refreshCols(true, false);\n\n      Garnish.$doc.ready(() => {\n        this.refreshCols(false, false);\n      });\n    },\n\n    addItems: function (items) {\n      this.$items = $().add(this.$items.add(items));\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    removeItems: function (items) {\n      this.$items = $().add(this.$items.not(items));\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    resetItemOrder: function () {\n      this.$items = $().add(this.$items);\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    setItems: function () {\n      this.setItems._ = {};\n\n      this.items = [];\n\n      for (\n        this.setItems._.i = 0;\n        this.setItems._.i < this.$items.length;\n        this.setItems._.i++\n      ) {\n        this.items.push($(this.$items[this.setItems._.i]));\n      }\n\n      delete this.setItems._;\n    },\n\n    refreshCols: function (force) {\n      if (this._refreshingCols) {\n        this._refreshColsAfterRefresh = true;\n        if (force) {\n          this._forceRefreshColsAfterRefresh = true;\n        }\n        return;\n      }\n\n      this._refreshingCols = true;\n\n      if (!this.items.length) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      this.refreshCols._ = {};\n\n      // Check to see if the grid is actually visible\n      this.refreshCols._.oldHeight = this.$container[0].style.height;\n      this.$container[0].style.height = 1;\n      this.refreshCols._.scrollHeight = this.$container[0].scrollHeight;\n      this.$container[0].style.height = this.refreshCols._.oldHeight;\n\n      if (this.refreshCols._.scrollHeight === 0) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      if (this.settings.cols) {\n        this.refreshCols._.totalCols = this.settings.cols;\n      } else {\n        this.refreshCols._.totalCols = Math.floor(\n          this.$container.width() / this.settings.minColWidth\n        );\n\n        // If we're adding a new column, require an extra 20 pixels in case a scrollbar shows up\n        if (\n          this.totalCols !== null &&\n          this.refreshCols._.totalCols > this.totalCols\n        ) {\n          this.refreshCols._.totalCols = Math.floor(\n            (this.$container.width() - 20) / this.settings.minColWidth\n          );\n        }\n\n        if (\n          this.settings.maxCols &&\n          this.refreshCols._.totalCols > this.settings.maxCols\n        ) {\n          this.refreshCols._.totalCols = this.settings.maxCols;\n        }\n      }\n\n      if (this.refreshCols._.totalCols === 0) {\n        this.refreshCols._.totalCols = 1;\n      }\n\n      // Same number of columns as before?\n      if (force !== true && this.totalCols === this.refreshCols._.totalCols) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      this.totalCols = this.refreshCols._.totalCols;\n      this.colGutterDrop =\n        (this.settings.gutter * (this.totalCols - 1)) / this.totalCols;\n\n      // Temporarily stop listening to container resizes\n      this.removeListener(this.$container, 'resize');\n\n      if (this.settings.fillMode === 'grid') {\n        this.refreshCols._.itemIndex = 0;\n\n        while (this.refreshCols._.itemIndex < this.items.length) {\n          // Append the next X items and figure out which one is the tallest\n          this.refreshCols._.tallestItemHeight = -1;\n          this.refreshCols._.colIndex = 0;\n\n          for (\n            this.refreshCols._.i = this.refreshCols._.itemIndex;\n            this.refreshCols._.i <\n              this.refreshCols._.itemIndex + this.totalCols &&\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.itemHeight = this.items[this.refreshCols._.i]\n              .height('auto')\n              .height();\n\n            if (\n              this.refreshCols._.itemHeight >\n              this.refreshCols._.tallestItemHeight\n            ) {\n              this.refreshCols._.tallestItemHeight =\n                this.refreshCols._.itemHeight;\n            }\n\n            this.refreshCols._.colIndex++;\n          }\n\n          if (this.settings.snapToGrid) {\n            this.refreshCols._.remainder =\n              this.refreshCols._.tallestItemHeight % this.settings.snapToGrid;\n\n            if (this.refreshCols._.remainder) {\n              this.refreshCols._.tallestItemHeight +=\n                this.settings.snapToGrid - this.refreshCols._.remainder;\n            }\n          }\n\n          // Now set their heights to the tallest one\n          for (\n            this.refreshCols._.i = this.refreshCols._.itemIndex;\n            this.refreshCols._.i <\n              this.refreshCols._.itemIndex + this.totalCols &&\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.items[this.refreshCols._.i].height(\n              this.refreshCols._.tallestItemHeight\n            );\n          }\n\n          // set the this.refreshCols._.itemIndex pointer to the next one up\n          this.refreshCols._.itemIndex += this.totalCols;\n        }\n      } else {\n        this.removeListener(this.$items, 'resize');\n\n        // If there's only one column, sneak out early\n        if (this.totalCols === 1) {\n          this.$container.height('auto');\n          this.$items\n            .show()\n            .css({\n              position: 'relative',\n              width: 'auto',\n              top: 0,\n            })\n            .css(Craft.left, 0);\n        } else {\n          this.$items.css('position', 'absolute');\n          this.colPctWidth = 100 / this.totalCols;\n\n          // The setup\n\n          this.layouts = [];\n\n          this.itemPositions = [];\n          this.itemColspansByPosition = [];\n\n          // Figure out all of the possible colspans for each item,\n          // as well as all the possible positions for each item at each of its colspans\n\n          this.possibleItemColspans = [];\n          this.possibleItemPositionsByColspan = [];\n          this.itemHeightsByColspan = [];\n\n          for (\n            this.refreshCols._.item = 0;\n            this.refreshCols._.item < this.items.length;\n            this.refreshCols._.item++\n          ) {\n            this.possibleItemColspans[this.refreshCols._.item] = [];\n            this.possibleItemPositionsByColspan[this.refreshCols._.item] = {};\n            this.itemHeightsByColspan[this.refreshCols._.item] = {};\n\n            this.refreshCols._.$item =\n              this.items[this.refreshCols._.item].show();\n            this.refreshCols._.positionRight =\n              this.refreshCols._.$item.data('position') === 'right';\n            this.refreshCols._.positionLeft =\n              this.refreshCols._.$item.data('position') === 'left';\n            this.refreshCols._.minColspan = this.refreshCols._.$item.data(\n              'colspan'\n            )\n              ? this.refreshCols._.$item.data('colspan')\n              : this.refreshCols._.$item.data('min-colspan')\n              ? this.refreshCols._.$item.data('min-colspan')\n              : 1;\n            this.refreshCols._.maxColspan = this.refreshCols._.$item.data(\n              'colspan'\n            )\n              ? this.refreshCols._.$item.data('colspan')\n              : this.refreshCols._.$item.data('max-colspan')\n              ? this.refreshCols._.$item.data('max-colspan')\n              : this.totalCols;\n\n            if (this.refreshCols._.minColspan > this.totalCols) {\n              this.refreshCols._.minColspan = this.totalCols;\n            }\n            if (this.refreshCols._.maxColspan > this.totalCols) {\n              this.refreshCols._.maxColspan = this.totalCols;\n            }\n\n            for (\n              this.refreshCols._.colspan = this.refreshCols._.minColspan;\n              this.refreshCols._.colspan <= this.refreshCols._.maxColspan;\n              this.refreshCols._.colspan++\n            ) {\n              // Get the height for this colspan\n              this.refreshCols._.$item.css(\n                'width',\n                this.getItemWidthCss(this.refreshCols._.colspan)\n              );\n              this.itemHeightsByColspan[this.refreshCols._.item][\n                this.refreshCols._.colspan\n              ] = this.refreshCols._.$item.outerHeight();\n\n              this.possibleItemColspans[this.refreshCols._.item].push(\n                this.refreshCols._.colspan\n              );\n              this.possibleItemPositionsByColspan[this.refreshCols._.item][\n                this.refreshCols._.colspan\n              ] = [];\n\n              if (this.refreshCols._.positionLeft) {\n                this.refreshCols._.minPosition = 0;\n                this.refreshCols._.maxPosition = 0;\n              } else if (this.refreshCols._.positionRight) {\n                this.refreshCols._.minPosition =\n                  this.totalCols - this.refreshCols._.colspan;\n                this.refreshCols._.maxPosition = this.refreshCols._.minPosition;\n              } else {\n                this.refreshCols._.minPosition = 0;\n                this.refreshCols._.maxPosition =\n                  this.totalCols - this.refreshCols._.colspan;\n              }\n\n              for (\n                this.refreshCols._.position = this.refreshCols._.minPosition;\n                this.refreshCols._.position <= this.refreshCols._.maxPosition;\n                this.refreshCols._.position++\n              ) {\n                this.possibleItemPositionsByColspan[this.refreshCols._.item][\n                  this.refreshCols._.colspan\n                ].push(this.refreshCols._.position);\n              }\n            }\n          }\n\n          // Find all the possible layouts\n\n          this.refreshCols._.colHeights = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.totalCols;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.colHeights.push(0);\n          }\n\n          this.createLayouts(0, [], [], this.refreshCols._.colHeights, 0);\n\n          // Now find the layout that looks the best.\n\n          // First find the layouts with the highest number of used columns\n          this.refreshCols._.layoutTotalCols = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.layouts.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.layoutTotalCols[this.refreshCols._.i] = 0;\n\n            for (\n              this.refreshCols._.j = 0;\n              this.refreshCols._.j < this.totalCols;\n              this.refreshCols._.j++\n            ) {\n              if (\n                this.layouts[this.refreshCols._.i].colHeights[\n                  this.refreshCols._.j\n                ]\n              ) {\n                this.refreshCols._.layoutTotalCols[this.refreshCols._.i]++;\n              }\n            }\n          }\n\n          this.refreshCols._.highestTotalCols = Math.max.apply(\n            null,\n            this.refreshCols._.layoutTotalCols\n          );\n\n          // Filter out the ones that aren't using as many columns as they could be\n          for (\n            this.refreshCols._.i = this.layouts.length - 1;\n            this.refreshCols._.i >= 0;\n            this.refreshCols._.i--\n          ) {\n            if (\n              this.refreshCols._.layoutTotalCols[this.refreshCols._.i] !==\n              this.refreshCols._.highestTotalCols\n            ) {\n              this.layouts.splice(this.refreshCols._.i, 1);\n            }\n          }\n\n          // Find the layout(s) with the least overall height\n          this.refreshCols._.layoutHeights = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.layouts.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.layoutHeights.push(\n              Math.max.apply(\n                null,\n                this.layouts[this.refreshCols._.i].colHeights\n              )\n            );\n          }\n\n          this.refreshCols._.shortestHeight = Math.min.apply(\n            null,\n            this.refreshCols._.layoutHeights\n          );\n          this.refreshCols._.shortestLayouts = [];\n          this.refreshCols._.emptySpaces = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.refreshCols._.layoutHeights.length;\n            this.refreshCols._.i++\n          ) {\n            if (\n              this.refreshCols._.layoutHeights[this.refreshCols._.i] ===\n              this.refreshCols._.shortestHeight\n            ) {\n              this.refreshCols._.shortestLayouts.push(\n                this.layouts[this.refreshCols._.i]\n              );\n\n              // Now get its total empty space, including any trailing empty space\n              this.refreshCols._.emptySpace =\n                this.layouts[this.refreshCols._.i].emptySpace;\n\n              for (\n                this.refreshCols._.j = 0;\n                this.refreshCols._.j < this.totalCols;\n                this.refreshCols._.j++\n              ) {\n                this.refreshCols._.emptySpace +=\n                  this.refreshCols._.shortestHeight -\n                  this.layouts[this.refreshCols._.i].colHeights[\n                    this.refreshCols._.j\n                  ];\n              }\n\n              this.refreshCols._.emptySpaces.push(\n                this.refreshCols._.emptySpace\n              );\n            }\n          }\n\n          // And the layout with the least empty space is...\n          this.layout =\n            this.refreshCols._.shortestLayouts[\n              $.inArray(\n                Math.min.apply(null, this.refreshCols._.emptySpaces),\n                this.refreshCols._.emptySpaces\n              )\n            ];\n\n          // Set the item widths and left positions\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.css = {\n              width: this.getItemWidthCss(\n                this.layout.colspans[this.refreshCols._.i]\n              ),\n            };\n            this.refreshCols._.css[Craft.left] = this.getItemLeftPosCss(\n              this.layout.positions[this.refreshCols._.i]\n            );\n            this.items[this.refreshCols._.i].css(this.refreshCols._.css);\n          }\n\n          // If every item is at position 0, then let them lay out au naturel\n          if (this.isSimpleLayout()) {\n            this.$container.height('auto');\n            this.$items.css({\n              position: 'relative',\n              top: 0,\n              'margin-bottom': this.settings.gutter + 'px',\n            });\n          } else {\n            this.$items.css('position', 'absolute');\n\n            // Now position the items\n            this.positionItems();\n\n            // Update the positions as the items' heigthts change\n            this.addListener(this.$items, 'resize', 'onItemResize');\n          }\n        }\n      }\n\n      this.completeRefreshCols();\n\n      // Resume container resize listening\n      this.addListener(\n        this.$container,\n        'resize',\n        this.handleContainerHeightProxy\n      );\n\n      this.onRefreshCols();\n    },\n\n    completeRefreshCols: function () {\n      // Delete the internal variable object\n      if (typeof this.refreshCols._ !== 'undefined') {\n        delete this.refreshCols._;\n      }\n\n      this._refreshingCols = false;\n\n      if (this._refreshColsAfterRefresh) {\n        var force = this._forceRefreshColsAfterRefresh;\n        this._refreshColsAfterRefresh = false;\n        this._forceRefreshColsAfterRefresh = false;\n\n        Garnish.requestAnimationFrame(() => {\n          this.refreshCols(force);\n        });\n      }\n    },\n\n    getItemWidth: function (colspan) {\n      return this.colPctWidth * colspan;\n    },\n\n    getItemWidthCss: function (colspan) {\n      return (\n        'calc(' +\n        this.getItemWidth(colspan) +\n        '% - ' +\n        this.colGutterDrop +\n        'px)'\n      );\n    },\n\n    getItemWidthInPx: function (colspan) {\n      return (\n        (this.getItemWidth(colspan) / 100) * this.$container.width() -\n        this.colGutterDrop\n      );\n    },\n\n    getItemLeftPosCss: function (position) {\n      return (\n        'calc(' +\n        '(' +\n        this.getItemWidth(1) +\n        '% + ' +\n        (this.settings.gutter - this.colGutterDrop) +\n        'px) * ' +\n        position +\n        ')'\n      );\n    },\n\n    getItemLeftPosInPx: function (position) {\n      return (\n        ((this.getItemWidth(1) / 100) * this.$container.width() +\n          (this.settings.gutter - this.colGutterDrop)) *\n        position\n      );\n    },\n\n    createLayouts: function (\n      item,\n      prevPositions,\n      prevColspans,\n      prevColHeights,\n      prevEmptySpace\n    ) {\n      new Craft.Grid.LayoutGenerator(this).createLayouts(\n        item,\n        prevPositions,\n        prevColspans,\n        prevColHeights,\n        prevEmptySpace\n      );\n    },\n\n    isSimpleLayout: function () {\n      this.isSimpleLayout._ = {};\n\n      for (\n        this.isSimpleLayout._.i = 0;\n        this.isSimpleLayout._.i < this.layout.positions.length;\n        this.isSimpleLayout._.i++\n      ) {\n        if (this.layout.positions[this.isSimpleLayout._.i] !== 0) {\n          delete this.isSimpleLayout._;\n          return false;\n        }\n      }\n\n      delete this.isSimpleLayout._;\n      return true;\n    },\n\n    positionItems: function () {\n      this.positionItems._ = {};\n\n      this.positionItems._.colHeights = [];\n\n      for (\n        this.positionItems._.i = 0;\n        this.positionItems._.i < this.totalCols;\n        this.positionItems._.i++\n      ) {\n        this.positionItems._.colHeights.push(0);\n      }\n\n      for (\n        this.positionItems._.i = 0;\n        this.positionItems._.i < this.items.length;\n        this.positionItems._.i++\n      ) {\n        this.positionItems._.endingCol =\n          this.layout.positions[this.positionItems._.i] +\n          this.layout.colspans[this.positionItems._.i] -\n          1;\n        this.positionItems._.affectedColHeights = [];\n\n        for (\n          this.positionItems._.col =\n            this.layout.positions[this.positionItems._.i];\n          this.positionItems._.col <= this.positionItems._.endingCol;\n          this.positionItems._.col++\n        ) {\n          this.positionItems._.affectedColHeights.push(\n            this.positionItems._.colHeights[this.positionItems._.col]\n          );\n        }\n\n        this.positionItems._.top = Math.max.apply(\n          null,\n          this.positionItems._.affectedColHeights\n        );\n        if (this.positionItems._.top > 0) {\n          this.positionItems._.top += this.settings.gutter;\n        }\n\n        this.items[this.positionItems._.i].css('top', this.positionItems._.top);\n\n        // Now add the new heights to those columns\n        for (\n          this.positionItems._.col =\n            this.layout.positions[this.positionItems._.i];\n          this.positionItems._.col <= this.positionItems._.endingCol;\n          this.positionItems._.col++\n        ) {\n          this.positionItems._.colHeights[this.positionItems._.col] =\n            this.positionItems._.top +\n            this.itemHeightsByColspan[this.positionItems._.i][\n              this.layout.colspans[this.positionItems._.i]\n            ];\n        }\n      }\n\n      // Set the container height\n      this.$container.height(\n        Math.max.apply(null, this.positionItems._.colHeights)\n      );\n\n      delete this.positionItems._;\n    },\n\n    onItemResize: function (ev) {\n      this.onItemResize._ = {};\n\n      // Prevent this from bubbling up to the container, which has its own resize listener\n      ev.stopPropagation();\n\n      this.onItemResize._.item = $.inArray(ev.currentTarget, this.$items);\n\n      if (this.onItemResize._.item !== -1) {\n        // Update the height and reposition the items\n        this.onItemResize._.newHeight =\n          this.items[this.onItemResize._.item].outerHeight();\n\n        if (\n          this.onItemResize._.newHeight !==\n          this.itemHeightsByColspan[this.onItemResize._.item][\n            this.layout.colspans[this.onItemResize._.item]\n          ]\n        ) {\n          this.itemHeightsByColspan[this.onItemResize._.item][\n            this.layout.colspans[this.onItemResize._.item]\n          ] = this.onItemResize._.newHeight;\n          this.positionItems(false);\n        }\n      }\n\n      delete this.onItemResize._;\n    },\n\n    onRefreshCols: function () {\n      this.trigger('refreshCols');\n      this.settings.onRefreshCols();\n    },\n\n    destroy: function () {\n      this.$container.removeData('grid');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      itemSelector: '.item',\n      cols: null,\n      maxCols: null,\n      minColWidth: 320,\n      gutter: 14,\n      fillMode: 'top',\n      colClass: 'col',\n      snapToGrid: null,\n\n      onRefreshCols: $.noop,\n    },\n  }\n);\n\nCraft.Grid.LayoutGenerator = Garnish.Base.extend({\n  grid: null,\n  _: null,\n\n  init: function (grid) {\n    this.grid = grid;\n  },\n\n  createLayouts: function (\n    item,\n    prevPositions,\n    prevColspans,\n    prevColHeights,\n    prevEmptySpace\n  ) {\n    this._ = {};\n\n    // Loop through all possible colspans\n    for (\n      this._.c = 0;\n      this._.c < this.grid.possibleItemColspans[item].length;\n      this._.c++\n    ) {\n      this._.colspan = this.grid.possibleItemColspans[item][this._.c];\n\n      // Loop through all the possible positions for this colspan,\n      // and find the one that is closest to the top\n\n      this._.tallestColHeightsByPosition = [];\n\n      for (\n        this._.p = 0;\n        this._.p <\n        this.grid.possibleItemPositionsByColspan[item][this._.colspan].length;\n        this._.p++\n      ) {\n        this._.position =\n          this.grid.possibleItemPositionsByColspan[item][this._.colspan][\n            this._.p\n          ];\n\n        this._.colHeightsForPosition = [];\n        this._.endingCol = this._.position + this._.colspan - 1;\n\n        for (\n          this._.col = this._.position;\n          this._.col <= this._.endingCol;\n          this._.col++\n        ) {\n          this._.colHeightsForPosition.push(prevColHeights[this._.col]);\n        }\n\n        this._.tallestColHeightsByPosition[this._.p] = Math.max.apply(\n          null,\n          this._.colHeightsForPosition\n        );\n      }\n\n      // And the shortest position for this colspan is...\n      this._.p = $.inArray(\n        Math.min.apply(null, this._.tallestColHeightsByPosition),\n        this._.tallestColHeightsByPosition\n      );\n      this._.position =\n        this.grid.possibleItemPositionsByColspan[item][this._.colspan][\n          this._.p\n        ];\n\n      // Now log the colspan/position placement\n      this._.positions = prevPositions.slice(0);\n      this._.colspans = prevColspans.slice(0);\n      this._.colHeights = prevColHeights.slice(0);\n      this._.emptySpace = prevEmptySpace;\n\n      this._.positions.push(this._.position);\n      this._.colspans.push(this._.colspan);\n\n      // Add the new heights to those columns\n      this._.tallestColHeight = this._.tallestColHeightsByPosition[this._.p];\n      this._.endingCol = this._.position + this._.colspan - 1;\n\n      for (\n        this._.col = this._.position;\n        this._.col <= this._.endingCol;\n        this._.col++\n      ) {\n        this._.emptySpace +=\n          this._.tallestColHeight - this._.colHeights[this._.col];\n        this._.colHeights[this._.col] =\n          this._.tallestColHeight +\n          this.grid.itemHeightsByColspan[item][this._.colspan];\n      }\n\n      // If this is the last item, create the layout\n      if (item === this.grid.items.length - 1) {\n        this.grid.layouts.push({\n          positions: this._.positions,\n          colspans: this._.colspans,\n          colHeights: this._.colHeights,\n          emptySpace: this._.emptySpace,\n        });\n      } else {\n        // Dive deeper\n        this.grid.createLayouts(\n          item + 1,\n          this._.positions,\n          this._.colspans,\n          this._.colHeights,\n          this._.emptySpace\n        );\n      }\n    }\n\n    delete this._;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.HandleGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    var handle = sourceVal.replace(/<(.*?)>/g, '');\n\n    // Remove inner-word punctuation\n    handle = handle.replace(/['\"‘’“”\\[\\]\\(\\)\\{\\}:]/g, '');\n\n    // Make it lowercase\n    handle = handle.toLowerCase();\n\n    // Convert extended ASCII characters to basic ASCII\n    handle = Craft.asciiString(handle);\n\n    if (!this.settings.allowNonAlphaStart) {\n      // Handle must start with a letter\n      handle = handle.replace(/^[^a-z]+/, '');\n    }\n\n    // Get the \"words\"\n    var words = Craft.filterArray(handle.split(/[^a-z0-9]+/));\n    handle = '';\n\n    if (Craft.handleCasing === 'snake') {\n      return words.join('_');\n    }\n\n    // Make it camelCase\n    for (let i = 0; i < words.length; i++) {\n      if (Craft.handleCasing !== 'pascal' && i === 0) {\n        handle += words[i];\n      } else {\n        handle += words[i].charAt(0).toUpperCase() + words[i].substring(1);\n      }\n    }\n\n    return handle;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Image upload class for user photos, site icon and logo.\n */\nCraft.ImageUpload = Garnish.Base.extend(\n  {\n    $container: null,\n    progressBar: null,\n    uploader: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.ImageUpload.defaults);\n      this.initImageUpload();\n    },\n\n    initImageUpload: function () {\n      this.$container = $(this.settings.containerSelector);\n      this.progressBar = new Craft.ProgressBar(\n        $('<div class=\"progress-shade\"></div>').appendTo(this.$container)\n      );\n\n      var options = {\n        url: Craft.getActionUrl(this.settings.uploadAction),\n        formData: this.settings.postParameters,\n        fileInput: this.$container.find(this.settings.fileInputSelector),\n        paramName: this.settings.uploadParamName,\n      };\n\n      // If CSRF protection isn't enabled, these won't be defined.\n      if (\n        typeof Craft.csrfTokenName !== 'undefined' &&\n        typeof Craft.csrfTokenValue !== 'undefined'\n      ) {\n        // Add the CSRF token\n        options.formData[Craft.csrfTokenName] = Craft.csrfTokenValue;\n      }\n\n      options.events = {};\n      options.events.fileuploadstart = this._onUploadStart.bind(this);\n      options.events.fileuploadprogressall = this._onUploadProgress.bind(this);\n      options.events.fileuploaddone = this._onUploadComplete.bind(this);\n      options.events.fileuploadfail = this._onUploadFailure.bind(this);\n\n      this.uploader = new Craft.Uploader(this.$container, options);\n\n      this.initButtons();\n    },\n\n    initButtons: function () {\n      this.$container\n        .find(this.settings.uploadButtonSelector)\n        .on('click', (ev) => {\n          this.$container\n            .find(this.settings.fileInputSelector)\n            .trigger('click');\n        });\n\n      this.$container\n        .find(this.settings.deleteButtonSelector)\n        .on('click', (ev) => {\n          if (\n            confirm(\n              Craft.t('app', 'Are you sure you want to delete this image?')\n            )\n          ) {\n            $(ev.currentTarget)\n              .parent()\n              .append('<div class=\"blocking-modal\"></div>');\n\n            Craft.sendActionRequest('POST', this.settings.deleteAction, {\n              data: this.settings.postParameters,\n            }).then(({data}) => {\n              this.refreshImage(data);\n            });\n          }\n        });\n    },\n\n    refreshImage: function (response) {\n      $(this.settings.containerSelector).replaceWith(response.html);\n      this.settings.onAfterRefreshImage(response);\n      this.initImageUpload();\n    },\n\n    /**\n     * On upload start.\n     */\n    _onUploadStart: function (event) {\n      this.progressBar.$progressBar.css({\n        top: Math.round(this.$container.outerHeight() / 2) - 6,\n      });\n\n      this.$container.addClass('uploading');\n      this.progressBar.resetProgressBar();\n      this.progressBar.showProgressBar();\n    },\n\n    /**\n     * On upload progress.\n     */\n    _onUploadProgress: function (event, data) {\n      var progress = parseInt((data.loaded / data.total) * 100, 10);\n      this.progressBar.setProgressPercentage(progress);\n    },\n\n    /**\n     * On a file being uploaded.\n     */\n    _onUploadComplete: function (event, data) {\n      if (data.result.error) {\n        Craft.cp.displayError(data.result.error);\n      } else {\n        var html = $(data.result.html);\n        this.refreshImage(data.result);\n      }\n\n      // Last file\n      if (this.uploader.isLastUpload()) {\n        this.progressBar.hideProgressBar();\n        this.$container.removeClass('uploading');\n      }\n    },\n\n    /**\n     * On Upload Failure.\n     */\n    _onUploadFailure: function (event, data) {\n      const response = data.response();\n      let {message, filename} = response?.jqXHR?.responseJSON || {};\n\n      if (!message) {\n        message = filename\n          ? Craft.t('app', 'Upload failed for “{filename}”.', {filename})\n          : Craft.t('app', 'Upload failed.');\n      }\n\n      Craft.cp.displayError(message);\n      this.progressBar.hideProgressBar();\n      this.$container.removeClass('uploading');\n    },\n  },\n  {\n    defaults: {\n      postParameters: {},\n      uploadAction: '',\n      deleteAction: '',\n      fileInputSelector: '',\n\n      onAfterRefreshImage: $.noop,\n      containerSelector: null,\n\n      uploadButtonSelector: null,\n      deleteButtonSelector: null,\n\n      uploadParamName: 'files',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Info icon class\n */\nCraft.InfoIcon = Garnish.Base.extend({\n  $container: null,\n  $icon: null,\n  $liveRegion: null,\n  content: null,\n  hud: null,\n\n  init: function (icon) {\n    this.$icon = $(icon);\n    this.$liveRegion = $('<span/>', {\n      role: 'status',\n      class: 'visually-hidden',\n    });\n\n    if (this.$icon.data('infoicon')) {\n      console.warn('Double-instantiating an info icon on an element');\n      this.content = this.$icon.data('infoicon').content;\n      this.$icon.data('infoicon').destroy();\n    } else {\n      this.content = this.$icon.html();\n      this.$icon\n        .html('')\n        .attr({\n          tabindex: 0,\n          role: 'button',\n          type: 'button',\n          'aria-label': Craft.t('app', 'More info'),\n        })\n        .wrap(\n          $('<span/>', {\n            class: 'infoicon-container',\n          })\n        );\n\n      this.$container = this.$icon.parent();\n      this.$container.append(this.$liveRegion);\n    }\n\n    this.$icon.data('infoicon', this);\n\n    if (\n      this.$icon[0].previousSibling &&\n      this.$icon[0].previousSibling.nodeType === Node.TEXT_NODE\n    ) {\n      // Make sure it's in a .nowrap container\n      const $parent = this.$icon.parent();\n      if (!$parent.hasClass('nowrap')) {\n        // Find the last word in the text\n        const m = this.$icon[0].previousSibling.nodeValue.match(/[^\\s\\-]+\\s*$/);\n        if (m) {\n          this.$icon[0].previousSibling.nodeValue =\n            this.$icon[0].previousSibling.nodeValue.substring(0, m.index);\n          $('<span/>', {\n            class: 'nowrap',\n            html: m[0].replace(/\\s+$/, '') + ' ',\n          })\n            .insertAfter(this.$icon[0].previousSibling)\n            .append(this.$icon);\n        }\n      }\n    }\n\n    this.addListener(this.$icon, 'click', (ev) => {\n      ev.preventDefault();\n      ev.stopPropagation();\n      this.showHud();\n    });\n\n    this.addListener(this.$icon, 'keydown', (ev) => {\n      if (\n        !(this.hud && this.hud.showing) &&\n        [Garnish.SPACE_KEY, Garnish.RETURN_KEY].includes(ev.keyCode)\n      ) {\n        ev.preventDefault();\n        ev.stopPropagation();\n        this.showHud();\n      }\n    });\n  },\n\n  showHud: function (ev) {\n    if (!this.hud) {\n      this.hud = new Garnish.HUD(this.$icon, this.content, {\n        hudClass: 'hud info-hud',\n        closeOtherHUDs: false,\n        onShow: () => {\n          Garnish.uiLayerManager.registerShortcut(Garnish.SPACE_KEY, () => {\n            this.hud.hide();\n          });\n\n          this.$liveRegion.html('');\n\n          setTimeout(() => {\n            this.$liveRegion.html(this.content);\n          }, 200);\n        },\n        onHide: () => {\n          this.$liveRegion.html('');\n        },\n      });\n      Craft.initUiElements(this.hud.$body);\n    } else {\n      this.hud.show();\n    }\n  },\n\n  destroy: function () {\n    this.$icon.removeData('infoicon');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Light Switch\n */\nCraft.LightSwitch = Garnish.Base.extend(\n  {\n    settings: null,\n    $outerContainer: null,\n    $innerContainer: null,\n    $input: null,\n    small: false,\n    on: false,\n    indeterminate: false,\n    dragger: null,\n\n    dragStartMargin: null,\n\n    init: function (outerContainer, settings) {\n      this.$outerContainer = $(outerContainer);\n\n      // Is this already a lightswitch?\n      if (this.$outerContainer.data('lightswitch')) {\n        console.warn('Double-instantiating a lightswitch on an element');\n        this.$outerContainer.data('lightswitch').destroy();\n      }\n\n      this.$outerContainer.data('lightswitch', this);\n\n      this.small = this.$outerContainer.hasClass('small');\n\n      this.setSettings(settings, Craft.LightSwitch.defaults);\n\n      this.$innerContainer = this.$outerContainer.find(\n        '.lightswitch-container:first'\n      );\n      this.$input = this.$outerContainer.find('input:first');\n\n      // If the input is disabled, go no further\n      if (this.$input.prop('disabled')) {\n        return;\n      }\n\n      this.on = this.$outerContainer.hasClass('on');\n      this.indeterminate = this.$outerContainer.hasClass('indeterminate');\n\n      this.addListener(this.$outerContainer, 'mousedown', '_onMouseDown');\n      this.addListener(this.$outerContainer, 'keydown', '_onKeyDown');\n\n      this.dragger = new Garnish.BaseDrag(this.$outerContainer, {\n        axis: Garnish.X_AXIS,\n        ignoreHandleSelector: null,\n        onDragStart: this._onDragStart.bind(this),\n        onDrag: this._onDrag.bind(this),\n        onDragStop: this._onDragStop.bind(this),\n      });\n\n      // Does the input have on/off labels?\n      let $wrapper = this.$outerContainer.parent(\n        '.lightswitch-inner-container'\n      );\n      if ($wrapper.length) {\n        this.addListener(\n          $wrapper.children('span[data-toggle=\"off\"]'),\n          'click',\n          this.turnOff\n        );\n        this.addListener(\n          $wrapper.children('span[data-toggle=\"on\"]'),\n          'click',\n          this.turnOn\n        );\n      }\n    },\n\n    turnOn: function (muteEvent) {\n      var changed = !this.on;\n\n      this.on = true;\n      this.indeterminate = false;\n\n      this.$outerContainer.addClass('dragging');\n\n      if (Garnish.prefersReducedMotion()) {\n        this.$innerContainer.css('margin-' + Craft.left, 0);\n      } else {\n        var animateCss = {};\n        animateCss['margin-' + Craft.left] = 0;\n        this.$innerContainer\n          .velocity('stop')\n          .velocity(\n            animateCss,\n            Craft.LightSwitch.animationDuration,\n            this._onSettle.bind(this)\n          );\n      }\n\n      this.$input.val(this.settings.value);\n      this.$outerContainer.addClass('on');\n      this.$outerContainer.removeClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'true');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    turnOff: function (muteEvent) {\n      var changed = this.on || this.indeterminate;\n\n      this.on = false;\n      this.indeterminate = false;\n\n      this.$outerContainer.addClass('dragging');\n\n      if (Garnish.prefersReducedMotion()) {\n        this.$innerContainer.css('margin-' + Craft.left, this._getOffMargin());\n      } else {\n        var animateCss = {};\n        animateCss['margin-' + Craft.left] = this._getOffMargin();\n        this.$innerContainer\n          .velocity('stop')\n          .velocity(\n            animateCss,\n            Craft.LightSwitch.animationDuration,\n            this._onSettle.bind(this)\n          );\n      }\n\n      this.$input.val('');\n      this.$outerContainer.removeClass('on');\n      this.$outerContainer.removeClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'false');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    turnIndeterminate: function (muteEvent) {\n      var changed = !this.indeterminate;\n\n      this.on = false;\n      this.indeterminate = true;\n\n      this.$outerContainer.addClass('dragging');\n      var animateCss = {};\n      animateCss['margin-' + Craft.left] = this._getOffMargin() / 2;\n      this.$innerContainer\n        .velocity('stop')\n        .velocity(\n          animateCss,\n          Craft.LightSwitch.animationDuration,\n          this._onSettle.bind(this)\n        );\n\n      this.$input.val(this.settings.indeterminateValue);\n      this.$outerContainer.removeClass('on');\n      this.$outerContainer.addClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'mixed');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    toggle: function () {\n      if (this.indeterminate || !this.on) {\n        this.turnOn();\n      } else {\n        this.turnOff();\n      }\n    },\n\n    onChange: function () {\n      this.trigger('change');\n      this.settings.onChange(this.on);\n      this.$outerContainer.trigger('change');\n    },\n\n    _onMouseDown: function () {\n      this.addListener(Garnish.$doc, 'mouseup', '_onMouseUp');\n    },\n\n    _onMouseUp: function () {\n      this.removeListener(Garnish.$doc, 'mouseup');\n\n      // Was this a click?\n      if (!this.dragger.dragging) {\n        this.toggle();\n      }\n    },\n\n    _onKeyDown: function (event) {\n      switch (event.keyCode) {\n        case Garnish.SPACE_KEY: {\n          this.toggle();\n          event.preventDefault();\n          break;\n        }\n        case Garnish.RIGHT_KEY: {\n          if (Craft.orientation === 'ltr') {\n            this.turnOn();\n          } else {\n            this.turnOff();\n          }\n\n          event.preventDefault();\n          break;\n        }\n        case Garnish.LEFT_KEY: {\n          if (Craft.orientation === 'ltr') {\n            this.turnOff();\n          } else {\n            this.turnOn();\n          }\n\n          event.preventDefault();\n          break;\n        }\n      }\n    },\n\n    _getMargin: function () {\n      return parseInt(this.$innerContainer.css('margin-' + Craft.left));\n    },\n\n    _onDragStart: function () {\n      this.$outerContainer.addClass('dragging');\n      this.dragStartMargin = this._getMargin();\n    },\n\n    _onDrag: function () {\n      var margin;\n\n      if (Craft.orientation === 'ltr') {\n        margin = this.dragStartMargin + this.dragger.mouseDistX;\n      } else {\n        margin = this.dragStartMargin - this.dragger.mouseDistX;\n      }\n\n      if (margin < this._getOffMargin()) {\n        margin = this._getOffMargin();\n      } else if (margin > 0) {\n        margin = 0;\n      }\n\n      this.$innerContainer.css('margin-' + Craft.left, margin);\n    },\n\n    _onDragStop: function () {\n      var margin = this._getMargin();\n\n      if (margin > this._getOffMargin() / 2) {\n        this.turnOn();\n      } else {\n        this.turnOff();\n      }\n    },\n\n    _onSettle: function () {\n      this.$outerContainer.removeClass('dragging');\n    },\n\n    destroy: function () {\n      this.$outerContainer.removeData('lightswitch');\n      this.base();\n      this.dragger.destroy();\n    },\n\n    _getOffMargin: function () {\n      return this.small ? -10 : -12;\n    },\n  },\n  {\n    animationDuration: 100,\n    defaults: {\n      value: '1',\n      indeterminateValue: '-',\n      onChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Listbox\n */\nCraft.Listbox = Garnish.Base.extend(\n  {\n    $container: null,\n    $options: null,\n    $selectedOption: null,\n    selectedOptionIndex: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.Listbox.defaults);\n\n      // Is this already a listbox?\n      if (this.$container.data('listbox')) {\n        console.warn('Double-instantiating a listbox on an element');\n        this.$container.data('listbox').destroy();\n      }\n\n      this.$container.data('listbox', this);\n      // todo: drop [role=option] in Craft 5\n      this.$options = this.$container.find('button,[role=option]');\n\n      // is there already a selected option?\n      // todo: drop [aria-selected=true] & attr normalization in Craft 5\n      this.$selectedOption = this.$options\n        .filter('[aria-pressed=true],[aria-selected=true]')\n        .removeAttr('aria-selected')\n        .attr('aria-pressed', 'true');\n      if (this.$selectedOption.length) {\n        this.selectedOptionIndex = this.$options.index(this.$selectedOption);\n      } else {\n        this.$selectedOption = null;\n      }\n\n      this.addListener(this.$options, 'click', (ev) => {\n        this.select(this.$options.index($(ev.currentTarget)));\n        ev.preventDefault();\n      });\n    },\n\n    select: function (index) {\n      if (\n        index < 0 ||\n        index >= this.$options.length ||\n        index === this.selectedOptionIndex\n      ) {\n        return;\n      }\n\n      if (this.$selectedOption) {\n        this.$selectedOption\n          .removeClass(this.settings.selectedClass)\n          .attr('aria-pressed', 'false');\n      }\n\n      this.$selectedOption = this.$options\n        .eq(index)\n        .addClass(this.settings.selectedClass)\n        .attr('aria-pressed', 'true');\n\n      this.selectedOptionIndex = index;\n\n      this.settings.onChange(this.$selectedOption, index);\n      this.trigger('change', {\n        $selectedOption: this.$selectedOption,\n        selectedOptionIndex: index,\n      });\n    },\n\n    disable: function () {\n      this.base();\n      this.$container.attr('aria-disabled', 'true');\n    },\n\n    enable: function () {\n      this.base();\n      this.$container.removeAttr('aria-disabled');\n    },\n\n    destroy: function () {\n      this.$container.removeData('listbox');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      selectedClass: 'active',\n      focusClass: 'focus',\n      onChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Live Preview\n */\nCraft.LivePreview = Garnish.Base.extend(\n  {\n    $extraFields: null,\n    $trigger: null,\n    $shade: null,\n    $editorContainer: null,\n    $editor: null,\n    $dragHandle: null,\n    $previewContainer: null,\n    $iframeContainer: null,\n    $iframe: null,\n    $fieldPlaceholder: null,\n\n    previewUrl: null,\n    token: null,\n    basePostData: null,\n    inPreviewMode: false,\n    fields: null,\n    lastPostData: null,\n    updateIframeInterval: null,\n    loading: false,\n    checkAgain: false,\n\n    dragger: null,\n    dragStartEditorWidth: null,\n\n    _slideInOnIframeLoad: false,\n\n    _scrollX: null,\n    _scrollY: null,\n\n    _editorWidth: null,\n    _editorWidthInPx: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.LivePreview.defaults);\n\n      // Should preview requests use a specific URL?\n      // This won't affect how the request gets routed (the action param will override it),\n      // but it will allow the templates to change behavior based on the request URI.\n      if (this.settings.previewUrl) {\n        this.previewUrl = this.settings.previewUrl;\n      } else {\n        this.previewUrl = Craft.baseSiteUrl.replace(/\\/+$/, '') + '/';\n      }\n\n      // Load the preview over SSL if the current request is\n      if (document.location.protocol === 'https:') {\n        this.previewUrl = this.previewUrl.replace(/^http:/, 'https:');\n      }\n\n      // Set the base post data\n      this.basePostData = $.extend({}, this.settings.previewParams);\n\n      // Find the DOM elements\n      this.$extraFields = $(this.settings.extraFields);\n      this.$trigger = $(this.settings.trigger);\n      this.$fieldPlaceholder = $('<div/>');\n\n      // Set the initial editor width\n      this.editorWidth = Craft.getLocalStorage(\n        'LivePreview.editorWidth',\n        Craft.LivePreview.defaultEditorWidth\n      );\n\n      // Event Listeners\n      this.addListener(this.$trigger, 'activate', 'toggle');\n\n      Craft.cp.on('beforeSaveShortcut', () => {\n        if (this.inPreviewMode) {\n          this.moveFieldsBack();\n        }\n      });\n\n      Craft.Preview.instances.push(this);\n    },\n\n    get editorWidth() {\n      return this._editorWidth;\n    },\n\n    get editorWidthInPx() {\n      return this._editorWidthInPx;\n    },\n\n    set editorWidth(width) {\n      var inPx;\n\n      // Is this getting set in pixels?\n      if (width >= 1) {\n        inPx = width;\n        width /= Garnish.$win.width();\n      } else {\n        inPx = Math.round(width * Garnish.$win.width());\n      }\n\n      // Make sure it's no less than the minimum\n      if (inPx < Craft.LivePreview.minEditorWidthInPx) {\n        inPx = Craft.LivePreview.minEditorWidthInPx;\n        width = inPx / Garnish.$win.width();\n      }\n\n      this._editorWidth = width;\n      this._editorWidthInPx = inPx;\n    },\n\n    toggle: function () {\n      if (this.inPreviewMode) {\n        this.exit();\n      } else {\n        this.enter();\n      }\n    },\n\n    enter: function () {\n      if (this.inPreviewMode) {\n        return;\n      }\n\n      if (!this.token) {\n        this.createToken();\n        return;\n      }\n\n      this.trigger('beforeEnter');\n\n      $(document.activeElement).trigger('blur');\n\n      if (!this.$editor) {\n        this.$shade = $('<div/>', {class: 'modal-shade dark'}).appendTo(\n          Garnish.$bod\n        );\n        this.$previewContainer = $('<div/>', {\n          class: 'lp-preview-container',\n        }).appendTo(Garnish.$bod);\n        this.$iframeContainer = $('<div/>', {\n          class: 'lp-iframe-container',\n        }).appendTo(this.$previewContainer);\n        this.$editorContainer = $('<div/>', {\n          class: 'lp-editor-container',\n        }).appendTo(Garnish.$bod);\n\n        var $editorHeader = $('<header/>', {class: 'flex'}).appendTo(\n          this.$editorContainer\n        );\n        this.$editor = $('<form/>', {class: 'lp-editor'}).appendTo(\n          this.$editorContainer\n        );\n        this.$dragHandle = $('<div/>', {class: 'lp-draghandle'}).appendTo(\n          this.$editorContainer\n        );\n        var $closeBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Close Preview'),\n        }).appendTo($editorHeader);\n        $('<div/>', {class: 'flex-grow'}).appendTo($editorHeader);\n        let $saveBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit',\n          text: Craft.t('app', 'Save'),\n        }).appendTo($editorHeader);\n\n        this.dragger = new Garnish.BaseDrag(this.$dragHandle, {\n          axis: Garnish.X_AXIS,\n          onDragStart: this._onDragStart.bind(this),\n          onDrag: this._onDrag.bind(this),\n          onDragStop: this._onDragStop.bind(this),\n        });\n\n        this.addListener($closeBtn, 'click', 'exit');\n        this.addListener($saveBtn, 'click', 'save');\n      }\n\n      // Set the sizes\n      this.handleWindowResize();\n      this.addListener(Garnish.$win, 'resize', 'handleWindowResize');\n\n      this.$editorContainer.css(Craft.left, -this.editorWidthInPx + 'px');\n      this.$previewContainer.css(Craft.right, -this.getIframeWidth());\n\n      // Move all the fields into the editor rather than copying them\n      // so any JS that's referencing the elements won't break.\n      this.fields = [];\n      var $fields = $(this.settings.fields);\n\n      for (var i = 0; i < $fields.length; i++) {\n        var $field = $($fields[i]),\n          $clone = this._getClone($field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter($field);\n        $field.detach();\n        this.$fieldPlaceholder.replaceWith($clone);\n        $field.appendTo(this.$editor);\n\n        this.fields.push({\n          $field: $field,\n          $clone: $clone,\n        });\n      }\n\n      if (this.updateIframe()) {\n        this._slideInOnIframeLoad = true;\n      } else {\n        this.slideIn();\n      }\n\n      Craft.ElementThumbLoader.retryAll();\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.exit();\n      });\n\n      this.inPreviewMode = true;\n      this.trigger('enter');\n    },\n\n    createToken: function () {\n      const data = {previewAction: this.settings.previewAction};\n      Craft.sendActionRequest('POST', 'live-preview/create-token', {data}).then(\n        (response) => {\n          this.token = response.data.token;\n          this.enter();\n        }\n      );\n    },\n\n    save: function () {\n      Craft.cp.submitPrimaryForm();\n    },\n\n    handleWindowResize: function () {\n      // Reset the width so the min width is enforced\n      this.editorWidth = this.editorWidth;\n\n      // Update the editor/iframe sizes\n      this.updateWidths();\n    },\n\n    slideIn: function () {\n      $('html').addClass('noscroll');\n      this.$shade.velocity('fadeIn');\n\n      this.$editorContainer\n        .show()\n        .velocity('stop')\n        .animateLeft(0, 'slow', () => {\n          this.trigger('slideIn');\n          Garnish.$win.trigger('resize');\n        });\n\n      this.$previewContainer\n        .show()\n        .velocity('stop')\n        .animateRight(0, 'slow', () => {\n          this.updateIframeInterval = setInterval(\n            this.updateIframe.bind(this),\n            1000\n          );\n        });\n    },\n\n    exit: function () {\n      if (!this.inPreviewMode) {\n        return;\n      }\n\n      this.trigger('beforeExit');\n\n      $('html').removeClass('noscroll');\n\n      this.removeListener(Garnish.$win, 'resize');\n      Garnish.uiLayerManager.removeLayer();\n\n      if (this.updateIframeInterval) {\n        clearInterval(this.updateIframeInterval);\n      }\n\n      this.moveFieldsBack();\n\n      this.$shade.delay(200).velocity('fadeOut');\n\n      this.$editorContainer\n        .velocity('stop')\n        .animateLeft(-this.editorWidthInPx, 'slow', () => {\n          for (var i = 0; i < this.fields.length; i++) {\n            this.fields[i].$newClone.remove();\n          }\n          this.$editorContainer.hide();\n          this.trigger('slideOut');\n        });\n\n      this.$previewContainer\n        .velocity('stop')\n        .animateRight(-this.getIframeWidth(), 'slow', () => {\n          this.$previewContainer.hide();\n        });\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.inPreviewMode = false;\n      this.trigger('exit');\n    },\n\n    moveFieldsBack: function () {\n      for (var i = 0; i < this.fields.length; i++) {\n        var field = this.fields[i];\n        field.$newClone = this._getClone(field.$field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter(field.$field);\n        field.$field.detach();\n        this.$fieldPlaceholder.replaceWith(field.$newClone);\n        field.$clone.replaceWith(field.$field);\n      }\n\n      Garnish.$win.trigger('resize');\n    },\n\n    getIframeWidth: function () {\n      return Garnish.$win.width() - this.editorWidthInPx;\n    },\n\n    updateWidths: function () {\n      this.$editorContainer.css('width', this.editorWidthInPx + 'px');\n      this.$previewContainer.width(this.getIframeWidth());\n    },\n\n    updateIframe: function (force) {\n      if (force) {\n        this.lastPostData = null;\n      }\n\n      if (!this.inPreviewMode) {\n        return false;\n      }\n\n      if (this.loading) {\n        this.checkAgain = true;\n        return false;\n      }\n\n      // Has the post data changed?\n      var postData = $.extend(\n        Garnish.getPostData(this.$editor),\n        Garnish.getPostData(this.$extraFields)\n      );\n\n      if (\n        !this.lastPostData ||\n        !Craft.compare(postData, this.lastPostData, false)\n      ) {\n        this.lastPostData = postData;\n        this.loading = true;\n\n        var $doc = this.$iframe\n          ? $(this.$iframe[0].contentWindow.document)\n          : null;\n\n        this._scrollX = $doc ? $doc.scrollLeft() : 0;\n        this._scrollY = $doc ? $doc.scrollTop() : 0;\n\n        $.ajax({\n          url:\n            this.previewUrl +\n            (this.previewUrl.indexOf('?') !== -1 ? '&' : '?') +\n            Craft.tokenParam +\n            '=' +\n            this.token,\n          method: 'POST',\n          data: $.extend({}, postData, this.basePostData),\n          headers: {\n            'X-Craft-Token': this.token,\n          },\n          xhrFields: {\n            withCredentials: true,\n          },\n          crossDomain: true,\n          success: this.handleSuccess.bind(this),\n          error: this.handleError.bind(this),\n        });\n\n        return true;\n      } else {\n        return false;\n      }\n    },\n\n    forceUpdateIframe: function () {\n      return this.updateIframe(true);\n    },\n\n    handleSuccess: function (data) {\n      var html =\n        data +\n        '<script type=\"text/javascript\">window.scrollTo(' +\n        this._scrollX +\n        ', ' +\n        this._scrollY +\n        ');</script>';\n\n      // Create a new iframe\n      var $iframe = $('<iframe class=\"lp-preview\" frameborder=\"0\"/>');\n      if (this.$iframe) {\n        $iframe.insertBefore(this.$iframe);\n      } else {\n        $iframe.appendTo(this.$iframeContainer);\n      }\n\n      this.addListener($iframe, 'load', function () {\n        if (this.$iframe) {\n          this.$iframe.remove();\n        }\n        this.$iframe = $iframe;\n\n        if (this._slideInOnIframeLoad) {\n          this.slideIn();\n          this._slideInOnIframeLoad = false;\n        }\n\n        this.removeListener($iframe, 'load');\n      });\n\n      Garnish.requestAnimationFrame(() => {\n        $iframe[0].contentWindow.document.open();\n        $iframe[0].contentWindow.document.write(html);\n        $iframe[0].contentWindow.document.close();\n        this.onResponse();\n      });\n    },\n\n    handleError: function () {\n      this.onResponse();\n    },\n\n    onResponse: function () {\n      this.loading = false;\n\n      if (this.checkAgain) {\n        this.checkAgain = false;\n        this.updateIframe();\n      }\n    },\n\n    _getClone: function ($field) {\n      var $clone = $field.clone();\n\n      // clone() won't account for input values that have changed since the original HTML set them\n      Garnish.copyInputValues($field, $clone);\n\n      // Remove any id= attributes\n      $clone.attr('id', '');\n      $clone.find('[id]').attr('id', '');\n\n      return $clone;\n    },\n\n    _onDragStart: function () {\n      this.dragStartEditorWidth = this.editorWidthInPx;\n      this.$previewContainer.addClass('dragging');\n    },\n\n    _onDrag: function () {\n      if (Craft.orientation === 'ltr') {\n        this.editorWidth = this.dragStartEditorWidth + this.dragger.mouseDistX;\n      } else {\n        this.editorWidth = this.dragStartEditorWidth - this.dragger.mouseDistX;\n      }\n\n      this.updateWidths();\n    },\n\n    _onDragStop: function () {\n      this.$previewContainer.removeClass('dragging');\n      Craft.setLocalStorage('LivePreview.editorWidth', this.editorWidth);\n    },\n\n    destroy: function () {\n      Craft.Preview.instances = Craft.Preview.instances.filter(\n        (o) => o !== this\n      );\n      this.base();\n    },\n  },\n  {\n    defaultEditorWidth: 0.33,\n    minEditorWidthInPx: 320,\n    instances: [],\n\n    defaults: {\n      trigger: '.livepreviewbtn',\n      fields: null,\n      extraFields: null,\n      previewUrl: null,\n      previewAction: null,\n      previewParams: {},\n    },\n  }\n);\n\nCraft.LivePreview.init = function (settings) {\n  Craft.livePreview = new Craft.LivePreview(settings);\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Password Input\n */\nCraft.PasswordInput = Garnish.Base.extend(\n  {\n    $passwordWrapper: null,\n    $passwordInput: null,\n    $textInput: null,\n    $currentInput: null,\n\n    $showPasswordToggle: null,\n    showingPassword: null,\n\n    init: function (passwordInput, settings) {\n      this.$passwordInput = $(passwordInput);\n      this.$passwordWrapper = this.$passwordInput.parent('.passwordwrapper');\n      this.settings = $.extend({}, Craft.PasswordInput.defaults, settings);\n\n      // Is this already a password input?\n      if (this.$passwordInput.data('passwordInput')) {\n        console.warn('Double-instantiating a password input on an element');\n        this.$passwordInput.data('passwordInput').destroy();\n      }\n\n      this.$passwordInput.data('passwordInput', this);\n\n      this.$showPasswordToggle = $(\n        '<button type=\"button\" class=\"invisible\" />'\n      );\n      this.$showPasswordToggle.addClass('password-toggle');\n      this.$showPasswordToggle.insertAfter(this.$passwordInput);\n\n      this.initInputFocusEvents(this.$passwordInput);\n      this.addListener(this.$showPasswordToggle, 'click', 'onClick');\n      this.hidePassword();\n\n      this.addListener(\n        this.$passwordWrapper.closest('form'),\n        'submit',\n        'hidePassword'\n      );\n    },\n\n    setCurrentInput: function ($input) {\n      if (this.$currentInput) {\n        // Swap the inputs, while preventing the focus animation\n        $input.insertAfter(this.$currentInput);\n        this.$currentInput.detach();\n        $input.trigger('focus');\n\n        // Restore the input value\n        $input.val(this.$currentInput.val());\n      }\n\n      this.$currentInput = $input;\n\n      this.addListener(\n        this.$currentInput,\n        'keypress,keyup,change,blur',\n        'onInputChange'\n      );\n    },\n\n    updateToggleLabel: function (label) {\n      this.$showPasswordToggle.text(label);\n    },\n\n    initInputFocusEvents: function ($input) {\n      this.addListener($input, 'focus', function () {\n        this.$passwordWrapper.addClass('focus');\n      });\n      this.addListener($input, 'blur', function () {\n        this.$passwordWrapper.removeClass('focus');\n      });\n    },\n\n    showPassword: function () {\n      if (this.showingPassword) {\n        return;\n      }\n\n      if (!this.$textInput) {\n        this.$textInput = this.$passwordInput.clone(true);\n        this.$textInput.attr({\n          type: 'text',\n          autocapitalize: 'off',\n        });\n        this.initInputFocusEvents(this.$textInput);\n      }\n\n      this.setCurrentInput(this.$textInput);\n      this.updateToggleLabel(Craft.t('app', 'Hide'));\n      this.showingPassword = true;\n    },\n\n    hidePassword: function () {\n      // showingPassword could be null, which is acceptable\n      if (this.showingPassword === false) {\n        return;\n      }\n\n      this.setCurrentInput(this.$passwordInput);\n      this.updateToggleLabel(Craft.t('app', 'Show'));\n      this.showingPassword = false;\n    },\n\n    togglePassword: function () {\n      if (this.showingPassword) {\n        this.hidePassword();\n      } else {\n        this.showPassword();\n      }\n\n      this.settings.onToggleInput(this.$currentInput);\n    },\n\n    onInputChange: function () {\n      if (this.$currentInput.val()) {\n        this.$showPasswordToggle.removeClass('invisible');\n      } else {\n        this.$showPasswordToggle.addClass('invisible');\n      }\n    },\n\n    onClick: function (ev) {\n      if (this.$currentInput[0].setSelectionRange) {\n        var selectionStart = this.$currentInput[0].selectionStart,\n          selectionEnd = this.$currentInput[0].selectionEnd;\n\n        this.togglePassword();\n        this.$currentInput[0].setSelectionRange(selectionStart, selectionEnd);\n      } else {\n        this.togglePassword();\n      }\n    },\n\n    destroy: function () {\n      this.$passwordInput.removeData('passwordInput');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      onToggleInput: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Preview\n */\nCraft.Preview = Garnish.Base.extend(\n  {\n    elementEditor: null,\n\n    $shade: null,\n    $editorContainer: null,\n    $editor: null,\n    $spinner: null,\n    $statusIcon: null,\n    $dragHandle: null,\n    $previewWrapper: null,\n    $previewContainer: null,\n    $previewSkipLink: null,\n    $bumperLink: null,\n    $notifier: null,\n    $iframeContainer: null,\n    $previewHeader: null,\n    $targetBtn: null,\n    $targetMenu: null,\n    $deviceTypeContainer: null,\n    $orientationBtn: null,\n    $refreshBtn: null,\n    $deviceMask: null,\n    $devicePreviewContainer: null,\n    $iframe: null,\n    iframeLoaded: false,\n    $tempInput: null,\n    $fieldPlaceholder: null,\n\n    isActive: false,\n    isVisible: false,\n    activeTarget: 0,\n\n    animationDuration: 'slow',\n\n    currentDeviceType: 'desktop',\n    deviceOrientation: null,\n    deviceWidth: '',\n    deviceHeight: '',\n    deviceMaskDimensions: {\n      phone: {\n        width: 375,\n        height: 753,\n      },\n      tablet: {\n        width: 768,\n        height: 1110,\n      },\n    },\n\n    draftId: null,\n    url: null,\n    fields: null,\n\n    iframeHeight: null,\n    scrollTop: null,\n    scrollLeft: null,\n\n    dragger: null,\n    dragStartEditorWidth: null,\n\n    _updateIframeProxy: null,\n\n    _editorWidth: null,\n    _editorWidthInPx: null,\n\n    init: function (elementEditor) {\n      this.elementEditor = elementEditor;\n\n      this._updateIframeProxy = this.updateIframe.bind(this);\n\n      this.$tempInput = $('<input/>', {\n        type: 'hidden',\n        name: '__PREVIEW_FIELDS__',\n        value: '1',\n      });\n      this.$fieldPlaceholder = $('<div/>');\n\n      // Set the initial editor width\n      this.editorWidth = Craft.getLocalStorage(\n        'LivePreview.editorWidth',\n        Craft.Preview.defaultEditorWidth\n      );\n\n      Craft.Preview.instances.push(this);\n    },\n\n    get editorWidth() {\n      return this._editorWidth;\n    },\n\n    get editorWidthInPx() {\n      return this._editorWidthInPx;\n    },\n\n    set editorWidth(width) {\n      var inPx;\n\n      // Is this getting set in pixels?\n      if (width >= 1) {\n        inPx = width;\n        width /= Garnish.$win.width();\n      } else {\n        inPx = Math.round(width * Garnish.$win.width());\n      }\n\n      // Make sure it's no less than the minimum\n      if (inPx < Craft.Preview.minEditorWidthInPx) {\n        inPx = Craft.Preview.minEditorWidthInPx;\n        width = inPx / Garnish.$win.width();\n      }\n\n      this._editorWidth = width;\n      this._editorWidthInPx = inPx;\n    },\n\n    open: function () {\n      if (this.isActive) {\n        return;\n      }\n\n      this.isActive = true;\n      this.trigger('beforeOpen');\n\n      $(document.activeElement).trigger('blur');\n\n      if (!this.$editor) {\n        const previewSkipLinkText = Craft.t('app', 'Skip to {title}', {\n          title: Craft.t('app', 'Top of preview'),\n        });\n\n        this.$shade = $('<div/>', {class: 'modal-shade dark'}).appendTo(\n          Garnish.$bod\n        );\n        this.$previewWrapper = $('<div/>', {\n          role: 'dialog',\n          'aria-modal': 'true',\n          'aria-labelledby': 'lp-preview-heading',\n        }).appendTo(Garnish.$bod);\n        this.$modalLabel = $('<h2/>', {\n          id: 'lp-preview-heading',\n          class: 'visually-hidden',\n          html: Craft.t('app', 'Preview'),\n        }).appendTo(this.$previewWrapper);\n        this.$editorContainer = $('<div/>', {\n          class: 'lp-editor-container',\n        }).appendTo(this.$previewWrapper);\n        this.$previewContainer = $('<div/>', {\n          class: 'lp-preview-container',\n          id: 'lp-preview-container',\n        }).appendTo(this.$previewWrapper);\n        this.$notifier = $('<span/>', {\n          class: 'visually-hidden',\n          'aria-live': 'assertive',\n        }).appendTo(this.$previewContainer);\n\n        var $editorHeader = $('<header/>', {class: 'flex'}).appendTo(\n          this.$editorContainer\n        );\n        this.$editor = $('<form/>', {class: 'lp-editor'}).appendTo(\n          this.$editorContainer\n        );\n        this.$dragHandle = $('<div/>', {class: 'lp-draghandle'}).appendTo(\n          this.$editorContainer\n        );\n        var $closeBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Close Preview'),\n        }).appendTo($editorHeader);\n        $('<div/>', {class: 'flex-grow'}).appendTo($editorHeader);\n        this.$spinner = $('<div/>', {\n          class: 'spinner hidden',\n          title: Craft.t('app', 'Saving'),\n        }).appendTo($editorHeader);\n        this.$statusIcon = $('<div/>', {class: 'invisible'}).appendTo(\n          $editorHeader\n        );\n        this.$statusMessage = $('<span/>', {\n          class: 'visually-hidden',\n          'aria-live': 'polite',\n        }).appendTo($editorHeader);\n        this.$previewSkipLink = $('<a/>', {\n          class: 'skip-link btn',\n          href: '#lp-preview-container',\n          html: previewSkipLinkText,\n        }).appendTo($editorHeader);\n\n        if (Craft.Pro) {\n          this.$previewHeader = $('<header/>', {\n            class: 'lp-preview-header',\n          }).appendTo(this.$previewContainer);\n\n          // Preview targets\n          if (this.elementEditor.settings.previewTargets.length > 1) {\n            this.$targetBtn = $('<button/>', {\n              type: 'button',\n              class: 'btn menubtn',\n              text: this.elementEditor.settings.previewTargets[0].label,\n            }).appendTo(this.$previewHeader);\n            this.$targetMenu = $('<div/>', {\n              class: 'menu lp-target-menu',\n            }).insertAfter(this.$targetBtn);\n            const $ul = $('<ul/>', {class: 'padded'}).appendTo(\n              this.$targetMenu\n            );\n            let $li, $a;\n            for (\n              let i = 0;\n              i < this.elementEditor.settings.previewTargets.length;\n              i++\n            ) {\n              $li = $('<li/>').appendTo($ul);\n              $a = $('<a/>', {\n                data: {target: i},\n                text: this.elementEditor.settings.previewTargets[i].label,\n                class: i === 0 ? 'sel' : null,\n              }).appendTo($li);\n            }\n            new Garnish.MenuBtn(this.$targetBtn, {\n              onOptionSelect: (option) => {\n                this.switchTarget($(option).data('target'));\n              },\n            });\n\n            $('<div class=\"flex-grow\"/>').appendTo(this.$previewHeader);\n          }\n\n          this._buildDeviceTypeFieldset();\n\n          $('<div class=\"flex-grow\"/>').appendTo(this.$previewHeader);\n          const $buttonContainer = $('<div class=\"buttons\"/>').appendTo(\n            this.$previewHeader\n          );\n\n          // Orientation toggle\n          this.$orientationBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn disabled',\n            'data-icon': 'rotate',\n            'aria-disabled': 'true',\n            text: Craft.t('app', 'Rotate'),\n            'aria-label': Craft.t('app', 'Rotate'),\n          }).appendTo($buttonContainer);\n          this.addListener(this.$orientationBtn, 'click', 'switchOrientation');\n\n          // Refresh button\n          this.$refreshBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn',\n            text: Craft.t('app', 'Refresh'),\n            'data-icon': 'refresh',\n          }).appendTo($buttonContainer);\n          this.addListener(this.$refreshBtn, 'click', () => {\n            this.updateIframe(false, true);\n          });\n\n          // Get the last stored orientation\n          this.deviceOrientation = Craft.getLocalStorage(\n            'LivePreview.orientation'\n          );\n        }\n\n        this.$iframeContainer = $('<div/>', {\n          class: 'lp-iframe-container',\n        }).appendTo(this.$previewContainer);\n        this.$devicePreviewContainer = $('<div/>', {\n          class: 'lp-device-preview-container',\n        }).appendTo(this.$iframeContainer);\n        this.$deviceMask = $('<div/>', {\n          class: 'lp-device-mask',\n        }).appendTo(this.$iframeContainer);\n\n        /* Prevents focus trap bug caused by iframe as last element */\n        this.$bumperLink = $('<a/>', {\n          class: 'skip-link btn lp-preview-container__bumper-link',\n          html: previewSkipLinkText,\n          href: '#lp-preview-container',\n        });\n        this.$bumperLink.appendTo(this.$previewContainer);\n\n        this.dragger = new Garnish.BaseDrag(this.$dragHandle, {\n          axis: Garnish.X_AXIS,\n          onDragStart: this._onDragStart.bind(this),\n          onDrag: this._onDrag.bind(this),\n          onDragStop: this._onDragStop.bind(this),\n        });\n\n        this.addListener($closeBtn, 'click', 'close');\n        this.addListener(this.$statusIcon, 'click', () => {\n          this.elementEditor.showStatusHud(this.$statusIcon);\n        });\n      }\n\n      // Set the sizes\n      this.handleWindowResize();\n      this.addListener(Garnish.$win, 'resize', 'handleWindowResize');\n\n      this.$editorContainer.css(Craft.left, -this.editorWidthInPx + 'px');\n      this.$previewContainer.css(Craft.right, -this.getIframeWidth());\n\n      // Find the fields, excluding nested fields\n      this.fields = [];\n      var $fields = $('#content .field').not($('#content .field .field'));\n\n      if ($fields.length) {\n        // Insert our temporary input before the first field so we know where to swap in the serialized form values\n        this.$tempInput.insertBefore($fields.get(0));\n\n        // Move all the fields into the editor rather than copying them\n        // so any JS that's referencing the elements won't break.\n        for (let i = 0; i < $fields.length; i++) {\n          let $field = $($fields[i]),\n            $clone = this._getClone($field);\n\n          // It's important that the actual field is added to the DOM *after* the clone,\n          // so any radio buttons in the field get deselected from the clone rather than the actual field.\n          this.$fieldPlaceholder.insertAfter($field);\n          $field.detach();\n          this.$fieldPlaceholder.replaceWith($clone);\n          $field.appendTo(this.$editor);\n\n          this.fields.push({\n            $field: $field,\n            $clone: $clone,\n          });\n        }\n      }\n\n      this.updateIframe();\n\n      this.elementEditor.on('update', this._updateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.trigger('open');\n    },\n\n    _getDeviceTypeTranslation: function (type) {\n      let translation;\n      switch (type) {\n        case 'phone':\n          translation = Craft.t('app', 'Mobile');\n          break;\n        case 'tablet':\n          translation = Craft.t('app', 'Tablet');\n          break;\n        default:\n          translation = Craft.t('app', 'Desktop');\n          break;\n      }\n      return translation;\n    },\n\n    _getDeviceOrientationTranslation: function (orientation) {\n      return orientation === 'portrait'\n        ? Craft.t('app', 'Portrait')\n        : Craft.t('app', 'Landscape');\n    },\n\n    _buildDeviceTypeFieldset: function () {\n      // Device type buttons\n      this.$deviceTypeContainer = $('<section/>', {\n        class: 'btngroup lp-device-type',\n        'aria-label': Craft.t('app', 'Device type'),\n      }).appendTo(this.$previewHeader);\n      $('<button/>', {\n        type: 'button',\n        class: 'btn lp-device-type-btn--desktop active',\n        title: Craft.t('app', 'Desktop'),\n        'aria-label': Craft.t('app', 'Desktop'),\n        'aria-pressed': 'true',\n        data: {\n          width: '',\n          height: '',\n          deviceType: 'desktop',\n        },\n      }).appendTo(this.$deviceTypeContainer);\n      $('<button/>', {\n        type: 'button',\n        class: 'btn lp-device-type-btn--tablet',\n        title: Craft.t('app', 'Tablet'),\n        'aria-label': Craft.t('app', 'Tablet'),\n        'aria-pressed': 'false',\n        data: {\n          width: 768,\n          height: 1024,\n          deviceType: 'tablet',\n        },\n      }).appendTo(this.$deviceTypeContainer);\n      $('<button/>', {\n        type: 'button',\n        class: 'btn lp-device-type-btn--phone',\n        title: Craft.t('app', 'Mobile'),\n        'aria-label': Craft.t('app', 'Mobile'),\n        'aria-pressed': 'false',\n        data: {\n          width: 375,\n          height: 667,\n          deviceType: 'phone',\n        },\n      }).appendTo(this.$deviceTypeContainer);\n\n      // Add functionality\n      this.deviceBtnGroup = new Craft.Listbox(this.$deviceTypeContainer, {\n        onChange: ($selectedOption) => {\n          this.switchDeviceType($selectedOption);\n        },\n      });\n    },\n\n    _activeTarget: function () {\n      return this.elementEditor.settings.previewTargets[this.activeTarget];\n    },\n\n    /**\n     * @returns {boolean}\n     * @private\n     */\n    _autoRefresh: function () {\n      const target = this._activeTarget();\n      return typeof typeof target.refresh === 'undefined' || !!target.refresh;\n    },\n\n    switchTarget: function (i) {\n      this.activeTarget = i;\n      this.$targetBtn.text(this.elementEditor.settings.previewTargets[i].label);\n      this.$targetMenu.find('a.sel').removeClass('sel');\n      this.$targetMenu.find('a').eq(i).addClass('sel');\n      this.updateIframe(true);\n      this.trigger('switchTarget', {\n        previewTarget: this.elementEditor.settings.previewTargets[i],\n      });\n    },\n\n    handleWindowResize: function () {\n      // Reset the width so the min width is enforced\n      this.editorWidth = this.editorWidth;\n\n      // Update the editor/iframe sizes\n      this.updateWidths();\n    },\n\n    slideIn: function () {\n      if (!this.isActive || this.isVisible) {\n        return;\n      }\n\n      $('html').addClass('noscroll');\n      this.$shade.velocity('fadeIn');\n\n      this.$editorContainer\n        .show()\n        .velocity('stop')\n        .animateLeft(\n          0,\n          Garnish.getUserPreferredAnimationDuration(this.animationDuration),\n          () => {\n            this.trigger('slideIn');\n            Garnish.$win.trigger('resize');\n          }\n        );\n\n      this.$previewContainer\n        .show()\n        .velocity('stop')\n        .animateRight(\n          0,\n          Garnish.getUserPreferredAnimationDuration(this.animationDuration)\n        );\n\n      this.isVisible = true;\n\n      Garnish.uiLayerManager.addLayer(this.$previewWrapper);\n      Garnish.hideModalBackgroundLayers();\n      Craft.setFocusWithin(this.$previewWrapper);\n      Craft.trapFocusWithin(this.$previewWrapper);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.close();\n      });\n    },\n\n    close: function () {\n      if (!this.isActive || !this.isVisible) {\n        return;\n      }\n\n      this.trigger('beforeClose');\n\n      $('html').removeClass('noscroll');\n\n      this.removeListener(Garnish.$win, 'resize');\n      Garnish.uiLayerManager.removeLayer();\n      Garnish.resetModalBackgroundLayerVisibility();\n\n      // Remove our temporary input and move the preview fields back into place\n      this.$tempInput.detach();\n      this.moveFieldsBack();\n\n      // Delay shade fade-out when animation is present\n      if (Garnish.prefersReducedMotion()) {\n        this.$shade.velocity('fadeOut');\n      } else {\n        this.$shade.delay(200).velocity('fadeOut');\n      }\n\n      this.$editorContainer\n        .velocity('stop')\n        .animateLeft(\n          -this.editorWidthInPx,\n          Garnish.getUserPreferredAnimationDuration(this.animationDuration),\n          () => {\n            for (var i = 0; i < this.fields.length; i++) {\n              this.fields[i].$newClone.remove();\n            }\n            this.$editorContainer.hide();\n            this.trigger('slideOut');\n          }\n        );\n\n      this.$previewContainer\n        .velocity('stop')\n        .animateRight(\n          -this.getIframeWidth(),\n          Garnish.getUserPreferredAnimationDuration(this.animationDuration),\n          () => {\n            this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n            this.$previewContainer.hide();\n          }\n        );\n\n      this.elementEditor.off('update', this._updateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      if (this.elementEditor.$previewBtn) {\n        this.elementEditor.$previewBtn.focus();\n      }\n\n      this.isActive = false;\n      this.isVisible = false;\n      this.trigger('close');\n    },\n\n    moveFieldsBack: function () {\n      for (var i = 0; i < this.fields.length; i++) {\n        var field = this.fields[i];\n        field.$newClone = this._getClone(field.$field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter(field.$field);\n        field.$field.detach();\n        this.$fieldPlaceholder.replaceWith(field.$newClone);\n        field.$clone.replaceWith(field.$field);\n      }\n\n      Garnish.$win.trigger('resize');\n      Garnish.$doc.trigger('scroll');\n    },\n\n    getIframeWidth: function () {\n      return Garnish.$win.width() - this.editorWidthInPx;\n    },\n\n    updateWidths: function () {\n      this.$editorContainer.css('width', this.editorWidthInPx + 'px');\n      this.$previewContainer.width(this.getIframeWidth());\n      if (this._devicePreviewIsActive()) {\n        this.updateDevicePreview();\n      }\n    },\n\n    _useIframeResizer: function () {\n      return Craft.previewIframeResizerOptions !== false;\n    },\n\n    /**\n     * @param {boolean} [resetScroll=false]\n     * @param {boolean} [refresh]\n     */\n    updateIframe: function (resetScroll, refresh) {\n      if (!this.isActive) {\n        return false;\n      }\n\n      // Ignore non-boolean resetScroll values\n      resetScroll = resetScroll === true;\n\n      // If the draft ID has changed or there's no iframe, we definitely need to refresh\n      if (\n        this.draftId !== (this.draftId = this.elementEditor.settings.draftId) ||\n        !this.$iframe\n      ) {\n        refresh = true;\n      }\n\n      const target = this._activeTarget();\n      if (typeof refresh === 'undefined') {\n        refresh = resetScroll || this._autoRefresh();\n      }\n\n      this.trigger('beforeUpdateIframe', {\n        previewTarget: target,\n        resetScroll: resetScroll,\n        refresh: refresh,\n      });\n\n      // If this is an existing preview target, make sure it wants to be refreshed automatically\n      if (!refresh) {\n        this.slideIn();\n        return;\n      }\n\n      this.elementEditor\n        .getTokenizedPreviewUrl(target.url, 'x-craft-live-preview')\n        .then((url) => {\n          // Maintain the current scroll position?\n          let sameHost;\n          if (resetScroll) {\n            this.scrollTop = null;\n            this.scrollLeft = null;\n          } else if (this.iframeLoaded && this.$iframe) {\n            if (this._useIframeResizer()) {\n              this.iframeHeight = this.$iframe.height();\n              this.scrollTop = this.$iframeContainer.scrollTop();\n              this.scrollLeft = this.$iframeContainer.scrollLeft();\n            } else {\n              sameHost = Craft.isSameHost(url);\n              if (sameHost && this.$iframe[0].contentWindow) {\n                this.scrollTop = $(\n                  this.$iframe[0].contentWindow.document\n                ).scrollTop();\n\n                this.scrollLeft = $(\n                  this.$iframe[0].contentWindow.document\n                ).scrollLeft();\n              }\n            }\n          }\n\n          this.iframeLoaded = false;\n\n          var $iframe = $('<iframe/>', {\n            class: 'lp-preview',\n            frameborder: 0,\n            src: url,\n            title: Craft.t('app', 'Preview'),\n          });\n\n          if (this.$iframe) {\n            this.$iframe.replaceWith($iframe);\n          } else {\n            $iframe.appendTo(this.$devicePreviewContainer);\n          }\n\n          // Keep the iframe height consistent with its content\n          if (this._useIframeResizer()) {\n            if (!resetScroll && this.iframeHeight !== null) {\n              $iframe.height(this.iframeHeight);\n              this.$iframeContainer.scrollTop(this.scrollTop);\n              this.$iframeContainer.scrollLeft(this.scrollLeft);\n            }\n\n            iFrameResize(\n              $.extend(\n                {\n                  checkOrigin: false,\n                  // Allow iframe scrolling until we've successfully initialized the resizer\n                  scrolling: true,\n                  onInit: (iframe) => {\n                    this.iframeLoaded = true;\n                    this.iframeHeight = null;\n                    this.scrollTop = null;\n                    this.scrollLeft = null;\n                    iframe.scrolling = 'no';\n                  },\n                },\n                Craft.previewIframeResizerOptions || {}\n              ),\n              $iframe[0]\n            );\n          } else {\n            $iframe.on('load', () => {\n              this.iframeLoaded = true;\n              if (!resetScroll && sameHost) {\n                if (this.scrollTop !== null) {\n                  $($iframe[0].contentWindow.document).scrollTop(\n                    this.scrollTop\n                  );\n                }\n\n                if (this.scrollLeft !== null) {\n                  $($iframe[0].contentWindow.document).scrollLeft(\n                    this.scrollLeft\n                  );\n                }\n              }\n            });\n          }\n\n          this.url = url;\n          this.$iframe = $iframe;\n\n          if (this._devicePreviewIsActive()) {\n            this.updateDevicePreview();\n          }\n\n          this.trigger('afterUpdateIframe', {\n            previewTarget:\n              this.elementEditor.settings.previewTargets[this.activeTarget],\n            $iframe: this.$iframe,\n          });\n\n          this.slideIn();\n        });\n    },\n\n    _devicePreviewIsActive: function () {\n      return this.currentDeviceType !== 'desktop';\n    },\n\n    _updateNotifier: function () {\n      this.$notifier.html = '';\n\n      const translation =\n        this.currentDeviceType === 'desktop'\n          ? 'Previewing {type} device'\n          : 'Previewing {type} device in {orientation}';\n      let params = {\n        type: this._getDeviceTypeTranslation(this.currentDeviceType),\n      };\n\n      if (this.currentDeviceType !== 'desktop') {\n        params = {\n          ...params,\n          ...{\n            orientation: this._getDeviceOrientationTranslation(\n              this.deviceOrientation\n            ),\n          },\n        };\n      }\n\n      const message = Craft.t('app', translation, params);\n\n      setTimeout(() => {\n        this.$notifier.text(message);\n      }, 200);\n    },\n\n    switchDeviceType: function ($option) {\n      this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n\n      const newDeviceType = $option.data('deviceType');\n      // Bail if we’re just smashing the same button\n      if (newDeviceType === this.currentDeviceType) {\n        return false;\n      }\n\n      // Store new device type data\n      this.currentDeviceType = newDeviceType;\n      this.deviceWidth = $option.data('width');\n      this.deviceHeight = $option.data('height');\n\n      if (this.currentDeviceType === 'desktop') {\n        // Disable the orientation button\n        this.$orientationBtn.addClass('disabled').attr('aria-disabled', 'true');\n\n        this.$iframeContainer.removeClass(\n          'lp-iframe-container--has-device-preview'\n        );\n      } else {\n        // Enable the orientation button\n        this.$orientationBtn\n          .removeClass('disabled')\n          .removeAttr('aria-disabled');\n\n        this.$iframeContainer.addClass(\n          'lp-iframe-container--has-device-preview'\n        );\n      }\n\n      // Add the tablet class if needed\n      if (this.currentDeviceType === 'tablet') {\n        this.$iframeContainer.addClass('lp-iframe-container--tablet');\n      } else {\n        this.$iframeContainer.removeClass('lp-iframe-container--tablet');\n      }\n\n      this._updateNotifier();\n\n      if (this.currentDeviceType !== 'desktop') {\n        this.updateDevicePreview();\n      }\n    },\n\n    switchOrientation: function () {\n      if (!this._devicePreviewIsActive()) {\n        return false;\n      }\n\n      // Switch to whichever orientation is currently not stored\n      if (!this.deviceOrientation || this.deviceOrientation === 'portrait') {\n        this.deviceOrientation = 'landscape';\n      } else {\n        this.deviceOrientation = 'portrait';\n      }\n\n      // Store the new one\n      Craft.setLocalStorage('LivePreview.orientation', this.deviceOrientation);\n\n      // Allow the animation to take place\n      this.$iframeContainer.addClass('lp-iframe-container--rotating');\n\n      // Update the device preview\n      this.updateDevicePreview();\n      this._updateNotifier();\n\n      setTimeout(() => {\n        this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n      }, 300);\n    },\n\n    updateDevicePreview: function () {\n      // Figure out the best zoom\n      let hZoom = 1;\n      let wZoom = 1;\n      let zoom = 1;\n      let previewHeight = this.$previewContainer.height() - 50 - 48; // 50px for the header bar and 24px clearance\n      let previewWidth = this.$previewContainer.width() - 48;\n      let maskHeight = this.deviceMaskDimensions[this.currentDeviceType].height;\n      let maskWidth = this.deviceMaskDimensions[this.currentDeviceType].width;\n\n      if (this.deviceOrientation === 'landscape') {\n        if (previewWidth < maskHeight) {\n          hZoom = previewWidth / maskHeight;\n        }\n        if (previewHeight < maskWidth) {\n          wZoom = previewHeight / maskWidth;\n        }\n      } else {\n        if (previewHeight < maskHeight) {\n          hZoom = previewHeight / maskHeight;\n        }\n        if (previewWidth < maskWidth) {\n          wZoom = previewWidth / maskWidth;\n        }\n      }\n\n      zoom = hZoom;\n      if (wZoom < hZoom) {\n        zoom = wZoom;\n      }\n\n      // Figure out the css values\n      const translate = -(100 / zoom / 2);\n      const rotationDeg =\n        this.deviceOrientation === 'landscape' ? '-90deg' : '0deg';\n\n      // Apply first to the device mask\n      this.$deviceMask.css({\n        width: this.deviceMaskDimensions[this.currentDeviceType].width + 'px',\n        height: this.deviceMaskDimensions[this.currentDeviceType].height + 'px',\n        transform:\n          'scale(' +\n          zoom +\n          ') translate(' +\n          translate +\n          '%, ' +\n          translate +\n          '%) rotate(' +\n          rotationDeg +\n          ')',\n      });\n\n      if (this.deviceOrientation === 'landscape') {\n        this.$devicePreviewContainer.css({\n          width: this.deviceHeight + 'px',\n          height: this.deviceWidth + 'px',\n          transform:\n            'scale(' +\n            zoom +\n            ') translate(' +\n            translate +\n            '%, ' +\n            translate +\n            '%)',\n          marginTop: 0,\n          marginLeft: '-' + 12 * zoom + 'px',\n        });\n      } else {\n        this.$devicePreviewContainer.css({\n          width: this.deviceWidth + 'px',\n          height: this.deviceHeight + 'px',\n          transform:\n            'scale(' +\n            zoom +\n            ') translate(' +\n            translate +\n            '%, ' +\n            translate +\n            '%)',\n          marginTop: '-' + 12 * zoom + 'px',\n          marginLeft: 0,\n        });\n      }\n    },\n\n    _getClone: function ($field) {\n      var $clone = $field.clone();\n\n      // clone() won't account for input values that have changed since the original HTML set them\n      Garnish.copyInputValues($field, $clone);\n\n      // Remove any id= attributes\n      $clone.attr('id', '');\n      $clone.find('[id]').attr('id', '');\n\n      // Disable anything with a name attribute\n      $clone.find('[name]').prop('disabled', true);\n\n      return $clone;\n    },\n\n    _onDragStart: function () {\n      this.dragStartEditorWidth = this.editorWidthInPx;\n      this.$previewContainer.addClass('dragging');\n    },\n\n    _onDrag: function () {\n      if (Craft.orientation === 'ltr') {\n        this.editorWidth = this.dragStartEditorWidth + this.dragger.mouseDistX;\n      } else {\n        this.editorWidth = this.dragStartEditorWidth - this.dragger.mouseDistX;\n      }\n\n      this.updateWidths();\n    },\n\n    _onDragStop: function () {\n      this.$previewContainer.removeClass('dragging');\n      Craft.setLocalStorage('LivePreview.editorWidth', this.editorWidth);\n    },\n\n    destroy: function () {\n      Craft.Preview.instances = Craft.Preview.instances.filter(\n        (o) => o !== this\n      );\n      this.base();\n    },\n  },\n  {\n    defaultEditorWidth: 0.33,\n    minEditorWidthInPx: 320,\n    instances: [],\n\n    refresh: function () {\n      for (preview of Craft.Preview.instances) {\n        preview.updateIframe();\n      }\n      for (preview of Craft.LivePreview.instances) {\n        preview.forceUpdateIframe();\n      }\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Preview File Modal\n */\nCraft.PreviewFileModal = Garnish.Modal.extend(\n  {\n    assetId: null,\n    $spinner: null,\n    $triggerElement: null,\n    $bumperButtonStart: null,\n    $bumperButtonEnd: null,\n    elementSelect: null,\n    type: null,\n    loaded: null,\n    requestId: 0,\n\n    /**\n     * Initialize the preview file modal.\n     * @returns {*|void}\n     */\n    init: function (assetId, elementSelect, settings) {\n      settings = $.extend(this.defaultSettings, settings);\n      this.$triggerElement = Garnish.getFocusedElement();\n\n      settings.onHide = this._onHide.bind(this);\n\n      if (Craft.PreviewFileModal.openInstance) {\n        var instance = Craft.PreviewFileModal.openInstance;\n\n        if (instance.assetId !== assetId) {\n          instance.loadAsset(\n            assetId,\n            settings.startingWidth,\n            settings.startingHeight\n          );\n          instance.elementSelect = elementSelect;\n        }\n\n        return this.destroy();\n      }\n\n      Craft.PreviewFileModal.openInstance = this;\n      this.elementSelect = elementSelect;\n\n      this.$container = $('<div class=\"modal previewmodal loading\"/>').appendTo(\n        Garnish.$bod\n      );\n\n      this.base(\n        this.$container,\n        $.extend(\n          {\n            resizable: true,\n          },\n          settings\n        )\n      );\n\n      // Cut the flicker, just show the nice person the preview.\n      if (this.$container) {\n        this.$container.velocity('stop');\n        this.$container.show().css('opacity', 1);\n\n        this.$shade.velocity('stop');\n        this.$shade.show().css('opacity', 1);\n\n        Garnish.setFocusWithin(this.$container);\n      }\n\n      // Add bumper elements to maintain focus trap\n      this.$bumperButtonStart = Craft.ui.createButton({\n        html: Craft.t('app', 'Close Preview'),\n        class: 'skip-link',\n      });\n\n      this.addListener(this.$bumperButtonStart, 'click', () => {\n        this.hide();\n      });\n      this.$bumperButtonEnd = this.$bumperButtonStart.clone(true);\n\n      this.loadAsset(assetId, settings.startingWidth, settings.startingHeight);\n    },\n\n    /**\n     * When hiding, remove all traces and focus last focused element.\n     * @private\n     */\n    _onHide: function () {\n      Craft.PreviewFileModal.openInstance = null;\n      if (this.elementSelect) {\n        this.elementSelect.focusItem(this.elementSelect.$focusedItem);\n      } else if (this.$triggerElement && this.$triggerElement.length) {\n        this.$triggerElement.trigger('focus');\n      }\n\n      this.$shade.remove();\n\n      return this.destroy();\n    },\n\n    _addBumperButtons: function () {\n      this.$container\n        .prepend(this.$bumperButtonStart)\n        .append(this.$bumperButtonEnd);\n    },\n\n    _addModalName: function () {\n      const headingId = 'preview-heading';\n\n      $('<h1/>', {\n        class: 'visually-hidden',\n        id: headingId,\n        text: Craft.t('app', 'Preview file'),\n      }).prependTo(this.$container);\n\n      this.$container.attr('aria-labelledby', headingId);\n    },\n\n    /**\n     * Disappear immediately forever.\n     * @returns {boolean}\n     */\n    selfDestruct: function () {\n      var instance = Craft.PreviewFileModal.openInstance;\n\n      instance.hide();\n      instance.$shade.remove();\n      instance.destroy();\n\n      Craft.PreviewFileModal.openInstance = null;\n      Craft.focalPoint.destruct();\n      Craft.focalPoint = null;\n\n      return true;\n    },\n\n    /**\n     * Load an asset, using starting width and height, if applicable\n     * @param {number} assetId\n     * @param {number} [startingWidth]\n     * @param {number} [startingHeight]\n     */\n    loadAsset: function (assetId, startingWidth, startingHeight) {\n      this.assetId = assetId;\n\n      this.$container.empty();\n      this.loaded = false;\n\n      this.desiredHeight = null;\n      this.desiredWidth = null;\n\n      var containerHeight = Garnish.$win.height() * 0.66;\n      var containerWidth = Math.min(\n        (containerHeight / 3) * 4,\n        Garnish.$win.width() - this.settings.minGutter * 2\n      );\n      containerHeight = (containerWidth / 4) * 3;\n\n      if (startingWidth && startingHeight) {\n        var ratio = startingWidth / startingHeight;\n        containerWidth = Math.min(\n          startingWidth,\n          Garnish.$win.width() - this.settings.minGutter * 2\n        );\n        containerHeight = Math.min(\n          containerWidth / ratio,\n          Garnish.$win.height() - this.settings.minGutter * 2\n        );\n        containerWidth = containerHeight * ratio;\n\n        // This might actually have put width over the viewport limits, so doublecheck\n        if (\n          containerWidth >\n          Math.min(\n            startingWidth,\n            Garnish.$win.width() - this.settings.minGutter * 2\n          )\n        ) {\n          containerWidth = Math.min(\n            startingWidth,\n            Garnish.$win.width() - this.settings.minGutter * 2\n          );\n          containerHeight = containerWidth / ratio;\n        }\n      }\n\n      this._resizeContainer(containerWidth, containerHeight);\n\n      this.$spinner = $('<div class=\"spinner centeralign\"></div>').appendTo(\n        this.$container\n      );\n      var top =\n          this.$container.height() / 2 - this.$spinner.height() / 2 + 'px',\n        left = this.$container.width() / 2 - this.$spinner.width() / 2 + 'px';\n\n      this.$spinner.css({left: left, top: top, position: 'absolute'});\n      this.requestId++;\n\n      let data = {assetId: assetId, requestId: this.requestId};\n      let onResponse = () => {\n        this.$container.removeClass('loading');\n        this.$spinner.remove();\n        this.loaded = true;\n      };\n      Craft.sendActionRequest('POST', 'assets/preview-file', {data})\n        .then((response) => {\n          onResponse();\n\n          if (response.data.requestId != this.requestId) {\n            return;\n          }\n\n          if (!response.data.previewHtml) {\n            this.$container.addClass('zilch');\n            this.$container.append(\n              $('<p/>', {text: Craft.t('app', 'No preview available.')})\n            );\n            this._addBumperButtons();\n            return;\n          }\n\n          this.$container.removeClass('zilch');\n          this.$container.attr('data-asset-id', this.assetId);\n          this.$container.append(response.data.previewHtml);\n          this._addBumperButtons();\n          this._addModalName();\n          Craft.appendHeadHtml(response.data.headHtml);\n          Craft.appendBodyHtml(response.data.bodyHtml);\n        })\n        .catch(({response}) => {\n          onResponse();\n          Craft.cp.displayError(response.data.message);\n          this.hide();\n        });\n    },\n\n    /**\n     * Resize the container to specified dimensions\n     * @param {number} containerWidth\n     * @param {number} containerHeight\n     * @private\n     */\n    _resizeContainer: function (containerWidth, containerHeight) {\n      this.$container.css({\n        width: containerWidth,\n        'min-width': containerWidth,\n        'max-width': containerWidth,\n        height: containerHeight,\n        'min-height': containerHeight,\n        'max-height': containerHeight,\n        top: (Garnish.$win.height() - containerHeight) / 2,\n        left: (Garnish.$win.width() - containerWidth) / 2,\n      });\n    },\n  },\n  {\n    defaultSettings: {\n      startingWidth: null,\n      startingHeight: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.ProgressBar = Garnish.Base.extend({\n  $progressBar: null,\n  $innerProgressBar: null,\n  $progressBarStatus: null,\n\n  _itemCount: 0,\n  _processedItemCount: 0,\n  _displaySteps: false,\n\n  init: function ($element, displaySteps) {\n    if (displaySteps) {\n      this._displaySteps = true;\n    }\n\n    this.$progressBar = $('<div class=\"progressbar pending hidden\"/>').appendTo(\n      $element\n    );\n    this.$innerProgressBar = $('<div class=\"progressbar-inner\"/>').appendTo(\n      this.$progressBar\n    );\n    this.$progressBarStatus = $(\n      '<div class=\"progressbar-status hidden\" />'\n    ).insertAfter(this.$progressBar);\n\n    this.resetProgressBar();\n  },\n\n  /**\n   * Reset the progress bar\n   */\n  resetProgressBar: function () {\n    // Since setting the progress percentage implies that there is progress to be shown\n    // It removes the pending class - we must add it back.\n    this.setProgressPercentage(100);\n    this.$progressBar.addClass('pending');\n\n    // Reset all the counters\n    this.setItemCount(1);\n    this.setProcessedItemCount(0);\n    this.$progressBarStatus.html('');\n\n    if (this._displaySteps) {\n      this.$progressBar.addClass('has-status');\n    }\n  },\n\n  /**\n   * Fade to invisible, hide it using a class and reset opacity to visible\n   */\n  hideProgressBar: function () {\n    this.$progressBar.addClass('hidden');\n    this.$progressBarStatus.addClass('hidden');\n  },\n\n  showProgressBar: function () {\n    this.$progressBar.removeClass('hidden');\n    this.$progressBarStatus.removeClass('hidden');\n  },\n\n  setItemCount: function (count) {\n    this._itemCount = count;\n  },\n\n  incrementItemCount: function (count) {\n    this._itemCount += count;\n  },\n\n  setProcessedItemCount: function (count) {\n    this._processedItemCount = count;\n  },\n\n  incrementProcessedItemCount: function (count) {\n    this._processedItemCount += count;\n  },\n\n  updateProgressBar: function () {\n    // Only fools would allow accidental division by zero.\n    this._itemCount = Math.max(this._itemCount, 1);\n\n    var width = Math.min(\n      100,\n      Math.round((100 * this._processedItemCount) / this._itemCount)\n    );\n\n    this.setProgressPercentage(width);\n\n    if (this._displaySteps) {\n      this.$progressBarStatus.html(\n        this._processedItemCount + ' / ' + this._itemCount\n      );\n    }\n  },\n\n  setProgressPercentage: function (percentage, animate) {\n    if (percentage === 0) {\n      this.$progressBar.addClass('pending');\n    } else {\n      this.$progressBar.removeClass('pending');\n\n      if (animate) {\n        this.$innerProgressBar\n          .velocity('stop')\n          .velocity({width: percentage + '%'}, 'fast');\n      } else {\n        this.$innerProgressBar.velocity('stop').width(percentage + '%');\n      }\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.PromptHandler = Garnish.Base.extend({\n  modal: null,\n  $modalContainerDiv: null,\n  $prompt: null,\n  $promptApplyToRemainingContainer: null,\n  $promptApplyToRemainingCheckbox: null,\n  $promptApplyToRemainingLabel: null,\n  $pomptChoices: null,\n\n  _prompts: [],\n  _promptBatchCallback: $.noop,\n  _promptBatchReturnData: [],\n  _promptBatchNum: 0,\n\n  resetPrompts: function () {\n    this._prompts = [];\n    this._promptBatchCallback = $.noop;\n    this._promptBatchReturnData = [];\n    this._promptBatchNum = 0;\n  },\n\n  addPrompt: function (prompt) {\n    this._prompts.push(prompt);\n  },\n\n  getPromptCount: function () {\n    return this._prompts.length;\n  },\n\n  showBatchPrompts: function (callback) {\n    this._promptBatchCallback = callback;\n    this._promptBatchReturnData = [];\n    this._promptBatchNum = 0;\n\n    this._showNextPromptInBatch();\n  },\n\n  _showNextPromptInBatch: function () {\n    var prompt = this._prompts[this._promptBatchNum].prompt,\n      remainingInBatch = this._prompts.length - (this._promptBatchNum + 1);\n\n    this._showPrompt(\n      prompt.message,\n      prompt.choices,\n      this._handleBatchPromptSelection.bind(this),\n      remainingInBatch\n    );\n  },\n\n  /**\n   * Handles a prompt choice selection.\n   *\n   * @param {string} choice\n   * @param {boolean} applyToRemaining\n   * @private\n   */\n  _handleBatchPromptSelection: function (choice, applyToRemaining) {\n    var prompt = this._prompts[this._promptBatchNum],\n      remainingInBatch = this._prompts.length - (this._promptBatchNum + 1);\n\n    // Record this choice\n    var choiceData = $.extend(prompt, {choice});\n    this._promptBatchReturnData.push(choiceData);\n\n    // Are there any remaining items in the batch?\n    if (remainingInBatch) {\n      // Get ready to deal with the next prompt\n      this._promptBatchNum++;\n\n      // Apply the same choice to the remaining items?\n      if (applyToRemaining) {\n        this._handleBatchPromptSelection(choice, true);\n      } else {\n        // Show the next prompt\n        this._showNextPromptInBatch();\n      }\n    } else {\n      // All done! Call the callback\n      if (typeof this._promptBatchCallback === 'function') {\n        this._promptBatchCallback(this._promptBatchReturnData);\n      }\n    }\n  },\n\n  /**\n   * @callback showPromptCallback\n   * @param {string} choice\n   * @param {boolean} applyToRemaining\n   */\n  /**\n   * Show the user prompt with a given message and choices, plus an optional \"Apply to remaining\" checkbox.\n   *\n   * @param {string} message\n   * @param {Array} choices\n   * @param {showPromptCallback} callback\n   * @param {number} itemsToGo\n   */\n  _showPrompt: function (message, choices, callback, itemsToGo) {\n    this._promptCallback = callback;\n\n    if (this.modal === null) {\n      this.modal = new Garnish.Modal({closeOtherModals: false});\n    }\n\n    if (this.$modalContainerDiv === null) {\n      this.$modalContainerDiv = $(\n        '<div class=\"modal fitted prompt-modal\"></div>'\n      )\n        .addClass()\n        .appendTo(Garnish.$bod);\n    }\n\n    this.$prompt = $('<div class=\"body\"></div>').appendTo(\n      this.$modalContainerDiv.empty()\n    );\n\n    this.$promptMessage = $('<p class=\"prompt-msg\"/>').appendTo(this.$prompt);\n\n    this.$promptChoices = $('<div class=\"options\"></div>').appendTo(\n      this.$prompt\n    );\n\n    this.$promptApplyToRemainingContainer = $(\n      '<label class=\"assets-applytoremaining\"/>'\n    )\n      .appendTo(this.$prompt)\n      .hide();\n    this.$promptApplyToRemainingCheckbox = $(\n      '<input type=\"checkbox\"/>'\n    ).appendTo(this.$promptApplyToRemainingContainer);\n    this.$promptApplyToRemainingLabel = $('<span/>').appendTo(\n      this.$promptApplyToRemainingContainer\n    );\n\n    this.$promptButtons = $('<div class=\"buttons right\"/>').appendTo(\n      this.$prompt\n    );\n\n    this.modal.setContainer(this.$modalContainerDiv);\n\n    this.$promptMessage.html(message);\n\n    let $cancelBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Cancel'),\n    }).appendTo(this.$promptButtons);\n    let $submitBtn = $('<button/>', {\n      type: 'submit',\n      class: 'btn submit disabled',\n      text: Craft.t('app', 'OK'),\n    }).appendTo(this.$promptButtons);\n\n    for (var i = 0; i < choices.length; i++) {\n      var $radioButtonHtml = $(\n          '<div><label><input type=\"radio\" name=\"promptAction\" value=\"' +\n            choices[i].value +\n            '\"/> ' +\n            choices[i].title +\n            '</label></div>'\n        ).appendTo(this.$promptChoices),\n        $radioButton = $radioButtonHtml.find('input');\n\n      this.addListener($radioButton, 'click', function () {\n        $submitBtn.removeClass('disabled');\n      });\n    }\n\n    this.addListener($submitBtn, 'activate', function (ev) {\n      var choice = $(ev.currentTarget)\n          .parents('.modal')\n          .find('input[name=promptAction]:checked')\n          .val(),\n        applyToRemaining = this.$promptApplyToRemainingCheckbox.prop('checked');\n\n      this._selectPromptChoice(choice, applyToRemaining);\n    });\n\n    this.addListener($cancelBtn, 'activate', function () {\n      var choice = 'cancel',\n        applyToRemaining = this.$promptApplyToRemainingCheckbox.prop('checked');\n\n      this._selectPromptChoice(choice, applyToRemaining);\n    });\n\n    if (itemsToGo) {\n      this.$promptApplyToRemainingContainer.show();\n      this.$promptApplyToRemainingLabel.html(\n        ' ' +\n          Craft.t('app', 'Apply this to the {number} remaining conflicts?', {\n            number: itemsToGo,\n          })\n      );\n    }\n\n    this.modal.show();\n    this.modal.removeListener(Garnish.Modal.$shade, 'click');\n    this.addListener(Garnish.Modal.$shade, 'click', '_cancelPrompt');\n  },\n\n  /**\n   * Handles when a user selects one of the prompt choices.\n   *\n   * @param {string} choice\n   * @param {boolean} applyToRemaining\n   * @private\n   */\n  _selectPromptChoice: function (choice, applyToRemaining) {\n    this.$prompt.fadeOut('fast', () => {\n      this.modal.hide();\n      this._promptCallback(choice, applyToRemaining);\n    });\n  },\n\n  /**\n   * Cancels the prompt.\n   */\n  _cancelPrompt: function () {\n    this._selectPromptChoice('cancel', true);\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Queue\n */\nCraft.Queue = Garnish.Base.extend({\n  running: false,\n  paused: false,\n  pausedForVisibility: false,\n  jobs: null,\n\n  get length() {\n    return this.jobs.length;\n  },\n\n  get isPaused() {\n    return this.paused || this.pausedForVisibility;\n  },\n\n  init: function () {\n    this.jobs = [];\n\n    Garnish.$doc.on('visibilitychange', () => {\n      if (this.pausedForVisibility && Craft.isVisible()) {\n        this.pausedForVisibility = false;\n        this._resume();\n      }\n    });\n  },\n\n  /**\n   * Adds a job to the queue.\n   * @param {function} job\n   * @returns {Promise}\n   */\n  push: function (job) {\n    return this._add(job, 'push');\n  },\n\n  /**\n   * Adds a job to the beginning of the queue.\n   * @param {function} job\n   * @returns {Promise}\n   */\n  unshift: function (job) {\n    return this._add(job, 'unshift');\n  },\n\n  pause: function () {\n    if (!this.paused) {\n      this.paused = true;\n      if (!this.pausedForVisibility) {\n        this.trigger('pause');\n      }\n    }\n  },\n\n  resume: function () {\n    if (this.paused) {\n      this.paused = false;\n      this._resume();\n    }\n  },\n\n  /**\n   * Adds a job to the queue.\n   * @param {function} job\n   * @param {string} method\n   * @returns {Promise}\n   * @private\n   */\n  _add: function (job, method) {\n    return new Promise((resolve, reject) => {\n      this.jobs[method](() => {\n        return new Promise((qResolve, qReject) => {\n          job()\n            .then((value) => {\n              // ...arguments doesn't work here :(\n              resolve(value);\n              qResolve();\n            })\n            .catch((value) => {\n              // ...arguments doesn't work here :(\n              reject(value);\n              qReject();\n            });\n        });\n      });\n\n      if (!this.running) {\n        this.trigger('beforeRun');\n        this.running = true;\n        this._exec();\n      }\n    });\n  },\n\n  clear: function () {\n    this.jobs.length = 0;\n  },\n\n  /**\n   * Runs the next job in the queue.\n   * @private\n   */\n  _exec: function () {\n    if (!this.jobs.length) {\n      this.running = false;\n      this.trigger('afterRun');\n      return;\n    }\n\n    if (!this.pausedForVisibility && !Craft.isVisible()) {\n      this.pausedForVisibility = true;\n      if (!this.paused) {\n        this.trigger('pause');\n      }\n    }\n\n    if (this.paused || this.pausedForVisibility) {\n      return;\n    }\n\n    this.trigger('beforeExec');\n    const job = this.jobs.shift();\n    job().finally(() => {\n      this.trigger('afterExec');\n      this._exec();\n    });\n  },\n\n  _resume: function () {\n    if (!this.isPaused) {\n      this.trigger('resume');\n      this._exec();\n    }\n  },\n});\n\nCraft.queue = new Craft.Queue();\n","(function ($) {\n  /** global: Craft */\n  /** global: Garnish */\n  /**\n   * Slide Picker\n   */\n  Craft.SlidePicker = Garnish.Base.extend(\n    {\n      min: null,\n      max: null,\n      totalSteps: null,\n      value: null,\n      label: null,\n      describedBy: null,\n\n      $container: null,\n      $buttons: null,\n\n      init: function (value, settings) {\n        this.setSettings(settings, Craft.SlidePicker.defaults);\n\n        this.$container = $('<div/>', {\n          class: 'slide-picker',\n          role: 'slider',\n          tabindex: 0,\n        });\n\n        this.refresh();\n        this.setValue(value, false);\n\n        this.addListener(this.$container, 'keydown', (ev) => {\n          switch (ev.keyCode) {\n            case Garnish.UP_KEY:\n              this.setValue(this.value + this.settings.step);\n              ev.preventDefault();\n              break;\n            case Garnish.DOWN_KEY:\n              this.setValue(this.value - this.settings.step);\n              ev.preventDefault();\n              break;\n            case Garnish.RIGHT_KEY:\n              if (Craft.orientation === 'ltr') {\n                this.setValue(this.value + this.settings.step);\n              } else {\n                this.setValue(this.value - this.settings.step);\n              }\n              ev.preventDefault();\n              break;\n            case Garnish.LEFT_KEY:\n              if (Craft.orientation === 'ltr') {\n                this.setValue(this.value - this.settings.step);\n              } else {\n                this.setValue(this.value + this.settings.step);\n              }\n              ev.preventDefault();\n              break;\n            case Garnish.HOME_KEY:\n              this.setValue(this.min);\n              ev.preventDefault();\n              break;\n            case Garnish.END_KEY:\n              this.setValue(this.max);\n              ev.preventDefault();\n              break;\n          }\n        });\n      },\n\n      refresh: function () {\n        // Figure out what the min/max values are\n        this.min = this._min();\n        this.max = this._max();\n        this.totalSteps = (this.max - this.min) / this.settings.step;\n\n        // Set label\n        this.label = this.settings.label;\n        this.describedBy = this.settings.describedBy;\n\n        if (!Number.isInteger(this.totalSteps)) {\n          throw 'Invalid SlidePicker config';\n        }\n\n        if (this.$buttons) {\n          this.$buttons.remove();\n        }\n\n        this.$container.attr('aria-valuemin', this.min);\n        this.$container.attr('aria-valuemax', this.max);\n\n        if (this.label) {\n          this.$container.attr('aria-label', this.label);\n        }\n\n        if (this.describedBy) {\n          this.$container.attr('aria-describedby', this.describedBy);\n        }\n\n        this.$buttons = $();\n\n        // Create the buttons\n        for (\n          let value = this.min;\n          value <= this.max;\n          value += this.settings.step\n        ) {\n          this.$buttons = this.$buttons.add(\n            $('<a/>', {\n              title: this.settings.valueLabel(value),\n              data: {value},\n            })\n          );\n        }\n\n        this.$buttons.appendTo(this.$container);\n\n        if (this.value !== null) {\n          let value = this.value;\n          this.value = null;\n          this.setValue(value, false);\n        }\n\n        this.addListener(this.$buttons, 'mouseover', (ev) => {\n          this.$buttons.removeClass('active-hover last-active-hover');\n          $(ev.currentTarget)\n            .addClass('active-hover last-active-hover')\n            .prevAll()\n            .addClass('active-hover');\n        });\n\n        this.addListener(this.$buttons, 'mouseout', () => {\n          this.$buttons.removeClass('active-hover');\n        });\n\n        this.addListener(this.$buttons, 'click', (ev) => {\n          this.setValue($.data(ev.currentTarget, 'value'));\n          ev.stopPropagation();\n          this.$container.focus();\n        });\n      },\n\n      setValue: function (value, triggerEvent) {\n        value = Math.max(Math.min(value, this.max), this.min);\n\n        if (this.value === (this.value = value)) {\n          return;\n        }\n\n        this.$container.attr({\n          'aria-valuenow': this.value,\n          'aria-valuetext': this.settings.valueLabel(this.value),\n        });\n\n        this.$buttons.removeClass('last-active active');\n        let $activeButton = this.$buttons.eq(\n          (this.value - this.min) / this.settings.step\n        );\n        $activeButton.add($activeButton.prevAll()).addClass('active');\n        $activeButton.addClass('last-active');\n\n        if (triggerEvent !== false) {\n          this.settings.onChange(value);\n        }\n      },\n\n      _min: function () {\n        if (typeof this.settings.min === 'function') {\n          return this.settings.min();\n        }\n        return this.settings.min;\n      },\n\n      _max: function () {\n        if (typeof this.settings.max === 'function') {\n          return this.settings.max();\n        }\n        return this.settings.max;\n      },\n    },\n    {\n      defaults: {\n        min: 0,\n        max: 100,\n        step: 10,\n        valueLabel: null,\n        onChange: $.noop,\n      },\n    }\n  );\n})(jQuery);\n","/** global: Garnish */\n\nCraft.SlideRuleInput = Garnish.Base.extend({\n  $container: null,\n  $options: null,\n  $selectedOption: null,\n  $input: null,\n  value: null,\n\n  startPositionX: null,\n\n  init: function (id, settings) {\n    this.setSettings(settings, Craft.SlideRuleInput.defaultSettings);\n\n    this.value = 0;\n    this.graduationsMin = -70;\n    this.graduationsMax = 70;\n    this.slideMin = -45;\n    this.slideMax = 45;\n\n    this.$container = $('#' + id);\n    this.$overlay = $('<div class=\"overlay\"></div>').appendTo(this.$container);\n    this.$cursor = $('<div class=\"cursor\"></div>').appendTo(this.$container);\n    this.$graduations = $('<div class=\"graduations\"></div>').appendTo(\n      this.$container\n    );\n    this.$graduationsUl = $('<ul></ul>').appendTo(this.$graduations);\n\n    this.$container.attr({\n      role: 'slider',\n      tabindex: '0',\n      'aria-valuemin': this.slideMin,\n      'aria-valuemax': this.slideMax,\n      'aria-valuenow': '0',\n      'aria-valuetext': Craft.t(\n        'app',\n        '{num, number} {num, plural, =1{degree} other{degrees}}',\n        {\n          num: 0,\n        }\n      ),\n    });\n\n    for (var i = this.graduationsMin; i <= this.graduationsMax; i++) {\n      var $li = $(\n        '<li class=\"graduation\" data-graduation=\"' +\n          i +\n          '\"><div class=\"label\">' +\n          i +\n          '</div></li>'\n      ).appendTo(this.$graduationsUl);\n\n      if (i % 5 === 0) {\n        $li.addClass('main-graduation');\n      }\n\n      if (i === 0) {\n        $li.addClass('selected');\n      }\n    }\n\n    this.$options = this.$container.find('.graduation');\n\n    this.addListener(this.$container, 'resize', this._handleResize.bind(this));\n    this.addListener(\n      this.$container,\n      'tapstart',\n      this._handleTapStart.bind(this)\n    );\n    this.addListener(Garnish.$bod, 'tapmove', this._handleTapMove.bind(this));\n    this.addListener(Garnish.$bod, 'tapend', this._handleTapEnd.bind(this));\n    this.addListener(\n      this.$container,\n      'keydown',\n      this._handleKeypress.bind(this)\n    );\n\n    // Set to zero\n\n    // this.setValue(0);\n\n    setTimeout(() => {\n      // (n -1) options because the border is placed on the left of the 10px box\n      this.graduationsCalculatedWidth = (this.$options.length - 1) * 10;\n      this.$graduationsUl.css(\n        'left',\n        -this.graduationsCalculatedWidth / 2 + this.$container.width() / 2\n      );\n    }, 50);\n  },\n\n  _handleResize: function () {\n    var left = this.valueToPosition(this.value);\n    this.$graduationsUl.css('left', left);\n  },\n\n  _handleKeypress: function (event) {\n    const current = parseInt(this.$container.attr('aria-valuenow'), 10);\n\n    switch (event.keyCode) {\n      case Garnish.UP_KEY:\n      case Garnish.RIGHT_KEY:\n        this.setValue(current + 1);\n        break;\n      case Garnish.DOWN_KEY:\n      case Garnish.LEFT_KEY:\n        this.setValue(current - 1);\n        break;\n      case Garnish.PAGE_UP_KEY:\n        this.setValue(current + 10);\n        break;\n      case Garnish.PAGE_DOWN_KEY:\n        this.setValue(current - 10);\n        break;\n      case Garnish.HOME_KEY:\n        this.setValue(this.slideMin);\n        break;\n      case Garnish.END_KEY:\n        this.setValue(this.slideMax);\n        break;\n    }\n\n    this.onChange();\n  },\n\n  _handleTapStart: function (ev, touch) {\n    ev.preventDefault();\n\n    this.startPositionX = touch.position.x;\n    this.startLeft = this.$graduationsUl.position().left;\n\n    this.dragging = true;\n    this.onStart();\n  },\n\n  _handleTapMove: function (ev, touch) {\n    if (this.dragging) {\n      ev.preventDefault();\n\n      var curX = this.startPositionX - touch.position.x;\n      var left = this.startLeft - curX;\n      var value = this.positionToValue(left);\n\n      this.setValue(value);\n\n      this.onChange();\n    }\n  },\n\n  setValue: function (value) {\n    var left = this.valueToPosition(value);\n    if (value < this.slideMin) {\n      value = this.slideMin;\n      left = this.valueToPosition(value);\n    } else if (value > this.slideMax) {\n      value = this.slideMax;\n      left = this.valueToPosition(value);\n    }\n\n    this.$graduationsUl.css('left', left);\n\n    if (value >= this.slideMin && value <= this.slideMax) {\n      this.$options.removeClass('selected');\n\n      $.each(this.$options, function (key, option) {\n        if ($(option).data('graduation') > 0) {\n          if ($(option).data('graduation') <= value) {\n            $(option).addClass('selected');\n          }\n        }\n        if ($(option).data('graduation') < 0) {\n          if ($(option).data('graduation') >= value) {\n            $(option).addClass('selected');\n          }\n        }\n\n        if ($(option).data('graduation') == 0) {\n          $(option).addClass('selected');\n        }\n      });\n    }\n\n    this.$container.attr({\n      'aria-valuenow': value,\n      'aria-valuetext': Craft.t(\n        'app',\n        '{num, number} {num, plural, =1{degree} other{degrees}}',\n        {num: parseInt(value, 10)}\n      ),\n    });\n    this.value = value;\n  },\n\n  _handleTapEnd: function (ev) {\n    if (this.dragging) {\n      ev.preventDefault();\n      this.dragging = false;\n      this.onEnd();\n    }\n  },\n\n  positionToValue: function (position) {\n    var scaleMin = this.graduationsMin * -1;\n    var scaleMax = (this.graduationsMin - this.graduationsMax) * -1;\n\n    return (\n      ((this.$graduations.width() / 2 + position * -1) /\n        this.graduationsCalculatedWidth) *\n        scaleMax -\n      scaleMin\n    );\n  },\n\n  valueToPosition: function (value) {\n    var scaleMin = this.graduationsMin * -1;\n    var scaleMax = (this.graduationsMin - this.graduationsMax) * -1;\n\n    return -(\n      ((value + scaleMin) * this.graduationsCalculatedWidth) / scaleMax -\n      this.$graduations.width() / 2\n    );\n  },\n\n  onStart: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onStart(this);\n    }\n  },\n\n  onChange: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onChange(this);\n    }\n  },\n\n  onEnd: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onEnd(this);\n    }\n  },\n\n  defaultSettings: {\n    onStart: $.noop,\n    onChange: $.noop,\n    onEnd: $.noop,\n  },\n});\n","(function ($) {\n  /** global: Craft */\n  /** global: Garnish */\n  /**\n   * Slide Picker\n   */\n  Craft.Slideout = Garnish.Base.extend(\n    {\n      $outerContainer: null,\n      $container: null,\n      $shade: null,\n      isOpen: false,\n\n      init: function (contents, settings) {\n        this.setSettings(settings, Craft.Slideout.defaults);\n\n        if (!Craft.useMobileStyles()) {\n          this.$shade = $('<div class=\"slideout-shade\"/>').appendTo(\n            Garnish.$bod\n          );\n\n          if (this.settings.closeOnShadeClick) {\n            this.addListener(this.$shade, 'click', (ev) => {\n              ev.stopPropagation();\n              this.close();\n            });\n          }\n        }\n\n        this.$outerContainer = $('<div/>', {\n          class: 'slideout-container hidden',\n        });\n        this.$container = $(\n          `<${this.settings.containerElement}/>`,\n          this.settings.containerAttributes\n        )\n          .attr('data-slideout', '')\n          .addClass('slideout')\n          .append(contents)\n          .data('slideout', this)\n          .appendTo(this.$outerContainer);\n\n        Garnish.addModalAttributes(this.$outerContainer);\n\n        if (Craft.useMobileStyles()) {\n          this.$container.addClass('so-mobile');\n        }\n\n        Craft.trapFocusWithin(this.$container);\n\n        if (this.settings.autoOpen) {\n          this.open();\n        }\n      },\n\n      open: function () {\n        if (this.isOpen) {\n          return;\n        }\n\n        this.setTriggerElement(document.activeElement);\n\n        this._cancelTransitionListeners();\n\n        // Move the shade + container to the end of <body> so they get the highest sub-z-indexes\n        if (this.$shade) {\n          this.$shade.appendTo(Garnish.$bod).show();\n        }\n\n        this.$outerContainer.appendTo(Garnish.$bod).removeClass('hidden');\n\n        if (Craft.useMobileStyles()) {\n          this.$container.css('top', '100vh');\n        } else {\n          this.$container.css(Garnish.ltr ? 'left' : 'right', '100vw');\n        }\n\n        this.$container.one('transitionend.slideout', () => {\n          Craft.setFocusWithin(this.$container);\n        });\n\n        if (this.$shade) {\n          this.$shade[0].offsetWidth;\n          this.$shade.addClass('so-visible');\n        }\n\n        this.$container[0].offsetWidth;\n        Craft.Slideout.addPanel(this);\n\n        this.enable();\n        Garnish.uiLayerManager.addLayer(this.$outerContainer);\n        Garnish.hideModalBackgroundLayers();\n\n        if (this.settings.closeOnEsc) {\n          Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n            this.close();\n          });\n        }\n\n        this.isOpen = true;\n        this.trigger('open');\n      },\n\n      setTriggerElement: function (trigger) {\n        this.settings.triggerElement = trigger;\n      },\n\n      close: function () {\n        if (!this.isOpen) {\n          return;\n        }\n\n        this.trigger('beforeClose');\n        this.disable();\n        this.isOpen = false;\n\n        this._cancelTransitionListeners();\n\n        if (this.$shade) {\n          this.$shade\n            .removeClass('so-visible')\n            .one('transitionend.slideout', () => {\n              this.$shade.hide();\n            });\n        }\n\n        Craft.Slideout.removePanel(this);\n        Garnish.uiLayerManager.removeLayer();\n        Garnish.resetModalBackgroundLayerVisibility();\n        this.$container.one('transitionend.slideout', () => {\n          this.$outerContainer.addClass('hidden');\n          this.trigger('close');\n        });\n\n        if (this.settings.triggerElement) {\n          this.settings.triggerElement.focus();\n        }\n      },\n\n      _cancelTransitionListeners: function () {\n        if (this.$shade) {\n          this.$shade.off('transitionend.slideout');\n        }\n\n        this.$container.off('transitionend.slideout');\n      },\n\n      /**\n       * Destroy\n       */\n      destroy: function () {\n        if (this.$shade) {\n          this.$shade.remove();\n          this.$shade = null;\n        }\n\n        this.$outerContainer.remove();\n        this.$outerContainer = null;\n        this.$container = null;\n\n        this.base();\n      },\n    },\n    {\n      defaults: {\n        containerElement: 'div',\n        containerAttributes: {},\n        autoOpen: true,\n        closeOnEsc: true,\n        closeOnShadeClick: true,\n        triggerElement: null,\n      },\n      openPanels: [],\n      addPanel: function (panel) {\n        Craft.Slideout.openPanels.unshift(panel);\n        if (Craft.useMobileStyles()) {\n          panel.$container.css('top', 0);\n        } else {\n          Craft.Slideout.updateStyles();\n        }\n      },\n      removePanel: function (panel) {\n        Craft.Slideout.openPanels = Craft.Slideout.openPanels.filter(\n          (m) => m !== panel\n        );\n        if (Craft.useMobileStyles()) {\n          panel.$container.css('top', '100vh');\n        } else {\n          panel.$container.css(Garnish.ltr ? 'left' : 'right', '100vw');\n          Craft.Slideout.updateStyles();\n        }\n      },\n      updateStyles: function () {\n        const totalPanels = Craft.Slideout.openPanels.length;\n        Craft.Slideout.openPanels.forEach((panel, i) => {\n          panel.$container.css(\n            Garnish.ltr ? 'left' : 'right',\n            `${50 * ((totalPanels - i) / totalPanels)}vw`\n          );\n        });\n\n        if (totalPanels !== 0) {\n          Garnish.$bod.addClass('no-scroll');\n        } else {\n          Garnish.$bod.removeClass('no-scroll');\n        }\n      },\n    }\n  );\n})(jQuery);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Slug Generator\n */\nCraft.SlugGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    sourceVal = sourceVal.replace(/<(.*?)>/g, '');\n\n    // Remove inner-word punctuation\n    sourceVal = sourceVal.replace(/['\"‘’“”\\[\\]\\(\\)\\{\\}:]/g, '');\n\n    // Make it lowercase\n    if (!Craft.allowUppercaseInSlug) {\n      sourceVal = sourceVal.toLowerCase();\n    }\n\n    if (Craft.limitAutoSlugsToAscii) {\n      // Convert extended ASCII characters to basic ASCII\n      sourceVal = Craft.asciiString(sourceVal, this.settings.charMap);\n    }\n\n    // Get the \"words\". Split on anything that is not alphanumeric.\n    // Reference: http://www.regular-expressions.info/unicode.html\n    var words = Craft.filterArray(\n      XRegExp.matchChain(sourceVal, [XRegExp('[\\\\p{L}\\\\p{N}\\\\p{M}]+')])\n    );\n\n    if (words.length) {\n      return words.join(Craft.slugWordSeparator);\n    } else {\n      return '';\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Structure class\n */\nCraft.Structure = Garnish.Base.extend(\n  {\n    id: null,\n\n    $container: null,\n    state: null,\n    structureDrag: null,\n\n    /**\n     * Init\n     */\n    init: function (id, container, settings) {\n      this.id = id;\n      this.$container = $(container);\n      this.setSettings(settings, Craft.Structure.defaults);\n\n      // Is this already a structure?\n      if (this.$container.data('structure')) {\n        console.warn('Double-instantiating a structure on an element');\n        this.$container.data('structure').destroy();\n      }\n\n      this.$container.data('structure', this);\n\n      this.state = {};\n\n      if (this.settings.storageKey) {\n        $.extend(\n          this.state,\n          Craft.getLocalStorage(this.settings.storageKey, {})\n        );\n      }\n\n      if (typeof this.state.collapsedElementIds === 'undefined') {\n        this.state.collapsedElementIds = [];\n      }\n\n      var $parents = this.$container.find('ul').prev('.row');\n\n      for (var i = 0; i < $parents.length; i++) {\n        var $row = $($parents[i]),\n          $li = $row.parent(),\n          $toggle = $(\n            '<div class=\"toggle\" title=\"' +\n              Craft.t('app', 'Show/hide children') +\n              '\"/>'\n          ).prependTo($row);\n\n        if (\n          $.inArray(\n            $row.children('.element').data('id'),\n            this.state.collapsedElementIds\n          ) !== -1\n        ) {\n          $li.addClass('collapsed');\n        }\n\n        this.initToggle($toggle);\n      }\n\n      if (this.settings.sortable) {\n        this.structureDrag = new Craft.StructureDrag(\n          this,\n          this.settings.maxLevels\n        );\n      }\n\n      if (this.settings.newChildUrl) {\n        this.initNewChildMenus(this.$container.find('.add'));\n      }\n    },\n\n    initToggle: function ($toggle) {\n      $toggle.on('click', (ev) => {\n        var $li = $(ev.currentTarget).closest('li'),\n          elementId = $li.children('.row').find('.element:first').data('id'),\n          viewStateKey = $.inArray(elementId, this.state.collapsedElementIds);\n\n        if ($li.hasClass('collapsed')) {\n          $li.removeClass('collapsed');\n\n          if (viewStateKey !== -1) {\n            this.state.collapsedElementIds.splice(viewStateKey, 1);\n          }\n        } else {\n          $li.addClass('collapsed');\n\n          if (viewStateKey === -1) {\n            this.state.collapsedElementIds.push(elementId);\n          }\n        }\n\n        if (this.settings.storageKey) {\n          Craft.setLocalStorage(this.settings.storageKey, this.state);\n        }\n      });\n    },\n\n    initNewChildMenus: function ($addBtns) {\n      this.addListener($addBtns, 'click', 'onNewChildMenuClick');\n    },\n\n    onNewChildMenuClick: function (ev) {\n      var $btn = $(ev.currentTarget);\n\n      if (!$btn.data('menubtn')) {\n        var elementId = $btn.parent().children('.element').data('id'),\n          newChildUrl = Craft.getUrl(\n            this.settings.newChildUrl,\n            'parentId=' + elementId\n          );\n\n        $(\n          '<div class=\"menu\"><ul><li><a href=\"' +\n            newChildUrl +\n            '\">' +\n            Craft.t('app', 'New child') +\n            '</a></li></ul></div>'\n        ).insertAfter($btn);\n\n        var menuBtn = new Garnish.MenuBtn($btn);\n        menuBtn.showMenu();\n      }\n    },\n\n    getIndent: function (level) {\n      return (\n        Craft.Structure.baseIndent + (level - 1) * Craft.Structure.nestedIndent\n      );\n    },\n\n    addElement: function ($element) {\n      var $li = $('<li data-level=\"1\"/>').appendTo(this.$container),\n        $row = $(\n          '<div class=\"row\" style=\"margin-' +\n            Craft.left +\n            ': -' +\n            Craft.Structure.baseIndent +\n            'px; padding-' +\n            Craft.left +\n            ': ' +\n            Craft.Structure.baseIndent +\n            'px;\">'\n        ).appendTo($li);\n\n      $row.append($element);\n\n      if (this.settings.sortable) {\n        $row.append(\n          '<a class=\"move icon\" title=\"' + Craft.t('app', 'Move') + '\"></a>'\n        );\n        this.structureDrag.addItems($li);\n      }\n\n      if (this.settings.newChildUrl) {\n        var $addBtn = $(\n          '<a class=\"add icon\" title=\"' + Craft.t('app', 'New child') + '\"></a>'\n        ).appendTo($row);\n        this.initNewChildMenus($addBtn);\n      }\n\n      $row.css('margin-bottom', -30);\n      $row.velocity({'margin-bottom': 0}, 'fast');\n    },\n\n    removeElement: function ($element) {\n      var $li = $element.parent().parent();\n\n      if (this.settings.sortable) {\n        this.structureDrag.removeItems($li);\n      }\n\n      var $parentUl;\n\n      if (!$li.siblings().length) {\n        $parentUl = $li.parent();\n      }\n\n      $li\n        .css('visibility', 'hidden')\n        .velocity({marginBottom: -$li.height()}, 'fast', () => {\n          $li.remove();\n\n          if (typeof $parentUl !== 'undefined') {\n            this._removeUl($parentUl);\n          }\n        });\n    },\n\n    _removeUl: function ($ul) {\n      $ul.siblings('.row').children('.toggle').remove();\n      $ul.remove();\n    },\n\n    destroy: function () {\n      this.$container.removeData('structure');\n      this.base();\n    },\n  },\n  {\n    baseIndent: 8,\n    nestedIndent: 35,\n\n    defaults: {\n      storageKey: null,\n      sortable: false,\n      newChildUrl: null,\n      maxLevels: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Structure drag class\n */\nCraft.StructureDrag = Garnish.Drag.extend({\n  structure: null,\n  maxLevels: null,\n  draggeeLevel: null,\n\n  $helperLi: null,\n  $targets: null,\n  draggeeHeight: null,\n\n  init: function (structure, maxLevels) {\n    this.structure = structure;\n    this.maxLevels = maxLevels;\n\n    this.$insertion = $('<li class=\"draginsertion\"/>');\n\n    var $items = this.structure.$container.find('li');\n\n    this.base($items, {\n      handle: '.element:first, .move:first',\n      helper: this.getHelper.bind(this),\n    });\n  },\n\n  getHelper: function ($helper) {\n    this.$helperLi = $helper;\n    var $ul = $('<ul class=\"structure draghelper\"/>').append($helper);\n    $helper.css(\n      'padding-' + Craft.left,\n      this.$draggee.css('padding-' + Craft.left)\n    );\n    $helper.find('.move').removeAttr('title');\n    return $ul;\n  },\n\n  onDragStart: function () {\n    this.$targets = $();\n\n    // Recursively find each of the targets, in the order they appear to be in\n    this.findTargets(this.structure.$container);\n\n    // How deep does the rabbit hole go?\n    this.draggeeLevel = 0;\n    var $level = this.$draggee;\n    do {\n      this.draggeeLevel++;\n      $level = $level.find('> ul > li');\n    } while ($level.length);\n\n    // Collapse the draggee\n    this.draggeeHeight = this.$draggee.height();\n    this.$draggee.velocity(\n      {\n        height: 0,\n      },\n      'fast',\n      () => {\n        this.$draggee.addClass('hidden');\n      }\n    );\n    this.base();\n\n    this.addListener(Garnish.$doc, 'keydown', function (ev) {\n      if (ev.keyCode === Garnish.ESC_KEY) {\n        this.cancelDrag();\n      }\n    });\n  },\n\n  findTargets: function ($ul) {\n    var $lis = $ul.children().not(this.$draggee);\n\n    for (var i = 0; i < $lis.length; i++) {\n      var $li = $($lis[i]);\n      this.$targets = this.$targets.add($li.children('.row'));\n\n      if (!$li.hasClass('collapsed')) {\n        this.findTargets($li.children('ul'));\n      }\n    }\n  },\n\n  onDrag: function () {\n    if (this._.$closestTarget) {\n      this._.$closestTarget.removeClass('draghover');\n      this.$insertion.remove();\n    }\n\n    // First let's find the closest target\n    this._.$closestTarget = null;\n    this._.closestTargetPos = null;\n    this._.closestTargetYDiff = null;\n    this._.closestTargetOffset = null;\n    this._.closestTargetHeight = null;\n\n    for (this._.i = 0; this._.i < this.$targets.length; this._.i++) {\n      this._.$target = $(this.$targets[this._.i]);\n      this._.targetOffset = this._.$target.offset();\n      this._.targetHeight = this._.$target.outerHeight();\n      this._.targetYMidpoint =\n        this._.targetOffset.top + this._.targetHeight / 2;\n      this._.targetYDiff = Math.abs(this.mouseY - this._.targetYMidpoint);\n\n      if (\n        this._.i === 0 ||\n        (this.mouseY >= this._.targetOffset.top + 5 &&\n          this._.targetYDiff < this._.closestTargetYDiff)\n      ) {\n        this._.$closestTarget = this._.$target;\n        this._.closestTargetPos = this._.i;\n        this._.closestTargetYDiff = this._.targetYDiff;\n        this._.closestTargetOffset = this._.targetOffset;\n        this._.closestTargetHeight = this._.targetHeight;\n      } else {\n        // Getting colder\n        break;\n      }\n    }\n\n    if (!this._.$closestTarget) {\n      return;\n    }\n\n    // Are we hovering above the first row?\n    if (\n      this._.closestTargetPos === 0 &&\n      this.mouseY < this._.closestTargetOffset.top + 5\n    ) {\n      this.$insertion.prependTo(this.structure.$container);\n    } else {\n      this._.$closestTargetLi = this._.$closestTarget.parent();\n      this._.closestTargetLevel = this._.$closestTargetLi.data('level');\n\n      // Is there a next row?\n      if (this._.closestTargetPos < this.$targets.length - 1) {\n        this._.$nextTargetLi = $(\n          this.$targets[this._.closestTargetPos + 1]\n        ).parent();\n        this._.nextTargetLevel = this._.$nextTargetLi.data('level');\n      } else {\n        this._.$nextTargetLi = null;\n        this._.nextTargetLevel = null;\n      }\n\n      // Are we hovering between this row and the next one?\n      this._.hoveringBetweenRows =\n        this.mouseY >=\n        this._.closestTargetOffset.top + this._.closestTargetHeight - 5;\n\n      /**\n       * Scenario 1: Both rows have the same level.\n       *\n       *     * Row 1\n       *     ----------------------\n       *     * Row 2\n       */\n\n      if (\n        this._.$nextTargetLi &&\n        this._.nextTargetLevel == this._.closestTargetLevel\n      ) {\n        if (this._.hoveringBetweenRows) {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel - 1\n          ) {\n            // Position the insertion after the closest target\n            this.$insertion.insertAfter(this._.$closestTargetLi);\n          }\n        } else {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel\n          ) {\n            this._.$closestTarget.addClass('draghover');\n          }\n        }\n      } else if (\n        /**\n         * Scenario 2: Next row is a child of this one.\n         *\n         *     * Row 1\n         *     ----------------------\n         *         * Row 2\n         */\n        this._.$nextTargetLi &&\n        this._.nextTargetLevel > this._.closestTargetLevel\n      ) {\n        if (\n          !this.maxLevels ||\n          this.maxLevels >= this._.nextTargetLevel + this.draggeeLevel - 1\n        ) {\n          if (this._.hoveringBetweenRows) {\n            // Position the insertion as the first child of the closest target\n            this.$insertion.insertBefore(this._.$nextTargetLi);\n          } else {\n            this._.$closestTarget.addClass('draghover');\n            this.$insertion.appendTo(this._.$closestTargetLi.children('ul'));\n          }\n        }\n      } else {\n        /**\n         * Scenario 3: Next row is a child of a parent node, or there is no next row.\n         *\n         *         * Row 1\n         *     ----------------------\n         *     * Row 2\n         */\n        if (this._.hoveringBetweenRows) {\n          // Determine which <li> to position the insertion after\n          this._.draggeeX = this.mouseX - this.targetItemMouseDiffX;\n\n          if (Craft.orientation === 'rtl') {\n            this._.draggeeX += this.$helperLi.width();\n          }\n\n          this._.$parentLis = this._.$closestTarget.parentsUntil(\n            this.structure.$container,\n            'li'\n          );\n          this._.$closestParentLi = null;\n          this._.closestParentLiXDiff = null;\n          this._.closestParentLevel = null;\n\n          for (this._.i = 0; this._.i < this._.$parentLis.length; this._.i++) {\n            this._.$parentLi = $(this._.$parentLis[this._.i]);\n            this._.parentLiX = this._.$parentLi.offset().left;\n\n            if (Craft.orientation === 'rtl') {\n              this._.parentLiX += this._.$parentLi.width();\n            }\n\n            this._.parentLiXDiff = Math.abs(this._.parentLiX - this._.draggeeX);\n            this._.parentLevel = this._.$parentLi.data('level');\n\n            if (\n              (!this.maxLevels ||\n                this.maxLevels >= this._.parentLevel + this.draggeeLevel - 1) &&\n              (!this._.$closestParentLi ||\n                (this._.parentLiXDiff < this._.closestParentLiXDiff &&\n                  (!this._.$nextTargetLi ||\n                    this._.parentLevel >= this._.nextTargetLevel)))\n            ) {\n              this._.$closestParentLi = this._.$parentLi;\n              this._.closestParentLiXDiff = this._.parentLiXDiff;\n              this._.closestParentLevel = this._.parentLevel;\n            }\n          }\n\n          if (this._.$closestParentLi) {\n            this.$insertion.insertAfter(this._.$closestParentLi);\n          }\n        } else {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel\n          ) {\n            this._.$closestTarget.addClass('draghover');\n          }\n        }\n      }\n    }\n  },\n\n  cancelDrag: function () {\n    this.$insertion.remove();\n\n    if (this._.$closestTarget) {\n      this._.$closestTarget.removeClass('draghover');\n    }\n\n    this.onMouseUp();\n  },\n\n  onDragStop: function () {\n    // Are we repositioning the draggee?\n    if (\n      this._.$closestTarget &&\n      (this.$insertion.parent().length ||\n        this._.$closestTarget.hasClass('draghover'))\n    ) {\n      var $draggeeParent, moved;\n\n      // Are we about to leave the draggee's original parent childless?\n      if (!this.$draggee.siblings().length) {\n        $draggeeParent = this.$draggee.parent();\n      }\n\n      if (this.$insertion.parent().length) {\n        // Make sure the insertion isn't right next to the draggee\n        var $closestSiblings = this.$insertion\n          .next()\n          .add(this.$insertion.prev());\n\n        if ($.inArray(this.$draggee[0], $closestSiblings) === -1) {\n          this.$insertion.replaceWith(this.$draggee);\n          moved = true;\n        } else {\n          this.$insertion.remove();\n          moved = false;\n        }\n      } else {\n        var $ul = this._.$closestTargetLi.children('ul');\n\n        // Make sure this is a different parent than the draggee's\n        if (!$draggeeParent || !$ul.length || $ul[0] !== $draggeeParent[0]) {\n          if (!$ul.length) {\n            var $toggle = $(\n              '<div class=\"toggle\" title=\"' +\n                Craft.t('app', 'Show/hide children') +\n                '\"/>'\n            ).prependTo(this._.$closestTarget);\n            this.structure.initToggle($toggle);\n\n            $ul = $('<ul>').appendTo(this._.$closestTargetLi);\n          } else if (this._.$closestTargetLi.hasClass('collapsed')) {\n            this._.$closestTarget.children('.toggle').trigger('click');\n          }\n\n          this.$draggee.appendTo($ul);\n          moved = true;\n        } else {\n          moved = false;\n        }\n      }\n\n      // Remove the class either way\n      this._.$closestTarget.removeClass('draghover');\n\n      if (moved) {\n        // Now deal with the now-childless parent\n        if ($draggeeParent) {\n          this.structure._removeUl($draggeeParent);\n        }\n\n        // Has the level changed?\n        var newLevel =\n          this.$draggee.parentsUntil(this.structure.$container, 'li').length +\n          1;\n\n        var animateCss;\n\n        if (newLevel != this.$draggee.data('level')) {\n          // Correct the helper's padding if moving to/from level 1\n          if (this.$draggee.data('level') == 1) {\n            animateCss = {};\n            animateCss['padding-' + Craft.left] = 38;\n            this.$helperLi.velocity(animateCss, 'fast');\n          } else if (newLevel == 1) {\n            animateCss = {};\n            animateCss['padding-' + Craft.left] = Craft.Structure.baseIndent;\n            this.$helperLi.velocity(animateCss, 'fast');\n          }\n\n          this.setLevel(this.$draggee, newLevel);\n        }\n\n        // Make it real\n        var $element = this.$draggee.children('.row').children('.element');\n\n        var data = {\n          structureId: this.structure.id,\n          elementId: $element.data('id'),\n          siteId: $element.data('site-id'),\n          prevId: this.$draggee\n            .prev()\n            .children('.row')\n            .children('.element')\n            .data('id'),\n          parentId: this.$draggee\n            .parent('ul')\n            .parent('li')\n            .children('.row')\n            .children('.element')\n            .data('id'),\n        };\n\n        Craft.sendActionRequest('POST', 'structures/move-element', {data}).then(\n          (response) => {\n            Craft.cp.displaySuccess(Craft.t('app', 'New order saved.'));\n          }\n        );\n      }\n    }\n\n    // Animate things back into place\n    this.$draggee\n      .velocity('stop')\n      .removeClass('hidden')\n      .velocity(\n        {\n          height: this.draggeeHeight,\n        },\n        'fast',\n        () => {\n          this.$draggee.css('height', 'auto');\n        }\n      );\n\n    this.returnHelpersToDraggees();\n\n    this.base();\n  },\n\n  setLevel: function ($li, level) {\n    $li.data('level', level);\n\n    var indent = this.structure.getIndent(level);\n\n    var css = {};\n    css['margin-' + Craft.left] = '-' + indent + 'px';\n    css['padding-' + Craft.left] = indent + 'px';\n    this.$draggee.children('.row').css(css);\n\n    var $childLis = $li.children('ul').children();\n\n    for (var i = 0; i < $childLis.length; i++) {\n      this.setLevel($($childLis[i]), level + 1);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.StructureTableSorter = Garnish.DragSort.extend(\n  {\n    tableView: null,\n    structureId: null,\n    maxLevels: null,\n\n    _basePadding: null,\n    _helperMargin: null,\n\n    _$firstRowCells: null,\n    _$titleHelperCell: null,\n\n    _titleHelperCellOuterWidth: null,\n\n    _ancestors: null,\n    _updateAncestorsFrame: null,\n\n    _draggeeLevel: null,\n    _draggeeLevelDelta: null,\n    draggingLastElements: null,\n    _loadingDraggeeLevelDelta: false,\n\n    _targetLevel: null,\n    _targetLevelBounds: null,\n\n    _positionChanged: null,\n\n    /**\n     * Constructor\n     */\n    init: function (tableView, $elements, settings) {\n      this.tableView = tableView;\n      this.structureId = this.tableView.$table.data('structure-id');\n      this.maxLevels = parseInt(this.tableView.$table.attr('data-max-levels'));\n\n      this._basePadding = 14 + (this.tableView.elementIndex.actions ? 34 : 24); // see _elements/tableview/elements.html\n      this._helperMargin = this.tableView.elementIndex.actions ? 54 : 0;\n\n      settings = $.extend({}, Craft.StructureTableSorter.defaults, settings, {\n        handle: '.move',\n        collapseDraggees: true,\n        singleHelper: true,\n        helperSpacingY: 2,\n        magnetStrength: 4,\n        helper: this.getHelper.bind(this),\n        helperLagBase: 1.5,\n        axis: Garnish.Y_AXIS,\n      });\n\n      this.base($elements, settings);\n    },\n\n    /**\n     * Returns the draggee rows (including any descendent rows).\n     */\n    findDraggee: function () {\n      this._draggeeLevel = this._targetLevel = this.$targetItem.data('level');\n      this._draggeeLevelDelta = 0;\n\n      var $draggee = $(this.$targetItem),\n        $nextRow = this.$targetItem.next();\n\n      while ($nextRow.length) {\n        // See if this row is a descendant of the draggee\n        var nextRowLevel = $nextRow.data('level');\n\n        if (nextRowLevel <= this._draggeeLevel) {\n          break;\n        }\n\n        // Is this the deepest descendant we've seen so far?\n        var nextRowLevelDelta = nextRowLevel - this._draggeeLevel;\n\n        if (nextRowLevelDelta > this._draggeeLevelDelta) {\n          this._draggeeLevelDelta = nextRowLevelDelta;\n        }\n\n        // Add it and prep the next row\n        $draggee = $draggee.add($nextRow);\n        $nextRow = $nextRow.next();\n      }\n\n      // Are we dragging the last elements on the page?\n      this.draggingLastElements = !$nextRow.length;\n\n      // Do we have a maxLevels to enforce,\n      // and does it look like this draggee has descendants we don't know about yet?\n      if (\n        this.maxLevels &&\n        this.draggingLastElements &&\n        this.tableView.getMorePending()\n      ) {\n        // Only way to know the true descendant level delta is to ask PHP\n        this._loadingDraggeeLevelDelta = true;\n\n        var data = this._getAjaxBaseData(this.$targetItem);\n\n        Craft.sendActionRequest('POST', 'structures/get-element-level-delta', {\n          data,\n        }).then((response) => {\n          this._loadingDraggeeLevelDelta = false;\n\n          if (this.dragging) {\n            this._draggeeLevelDelta = response.data.delta;\n            this.drag(false);\n          }\n        });\n      }\n\n      return $draggee;\n    },\n\n    /**\n     * Returns the drag helper.\n     */\n    getHelper: function ($helperRow) {\n      var $outerContainer = $(\n          '<div class=\"elements datatablesorthelper\"/>'\n        ).appendTo(Garnish.$bod),\n        $innerContainer = $('<div class=\"tableview\"/>').appendTo(\n          $outerContainer\n        ),\n        $table = $('<table class=\"data\"/>').appendTo($innerContainer),\n        $tbody = $('<tbody/>').appendTo($table);\n\n      $helperRow.appendTo($tbody);\n\n      // Copy the column widths\n      this._$firstRowCells = this.tableView.$elementContainer\n        .children('tr:first')\n        .children();\n      var $helperCells = $helperRow.children();\n\n      for (var i = 0; i < $helperCells.length; i++) {\n        var $helperCell = $($helperCells[i]);\n\n        // Skip the checkbox cell\n        if ($helperCell.hasClass('checkbox-cell')) {\n          $helperCell.remove();\n          continue;\n        }\n\n        // Hard-set the cell widths\n        var $firstRowCell = $(this._$firstRowCells[i]);\n        var width = $firstRowCell[0].getBoundingClientRect().width;\n\n        $firstRowCell.css('width', width + 'px');\n        $helperCell.css('width', width + 'px');\n\n        // Is this the title cell?\n        if (Garnish.hasAttr($firstRowCell, 'data-titlecell')) {\n          this._$titleHelperCell = $helperCell;\n          var padding = parseInt($firstRowCell.css('padding-' + Craft.left));\n          this._titleHelperCellOuterWidth = width;\n\n          $helperCell.css('padding-' + Craft.left, this._basePadding);\n        }\n      }\n\n      return $outerContainer;\n    },\n\n    /**\n     * Returns whether the draggee can be inserted before a given item.\n     */\n    canInsertBefore: function ($item) {\n      if (this._loadingDraggeeLevelDelta) {\n        return false;\n      }\n\n      return this._getLevelBounds($item.prev(), $item) !== false;\n    },\n\n    /**\n     * Returns whether the draggee can be inserted after a given item.\n     */\n    canInsertAfter: function ($item) {\n      if (this._loadingDraggeeLevelDelta) {\n        return false;\n      }\n\n      return this._getLevelBounds($item, $item.next()) !== false;\n    },\n\n    // Events\n    // -------------------------------------------------------------------------\n\n    /**\n     * On Drag Start\n     */\n    onDragStart: function () {\n      // Get the initial set of ancestors, before the item gets moved\n      this._ancestors = this._getAncestors(\n        this.$targetItem,\n        this.$targetItem.data('level')\n      );\n\n      // Set the initial target level bounds\n      this._setTargetLevelBounds();\n\n      // Check to see if we should load more elements now\n      this.tableView.maybeLoadMore();\n\n      this.base();\n    },\n\n    /**\n     * On Drag\n     */\n    onDrag: function () {\n      this.base();\n      this._updateIndent();\n    },\n\n    /**\n     * On Insertion Point Change\n     */\n    onInsertionPointChange: function () {\n      this._setTargetLevelBounds();\n      this._updateAncestorsBeforeRepaint();\n      this.base();\n    },\n\n    /**\n     * On Drag Stop\n     */\n    onDragStop: function () {\n      this._positionChanged = false;\n      this.base();\n\n      // Update the draggee's padding if the position just changed\n      // ---------------------------------------------------------------------\n\n      if (this._targetLevel != this._draggeeLevel) {\n        var levelDiff = this._targetLevel - this._draggeeLevel;\n\n        for (var i = 0; i < this.$draggee.length; i++) {\n          var $draggee = $(this.$draggee[i]),\n            oldLevel = $draggee.data('level'),\n            newLevel = oldLevel + levelDiff,\n            padding = this._basePadding + this._getLevelIndent(newLevel);\n\n          $draggee.data('level', newLevel);\n          $draggee.find('.element').data('level', newLevel);\n          $draggee\n            .children('[data-titlecell]:first')\n            .css('padding-' + Craft.left, padding);\n        }\n\n        this._positionChanged = true;\n      }\n\n      // Keep in mind this could have also been set by onSortChange()\n      if (this._positionChanged) {\n        // Tell the server about the new position\n        // -----------------------------------------------------------------\n\n        var data = this._getAjaxBaseData(this.$draggee);\n\n        // Find the previous sibling/parent, if there is one\n        var $prevRow = this.$draggee.first().prev();\n\n        while ($prevRow.length) {\n          var prevRowLevel = $prevRow.data('level');\n\n          if (prevRowLevel == this._targetLevel) {\n            data.prevId = $prevRow.data('id');\n            break;\n          }\n\n          if (prevRowLevel < this._targetLevel) {\n            data.parentId = $prevRow.data('id');\n\n            // Is this row collapsed?\n            var $toggle = $prevRow.find('> th > .toggle');\n\n            if (!$toggle.hasClass('expanded')) {\n              // Make it look expanded\n              $toggle.addClass('expanded');\n\n              // Add a temporary row\n              var $spinnerRow = this.tableView._createSpinnerRowAfter($prevRow);\n\n              // Remove the target item\n              if (this.tableView.elementSelect) {\n                this.tableView.elementSelect.removeItems(this.$targetItem);\n              }\n\n              this.removeItems(this.$targetItem);\n              this.$targetItem.remove();\n              this.tableView._totalVisible--;\n            }\n\n            break;\n          }\n\n          $prevRow = $prevRow.prev();\n        }\n\n        Craft.sendActionRequest('POST', 'structures/move-element', {data})\n          .then((response) => {\n            Craft.cp.displaySuccess(Craft.t('app', 'New position saved.'));\n            this.onPositionChange();\n\n            // Were we waiting on this to complete so we can expand the new parent?\n            if ($spinnerRow && $spinnerRow.parent().length) {\n              $spinnerRow.remove();\n              this.tableView._expandElement($toggle, true);\n            }\n\n            // See if we should run any pending tasks\n            Craft.cp.runQueue();\n          })\n          .catch(({response}) => {\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n            this.tableView.elementIndex.updateElements();\n            return;\n          });\n      }\n    },\n\n    onSortChange: function () {\n      if (this.tableView.elementSelect) {\n        this.tableView.elementSelect.resetItemOrder();\n      }\n\n      this._positionChanged = true;\n      this.base();\n    },\n\n    onPositionChange: function () {\n      Garnish.requestAnimationFrame(() => {\n        this.trigger('positionChange');\n        this.settings.onPositionChange();\n      });\n    },\n\n    onReturnHelpersToDraggees: function () {\n      this._$firstRowCells.css('width', '');\n\n      // If we were dragging the last elements on the page and ended up loading any additional elements in,\n      // there could be a gap between the last draggee item and whatever now comes after it.\n      // So remove the post-draggee elements and possibly load up the next batch.\n      if (this.draggingLastElements && this.tableView.getMorePending()) {\n        // Update the element index's record of how many items are actually visible\n        this.tableView._totalVisible +=\n          this.newDraggeeIndexes[0] - this.oldDraggeeIndexes[0];\n\n        var $postDraggeeItems = this.$draggee.last().nextAll();\n\n        if ($postDraggeeItems.length) {\n          this.removeItems($postDraggeeItems);\n          $postDraggeeItems.remove();\n          this.tableView.maybeLoadMore();\n        }\n      }\n\n      this.base();\n    },\n\n    /**\n     * Returns the min and max levels that the draggee could occupy between\n     * two given rows, or false if it’s not going to work out.\n     */\n    _getLevelBounds: function ($prevRow, $nextRow) {\n      // Can't go any lower than the next row, if there is one\n      if ($nextRow && $nextRow.length) {\n        this._getLevelBounds._minLevel = $nextRow.data('level');\n      } else {\n        this._getLevelBounds._minLevel = 1;\n      }\n\n      // Can't go any higher than the previous row + 1\n      if ($prevRow && $prevRow.length) {\n        this._getLevelBounds._maxLevel = $prevRow.data('level') + 1;\n      } else {\n        this._getLevelBounds._maxLevel = 1;\n      }\n\n      // Does this structure have a max level?\n      if (this.maxLevels) {\n        // Make sure it's going to fit at all here\n        if (\n          this._getLevelBounds._minLevel != 1 &&\n          this._getLevelBounds._minLevel + this._draggeeLevelDelta >\n            this.maxLevels\n        ) {\n          return false;\n        }\n\n        // Limit the max level if we have to\n        if (\n          this._getLevelBounds._maxLevel + this._draggeeLevelDelta >\n          this.maxLevels\n        ) {\n          this._getLevelBounds._maxLevel =\n            this.maxLevels - this._draggeeLevelDelta;\n\n          if (this._getLevelBounds._maxLevel < this._getLevelBounds._minLevel) {\n            this._getLevelBounds._maxLevel = this._getLevelBounds._minLevel;\n          }\n        }\n      }\n\n      return {\n        min: this._getLevelBounds._minLevel,\n        max: this._getLevelBounds._maxLevel,\n      };\n    },\n\n    /**\n     * Determines the min and max possible levels at the current draggee's position.\n     */\n    _setTargetLevelBounds: function () {\n      this._targetLevelBounds = this._getLevelBounds(\n        this.$draggee.first().prev(),\n        this.$draggee.last().next()\n      );\n    },\n\n    /**\n     * Determines the target level based on the current mouse position.\n     */\n    _updateIndent: function (forcePositionChange) {\n      // Figure out the target level\n      // ---------------------------------------------------------------------\n\n      // How far has the cursor moved?\n      this._updateIndent._mouseDist = this.realMouseX - this.mousedownX;\n\n      // Flip that if this is RTL\n      if (Craft.orientation === 'rtl') {\n        this._updateIndent._mouseDist *= -1;\n      }\n\n      // What is that in indentation levels?\n      this._updateIndent._indentationDist = Math.round(\n        this._updateIndent._mouseDist / Craft.StructureTableSorter.LEVEL_INDENT\n      );\n\n      // Combine with the original level to get the new target level\n      this._updateIndent._targetLevel =\n        this._draggeeLevel + this._updateIndent._indentationDist;\n\n      // Contain it within our min/max levels\n      if (this._updateIndent._targetLevel < this._targetLevelBounds.min) {\n        this._updateIndent._indentationDist +=\n          this._targetLevelBounds.min - this._updateIndent._targetLevel;\n        this._updateIndent._targetLevel = this._targetLevelBounds.min;\n      } else if (\n        this._updateIndent._targetLevel > this._targetLevelBounds.max\n      ) {\n        this._updateIndent._indentationDist -=\n          this._updateIndent._targetLevel - this._targetLevelBounds.max;\n        this._updateIndent._targetLevel = this._targetLevelBounds.max;\n      }\n\n      // Has the target level changed?\n      if (\n        this._targetLevel !==\n        (this._targetLevel = this._updateIndent._targetLevel)\n      ) {\n        // Target level is changing, so update the ancestors\n        this._updateAncestorsBeforeRepaint();\n      }\n\n      // Update the UI\n      // ---------------------------------------------------------------------\n\n      // How far away is the cursor from the exact target level distance?\n      this._updateIndent._targetLevelMouseDiff =\n        this._updateIndent._mouseDist -\n        this._updateIndent._indentationDist *\n          Craft.StructureTableSorter.LEVEL_INDENT;\n\n      // What's the magnet impact of that?\n      this._updateIndent._magnetImpact = Math.round(\n        this._updateIndent._targetLevelMouseDiff / 15\n      );\n\n      // Put it on a leash\n      if (\n        Math.abs(this._updateIndent._magnetImpact) >\n        Craft.StructureTableSorter.MAX_GIVE\n      ) {\n        this._updateIndent._magnetImpact =\n          (this._updateIndent._magnetImpact > 0 ? 1 : -1) *\n          Craft.StructureTableSorter.MAX_GIVE;\n      }\n\n      // Apply the new margin/width\n      this._updateIndent._closestLevelMagnetIndent =\n        this._getLevelIndent(this._targetLevel) +\n        this._updateIndent._magnetImpact;\n      this.helpers[0].css(\n        'margin-' + Craft.left,\n        this._updateIndent._closestLevelMagnetIndent + this._helperMargin\n      );\n      this._$titleHelperCell.css(\n        'width',\n        this._titleHelperCellOuterWidth -\n          this._updateIndent._closestLevelMagnetIndent\n      );\n    },\n\n    /**\n     * Returns the indent size for a given level\n     */\n    _getLevelIndent: function (level) {\n      return (level - 1) * Craft.StructureTableSorter.LEVEL_INDENT;\n    },\n\n    /**\n     * Returns the base data that should be sent with StructureController Ajax requests.\n     */\n    _getAjaxBaseData: function ($row) {\n      return {\n        structureId: this.structureId,\n        elementId: $row.data('id'),\n        siteId: $row.find('.element:first').data('site-id'),\n      };\n    },\n\n    /**\n     * Returns a row's ancestor rows\n     */\n    _getAncestors: function ($row, targetLevel) {\n      this._getAncestors._ancestors = [];\n\n      if (targetLevel != 0) {\n        this._getAncestors._level = targetLevel;\n        this._getAncestors._$prevRow = $row.prev();\n\n        while (this._getAncestors._$prevRow.length) {\n          if (\n            this._getAncestors._$prevRow.data('level') <\n            this._getAncestors._level\n          ) {\n            this._getAncestors._ancestors.unshift(this._getAncestors._$prevRow);\n            this._getAncestors._level =\n              this._getAncestors._$prevRow.data('level');\n\n            // Did we just reach the top?\n            if (this._getAncestors._level == 0) {\n              break;\n            }\n          }\n\n          this._getAncestors._$prevRow = this._getAncestors._$prevRow.prev();\n        }\n      }\n\n      return this._getAncestors._ancestors;\n    },\n\n    /**\n     * Prepares to have the ancestors updated before the screen is repainted.\n     */\n    _updateAncestorsBeforeRepaint: function () {\n      if (this._updateAncestorsFrame) {\n        Garnish.cancelAnimationFrame(this._updateAncestorsFrame);\n      }\n\n      this._updateAncestorsFrame = Garnish.requestAnimationFrame(\n        this._updateAncestors.bind(this)\n      );\n    },\n\n    _updateAncestors: function () {\n      this._updateAncestorsFrame = null;\n\n      // Update the old ancestors\n      // -----------------------------------------------------------------\n\n      for (\n        this._updateAncestors._i = 0;\n        this._updateAncestors._i < this._ancestors.length;\n        this._updateAncestors._i++\n      ) {\n        this._updateAncestors._$ancestor =\n          this._ancestors[this._updateAncestors._i];\n\n        // One less descendant now\n        this._updateAncestors._$ancestor.data(\n          'descendants',\n          this._updateAncestors._$ancestor.data('descendants') - 1\n        );\n\n        // Is it now childless?\n        if (this._updateAncestors._$ancestor.data('descendants') == 0) {\n          // Remove its toggle\n          this._updateAncestors._$ancestor\n            .find('> th > .toggle:first')\n            .remove();\n        }\n      }\n\n      // Update the new ancestors\n      // -----------------------------------------------------------------\n\n      this._updateAncestors._newAncestors = this._getAncestors(\n        this.$targetItem,\n        this._targetLevel\n      );\n\n      for (\n        this._updateAncestors._i = 0;\n        this._updateAncestors._i < this._updateAncestors._newAncestors.length;\n        this._updateAncestors._i++\n      ) {\n        this._updateAncestors._$ancestor =\n          this._updateAncestors._newAncestors[this._updateAncestors._i];\n\n        // One more descendant now\n        this._updateAncestors._$ancestor.data(\n          'descendants',\n          this._updateAncestors._$ancestor.data('descendants') + 1\n        );\n\n        // Is this its first child?\n        if (this._updateAncestors._$ancestor.data('descendants') == 1) {\n          // Create its toggle\n          const ancestorTitle = this._updateAncestors._$ancestor.data('title');\n          $(\n            '<button class=\"toggle expanded\" type=\"button\" aria-expanded=\"true\" title=\"' +\n              Craft.t('app', 'Show/hide children') +\n              '\" aria-label=\"' +\n              Craft.t('app', 'Show {title} children', {title: ancestorTitle}) +\n              '\"></button>'\n          ).insertAfter(\n            this._updateAncestors._$ancestor.find('> th .move:first')\n          );\n        }\n      }\n\n      this._ancestors = this._updateAncestors._newAncestors;\n\n      delete this._updateAncestors._i;\n      delete this._updateAncestors._$ancestor;\n      delete this._updateAncestors._newAncestors;\n    },\n  },\n  {\n    HELPER_MARGIN: 0,\n    LEVEL_INDENT: 44,\n    MAX_GIVE: 22,\n\n    defaults: {\n      onPositionChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Table Element Index View\n */\nCraft.TableElementIndexView = Craft.BaseElementIndexView.extend({\n  $table: null,\n  $tableCaption: null,\n  $selectedSortHeader: null,\n  $statusMessage: null,\n\n  structureTableSort: null,\n\n  _totalVisiblePostStructureTableDraggee: null,\n  _morePendingPostStructureTableDraggee: false,\n\n  _broadcastListener: null,\n\n  getElementContainer: function () {\n    // Save a reference to the table\n    this.$table = this.$container.find('table:first');\n    return this.$table.children('tbody:first');\n  },\n\n  afterInit: function () {\n    // Set table caption\n    this.$tableCaption = this.$table.find('caption');\n\n    this.$statusMessage = this.$table.parent().find('[data-status-message]');\n\n    // Set the sort header\n    this.initTableHeaders();\n\n    // Add callback for after elements are updated\n    this.elementIndex.on('updateElements', () => {\n      this._updateScreenReaderStatus();\n    });\n\n    // Create the Structure Table Sorter\n    if (\n      this.elementIndex.settings.context === 'index' &&\n      this.elementIndex.viewMode === 'structure' &&\n      Garnish.hasAttr(this.$table, 'data-structure-id')\n    ) {\n      this.structureTableSort = new Craft.StructureTableSorter(\n        this,\n        this.getAllElements()\n      );\n    } else {\n      this.structureTableSort = null;\n    }\n\n    // Handle expand/collapse toggles for Structures\n    if (this.elementIndex.viewMode === 'structure') {\n      this.addListener(this.$elementContainer, 'click', function (ev) {\n        var $target = $(ev.target);\n\n        if ($target.hasClass('toggle')) {\n          if (this._collapseElement($target) === false) {\n            this._expandElement($target);\n          }\n        }\n      });\n    }\n\n    // Set up the broadcast listener\n    if (Craft.messageReceiver) {\n      this._broadcastListener = (ev) => {\n        if (ev.data.event === 'saveElement') {\n          const $rows = this.$table.find(\n            `> tbody > tr[data-id=\"${ev.data.id}\"]`\n          );\n          if ($rows.length) {\n            const data = {\n              elementType: this.elementIndex.elementType,\n              source: this.elementIndex.sourceKey,\n              id: ev.data.id,\n              siteId: this.elementIndex.siteId,\n            };\n            Craft.sendActionRequest(\n              'POST',\n              'element-indexes/element-table-html',\n              {data}\n            ).then(({data}) => {\n              for (let i = 0; i < $rows.length; i++) {\n                const $row = $rows.eq(i);\n                $row\n                  .find('> th[data-titlecell] .element')\n                  .replaceWith(data.elementHtml);\n                for (let attribute in data.attributeHtml) {\n                  if (data.attributeHtml.hasOwnProperty(attribute)) {\n                    $row\n                      .find(`> td[data-attr=\"${attribute}\"]`)\n                      .html(data.attributeHtml[attribute]);\n                  }\n                }\n              }\n              Craft.cp.elementThumbLoader.load($rows);\n            });\n          }\n        }\n      };\n\n      Craft.messageReceiver.addEventListener(\n        'message',\n        this._broadcastListener\n      );\n    }\n  },\n\n  initTableHeaders: function () {\n    let selectedSortAttr, selectedSortDir;\n    if (this.elementIndex.viewMode === 'structure') {\n      selectedSortAttr = 'structure';\n      selectedSortDir = 'asc';\n    } else {\n      [selectedSortAttr, selectedSortDir] =\n        this.elementIndex.getSortAttributeAndDirection();\n    }\n\n    const $tableHeaders = this.$table\n      .children('thead')\n      .children()\n      .children('[data-attribute]');\n\n    for (let i = 0; i < $tableHeaders.length; i++) {\n      const $header = $tableHeaders.eq(i);\n      const attr = $header.attr('data-attribute');\n      let sortValue = 'none';\n\n      // Is this the selected sort attribute?\n      if (attr === selectedSortAttr) {\n        this.$selectedSortHeader = $header;\n        sortValue = selectedSortDir === 'asc' ? 'ascending' : 'descending';\n        $header.addClass('ordered ' + selectedSortDir);\n        this.makeColumnSortable($header, true);\n      } else {\n        // Is this attribute sortable?\n        if (this.elementIndex.getSortOption(attr)) {\n          this.makeColumnSortable($header);\n        }\n      }\n\n      $header.attr('aria-sort', sortValue);\n    }\n  },\n\n  makeColumnSortable: function ($header, sorted = false) {\n    $header.addClass('orderable');\n\n    const headerHtml = $header.html();\n    const $instructions = this.$tableCaption.find('[data-sort-instructions]');\n    const $headerButton = $('<button/>', {\n      id: `${this.elementIndex.idPrefix}-${$header.attr('data-attribute')}`,\n      type: 'button',\n      'aria-pressed': 'false',\n    }).html(headerHtml);\n\n    if ($instructions.length) {\n      $headerButton.attr('aria-describedby', $instructions.attr('id'));\n    }\n\n    if (sorted) {\n      $headerButton.attr('aria-pressed', 'true');\n      $headerButton.on('click', this._handleSelectedSortHeaderClick.bind(this));\n    } else {\n      $headerButton.on(\n        'click',\n        this._handleUnselectedSortHeaderClick.bind(this)\n      );\n    }\n\n    $header.empty().append($headerButton);\n  },\n\n  isVerticalList: function () {\n    return true;\n  },\n\n  getTotalVisible: function () {\n    if (this._isStructureTableDraggingLastElements()) {\n      return this._totalVisiblePostStructureTableDraggee;\n    } else {\n      return this._totalVisible;\n    }\n  },\n\n  setTotalVisible: function (totalVisible) {\n    if (this._isStructureTableDraggingLastElements()) {\n      this._totalVisiblePostStructureTableDraggee = totalVisible;\n    } else {\n      this._totalVisible = totalVisible;\n    }\n  },\n\n  getMorePending: function () {\n    if (this._isStructureTableDraggingLastElements()) {\n      return this._morePendingPostStructureTableDraggee;\n    } else {\n      return this._morePending;\n    }\n  },\n\n  setMorePending: function (morePending) {\n    if (this._isStructureTableDraggingLastElements()) {\n      this._morePendingPostStructureTableDraggee = morePending;\n    } else {\n      this._morePending = this._morePendingPostStructureTableDraggee =\n        morePending;\n    }\n  },\n\n  getLoadMoreParams: function () {\n    var params = this.base();\n\n    // If we are dragging the last elements on the page,\n    // tell the controller to only load elements positioned after the draggee.\n    if (this._isStructureTableDraggingLastElements()) {\n      params.criteria.positionedAfter =\n        this.structureTableSort.$targetItem.data('id');\n    }\n\n    return params;\n  },\n\n  appendElements: function ($newElements) {\n    this.base($newElements);\n\n    if (this.structureTableSort) {\n      this.structureTableSort.addItems($newElements);\n    }\n\n    Craft.cp.updateResponsiveTables();\n  },\n\n  _collapseElement: function ($toggle, force) {\n    if (!force && !$toggle.hasClass('expanded')) {\n      return false;\n    }\n\n    $toggle.removeClass('expanded');\n    $toggle.attr('aria-expanded', 'false');\n\n    // Find and remove the descendant rows\n    var $row = $toggle.parent().parent(),\n      id = $row.data('id'),\n      level = $row.data('level'),\n      $nextRow = $row.next();\n\n    while ($nextRow.length) {\n      if (!Garnish.hasAttr($nextRow, 'data-spinnerrow')) {\n        if ($nextRow.data('level') <= level) {\n          break;\n        }\n\n        if (this.elementSelect) {\n          this.elementSelect.removeItems($nextRow);\n        }\n\n        if (this.structureTableSort) {\n          this.structureTableSort.removeItems($nextRow);\n        }\n\n        this._totalVisible--;\n      }\n\n      var $nextNextRow = $nextRow.next();\n      $nextRow.remove();\n      $nextRow = $nextNextRow;\n    }\n\n    // Remember that this row should be collapsed\n    if (!this.elementIndex.instanceState.collapsedElementIds) {\n      this.elementIndex.instanceState.collapsedElementIds = [];\n    }\n\n    this.elementIndex.instanceState.collapsedElementIds.push(id);\n    this.elementIndex.setInstanceState(\n      'collapsedElementIds',\n      this.elementIndex.instanceState.collapsedElementIds\n    );\n\n    // Bottom of the index might be viewable now\n    this.maybeLoadMore();\n  },\n\n  _expandElement: function ($toggle, force) {\n    if (!force && $toggle.hasClass('expanded')) {\n      return false;\n    }\n\n    $toggle.addClass('expanded');\n    $toggle.attr('aria-expanded', 'true');\n\n    // Remove this element from our list of collapsed elements\n    if (this.elementIndex.instanceState.collapsedElementIds) {\n      var $row = $toggle.parent().parent(),\n        id = $row.data('id'),\n        index = $.inArray(\n          id,\n          this.elementIndex.instanceState.collapsedElementIds\n        );\n\n      if (index !== -1) {\n        this.elementIndex.instanceState.collapsedElementIds.splice(index, 1);\n        this.elementIndex.setInstanceState(\n          'collapsedElementIds',\n          this.elementIndex.instanceState.collapsedElementIds\n        );\n\n        // Add a temporary row\n        var $spinnerRow = this._createSpinnerRowAfter($row);\n\n        // Load the nested elements\n        let data = $.extend(true, {}, this.settings.params);\n        data.criteria.descendantOf = id;\n\n        Craft.sendActionRequest('POST', this.settings.loadMoreElementsAction, {\n          data,\n        })\n          .then((response) => {\n            // Do we even care about this anymore?\n            if (!$spinnerRow.parent().length) {\n              return;\n            }\n\n            let $newElements = $(response.data.html);\n\n            // Are there more descendants we didn't get in this batch?\n            let totalVisible = this._totalVisible + $newElements.length;\n            let morePending =\n              this.settings.batchSize &&\n              $newElements.length === this.settings.batchSize;\n\n            if (morePending) {\n              // Remove all the elements after it\n              let $nextRows = $spinnerRow.nextAll();\n\n              if (this.elementSelect) {\n                this.elementSelect.removeItems($nextRows);\n              }\n\n              if (this.structureTableSort) {\n                this.structureTableSort.removeItems($nextRows);\n              }\n\n              $nextRows.remove();\n              totalVisible -= $nextRows.length;\n            } else {\n              // Maintain the current 'more' status\n              morePending = this._morePending;\n            }\n\n            $spinnerRow.replaceWith($newElements);\n            this.thumbLoader.load($newElements);\n\n            if (this.elementIndex.actions || this.settings.selectable) {\n              this.elementSelect.addItems(\n                $newElements.filter(':not(.disabled)')\n              );\n              this.elementIndex.updateActionTriggers();\n            }\n\n            if (this.structureTableSort) {\n              this.structureTableSort.addItems($newElements);\n            }\n\n            Craft.appendHeadHtml(response.data.headHtml);\n            Craft.appendBodyHtml(response.data.bodyHtml);\n            Craft.cp.updateResponsiveTables();\n\n            this.setTotalVisible(totalVisible);\n            this.setMorePending(morePending);\n\n            // Is there room to load more right now?\n            this.maybeLoadMore();\n          })\n          .catch((e) => {\n            Craft.cp.displayError();\n            if (!$spinnerRow.parent().length) {\n              return;\n            }\n          });\n      }\n    }\n  },\n\n  _createSpinnerRowAfter: function ($row) {\n    return $(\n      '<tr data-spinnerrow>' +\n        '<td class=\"centeralign\" colspan=\"' +\n        $row.children().length +\n        '\">' +\n        '<div class=\"spinner\"/>' +\n        '</td>' +\n        '</tr>'\n    ).insertAfter($row);\n  },\n\n  _isStructureTableDraggingLastElements: function () {\n    return (\n      this.structureTableSort &&\n      this.structureTableSort.dragging &&\n      this.structureTableSort.draggingLastElements\n    );\n  },\n\n  _handleSelectedSortHeaderClick: function (ev) {\n    var $header = $(ev.currentTarget).closest('th');\n\n    if ($header.hasClass('loading')) {\n      return;\n    }\n\n    // Reverse the sort direction\n    var selectedSortDir = this.elementIndex.getSelectedSortDirection(),\n      newSortDir = selectedSortDir === 'asc' ? 'desc' : 'asc';\n\n    // In case it's actually the structure view\n    this.elementIndex.selectViewMode('table');\n\n    this.elementIndex.setSelectedSortDirection(newSortDir);\n    this._handleSortHeaderClick(ev, $header);\n  },\n\n  _handleUnselectedSortHeaderClick: function (ev) {\n    var $header = $(ev.currentTarget).closest('th');\n\n    if ($header.hasClass('loading')) {\n      return;\n    }\n\n    var attr = $header.attr('data-attribute');\n\n    // In case it's actually the structure view\n    this.elementIndex.selectViewMode('table');\n\n    this.elementIndex.setSelectedSortAttribute(attr);\n    this._handleSortHeaderClick(ev, $header);\n  },\n\n  _handleSortHeaderClick: function (ev, $header) {\n    if (this.$selectedSortHeader) {\n      this.$selectedSortHeader.removeClass('ordered asc desc');\n    }\n\n    $header.addClass('ordered loading');\n    this.elementIndex.updateElements();\n\n    // No need for two spinners\n    this.elementIndex.setIndexAvailable();\n  },\n\n  _updateScreenReaderStatus: function () {\n    let attr, dir;\n    if (this.elementIndex.viewMode === 'structure') {\n      attr = 'structure';\n      dir = 'asc';\n    } else {\n      [attr, dir] = this.elementIndex.getSortAttributeAndDirection();\n    }\n\n    const attrLabel = this.elementIndex.getSortLabel(attr);\n    if (!attrLabel) {\n      return;\n    }\n\n    const dirLabel =\n      dir === 'asc'\n        ? Craft.t('app', 'Ascending')\n        : Craft.t('app', 'Descending');\n\n    const message = Craft.t(\n      'app',\n      'Table {name} sorted by {attribute}, {direction}',\n      {\n        name: this.$table.attr('data-name'),\n        attribute: attrLabel,\n        direction: dirLabel,\n      }\n    );\n\n    this.$statusMessage.empty();\n    this.$statusMessage.text(message);\n  },\n\n  _updateTableAttributes: function ($element, tableAttributes) {\n    var $tr = $element.closest('tr');\n\n    for (var attr in tableAttributes) {\n      if (!tableAttributes.hasOwnProperty(attr)) {\n        continue;\n      }\n\n      $tr\n        .children('[data-attr=\"' + attr + '\"]:first')\n        .html(tableAttributes[attr]);\n    }\n  },\n\n  destroy: function () {\n    if (this._broadcastListener) {\n      Craft.messageReceiver.removeEventListener(\n        'message',\n        this._broadcastListener\n      );\n      delete this._broadcastListener;\n    }\n\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Tab manager\n */\nCraft.Tabs = Garnish.Base.extend({\n  $container: null,\n  $tablist: null,\n  $menuBtn: null,\n  $tabs: null,\n  $firstTab: null,\n  $lastTab: null,\n  $selectedTab: null,\n  $focusableTab: null,\n  menu: null,\n\n  init: function (container) {\n    this.$container = $(container);\n    this.$tablist = this.$container.find('> [role=\"tablist\"]:first');\n    this.$tabs = this.$tablist.find('> [role=\"tab\"]');\n    this.$firstTab = this.$tabs.first();\n    this.$lastTab = this.$tabs.last();\n    this.$selectedTab = this.$tabs.filter('.sel:first');\n    this.$focusableTab = this.$tabs.filter('[tabindex=0]:first');\n    this.$menuBtn = this.$container.find('> .menubtn:first').menubtn();\n    this.menu = this.$menuBtn.data('menubtn').menu;\n\n    // Is there already a tab manager?\n    if (this.$container.data('tabs')) {\n      console.warn('Double-instantiating a tab manager on an element');\n      this.$container.data('tabs').destroy();\n    }\n\n    this.$container.data('tabs', this);\n\n    for (let i = 0; i < this.$tabs.length; i++) {\n      const $a = this.$tabs.eq(i);\n\n      // Does it link to an anchor?\n      const href = $a.attr('href');\n      if (href && href.charAt(0) === '#') {\n        this.addListener($a, 'keydown', (ev) => {\n          if ([Garnish.SPACE_KEY, Garnish.RETURN_KEY].includes(ev.keyCode)) {\n            ev.preventDefault();\n            this.selectTab(ev.currentTarget);\n          }\n        });\n        this.addListener($a, 'click', (ev) => {\n          ev.preventDefault();\n          this.selectTab(ev.currentTarget);\n        });\n      }\n\n      this.addListener($a, 'keydown', (ev) => {\n        let $tab;\n        if (\n          [Garnish.LEFT_KEY, Garnish.RIGHT_KEY].includes(ev.keyCode) &&\n          $.contains(this.$tablist[0], ev.currentTarget)\n        ) {\n          if (\n            ev.keyCode ===\n            (Craft.orientation === 'ltr' ? Garnish.LEFT_KEY : Garnish.RIGHT_KEY)\n          ) {\n            $tab = $(ev.currentTarget).prevAll(\n              '[role=\"tab\"]:not(.hidden):first'\n            );\n            $tab = $tab.length ? $tab : this.$lastTab;\n          } else {\n            $tab = $(ev.currentTarget).nextAll(\n              '[role=\"tab\"]:not(.hidden):first'\n            );\n            $tab = $tab.length ? $tab : this.$firstTab;\n          }\n        } else if (\n          ev.keyCode === Garnish.HOME_KEY ||\n          ev.keyCode === Garnish.END_KEY\n        ) {\n          $tab =\n            ev.keyCode === Garnish.HOME_KEY ? this.$firstTab : this.$lastTab;\n        }\n\n        if ($tab) {\n          ev.preventDefault();\n          this.makeTabFocusable($tab);\n          $tab.focus();\n          this.scrollToTab($tab);\n        }\n      });\n    }\n\n    this.updateMenuBtn();\n\n    Garnish.$win.on('resize', () => {\n      this.updateMenuBtn();\n    });\n\n    // Prevent menu options from updating the URL\n    this.menu.$options.on('click', (ev) => {\n      const $option = $(ev.currentTarget);\n      const href = $option.attr('href');\n      if (href && href.charAt(0) === '#') {\n        ev.preventDefault();\n      }\n    });\n\n    this.menu.on('optionselect', (ev) => {\n      this.selectTab($(ev.selectedOption).data('id'));\n    });\n  },\n\n  selectTab: function (tab, focusTab = true) {\n    const $tab = this._getTab(tab);\n\n    if ($tab[0] === this.$selectedTab[0]) {\n      return;\n    }\n\n    this.deselectTab();\n    this.$selectedTab = $tab.addClass('sel').attr('aria-selected', 'true');\n    this.makeTabFocusable($tab);\n\n    if (focusTab) {\n      $tab.trigger('focus');\n    }\n\n    this.scrollToTab($tab);\n\n    this.menu.$options.removeClass('sel');\n    this.menu.$options.filter(`[data-id=\"${$tab.data('id')}\"]`).addClass('sel');\n\n    this.trigger('selectTab', {\n      $tab: $tab,\n    });\n\n    $('#content').trigger('scroll');\n\n    const $slideoutContainer = $tab.closest('.slideout-container');\n    if ($slideoutContainer.length) {\n      $slideoutContainer.find('.so-content').trigger('scroll');\n    }\n  },\n\n  deselectTab: function () {\n    const $tab = this.$selectedTab\n      .removeClass('sel')\n      .attr('aria-selected', 'false');\n    this.$selectedTab = null;\n\n    this.trigger('deselectTab', {\n      $tab: $tab,\n    });\n  },\n\n  makeTabFocusable: function (tab) {\n    const $tab = this._getTab(tab);\n\n    if ($tab[0] === this.$focusableTab[0]) {\n      return;\n    }\n\n    this.$focusableTab.attr('tabindex', '-1');\n    this.$focusableTab = $tab.attr('tabindex', '0');\n  },\n\n  scrollToTab: function (tab) {\n    const $tab = this._getTab(tab);\n    const scrollLeft = this.$tablist.scrollLeft();\n    const tabOffset = $tab.offset().left;\n    const elemScrollOffset = tabOffset - this.$tablist.offset().left;\n    let targetScrollLeft = false;\n\n    // Is the tab hidden on the left?\n    if (elemScrollOffset < 0) {\n      targetScrollLeft = scrollLeft + elemScrollOffset - 24;\n    } else {\n      const tabWidth = $tab.outerWidth();\n      const ulWidth = this.$tablist.prop('clientWidth');\n\n      // Is it hidden to the right?\n      if (elemScrollOffset + tabWidth > ulWidth) {\n        targetScrollLeft =\n          scrollLeft + (elemScrollOffset - (ulWidth - tabWidth)) + 24;\n      }\n    }\n\n    if (targetScrollLeft !== false) {\n      this.$tablist.scrollLeft(targetScrollLeft);\n    }\n  },\n\n  updateMenuBtn: function () {\n    if (\n      Math.floor(this.$tablist.prop('scrollWidth') - 48) >\n      this.$container.prop('clientWidth')\n    ) {\n      this.$tablist.addClass('scrollable');\n      this.$menuBtn.removeClass('hidden');\n    } else {\n      this.$tablist.removeClass('scrollable');\n      this.$menuBtn.addClass('hidden');\n    }\n  },\n\n  _getTab: function (tab) {\n    if (tab instanceof jQuery) {\n      return tab;\n    }\n\n    if (tab instanceof HTMLElement) {\n      return $(tab);\n    }\n\n    if (typeof tab !== 'string') {\n      throw 'Invalid tab ID';\n    }\n\n    const $tab = this.$tabs.filter(`[data-id=\"${tab}\"]`);\n\n    if (!$tab.length) {\n      throw `Invalid tab ID: ${tab}`;\n    }\n\n    return $tab;\n  },\n\n  destroy: function () {\n    this.$container.removeData('tabs');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Tag select input\n */\nCraft.TagSelectInput = Craft.BaseElementSelectInput.extend(\n  {\n    searchTimeout: null,\n    searchMenu: null,\n\n    $container: null,\n    $elementsContainer: null,\n    $elements: null,\n    $addTagInput: null,\n    $spinner: null,\n\n    _ignoreBlur: false,\n\n    init: function (settings) {\n      // Normalize the settings\n      // ---------------------------------------------------------------------\n\n      // Are they still passing in a bunch of arguments?\n      if (!$.isPlainObject(settings)) {\n        // Loop through all of the old arguments and apply them to the settings\n        var normalizedSettings = {},\n          args = ['id', 'name', 'tagGroupId', 'sourceElementId'];\n\n        for (var i = 0; i < args.length; i++) {\n          if (typeof arguments[i] !== 'undefined') {\n            normalizedSettings[args[i]] = arguments[i];\n          } else {\n            break;\n          }\n        }\n\n        settings = normalizedSettings;\n      }\n\n      this.base($.extend({}, Craft.TagSelectInput.defaults, settings));\n\n      this.$addTagInput = this.$container.children('.add').children('.text');\n      this.$spinner = this.$addTagInput.next();\n\n      this.addListener(this.$addTagInput, 'input', () => {\n        if (this.searchTimeout) {\n          clearTimeout(this.searchTimeout);\n        }\n\n        this.searchTimeout = setTimeout(this.searchForTags.bind(this), 500);\n      });\n\n      this.addListener(this.$addTagInput, 'keydown', function (ev) {\n        if (ev.keyCode === Garnish.RETURN_KEY) {\n          ev.preventDefault();\n        }\n\n        let $option;\n\n        switch (ev.keyCode) {\n          case Garnish.RETURN_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              this.selectTag(this.searchMenu.$options.filter('.hover'));\n            }\n            return;\n          }\n\n          case Garnish.DOWN_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              let $hoverOption = this.searchMenu.$options.filter('.hover');\n              if ($hoverOption.length) {\n                let $nextOption = $hoverOption\n                  .parent()\n                  .nextAll()\n                  .find('a:not(.disabled)')\n                  .first();\n                if ($nextOption.length) {\n                  this.focusOption($nextOption);\n                }\n              } else {\n                this.focusOption(this.searchMenu.$options.eq(0));\n              }\n            }\n            return;\n          }\n\n          case Garnish.UP_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              let $hoverOption = this.searchMenu.$options.filter('.hover');\n              if ($hoverOption.length) {\n                let $prevOption = $hoverOption\n                  .parent()\n                  .prevAll()\n                  .find('a:not(.disabled)')\n                  .last();\n                if ($prevOption.length) {\n                  this.focusOption($prevOption);\n                }\n              } else {\n                this.focusOption(\n                  this.searchMenu.$options.eq(\n                    this.searchMenu.$options.length - 1\n                  )\n                );\n              }\n            }\n            return;\n          }\n        }\n      });\n\n      this.addListener(this.$addTagInput, 'focus', function () {\n        if (this.searchMenu) {\n          this.searchMenu.show();\n        }\n      });\n\n      this.addListener(this.$addTagInput, 'blur', function () {\n        if (this._ignoreBlur) {\n          this._ignoreBlur = false;\n          return;\n        }\n\n        setTimeout(() => {\n          if (this.searchMenu) {\n            this.searchMenu.hide();\n          }\n        }, 1);\n      });\n    },\n\n    focusOption: function ($option) {\n      this.searchMenu.$options.removeClass('hover');\n      $option.addClass('hover');\n      this.searchMenu.$menuList.attr(\n        'aria-activedescendant',\n        $option.attr('id')\n      );\n    },\n\n    // No \"add\" button\n    getAddElementsBtn: $.noop,\n\n    getElementSortAxis: function () {\n      return null;\n    },\n\n    searchForTags: function () {\n      if (this.searchMenu) {\n        this.killSearchMenu();\n      }\n\n      var val = this.$addTagInput.val();\n\n      if (val) {\n        this.$spinner.removeClass('hidden');\n\n        var excludeIds = [];\n\n        for (var i = 0; i < this.$elements.length; i++) {\n          var id = $(this.$elements[i]).data('id');\n\n          if (id) {\n            excludeIds.push(id);\n          }\n        }\n\n        // take allowSelfRelations into consideration too\n        if (\n          this.settings.sourceElementId &&\n          !this.settings.allowSelfRelations\n        ) {\n          excludeIds.push(this.settings.sourceElementId);\n        }\n\n        var data = {\n          search: this.$addTagInput.val(),\n          tagGroupId: this.settings.tagGroupId,\n          excludeIds: excludeIds,\n        };\n\n        Craft.sendActionRequest('POST', 'tags/search-for-tags', {data})\n          .then((response) => {\n            if (this.searchMenu) {\n              this.killSearchMenu();\n            }\n            this.$spinner.addClass('hidden');\n            var $menu = $('<div class=\"menu tagmenu\"/>').appendTo(Garnish.$bod),\n              $ul = $('<ul/>').appendTo($menu);\n\n            var $li;\n\n            for (var i = 0; i < response.data.tags.length; i++) {\n              $li = $('<li/>').appendTo($ul);\n\n              $('<a data-icon=\"tag\"/>')\n                .appendTo($li)\n                .text(response.data.tags[i].title)\n                .data('id', response.data.tags[i].id)\n                .addClass(response.data.tags[i].exclude ? 'disabled' : '');\n            }\n\n            if (!response.data.exactMatch) {\n              $li = $('<li/>').appendTo($ul);\n              $('<a data-icon=\"plus\"/>').appendTo($li).text(data.search);\n            }\n\n            $ul.find('a:not(.disabled):first').addClass('hover');\n\n            this.searchMenu = new Garnish.Menu($menu, {\n              attachToElement: this.$addTagInput,\n              onOptionSelect: this.selectTag.bind(this),\n            });\n\n            this.addListener($menu, 'mousedown', () => {\n              this._ignoreBlur = true;\n            });\n\n            this.searchMenu.show();\n          })\n          .catch(({response}) => {\n            // Just in case\n            if (this.searchMenu) {\n              this.killSearchMenu();\n            }\n\n            this.$spinner.addClass('hidden');\n          });\n      } else {\n        this.$spinner.addClass('hidden');\n      }\n    },\n\n    selectTag: function (option) {\n      var $option = $(option);\n\n      if ($option.hasClass('disabled')) {\n        return;\n      }\n\n      var id = $option.data('id');\n      var title = $option.text();\n\n      var $element = $('<div/>', {\n        class: 'element small removable',\n        'data-id': id,\n        'data-site-id': this.settings.targetSiteId,\n        'data-label': title,\n        'data-editable': '1',\n      }).appendTo(this.$elementsContainer);\n\n      var $input = $('<input/>', {\n        type: 'hidden',\n        name: this.settings.name + '[]',\n        value: id,\n      }).appendTo($element);\n\n      $('<button/>', {\n        class: 'delete icon',\n        title: Craft.t('app', 'Remove'),\n        type: 'button',\n        'aria-label': Craft.t('app', 'Remove {label}', {\n          label: title,\n        }),\n      }).appendTo($element);\n\n      var $titleContainer = $('<div/>', {\n        class: 'label',\n      }).appendTo($element);\n\n      $('<span/>', {\n        class: 'title',\n        text: title,\n      }).appendTo($titleContainer);\n\n      this.$elements = this.$elements.add($element);\n\n      this.addElements($element);\n\n      this.killSearchMenu();\n      this.$addTagInput.val('');\n      this.$addTagInput.trigger('focus');\n\n      if (!id) {\n        // We need to create the tag first\n        $element.addClass('loading disabled');\n\n        var data = {\n          groupId: this.settings.tagGroupId,\n          title: title,\n        };\n\n        Craft.sendActionRequest('POST', 'tags/create-tag', {data})\n          .then((response) => {\n            $element.attr('data-id', response.data.id);\n            $input.val(response.data.id);\n\n            $element.removeClass('loading disabled');\n          })\n          .catch(({response}) => {\n            this.removeElement($element);\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n          });\n      }\n    },\n\n    killSearchMenu: function () {\n      this.searchMenu.hide();\n      this.searchMenu.destroy();\n      this.searchMenu = null;\n    },\n  },\n  {\n    defaults: {\n      tagGroupId: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Thumb Element Index View\n */\nCraft.ThumbsElementIndexView = Craft.BaseElementIndexView.extend({\n  getElementContainer: function () {\n    return this.$container.children('ul');\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.ui = {\n  createButton: function (config) {\n    const $btn = $('<button/>', {\n      type: config.type || 'button',\n      class: 'btn',\n    });\n    if (config.id) {\n      $btn.attr('id', config.id);\n    }\n    if (config.class) {\n      $btn.addClass(config.class);\n    }\n    if (config.ariaLabel) {\n      $btn.attr('aria-label', config.ariaLabel);\n    }\n    if (config.role) {\n      $btn.attr('role', config.role);\n    }\n    if (config.html) {\n      $btn.html(config.html);\n    } else if (config.label) {\n      $btn.append($('<div class=\"label\"/>').text(config.label));\n    } else {\n      $btn.addClass('btn-empty');\n    }\n    if (config.toggle) {\n      $btn.attr('aria-expanded', 'false');\n    }\n    if (config.controls) {\n      $btn.attr('aria-controls', config.controls);\n    }\n    if (config.spinner) {\n      $btn.append($('<div class=\"spinner spinner-absolute\"/>'));\n    }\n    return $btn;\n  },\n\n  createSubmitButton: function (config) {\n    const $btn = this.createButton(\n      Object.assign({}, config, {\n        type: 'submit',\n        label: config.label || Craft.t('app', 'Submit'),\n      })\n    );\n    $btn.addClass('submit');\n    return $btn;\n  },\n\n  createTextInput: function (config) {\n    config = $.extend(\n      {\n        autocomplete: false,\n      },\n      config\n    );\n    var $input = $('<input/>', {\n      attr: {\n        class: 'text',\n        type: config.type || 'text',\n        inputmode: config.inputmode,\n        id: config.id,\n        size: config.size,\n        name: config.name,\n        value: config.value,\n        maxlength: config.maxlength,\n        autofocus: this.getAutofocusValue(config.autofocus),\n        autocomplete:\n          typeof config.autocomplete === 'boolean'\n            ? config.autocomplete\n              ? 'on'\n              : 'off'\n            : config.autocomplete,\n        disabled: this.getDisabledValue(config.disabled),\n        readonly: config.readonly,\n        title: config.title,\n        placeholder: config.placeholder,\n        step: config.step,\n        min: config.min,\n        max: config.max,\n      },\n    });\n\n    if (config.class) {\n      $input.addClass(config.class);\n    }\n    if (config.placeholder) {\n      $input.addClass('nicetext');\n    }\n    if (config.type === 'password') {\n      $input.addClass('password');\n    }\n    if (config.disabled) {\n      $input.addClass('disabled');\n    }\n    if (!config.size) {\n      $input.addClass('fullwidth');\n    }\n\n    if (config.showCharsLeft && config.maxlength) {\n      $input\n        .attr('data-show-chars-left')\n        .css(\n          'padding-' + (Craft.orientation === 'ltr' ? 'right' : 'left'),\n          7.2 * config.maxlength.toString().length + 14 + 'px'\n        );\n    }\n\n    if (config.placeholder || config.showCharsLeft) {\n      new Garnish.NiceText($input);\n    }\n\n    if (config.type === 'password') {\n      return $('<div class=\"passwordwrapper\"/>').append($input);\n    } else {\n      return $input;\n    }\n  },\n\n  createTextField: function (config) {\n    if (!config.id) {\n      config.id = 'text' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTextInput(config), config);\n  },\n\n  createCopyTextInput: function (config) {\n    let id = config.id || 'copytext' + Math.floor(Math.random() * 1000000000);\n    let buttonId = config.buttonId || `${id}-btn`;\n\n    let $container = $('<div/>', {\n      class: 'copytext',\n    });\n\n    let $input = this.createTextInput(\n      $.extend({}, config, {\n        readonly: true,\n      })\n    ).appendTo($container);\n\n    let $btn = $('<button/>', {\n      type: 'button',\n      id: buttonId,\n      class: 'btn',\n      'data-icon': 'clipboard',\n      title: Craft.t('app', 'Copy to clipboard'),\n      'aria-label': Craft.t('app', 'Copy to clipboard'),\n    }).appendTo($container);\n\n    $btn.on('click', () => {\n      $input[0].select();\n      document.execCommand('copy');\n      Craft.cp.displayNotice(Craft.t('app', 'Copied to clipboard.'));\n      $container.trigger('copy');\n      $input[0].setSelectionRange(0, 0);\n    });\n\n    return $container;\n  },\n\n  createCopyTextBtn: function (config) {\n    let id = config.id || 'copytext' + Math.floor(Math.random() * 1000000000);\n    let value = config.value;\n\n    let $btn = $('<div/>', {\n      id,\n      class: 'copytextbtn',\n      role: 'button',\n      title: Craft.t('app', 'Copy to clipboard'),\n      'aria-label': Craft.t('app', 'Copy to clipboard'),\n      tabindex: '0',\n    });\n\n    if (config.class) {\n      $btn.addClass(config.class);\n    }\n\n    let $input = $('<input/>', {\n      value,\n      readonly: true,\n      size: value.length,\n      tabindex: '-1',\n    }).appendTo($btn);\n\n    let $icon = $('<span/>', {\n      'data-icon': 'clipboard',\n      'aria-hidden': 'true',\n    }).appendTo($btn);\n\n    const copyValue = function () {\n      $input[0].select();\n      document.execCommand('copy');\n      Craft.cp.displayNotice(Craft.t('app', 'Copied to clipboard.'));\n      $btn.trigger('copy');\n      $input[0].setSelectionRange(0, 0);\n      $btn.focus();\n    };\n\n    $btn.on('click', () => {\n      copyValue();\n    });\n\n    $btn.on('keydown', (ev) => {\n      if (ev.keyCode === Garnish.SPACE_KEY) {\n        copyValue();\n        ev.preventDefault();\n      }\n    });\n\n    return $btn;\n  },\n\n  createCopyTextField: function (config) {\n    if (!config.id) {\n      config.id = 'copytext' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createCopyTextInput(config), config);\n  },\n\n  createCopyTextPrompt: function (config) {\n    let $container = $('<div/>', {\n      class: 'modal fitted',\n    });\n    let $body = $('<div/>', {\n      class: 'body',\n    }).appendTo($container);\n    this.createCopyTextField(\n      $.extend(\n        {\n          size: Math.max(Math.min(config.value.length, 50), 25),\n        },\n        config\n      )\n    ).appendTo($body);\n\n    const $label = $body.find('label');\n\n    // Provide accessible name for modal dialog\n    if ($label.length > 0 && $label.attr('id')) {\n      $container.attr('aria-labelledby', $label.attr('id'));\n    }\n\n    let modal = new Garnish.Modal($container, {\n      closeOtherModals: false,\n    });\n    $container.on('copy', () => {\n      modal.hide();\n    });\n    return $container;\n  },\n\n  createTextarea: function (config) {\n    var $textarea = $('<textarea/>', {\n      class: 'text',\n      rows: config.rows || 2,\n      cols: config.cols || 50,\n      id: config.id,\n      name: config.name,\n      maxlength: config.maxlength,\n      autofocus: config.autofocus && !Garnish.isMobileBrowser(true),\n      disabled: !!config.disabled,\n      placeholder: config.placeholder,\n      html: config.value,\n    });\n\n    if (config.showCharsLeft) {\n      $textarea.attr('data-show-chars-left', '');\n    }\n\n    if (config.class) {\n      $textarea.addClass(config.class);\n    }\n\n    if (!config.size) {\n      $textarea.addClass('fullwidth');\n    }\n\n    return $textarea;\n  },\n\n  createTextareaField: function (config) {\n    if (!config.id) {\n      config.id = 'textarea' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTextarea(config), config);\n  },\n\n  createSelect: function (config) {\n    var $container = $('<div/>', {\n      class: 'select',\n    });\n\n    if (config.class) {\n      $container.addClass(config.class);\n    }\n\n    var $select = $('<select/>', {\n      id: config.id,\n      name: config.name,\n      autofocus: config.autofocus && Garnish.isMobileBrowser(true),\n      disabled: config.disabled,\n      'data-target-prefix': config.targetPrefix,\n      'aria-labelledby': config.labelledBy,\n    }).appendTo($container);\n\n    // Normalize the options into an array\n    if ($.isPlainObject(config.options)) {\n      let options = [];\n      for (var key in config.options) {\n        if (!config.options.hasOwnProperty(key)) {\n          continue;\n        }\n        let option = config.options[key];\n        if ($.isPlainObject(option)) {\n          if (typeof option.optgroup !== 'undefined') {\n            options.push(option);\n          } else {\n            options.push({\n              label: option.label,\n              value: typeof option.value !== 'undefined' ? option.value : key,\n              disabled:\n                typeof option.disabled !== 'undefined'\n                  ? option.disabled\n                  : false,\n            });\n          }\n        } else {\n          options.push({\n            label: option,\n            value: key,\n          });\n        }\n      }\n      config.options = options;\n    }\n\n    var $optgroup = null;\n\n    for (let i = 0; i < config.options.length; i++) {\n      let option = config.options[i];\n\n      // Starting a new <optgroup>?\n      if (typeof option.optgroup !== 'undefined') {\n        $optgroup = $('<optgroup/>', {\n          label: option.label,\n        }).appendTo($select);\n      } else {\n        $('<option/>', {\n          value: option.value,\n          selected: option.value == config.value,\n          disabled:\n            typeof option.disabled !== 'undefined' ? option.disabled : false,\n          html: option.label,\n        }).appendTo($optgroup || $select);\n      }\n    }\n\n    if (config.toggle) {\n      $select.addClass('fieldtoggle');\n      new Craft.FieldToggle($select);\n    }\n\n    return $container;\n  },\n\n  createSelectField: function (config) {\n    if (!config.id) {\n      config.id = 'select' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createSelect(config), config);\n  },\n\n  createCheckbox: function (config) {\n    var id = config.id || 'checkbox' + Math.floor(Math.random() * 1000000000);\n\n    var $input = $('<input/>', {\n      type: 'checkbox',\n      value: typeof config.value !== 'undefined' ? config.value : '1',\n      id: id,\n      class: 'checkbox',\n      name: config.name,\n      checked: config.checked ? 'checked' : null,\n      autofocus: this.getAutofocusValue(config.autofocus),\n      disabled: this.getDisabledValue(config.disabled),\n      'data-target': config.toggle,\n      'data-reverse-target': config.reverseToggle,\n    });\n\n    if (config.class) {\n      $input.addClass(config.class);\n    }\n\n    if (config.toggle || config.reverseToggle) {\n      $input.addClass('fieldtoggle');\n      new Craft.FieldToggle($input);\n    }\n\n    var $label = $('<label/>', {\n      for: id,\n      html: config.label,\n    });\n\n    // Should we include a hidden input first?\n    if (\n      config.name &&\n      (config.name.length < 3 || config.name.slice(-2) !== '[]')\n    ) {\n      return $([\n        $('<input/>', {\n          type: 'hidden',\n          name: config.name,\n          value: '',\n        })[0],\n        $input[0],\n        $label[0],\n      ]);\n    } else {\n      return $([$input[0], $label[0]]);\n    }\n  },\n\n  createCheckboxField: function (config) {\n    if (!config.id) {\n      config.id = 'checkbox' + Math.floor(Math.random() * 1000000000);\n    }\n\n    var $field = $('<div class=\"field checkboxfield\"/>', {\n      id: `${config.id}-field`,\n    });\n\n    if (config.first) {\n      $field.addClass('first');\n    }\n    if (config.instructions) {\n      $field.addClass('has-instructions');\n    }\n\n    this.createCheckbox(config).appendTo($field);\n\n    if (config.instructions) {\n      $('<div class=\"instructions\"/>')\n        .text(config.instructions)\n        .appendTo($field);\n    }\n\n    return $field;\n  },\n\n  createCheckboxSelect: function (config) {\n    var $container = $('<fieldset class=\"checkbox-select\"/>');\n\n    if (config.class) {\n      $container.addClass(config.class);\n    }\n\n    var allValue, allChecked;\n\n    if (config.showAllOption) {\n      allValue = config.allValue || '*';\n      allChecked = config.values == allValue;\n\n      // Create the \"All\" checkbox\n      $('<div/>')\n        .appendTo($container)\n        .append(\n          this.createCheckbox({\n            id: config.id,\n            class: 'all',\n            label: '<b>' + (config.allLabel || Craft.t('app', 'All')) + '</b>',\n            name: config.name,\n            value: allValue,\n            checked: allChecked,\n            autofocus: config.autofocus,\n          })\n        );\n    } else {\n      allChecked = false;\n    }\n\n    // Create the actual options\n    for (var i = 0; i < config.options.length; i++) {\n      var option = config.options[i];\n\n      if (option.value == allValue) {\n        continue;\n      }\n\n      $('<div/>')\n        .appendTo($container)\n        .append(\n          this.createCheckbox({\n            label: option.label,\n            name: config.name ? config.name + '[]' : null,\n            value: option.value,\n            checked: allChecked || (config.values || []).includes(option.value),\n            disabled: allChecked,\n          })\n        );\n    }\n\n    new Garnish.CheckboxSelect($container);\n\n    return $container;\n  },\n\n  createCheckboxSelectField: function (config) {\n    config.fieldset = true;\n    if (!config.id) {\n      config.id = 'checkboxselect' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createCheckboxSelect(config), config);\n  },\n\n  createLightswitch: function (config) {\n    var value = config.value || '1';\n    var indeterminateValue = config.indeterminateValue || '-';\n\n    var $container = $('<button/>', {\n      type: 'button',\n      class: 'lightswitch',\n      'data-value': value,\n      'data-indeterminate-value': indeterminateValue,\n      id: config.id,\n      role: 'switch',\n      'aria-checked': config.on\n        ? 'true'\n        : config.indeterminate\n        ? 'mixed'\n        : 'false',\n      'aria-labelledby': config.labelId,\n      'data-target': config.toggle,\n      'data-reverse-target': config.reverseToggle,\n    });\n\n    if (config.on) {\n      $container.addClass('on');\n    } else if (config.indeterminate) {\n      $container.addClass('indeterminate');\n    }\n\n    if (config.small) {\n      $container.addClass('small');\n    }\n\n    if (config.disabled) {\n      $container.addClass('disabled');\n    }\n\n    $(\n      '<div class=\"lightswitch-container\">' +\n        '<div class=\"handle\"></div>' +\n        '</div>'\n    ).appendTo($container);\n\n    if (config.name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: config.name,\n        value: config.on\n          ? value\n          : config.indeterminate\n          ? indeterminateValue\n          : '',\n        disabled: config.disabled,\n      }).appendTo($container);\n    }\n\n    if (config.toggle || config.reverseToggle) {\n      $container.addClass('fieldtoggle');\n      new Craft.FieldToggle($container);\n    }\n\n    new Craft.LightSwitch($container, {\n      onChange: config.onChange || $.noop,\n    });\n\n    return $container;\n  },\n\n  createLightswitchField: function (config) {\n    if (!config.id) {\n      config.id = 'lightswitch' + Math.floor(Math.random() * 1000000000);\n    }\n    if (!config.labelId) {\n      config.labelId = `${config.id}-label`;\n    }\n    return this.createField(this.createLightswitch(config), config).addClass(\n      'lightswitch-field'\n    );\n  },\n\n  createColorInput: function (config) {\n    const id = config.id || 'color' + Math.floor(Math.random() * 1000000000);\n    const containerId = config.containerId || id + '-container';\n    const name = config.name || null;\n    const value = config.value || null;\n    const small = config.small || false;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      id: containerId,\n      class: 'flex color-container',\n    });\n\n    const $colorPreviewContainer = $('<div/>', {\n      class: 'color static' + (small ? ' small' : ''),\n    }).appendTo($container);\n\n    const $colorPreview = $('<div/>', {\n      class: 'color-preview',\n      style: config.value ? {backgroundColor: config.value} : null,\n    }).appendTo($colorPreviewContainer);\n\n    const $inputContainer = $('<div/>', {\n      class: 'color-input-container',\n    })\n      .append(\n        $('<div/>', {\n          class: 'color-hex-indicator light code',\n          'aria-hidden': 'true',\n          text: '#',\n        })\n      )\n      .appendTo($container);\n\n    const $input = this.createTextInput({\n      id: id,\n      name: name,\n      value: Craft.ltrim(value, '#'),\n      size: 10,\n      class: 'color-input',\n      autofocus: autofocus,\n      disabled: disabled,\n      'aria-label': Craft.t('app', 'Color hex value'),\n    }).appendTo($inputContainer);\n\n    new Craft.ColorInput($container);\n    return $container;\n  },\n\n  createColorField: function (config) {\n    config.fieldset = true;\n    o;\n    if (!config.id) {\n      config.id = 'color' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createColorInput(config), config);\n  },\n\n  createDateInput: function (config) {\n    const isMobile = Garnish.isMobileBrowser();\n    const id =\n      (config.id || 'date' + Math.floor(Math.random() * 1000000000)) + '-date';\n    const name = config.name || null;\n    const inputName = name ? name + '[date]' : null;\n    const value =\n      config.value && typeof config.value.getMonth === 'function'\n        ? config.value\n        : null;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      class: 'datewrapper',\n    });\n\n    const $input = this.createTextInput({\n      id: id,\n      type: isMobile ? 'date' : 'text',\n      class: isMobile && !value ? 'empty-value' : false,\n      name: inputName,\n      value: value\n        ? isMobile\n          ? value.toISOString().split('T')[0]\n          : Craft.formatDate(value)\n        : '',\n      placeholder: ' ',\n      autocomplete: false,\n      autofocus: autofocus,\n      disabled: disabled,\n    }).appendTo($container);\n\n    $('<div data-icon=\"date\"></div>').appendTo($container);\n\n    if (name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: name + '[timezone]',\n        val: Craft.timezone,\n      }).appendTo($container);\n    }\n\n    if (isMobile) {\n      $input.datetimeinput();\n    } else {\n      $input.datepicker(\n        $.extend(\n          {\n            defaultDate: value || new Date(),\n          },\n          Craft.datepickerOptions\n        )\n      );\n    }\n\n    if (config.hasOuterContainer) {\n      return $container;\n    }\n\n    return $('<div class=\"datetimewrapper\"/>').append($container).datetime();\n  },\n\n  createDateField: function (config) {\n    if (!config.id) {\n      config.id = 'date' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createDateInput(config), config);\n  },\n\n  createDateRangePicker: function (config) {\n    var now = new Date();\n    var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n    config = $.extend(\n      {\n        class: '',\n        options: [\n          'today',\n          'thisWeek',\n          'thisMonth',\n          'thisYear',\n          'past7Days',\n          'past30Days',\n          'past90Days',\n          'pastYear',\n        ],\n        onChange: $.noop,\n        selected: null,\n        startDate: null,\n        endDate: null,\n      },\n      config\n    );\n\n    var $menu = $('<div/>', {class: 'menu'});\n    var $ul = $('<ul/>', {class: 'padded'}).appendTo($menu);\n    var $allOption = $('<a/>')\n      .addClass('sel')\n      .text(Craft.t('app', 'All'))\n      .data('handle', 'all');\n\n    $('<li/>').append($allOption).appendTo($ul);\n\n    var option;\n    var selectedOption;\n    for (var i = 0; i < config.options.length; i++) {\n      var handle = config.options[i];\n      switch (handle) {\n        case 'today':\n          option = {\n            label: Craft.t('app', 'Today'),\n            startDate: today,\n            endDate: today,\n          };\n          break;\n        case 'thisWeek':\n          var firstDayOffset = now.getDay() - Craft.datepickerOptions.firstDay;\n          if (firstDayOffset < 0) {\n            firstDayOffset += 7;\n          }\n          option = {\n            label: Craft.t('app', 'This week'),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - firstDayOffset\n            ),\n            endDate: today,\n          };\n          break;\n        case 'thisMonth':\n          option = {\n            label: Craft.t('app', 'This month'),\n            startDate: new Date(now.getFullYear(), now.getMonth()),\n            endDate: today,\n          };\n          break;\n        case 'thisYear':\n          option = {\n            label: Craft.t('app', 'This year'),\n            startDate: new Date(now.getFullYear(), 0),\n            endDate: today,\n          };\n          break;\n        case 'past7Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 7}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 7\n            ),\n            endDate: today,\n          };\n          break;\n        case 'past30Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 30}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 30\n            ),\n            endDate: today,\n          };\n          break;\n        case 'past90Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 90}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 90\n            ),\n            endDate: today,\n          };\n          break;\n        case 'pastYear':\n          option = {\n            label: Craft.t('app', 'Past year'),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 365\n            ),\n            endDate: today,\n          };\n          break;\n      }\n\n      var $li = $('<li/>');\n      var $a = $('<a/>', {text: option.label})\n        .data('handle', handle)\n        .data('startDate', option.startDate)\n        .data('endDate', option.endDate)\n        .data('startTime', option.startDate ? option.startDate.getTime() : null)\n        .data('endTime', option.endDate ? option.endDate.getTime() : null);\n\n      if (config.selected && handle == config.selected) {\n        selectedOption = $a[0];\n      }\n\n      $li.append($a);\n      $li.appendTo($ul);\n    }\n\n    $('<hr/>').appendTo($menu);\n\n    var $flex = $('<div/>', {class: 'flex flex-nowrap padded'}).appendTo($menu);\n    var $startDate = this.createDateField({label: Craft.t('app', 'From')})\n      .appendTo($flex)\n      .find('input');\n    var $endDate = this.createDateField({label: Craft.t('app', 'To')})\n      .appendTo($flex)\n      .find('input');\n\n    // prevent ESC keypresses in the date inputs from closing the menu\n    var $dateInputs = $startDate.add($endDate);\n    $dateInputs.on('keyup', function (ev) {\n      if (\n        ev.keyCode === Garnish.ESC_KEY &&\n        $(this).data('datepicker') &&\n        $(this).data('datepicker').dpDiv.is(':visible')\n      ) {\n        ev.stopPropagation();\n      }\n    });\n\n    // prevent clicks in the datepicker divs from closing the menu\n    if ($startDate.data('datepicker')) {\n      $startDate.data('datepicker').dpDiv.on('mousedown', function (ev) {\n        ev.stopPropagation();\n      });\n    }\n    if ($endDate.data('datepicker')) {\n      $endDate.data('datepicker').dpDiv.on('mousedown', function (ev) {\n        ev.stopPropagation();\n      });\n    }\n\n    var menu = new Garnish.Menu($menu, {\n      onOptionSelect: function (option) {\n        var $option = $(option);\n        $btn.text($option.text());\n        menu.setPositionRelativeToAnchor();\n        $menu.find('.sel').removeClass('sel');\n        $option.addClass('sel');\n\n        // Update the start/end dates\n        $startDate.datepicker('setDate', $option.data('startDate'));\n        $endDate.datepicker('setDate', $option.data('endDate'));\n\n        config.onChange(\n          $option.data('startDate') || null,\n          $option.data('endDate') || null,\n          $option.data('handle')\n        );\n      },\n    });\n\n    $dateInputs.on('change', function () {\n      // Do the start & end dates match one of our options?\n      let startDate = $startDate.datepicker('getDate');\n      let endDate = $endDate.datepicker('getDate');\n      let startTime = startDate ? startDate.getTime() : null;\n      let endTime = endDate ? endDate.getTime() : null;\n\n      let $options = $ul.find('a');\n      let $option;\n      let foundOption = false;\n\n      for (let i = 0; i < $options.length; i++) {\n        $option = $options.eq(i);\n        if (\n          startTime === ($option.data('startTime') || null) &&\n          endTime === ($option.data('endTime') || null)\n        ) {\n          menu.selectOption($option[0]);\n          foundOption = true;\n          config.onChange(null, null, $option.data('handle'));\n          break;\n        }\n      }\n\n      if (!foundOption) {\n        $menu.find('.sel').removeClass('sel');\n        $flex.addClass('sel');\n\n        if (!startTime && !endTime) {\n          $btn.text(Craft.t('app', 'All'));\n        } else if (startTime && endTime) {\n          $btn.text($startDate.val() + ' - ' + $endDate.val());\n        } else if (startTime) {\n          $btn.text(Craft.t('app', 'From {date}', {date: $startDate.val()}));\n        } else {\n          $btn.text(Craft.t('app', 'To {date}', {date: $endDate.val()}));\n        }\n        menu.setPositionRelativeToAnchor();\n\n        config.onChange(startDate, endDate, 'custom');\n      }\n    });\n\n    menu.on('hide', function () {\n      $startDate.datepicker('hide');\n      $endDate.datepicker('hide');\n    });\n\n    let btnClasses = 'btn menubtn';\n    if (config.class) {\n      btnClasses = btnClasses + ' ' + config.class;\n    }\n\n    let $btn = $('<button/>', {\n      type: 'button',\n      class: btnClasses,\n      'data-icon': 'date',\n      text: Craft.t('app', 'All'),\n    });\n\n    new Garnish.MenuBtn($btn, menu);\n\n    if (selectedOption) {\n      menu.selectOption(selectedOption);\n    }\n\n    if (config.startDate) {\n      $startDate.datepicker('setDate', config.startDate);\n    }\n\n    if (config.endDate) {\n      $endDate.datepicker('setDate', config.endDate);\n    }\n\n    if (config.startDate || config.endDate) {\n      $dateInputs.trigger('change');\n    }\n\n    return $btn;\n  },\n\n  createTimeInput: function (config) {\n    const isMobile = Garnish.isMobileBrowser();\n    const id =\n      (config.id || 'time' + Math.floor(Math.random() * 1000000000)) + '-time';\n    const name = config.name || null;\n    const inputName = name ? name + '[time]' : null;\n    const value =\n      config.value && typeof config.value.getMonth === 'function'\n        ? config.value\n        : null;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      class: 'timewrapper',\n    });\n\n    const $input = this.createTextInput({\n      id: id,\n      type: isMobile ? 'time' : 'text',\n      class: isMobile && !value ? 'empty-value' : false,\n      name: inputName,\n      placeholder: ' ',\n      autocomplete: false,\n      autofocus: autofocus,\n      disabled: disabled,\n    }).appendTo($container);\n\n    $('<div data-icon=\"time\"></div>').appendTo($container);\n\n    if (name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: name + '[timezone]',\n        val: Craft.timezone,\n      }).appendTo($container);\n    }\n\n    if (isMobile) {\n      if (value) {\n        $input.val(value.toISOString().split('T')[1]);\n      }\n      $input.datetimeinput();\n    } else {\n      $input.timepicker(Craft.timepickerOptions);\n      if (value) {\n        $input.timepicker(\n          'setTime',\n          value.getHours() * 3600 + value.getMinutes() * 60 + value.getSeconds()\n        );\n      }\n    }\n\n    if (config.hasOuterContainer) {\n      return $container;\n    }\n\n    return $('<div class=\"datetimewrapper\"/>').append($container).datetime();\n  },\n\n  createTimeField: function (config) {\n    if (!config.id) {\n      config.id = 'time' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTimeInput(config), config);\n  },\n\n  createField: function (input, config) {\n    const label =\n      config.label && config.label !== '__blank__' ? config.label : null;\n\n    const $field = $(config.fieldset ? '<fieldset/>' : '<div/>', {\n      class: 'field',\n      id: config.fieldId || (config.id ? config.id + '-field' : null),\n    });\n\n    if (config.first) {\n      $field.addClass('first');\n    }\n\n    if (config.fieldClass) {\n      $field.addClass(config.fieldClass);\n    }\n\n    if (label && config.fieldset) {\n      $('<legend/>', {\n        text: label,\n        class: 'visually-hidden',\n        'data-label': label,\n      }).appendTo($field);\n    }\n\n    if (label) {\n      const $heading = $('<div class=\"heading\"/>').appendTo($field);\n\n      $(config.fieldset ? '<legend/>' : '<label/>', {\n        id:\n          config.labelId ||\n          (config.id\n            ? `${config.id}-${config.fieldset ? 'legend' : 'label'}`\n            : null),\n        class: config.required ? 'required' : null,\n        for: (!config.fieldset && config.id) || null,\n        text: label,\n      }).appendTo($heading);\n    }\n\n    if (config.instructions) {\n      $('<div class=\"instructions\"/>')\n        .text(config.instructions)\n        .appendTo($field);\n    }\n\n    $('<div class=\"input\"/>').append(input).appendTo($field);\n\n    if (config.tip) {\n      const $tip = $('<p class=\"notice has-icon\"/>');\n      $('<span class=\"icon\" aria-hidden=\"true\"/>').appendTo($tip);\n      $('<span class=\"visually-hidden\"/>')\n        .text(Craft.t('app', 'Tip') + ': ')\n        .appendTo($tip);\n      $('<span/>').text(config.tip).appendTo($tip);\n      $tip.appendTo($field);\n    }\n\n    if (config.warning) {\n      const $warning = $('<p class=\"warning has-icon\"/>');\n      $('<span class=\"icon\" aria-hidden=\"true\"/>').appendTo($warning);\n      $('<span class=\"visually-hidden\"/>')\n        .text(Craft.t('app', 'Warning') + ': ')\n        .appendTo($warning);\n      $('<span/>').text(config.warning).appendTo($warning);\n      $warning.appendTo($field);\n    }\n\n    if (config.errors) {\n      this.addErrorsToField($field, config.errors);\n    }\n\n    return $field;\n  },\n\n  createErrorList: function (errors) {\n    var $list = $('<ul class=\"errors\"/>');\n\n    if (errors) {\n      this.addErrorsToList($list, errors);\n    }\n\n    return $list;\n  },\n\n  addErrorsToList: function ($list, errors) {\n    for (var i = 0; i < errors.length; i++) {\n      $('<li/>').text(errors[i]).appendTo($list);\n    }\n  },\n\n  addErrorsToField: function ($field, errors) {\n    if (!errors) {\n      return;\n    }\n\n    $field.addClass('has-errors');\n    $field.children('.input').addClass('errors');\n\n    var $errors = $field.children('ul.errors');\n\n    if (!$errors.length) {\n      $errors = this.createErrorList().appendTo($field);\n    }\n\n    this.addErrorsToList($errors, errors);\n  },\n\n  clearErrorsFromField: function ($field) {\n    $field.removeClass('has-errors');\n    $field.children('.input').removeClass('errors');\n    $field.children('ul.errors').remove();\n  },\n\n  getAutofocusValue: function (autofocus) {\n    return autofocus && !Garnish.isMobileBrowser(true) ? 'autofocus' : null;\n  },\n\n  getDisabledValue: function (disabled) {\n    return disabled ? 'disabled' : null;\n  },\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.Uploader = Garnish.Base.extend(\n  {\n    uploader: null,\n    allowedKinds: null,\n    $element: null,\n    settings: null,\n    _rejectedFiles: {},\n    _extensionList: null,\n    _totalFileCounter: 0,\n    _validFileCounter: 0,\n\n    init: function ($element, settings) {\n      this._rejectedFiles = {size: [], type: [], limit: []};\n      this.$element = $element;\n      this.allowedKinds = null;\n      this._extensionList = null;\n      this._totalFileCounter = 0;\n      this._validFileCounter = 0;\n\n      settings = $.extend({}, Craft.Uploader.defaults, settings);\n\n      var events = settings.events;\n      delete settings.events;\n\n      if (settings.allowedKinds && settings.allowedKinds.length) {\n        if (typeof settings.allowedKinds === 'string') {\n          settings.allowedKinds = [settings.allowedKinds];\n        }\n\n        this.allowedKinds = settings.allowedKinds;\n        delete settings.allowedKinds;\n      }\n\n      settings.autoUpload = false;\n\n      this.uploader = this.$element.fileupload(settings);\n      for (var event in events) {\n        if (!events.hasOwnProperty(event)) {\n          continue;\n        }\n\n        this.uploader.on(event, events[event]);\n      }\n\n      this.settings = settings;\n\n      this.uploader.on('fileuploadadd', this.onFileAdd.bind(this));\n    },\n\n    /**\n     * Set uploader parameters.\n     */\n    setParams: function (paramObject) {\n      // If CSRF protection isn't enabled, these won't be defined.\n      if (\n        typeof Craft.csrfTokenName !== 'undefined' &&\n        typeof Craft.csrfTokenValue !== 'undefined'\n      ) {\n        // Add the CSRF token\n        paramObject[Craft.csrfTokenName] = Craft.csrfTokenValue;\n      }\n\n      this.uploader.fileupload('option', {formData: paramObject});\n    },\n\n    /**\n     * Get the number of uploads in progress.\n     */\n    getInProgress: function () {\n      return this.uploader.fileupload('active');\n    },\n\n    /**\n     * Return true, if this is the last upload.\n     */\n    isLastUpload: function () {\n      // Processing the last file or not processing at all.\n      return this.getInProgress() < 2;\n    },\n\n    /**\n     * Called on file add.\n     */\n    onFileAdd: function (e, data) {\n      e.stopPropagation();\n\n      var validateExtension = false;\n\n      if (this.allowedKinds) {\n        if (!this._extensionList) {\n          this._createExtensionList();\n        }\n\n        validateExtension = true;\n      }\n\n      // Make sure that file API is there before relying on it\n      data.process().done(() => {\n        var file = data.files[0];\n        var pass = true;\n        if (validateExtension) {\n          var matches = file.name.match(/\\.([a-z0-4_]+)$/i);\n          var fileExtension = matches[1];\n          if (\n            $.inArray(fileExtension.toLowerCase(), this._extensionList) === -1\n          ) {\n            pass = false;\n            this._rejectedFiles.type.push('“' + file.name + '”');\n          }\n        }\n\n        if (file.size > this.settings.maxFileSize) {\n          this._rejectedFiles.size.push('“' + file.name + '”');\n          pass = false;\n        }\n\n        // If the validation has passed for this file up to now, check if we're not hitting any limits\n        if (\n          pass &&\n          typeof this.settings.canAddMoreFiles === 'function' &&\n          !this.settings.canAddMoreFiles(this._validFileCounter)\n        ) {\n          this._rejectedFiles.limit.push('“' + file.name + '”');\n          pass = false;\n        }\n\n        if (pass) {\n          this._validFileCounter++;\n          data.submit();\n        }\n\n        if (++this._totalFileCounter === data.originalFiles.length) {\n          this._totalFileCounter = 0;\n          this._validFileCounter = 0;\n          this.processErrorMessages();\n        }\n      });\n\n      return true;\n    },\n\n    /**\n     * Process error messages.\n     */\n    processErrorMessages: function () {\n      var str;\n\n      if (this._rejectedFiles.type.length) {\n        if (this._rejectedFiles.type.length === 1) {\n          str =\n            'The file {files} could not be uploaded. The allowed file kinds are: {kinds}.';\n        } else {\n          str =\n            'The files {files} could not be uploaded. The allowed file kinds are: {kinds}.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.type.join(', '),\n          kinds: this.allowedKinds.join(', '),\n        });\n        this._rejectedFiles.type = [];\n        Craft.cp.displayError(str);\n      }\n\n      if (this._rejectedFiles.size.length) {\n        if (this._rejectedFiles.size.length === 1) {\n          str =\n            'The file {files} could not be uploaded, because it exceeds the maximum upload size of {size}.';\n        } else {\n          str =\n            'The files {files} could not be uploaded, because they exceeded the maximum upload size of {size}.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.size.join(', '),\n          size: this.humanFileSize(Craft.maxUploadSize),\n        });\n        this._rejectedFiles.size = [];\n        Craft.cp.displayError(str);\n      }\n\n      if (this._rejectedFiles.limit.length) {\n        if (this._rejectedFiles.limit.length === 1) {\n          str =\n            'The file {files} could not be uploaded, because the field limit has been reached.';\n        } else {\n          str =\n            'The files {files} could not be uploaded, because the field limit has been reached.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.limit.join(', '),\n        });\n        this._rejectedFiles.limit = [];\n        Craft.cp.displayError(str);\n      }\n    },\n\n    humanFileSize: function (bytes) {\n      var threshold = 1024;\n\n      if (bytes < threshold) {\n        return bytes + ' B';\n      }\n\n      var units = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n\n      var u = -1;\n\n      do {\n        bytes = bytes / threshold;\n        ++u;\n      } while (bytes >= threshold);\n\n      return bytes.toFixed(1) + ' ' + units[u];\n    },\n\n    _createExtensionList: function () {\n      this._extensionList = [];\n\n      for (var i = 0; i < this.allowedKinds.length; i++) {\n        var allowedKind = this.allowedKinds[i];\n\n        if (typeof Craft.fileKinds[allowedKind] !== 'undefined') {\n          for (\n            var j = 0;\n            j < Craft.fileKinds[allowedKind].extensions.length;\n            j++\n          ) {\n            var ext = Craft.fileKinds[allowedKind].extensions[j];\n            this._extensionList.push(ext);\n          }\n        }\n      }\n    },\n\n    destroy: function () {\n      this.$element.fileupload('destroy');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      dropZone: null,\n      pasteZone: null,\n      fileInput: null,\n      sequentialUploads: true,\n      maxFileSize: Craft.maxUploadSize,\n      allowedKinds: null,\n      events: {},\n      canAddMoreFiles: null,\n      headers: {Accept: 'application/json;q=0.9,*/*;q=0.8'},\n      paramName: 'assets-upload',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.UriFormatGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    sourceVal = sourceVal.replace(/<(.*?)>/g, '');\n\n    // Make it lowercase\n    sourceVal = sourceVal.toLowerCase();\n\n    // Convert extended ASCII characters to basic ASCII\n    sourceVal = Craft.asciiString(sourceVal);\n\n    // Handle must start with a letter and end with a letter/number\n    sourceVal = sourceVal.replace(/^[^a-z]+/, '');\n    sourceVal = sourceVal.replace(/[^a-z0-9]+$/, '');\n\n    // Get the \"words\"\n    var words = Craft.filterArray(sourceVal.split(/[^a-z0-9]+/));\n\n    var uriFormat = words.join(Craft.slugWordSeparator);\n\n    if (uriFormat && this.settings.suffix) {\n      uriFormat += this.settings.suffix;\n    }\n\n    return uriFormat;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * User index class\n */\nCraft.UserIndex = Craft.BaseElementIndex.extend({\n  init: function (elementType, $container, settings) {\n    this.on('selectSource', this.updateUrl.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific group in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultSourceSlug !== 'undefined'\n    ) {\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = $(this.$sources[i]);\n        if ($source.data('slug') === defaultSourceSlug) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateUrl: function () {\n    if (this.settings.context === 'index') {\n      let uri = 'users';\n      const slug = this.$source.data('slug');\n      if (slug) {\n        uri += `/${slug}`;\n      }\n      Craft.setPath(uri);\n    }\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\User', Craft.UserIndex);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Volume folder selector modal class\n */\nCraft.VolumeFolderSelectorModal = Craft.BaseElementSelectorModal.extend(\n  {\n    init: function (settings) {\n      settings = Object.assign(\n        {},\n        Craft.VolumeFolderSelectorModal.defaults,\n        settings,\n        {\n          showSiteMenu: false,\n        }\n      );\n      settings.indexSettings.disabledFolderIds = settings.disabledFolderIds;\n      this.base('craft\\\\elements\\\\Asset', settings);\n    },\n\n    getElementIndexParams: function () {\n      return Object.assign({}, this.base(), {\n        foldersOnly: true,\n      });\n    },\n\n    hasSelection: function () {\n      return (\n        this.base() ||\n        (this.elementIndex &&\n          this.elementIndex.sourcePath.length &&\n          typeof this.elementIndex.sourcePath[\n            this.elementIndex.sourcePath.length - 1\n          ].folderId !== 'undefined' &&\n          !this.settings.disabledFolderIds.includes(\n            this.elementIndex.sourcePath[\n              this.elementIndex.sourcePath.length - 1\n            ].folderId\n          ))\n      );\n    },\n\n    getElementInfo: function ($selectedElements) {\n      return [\n        {\n          folderId: $selectedElements.length\n            ? parseInt(\n                $selectedElements.find('.element:first').data('folder-id')\n              )\n            : this.elementIndex.sourcePath[\n                this.elementIndex.sourcePath.length - 1\n              ].folderId,\n        },\n      ];\n    },\n\n    getIndexSettings: function () {\n      return Object.assign(this.base(), {\n        foldersOnly: true,\n        canSelectElement: ($element) => {\n          const folderId = $element.find('.element:first').data('folder-id');\n          return (\n            folderId && !this.settings.disabledFolderIds.includes(folderId)\n          );\n        },\n      });\n    },\n  },\n  {\n    defaults: {\n      disabledFolderIds: [],\n      indexSettings: {},\n    },\n  }\n);\n","// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = require(\"!!../../../../../../node_modules/mini-css-extract-plugin/dist/loader.js??ruleSet[1].rules[3].use[1]!../../../../../../node_modules/css-loader/dist/cjs.js!../../../../../../node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!../../../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./charts.scss\");\nif(content.__esModule) content = content.default;\nif(typeof content === 'string') content = [[module.id, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = require(\"!../../../../../../node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"3790022a\", content, true, {});","// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = require(\"!!../../../../../../node_modules/mini-css-extract-plugin/dist/loader.js??ruleSet[1].rules[3].use[1]!../../../../../../node_modules/css-loader/dist/cjs.js!../../../../../../node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!../../../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./craft.scss\");\nif(content.__esModule) content = content.default;\nif(typeof content === 'string') content = [[module.id, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = require(\"!../../../../../../node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"80058a3c\", content, true, {});","/**\n * Translates the list format produced by css-loader into something\n * easier to manipulate.\n */\nexport default function listToStyles (parentId, list) {\n  var styles = []\n  var newStyles = {}\n  for (var i = 0; i < list.length; i++) {\n    var item = list[i]\n    var id = item[0]\n    var css = item[1]\n    var media = item[2]\n    var sourceMap = item[3]\n    var part = {\n      id: parentId + ':' + i,\n      css: css,\n      media: media,\n      sourceMap: sourceMap\n    }\n    if (!newStyles[id]) {\n      styles.push(newStyles[id] = { id: id, parts: [part] })\n    } else {\n      newStyles[id].parts.push(part)\n    }\n  }\n  return styles\n}\n","/*\n  MIT License http://www.opensource.org/licenses/mit-license.php\n  Author Tobias Koppers @sokra\n  Modified by Evan You @yyx990803\n*/\n\nimport listToStyles from './listToStyles'\n\nvar hasDocument = typeof document !== 'undefined'\n\nif (typeof DEBUG !== 'undefined' && DEBUG) {\n  if (!hasDocument) {\n    throw new Error(\n    'vue-style-loader cannot be used in a non-browser environment. ' +\n    \"Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.\"\n  ) }\n}\n\n/*\ntype StyleObject = {\n  id: number;\n  parts: Array<StyleObjectPart>\n}\n\ntype StyleObjectPart = {\n  css: string;\n  media: string;\n  sourceMap: ?string\n}\n*/\n\nvar stylesInDom = {/*\n  [id: number]: {\n    id: number,\n    refs: number,\n    parts: Array<(obj?: StyleObjectPart) => void>\n  }\n*/}\n\nvar head = hasDocument && (document.head || document.getElementsByTagName('head')[0])\nvar singletonElement = null\nvar singletonCounter = 0\nvar isProduction = false\nvar noop = function () {}\nvar options = null\nvar ssrIdKey = 'data-vue-ssr-id'\n\n// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>\n// tags it will allow on a page\nvar isOldIE = typeof navigator !== 'undefined' && /msie [6-9]\\b/.test(navigator.userAgent.toLowerCase())\n\nexport default function addStylesClient (parentId, list, _isProduction, _options) {\n  isProduction = _isProduction\n\n  options = _options || {}\n\n  var styles = listToStyles(parentId, list)\n  addStylesToDom(styles)\n\n  return function update (newList) {\n    var mayRemove = []\n    for (var i = 0; i < styles.length; i++) {\n      var item = styles[i]\n      var domStyle = stylesInDom[item.id]\n      domStyle.refs--\n      mayRemove.push(domStyle)\n    }\n    if (newList) {\n      styles = listToStyles(parentId, newList)\n      addStylesToDom(styles)\n    } else {\n      styles = []\n    }\n    for (var i = 0; i < mayRemove.length; i++) {\n      var domStyle = mayRemove[i]\n      if (domStyle.refs === 0) {\n        for (var j = 0; j < domStyle.parts.length; j++) {\n          domStyle.parts[j]()\n        }\n        delete stylesInDom[domStyle.id]\n      }\n    }\n  }\n}\n\nfunction addStylesToDom (styles /* Array<StyleObject> */) {\n  for (var i = 0; i < styles.length; i++) {\n    var item = styles[i]\n    var domStyle = stylesInDom[item.id]\n    if (domStyle) {\n      domStyle.refs++\n      for (var j = 0; j < domStyle.parts.length; j++) {\n        domStyle.parts[j](item.parts[j])\n      }\n      for (; j < item.parts.length; j++) {\n        domStyle.parts.push(addStyle(item.parts[j]))\n      }\n      if (domStyle.parts.length > item.parts.length) {\n        domStyle.parts.length = item.parts.length\n      }\n    } else {\n      var parts = []\n      for (var j = 0; j < item.parts.length; j++) {\n        parts.push(addStyle(item.parts[j]))\n      }\n      stylesInDom[item.id] = { id: item.id, refs: 1, parts: parts }\n    }\n  }\n}\n\nfunction createStyleElement () {\n  var styleElement = document.createElement('style')\n  styleElement.type = 'text/css'\n  head.appendChild(styleElement)\n  return styleElement\n}\n\nfunction addStyle (obj /* StyleObjectPart */) {\n  var update, remove\n  var styleElement = document.querySelector('style[' + ssrIdKey + '~=\"' + obj.id + '\"]')\n\n  if (styleElement) {\n    if (isProduction) {\n      // has SSR styles and in production mode.\n      // simply do nothing.\n      return noop\n    } else {\n      // has SSR styles but in dev mode.\n      // for some reason Chrome can't handle source map in server-rendered\n      // style tags - source maps in <style> only works if the style tag is\n      // created and inserted dynamically. So we remove the server rendered\n      // styles and inject new ones.\n      styleElement.parentNode.removeChild(styleElement)\n    }\n  }\n\n  if (isOldIE) {\n    // use singleton mode for IE9.\n    var styleIndex = singletonCounter++\n    styleElement = singletonElement || (singletonElement = createStyleElement())\n    update = applyToSingletonTag.bind(null, styleElement, styleIndex, false)\n    remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true)\n  } else {\n    // use multi-style-tag mode in all other cases\n    styleElement = createStyleElement()\n    update = applyToTag.bind(null, styleElement)\n    remove = function () {\n      styleElement.parentNode.removeChild(styleElement)\n    }\n  }\n\n  update(obj)\n\n  return function updateStyle (newObj /* StyleObjectPart */) {\n    if (newObj) {\n      if (newObj.css === obj.css &&\n          newObj.media === obj.media &&\n          newObj.sourceMap === obj.sourceMap) {\n        return\n      }\n      update(obj = newObj)\n    } else {\n      remove()\n    }\n  }\n}\n\nvar replaceText = (function () {\n  var textStore = []\n\n  return function (index, replacement) {\n    textStore[index] = replacement\n    return textStore.filter(Boolean).join('\\n')\n  }\n})()\n\nfunction applyToSingletonTag (styleElement, index, remove, obj) {\n  var css = remove ? '' : obj.css\n\n  if (styleElement.styleSheet) {\n    styleElement.styleSheet.cssText = replaceText(index, css)\n  } else {\n    var cssNode = document.createTextNode(css)\n    var childNodes = styleElement.childNodes\n    if (childNodes[index]) styleElement.removeChild(childNodes[index])\n    if (childNodes.length) {\n      styleElement.insertBefore(cssNode, childNodes[index])\n    } else {\n      styleElement.appendChild(cssNode)\n    }\n  }\n}\n\nfunction applyToTag (styleElement, obj) {\n  var css = obj.css\n  var media = obj.media\n  var sourceMap = obj.sourceMap\n\n  if (media) {\n    styleElement.setAttribute('media', media)\n  }\n  if (options.ssrId) {\n    styleElement.setAttribute(ssrIdKey, obj.id)\n  }\n\n  if (sourceMap) {\n    // https://developer.chrome.com/devtools/docs/javascript-debugging\n    // this makes source maps inside style tags work properly in Chrome\n    css += '\\n/*# sourceURL=' + sourceMap.sources[0] + ' */'\n    // http://stackoverflow.com/a/26603875\n    css += '\\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */'\n  }\n\n  if (styleElement.styleSheet) {\n    styleElement.styleSheet.cssText = css\n  } else {\n    while (styleElement.firstChild) {\n      styleElement.removeChild(styleElement.firstChild)\n    }\n    styleElement.appendChild(document.createTextNode(css))\n  }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = function(module) {\n\tvar getter = module && module.__esModule ?\n\t\tfunction() { return module['default']; } :\n\t\tfunction() { return module; };\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }","var __WEBPACK_NAMESPACE_OBJECT__ = jQuery;","/** global: Craft */\n/** global: Garnish */\nimport $ from 'jquery';\n\n/**\n * CP class\n */\nCraft.CP = Garnish.Base.extend(\n  {\n    elementThumbLoader: null,\n    authManager: null,\n\n    $nav: null,\n    $navToggle: null,\n    $globalSidebar: null,\n    $globalContainer: null,\n    $mainContainer: null,\n    $alerts: null,\n    $crumbs: null,\n    $breadcrumbList: null,\n    $breadcrumbItems: null,\n    $notificationContainer: null,\n    $main: null,\n    $primaryForm: null,\n    $headerContainer: null,\n    $header: null,\n    $mainContent: null,\n    $details: null,\n    $sidebarContainer: null,\n    $sidebarToggle: null,\n    $sidebar: null,\n    $contentContainer: null,\n    $edition: null,\n\n    $confirmUnloadForms: null,\n    $deltaForms: null,\n    $collapsibleTables: null,\n\n    isMobile: null,\n    fixedHeader: false,\n\n    breadcrumbListWidth: 0,\n    breadcrumbDisclosureItem: `<li class=\"breadcrumb-toggle-wrapper\" data-disclosure-item><button data-disclosure-trigger aria-controls=\"breadcrumb-disclosure\" aria-haspopup=\"true\">${Craft.t(\n      'app',\n      'More…'\n    )}</button><div id=\"breadcrumb-disclosure\" class=\"menu menu--disclosure\" data-disclosure-menu><ul></ul></div></li>`,\n\n    tabManager: null,\n\n    enableQueue: true,\n    totalJobs: 0,\n    jobInfo: null,\n    displayedJobInfo: null,\n    displayedJobInfoUnchanged: 1,\n    trackJobProgressTimeout: null,\n    jobProgressIcon: null,\n\n    checkingForUpdates: false,\n    forcingRefreshOnUpdatesCheck: false,\n    includingDetailsOnUpdatesCheck: false,\n    checkForUpdatesCallbacks: null,\n\n    resizeTimeout: null,\n\n    init: function () {\n      this.elementThumbLoader = new Craft.ElementThumbLoader();\n\n      // Is this session going to expire?\n      if (Craft.remainingSessionTime !== 0) {\n        this.authManager = new Craft.AuthManager();\n      }\n\n      // Find all the key elements\n      this.$nav = $('#nav');\n      this.$navToggle = $('#primary-nav-toggle');\n      this.$globalSidebar = $('#global-sidebar');\n      this.$globalContainer = $('#global-container');\n      this.$mainContainer = $('#main-container');\n      this.$alerts = $('#alerts');\n      this.$crumbs = $('#crumbs');\n      this.$breadcrumbList = $('.breadcrumb-list');\n      this.$breadcrumbItems = $('.breadcrumb-list li');\n      this.$notificationContainer = $('#notifications');\n      this.$main = $('#main');\n      this.$primaryForm = $('#main-form');\n      this.$headerContainer = $('#header-container');\n      this.$header = $('#header');\n      this.$mainContent = $('#main-content');\n      this.$details = $('#details');\n      this.$sidebarContainer = $('#sidebar-container');\n      this.$sidebarToggle = $('#sidebar-toggle');\n      this.$sidebar = $('#sidebar');\n      this.$contentContainer = $('#content-container');\n      this.$collapsibleTables = $('table.collapsible');\n\n      this.isMobile = Garnish.isMobileBrowser();\n\n      this.updateContentHeading();\n\n      // Swap any instruction text with info icons\n      let $allInstructions = this.$details.find(\n        '.meta > .field > .instructions'\n      );\n\n      for (let i = 0; i < $allInstructions.length; i++) {\n        let $instructions = $allInstructions.eq(i);\n        let $label = $instructions.siblings('.heading').children('label');\n        $('<span/>', {\n          class: 'info',\n          html: $instructions.children().html(),\n        }).appendTo($label);\n        $instructions.remove();\n      }\n\n      if (!this.isMobile && this.$header.length) {\n        this.addListener(Garnish.$win, 'scroll', 'updateFixedHeader');\n        this.updateFixedHeader();\n      }\n\n      Garnish.$doc.ready(() => {\n        // Update responsive tables on window resize\n        this.addListener(Garnish.$win, 'resize', (ev) => {\n          // Ignore element resizes\n          if (ev.target === window) {\n            this.handleWindowResize();\n\n            clearTimeout(this.resizeTimeout);\n            var cp = this;\n            this.resizeTimeout = setTimeout(function () {\n              cp.setSidebarNavAttributes();\n            }, 100);\n          }\n        });\n        this.handleWindowResize();\n        this.setSidebarNavAttributes();\n\n        // Wait a frame before initializing any confirm-unload forms,\n        // so other JS that runs on ready() has a chance to initialize\n        Garnish.requestAnimationFrame(this.initSpecialForms.bind(this));\n      });\n\n      // Alerts\n      if (this.$alerts.length) {\n        this.initAlerts();\n      }\n\n      // Toggles\n      this.addListener(this.$navToggle, 'click', 'toggleNav');\n      this.addListener(this.$sidebarToggle, 'click', 'toggleSidebar');\n\n      // Does this page have a primary form?\n      if (!this.$primaryForm.length) {\n        this.$primaryForm = $('form[data-saveshortcut]:first');\n      }\n\n      // Does the primary form support the save shortcut?\n      if (\n        this.$primaryForm.length &&\n        Garnish.hasAttr(this.$primaryForm, 'data-saveshortcut')\n      ) {\n        let shortcuts = [];\n        let actions = this.$primaryForm.data('actions');\n        if (typeof actions === 'undefined') {\n          shortcuts.push([\n            {\n              keyCode: Garnish.S_KEY,\n              ctrl: true,\n            },\n            {\n              redirect: this.$primaryForm.data('saveshortcut-redirect'),\n              retainScroll: Garnish.hasAttr(\n                this.$primaryForm,\n                'saveshortcut-scroll'\n              ),\n            },\n          ]);\n        } else {\n          for (let i = 0; i < actions.length; i++) {\n            let action = actions[i];\n            if (!action.shortcut) {\n              continue;\n            }\n            shortcuts.push([\n              {\n                keyCode: Garnish.S_KEY,\n                ctrl: true,\n                shift: !!action.shift,\n              },\n              {\n                action: action.action,\n                redirect: action.redirect,\n                confirm: action.confirm,\n                params: action.params,\n                data: action.data,\n                retainScroll: action.retainScroll,\n              },\n            ]);\n          }\n        }\n        for (let i = 0; i < shortcuts.length; i++) {\n          Garnish.uiLayerManager.registerShortcut(shortcuts[i][0], () => {\n            this.submitPrimaryForm(shortcuts[i][1]);\n          });\n        }\n      }\n\n      this.initTabs();\n\n      if (this.tabManager) {\n        if (window.LOCATION_HASH) {\n          const $tab = this.tabManager.$tabs.filter(\n            `[href=\"#${window.LOCATION_HASH}\"]`\n          );\n          if ($tab.length) {\n            this.tabManager.selectTab($tab);\n          }\n        }\n      }\n\n      // Should we match the previous scroll position?\n      let scrollY = Craft.getLocalStorage('scrollY');\n      if (typeof scrollY !== 'undefined') {\n        Craft.removeLocalStorage('scrollY');\n        Garnish.$doc.ready(() => {\n          Garnish.requestAnimationFrame(() => {\n            window.scrollTo(0, scrollY);\n          });\n        });\n      }\n\n      if ($.isTouchCapable()) {\n        this.$mainContainer.on(\n          'focus',\n          'input, textarea, .focusable-input',\n          this._handleInputFocus.bind(this)\n        );\n        this.$mainContainer.on(\n          'blur',\n          'input, textarea, .focusable-input',\n          this._handleInputBlur.bind(this)\n        );\n      }\n\n      // Announcements HUD\n      if (Craft.announcements.length) {\n        let $btn = $('#announcements-btn').removeClass('hidden');\n        const hasUnreads = Craft.announcements.some((a) => a.unread);\n        let $unreadMessage;\n        if (hasUnreads) {\n          $unreadMessage = $('<span/>', {\n            class: 'visually-hidden',\n            html: Craft.t('app', 'Unread messages'),\n          });\n          $btn.addClass('unread').append($unreadMessage);\n        }\n        let hud;\n        this.addListener($btn, 'click', () => {\n          if (!hud) {\n            let contents = '';\n            Craft.announcements.forEach((a) => {\n              contents +=\n                `<div class=\"announcement ${\n                  a.unread ? 'unread' : ''\n                }\" role=\"listitem\">` +\n                '<div class=\"announcement__header\">' +\n                `<h3 class=\"announcement__heading h2\">${a.heading}</h3>` +\n                '<div class=\"announcement-label-container\">' +\n                `<div class=\"announcement-icon\" aria-hidden=\"true\">${a.icon}</div>` +\n                `<div class=\"announcement-label\">${a.label}</div>` +\n                '</div>' +\n                '</div>' +\n                `<p>${a.body}</p>` +\n                '</div>';\n            });\n            hud = new Garnish.HUD(\n              $btn,\n              `<h2 class=\"visually-hidden\">${Craft.t(\n                'app',\n                'Announcements'\n              )}</h2><div id=\"announcements\" role=\"list\">${contents}</div>`,\n              {\n                onShow: () => {\n                  $btn.addClass('active');\n                },\n                onHide: () => {\n                  $btn.removeClass('active');\n                },\n              }\n            );\n\n            // Open outbound links in new windows\n            $('a', hud.$main).each(function () {\n              if (\n                this.hostname.length &&\n                this.hostname !== location.hostname &&\n                typeof $(this).attr('target') === 'undefined'\n              ) {\n                $(this).attr('rel', 'noopener').attr('target', '_blank');\n              }\n            });\n\n            if (hasUnreads) {\n              $btn.removeClass('unread');\n              $unreadMessage.remove();\n              Craft.sendActionRequest(\n                'POST',\n                'users/mark-announcements-as-read',\n                {\n                  data: {\n                    ids: Craft.announcements.map((a) => a.id),\n                  },\n                }\n              );\n            }\n          } else {\n            hud.show();\n          }\n        });\n      }\n\n      // Add .stuck class to #footer when stuck\n      // h/t https://stackoverflow.com/a/61115077/1688568\n      const footer = document.getElementById('footer');\n      if (footer) {\n        const observer = new IntersectionObserver(\n          ([ev]) => {\n            ev.target.classList.toggle('stuck', ev.intersectionRatio < 1);\n          },\n          {\n            rootMargin: '0px 0px -1px 0px',\n            threshold: [1],\n          }\n        );\n        observer.observe(footer);\n      }\n\n      // Load any element thumbs\n      this.elementThumbLoader.load(this.$mainContent);\n    },\n\n    get $contentHeader() {\n      const $contentHeader = $('#content-header');\n      if ($contentHeader.length) {\n        return $contentHeader;\n      }\n      return $('<header/>', {\n        id: 'content-header',\n        class: 'pane-header',\n      }).prependTo($('#content'));\n    },\n\n    get $noticeContainer() {\n      const $noticeContainer = $('#content-notice');\n      if ($noticeContainer.length) {\n        return $noticeContainer;\n      }\n      return $('<div id=\"content-notice\"/>')\n        .attr('role', 'status')\n        .prependTo(this.$contentHeader);\n    },\n\n    initSpecialForms: function () {\n      // Look for forms that we should watch for changes on\n      this.$confirmUnloadForms = $('form[data-confirm-unload]');\n      this.$deltaForms = $('form[data-delta]');\n\n      if (!this.$confirmUnloadForms.length) {\n        return;\n      }\n\n      const $forms = this.$confirmUnloadForms.add(this.$deltaForms);\n\n      for (let i = 0; i < $forms.length; i++) {\n        const $form = $forms.eq(i);\n        let serialized;\n        if (!$form.data('initialSerializedValue')) {\n          if (typeof $form.data('serializer') === 'function') {\n            serialized = $form.data('serializer')();\n          } else {\n            serialized = $form.serialize();\n          }\n          $form.data('initialSerializedValue', serialized);\n        }\n        this.addListener($form, 'submit', function (ev) {\n          if (Garnish.hasAttr($form, 'data-confirm-unload')) {\n            this.removeListener(Garnish.$win, 'beforeunload');\n          }\n          if (Garnish.hasAttr($form, 'data-delta')) {\n            ev.preventDefault();\n            let serialized;\n            if (typeof $form.data('serializer') === 'function') {\n              serialized = $form.data('serializer')();\n            } else {\n              serialized = $form.serialize();\n            }\n            const data = Craft.findDeltaData(\n              $form.data('initialSerializedValue'),\n              serialized,\n              $form.data('delta-names'),\n              null,\n              $form.data('initial-delta-values'),\n              $form.data('modified-delta-names')\n            );\n            Craft.createForm(data).appendTo(Garnish.$bod).submit();\n          }\n        });\n      }\n\n      this.addListener(Garnish.$win, 'beforeunload', function (ev) {\n        let confirmUnload = false;\n        if (\n          typeof Craft.livePreview !== 'undefined' &&\n          Craft.livePreview.inPreviewMode\n        ) {\n          confirmUnload = true;\n        } else {\n          for (let i = 0; i < this.$confirmUnloadForms.length; i++) {\n            const $form = this.$confirmUnloadForms.eq(i);\n            let serialized;\n            if (typeof $form.data('serializer') === 'function') {\n              serialized = $form.data('serializer')();\n            } else {\n              serialized = $form.serialize();\n            }\n            if ($form.data('initialSerializedValue') !== serialized) {\n              confirmUnload = true;\n              break;\n            }\n          }\n        }\n\n        if (confirmUnload) {\n          var message = Craft.t(\n            'app',\n            'Any changes will be lost if you leave this page.'\n          );\n\n          if (ev) {\n            ev.originalEvent.returnValue = message;\n          } else {\n            window.event.returnValue = message;\n          }\n\n          return message;\n        }\n      });\n    },\n\n    _handleInputFocus: function () {\n      this.updateFixedHeader();\n    },\n\n    _handleInputBlur: function () {\n      this.updateFixedHeader();\n    },\n\n    /**\n     * Submits a form.\n     * @param {Object} [options]\n     * @param {string} [options.action] The `action` param value override\n     * @param {string} [options.redirect] The `redirect` param value override\n     * @param {string} [options.confirm] A confirmation message that should be shown to the user before submit\n     * @param {Object} [options.params] Additional params that should be added to the form, defined as name/value pairs\n     * @param {Object} [options.data] Additional data to be passed to the submit event\n     * @param {boolean} [options.retainScroll] Whether the scroll position should be stored and reapplied on the next page load\n     */\n    submitPrimaryForm: function (options) {\n      // Give other stuff on the page a chance to prepare\n      this.trigger('beforeSaveShortcut');\n\n      if (typeof options !== 'object' || !$.isPlainObject(options)) {\n        options = {};\n      }\n\n      if (!options.redirect) {\n        options.redirect = this.$primaryForm.data('saveshortcut-redirect');\n      }\n\n      if (!options.data) {\n        options.data = {};\n      }\n      options.data.saveShortcut = true;\n\n      Craft.submitForm(this.$primaryForm, options);\n    },\n\n    updateSidebarMenuLabel: function () {\n      this.updateContentHeading();\n    },\n\n    updateContentHeading: function () {\n      const $item = this.$sidebar.find('a.sel:first');\n      const $label = $item.children('.label');\n      $('#content-heading').text($label.length ? $label.text() : $item.text());\n      Garnish.$bod.removeClass('showing-sidebar');\n    },\n\n    toggleNav: function () {\n      const isExpanded = this.navIsExpanded();\n\n      if (isExpanded === null) return;\n\n      if (isExpanded) {\n        this.disableGlobalSidebarLinks();\n        this.$navToggle.focus();\n        this.$navToggle.attr('aria-expanded', 'false');\n        Garnish.$bod.removeClass('showing-nav');\n      } else {\n        this.enableGlobalSidebarLinks();\n        this.$globalSidebar.find(':focusable')[0].focus();\n        this.$navToggle.attr('aria-expanded', 'true');\n        Garnish.$bod.addClass('showing-nav');\n      }\n    },\n\n    enableGlobalSidebarLinks: function () {\n      const focusableItems = this.$globalSidebar.find(':focusable');\n\n      $(focusableItems).each(function () {\n        $(this).attr('tabindex', '0');\n      });\n    },\n\n    disableGlobalSidebarLinks: function () {\n      const focusableItems = this.$globalSidebar.find(':focusable');\n\n      $(focusableItems).each(function () {\n        $(this).attr('tabindex', '-1');\n      });\n    },\n\n    setSidebarNavAttributes: function () {\n      const isExpanded = this.navIsExpanded();\n\n      if (isExpanded === null) return;\n\n      if (!isExpanded) {\n        this.disableGlobalSidebarLinks();\n      } else {\n        this.enableGlobalSidebarLinks();\n      }\n    },\n\n    navIsExpanded: function () {\n      if (!this.$globalSidebar[0]) return null;\n\n      const isAlwaysVisible = getComputedStyle(this.$globalSidebar[0])\n        .getPropertyValue('--is-always-visible')\n        .trim();\n\n      return (\n        this.$navToggle.attr('aria-expanded') === 'true' ||\n        isAlwaysVisible === 'true'\n      );\n    },\n\n    toggleSidebar: function () {\n      const expanded = this.$sidebarToggle.attr('aria-expanded') === 'true';\n      const newState = expanded ? 'false' : 'true';\n      this.$sidebarToggle.attr('aria-expanded', newState);\n      Garnish.$bod.toggleClass('showing-sidebar');\n    },\n\n    initTabs: function () {\n      if (this.tabManager) {\n        this.tabManager.destroy();\n        this.tabManager = null;\n      }\n\n      const $tabs = $('#tabs');\n      if (!$tabs.length) {\n        return;\n      }\n\n      this.tabManager = new Craft.Tabs($tabs);\n\n      this.tabManager.on('selectTab', (ev) => {\n        const href = ev.$tab.attr('href');\n\n        // Show its content area\n        if (href && href.charAt(0) === '#') {\n          $(href).removeClass('hidden');\n        }\n\n        // Trigger a resize event to update any UI components that are listening for it\n        Garnish.$win.trigger('resize');\n\n        // Fixes Redactor fixed toolbars on previously hidden panes\n        Garnish.$doc.trigger('scroll');\n\n        // If there is a revision menu, set its links to this tab ID\n        if (href && href.charAt(0) === '#') {\n          const menuBtn = $('#context-btn').menubtn().data('menubtn');\n          if (menuBtn) {\n            for (let i = 0; i < menuBtn.menu.$options.length; i++) {\n              let a = menuBtn.menu.$options[i];\n              if (a.href) {\n                a.href = a.href.match(/^[^#]*/)[0] + href;\n              }\n            }\n          }\n        }\n\n        if (typeof history !== 'undefined') {\n          // Delay changing the hash so it doesn't cause the browser to jump on page load\n          Garnish.requestAnimationFrame(() => {\n            history.replaceState(undefined, undefined, href);\n          });\n        }\n      });\n\n      this.tabManager.on('deselectTab', (ev) => {\n        const href = ev.$tab.attr('href');\n        if (href && href.charAt(0) === '#') {\n          // Hide its content area\n          $(ev.$tab.attr('href')).addClass('hidden');\n        }\n      });\n    },\n\n    updateTabs: function (tabs) {\n      if (tabs) {\n        const $tabContainer = $(tabs).attr('id', 'tabs');\n        if (this.tabManager) {\n          this.tabManager.$container.replaceWith($tabContainer);\n        } else {\n          $tabContainer.appendTo(this.$contentHeader);\n        }\n        this.initTabs();\n      } else if (this.tabManager) {\n        if (this.tabManager.$container.siblings().length) {\n          this.tabManager.$container.remove();\n        } else {\n          this.tabManager.$container.parent().remove();\n        }\n        this.tabManager.destroy();\n        this.tabManager = null;\n      }\n    },\n\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabsContainer() {\n      return this.tabManager ? this.tabManager.$container : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabsList() {\n      return this.tabManager ? this.tabManager.$tablist : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabs() {\n      return this.tabManager ? this.tabManager.$tablist.find('> a') : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $selectedTab() {\n      return this.tabManager ? this.tabManager.$selectedTab : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get selectedTabIndex() {\n      return this.tabManager\n        ? this.tabManager.$tabs.index(this.tabManager.$selectedTab)\n        : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $focusableTab() {\n      return this.tabManager ? this.tabManager.$focusableTab : undefined;\n    },\n    /**\n     * @param {(jQuery|HTMLElement|string)} tab\n     * @deprecated in 3.7.0\n     */\n    selectTab: function (tab) {\n      if (this.tabManager) {\n        this.tabManager.selectTab(tab);\n      }\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    deselectTab: function () {\n      if (this.tabManager) {\n        this.tabManager.deselectTab();\n      }\n    },\n\n    handleWindowResize: function () {\n      this.updateResponsiveTables();\n      this.handleBreadcrumbVisibility();\n    },\n\n    breadcrumbItemsWrap: function () {\n      if (!this.$breadcrumbItems[0]) return;\n\n      this.$breadcrumbList.css(\n        Craft.orientation === 'ltr' ? 'margin-right' : 'margin-left',\n        ''\n      );\n      const listWidth = this.$breadcrumbList[0].getBoundingClientRect().width;\n      let totalItemWidth = 0;\n\n      // Iterate through all list items (inclusive of more button)\n      const $items = this.$breadcrumbList.find('li');\n      for (let i = 0; i < $items.length; i++) {\n        totalItemWidth += $items.get(i).getBoundingClientRect().width;\n      }\n\n      this.breadcrumbListWidth = listWidth;\n\n      if (totalItemWidth <= listWidth) {\n        return false;\n      }\n\n      // If it's less than a pixel off, it's probably just a rounding error.\n      // Give the container an extra pixel to be safe, though\n      if (totalItemWidth < listWidth + 1) {\n        this.$breadcrumbList.css(\n          Craft.orientation === 'ltr' ? 'margin-right' : 'margin-left',\n          '-1px'\n        );\n        return false;\n      }\n\n      return true;\n    },\n\n    handleBreadcrumbVisibility: function () {\n      if (!this.breadcrumbItemsWrap()) return;\n\n      if (this.$breadcrumbList.find('[data-disclosure-item]').length === 0) {\n        this.$breadcrumbList.append(this.breadcrumbDisclosureItem);\n      }\n\n      const triggerWidth = this.$breadcrumbList.find(\n        '[data-disclosure-item]'\n      )[0].offsetWidth;\n      let visibleItemWidth = triggerWidth;\n      let finalIndex;\n      let newWidth;\n      const listWidth = this.breadcrumbListWidth;\n\n      // Find breadcrumbs that should remain visible without overflowing\n      this.$breadcrumbItems.each(function (index) {\n        newWidth = visibleItemWidth + this.offsetWidth;\n\n        if (newWidth < listWidth) {\n          finalIndex = index;\n          visibleItemWidth += this.offsetWidth;\n        } else {\n          return false;\n        }\n      });\n\n      // Separate breadcrums that should remain visible vs. hidden\n      const shownItems = this.$breadcrumbItems.slice(0, finalIndex + 1);\n      const hiddenItems = this.$breadcrumbItems.slice(finalIndex + 1);\n\n      // Empty list DOM and add shown items and trigger item\n      this.$breadcrumbList.html('');\n      this.$breadcrumbList.append(shownItems);\n      this.$breadcrumbList.append(this.breadcrumbDisclosureItem);\n\n      // Add hidden items to disclosure menu and initialize\n      this.$breadcrumbList\n        .find('[data-disclosure-menu] ul')\n        .append(hiddenItems);\n      this.$breadcrumbList.find('[data-disclosure-trigger]').disclosureMenu();\n    },\n\n    updateResponsiveTables: function () {\n      for (\n        this.updateResponsiveTables._i = 0;\n        this.updateResponsiveTables._i < this.$collapsibleTables.length;\n        this.updateResponsiveTables._i++\n      ) {\n        this.updateResponsiveTables._$table = this.$collapsibleTables.eq(\n          this.updateResponsiveTables._i\n        );\n        this.updateResponsiveTables._containerWidth =\n          this.updateResponsiveTables._$table.parent().width();\n        this.updateResponsiveTables._check = false;\n\n        if (this.updateResponsiveTables._containerWidth > 0) {\n          // Is this the first time we've checked this table?\n          if (\n            typeof this.updateResponsiveTables._$table.data(\n              'lastContainerWidth'\n            ) === 'undefined'\n          ) {\n            this.updateResponsiveTables._check = true;\n          } else {\n            this.updateResponsiveTables._isCollapsed =\n              this.updateResponsiveTables._$table.hasClass('collapsed');\n\n            // Getting wider?\n            if (\n              this.updateResponsiveTables._containerWidth >\n              this.updateResponsiveTables._$table.data('lastContainerWidth')\n            ) {\n              if (this.updateResponsiveTables._isCollapsed) {\n                this.updateResponsiveTables._$table.removeClass('collapsed');\n                this.updateResponsiveTables._check = true;\n              }\n            } else if (!this.updateResponsiveTables._isCollapsed) {\n              this.updateResponsiveTables._check = true;\n            }\n          }\n\n          // Are we checking the table width?\n          if (this.updateResponsiveTables._check) {\n            if (\n              this.updateResponsiveTables._$table.width() - 30 >\n              this.updateResponsiveTables._containerWidth\n            ) {\n              this.updateResponsiveTables._$table.addClass('collapsed');\n            }\n          }\n\n          // Remember the container width for next time\n          this.updateResponsiveTables._$table.data(\n            'lastContainerWidth',\n            this.updateResponsiveTables._containerWidth\n          );\n        }\n      }\n    },\n\n    updateFixedHeader: function () {\n      if (this.isMobile) {\n        return;\n      }\n\n      // Have we scrolled passed the top of #main?\n      if (\n        this.$main.length &&\n        this.$headerContainer[0].getBoundingClientRect().top < 0\n      ) {\n        if (!this.fixedHeader) {\n          var headerHeight = this.$headerContainer.height();\n\n          // Hard-set the minimum content container height\n          this.$contentContainer.css(\n            'min-height',\n            'calc(100vh - ' + (headerHeight + 14 + 48 - 1) + 'px)'\n          );\n\n          // Hard-set the header container height\n          this.$headerContainer.height(headerHeight);\n          Garnish.$bod.addClass('fixed-header');\n\n          // Fix the sidebar and details pane positions if they are taller than #content-container\n          var contentHeight = this.$contentContainer.outerHeight();\n          var $detailsHeight = this.$details.outerHeight();\n          var css = {\n            top: headerHeight + 'px',\n            'max-height': 'calc(100vh - ' + headerHeight + 'px)',\n          };\n          this.$sidebar.addClass('fixed').css(css);\n          this.$details.addClass('fixed').css(css);\n          this.fixedHeader = true;\n        }\n      } else if (this.fixedHeader) {\n        this.$headerContainer.height('auto');\n        Garnish.$bod.removeClass('fixed-header');\n        this.$contentContainer.css('min-height', '');\n        this.$sidebar.removeClass('fixed').css({\n          top: '',\n          'max-height': '',\n        });\n        this.$details.removeClass('fixed').css({\n          top: '',\n          'max-height': '',\n        });\n        this.fixedHeader = false;\n      }\n    },\n\n    /**\n     * Dispays a notification.\n     *\n     * @param {string} type `notice`, `success`, or `error`\n     * @param {string} message\n     * @param {Object} [settings]\n     * @param {string} [settings.icon] The icon to show on the notification\n     * @param {string} [settings.iconLabel] The icon’s ARIA label\n     * @param {string} [settings.details] Any additional HTML that should be included below the message\n     * @returns {Object} The notification\n     */\n    displayNotification: function (type, message, settings) {\n      const notification = new Craft.CP.Notification(type, message, settings);\n\n      this.trigger('displayNotification', {\n        notificationType: type,\n        message,\n        notification,\n      });\n\n      return notification;\n    },\n\n    /**\n     * Displays a notice.\n     *\n     * @param {string} message\n     * @param {Object} [settings]\n     * @param {string} [settings.icon] The icon to show on the notification\n     * @param {string} [settings.iconLabel] The icon’s ARIA label\n     * @param {string} [settings.details] Any additional HTML that should be included below the message\n     * @returns {Object} The notification\n     */\n    displayNotice: function (message, settings) {\n      return this.displayNotification(\n        'notice',\n        message,\n        Object.assign(\n          {\n            icon: 'info',\n            iconLabel: Craft.t('app', 'Notice'),\n          },\n          settings\n        )\n      );\n    },\n\n    /**\n     * Displays a success notification.\n     *\n     * @param {string} message\n     * @param {Object} [settings]\n     * @param {string} [settings.icon] The icon to show on the notification\n     * @param {string} [settings.iconLabel] The icon’s ARIA label\n     * @param {string} [settings.details] Any additional HTML that should be included below the message\n     * @returns {Object} The notification\n     */\n    displaySuccess: function (message, settings) {\n      return this.displayNotification(\n        'success',\n        message,\n        Object.assign(\n          {\n            icon: 'check',\n            iconLabel: Craft.t('app', 'Success'),\n          },\n          settings\n        )\n      );\n    },\n\n    /**\n     * Displays an error.\n     *\n     * @param {string} message\n     * @param {Object} [settings]\n     * @param {string} [settings.icon] The icon to show on the notification\n     * @param {string} [settings.iconLabel] The icon’s ARIA label\n     * @param {string} [settings.details] Any additional HTML that should be included below the message\n     * @returns {Object} The notification\n     */\n    displayError: function (message, settings) {\n      if (!message || typeof message === 'object') {\n        settings = message;\n        message = Craft.t('app', 'A server error occurred.');\n      }\n\n      return this.displayNotification(\n        'error',\n        message,\n        Object.assign(\n          {\n            icon: 'alert',\n            iconLabel: Craft.t('app', 'Error'),\n          },\n          settings\n        )\n      );\n    },\n\n    fetchAlerts: function () {\n      return Craft.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            const data = {\n              path: Craft.path,\n            };\n            Craft.sendActionRequest('POST', 'app/get-cp-alerts', {data})\n              .then(({data}) => {\n                resolve(data.alerts);\n              })\n              .catch(reject);\n          })\n      );\n    },\n\n    displayAlerts: function (alerts) {\n      this.$alerts.remove();\n\n      if (Garnish.isArray(alerts) && alerts.length) {\n        this.$alerts = $('<ul id=\"alerts\"/>').prependTo($('#page-container'));\n\n        for (let alert of alerts) {\n          if (!$.isPlainObject(alert)) {\n            alert = {\n              content: alert,\n              showIcon: true,\n            };\n          }\n          let content = alert.content;\n          if (alert.showIcon) {\n            content = `<span data-icon=\"alert\" aria-label=\"${Craft.t(\n              'app',\n              'Error'\n            )}\"></span> ${content}`;\n          }\n          $(`<li>${content}</li>`).appendTo(this.$alerts);\n        }\n\n        var height = this.$alerts.outerHeight();\n        this.$alerts\n          .css('margin-top', -height)\n          .velocity({'margin-top': 0}, 'fast');\n\n        this.initAlerts();\n      }\n    },\n\n    initAlerts: function () {\n      // Are there any shunnable alerts?\n      var $shunnableAlerts = this.$alerts.find('a[class^=\"shun:\"]');\n\n      for (var i = 0; i < $shunnableAlerts.length; i++) {\n        this.addListener($shunnableAlerts[i], 'click', (ev) => {\n          ev.preventDefault();\n\n          Craft.queue.push(\n            () =>\n              new Promise((resolve, reject) => {\n                const $link = $(ev.currentTarget);\n                const data = {\n                  message: $link.prop('className').substring(5),\n                };\n                Craft.sendActionRequest('POST', 'app/shun-cp-alert', {data})\n                  .then(() => {\n                    $link.parent().remove();\n                    resolve();\n                  })\n                  .catch(({response}) => {\n                    this.displayError(response.data.message);\n                    reject();\n                  });\n              })\n          );\n        });\n      }\n    },\n\n    checkForUpdates: function (forceRefresh, includeDetails, callback) {\n      // Make 'includeDetails' optional\n      if (typeof includeDetails === 'function') {\n        callback = includeDetails;\n        includeDetails = false;\n      }\n\n      // If forceRefresh == true, we're currently checking for updates, and not currently forcing a refresh,\n      // then just set a new callback that re-checks for updates when the current one is done.\n      if (\n        this.checkingForUpdates &&\n        ((forceRefresh === true && !this.forcingRefreshOnUpdatesCheck) ||\n          (includeDetails === true && !this.includingDetailsOnUpdatesCheck))\n      ) {\n        var realCallback = callback;\n        callback = () => {\n          this.checkForUpdates(forceRefresh, includeDetails, realCallback);\n        };\n      }\n\n      // Callback function?\n      if (typeof callback === 'function') {\n        if (!Garnish.isArray(this.checkForUpdatesCallbacks)) {\n          this.checkForUpdatesCallbacks = [];\n        }\n\n        this.checkForUpdatesCallbacks.push(callback);\n      }\n\n      if (!this.checkingForUpdates) {\n        this.checkingForUpdates = true;\n        this.forcingRefreshOnUpdatesCheck = forceRefresh === true;\n        this.includingDetailsOnUpdatesCheck = includeDetails === true;\n\n        this._checkForUpdates(forceRefresh, includeDetails).then((info) => {\n          this.updateUtilitiesBadge();\n          this.checkingForUpdates = false;\n\n          if (Garnish.isArray(this.checkForUpdatesCallbacks)) {\n            var callbacks = this.checkForUpdatesCallbacks;\n            this.checkForUpdatesCallbacks = null;\n\n            for (var i = 0; i < callbacks.length; i++) {\n              callbacks[i](info);\n            }\n          }\n\n          this.trigger('checkForUpdates', {\n            updateInfo: info,\n          });\n        });\n      }\n    },\n\n    _checkForUpdates: function (forceRefresh, includeDetails) {\n      return new Promise((resolve, reject) => {\n        if (!forceRefresh) {\n          this._checkForCachedUpdates(includeDetails)\n            .then((info) => {\n              if (info.cached) {\n                resolve(info);\n                return;\n              }\n\n              this._getUpdates(includeDetails).then((info) => {\n                resolve(info);\n              });\n            })\n            .catch(reject);\n        } else {\n          this._getUpdates(includeDetails).then(resolve).catch(reject);\n        }\n      });\n    },\n\n    _checkForCachedUpdates: function (includeDetails) {\n      return new Promise(function (resolve, reject) {\n        var data = {\n          onlyIfCached: true,\n          includeDetails: includeDetails,\n        };\n\n        Craft.sendActionRequest('POST', 'app/check-for-updates', {data})\n          .then(({data}) => {\n            resolve(data);\n          })\n          .catch(() => {\n            resolve({cached: false});\n          });\n      });\n    },\n\n    _getUpdates: function (includeDetails) {\n      return new Promise((resolve, reject) => {\n        Craft.sendApiRequest('GET', 'updates')\n          .then((updates) => {\n            this._cacheUpdates(updates, includeDetails).then((data) => {\n              resolve(data);\n            });\n          })\n          .catch(reject);\n      });\n    },\n\n    _cacheUpdates: function (updates, includeDetails) {\n      return new Promise((resolve, reject) => {\n        const data = {\n          updates,\n          includeDetails,\n        };\n\n        Craft.sendActionRequest('POST', 'app/cache-updates', {data})\n          .then(({data}) => {\n            resolve(data);\n          })\n          .catch(reject);\n      });\n    },\n\n    updateUtilitiesBadge: function () {\n      var $utilitiesLink = $('#nav-utilities').find('> a:not(.sel)');\n\n      // Ignore if there is no (non-selected) Utilities nav item\n      if (!$utilitiesLink.length) {\n        return;\n      }\n\n      Craft.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            Craft.sendActionRequest('POST', 'app/get-utilities-badge-count')\n              .then(({data}) => {\n                // Get the existing utility nav badge and screen reader text, if any\n                let $badge = $utilitiesLink.children('.badge');\n                let $screenReaderText = $utilitiesLink.children(\n                  '[data-notification]'\n                );\n\n                if (data.badgeCount) {\n                  if (!$badge.length) {\n                    $badge = $(\n                      '<span class=\"badge\" aria-hidden=\"true\"/>'\n                    ).appendTo($utilitiesLink);\n                  }\n\n                  if (!$screenReaderText.length) {\n                    $screenReaderText = $(\n                      '<span class=\"visually-hidden\" data-notification/>'\n                    ).appendTo($utilitiesLink);\n                  }\n\n                  $badge.text(data.badgeCount);\n                  $screenReaderText.text(\n                    Craft.t(\n                      'app',\n                      '{num, number} {num, plural, =1{notification} other{notifications}}',\n                      {\n                        num: data.badgeCount,\n                      }\n                    )\n                  );\n                } else if ($badge.length && $screenReaderText.length) {\n                  $badge.remove();\n                  $screenReaderText.remove();\n                }\n                resolve();\n              })\n              .catch(reject);\n          })\n      );\n    },\n\n    runQueue: function () {\n      if (!this.enableQueue) {\n        return;\n      }\n\n      if (Craft.runQueueAutomatically) {\n        Craft.queue.push(\n          () =>\n            new Promise((resolve, reject) => {\n              Craft.sendActionRequest('POST', 'queue/run')\n                .then(() => {\n                  this.trackJobProgress(false, true);\n                  resolve();\n                })\n                .catch(reject);\n            })\n        );\n      } else {\n        this.trackJobProgress(false, true);\n      }\n    },\n\n    trackJobProgress: function (delay, force) {\n      if (force && this.trackJobProgressTimeout) {\n        clearTimeout(this.trackJobProgressTimeout);\n        this.trackJobProgressTimeout = null;\n      }\n\n      // Ignore if we're already tracking jobs, or the queue is disabled\n      if (this.trackJobProgressTimeout || !this.enableQueue) {\n        return;\n      }\n\n      if (delay === true) {\n        // Determine the delay based on how long the displayed job info has remained unchanged\n        var timeout = Math.min(60000, this.displayedJobInfoUnchanged * 500);\n        this.trackJobProgressTimeout = setTimeout(\n          this._trackJobProgressInternal.bind(this),\n          timeout\n        );\n      } else {\n        this._trackJobProgressInternal();\n      }\n    },\n\n    _trackJobProgressInternal: function () {\n      Craft.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            Craft.sendActionRequest(\n              'POST',\n              'queue/get-job-info?limit=50&dontExtendSession=1'\n            )\n              .then(({data}) => {\n                this.trackJobProgressTimeout = null;\n                this.totalJobs = data.total;\n                this.setJobInfo(data.jobs);\n                if (this.jobInfo.length) {\n                  // Check again after a delay\n                  this.trackJobProgress(true);\n                }\n                resolve();\n              })\n              .catch(reject);\n          })\n      );\n    },\n\n    setJobInfo: function (jobInfo) {\n      if (!this.enableQueue) {\n        return;\n      }\n\n      this.jobInfo = jobInfo;\n\n      // Update the displayed job info\n      var oldInfo = this.displayedJobInfo;\n      this.displayedJobInfo = this.getDisplayedJobInfo();\n\n      // Same old same old?\n      if (\n        oldInfo &&\n        this.displayedJobInfo &&\n        oldInfo.id === this.displayedJobInfo.id &&\n        oldInfo.progress === this.displayedJobInfo.progress &&\n        oldInfo.progressLabel === this.displayedJobInfo.progressLabel &&\n        oldInfo.status === this.displayedJobInfo.status\n      ) {\n        this.displayedJobInfoUnchanged++;\n      } else {\n        // Reset the counter\n        this.displayedJobInfoUnchanged = 1;\n      }\n\n      this.updateJobIcon();\n\n      // Fire a setJobInfo event\n      this.trigger('setJobInfo');\n    },\n\n    /**\n     * Returns info for the job that should be displayed in the control panel sidebar\n     */\n    getDisplayedJobInfo: function () {\n      if (!this.enableQueue) {\n        return null;\n      }\n\n      // Set the status preference order\n      var statuses = [\n        Craft.CP.JOB_STATUS_RESERVED,\n        Craft.CP.JOB_STATUS_FAILED,\n        Craft.CP.JOB_STATUS_WAITING,\n      ];\n\n      for (var i = 0; i < statuses.length; i++) {\n        for (var j = 0; j < this.jobInfo.length; j++) {\n          if (\n            this.jobInfo[j].status === statuses[i] &&\n            (statuses[i] !== Craft.CP.JOB_STATUS_WAITING ||\n              !this.jobInfo[j].delay)\n          ) {\n            return this.jobInfo[j];\n          }\n        }\n      }\n\n      return null;\n    },\n\n    updateJobIcon: function () {\n      if (!this.enableQueue || !this.$nav.length) {\n        return;\n      }\n\n      if (this.displayedJobInfo) {\n        if (!this.jobProgressIcon) {\n          this.jobProgressIcon = new JobProgressIcon();\n        }\n\n        if (\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_RESERVED ||\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_WAITING\n        ) {\n          this.jobProgressIcon.hideFailMode();\n          this.jobProgressIcon.setDescription(\n            this.displayedJobInfo.description,\n            this.displayedJobInfo.progressLabel\n          );\n          this.jobProgressIcon.setProgress(this.displayedJobInfo.progress);\n        } else if (\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_FAILED\n        ) {\n          this.jobProgressIcon.showFailMode(Craft.t('app', 'Failed'));\n        }\n      } else {\n        if (this.jobProgressIcon) {\n          this.jobProgressIcon.hideFailMode();\n          this.jobProgressIcon.complete();\n          delete this.jobProgressIcon;\n        }\n      }\n    },\n\n    /**\n     * Returns the active site for the control panel\n     *\n     * @returns {number}\n     */\n    getSiteId: function () {\n      // If the old BaseElementIndex.siteId value is in localStorage, go aheand and remove & return that\n      let siteId = Craft.getLocalStorage('BaseElementIndex.siteId');\n      if (typeof siteId !== 'undefined') {\n        Craft.removeLocalStorage('BaseElementIndex.siteId');\n        try {\n          this.setSiteId(siteId);\n        } catch (e) {}\n      }\n      return Craft.siteId;\n    },\n\n    /**\n     * Sets the active site for the control panel\n     * @param {number} siteId\n     */\n    setSiteId: function (siteId) {\n      const site = Craft.sites.find((s) => s.id === siteId);\n\n      if (!site) {\n        throw `Invalid site ID: ${siteId}`;\n      }\n\n      Craft.siteId = siteId;\n\n      // update the base URLs used get Craft.getUrl(), etc.\n      Craft.actionUrl = Craft.getUrl(Craft.actionUrl, {site: site.handle});\n      Craft.baseCpUrl = Craft.getUrl(Craft.baseCpUrl, {site: site.handle});\n      Craft.baseUrl = Craft.getUrl(Craft.baseUrl, {site: site.handle});\n\n      // update the current URL\n      const url = Craft.getUrl(document.location.href, {site: site.handle});\n      history.replaceState({}, '', url);\n\n      // update the site--x body class\n      for (let className of document.body.classList) {\n        if (className.match(/^site--/)) {\n          document.body.classList.remove(className);\n        }\n      }\n      document.body.classList.add(`site--${site.handle}`);\n\n      // update other URLs on the page\n      $('a').each(function () {\n        if (\n          this.hostname.length &&\n          this.hostname === location.hostname &&\n          this.href.indexOf(Craft.cpTrigger) !== -1\n        ) {\n          this.href = Craft.getUrl(this.href, {site: site.handle});\n        }\n      });\n    },\n  },\n  {\n    //maxWidth: 1051, //1024,\n\n    /**\n     * @deprecated in 4.2.0. Use Craft.notificationDuration instead.\n     */\n    notificationDuration: 5000,\n\n    JOB_STATUS_WAITING: 1,\n    JOB_STATUS_RESERVED: 2,\n    JOB_STATUS_DONE: 3,\n    JOB_STATUS_FAILED: 4,\n  }\n);\n\nCraft.CP.Notification = Garnish.Base.extend({\n  type: null,\n  message: null,\n  settings: null,\n  closing: false,\n  closeTimeout: null,\n  _preventDelayedClose: false,\n  $container: null,\n  $closeBtn: null,\n  originalActiveElement: null,\n\n  init: function (type, message, settings) {\n    this.type = type;\n    this.message = message;\n    this.settings = settings || {};\n\n    this.$container = $('<div/>', {\n      class: 'notification',\n      'data-type': this.type,\n    }).appendTo(Craft.cp.$notificationContainer);\n\n    const $body = $('<div class=\"notification-body\"/>').appendTo(\n      this.$container\n    );\n\n    if (this.settings.icon) {\n      const $icon = $('<span/>', {\n        class: 'notification-icon',\n        'data-icon': this.settings.icon,\n      }).appendTo($body);\n      if (this.settings.iconLabel) {\n        $icon.attr({\n          'aria-label': this.settings.iconLabel,\n          role: 'img',\n        });\n      } else {\n        $icon.attr('aria-hidden', 'true');\n      }\n    }\n\n    const $main = $('<div class=\"notification-main\"/>').appendTo($body);\n\n    $('<div/>', {\n      class: 'notification-message',\n      text: this.message,\n    }).appendTo($main);\n\n    const $closeBtnContainer = $('<div/>').appendTo(this.$container);\n    this.$closeBtn = $('<button/>', {\n      type: 'button',\n      class: 'notification-close-btn',\n      'aria-label': Craft.t('app', 'Close'),\n      'data-icon': 'remove',\n    }).appendTo($closeBtnContainer);\n\n    if (this.settings.details) {\n      const $detailsContainer = $('<div class=\"notification-details\"/>')\n        .append(this.settings.details)\n        .appendTo($main);\n\n      const $focusableElement = $detailsContainer.find('button,input');\n      if ($focusableElement.length) {\n        Garnish.uiLayerManager.addLayer(this.$container);\n        Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n          this.close();\n        });\n        this.originalActiveElement = document.activeElement;\n        this.$container.attr('tabindex', '-1').focus();\n        this.$container.on('keydown', (ev) => {\n          if (ev.keyCode === Garnish.ESC_KEY) {\n            ev.stopPropagation();\n            this.close();\n          }\n        });\n      }\n    }\n\n    this.$container\n      .css({\n        opacity: 0,\n        'margin-bottom': this._negMargin(),\n      })\n      .velocity({opacity: 1, 'margin-bottom': 0}, {duration: 'fast'});\n\n    Craft.initUiElements(this.$container);\n\n    this.addListener(this.$closeBtn, 'click', 'close');\n\n    if (Craft.notificationDuration) {\n      this._initDelayedClose();\n    }\n  },\n\n  _initDelayedClose: function () {\n    if (this._preventDelayedClose) {\n      return;\n    }\n\n    if (!Craft.isVisible()) {\n      Garnish.$doc.one('visibilitychange', () => {\n        this._initDelayedClose();\n      });\n      return;\n    }\n\n    this.delayedClose();\n\n    this.$container.on(\n      'keypress keyup change focus blur click mousedown mouseup',\n      (ev) => {\n        if (ev.target != this.$closeBtn[0]) {\n          this.$container.off(\n            'keypress keyup change focus blur click mousedown mouseup'\n          );\n          this.preventDelayedClose();\n        }\n      }\n    );\n  },\n\n  _negMargin: function () {\n    return `-${this.$container.outerHeight() + 12}px`;\n  },\n\n  close: function () {\n    if (this.closing) {\n      return;\n    }\n\n    if (this.closeTimeout) {\n      clearTimeout(this.closeTimeout);\n      this.closeTimeout = null;\n    }\n\n    this.closing = true;\n\n    if (\n      this.originalActiveElement &&\n      document.activeElement &&\n      (document.activeElement === this.$container[0] ||\n        $.contains(this.$container[0], document.activeElement))\n    ) {\n      $(this.originalActiveElement).focus();\n    }\n\n    this.$container.velocity(\n      {opacity: 0, 'margin-bottom': this._negMargin()},\n      {\n        duration: 'fast',\n        complete: () => {\n          this.$container.remove();\n        },\n      }\n    );\n  },\n\n  delayedClose: function () {\n    this.closeTimeout = setTimeout(() => {\n      this.close();\n    }, Craft.notificationDuration);\n\n    // Hold off on closing automatically on hover\n    this.$container.one('mouseover', () => {\n      clearTimeout(this.closeTimeout);\n      this.closeTimeout = null;\n\n      this.$container.on('mouseout', (ev) => {\n        if (ev.target == this.$container[0]) {\n          this.$container.off('mouseout');\n          this.delayedClose();\n        }\n      });\n    });\n  },\n\n  preventDelayedClose: function () {\n    this._preventDelayedClose = true;\n\n    if (this.closeTimeout) {\n      clearTimeout(this.closeTimeout);\n      this.closeTimeout = null;\n    }\n\n    this.$container.off('mouseover mouseout');\n  },\n});\n\nGarnish.$scrollContainer = Garnish.$win;\nCraft.cp = new Craft.CP();\n\n/**\n * Job progress icon class\n */\nvar JobProgressIcon = Garnish.Base.extend({\n  $li: null,\n  $a: null,\n  $label: null,\n  $progressLabel: null,\n\n  progress: null,\n  failMode: false,\n\n  _$bgCanvas: null,\n  _$staticCanvas: null,\n  _$hoverCanvas: null,\n  _$failCanvas: null,\n\n  _staticCtx: null,\n  _hoverCtx: null,\n  _canvasSize: null,\n  _arcPos: null,\n  _arcRadius: null,\n  _lineWidth: null,\n\n  _arcStartPos: 0,\n  _arcEndPos: 0,\n  _arcStartStepSize: null,\n  _arcEndStepSize: null,\n  _arcStep: null,\n  _arcStepTimeout: null,\n  _arcAnimateCallback: null,\n\n  _progressBar: null,\n\n  init: function () {\n    this.$li = $('<li/>').appendTo(Craft.cp.$nav.children('ul'));\n    this.$a = $('<a/>', {\n      id: 'job-icon',\n      href: Craft.canAccessQueueManager\n        ? Craft.getUrl('utilities/queue-manager')\n        : null,\n    }).appendTo(this.$li);\n    this.$canvasContainer = $('<span class=\"icon\"/>').appendTo(this.$a);\n    var $labelContainer = $('<span class=\"label\"/>').appendTo(this.$a);\n    this.$label = $('<span/>').appendTo($labelContainer);\n    this.$progressLabel = $('<span class=\"progress-label\"/>')\n      .appendTo($labelContainer)\n      .hide();\n\n    let m = window.devicePixelRatio > 1 ? 2 : 1;\n    this._canvasSize = 18 * m;\n    this._arcPos = this._canvasSize / 2;\n    this._arcRadius = 7 * m;\n    this._lineWidth = 3 * m;\n\n    this._$bgCanvas = this._createCanvas('bg', '#61666b');\n    this._$staticCanvas = this._createCanvas('static', '#d7d9db');\n    this._$hoverCanvas = this._createCanvas('hover', '#fff');\n    this._$failCanvas = this._createCanvas('fail', '#da5a47').hide();\n\n    this._staticCtx = this._$staticCanvas[0].getContext('2d');\n    this._hoverCtx = this._$hoverCanvas[0].getContext('2d');\n\n    this._drawArc(this._$bgCanvas[0].getContext('2d'), 0, 1);\n    this._drawArc(this._$failCanvas[0].getContext('2d'), 0, 1);\n  },\n\n  setDescription: function (description, progressLabel) {\n    this.$a.attr('title', description);\n    this.$label.text(description);\n    if (progressLabel) {\n      this.$progressLabel.text(progressLabel).show();\n    } else {\n      this.$progressLabel.hide();\n    }\n  },\n\n  setProgress: function (progress) {\n    if (progress == 0) {\n      this._$staticCanvas.hide();\n      this._$hoverCanvas.hide();\n    } else {\n      this._$staticCanvas.show();\n      this._$hoverCanvas.show();\n      if (this.progress && progress > this.progress) {\n        this._animateArc(0, progress / 100);\n      } else {\n        this._setArc(0, progress / 100);\n      }\n    }\n\n    this.progress = progress;\n  },\n\n  complete: function () {\n    this._animateArc(0, 1, () => {\n      this._$bgCanvas.velocity('fadeOut');\n\n      this._animateArc(1, 1, () => {\n        this.$a.remove();\n        this.destroy();\n      });\n    });\n  },\n\n  showFailMode: function (message) {\n    if (this.failMode) {\n      return;\n    }\n\n    this.failMode = true;\n    this.progress = null;\n\n    this._$bgCanvas.hide();\n    this._$staticCanvas.hide();\n    this._$hoverCanvas.hide();\n    this._$failCanvas.show();\n\n    this.setDescription(message);\n  },\n\n  hideFailMode: function () {\n    if (!this.failMode) {\n      return;\n    }\n\n    this.failMode = false;\n\n    this._$bgCanvas.show();\n    this._$staticCanvas.show();\n    this._$hoverCanvas.show();\n    this._$failCanvas.hide();\n  },\n\n  _createCanvas: function (id, color) {\n    var $canvas = $(\n        '<canvas id=\"job-icon-' +\n          id +\n          '\" width=\"' +\n          this._canvasSize +\n          '\" height=\"' +\n          this._canvasSize +\n          '\"/>'\n      ).appendTo(this.$canvasContainer),\n      ctx = $canvas[0].getContext('2d');\n\n    ctx.strokeStyle = color;\n    ctx.lineWidth = this._lineWidth;\n    ctx.lineCap = 'round';\n    return $canvas;\n  },\n\n  _setArc: function (startPos, endPos) {\n    this._arcStartPos = startPos;\n    this._arcEndPos = endPos;\n\n    this._drawArc(this._staticCtx, startPos, endPos);\n    this._drawArc(this._hoverCtx, startPos, endPos);\n  },\n\n  _drawArc: function (ctx, startPos, endPos) {\n    ctx.clearRect(0, 0, this._canvasSize, this._canvasSize);\n    ctx.beginPath();\n    ctx.arc(\n      this._arcPos,\n      this._arcPos,\n      this._arcRadius,\n      (1.5 + startPos * 2) * Math.PI,\n      (1.5 + endPos * 2) * Math.PI\n    );\n    ctx.stroke();\n    ctx.closePath();\n  },\n\n  _animateArc: function (targetStartPos, targetEndPos, callback) {\n    if (this._arcStepTimeout) {\n      clearTimeout(this._arcStepTimeout);\n    }\n\n    this._arcStep = 0;\n    this._arcStartStepSize = (targetStartPos - this._arcStartPos) / 10;\n    this._arcEndStepSize = (targetEndPos - this._arcEndPos) / 10;\n    this._arcAnimateCallback = callback;\n    this._takeNextArcStep();\n  },\n\n  _takeNextArcStep: function () {\n    this._setArc(\n      this._arcStartPos + this._arcStartStepSize,\n      this._arcEndPos + this._arcEndStepSize\n    );\n\n    this._arcStep++;\n\n    if (this._arcStep < 10) {\n      this._arcStepTimeout = setTimeout(this._takeNextArcStep.bind(this), 50);\n    } else if (this._arcAnimateCallback) {\n      this._arcAnimateCallback();\n    }\n  },\n});\n"],"names":["Craft","Accordion","Garnish","Base","extend","$trigger","targetSelector","_$target","init","trigger","this","$","data","console","warn","destroy","attr","addListener","event","key","keyCode","SPACE_KEY","RETURN_KEY","preventDefault","onTriggerClick","hideTarget","showTarget","$target","length","_currentHeight","height","removeClass","addClass","i","$t","prop","_targetHeight","css","overflow","velocity","getUserPreferredAnimationDuration","eq","$win","hasClass","removeData","base","AddressesInput","$container","$addBtn","$addBtnItem","$cards","container","settings","setSettings","defaults","find","closest","initCard","updateAddButton","createAddress","$card","ev","target","editAddress","$actionBtn","disclosureMenu","menu","$menu","$editBtn","stopPropagation","$deleteBtn","confirm","t","addressId","draftId","sendActionRequest","elementId","then","remove","not","createElementEditor","on","id","response","$newCard","html","replaceWith","insertBefore","initUiElements","add","canCreateAddress","maxAddresses","elementType","ownerId","element","AdminTable","totalItems","sorter","$noItems","$table","$tbody","$deleteBtns","allowDeleteAll","minItems","noItemsSelector","tableSelector","children","sortable","DataTableSorter","onSortChange","reorderItems","bind","handleDeleteBtnClick","updateUI","addRow","row","maxItems","$row","appendTo","addItems","ids","$items","idAttribute","push","JSON","stringify","reorderAction","onReorderItems","cp","displaySuccess","reorderSuccessMessage","displayError","reorderFailMessage","confirmDeleteItem","deleteItem","confirmDeleteMessage","name","getItemName","getItemId","deleteAction","handleDeleteItemSuccess","handleDeleteItemFailure","deleteFailMessage","removeItems","onDeleteItem","deleteSuccessMessage","escapeHtml","nameAttribute","hide","show","$moveButtons","newItemBtnSelector","noop","AssetImageEditor","Modal","$body","$footer","$imageTools","$buttons","$cancelBtn","$replaceBtn","$saveBtn","$focalPointBtn","$editorContainer","$straighten","$croppingCanvas","$spinner","$constraintContainer","$constraintRadioInputs","$customConstraints","canvas","image","viewport","focalPoint","grid","croppingCanvas","clipper","croppingRectangle","cropperHandles","cropperGrid","croppingShade","imageStraightenAngle","viewportRotation","originalWidth","originalHeight","imageVerticeCoords","zoomRatio","animationInProgress","currentView","assetId","cacheBust","draggingCropper","scalingCropper","draggingFocal","previousMouseX","previousMouseY","shiftKeyHeld","editorHeight","editorWidth","cropperState","scaleFactor","flipData","focalPointState","maxImageSize","lastLoadedDimensions","imageIsLoading","mouseMoveEvent","croppingConstraint","constraintOrientation","showingCustomConstraint","saving","renderImage","renderCropper","_queue","Queue","Date","now","allowDegreeFractions","isImagick","prefersReducedMotion","animationDuration","x","y","$bod","type","class","text","allowSavingAsNew","ui","createButton","label","spinner","saveImage","createSubmitButton","removeListener","$shade","getMaxImageSize","loadEditor","browserViewportWidth","$doc","get","documentElement","clientWidth","browserViewportHeight","clientHeight","Math","max","window","devicePixelRatio","$tabs","$viewsContainer","$views","innerHeight","innerWidth","_showSpinner","updateSizeAndPosition","$customConstraintWrapper","filter","parent","append","size","value","val","test","fabric","StaticCanvas","width","enableRetinaScaling","requestAnimationFrame","renderAll","imageUrl","getActionUrl","Image","fromURL","imageObject","set","originX","originY","left","top","getHeight","getWidth","getScaledImageDimensions","_setFittedImageVerticeCoordinates","_repositionEditorElements","focalState","imageDimensions","offsetX","offsetY","focal","focalData","adjustedX","adjustedY","storeFocalPointState","_createFocalPoint","_createViewport","storeCropperState","_addControlListeners","_handleMouseMove","_handleMouseDown","_handleMouseUp","_handleMouseOut","_hideSpinner","first","_reloadImage","setSrc","outerHeight","previousEditorDimensions","setDimensions","currentScaledDimensions","getZoomToFitRatio","previouslyOccupiedArea","_getBoundingRectangle","_repositionCropper","getZoomToCoverRatio","_repositionImage","_repositionViewport","_repositionFocalPoint","_zoomImage","Rect","fill","globalCompositeOperation","sizeFactor","focalX","focalY","deltaX","deltaY","Group","Circle","radius","strokeWidth","stroke","toggleFocalPoint","dimensions","state","currentWidth","ratio","hasOrientationChanged","_","imageRatio","editorRatio","min","round","_getPrevTab","newTabIndex","activeTabIndex","_getActiveTabIndex","_getNextTab","_getActiveTab","$activeTab","index","_handleTabClick","LEFT_KEY","UP_KEY","$prevTab","activateTab","RIGHT_KEY","DOWN_KEY","$nextTab","rotateImage","flipImage","straighteningInput","SlideRuleInput","onStart","_showGrid","onChange","slider","straighten","onEnd","_hideGrid","_cleanupFocalPointAfterStraighten","SHIFT_KEY","_handleConstraintChange","_handleOrientationClick","_applyCustomConstraint","_handleConstraintClick","constraint","currentTarget","siblings","_showCustomConstraint","_hideCustomConstraint","setCroppingConstraint","enforceCroppingConstraint","$constraints","$constraint","labelSelector","$label","split","reverse","join","replace","_getCustomConstraint","w","h","parseFloat","isNaN","_setCustomConstraint","$tab","tab","view","tabindex","showView","enableSlider","disableSlider","Promise","resolve","reject","disableCropMode","enableCropMode","zoomFactor","degrees","parseInt","imageZoomRatio","newAngle","angle","scaledImageDimensions","viewportProperties","imageProperties","angleInRadians","PI","newDeltaX","cos","sin","newDeltaY","modifiedDeltaX","modifiedDeltaY","temp","animate","duration","onComplete","cleanAngle","_adjustFocalPointByAngle","_resetFocalPointPosition","axis","editorCenter","setValue","properties","scaleY","scaleX","previousAngle","_adjustEditorElementsOnStraighten","newCenterX","newCenterY","angleDelta","currentZoomRatio","adjustmentRatio","cropperCenterX","cropperCenterY","imageVertices","getImageVerticeCoords","rectangle","_getZoomRatioToFitRectangle","_isCenterInside","opacity","object","containingObject","newFocalX","newFocalY","adjustedFocalX","adjustedFocalY","containingVertices","vertex","rectangleVertices","_getRectangleVertices","verticeIndex","arePointsInsideRectangle","edge","_getEdgeCrossed","rectangleCenter","distanceFromVertexToEdge","abs","sqrt","pow","distanceFromCenterToEdge","$button","postData","imageRotation","cropData","zoom","onSave","broadcaster","postMessage","runQueue","Preview","refresh","message","scaledWidth","scaledHeight","boundingBox","_getImageBoundingBox","scale","vertScale","horiScale","getCombinedZoomRatio","strokeOptions","gridWidth","gridHeight","xStep","yStep","Line","onFadeOut","removeAllListeners","_editorModeTransition","cropperData","_showCropper","_hideCropper","targetZoom","inverseZoomFactor","imageOffsetX","imageOffsetY","callback","pause","resume","clipperData","_setupCropperLayer","_redrawCropperElements","backgroundColor","hoverCursor","selection","position","rectangleRatio","rectWidth","rectHeight","lineOptions","gridOptions","pathGroup","Path","cropTextTop","cropTextBackgroundColor","previousImageArea","currentOffset","areaFactor","coordinateSet","a","b","c","d","_isMouseOver","move","handle","_cropperHandleHitTest","pageX","pageY","_handleMouseMoveInternal","_handleFocalDrag","_handleCropperDrag","_handleCropperResize","_setMouseCursor","vertices","dxi","dyi","furthest","furthestDeltas","newX","newY","previousHeight","previousWidth","startingRectangle","_calculateNewCropperSizeByDeltas","cropperDirection","topDelta","leftDelta","change","match","isMobileBrowser","cursor","parentOffset","offset","mouseX","mouseY","lb","rb","tb","bb","topLeft","topRight","bottomRight","bottomLeft","zoomMode","topVerticalSegment","bottomVerticalSegment","rightHorizontalSegment","leftHorizontalSegment","verticalOffset","horizontalOffset","_debug","fabricObj","points","ab","_getVector","bc","scalarAbAb","_getScalarProduct","scalarBcBc","point","ap","bp","scalarAbAp","scalarBcBp","projectsOnAB","projectsOnBC","_getVectorMagnitude","vector","_getAngleBetweenVectors","acos","edgePoints","centerPoint","smallestDiff","edgeCrossed","edgeIndex","toCenter","edgeVector","toVertex","diff","box","proportion","AssetIndex","BaseElementIndex","$includeSubfoldersContainer","$includeSubfoldersCheckbox","showingIncludeSubfoldersCheckbox","$uploadButton","$uploadInput","$progressBar","uploader","promptHandler","progressBar","$listedFolders","itemDrag","_uploadTotalFiles","_uploadFileProgress","_currentUploaderSettings","Object","assign","context","DragDrop","activeDropTargetClass","minMouseDist","hideDraggee","moveHelperToCursor","item","$targetItem","elementSelect","selectItem","_findDraggableItems","getSelectedElements","$item","$dropTargets","$visibleSources","toArray","source","hasAttr","sourcePath","$source","step","folderId","$btn","$draggee","targetFolderId","_targetFolderId","$activeDropTarget","returnHelpersToDraggees","fadeOutHelpers","$folders","$assets","folderIds","map","assetIds","mover","AssetMover","moveFolders","totalFoldersMoved","moveAssets","totalAssetsMoved","totalItemsMoved","displayNotice","elementIndex","updateElements","$main","modal","_positionProgressBar","$dropTarget","is","afterInit","foldersOnly","initForFiles","style","addButton","PromptHandler","ProgressBar","options","url","fileInput","dropZone","events","fileuploadstart","_onUploadStart","fileuploadprogressall","_onUploadProgress","fileuploaddone","_onUploadSuccess","fileuploadalways","_onUploadAlways","fileuploadfail","_onUploadFailure","criteria","kind","allowedKinds","Uploader","isIndexBusy","onSelectSource","setParams","onSourcePathChange","currentFolder","canMoveSubItems","selectable","multiSelect","startSearching","hideSidebar","hasChildren","floor","random","insertAfter","$search","$subContainer","setSelecetedSourceState","checked","getSelectedSourceState","marginBottom","stopSearching","complete","getViewSettings","canSelectElement","getViewParams","showFolders","trashed","includeSubfolders","setIndexBusy","resetProgressBar","showProgressBar","resetPrompts","progress","loaded","total","setProgressPercentage","result","selectElementAfterUpdate","conflict","prompt","file","filename","choices","title","addPrompt","isLastUpload","hideProgressBar","setIndexAvailable","getPromptCount","showBatchPrompts","_uploadFollowup","_updateAfterUpload","jqXHR","responseJSON","clearSearch","setSelectedSortAttribute","returnData","setItemCount","doFollowup","parameterArray","parameterIndex","action","followupAlways","incrementProcessedItemCount","updateProgressBar","followupSuccess","choice","sourceAssetId","conflictingAssetId","targetFilename","followupFailure","onUpdateElements","_onUpdateElements","getAllElements","newElements","$newElements","$elements","_onKeyDown","_onElementFocus","$folder","$title","folderName","disabledFolderIds","includes","has","$a","href","getCpUrl","uri","role","empty","firstFocusableEl","focus","removeAllItems","shiftKey","PreviewFileModal","openInstance","selfDestruct","$element","$focusedItem","_loadPreview","startingWidth","startingHeight","getSourcePathLabel","getSourcePathActionLabel","getSourcePathActions","actions","canCreate","onSelect","_createSubfolder","canRename","_renameFolder","canMove","getMoveTargetSourceKeys","_moveFolder","canDelete","destructive","_deleteFolder","subfolderName","parentId","folder","slice","newName","peerFiles","$sources","volumeHandle","parentFolder","VolumeFolderSelectorModal","sources","showTitle","modalTitle","selectBtnLabel","indexSettings","defaultSource","sourceKey","defaultSourcePath","targetFolder","$sourcePathActionsBtn","scrollTop","windowHeight","registerElementIndexClass","requests","for","params","_batchMoveRequests","conflictChoices","handleConflictChoice","request","force","suggestedFilename","transferList","folderIdsToDelete","onSuccess","merge","totalMoved","_processTransferList","_deleteFolders","_batchRequests","responses","success","error","prompts","nextRequests","nextRequest","nextTotalMoved","activeRequests","failure","AssetSelectInput","BaseElementSelectInput","$uploadBtn","openPreviewTimeout","apply","arguments","canUpload","_attachUploader","updateAddElementsBtn","$elementsContainer","openPreview","onAddElements","clearOpenPreviewTimeout","setTimeout","clearTimeout","minGutter","formData","fieldId","sourceElementId","siteId","$addElementBtn","limit","describedBy","multiple","csrfTokenName","csrfTokenValue","canAddMoreFiles","_onUploadComplete","next","enableAddElementsBtn","disableAddElementsBtn","selectUploadedFile","canAddMoreElements","$newElement","prepend","margin","outerWidth","animateCss","addElements","parameters","thumbSize","viewMode","appendHeadHtml","headHtml","getElementInfo","slotsTaken","AssetSelectorModal","BaseElementSelectorModal","$selectTransformBtn","_selectedTransform","transforms","createSelectTransformButton","$btnGroup","$primaryButtons","$selectBtn","$menuList","MenuButton","MenuBtn","onOptionSelect","onSelectTransform","disable","onSelectionChange","$selectedElements","allowTransforms","enable","option","transform","selectImagesWithTransform","transformUrls","imageIdsWithMissingUrls","showFooterSpinner","fetchMissingTransformUrls","hideFooterSpinner","selectElements","pop","info","elementInfo","canSelectImageTransforms","registerElementSelectorModalClass","AssetsFieldSettings","$useSingleFolderInput","$sourceInputs","$defaultUploadLocationSelect","$defaultUploadLocationOptions","useSingleFolderToggleId","sourcesFieldId","defaultUploadLocationId","updateDefaultUploadLocationSelect","firstEnabledValue","defaultUploadLocationVal","$input","getOption","$selectedOption","AuthManager","remainingSessionTime","checkRemainingSessionTimer","showLoginModalTimer","decrementLogoutWarningInterval","showingLogoutWarningModal","showingLoginModal","logoutWarningModal","loginModal","$logoutWarningPara","$passwordInput","$loginBtn","$loginErrorPara","submitLoginIfLoggedOut","username","updateRemainingSessionTime","setCheckRemainingSessionTimer","seconds","checkRemainingSessionTime","extendSession","ajax","dataType","textStatus","timeout","minSafeSessionTime","showLogoutWarningModal","checkInterval","showLoginModal","submitLogin","hideLogoutWarningModal","hideLoginModal","quickShow","$form","$logoutBtn","$renewSessionBtn","prependTo","autoShow","closeOtherModals","hideOnEsc","hideOnShadeClick","shadeClass","onFadeIn","updateLogoutWarningMessage","setInterval","decrementLogoutWarning","time","secondsToHumanTimeDuration","clearInterval","quick","quickHide","$inputContainer","$inputsFlexContainer","$passwordContainer","$buttonContainer","$passwordWrapper","PasswordInput","onToggleInput","$newPasswordInput","logout","redirectTo","renewSession","validatePassword","removeAttr","login","clearLoginError","loginName","password","showLoginError","shake","initialized","idPrefix","instanceState","sourceStates","sourceStatesStorageKey","searchTimeout","sourceSelect","$sidebar","showingSidebar","rootSourceKey","sourceViewModes","$rootSource","sourcesByKey","$sourceActionsContainer","$sourceActionsBtn","$toolbar","toolbarOffset","$searchContainer","$filterBtn","searching","searchText","sortByScore","drafts","$clearSearchBtn","$statusMenuBtn","$statusMenuContainer","statusMenu","status","$siteMenuBtn","siteMenu","_sourcePath","$sourcePathOuterContainer","$sourcePathInnerContainer","$sourcePathOverflowBtnContainer","$updateSpinner","$viewModeBtnContainer","viewModeBtns","_viewMode","_autoSelectElements","$countSpinner","$countContainer","$actionsContainer","page","resultSet","totalResults","$exportBtn","actionsHeadHtml","actionsBodyHtml","$selectAllContainer","$selectAllCheckbox","showingActionTriggers","exporters","exportersByType","_$triggers","_cancelToken","viewMenus","activeViewMenu","filterHuds","_activeElement","canSortByStructure","randomString","getDefaultInstanceState","storageKey","getLocalStorage","toolbarSelector","initSources","menubtn","_handleStatusChange","$option","$options","_setSite","_handleSiteChange","defaultSiteId","getSiteId","$storedSiteOption","updateElementsIfSearchTextChanged","queryParams","getQueryParams","selector","selectOption","setQueryParam","selectDefaultSource","getDefaultSourcePath","handleResize","search","sort","lastDashPos","lastIndexOf","substring","dir","setPage","pageNum","onAfterInit","showSourcePath","_updateSourcePathVisibility","_createCancelToken","axios","CancelToken","token","_cancelRequests","cancel","getSourceContainer","getSite","sites","s","_getSourcesInList","Select","multi","allowEmpty","vertical","_handleSourceSelectionChange","initSource","getQueryParam","getDefaultSourceKey","getSourceByKey","selectSource","refreshSources","refreshSourcesAction","e","isCancel","initSourceToggle","expandedSources","indexOf","_expandSource","deinitSourceToggle","$toggle","_getSourceToggle","deinitSource","selectedSource","$lastSource","segment","testSourceKey","_collapseSource","undefined","canView","getDefaultExpandedSources","$overflowBtn","overflowMenuId","$overflowUl","$nav","$ol","$overflowMenu","$overflowLi","icon","selectSourcePathStep","isFirst","isLast","$li","$btnBody","actionBtnLabel","menuId","groupedActions","administrative","group","forEach","_buildSourcePathActionList","history","replaceState","firstStep","lastStep","overage","_checkSourcePathOverage","getBoundingClientRect","$ul","num","updateSortField","setInstanceState","storeInstanceState","setLocalStorage","getSourceState","defaultValue","viewState","k","hasOwnProperty","storeSortAttributeAndDirection","getPageUrl","_resetCount","updateSourceMenu","getSourceActions","_buildActionList","userIsAdmin","allowAdminChanges","createCustomizeSourcesModal","updateViewMenu","hideTrigger","ViewMenu","showTrigger","batchSize","canHaveDrafts","savedDraftsOnly","draftOf","currentStep","condition","referenceElementId","referenceElementSiteId","disabledElementIds","paginated","_isViewPaginated","mode","order","collapsedElementIds","getSortAttributeAndDirection","sortAttribute","sortDirection","serialized","filters","preservePagination","pageChanged","updateElementsAction","cancelToken","fixedHeader","headerContainerHeight","$headerContainer","maxScrollTop","$scrollContainer","_updateView","$elementContainer","getElementContainer","firstFocusableElement","showActionTriggers","_createTriggers","submitAction","actionParams","selectedElementIds","getSelectedElementIds","_findAction","viewParams","expandPostArray","elementAction","elementIds","download","downloadFromUrl","submitActionsAction","badgeCounts","_updateBadgeCounts","afterAction","actionClass","onAfterAction","hideActionTriggers","detach","updateActionTriggers","totalSelected","getEnabledElements","setStatus","getSelectedSortAttribute","getRootSource","attribute","getSortOption","getDefaultSort","getSelectedSortDirection","direction","setSortAttribute","sortOption","defaultDir","attributes","lastAttr","oldHistory","orderHistory","setSortDirection","setSelectedSortDirection","getSortLabel","getSelectedViewMode","getSourceLevel","parentsUntil","getParentSource","$parent","keys","updateContentHeading","$firstOption","getViewModesForSource","sourceViewMode","$viewModeBtn","className","selectViewMode","doesSourceHaveViewMode","updateFilterBtn","urlParams","setUrl","getUrl","path","selectSourceByKey","getSortOptions","sortOptions","o","defaultSort","getTableColumnOptions","getTableColumnOption","getDefaultTableColumns","getSelectedTableColumns","setSelectedTableColumns","tableColumns","updateTableColumnField","viewModes","orientation","createView","getViewClass","TableElementIndexView","ThumbsElementIndexView","rememberDisabledElementId","inArray","forgetDisabledElementId","splice","enableElements","parents","onEnableElements","disableElements","onDisableElements","getElementById","enableElementsById","makeArray","disableElementsById","getButtonContainer","isShowingSidebar","buttonContainer","document","activeElement","contains","blur","elementsHeight","scrollParent","positionTop","setProperty","body","CustomizeSourcesModal","onHide","onSelectSite","elements","$selectedItems","_handleActionTriggerSubmit","getPostData","_handleMenuActionTriggerSubmit","selectedOption","queryParam","firstSite","updateSourceVisibility","$heading","$headings","setSiteId","toString","_handleSelectionChange","_handleSourceDblClick","_toggleSource","_handleSourceToggleClick","prev","$list","topLevel","_getChildSources","$childSources","_countResults","itemLabel","elementTypeNames","elementTypeName","toLowerCase","itemsLabel","elementTypePluralName","last","countLabel","items","$paginationContainer","totalPages","ceil","$paginationNav","$prevBtn","disabled","$nextBtn","appendBodyHtml","bodyHtml","selectAllElements","deselectAllElements","checkboxMode","selectElementById","$badge","countElementsAction","count","triggers","safeMenuActions","destructiveMenuActions","formatInputId","$menuTrigger","$safeList","_createMenuTriggerList","$destructiveList","$div","_showExportHud","typeOptions","$typeField","createSelectField","$formatField","$typeSelect","formattable","$limitField","createTextField","placeholder","$submitBtn","$exportSubmit","MultiFunctionBtn","HUD","submitting","busyEvent","format","successEvent","showFilterHud","FilterHud","showing","hasRules","$sortField","$sortAttributeSelect","$sortDirectionPicker","sortDirectionListbox","$tableColumnsField","$tableColumnsContainer","$revertContainer","$revertBtn","$closeBtn","_buildMenu","DisclosureMenu","tidyTableColumnField","FX_DURATION","$scoreOption","select","$lastContainer","lastIndex","$checkbox","$checkboxes","_getTableColumnCheckboxes","defaultOrder","column","reduce","obj","checkboxA","checkboxB","revert","$metaContainer","_createSortField","_createTableColumnsField","$footerContainer","_createRevertBtn","$sortAttributeSelectContainer","createSelect","Listbox","$field","createField","fieldset","columns","createCheckbox","DragSort","_onTableColumnChange","$selectedCheckboxes","compare","loading","$clearBtn","cleared","$loadingContent","hudClass","$hud","$tip","hudHtml","$btnContainer","clear","setBusy","setReady","setFocus","elem","func","setFocusWithin","updateSizeAndPositionInternal","hudHeight","searchOffset","availableSpace","bottom","overflowY","onShow","serialize","BaseElementIndexView","$loadingMoreSpinner","$scroller","loadingMore","_totalVisible","_morePending","_handleEnableElements","_handleDisableElements","thumbLoader","elementThumbLoader","setTotalVisible","setMorePending","load","isVerticalList","_handleElementEditing","maybeLoadMore","selectElement","selectAll","deselectAll","getElementCheckbox","getTotalVisible","totalVisible","getMorePending","morePending","canLoadMore","loadMore","loadMoreElementsAction","getLoadMoreParams","appendElements","onAppendElements","each","isSelected","off","elementSort","elementEditor","_initialized","isPlainObject","normalizedSettings","args","modalStorageKey","maintainHierarchy","getContainer","getElementsContainer","getAddElementsBtn","getSpinner","initElementSelect","initElementSort","resetElements","getElements","getSelectedItems","ignoreHandleSelector","getElementSortAxis","collapseDraggees","magnetStrength","helperLagBase","resetItemOrder","updateButtonContainer","showSpinner","hideSpinner","focusNextLogicalElement","focusLastRemoveBtn","$removeBtns","removeElements","editable","_handleShowElementEditor","isTouchCapable","removeElement","BACKSPACE_KEY","DELETE_KEY","elementSelectInput","prevalidate","replaceElement","replacementId","$existing","$nextDeleteBtn","lastElementIndex","onRemoveElements","$allElements","_animateStructureElementAway","animateElementAway","right","REMOVE_FX_DURATION","showModal","createModal","createElementSelectorModal","getModalSettings","hideOnSelect","showSiteMenu","getDisabledElementIds","onModalSelect","onModalHide","triggerElement","modalSettings","allowSelfRelations","selectStructuredElements","slotsLeft","updateDisabledElementsInModal","createNewElement","appendElement","animateElementIntoPlace","onSelectElements","disableCancelBtn","disableSelectBtn","containerId","branchLimit","selectionLabel","onResponse","enableCancelBtn","enableSelectBtn","$newElementsContainer","filteredElements","clone","removeText","setElementSize","single","$modalElement","$inputElement","origOffset","destOffset","$helper","zIndex","ADD_FX_DURATION","editorSettings","supportSidebarToggleView","$content","$sourceToggles","$sidebarToggleBtn","$sidebarCloseBtn","$mainHeading","$secondaryButtons","headingId","$headingContainer","fullscreen","updateModalBottomPadding","footerHeight","updateSidebarView","sidebarShouldBeHidden","buildSidebarToggleView","resetView","$mainHeader","$sidebarHeader","getActiveSourceName","toggle","controls","closeSidebar","toggleSidebar","sidebarIsOpen","openSidebar","uiLayerManager","addLayer","registerShortcut","ESC_KEY","$focusedEl","getFocusedElement","removeLayer","_createElementIndex","updateSelectBtnState","updateHeading","hasSelection","clearMouseUpTimeout","disableElementsOnSelect","getElementIndexParams","bodyAction","createElementIndex","getIndexSettings","touchData","firstTap","secondTap","getItemIndex","resizable","onCancel","BaseInputGenerator","listening","startListening","setNewSource","stopListening","onSourceTextChange","updateTarget","onTargetTextChange","onFormSubmit","sourceVal","targetVal","generateTargetValue","dispatchEvent","InputEvent","inputType","Event","selectFullValue","CategoryIndex","editableGroups","$newCategoryBtnGroup","$newCategoryBtn","updateButton","editableCategoryGroups","g","uid","defaultGroupHandle","selectedSourceHandle","$menuBtn","selectedGroup","visibleLabel","ariaLabel","isCtrlKeyPressed","originalEvent","button","open","_createCategory","$menuContainer","anchorRole","setPath","groupId","location","cpEditUrl","fresh","groupSourceKey","CategorySelectInput","selectedCategoryIds","categoryIds","$allCategories","_animateCategoryAway","charts","DataTable","rows","cellIndex","parseTime","d3","timeParse","Tip","setContent","setPosition","BaseChart","$chart","chartBaseClass","dataTable","formatLocale","timeFormatLocale","svg","globalSettings","formats","d3Formats","formatLocaleDefinition","d3FormatLocaleDefinition","timeFormatLocaleDefinition","d3TimeFormatLocaleDefinition","resize","baseSettings","draw","chartClass","onAfterDrawTicks","tickKey","tick","$tickText","numberFormat","percentFormat","currencyFormat","shortDateFormats","day","month","year","colors","Area","tip","drawingArea","getChartMargin","translateX","translateY","drawTicks","drawAxes","drawChart","drawTipTriggers","getX","xAxis","axisBottom","tickFormat","getXFormatter","ticks","call","yAxis","getY","axisLeft","getYFormatter","tickValues","getYTickValues","axisRight","showAxis","tickSizeOuter","gridlines","xLineAxis","tickSize","yLineAxis","line","datum","area","y0","y1","plots","enter","tips","chartMargin","xAxisTickInterval","node","getTotalLength","tipTriggerWidth","$xValue","$yValue","content","values","yTicksMaxWidth","computedTickWidth","formatter","padded","xDomainMin","xDomainMax","xDomain","scaleTime","range","domain","yDomain","getYMaxValue","scaleLinear","utils","getTimeFormatter","getNumberFormatter","maxValue","getDuration","secondsNum","hours","minutes","chartSettings","dataScale","ColorInput","$colorContainer","$colorPreview","$colorInput","createColorInput","handleTextChange","input","createElement","setAttribute","updateColor","trim","repeat","_browserSupportsColorInputs","doesBrowserSupportColorInputs","CpScreenSlideout","Slideout","namespace","showingLoadSpinner","hasTabs","hasCpLink","hasSidebar","$header","$tabContainer","$loadSpinner","$editLink","$sidebarBtn","$noticeContainer","tabManager","ignoreFailedRequest","fieldsWithErrors","ltr","showSidebar","$contents","containerElement","containerAttributes","method","novalidate","closeOnEsc","closeOnShadeClick","S_KEY","ctrl","handleSubmit","closeMeMaybe","refreshInitialData","showLoadSpinner","getParams","headers","requestOptions","update","deltaNames","initialDeltaValues","hideLoadSpinner","updateHeaderVisibility","forceShow","showHeader","submitButtonLabel","updateTabs","tabs","formAttributes","setElementAttributes","editUrl","sidebar","hostname","notice","Tabs","_closedSidebarStyles","offsetWidth","_openedSidebarStyles","one","trapFocusWithin","showSubmitSpinner","hideSubmitSpinner","submit","findDeltaData","handleSubmitResponse","handleSubmitError","clearErrors","notificationSettings","modelName","closeOnSubmit","close","isAxiosError","errors","showErrors","entries","fieldErrors","addErrorsToField","clearErrorsFromField","isDirty","isOpen","rxhtmlTag","jQuery","htmlPrefilter","navHeight","arr","isArray","grouped","thisKey","category","translations","formatMessage","pattern","tokens","_tokenizePattern","_parseToken","start","pos","depth","chars","param","arg","number","formatNumber","plural","selectorChars","p","formatDate","date","datepicker","datepickerOptions","dateFormat","shortcutText","shift","alt","clientOs","str","escapeRegex","getText","encodeUriComponent","encodeURIComponent","differences","chr","re","RegExp","setSelectionRange","inputName","rtrim","baseUrl","anchor","anchorPos","fromEntries","URLSearchParams","qsPos","isEmptyObject","pathParam","pathMatch","omitScriptNameInUrls","usePathInfo","scriptName","baseCpUrl","getSiteUrl","baseSiteUrl","actionUrl","hash","origin","pathname","qs","pageTrigger","pageParam","getCsrfInput","postActionRequest","contentType","_actionHeaders","errorThrown","readyState","alert","send","registeredAssetBundles","registeredJsFiles","toUpperCase","actionName","namespaceInputName","v","getTime","sendApiRequest","_getApiHeaders","apiHeaders","baseURL","baseApiUrl","apiParams","_apiHeaders","processCraftHeaders","httpProxy","proxy","apiResponse","_processApiHeaders","_loadingApiHeaders","_apiHeaderWaitlist","_rejectApiRequests","clearCachedApiHeaders","XMLHttpRequest","setRequestHeader","responseType","onload","disposition","getResponseHeader","matches","exec","blob","Blob","link","URL","createObjectURL","appendChild","click","removeChild","stringToArray","oldData","newData","modifiedDeltaNames","groupedOldParams","_groupParamsByDeltaNames","groupedNewParams","__root__","n","concat","withRoot","initialValues","encodeURIComponentExceptEqualChar","decodeURIComponent","paramLoop","paramName","serializeParam","subName","expanded","m","unshift","parentElem","createForm","chunks","obj1","obj2","sortObjectKeys","Array","getObjectKeys","escapeChars","escaped","ltrim","startsWith","substr","filterArray","filtered","removeFromArray","getLast","uppercaseFirst","charAt","lowercaseFirst","parseUrl","scheme","host","port","query","Proxy","searchParams","isSameHost","requestUrlInfo","urlInfo","showSeconds","secondsInWeek","weeks","days","timeComponents","asciiString","charMap","normalize","char","asciiStr","asciiCharMap","uuid","crypto","randomUUID","getRandomValues","Uint8Array","namespaceId","createErrorList","$existingCss","existingCss","regexp","$existingJs","src","existingJs","appendFootHtml","infoicon","checkboxselect","fieldtoggle","lightswitch","nicetext","formsubmit","datetime","datetimeinput","_elementIndexClasses","_elementSelectorModalClasses","_elementEditorClasses","registerElementEditorClass","ElementEditorSlideout","systemUid","localStorage","parse","removeLocalStorage","removeItem","getCookie","cookie","setCookie","defaultCookieOptions","maxAge","expires","toUTCString","secure","removeCookie","hasThumb","otherSize","$oldImg","$newImg","sizes","srcset","picturefill","submitForm","redirect","retainScroll","scrollY","filterInputVal","regex","selectionStart","newVal","filterNumberInputVal","dataAttributes","subValue","isVisible","visibilityState","useMobileStyles","pageId","BroadcastChannel","channelName","appId","messageReceiver","addEventListener","instances","elementHtml","$replacement","$inputs","fn","animateLeft","easing","animateRight","$elem","itemSelector","cols","maxCols","minColWidth","fillMode","colClass","snapToGrid","Grid","InfoIcon","CheckboxSelect","FieldToggle","settingName","settingValue","thisSettings","indeterminateValue","LightSwitch","NiceText","$anchor","customTrigger","menuAnchor","$wrapper","checkValue","hasValue","charsLeftHtml","charsLeft","ready","$elementIndexSourcesContainer","$sourcesContainer","$sourcesHeader","$sourcesHeading","$sourceSettingsContainer","$sourceSettingsHeader","$addSourceMenu","addSourceMenu","$footerBtnContainer","$loadingSpinner","sourceSort","baseSortOptions","availableTableAttributes","customFieldAttributes","conditionBuilderHtml","conditionBuilderJs","userGroups","setContainer","buildModal","defaultSortOptions","addSource","$menuBtnContainer","sourceData","scrollContainerToElement","$newHeadingBtn","focusLabelInput","$newCustomSourceBtn","tableAttributes","$labelInput","getSourceName","focusIsInside","currentLayer","isNew","$itemLabel","$itemInput","Heading","updateItemLabel","heading","Source","CustomSource","save","disabledSourceKeys","reload","appendIndexSourceItem","$sourceItem","$lastSourceItem","isHeading","$lastTopLevelSource","BaseSource","$settingsContainer","handleActivatingKeypress","isNative","deselect","createSettings","getIndexSourceItem","$sortDirectionInput","createLightswitchField","createSortField","createTableAttributesField","handleSortAttributeChange","useDefaultDir","$columnCheckboxes","selectedAttributes","createTableColumnOption","instructions","$labelField","defaultId","swapPlaceholders","createCheckboxSelectField","showAllOption","handleLabelInputChange","table","$rows","helper","getHelper","caboose","Y_AXIS","$helperRow","helperClass","$cells","$helperCells","DeleteUserModal","userId","$deleteActionRadios","$deleteSubmitBtn","userSelect","_deleting","idParam","contentSummary","_submitBtnLabel","validateDeleteInputs","withContent","validates","onSubmit","DynamicGenerator","EditableTable","baseName","biggestId","$addRowBtn","$tableParent","$statusMessage","rowCount","hasMaxRows","hasMinRows","radioCheckboxes","copyDraggeeInputValuesToHelper","updateAllRows","initialize","initializeIfVisible","minRows","createRowObj","updateAddRowButton","canAddRow","staticRows","updateRow","canDeleteRow","updateDeleteRowButton","rowId","updateStatusMessage","allowDelete","deleteRow","$tr","onDeleteRow","allowAdd","maxRows","rowIdPrefix","createRow","defaultValues","onAddRow","allowReorder","Row","focusOnPrevRow","tdIndex","blurTd","prevRow","$prevTr","$tds","focusOnNextRow","nextRow","$nextTr","importData","lines","j","textualColTypes","colId","$cell","col","scope","code","small","createDateInput","createLightswitch","createTimeInput","createTextInput","niceTexts","tds","$textareas","tr","td","$textarea","textareasByColId","onHeightChange","onTextareaHeightChange","radioMode","applyToggleCheckbox","autopopulate","HandleGenerator","allowNonAlphaStart","onTextareaFocus","onRadioCheckboxChange","checkbox","checkboxColId","neg","checkboxCol","colum","ignoreNextTextareaFocus","handleKeypress","charCode","handlePaste","clipboardData","getData","validateValue","safeValue","tallestTextareaHeight","tdHeight","numericKeyCodes","ElementActionTrigger","maxLevels","newChildUrl","triggerEnabled","batch","bulk","defineProperty","activate","updateTrigger","validateSelection","enableTrigger","disableTrigger","requireId","handleTriggerActivation","ElementEditor","isFullPage","$contentContainer","$revisionBtn","$revisionLabel","$expandSiteStatusesBtn","$statusIcon","$previewBtn","$editMetaBtn","metaHud","$nameTextInput","$saveMetaBtn","$siteStatusPane","$globalLightswitch","$siteLightswitches","$additionalSiteField","siteIds","newSiteIds","enableAutosave","lastSerializedValue","listeningForChanges","pauseLevel","queue","submittingForm","duplicatedElements","failed","httpStatus","httpError","openingPreview","preview","activatedPreviewToken","previewTokenQueue","previewLinks","hiddenTipsStorageKey","tipDismissBtn","slideout","$primaryForm","_createQueue","autosaveDrafts","siteStatuses","$spinnerContainer","canEditMultipleSites","previewTargets","enablePreview","$previewBtnContainer","createPreviewLink","createShareMenu","revisionId","serializeForm","isProvisionalDraft","initForProvisionalDraft","isUnpublishedDraft","initForDraft","canSaveCanonical","saveShortcut","createDraft","listenForChanges","showStatusHud","handleDismissibleTips","canonicalId","canCreateDrafts","statusIcons","checkForm","stopListeningForChanges","$discardButton","initialHeight","$notice","heightDiff","hashedCpEditUrl","provisional","createEditMetaBtn","expandSiteStatuses","$enabledForSiteField","_getOtherSupportedSites","_createSiteStatusField","$globalField","_showField","siteStatusValues","hasEnabled","hasDisabled","originalEnabledValue","originalSerializedStatus","enabledForSite","_updateGlobalStatus","serializedStatuses","additionalSites","_createAddlSiteField","_updateSiteStatuses","_removeField","allEnabled","allDisabled","turnOn","turnOff","turnIndeterminate","enabled","site","fieldClass","$lightswitch","some","selectLabelId","$addlSiteSelectLabel","$addlSiteSelectContainer","labelledBy","$addlSiteSelect","addlSiteInfo","enabledByDefault","_saveFailMessage","_saveSuccessMessage","hud","$mainContainer","spinners","statusMessage","getTokenizedPreviewUrl","targetUrl","targetLabel","activatePreviewToken","updatePreviewLinks","updatePreviewLinkHref","isLive","getPreviewTokenParams","previewToken","getPreviewToken","randoParam","asPromise","siteToken","previewUrl","tokenParam","createTokenParams","getPreview","$statusIcons","scrollTo","ensureIsDraftOrRevision","onlyIfChanged","removeActionParams","isPreviewActive","$editor","redirectName","saveDraft","isActive","modifiedFieldNames","preparedData","prepareData","deltaName","extraData","visibleLayoutElements","selectedTabId","_saveHeaders","newSelectedTabId","_afterSaveDraft","createdProvisionalDraft","docTitle","draftName","revisionMenu","oldId","siteSettings","creator","timestamp","updatePreviewTargets","checkMetaValues","selectors","modifiedAttributes","$fields","noChanges","$allTabContainers","changedElements","missingElements","tabInfo","$oldElement","$placeholder","$unusedTabContainers","$newSelectedTab","selectTab","afterUpdate","_showFailStatus","setStatusMessage","deltaCallback","swapDuplicatedElementIds","idsRE","namespacedFields","pre","post","_filterFieldInputName","nestedNames","lastHandle","fieldsWithoutContent","newTarget","$previewLink","delay","showMetaHud","createMetaHud","onMetaHudShow","$hudBody","$nameField","$nameInputContainer","saveMeta","onMetaHudHide","onMetaHudEscape","shakeMetaHud","autosave","$confirmUnloadForms","hideTip","getHiddenTipsUids","setHiddenTipsUids","uids","targetElement","$targetParent","layoutElementUid","Storage","hiddenTips","editor","saveParams","onSaveElement","validators","ElementFieldSettings","allowMultipleSources","$maintainHierarchyField","$maintainHierarchyInput","$sourcesField","$sourceSelect","$branchLimitField","$maxRelationsField","$minRelationsField","maintainHierarchyFieldId","branchLimitFieldId","minRelationsFieldId","maxRelationsFieldId","updateLimitFields","updateMaintainHierarchyField","showField","$checkedInputs","ElementThumbLoader","workers","Worker","$thumbs","$thumb","$scrollParent","addToQueue","invisibleThumbs","thumb","active","loadNext","scrollParentOffset","scrollParentHeight","thumbOffset","retryAll","loader","$img","ElevatedSessionForm","inputs","form","getInputPostVal","handleFormSubmit","elevatedSessionManager","fetchingTimeout","stopImmediatePropagation","inputsChanged","$currentInput","requireElevatedSession","ElevatedSessionManager","passwordModal","$errorPara","minSafeElevatedSessionTimeout","showPasswordModal","$passwordModal","focusPasswordInput","submitPassword","currentPassword","showPasswordError","EntryIndex","publishableSections","$newEntryBtnGroup","$newEntryBtn","defaultSectionHandle","selectedSection","section","_createEntry","sectionId","entry","sectionSourceKey","FieldLayoutDesigner","$configInput","$newTabBtn","$libraryToggle","$selectedLibrary","$fieldLibrary","$uiLibrary","$uiLibraryElements","$fieldSearch","$clearFieldSearchBtn","$fieldGroups","tabGrid","elementDrag","_config","$workspace","$fieldSearchContainer","initTab","ElementDrag","customizableTabs","tabDrag","TabDrag","customizableUi","$libraryPicker","$matches","$group","Tab","removeFieldByHandle","addTab","updatePositionInConfig","config","updateConfig","createSlideout","contents","js","eval","designer","destroyed","settingsNamespace","createMenu","initElement","menuBtn","onTabOptionSelect","$prev","$next","settingsHtml","settingsJs","applySettings","$indicator","hasConditions","Element","findIndex","designerConfig","newIndex","tabConfig","oldIndex","isField","requirable","hasCustomWidth","hasSettings","isRequired","showSettings","initUi","SlidePicker","valueLabel","pct","$fieldsContainer","selectorHtml","updateRequiredClass","required","elementConfig","BaseDrag","Drag","$insertion","showingInsertion","$caboose","findItems","onDragStart","createInsertion","createCaboose","removeCaboose","swapDraggeeWithInsertion","swapInsertionWithDraggee","setMidpoints","getClosestItem","_closestItem","_closestItemMouseDiff","_i","_$item","_midpoint","_mouseDiff","getDist","checkForNewClosestItem","refreshCols","onDragStop","display","draggeeDisplay","visibility","helpers","_showDraggee","onDrag","draggingLibraryElement","draggingField","originalTab","isDraggeeMandatory","isHoveringOverTab","hitTest","$fieldContainers","$libraryElement","targetPrefix","reverseTargetSelector","_$reverseTarget","getType","normalizeTargetSelector","findTargets","onToggleChange","nodeName","getToggleVal","boolean","postVal","_show","totalCols","colGutterDrop","colPctWidth","possibleItemColspans","possibleItemPositionsByColspan","itemPositions","itemColspansByPosition","layouts","layout","itemHeights","leftPadding","_refreshingCols","_refreshColsAfterRefresh","_forceRefreshColsAfterRefresh","handleContainerHeightProxy","setItems","oldHeight","scrollHeight","gutter","itemIndex","tallestItemHeight","colIndex","itemHeight","remainder","itemHeightsByColspan","positionRight","positionLeft","minColspan","maxColspan","colspan","getItemWidthCss","minPosition","maxPosition","colHeights","createLayouts","layoutTotalCols","highestTotalCols","layoutHeights","shortestHeight","shortestLayouts","emptySpaces","emptySpace","colspans","getItemLeftPosCss","positions","isSimpleLayout","positionItems","completeRefreshCols","onRefreshCols","getItemWidth","getItemWidthInPx","getItemLeftPosInPx","prevPositions","prevColspans","prevColHeights","prevEmptySpace","LayoutGenerator","endingCol","affectedColHeights","onItemResize","newHeight","tallestColHeightsByPosition","colHeightsForPosition","tallestColHeight","words","handleCasing","ImageUpload","initImageUpload","containerSelector","uploadAction","postParameters","fileInputSelector","uploadParamName","initButtons","uploadButtonSelector","deleteButtonSelector","refreshImage","onAfterRefreshImage","$icon","$liveRegion","wrap","previousSibling","nodeType","Node","TEXT_NODE","nodeValue","showHud","closeOtherHUDs","$outerContainer","$innerContainer","indeterminate","dragger","dragStartMargin","outerContainer","X_AXIS","_onDragStart","_onDrag","_onDragStop","muteEvent","changed","_onSettle","_getOffMargin","_onMouseDown","_onMouseUp","dragging","_getMargin","mouseDistX","selectedOptionIndex","selectedClass","focusClass","LivePreview","$extraFields","$dragHandle","$previewContainer","$iframeContainer","$iframe","$fieldPlaceholder","basePostData","inPreviewMode","fields","lastPostData","updateIframeInterval","checkAgain","dragStartEditorWidth","_slideInOnIframeLoad","_scrollX","_scrollY","_editorWidth","_editorWidthInPx","protocol","previewParams","extraFields","defaultEditorWidth","moveFieldsBack","editorWidthInPx","inPx","minEditorWidthInPx","exit","$editorHeader","handleWindowResize","getIframeWidth","$clone","_getClone","updateIframe","slideIn","createToken","previewAction","submitPrimaryForm","updateWidths","$newClone","field","contentWindow","scrollLeft","xhrFields","withCredentials","crossDomain","handleSuccess","handleError","forceUpdateIframe","write","copyInputValues","livePreview","$textInput","$showPasswordToggle","showingPassword","passwordInput","initInputFocusEvents","hidePassword","setCurrentInput","updateToggleLabel","showPassword","autocapitalize","togglePassword","onInputChange","onClick","selectionEnd","$previewWrapper","$previewSkipLink","$bumperLink","$notifier","$previewHeader","$targetBtn","$targetMenu","$deviceTypeContainer","$orientationBtn","$refreshBtn","$deviceMask","$devicePreviewContainer","iframeLoaded","$tempInput","activeTarget","currentDeviceType","deviceOrientation","deviceWidth","deviceHeight","deviceMaskDimensions","phone","tablet","iframeHeight","_updateIframeProxy","previewSkipLinkText","$modalLabel","Pro","switchTarget","_buildDeviceTypeFieldset","_getDeviceTypeTranslation","translation","_getDeviceOrientationTranslation","deviceType","deviceBtnGroup","switchDeviceType","_activeTarget","_autoRefresh","previewTarget","hideModalBackgroundLayers","resetModalBackgroundLayerVisibility","_devicePreviewIsActive","updateDevicePreview","_useIframeResizer","previewIframeResizerOptions","resetScroll","sameHost","frameborder","iFrameResize","checkOrigin","scrolling","onInit","iframe","_updateNotifier","newDeviceType","switchOrientation","hZoom","wZoom","previewHeight","previewWidth","maskHeight","maskWidth","translate","rotationDeg","marginTop","marginLeft","$triggerElement","$bumperButtonStart","$bumperButtonEnd","requestId","defaultSettings","_onHide","instance","loadAsset","focusItem","_addBumperButtons","_addModalName","destruct","desiredHeight","desiredWidth","containerHeight","containerWidth","_resizeContainer","previewHtml","$innerProgressBar","$progressBarStatus","_itemCount","_processedItemCount","_displaySteps","displaySteps","setProcessedItemCount","incrementItemCount","percentage","$modalContainerDiv","$prompt","$promptApplyToRemainingContainer","$promptApplyToRemainingCheckbox","$promptApplyToRemainingLabel","$pomptChoices","_prompts","_promptBatchCallback","_promptBatchReturnData","_promptBatchNum","_showNextPromptInBatch","remainingInBatch","_showPrompt","_handleBatchPromptSelection","applyToRemaining","choiceData","itemsToGo","_promptCallback","$promptMessage","$promptChoices","$promptButtons","$radioButton","_selectPromptChoice","fadeOut","_cancelPrompt","running","paused","pausedForVisibility","jobs","isPaused","_resume","job","_add","qResolve","qReject","_exec","totalSteps","HOME_KEY","END_KEY","_min","_max","Number","isInteger","prevAll","triggerEvent","$activeButton","startPositionX","graduationsMin","graduationsMax","slideMin","slideMax","$overlay","$cursor","$graduations","$graduationsUl","_handleResize","_handleTapStart","_handleTapMove","_handleTapEnd","_handleKeypress","graduationsCalculatedWidth","valueToPosition","current","PAGE_UP_KEY","PAGE_DOWN_KEY","touch","startLeft","curX","positionToValue","scaleMin","scaleMax","addModalAttributes","autoOpen","setTriggerElement","_cancelTransitionListeners","addPanel","removePanel","openPanels","panel","updateStyles","totalPanels","SlugGenerator","allowUppercaseInSlug","limitAutoSlugsToAscii","XRegExp","matchChain","slugWordSeparator","Structure","structureDrag","$parents","initToggle","StructureDrag","initNewChildMenus","viewStateKey","$addBtns","onNewChildMenuClick","showMenu","getIndent","level","baseIndent","nestedIndent","addElement","$parentUl","_removeUl","structure","draggeeLevel","$helperLi","$targets","draggeeHeight","$level","cancelDrag","$lis","$closestTarget","closestTargetPos","closestTargetYDiff","closestTargetOffset","closestTargetHeight","targetOffset","targetHeight","targetYMidpoint","targetYDiff","$closestTargetLi","closestTargetLevel","$nextTargetLi","nextTargetLevel","hoveringBetweenRows","draggeeX","targetItemMouseDiffX","$parentLis","$closestParentLi","closestParentLiXDiff","closestParentLevel","$parentLi","parentLiX","parentLiXDiff","parentLevel","onMouseUp","$draggeeParent","moved","$closestSiblings","newLevel","setLevel","structureId","prevId","indent","$childLis","StructureTableSorter","tableView","_basePadding","_helperMargin","_$firstRowCells","_$titleHelperCell","_titleHelperCellOuterWidth","_ancestors","_updateAncestorsFrame","_draggeeLevel","_draggeeLevelDelta","draggingLastElements","_loadingDraggeeLevelDelta","_targetLevel","_targetLevelBounds","_positionChanged","singleHelper","helperSpacingY","findDraggee","$nextRow","nextRowLevel","nextRowLevelDelta","_getAjaxBaseData","delta","drag","$helperCell","$firstRowCell","canInsertBefore","_getLevelBounds","canInsertAfter","_getAncestors","_setTargetLevelBounds","_updateIndent","onInsertionPointChange","_updateAncestorsBeforeRepaint","levelDiff","padding","_getLevelIndent","$prevRow","prevRowLevel","$spinnerRow","_createSpinnerRowAfter","onPositionChange","_expandElement","onReturnHelpersToDraggees","newDraggeeIndexes","oldDraggeeIndexes","$postDraggeeItems","nextAll","_minLevel","_maxLevel","forcePositionChange","_mouseDist","realMouseX","mousedownX","_indentationDist","LEVEL_INDENT","_targetLevelMouseDiff","_magnetImpact","MAX_GIVE","_closestLevelMagnetIndent","targetLevel","_level","_$prevRow","cancelAnimationFrame","_updateAncestors","_$ancestor","_newAncestors","ancestorTitle","HELPER_MARGIN","$tableCaption","$selectedSortHeader","structureTableSort","_totalVisiblePostStructureTableDraggee","_morePendingPostStructureTableDraggee","_broadcastListener","initTableHeaders","_updateScreenReaderStatus","_collapseElement","attributeHtml","selectedSortAttr","selectedSortDir","$tableHeaders","sortValue","makeColumnSortable","sorted","headerHtml","$instructions","$headerButton","_handleSelectedSortHeaderClick","_handleUnselectedSortHeaderClick","_isStructureTableDraggingLastElements","positionedAfter","updateResponsiveTables","$nextNextRow","descendantOf","$nextRows","newSortDir","_handleSortHeaderClick","attrLabel","dirLabel","_updateTableAttributes","removeEventListener","$tablist","$firstTab","$lastTab","$selectedTab","$focusableTab","makeTabFocusable","scrollToTab","updateMenuBtn","focusTab","_getTab","deselectTab","$slideoutContainer","elemScrollOffset","targetScrollLeft","tabWidth","ulWidth","HTMLElement","TagSelectInput","searchMenu","$addTagInput","_ignoreBlur","searchForTags","selectTag","$hoverOption","$nextOption","focusOption","$prevOption","killSearchMenu","excludeIds","tagGroupId","tags","exclude","exactMatch","Menu","attachToElement","targetSiteId","$titleContainer","autocomplete","inputmode","maxlength","autofocus","getAutofocusValue","getDisabledValue","readonly","showCharsLeft","createCopyTextInput","buttonId","execCommand","createCopyTextBtn","copyValue","createCopyTextField","createCopyTextPrompt","createTextarea","createTextareaField","$select","optgroup","$optgroup","selected","reverseToggle","createCheckboxField","createCheckboxSelect","allValue","allChecked","allLabel","labelId","$colorPreviewContainer","createColorField","isMobile","getMonth","toISOString","timezone","defaultDate","hasOuterContainer","createDateField","createDateRangePicker","today","getFullYear","getDate","startDate","endDate","$allOption","firstDayOffset","getDay","firstDay","$flex","$startDate","$endDate","$dateInputs","dpDiv","setPositionRelativeToAnchor","startTime","endTime","foundOption","btnClasses","timepicker","timepickerOptions","getHours","getMinutes","getSeconds","createTimeField","warning","$warning","addErrorsToList","$errors","_rejectedFiles","_extensionList","_totalFileCounter","_validFileCounter","autoUpload","fileupload","onFileAdd","paramObject","getInProgress","validateExtension","_createExtensionList","process","done","files","pass","fileExtension","maxFileSize","originalFiles","processErrorMessages","kinds","humanFileSize","maxUploadSize","bytes","threshold","u","toFixed","allowedKind","fileKinds","extensions","ext","pasteZone","sequentialUploads","Accept","UriFormatGenerator","uriFormat","suffix","UserIndex","updateUrl","defaultSourceSlug","slug","__esModule","default","module","locals","exports","listToStyles","list","styles","newStyles","part","media","sourceMap","parts","hasDocument","DEBUG","Error","stylesInDom","head","getElementsByTagName","singletonElement","singletonCounter","isProduction","ssrIdKey","isOldIE","navigator","userAgent","addStylesClient","_isProduction","_options","addStylesToDom","newList","mayRemove","domStyle","refs","addStyle","createStyleElement","styleElement","querySelector","parentNode","styleIndex","applyToSingletonTag","applyToTag","newObj","textStore","replaceText","replacement","Boolean","styleSheet","cssText","cssNode","createTextNode","childNodes","ssrId","btoa","unescape","firstChild","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getter","definition","enumerable","prototype","CP","authManager","$navToggle","$globalSidebar","$globalContainer","$alerts","$crumbs","$breadcrumbList","$breadcrumbItems","$notificationContainer","$mainContent","$details","$sidebarContainer","$sidebarToggle","$edition","$deltaForms","$collapsibleTables","breadcrumbListWidth","breadcrumbDisclosureItem","enableQueue","totalJobs","jobInfo","displayedJobInfo","displayedJobInfoUnchanged","trackJobProgressTimeout","jobProgressIcon","checkingForUpdates","forcingRefreshOnUpdatesCheck","includingDetailsOnUpdatesCheck","checkForUpdatesCallbacks","resizeTimeout","$allInstructions","updateFixedHeader","setSidebarNavAttributes","initSpecialForms","initAlerts","shortcuts","shortcut","initTabs","LOCATION_HASH","_handleInputFocus","_handleInputBlur","announcements","$unreadMessage","hasUnreads","unread","footer","IntersectionObserver","classList","intersectionRatio","rootMargin","observe","$contentHeader","$forms","confirmUnload","returnValue","updateSidebarMenuLabel","toggleNav","isExpanded","navIsExpanded","disableGlobalSidebarLinks","enableGlobalSidebarLinks","focusableItems","isAlwaysVisible","getComputedStyle","getPropertyValue","newState","toggleClass","$tabsContainer","$tabsList","selectedTabIndex","handleBreadcrumbVisibility","breadcrumbItemsWrap","listWidth","totalItemWidth","finalIndex","visibleItemWidth","shownItems","hiddenItems","_$table","_containerWidth","_check","_isCollapsed","headerHeight","displayNotification","notification","Notification","notificationType","iconLabel","fetchAlerts","alerts","displayAlerts","showIcon","$shunnableAlerts","$link","checkForUpdates","forceRefresh","includeDetails","realCallback","_checkForUpdates","updateUtilitiesBadge","callbacks","updateInfo","_getUpdates","_checkForCachedUpdates","cached","onlyIfCached","updates","_cacheUpdates","$utilitiesLink","$screenReaderText","badgeCount","runQueueAutomatically","trackJobProgress","_trackJobProgressInternal","setJobInfo","oldInfo","getDisplayedJobInfo","progressLabel","updateJobIcon","statuses","JOB_STATUS_RESERVED","JOB_STATUS_FAILED","JOB_STATUS_WAITING","JobProgressIcon","hideFailMode","setDescription","description","setProgress","showFailMode","cpTrigger","notificationDuration","JOB_STATUS_DONE","closing","closeTimeout","_preventDelayedClose","originalActiveElement","$closeBtnContainer","details","_negMargin","_initDelayedClose","delayedClose","preventDelayedClose","$progressLabel","failMode","_$bgCanvas","_$staticCanvas","_$hoverCanvas","_$failCanvas","_staticCtx","_hoverCtx","_canvasSize","_arcPos","_arcRadius","_lineWidth","_arcStartPos","_arcEndPos","_arcStartStepSize","_arcEndStepSize","_arcStep","_arcStepTimeout","_arcAnimateCallback","_progressBar","canAccessQueueManager","$canvasContainer","$labelContainer","_createCanvas","getContext","_drawArc","_animateArc","_setArc","color","$canvas","ctx","strokeStyle","lineWidth","lineCap","startPos","endPos","clearRect","beginPath","arc","closePath","targetStartPos","targetEndPos","_takeNextArcStep"],"sourceRoot":""}
\ No newline at end of file
+{"version":3,"file":"cp.js","mappings":"oDAKAA,MAAMC,UAAYC,QAAQC,KAAKC,OAAO,CACpCC,SAAU,KACVC,eAAgB,KAEhBC,SAAU,KAEVC,KAAM,SAAUC,GAAS,WACvBC,KAAKL,SAAWM,EAAEF,GAGdC,KAAKL,SAASO,KAAK,eACrBC,QAAQC,KAAK,2DACbJ,KAAKL,SAASO,KAAK,aAAaG,WAGlCL,KAAKL,SAASO,KAAK,YAAaF,MAChCA,KAAKJ,eAAiBI,KAAKL,SAASW,KAAK,iBAAgB,WACjDN,KAAKL,SAASW,KAAK,kBACvB,KAEAN,KAAKJ,iBACPI,KAAKH,SAAWI,EAAED,KAAKJ,iBAGzBI,KAAKO,YAAYP,KAAKL,SAAU,QAAS,kBACzCK,KAAKO,YAAYP,KAAKL,SAAU,YAAY,SAACa,GAC3C,IAAMC,EAAMD,EAAME,QAEdD,IAAQjB,QAAQmB,WAAaF,IAAQjB,QAAQoB,aAC/CJ,EAAMK,iBACN,EAAKC,iBAET,GACF,EAEAA,eAAgB,WACyC,SAAxCd,KAAKL,SAASW,KAAK,iBAGhCN,KAAKe,WAAWf,KAAKH,UAErBG,KAAKgB,WAAWhB,KAAKH,SAEzB,EAEAmB,WAAY,SAAUC,GAAS,WAC7B,GAAIA,GAAWA,EAAQC,OAAQ,CAC7BlB,KAAKgB,WAAWG,eAAiBF,EAAQG,SAEzCH,EAAQI,YAAY,UAEpBrB,KAAKL,SACF0B,YAAY,aACZC,SAAS,YACThB,KAAK,gBAAiB,QAEzB,IAAK,IAAIiB,EAAI,EAAGA,EAAIN,EAAQC,OAAQK,KAClC,SAAEC,GAC4B,SAAxBA,EAAGC,KAAK,cACVD,EAAGJ,OAAO,QACV,EAAKJ,WAAWU,cAAgBF,EAAG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KAAKgmH,YACJ,IAAiB,EAAXwB,GAAgB74G,KAAK8K,IAC3B,IAAe,EAATguG,GAAc94G,KAAK8K,IAE5B2tG,EAAInzG,SACJmzG,EAAIS,WACN,EAEAb,YAAa,SAAUc,EAAgBC,EAAc3oG,GAC/Cpf,KAAKumH,iBACPvvF,aAAah3B,KAAKumH,iBAGpBvmH,KAAKsmH,SAAW,EAChBtmH,KAAKomH,mBAAqB0B,EAAiB9nH,KAAKkmH,cAAgB,GAChElmH,KAAKqmH,iBAAmB0B,EAAe/nH,KAAKmmH,YAAc,GAC1DnmH,KAAKwmH,oBAAsBpnG,EAC3Bpf,KAAKgoH,kBACP,EAEAA,iBAAkB,WAChBhoH,KAAKinH,QACHjnH,KAAKkmH,aAAelmH,KAAKomH,kBACzBpmH,KAAKmmH,WAAanmH,KAAKqmH,iBAGzBrmH,KAAKsmH,WAEDtmH,KAAKsmH,SAAW,GAClBtmH,KAAKumH,gBAAkBxvF,WAAW/2B,KAAKgoH,iBAAiB3hH,KAAKrG,MAAO,IAC3DA,KAAKwmH,qBACdxmH,KAAKwmH,qBAET,I","sources":["webpack:///./js/Accordion.js","webpack:///./js/AddressesInput.js","webpack:///./js/AdminTable.js","webpack:///./js/AssetImageEditor.js","webpack:///./js/AssetIndex.js","webpack:///./js/AssetMover.js","webpack:///./js/AssetSelectInput.js","webpack:///./js/AssetSelectorModal.js","webpack:///./js/AssetsFieldSettings.js","webpack:///./js/AuthManager.js","webpack:///./js/BaseElementIndex.js","webpack:///./js/BaseElementIndexView.js","webpack:///./js/BaseElementSelectInput.js","webpack:///./js/BaseElementSelectorModal.js","webpack:///./js/BaseInputGenerator.js","webpack:///./js/CategoryIndex.js","webpack:///./js/CategorySelectInput.js","webpack:///./js/Chart.js","webpack:///./js/ColorInput.js","webpack:///./js/CpScreenSlideout.js","webpack:///./js/Craft.js","webpack:///./js/CustomizeSourcesModal.js","webpack:///./js/DataTableSorter.js","webpack:///./js/DeleteUserModal.js","webpack:///./js/DynamicGenerator.js","webpack:///./js/EditableTable.js","webpack:///./js/ElementActionTrigger.js","webpack:///./js/ElementEditor.js","webpack:///./js/ElementEditorSlideout.js","webpack:///./js/ElementFieldSettings.js","webpack:///./js/ElementThumbLoader.js","webpack:///./js/ElevatedSessionForm.js","webpack:///./js/ElevatedSessionManager.js","webpack:///./js/EntryIndex.js","webpack:///./js/FieldLayoutDesigner.js","webpack:///./js/FieldToggle.js","webpack:///./js/Grid.js","webpack:///./js/HandleGenerator.js","webpack:///./js/ImageUpload.js","webpack:///./js/InfoIcon.js","webpack:///./js/LightSwitch.js","webpack:///./js/Listbox.js","webpack:///./js/LivePreview.js","webpack:///./js/PasswordInput.js","webpack:///./js/Preview.js","webpack:///./js/PreviewFileModal.js","webpack:///./js/ProgressBar.js","webpack:///./js/PromptHandler.js","webpack:///./js/Queue.js","webpack:///./js/SlidePicker.js","webpack:///./js/SlideRuleInput.js","webpack:///./js/Slideout.js","webpack:///./js/SlugGenerator.js","webpack:///./js/Structure.js","webpack:///./js/StructureDrag.js","webpack:///./js/StructureTableSorter.js","webpack:///./js/TableElementIndexView.js","webpack:///./js/Tabs.js","webpack:///./js/TagSelectInput.js","webpack:///./js/ThumbsElementIndexView.js","webpack:///./js/UI.js","webpack:///./js/Uploader.js","webpack:///./js/UriFormatGenerator.js","webpack:///./js/UserIndex.js","webpack:///./js/VolumeFolderSelectorModal.js","webpack:///./css/charts.scss?4afb","webpack:///./css/craft.scss?1b58","webpack:///../../../../../node_modules/vue-style-loader/lib/listToStyles.js","webpack:///../../../../../node_modules/vue-style-loader/lib/addStylesClient.js","webpack:///webpack/bootstrap","webpack:///webpack/runtime/compat get default export","webpack:///webpack/runtime/define property getters","webpack:///webpack/runtime/hasOwnProperty shorthand","webpack:///external var \"jQuery\"","webpack:///./js/CP.js"],"sourcesContent":["/** global: Craft */\n/** global: Garnish */\n/**\n * Accordion\n */\nCraft.Accordion = Garnish.Base.extend({\n  $trigger: null,\n  targetSelector: null,\n\n  _$target: null,\n\n  init: function (trigger) {\n    this.$trigger = $(trigger);\n\n    // Is this already an accordion trigger?\n    if (this.$trigger.data('accordion')) {\n      console.warn('Double-instantiating an accordion trigger on an element');\n      this.$trigger.data('accordion').destroy();\n    }\n\n    this.$trigger.data('accordion', this);\n    this.targetSelector = this.$trigger.attr('aria-controls')\n      ? `#${this.$trigger.attr('aria-controls')}`\n      : null;\n\n    if (this.targetSelector) {\n      this._$target = $(this.targetSelector);\n    }\n\n    this.addListener(this.$trigger, 'click', 'onTriggerClick');\n    this.addListener(this.$trigger, 'keypress', (event) => {\n      const key = event.keyCode;\n\n      if (key === Garnish.SPACE_KEY || key === Garnish.RETURN_KEY) {\n        event.preventDefault();\n        this.onTriggerClick();\n      }\n    });\n  },\n\n  onTriggerClick: function () {\n    const isOpen = this.$trigger.attr('aria-expanded') === 'true';\n\n    if (isOpen) {\n      this.hideTarget(this._$target);\n    } else {\n      this.showTarget(this._$target);\n    }\n  },\n\n  showTarget: function ($target) {\n    if ($target && $target.length) {\n      this.showTarget._currentHeight = $target.height();\n\n      $target.removeClass('hidden');\n\n      this.$trigger\n        .removeClass('collapsed')\n        .addClass('expanded')\n        .attr('aria-expanded', 'true');\n\n      for (let i = 0; i < $target.length; i++) {\n        (($t) => {\n          if ($t.prop('nodeName') !== 'SPAN') {\n            $t.height('auto');\n            this.showTarget._targetHeight = $t.height();\n            $t.css({\n              height: this.showTarget._currentHeight,\n              overflow: 'hidden',\n            });\n\n            $t.velocity('stop');\n\n            $t.velocity(\n              {height: this.showTarget._targetHeight},\n              Garnish.getUserPreferredAnimationDuration('fast'),\n              function () {\n                $t.css({\n                  height: '',\n                  overflow: '',\n                });\n              }\n            );\n          }\n        })($target.eq(i));\n      }\n\n      delete this.showTarget._targetHeight;\n      delete this.showTarget._currentHeight;\n\n      // Trigger a resize event in case there are any grids in the target that need to initialize\n      Garnish.$win.trigger('resize');\n    }\n  },\n\n  hideTarget: function ($target) {\n    if ($target && $target.length) {\n      this.$trigger\n        .removeClass('expanded')\n        .addClass('collapsed')\n        .attr('aria-expanded', 'false');\n\n      for (let i = 0; i < $target.length; i++) {\n        (($t) => {\n          if ($t.hasClass('hidden')) {\n            return;\n          }\n          if ($t.prop('nodeName') === 'SPAN') {\n            $t.addClass('hidden');\n          } else {\n            $t.css('overflow', 'hidden');\n            $t.velocity('stop');\n            $t.velocity(\n              {height: 0},\n              Garnish.getUserPreferredAnimationDuration('fast'),\n              function () {\n                $t.addClass('hidden');\n              }\n            );\n          }\n        })($target.eq(i));\n      }\n    }\n  },\n\n  destroy: function () {\n    this.$trigger.removeData('accordion');\n    this.base();\n  },\n});\n","/** global: Craft */\n\n/**\n * AddressInput class\n */\nCraft.AddressesInput = Garnish.Base.extend(\n  {\n    $container: null,\n    $addBtn: null,\n    $addBtnItem: null,\n    $cards: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.AddressesInput.defaults);\n\n      // Is this already an address input?\n      if (this.$container.data('addresses')) {\n        console.warn('Double-instantiating an address input on an element');\n        this.$container.data('addresses').destroy();\n      }\n\n      this.$container.data('addresses', this);\n\n      this.$addBtn = this.$container.find('.address-cards__add-btn');\n      this.$addBtnItem = this.$addBtn.closest('li');\n      this.$cards = this.$container.find('> .address-card');\n\n      for (let i = 0; i < this.$cards.length; i++) {\n        this.initCard(this.$cards.eq(i));\n      }\n\n      this.updateAddButton();\n\n      this.addListener(this.$addBtn, 'click', () => {\n        this.createAddress();\n      });\n    },\n\n    initCard: function ($card) {\n      this.addListener($card, 'click', (ev) => {\n        if (!$(ev.target).closest('.menubtn').length) {\n          this.editAddress($card);\n        }\n      });\n\n      const $actionBtn = $card.find('.menubtn').disclosureMenu();\n      if ($actionBtn.length) {\n        const menu = $actionBtn.data('trigger');\n        const $menu = menu.$container;\n\n        // Activate edit button\n        const $editBtn = $menu.find('[data-action=\"edit\"]');\n        this.addListener($editBtn, 'click', (ev) => {\n          ev.stopPropagation();\n          this.editAddress($card);\n        });\n\n        // Activate delete button\n        const $deleteBtn = $menu.find('[data-action=\"delete\"]');\n        this.addListener($deleteBtn, 'click', (ev) => {\n          ev.preventDefault();\n          ev.stopPropagation();\n          if (\n            confirm(\n              Craft.t('app', 'Are you sure you want to delete this address?')\n            )\n          ) {\n            this.$addBtn.addClass('loading');\n            const addressId = $card.data('id');\n            const draftId = $card.data('draft-id');\n            Craft.sendActionRequest('POST', 'elements/delete', {\n              data: {\n                elementId: addressId,\n                draftId: draftId,\n              },\n            })\n              .then(() => {\n                $card.remove();\n                $menu.remove();\n                menu.destroy();\n                this.$cards = this.$cards.not($card);\n                this.updateAddButton();\n\n                this.trigger('deleteAddress', {\n                  addressId,\n                  draftId,\n                });\n              })\n              .finally(() => {\n                this.$addBtn.removeClass('loading');\n              });\n          }\n        });\n      }\n    },\n\n    editAddress: function ($card, settings) {\n      const slideout = Craft.createElementEditor(\n        'craft\\\\elements\\\\Address',\n        $card,\n        settings\n      );\n\n      slideout.on('submit', (ev) => {\n        this.trigger('saveAddress', {\n          data: ev.data,\n        });\n\n        Craft.sendActionRequest('POST', 'addresses/card-html', {\n          data: {\n            addressId: ev.data.id,\n          },\n        }).then((response) => {\n          const $newCard = $(response.data.html);\n          if ($card) {\n            $card.replaceWith($newCard);\n            this.$cards = this.$cards.not($card);\n          } else {\n            $newCard.insertBefore(this.$addBtnItem);\n          }\n          Craft.initUiElements($newCard);\n          this.initCard($newCard);\n          this.$cards = this.$cards.add($newCard);\n          this.updateAddButton();\n        });\n      });\n    },\n\n    updateAddButton: function () {\n      if (this.canCreateAddress()) {\n        this.$addBtn.removeClass('hidden');\n      } else {\n        this.$addBtn.addClass('hidden');\n      }\n    },\n\n    canCreateAddress: function () {\n      return (\n        !this.settings.maxAddresses ||\n        this.$cards.length < this.settings.maxAddresses\n      );\n    },\n\n    createAddress: function () {\n      if (!this.canCreateAddress()) {\n        throw 'No more addresses can be created.';\n      }\n\n      this.$addBtn.addClass('loading');\n\n      Craft.sendActionRequest('POST', 'elements/create', {\n        data: {\n          elementType: 'craft\\\\elements\\\\Address',\n          ownerId: this.settings.ownerId,\n        },\n      })\n        .then((ev) => {\n          this.editAddress(null, {\n            elementId: ev.data.element.id,\n            draftId: ev.data.element.draftId,\n          });\n        })\n        .finally(() => {\n          this.$addBtn.removeClass('loading');\n        });\n    },\n\n    destroy: function () {\n      this.$container.removeData('addresses');\n      this.base();\n    },\n  },\n  {\n    ownerId: null,\n    defaults: {\n      maxAddresses: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Admin table class\n */\nCraft.AdminTable = Garnish.Base.extend(\n  {\n    settings: null,\n    totalItems: null,\n    sorter: null,\n\n    $noItems: null,\n    $table: null,\n    $tbody: null,\n    $deleteBtns: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.AdminTable.defaults);\n\n      if (!this.settings.allowDeleteAll) {\n        this.settings.minItems = 1;\n      }\n\n      this.$noItems = $(this.settings.noItemsSelector);\n      this.$table = $(this.settings.tableSelector);\n      this.$tbody = this.$table.children('tbody');\n      this.totalItems = this.$tbody.children().length;\n\n      if (this.settings.sortable) {\n        this.sorter = new Craft.DataTableSorter(this.$table, {\n          onSortChange: this.reorderItems.bind(this),\n        });\n      }\n\n      this.$deleteBtns = this.$table.find('.delete:not(.disabled)');\n      this.addListener(this.$deleteBtns, 'click', 'handleDeleteBtnClick');\n      this.addListener(this.$deleteBtns, 'keydown', (event) => {\n        if (\n          event.keyCode === Garnish.SPACE_KEY ||\n          event.keyCode === Garnish.RETURN_KEY\n        ) {\n          event.preventDefault();\n          this.handleDeleteBtnClick(event);\n        }\n      });\n\n      this.updateUI();\n    },\n\n    addRow: function (row) {\n      if (this.settings.maxItems && this.totalItems >= this.settings.maxItems) {\n        // Sorry pal.\n        return;\n      }\n\n      var $row = $(row).appendTo(this.$tbody),\n        $deleteBtn = $row.find('.delete');\n\n      if (this.settings.sortable) {\n        this.sorter.addItems($row);\n      }\n\n      this.$deleteBtns = this.$deleteBtns.add($deleteBtn);\n\n      this.addListener($deleteBtn, 'click', 'handleDeleteBtnClick');\n      this.totalItems++;\n\n      this.updateUI();\n    },\n\n    reorderItems: function () {\n      if (!this.settings.sortable) {\n        return;\n      }\n\n      // Get the new field order\n      var ids = [];\n\n      for (var i = 0; i < this.sorter.$items.length; i++) {\n        var id = $(this.sorter.$items[i]).attr(this.settings.idAttribute);\n        ids.push(id);\n      }\n\n      // Send it to the server\n      var data = {\n        ids: JSON.stringify(ids),\n      };\n\n      Craft.sendActionRequest('POST', this.settings.reorderAction, {data})\n        .then((response) => {\n          this.onReorderItems(ids);\n          Craft.cp.displaySuccess(\n            Craft.t('app', this.settings.reorderSuccessMessage)\n          );\n        })\n        .catch(({response}) => {\n          Craft.cp.displayError(\n            Craft.t('app', this.settings.reorderFailMessage)\n          );\n        });\n    },\n\n    handleDeleteBtnClick: function (event) {\n      if (this.settings.minItems && this.totalItems <= this.settings.minItems) {\n        // Sorry pal.\n        return;\n      }\n\n      var $row = $(event.target).closest('tr');\n\n      if (this.confirmDeleteItem($row)) {\n        this.deleteItem($row);\n      }\n    },\n\n    confirmDeleteItem: function ($row) {\n      if (!this.settings.confirmDeleteMessage) {\n        return true;\n      }\n\n      var name = this.getItemName($row);\n      return confirm(\n        Craft.t('app', this.settings.confirmDeleteMessage, {name})\n      );\n    },\n\n    deleteItem: function ($row) {\n      var data = {\n        id: this.getItemId($row),\n      };\n\n      Craft.sendActionRequest('POST', this.settings.deleteAction, {data})\n        .then((response) => this.handleDeleteItemSuccess(response.data, $row))\n        .catch(({response}) =>\n          this.handleDeleteItemFailure(response.data, $row)\n        );\n    },\n\n    handleDeleteItemFailure: function (data, $row) {\n      var id = this.getItemId($row),\n        name = this.getItemName($row);\n\n      Craft.cp.displayError(\n        Craft.t('app', this.settings.deleteFailMessage, {name})\n      );\n    },\n\n    handleDeleteItemSuccess: function (data, $row) {\n      var id = this.getItemId($row),\n        name = this.getItemName($row);\n\n      if (this.sorter) {\n        this.sorter.removeItems($row);\n      }\n\n      $row.remove();\n      this.totalItems--;\n      this.updateUI();\n      this.onDeleteItem(id);\n\n      if (this.settings.deleteSuccessMessage) {\n        Craft.cp.displaySuccess(\n          Craft.t('app', this.settings.deleteSuccessMessage, {name})\n        );\n      }\n    },\n\n    onReorderItems: function (ids) {\n      this.settings.onReorderItems(ids);\n    },\n\n    onDeleteItem: function (id) {\n      this.settings.onDeleteItem(id);\n    },\n\n    getItemId: function ($row) {\n      return $row.attr(this.settings.idAttribute);\n    },\n\n    getItemName: function ($row) {\n      return Craft.escapeHtml($row.attr(this.settings.nameAttribute));\n    },\n\n    updateUI: function () {\n      // Show the \"No Whatever Exists\" message if there aren't any\n      if (this.totalItems === 0) {\n        this.$table.hide();\n        this.$noItems.removeClass('hidden');\n      } else {\n        this.$table.show();\n        this.$noItems.addClass('hidden');\n      }\n\n      // Disable the sort buttons if there's only one row\n      if (this.settings.sortable) {\n        var $moveButtons = this.$table.find('.move');\n\n        if (this.totalItems === 1) {\n          $moveButtons.addClass('disabled');\n        } else {\n          $moveButtons.removeClass('disabled');\n        }\n      }\n\n      // Disable the delete buttons if we've reached the minimum items\n      if (this.settings.minItems && this.totalItems <= this.settings.minItems) {\n        this.$deleteBtns.addClass('disabled');\n      } else {\n        this.$deleteBtns.removeClass('disabled');\n      }\n\n      // Hide the New Whatever button if we've reached the maximum items\n      if (this.settings.newItemBtnSelector) {\n        if (\n          this.settings.maxItems &&\n          this.totalItems >= this.settings.maxItems\n        ) {\n          $(this.settings.newItemBtnSelector).addClass('hidden');\n        } else {\n          $(this.settings.newItemBtnSelector).removeClass('hidden');\n        }\n      }\n    },\n  },\n  {\n    defaults: {\n      tableSelector: null,\n      noItemsSelector: null,\n      newItemBtnSelector: null,\n      idAttribute: 'data-id',\n      nameAttribute: 'data-name',\n      sortable: false,\n      allowDeleteAll: true,\n      minItems: 0,\n      maxItems: null,\n      reorderAction: null,\n      deleteAction: null,\n      reorderSuccessMessage: Craft.t('app', 'New order saved.'),\n      reorderFailMessage: Craft.t('app', 'Couldn’t save new order.'),\n      confirmDeleteMessage: Craft.t(\n        'app',\n        'Are you sure you want to delete “{name}”?'\n      ),\n      deleteSuccessMessage: Craft.t('app', '“{name}” deleted.'),\n      deleteFailMessage: Craft.t('app', 'Couldn’t delete “{name}”.'),\n      onReorderItems: $.noop,\n      onDeleteItem: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Asset image editor class\n */\n\nCraft.AssetImageEditor = Garnish.Modal.extend(\n  {\n    // jQuery objects\n    $body: null,\n    $footer: null,\n    $imageTools: null,\n    $buttons: null,\n    $cancelBtn: null,\n    $replaceBtn: null,\n    $saveBtn: null,\n    $focalPointBtn: null,\n    $editorContainer: null,\n    $straighten: null,\n    $croppingCanvas: null,\n    $spinner: null,\n    $constraintContainer: null,\n    $constraintRadioInputs: null,\n    $customConstraints: null,\n\n    // FabricJS objects\n    canvas: null,\n    image: null,\n    viewport: null,\n    focalPoint: null,\n    grid: null,\n    croppingCanvas: null,\n    clipper: null,\n    croppingRectangle: null,\n    cropperHandles: null,\n    cropperGrid: null,\n    croppingShade: null,\n\n    // Image state attributes\n    imageStraightenAngle: 0,\n    viewportRotation: 0,\n    originalWidth: 0,\n    originalHeight: 0,\n    imageVerticeCoords: null,\n    zoomRatio: 1,\n\n    // Editor state attributes\n    animationInProgress: false,\n    currentView: '',\n    assetId: null,\n    cacheBust: null,\n    draggingCropper: false,\n    scalingCropper: false,\n    draggingFocal: false,\n    previousMouseX: 0,\n    previousMouseY: 0,\n    shiftKeyHeld: false,\n    editorHeight: 0,\n    editorWidth: 0,\n    cropperState: false,\n    scaleFactor: 1,\n    flipData: {},\n    focalPointState: false,\n    maxImageSize: null,\n    lastLoadedDimensions: null,\n    imageIsLoading: false,\n    mouseMoveEvent: null,\n    croppingConstraint: false,\n    constraintOrientation: 'landscape',\n    showingCustomConstraint: false,\n    saving: false,\n\n    // Rendering proxy functions\n    renderImage: null,\n    renderCropper: null,\n\n    _queue: null,\n\n    init: function (assetId, settings) {\n      this._queue = new Craft.Queue();\n\n      this.cacheBust = Date.now();\n\n      this.setSettings(settings, Craft.AssetImageEditor.defaults);\n\n      if (this.settings.allowDegreeFractions === null) {\n        this.settings.allowDegreeFractions = Craft.isImagick;\n      }\n\n      if (Garnish.prefersReducedMotion()) {\n        this.settings.animationDuration = 1;\n      }\n\n      this.assetId = assetId;\n      this.flipData = {x: 0, y: 0};\n\n      // Build the modal\n      this.$container = $(\n        '<form class=\"modal fitted imageeditor\"></form>'\n      ).appendTo(Garnish.$bod);\n      this.$body = $('<div class=\"body\"></div>').appendTo(this.$container);\n      this.$footer = $('<div class=\"footer\"/>').appendTo(this.$container);\n\n      this.base(this.$container, this.settings);\n\n      this.$buttons = $('<div class=\"buttons right\"/>').appendTo(this.$footer);\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn cancel',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$buttons);\n\n      if (this.settings.allowSavingAsNew) {\n        this.$saveBtn = Craft.ui\n          .createButton({\n            class: 'save copy',\n            label: Craft.t('app', 'Save as a new asset'),\n            spinner: true,\n          })\n          .appendTo(this.$buttons);\n        this.addListener(this.$saveBtn, 'activate', this.saveImage);\n      }\n\n      this.$replaceBtn = Craft.ui\n        .createSubmitButton({\n          class: 'save replace',\n          label: Craft.t('app', 'Save'),\n          spinner: true,\n        })\n        .appendTo(this.$buttons);\n\n      this.addListener(this.$replaceBtn, 'activate', this.saveImage);\n      this.addListener(this.$cancelBtn, 'activate', this.hide);\n      this.removeListener(this.$shade, 'click');\n\n      this.maxImageSize = this.getMaxImageSize();\n      Craft.sendActionRequest('POST', 'assets/image-editor', {\n        data: {assetId},\n      }).then((response) => this.loadEditor(response.data));\n    },\n\n    /**\n     * Get the max image size that is viewable in the editor currently\n     */\n    getMaxImageSize: function () {\n      var browserViewportWidth =\n        Garnish.$doc.get(0).documentElement.clientWidth;\n      var browserViewportHeight =\n        Garnish.$doc.get(0).documentElement.clientHeight;\n\n      return (\n        Math.max(browserViewportHeight, browserViewportWidth) *\n        (window.devicePixelRatio > 1 ? 2 : 1)\n      );\n    },\n\n    /**\n     * Load the editor markup and start loading components and the image.\n     *\n     * @param {Object} data\n     */\n    loadEditor: function (data) {\n      if (!data.html) {\n        Craft.cp.displayError(\n          Craft.t('app', 'Could not load the image editor.')\n        );\n      }\n\n      this.$body.html(data.html);\n      this.$tabs = $('.tabs li', this.$body);\n      this.$viewsContainer = $('.views', this.$body);\n      this.$views = $('> div', this.$viewsContainer);\n      this.$imageTools = $('.image-container .image-tools', this.$body);\n      this.$editorContainer = $('.image-container .image', this.$body);\n      this.$constraintContainer = $('.constraint-group', this.$body);\n      this.$constraintRadioInputs = $(\n        '[name=\"constraint\"]',\n        this.$constraintContainer\n      );\n      this.$focalPointBtn = $('.focal-point', this.$body);\n      this.editorHeight = this.$editorContainer.innerHeight();\n      this.editorWidth = this.$editorContainer.innerWidth();\n\n      this._showSpinner();\n\n      this.updateSizeAndPosition();\n\n      $customConstraintWrapper = this.$constraintRadioInputs\n        .filter('[value=\"custom\"]')\n        .parent();\n\n      // Add custom constraint inputs to fieldset\n      this.$customConstraints = $('<div/>', {\n        class: 'constraint custom hidden',\n        'data-constraint': 'custom',\n      })\n        .append(\n          $('<input/>', {\n            type: 'text',\n            class: 'custom-constraint-w',\n            size: 3,\n            value: 1,\n            'aria-label': Craft.t('app', 'Width unit'),\n          })\n        )\n        .append(\n          $('<span/>', {\n            class: 'custom-constraint-spacer',\n            text: 'x',\n            'aria-hidden': 'true',\n          })\n        )\n        .append(\n          $('<input/>', {\n            type: 'text',\n            class: 'custom-constraint-h',\n            size: 3,\n            value: 1,\n            'aria-label': Craft.t('app', 'Height unit'),\n          })\n        )\n        .appendTo($customConstraintWrapper);\n\n      // Specify which get flipped on orientation change\n      this.$constraintRadioInputs\n        .filter(function () {\n          const regex = /^\\d*\\.\\d+$/;\n          const value = $(this).val();\n          return regex.test(value);\n        })\n        .addClass('flip');\n\n      // Load the canvas on which we'll host our image and set up the proxy render function\n      this.canvas = new fabric.StaticCanvas('image-canvas');\n\n      // Set up the cropping canvas jquery element for tracking all the nice events\n      this.$croppingCanvas = $('#cropping-canvas', this.$editorContainer);\n      this.$croppingCanvas.width(this.editorWidth);\n      this.$croppingCanvas.height(this.editorHeight);\n\n      this.canvas.enableRetinaScaling = true;\n      this.renderImage = () => {\n        Garnish.requestAnimationFrame(this.canvas.renderAll.bind(this.canvas));\n      };\n\n      // Load the image from URL\n      var imageUrl = Craft.getActionUrl('assets/edit-image', {\n        assetId: this.assetId,\n        size: this.maxImageSize,\n        cacheBust: this.cacheBust,\n      });\n\n      // Load image and set up the initial properties\n      fabric.Image.fromURL(imageUrl, (imageObject) => {\n        this.image = imageObject;\n        this.image.set({\n          originX: 'center',\n          originY: 'center',\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n        });\n        this.canvas.add(this.image);\n\n        this.originalHeight = this.image.getHeight();\n        this.originalWidth = this.image.getWidth();\n        this.zoomRatio = 1;\n\n        this.lastLoadedDimensions = this.getScaledImageDimensions();\n\n        // Set up the image bounding box, viewport and position everything\n        this._setFittedImageVerticeCoordinates();\n        this._repositionEditorElements();\n\n        // Set up the focal point\n        var focalState = {\n          imageDimensions: this.getScaledImageDimensions(),\n          offsetX: 0,\n          offsetY: 0,\n        };\n\n        var focal = false;\n        if (data.focalPoint) {\n          // Transform the focal point coordinates from relative to absolute\n          var focalData = data.focalPoint;\n\n          // Resolve for the current image dimensions.\n          var adjustedX = focalState.imageDimensions.width * focalData.x;\n          var adjustedY = focalState.imageDimensions.height * focalData.y;\n\n          focalState.offsetX = adjustedX - focalState.imageDimensions.width / 2;\n          focalState.offsetY =\n            adjustedY - focalState.imageDimensions.height / 2;\n\n          focal = true;\n        }\n\n        this.storeFocalPointState(focalState);\n\n        if (focal) {\n          this._createFocalPoint();\n        }\n\n        this._createViewport();\n        this.storeCropperState();\n\n        // Add listeners to buttons\n        this._addControlListeners();\n\n        // Add mouse event listeners\n        this.addListener(\n          this.$croppingCanvas,\n          'mousemove,touchmove',\n          this._handleMouseMove\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mousedown,touchstart',\n          this._handleMouseDown\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mouseup,touchend',\n          this._handleMouseUp\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mouseout,touchcancel',\n          this._handleMouseOut\n        );\n\n        this._hideSpinner();\n\n        // Render it, finally\n        this.renderImage();\n\n        // Make sure verything gets fired for the first tab\n        this.$tabs.first().trigger('click');\n      });\n    },\n\n    /**\n     * Reload the image to better fit the current available image editor viewport.\n     */\n    _reloadImage: function () {\n      if (this.imageIsLoading) {\n        return;\n      }\n\n      this.imageIsLoading = true;\n      this.maxImageSize = this.getMaxImageSize();\n\n      // Load the image from URL\n      var imageUrl = Craft.getActionUrl('assets/edit-image', {\n        assetId: this.assetId,\n        size: this.maxImageSize,\n        cacheBust: this.cacheBust,\n      });\n\n      this.image.setSrc(imageUrl, (imageObject) => {\n        this.originalHeight = imageObject.getHeight();\n        this.originalWidth = imageObject.getWidth();\n        this.lastLoadedDimensions = {\n          width: this.originalHeight,\n          height: this.originalWidth,\n        };\n        this.updateSizeAndPosition();\n        this.renderImage();\n        this.imageIsLoading = false;\n      });\n    },\n\n    /**\n     * Update the modal size and position on browser resize\n     */\n    updateSizeAndPosition: function () {\n      if (!this.$container) {\n        return;\n      }\n\n      // Fullscreen modal\n      var innerWidth = window.innerWidth;\n      var innerHeight = window.innerHeight;\n\n      this.$container.css({\n        width: innerWidth,\n        'min-width': innerWidth,\n        left: 0,\n\n        height: innerHeight,\n        'min-height': innerHeight,\n        top: 0,\n      });\n\n      this.$body.css({\n        height: innerHeight - (this.$footer.outerHeight() - 1),\n      });\n\n      if (innerWidth < innerHeight) {\n        this.$container.addClass('vertical');\n      } else {\n        this.$container.removeClass('vertical');\n      }\n\n      // If image is already loaded, make sure it looks pretty.\n      if (this.$editorContainer && this.image) {\n        this._repositionEditorElements();\n      }\n    },\n\n    /**\n     * Reposition the editor elements to accurately reflect the editor state with current dimensions\n     */\n    _repositionEditorElements: function () {\n      // Remember what the dimensions were before the resize took place\n      var previousEditorDimensions = {\n        width: this.editorWidth,\n        height: this.editorHeight,\n      };\n\n      this.editorHeight = this.$editorContainer.innerHeight();\n      this.editorWidth = this.$editorContainer.innerWidth();\n\n      this.canvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      var currentScaledDimensions = this.getScaledImageDimensions();\n\n      // If we're cropping now, we have to reposition the cropper correctly in case\n      // the area for image changes, forcing the image size to change as well.\n      if (this.currentView === 'crop') {\n        this.zoomRatio = this.getZoomToFitRatio(\n          this.getScaledImageDimensions()\n        );\n        var previouslyOccupiedArea = this._getBoundingRectangle(\n          this.imageVerticeCoords\n        );\n        this._setFittedImageVerticeCoordinates();\n        this._repositionCropper(previouslyOccupiedArea);\n      } else {\n        // Otherwise just recalculate the image zoom ratio\n        this.zoomRatio =\n          this.getZoomToCoverRatio(this.getScaledImageDimensions()) *\n          this.scaleFactor;\n      }\n\n      // Reposition the image relatively to the previous editor dimensions.\n      this._repositionImage(previousEditorDimensions);\n      this._repositionViewport();\n      this._repositionFocalPoint(previousEditorDimensions);\n      this._zoomImage();\n\n      this.renderImage();\n\n      if (\n        currentScaledDimensions.width / this.lastLoadedDimensions.width > 1.5 ||\n        currentScaledDimensions.height / this.lastLoadedDimensions.height > 1.5\n      ) {\n        this._reloadImage();\n      }\n    },\n\n    /**\n     * Reposition image based on how the editor dimensions have changed.\n     * This ensures keeping the image center offset, if there is any.\n     *\n     * @param {Object} previousEditorDimensions\n     */\n    _repositionImage: function (previousEditorDimensions) {\n      this.image.set({\n        left:\n          this.image.left -\n          (previousEditorDimensions.width - this.editorWidth) / 2,\n        top:\n          this.image.top -\n          (previousEditorDimensions.height - this.editorHeight) / 2,\n      });\n    },\n\n    /**\n     * Create the viewport for image editor.\n     */\n    _createViewport: function () {\n      this.viewport = new fabric.Rect({\n        width: this.image.width,\n        height: this.image.height,\n        fill: 'rgba(127,0,0,1)',\n        originX: 'center',\n        originY: 'center',\n        globalCompositeOperation: 'destination-in', // This clips everything outside of the viewport\n        left: this.image.left,\n        top: this.image.top,\n      });\n      this.canvas.add(this.viewport);\n      this.renderImage();\n    },\n\n    /**\n     * Create the focal point.\n     */\n    _createFocalPoint: function () {\n      var focalPointState = this.focalPointState;\n      var sizeFactor =\n        this.getScaledImageDimensions().width /\n        focalPointState.imageDimensions.width;\n\n      var focalX =\n        focalPointState.offsetX *\n        sizeFactor *\n        this.zoomRatio *\n        this.scaleFactor;\n      var focalY =\n        focalPointState.offsetY *\n        sizeFactor *\n        this.zoomRatio *\n        this.scaleFactor;\n\n      // Adjust by image margins\n      focalX += this.image.left;\n      focalY += this.image.top;\n\n      var deltaX = 0;\n      var deltaY = 0;\n\n      // When creating a fresh focal point, drop it dead in the center of the viewport, not the image.\n      if (\n        this.viewport &&\n        focalPointState.offsetX === 0 &&\n        focalPointState.offsetY === 0\n      ) {\n        if (this.currentView !== 'crop') {\n          deltaX = this.viewport.left - this.image.left;\n          deltaY = this.viewport.top - this.image.top;\n        } else {\n          // Unless we have a cropper showing, in which case drop it in the middle of the cropper\n          deltaX = this.clipper.left - this.image.left;\n          deltaY = this.clipper.top - this.image.top;\n        }\n\n        // Bump focal to middle of viewport\n        focalX += deltaX;\n        focalY += deltaY;\n\n        // Reflect changes in saved state\n        focalPointState.offsetX +=\n          deltaX / (sizeFactor * this.zoomRatio * this.scaleFactor);\n        focalPointState.offsetY +=\n          deltaY / (sizeFactor * this.zoomRatio * this.scaleFactor);\n      }\n\n      this.focalPoint = new fabric.Group(\n        [\n          new fabric.Circle({\n            radius: 8,\n            fill: 'rgba(0,0,0,0.5)',\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,0.8)',\n            left: 0,\n            top: 0,\n            originX: 'center',\n            originY: 'center',\n          }),\n          new fabric.Circle({\n            radius: 1,\n            fill: 'rgba(255,255,255,0)',\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,0.8)',\n            left: 0,\n            top: 0,\n            originX: 'center',\n            originY: 'center',\n          }),\n        ],\n        {\n          originX: 'center',\n          originY: 'center',\n          left: focalX,\n          top: focalY,\n        }\n      );\n\n      this.storeFocalPointState(focalPointState);\n      this.canvas.add(this.focalPoint);\n    },\n\n    /**\n     * Toggle focal point\n     */\n    toggleFocalPoint: function () {\n      if (!this.focalPoint) {\n        this._createFocalPoint();\n        this.$focalPointBtn.attr('aria-pressed', 'true');\n      } else {\n        this.canvas.remove(this.focalPoint);\n        this.focalPoint = null;\n        this.$focalPointBtn.attr('aria-pressed', 'false');\n      }\n\n      this.renderImage();\n    },\n\n    /**\n     * Reposition the viewport to handle editor resizing.\n     */\n    _repositionViewport: function () {\n      if (this.viewport) {\n        var dimensions = {\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n        };\n\n        // If we're cropping, nothing exciting happens for the viewport\n        if (this.currentView === 'crop') {\n          dimensions.width = this.editorWidth;\n          dimensions.height = this.editorHeight;\n        } else {\n          // If this is the first initial reposition, no cropper state yet\n          if (this.cropperState) {\n            // Recall the state\n            var state = this.cropperState;\n\n            var scaledImageDimensions = this.getScaledImageDimensions();\n            // Make sure we have the correct current image size\n            var sizeFactor =\n              scaledImageDimensions.width / state.imageDimensions.width;\n\n            // Set the viewport dimensions\n            dimensions.width = state.width * sizeFactor * this.zoomRatio;\n            dimensions.height = state.height * sizeFactor * this.zoomRatio;\n\n            // Adjust the image position to show the correct part of the image in the viewport\n            this.image.set({\n              left: this.editorWidth / 2 - state.offsetX * sizeFactor,\n              top: this.editorHeight / 2 - state.offsetY * sizeFactor,\n            });\n          } else {\n            $.extend(dimensions, this.getScaledImageDimensions());\n          }\n        }\n        this.viewport.set(dimensions);\n      }\n    },\n\n    _repositionFocalPoint: function (previousEditorDimensions) {\n      if (this.focalPoint) {\n        var offsetX = this.focalPoint.left - this.editorWidth / 2;\n        var offsetY = this.focalPoint.top - this.editorHeight / 2;\n\n        var currentWidth = this.image.width;\n        var newWidth = this.getScaledImageDimensions().width * this.zoomRatio;\n        var ratio = newWidth / currentWidth / this.scaleFactor;\n\n        offsetX -= (previousEditorDimensions.width - this.editorWidth) / 2;\n        offsetY -= (previousEditorDimensions.height - this.editorHeight) / 2;\n\n        offsetX *= ratio;\n        offsetY *= ratio;\n\n        this.focalPoint.set({\n          left: this.editorWidth / 2 + offsetX,\n          top: this.editorHeight / 2 + offsetY,\n        });\n      }\n    },\n\n    /**\n     * Return true if the image orientation has changed\n     */\n    hasOrientationChanged: function () {\n      return this.viewportRotation % 180 !== 0;\n    },\n\n    /**\n     * Return the current image dimensions that would be used in the current image area with no straightening or rotation applied.\n     */\n    getScaledImageDimensions: function () {\n      if (typeof this.getScaledImageDimensions._ === 'undefined') {\n        this.getScaledImageDimensions._ = {};\n      }\n\n      this.getScaledImageDimensions._.imageRatio =\n        this.originalHeight / this.originalWidth;\n      this.getScaledImageDimensions._.editorRatio =\n        this.editorHeight / this.editorWidth;\n\n      this.getScaledImageDimensions._.dimensions = {};\n      if (\n        this.getScaledImageDimensions._.imageRatio >\n        this.getScaledImageDimensions._.editorRatio\n      ) {\n        this.getScaledImageDimensions._.dimensions.height = Math.min(\n          this.editorHeight,\n          this.originalHeight\n        );\n        this.getScaledImageDimensions._.dimensions.width = Math.round(\n          this.originalWidth /\n            (this.originalHeight /\n              this.getScaledImageDimensions._.dimensions.height)\n        );\n      } else {\n        this.getScaledImageDimensions._.dimensions.width = Math.min(\n          this.editorWidth,\n          this.originalWidth\n        );\n        this.getScaledImageDimensions._.dimensions.height = Math.round(\n          this.originalHeight *\n            (this.getScaledImageDimensions._.dimensions.width /\n              this.originalWidth)\n        );\n      }\n\n      return this.getScaledImageDimensions._.dimensions;\n    },\n\n    /**\n     * Set the image dimensions to reflect the current zoom ratio.\n     */\n    _zoomImage: function () {\n      if (typeof this._zoomImage._ === 'undefined') {\n        this._zoomImage._ = {};\n      }\n\n      this._zoomImage._.imageDimensions = this.getScaledImageDimensions();\n      this.image.set({\n        width: this._zoomImage._.imageDimensions.width * this.zoomRatio,\n        height: this._zoomImage._.imageDimensions.height * this.zoomRatio,\n      });\n    },\n\n    /**\n     * Gets previous tab element from currently-active.\n     */\n    _getPrevTab: function () {\n      const activeTabIndex = this._getActiveTabIndex();\n\n      if (activeTabIndex < 0) return;\n\n      let newTabIndex;\n\n      if (activeTabIndex > 0) {\n        newTabIndex = activeTabIndex - 1;\n      } else {\n        newTabIndex = this.$tabs.length - 1;\n      }\n\n      return this.$tabs.eq(newTabIndex);\n    },\n\n    /**\n     * Gets next tab element from currently-active.\n     */\n    _getNextTab: function () {\n      const activeTabIndex = this._getActiveTabIndex();\n\n      if (activeTabIndex < 0) return;\n\n      let newTabIndex;\n\n      if (activeTabIndex < this.$tabs.length - 1) {\n        newTabIndex = activeTabIndex + 1;\n      } else {\n        newTabIndex = 0;\n      }\n\n      return this.$tabs.eq(newTabIndex);\n    },\n\n    /**\n     * Gets active tab element\n     */\n    _getActiveTab: function () {\n      return this.$tabs.filter('[aria-selected=\"true\"]');\n    },\n\n    /**\n     * Gets index of active tab among sibling tabs\n     */\n    _getActiveTabIndex: function () {\n      const $activeTab = this._getActiveTab();\n\n      if (!$activeTab.length) return;\n\n      return $activeTab.index();\n    },\n\n    /**\n     * Set up listeners for the controls.\n     */\n    _addControlListeners: function () {\n      // Tabs\n      this.addListener(this.$tabs, 'click', this._handleTabClick);\n      this.addListener(this.$tabs, 'keydown', (event) => {\n        switch (event.keyCode) {\n          case Garnish.LEFT_KEY:\n          case Garnish.UP_KEY:\n            event.preventDefault();\n            const $prevTab = this._getPrevTab();\n            this.activateTab($prevTab);\n            break;\n          case Garnish.RIGHT_KEY:\n          case Garnish.DOWN_KEY:\n            event.preventDefault();\n            const $nextTab = this._getNextTab();\n            this.activateTab($nextTab);\n            break;\n        }\n      });\n\n      // Focal point\n      this.addListener(this.$focalPointBtn, 'click', this.toggleFocalPoint);\n\n      // Rotate controls\n      this.addListener($('.rotate-left'), 'click', function () {\n        this.rotateImage(-90);\n      });\n      this.addListener($('.rotate-right'), 'click', function () {\n        this.rotateImage(90);\n      });\n      this.addListener($('.flip-vertical'), 'click', function () {\n        this.flipImage('y');\n      });\n      this.addListener($('.flip-horizontal'), 'click', function () {\n        this.flipImage('x');\n      });\n\n      // Straighten slider\n      this.straighteningInput = new Craft.SlideRuleInput('slide-rule', {\n        onStart: () => {\n          this._showGrid();\n        },\n        onChange: (slider) => {\n          this.straighten(slider);\n        },\n        onEnd: () => {\n          this._hideGrid();\n          this._cleanupFocalPointAfterStraighten();\n        },\n      });\n\n      // Cropper scale modifier key\n      this.addListener(Garnish.$doc, 'keydown', function (ev) {\n        if (ev.keyCode === Garnish.SHIFT_KEY) {\n          this.shiftKeyHeld = true;\n        }\n      });\n      this.addListener(Garnish.$doc, 'keyup', function (ev) {\n        if (ev.keyCode === Garnish.SHIFT_KEY) {\n          this.shiftKeyHeld = false;\n        }\n      });\n\n      this.addListener(\n        this.$constraintRadioInputs,\n        'change',\n        this._handleConstraintChange\n      );\n      this.addListener(\n        $('.orientation input', this.$container),\n        'click',\n        this._handleOrientationClick\n      );\n      this.addListener(\n        $('.constraint-group .custom input', this.$container),\n        'keyup',\n        this._applyCustomConstraint\n      );\n    },\n\n    /**\n     * Handle a constraint button click.\n     *\n     * @param {Object} ev\n     */\n    _handleConstraintClick: function (ev) {\n      var constraint = $(ev.currentTarget).data('constraint');\n      var $target = $(ev.currentTarget);\n      $target.siblings().removeClass('active');\n      $target.addClass('active');\n\n      if (constraint == 'custom') {\n        this._showCustomConstraint();\n        this._applyCustomConstraint();\n        return;\n      }\n\n      this._hideCustomConstraint();\n\n      this.setCroppingConstraint(constraint);\n      this.enforceCroppingConstraint();\n    },\n\n    /**\n     * Handle a constraint change.\n     *\n     * @param {Object} ev\n     */\n    _handleConstraintChange: function (ev) {\n      const constraint = $(ev.target).val();\n\n      if (constraint == 'custom') {\n        this._showCustomConstraint();\n        this._applyCustomConstraint();\n        return;\n      }\n\n      this._hideCustomConstraint();\n\n      this.setCroppingConstraint(constraint);\n      this.enforceCroppingConstraint();\n    },\n\n    /**\n     * Handle an orientation switch click.\n     *\n     * @param {Object} ev\n     */\n    _handleOrientationClick: function (ev) {\n      if (ev.currentTarget.value === this.constraintOrientation) {\n        return;\n      }\n      this.constraintOrientation = ev.currentTarget.value;\n\n      const $constraints = $('.flip', this.$constraintContainer);\n\n      for (var i = 0; i < $constraints.length; i++) {\n        var $constraint = $($constraints[i]);\n        const labelSelector = 'label[for=\"' + $constraint.attr('id') + '\"]';\n        const $label = $(labelSelector, this.$constraintContainer);\n        $constraint.val(1 / $constraint.val());\n        $label.html(\n          $label.text().split(':').reverse().join(':').replace(/\\s/g, '')\n        );\n      }\n\n      $constraints.filter(':checked').trigger('change');\n    },\n\n    /**\n     * Apply the custom ratio set in the inputs\n     */\n    _applyCustomConstraint: function () {\n      var constraint = this._getCustomConstraint();\n\n      if (constraint.w > 0 && constraint.h > 0) {\n        this.setCroppingConstraint(constraint.w / constraint.h);\n        this.enforceCroppingConstraint();\n      }\n    },\n\n    /**\n     * Get the custom constraint.\n     *\n     * @returns {{w: *, h: *}}\n     */\n    _getCustomConstraint: function () {\n      var w = parseFloat($('.custom-constraint-w').val());\n      var h = parseFloat($('.custom-constraint-h').val());\n      return {\n        w: isNaN(w) ? 0 : w,\n        h: isNaN(h) ? 0 : h,\n      };\n    },\n\n    /**\n     * Set the custom constraint.\n     *\n     * @param {number} w\n     * @param {number} h\n     */\n    _setCustomConstraint: function (w, h) {\n      $('.custom-constraint-w').val(parseFloat(w));\n      $('.custom-constraint-h').val(parseFloat(h));\n    },\n\n    /**\n     * Hide the custom constraint inputs.\n     */\n    _hideCustomConstraint: function () {\n      this.showingCustomConstraint = false;\n      this.$customConstraints.addClass('hidden');\n      $('.orientation', this.$container).removeClass('hidden');\n    },\n\n    /**\n     * Show the custom constraint inputs.\n     */\n    _showCustomConstraint: function () {\n      if (this.showingCustomConstraint) {\n        return;\n      }\n\n      this.showingCustomConstraint = true;\n      this.$customConstraints.removeClass('hidden');\n      $('.orientation', this.$container).addClass('hidden');\n    },\n\n    /**\n     * Handle tab click.\n     *\n     * @param {Object} ev\n     */\n    _handleTabClick: function (ev) {\n      if (!this.animationInProgress) {\n        var $tab = $(ev.currentTarget);\n        this.activateTab($tab);\n      }\n    },\n\n    /**\n     * Activate a tab.\n     *\n     * @param {(jQuery|HTMLElement|string)} tab\n     */\n\n    activateTab: function (tab) {\n      const view = $(tab).data('view');\n      this.$tabs.removeClass('selected').attr({\n        'aria-selected': 'false',\n        tabindex: '-1',\n      });\n      $(tab)\n        .addClass('selected')\n        .attr({\n          'aria-selected': 'true',\n          tabindex: '0',\n        })\n        .trigger('focus');\n      this.showView(view);\n    },\n\n    /**\n     * Show a view.\n     *\n     * @param {string} view\n     */\n    showView: function (view) {\n      if (this.currentView === view) {\n        return;\n      }\n\n      this.$views.addClass('hidden');\n      var $view = this.$views.filter('[data-view=\"' + view + '\"]');\n      $view.removeClass('hidden');\n\n      if (view === 'rotate') {\n        this.enableSlider();\n      } else {\n        this.disableSlider();\n      }\n\n      // Now that most likely our editor dimensions have changed, time to reposition stuff\n      this.updateSizeAndPosition();\n\n      // See if we have to enable or disable crop mode as we transition between tabs\n      if (this.currentView === 'crop' && view !== 'crop') {\n        this._queue.push(\n          () =>\n            new Promise((resolve, reject) => {\n              this.disableCropMode();\n              resolve();\n            })\n        );\n      } else if (this.currentView !== 'crop' && view === 'crop') {\n        this._queue.push(\n          () =>\n            new Promise((resolve, reject) => {\n              this.enableCropMode();\n              resolve();\n            })\n        );\n      }\n\n      // Mark the current view\n      this.currentView = view;\n    },\n\n    /**\n     * Store the current cropper state.\n     *\n     * Cropper state is always assumed to be saved at a zoom ratio of 1 to be used\n     * as the basis for recalculating the cropper position and dimensions.\n     *\n     * @param {Object} [state]\n     */\n    storeCropperState: function (state) {\n      if (typeof this.storeCropperState._ === 'undefined') {\n        this.storeCropperState._ = {};\n      }\n\n      // If we're asked to store a specific state.\n      if (state) {\n        this.cropperState = state;\n      } else if (this.clipper) {\n        this.storeCropperState._.zoomFactor = 1 / this.zoomRatio;\n\n        this.cropperState = {\n          offsetX:\n            (this.clipper.left - this.image.left) *\n            this.storeCropperState._.zoomFactor,\n          offsetY:\n            (this.clipper.top - this.image.top) *\n            this.storeCropperState._.zoomFactor,\n          height: this.clipper.height * this.storeCropperState._.zoomFactor,\n          width: this.clipper.width * this.storeCropperState._.zoomFactor,\n          imageDimensions: this.getScaledImageDimensions(),\n        };\n      } else {\n        this.storeCropperState._.dimensions = this.getScaledImageDimensions();\n        this.cropperState = {\n          offsetX: 0,\n          offsetY: 0,\n          height: this.storeCropperState._.dimensions.height,\n          width: this.storeCropperState._.dimensions.width,\n          imageDimensions: this.storeCropperState._.dimensions,\n        };\n      }\n    },\n\n    /**\n     * Store focal point coordinates in a manner that is not tied to zoom ratio and rotation.\n     */\n    storeFocalPointState: function (state) {\n      if (typeof this.storeFocalPointState._ === 'undefined') {\n        this.storeFocalPointState._ = {};\n      }\n\n      // If we're asked to store a specific state.\n      if (state) {\n        this.focalPointState = state;\n      } else if (this.focalPoint) {\n        this.storeFocalPointState._.zoomFactor = 1 / this.zoomRatio;\n        this.focalPointState = {\n          offsetX:\n            ((this.focalPoint.left - this.image.left) *\n              this.storeFocalPointState._.zoomFactor) /\n            this.scaleFactor,\n          offsetY:\n            ((this.focalPoint.top - this.image.top) *\n              this.storeFocalPointState._.zoomFactor) /\n            this.scaleFactor,\n          imageDimensions: this.getScaledImageDimensions(),\n        };\n      }\n    },\n\n    /**\n     * Rotate the image along with the viewport.\n     *\n     * @param {number} degrees\n     */\n    rotateImage: function (degrees) {\n      if (!this.animationInProgress) {\n        // We're not that kind of an establishment, sir.\n        if (degrees !== 90 && degrees !== -90) {\n          return false;\n        }\n\n        this.animationInProgress = true;\n        this.viewportRotation += degrees;\n\n        // Normalize the viewport rotation angle so it's between 0 and 359\n        this.viewportRotation = parseInt(\n          (this.viewportRotation + 360) % 360,\n          10\n        );\n\n        var newAngle = this.image.angle + degrees;\n        var scaledImageDimensions = this.getScaledImageDimensions();\n        var imageZoomRatio;\n\n        if (this.hasOrientationChanged()) {\n          imageZoomRatio = this.getZoomToCoverRatio({\n            height: scaledImageDimensions.width,\n            width: scaledImageDimensions.height,\n          });\n        } else {\n          imageZoomRatio = this.getZoomToCoverRatio(scaledImageDimensions);\n        }\n\n        // In cases when for some reason we've already zoomed in on the image,\n        // use existing zoom.\n        if (this.zoomRatio > imageZoomRatio) {\n          imageZoomRatio = this.zoomRatio;\n        }\n\n        var viewportProperties = {\n          angle: degrees === 90 ? '+=90' : '-=90',\n        };\n\n        var imageProperties = {\n          angle: newAngle,\n          width: scaledImageDimensions.width * imageZoomRatio,\n          height: scaledImageDimensions.height * imageZoomRatio,\n        };\n\n        var scaleFactor = 1;\n        if (this.scaleFactor < 1) {\n          scaleFactor = 1 / this.scaleFactor;\n          this.scaleFactor = 1;\n        } else {\n          if (this.viewport.width > this.editorHeight) {\n            scaleFactor = this.editorHeight / this.viewport.width;\n          } else if (this.viewport.height > this.editorWidth) {\n            scaleFactor = this.editorWidth / this.viewport.height;\n          }\n          this.scaleFactor = scaleFactor;\n        }\n\n        if (scaleFactor < 1) {\n          imageProperties.width *= scaleFactor;\n          imageProperties.height *= scaleFactor;\n        }\n\n        var state = this.cropperState;\n\n        // Make sure we reposition the image as well to focus on the same image area\n        var deltaX = state.offsetX;\n        var deltaY = state.offsetY;\n        var angleInRadians = degrees * (Math.PI / 180);\n\n        // Calculate how the cropper would need to move in a circle to maintain\n        // the focus on the same region if the image was rotated with zoom intact.\n        var newDeltaX =\n          deltaX * Math.cos(angleInRadians) - deltaY * Math.sin(angleInRadians);\n        var newDeltaY =\n          deltaX * Math.sin(angleInRadians) + deltaY * Math.cos(angleInRadians);\n\n        var sizeFactor =\n          scaledImageDimensions.width / state.imageDimensions.width;\n\n        var modifiedDeltaX =\n          newDeltaX * sizeFactor * this.zoomRatio * this.scaleFactor;\n        var modifiedDeltaY =\n          newDeltaY * sizeFactor * this.zoomRatio * this.scaleFactor;\n\n        imageProperties.left = this.editorWidth / 2 - modifiedDeltaX;\n        imageProperties.top = this.editorHeight / 2 - modifiedDeltaY;\n\n        state.offsetX = newDeltaX;\n        state.offsetY = newDeltaY;\n\n        var temp = state.width;\n        state.width = state.height;\n        state.height = temp;\n\n        this.storeCropperState(state);\n\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n        }\n\n        this.viewport.animate(viewportProperties, {\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            // If we're zooming the image in or out, better do the same to viewport\n            var temp = this.viewport.height * scaleFactor;\n            this.viewport.height = this.viewport.width * scaleFactor;\n            this.viewport.width = temp;\n            this.viewport.set({angle: 0});\n          },\n        });\n\n        // Animate the rotation and dimension change\n        this.image.animate(imageProperties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            var cleanAngle = parseFloat((this.image.angle + 360) % 360);\n            this.image.set({angle: cleanAngle});\n            this.animationInProgress = false;\n            if (this.focalPoint) {\n              this._adjustFocalPointByAngle(degrees);\n              this.straighten(this.straighteningInput);\n              this.canvas.add(this.focalPoint);\n            } else {\n              this._resetFocalPointPosition();\n            }\n          },\n        });\n      }\n    },\n\n    /**\n     * Flip an image along an axis.\n     *\n     * @param {string} axis\n     */\n    flipImage: function (axis) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        if (this.hasOrientationChanged()) {\n          axis = axis === 'y' ? 'x' : 'y';\n        }\n\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n        } else {\n          this._resetFocalPointPosition();\n        }\n\n        var editorCenter = {x: this.editorWidth / 2, y: this.editorHeight / 2};\n        this.straighteningInput.setValue(-this.imageStraightenAngle);\n        this.imageStraightenAngle = -this.imageStraightenAngle;\n        var properties = {\n          angle: this.viewportRotation + this.imageStraightenAngle,\n        };\n\n        var deltaY, deltaX;\n        var cropperState = this.cropperState;\n        var focalPointState = this.focalPointState;\n\n        // Reposition the image, viewport, and stored cropper and focal point states.\n        if (\n          (axis === 'y' && this.hasOrientationChanged()) ||\n          (axis !== 'y' && !this.hasOrientationChanged())\n        ) {\n          cropperState.offsetX = -cropperState.offsetX;\n          focalPointState.offsetX = -focalPointState.offsetX;\n          deltaX = this.image.left - editorCenter.x;\n          properties.left = editorCenter.x - deltaX;\n        } else {\n          cropperState.offsetY = -cropperState.offsetY;\n          focalPointState.offsetY = -focalPointState.offsetY;\n          deltaY = this.image.top - editorCenter.y;\n          properties.top = editorCenter.y - deltaY;\n        }\n\n        if (axis === 'y') {\n          properties.scaleY = this.image.scaleY * -1;\n          this.flipData.y = 1 - this.flipData.y;\n        } else {\n          properties.scaleX = this.image.scaleX * -1;\n          this.flipData.x = 1 - this.flipData.x;\n        }\n\n        this.storeCropperState(cropperState);\n        this.storeFocalPointState(focalPointState);\n\n        this.image.animate(properties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            this.animationInProgress = false;\n            if (this.focalPoint) {\n              // Well this is handy\n              this._adjustFocalPointByAngle(0);\n              this.canvas.add(this.focalPoint);\n            }\n          },\n        });\n      }\n    },\n\n    /**\n     * Perform the straightening with input slider.\n     *\n     * @param {Craft.SlideRuleInput} slider\n     */\n    straighten: function (slider) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        var previousAngle = this.image.angle;\n\n        this.imageStraightenAngle =\n          (this.settings.allowDegreeFractions\n            ? parseFloat(slider.value)\n            : Math.round(parseFloat(slider.value))) % 360;\n\n        // Straighten the image\n        this.image.set({\n          angle: this.viewportRotation + this.imageStraightenAngle,\n        });\n\n        // Set the new zoom ratio\n        this.zoomRatio =\n          this.getZoomToCoverRatio(this.getScaledImageDimensions()) *\n          this.scaleFactor;\n        this._zoomImage();\n\n        if (this.cropperState) {\n          this._adjustEditorElementsOnStraighten(previousAngle);\n        }\n\n        this.renderImage();\n\n        this.animationInProgress = false;\n      }\n    },\n\n    /**\n     * Adjust the cropped viewport when straightening the image to correct for\n     * bumping into edges, keeping focus on the cropped area center and to\n     * maintain the illusion that the image is being straightened relative to the viewport center.\n     *\n     * @param {integer} previousAngle integer the previous image angle before straightening\n     */\n    _adjustEditorElementsOnStraighten: function (previousAngle) {\n      var scaledImageDimensions = this.getScaledImageDimensions();\n      var angleDelta = this.image.angle - previousAngle;\n      var state = this.cropperState;\n\n      var currentZoomRatio = this.zoomRatio;\n      var adjustmentRatio = 1;\n\n      var deltaX, deltaY, newCenterX, newCenterY, sizeFactor;\n\n      do {\n        // Get the cropper center coordinates\n        var cropperCenterX = state.offsetX;\n        var cropperCenterY = state.offsetY;\n        var angleInRadians = angleDelta * (Math.PI / 180);\n\n        // Calculate how the cropper would need to move in a circle to maintain\n        // the focus on the same region if the image was rotated with zoom intact.\n        newCenterX =\n          cropperCenterX * Math.cos(angleInRadians) -\n          cropperCenterY * Math.sin(angleInRadians);\n        newCenterY =\n          cropperCenterX * Math.sin(angleInRadians) +\n          cropperCenterY * Math.cos(angleInRadians);\n\n        sizeFactor = scaledImageDimensions.width / state.imageDimensions.width;\n\n        // Figure out the final image offset to keep the viewport focused where we need it\n        deltaX = newCenterX * currentZoomRatio * sizeFactor;\n        deltaY = newCenterY * currentZoomRatio * sizeFactor;\n\n        // If the image would creep in the viewport, figure out how to math around it.\n        var imageVertices = this.getImageVerticeCoords(currentZoomRatio);\n        var rectangle = {\n          width: this.viewport.width,\n          height: this.viewport.height,\n          left: this.editorWidth / 2 - this.viewport.width / 2 + deltaX,\n          top: this.editorHeight / 2 - this.viewport.height / 2 + deltaY,\n        };\n        adjustmentRatio = this._getZoomRatioToFitRectangle(\n          rectangle,\n          imageVertices\n        );\n        currentZoomRatio = currentZoomRatio * adjustmentRatio;\n\n        // If we had to make adjustments, do the calculations again\n      } while (adjustmentRatio !== 1);\n\n      // Reposition the image correctly\n      this.image.set({\n        left: this.editorWidth / 2 - deltaX,\n        top: this.editorHeight / 2 - deltaY,\n      });\n\n      // Finally, store the new cropper state to reflect the rotation change.\n      state.offsetX = newCenterX;\n      state.offsetY = newCenterY;\n      state.width = this.viewport.width / currentZoomRatio / sizeFactor;\n      state.height = this.viewport.height / currentZoomRatio / sizeFactor;\n\n      this.storeCropperState(state);\n\n      // Zoom the image in and we're done.\n      this.zoomRatio = currentZoomRatio;\n\n      if (this.focalPoint) {\n        this._adjustFocalPointByAngle(angleDelta);\n\n        if (!this._isCenterInside(this.focalPoint, this.viewport)) {\n          this.focalPoint.set({opacity: 0});\n        } else {\n          this.focalPoint.set({opacity: 1});\n        }\n      } else if (angleDelta !== 0) {\n        this._resetFocalPointPosition();\n      }\n\n      this._zoomImage();\n    },\n\n    /**\n     * If focal point is active and outside of viewport after straightening, reset it.\n     */\n    _cleanupFocalPointAfterStraighten: function () {\n      if (\n        this.focalPoint &&\n        !this._isCenterInside(this.focalPoint, this.viewport)\n      ) {\n        this.focalPoint.set({opacity: 1});\n        var state = this.focalPointState;\n        state.offsetX = 0;\n        state.offsetY = 0;\n        this.storeFocalPointState(state);\n        this.toggleFocalPoint();\n      }\n    },\n\n    /**\n     * Reset focal point to the middle of image.\n     */\n    _resetFocalPointPosition: function () {\n      var state = this.focalPointState;\n      state.offsetX = 0;\n      state.offsetY = 0;\n      this.storeFocalPointState(state);\n    },\n\n    /**\n     * Returns true if a center of an object is inside another rectangle shaped object that is not rotated.\n     *\n     * @param {Object} object\n     * @param {Object} containingObject\n     * @returns {boolean}\n     */\n    _isCenterInside: function (object, containingObject) {\n      return (\n        object.left > containingObject.left - containingObject.width / 2 &&\n        object.top > containingObject.top - containingObject.height / 2 &&\n        object.left < containingObject.left + containingObject.width / 2 &&\n        object.top < containingObject.top + containingObject.height / 2\n      );\n    },\n\n    /**\n     * Adjust the focal point by an angle in degrees.\n     * @param {number} angle\n     */\n    _adjustFocalPointByAngle: function (angle) {\n      var angleInRadians = angle * (Math.PI / 180);\n      var state = this.focalPointState;\n\n      var focalX = state.offsetX;\n      var focalY = state.offsetY;\n\n      // Calculate how the focal point would need to move in a circle to keep on the same spot\n      // on the image if it was rotated with zoom intact.\n      var newFocalX =\n        focalX * Math.cos(angleInRadians) - focalY * Math.sin(angleInRadians);\n      var newFocalY =\n        focalX * Math.sin(angleInRadians) + focalY * Math.cos(angleInRadians);\n      var sizeFactor =\n        this.getScaledImageDimensions().width / state.imageDimensions.width;\n\n      var adjustedFocalX = newFocalX * sizeFactor * this.zoomRatio;\n      var adjustedFocalY = newFocalY * sizeFactor * this.zoomRatio;\n\n      this.focalPoint.left = this.image.left + adjustedFocalX;\n      this.focalPoint.top = this.image.top + adjustedFocalY;\n\n      state.offsetX = newFocalX;\n      state.offsetY = newFocalY;\n      this.storeFocalPointState(state);\n    },\n\n    /**\n     * Get the zoom ratio required to fit a rectangle within another rectangle, that is defined by vertices.\n     * If the rectangle fits, 1 will be returned.\n     *\n     * @param {Object} rectangle\n     * @param {Object} containingVertices\n     */\n    _getZoomRatioToFitRectangle: function (rectangle, containingVertices) {\n      var rectangleVertices = this._getRectangleVertices(rectangle);\n      var vertex;\n\n      // Check if any of the viewport vertices end up out of bounds\n      for (\n        var verticeIndex = 0;\n        verticeIndex < rectangleVertices.length;\n        verticeIndex++\n      ) {\n        vertex = rectangleVertices[verticeIndex];\n\n        if (!this.arePointsInsideRectangle([vertex], containingVertices)) {\n          break;\n        }\n\n        vertex = false;\n      }\n\n      // If there's no vertex set after loop, it means that all of them are inside the image rectangle\n      var adjustmentRatio;\n\n      if (!vertex) {\n        adjustmentRatio = 1;\n      } else {\n        // Find out which edge got crossed by the vertex\n        var edge = this._getEdgeCrossed(containingVertices, vertex);\n\n        var rectangleCenter = {\n          x: rectangle.left + rectangle.width / 2,\n          y: rectangle.top + rectangle.height / 2,\n        };\n\n        // Calculate how much further that edge needs to be.\n        // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points\n        var distanceFromVertexToEdge =\n          Math.abs(\n            (edge[1].y - edge[0].y) * vertex.x -\n              (edge[1].x - edge[0].x) * vertex.y +\n              edge[1].x * edge[0].y -\n              edge[1].y * edge[0].x\n          ) /\n          Math.sqrt(\n            Math.pow(edge[1].y - edge[0].y, 2) +\n              Math.pow(edge[1].x - edge[0].x, 2)\n          );\n        var distanceFromCenterToEdge =\n          Math.abs(\n            (edge[1].y - edge[0].y) * rectangleCenter.x -\n              (edge[1].x - edge[0].x) * rectangleCenter.y +\n              edge[1].x * edge[0].y -\n              edge[1].y * edge[0].x\n          ) /\n          Math.sqrt(\n            Math.pow(edge[1].y - edge[0].y, 2) +\n              Math.pow(edge[1].x - edge[0].x, 2)\n          );\n\n        // Adjust the zoom ratio\n        adjustmentRatio =\n          (distanceFromVertexToEdge + distanceFromCenterToEdge) /\n          distanceFromCenterToEdge;\n      }\n\n      return adjustmentRatio;\n    },\n\n    /**\n     * Save the image.\n     *\n     * @param {Object} ev\n     */\n    saveImage: function (ev) {\n      var $button = $(ev.currentTarget);\n      if (this.saving) {\n        return false;\n      }\n\n      this.saving = true;\n      $button.addClass('loading');\n      const replace = $button.hasClass('replace');\n\n      var postData = {\n        assetId: this.assetId,\n        viewportRotation: this.viewportRotation,\n        imageRotation: this.imageStraightenAngle,\n        replace: replace ? 1 : 0,\n      };\n\n      if (this.cropperState) {\n        var cropData = {};\n\n        cropData.height = this.cropperState.height;\n        cropData.width = this.cropperState.width;\n        cropData.offsetX = this.cropperState.offsetX;\n        cropData.offsetY = this.cropperState.offsetY;\n\n        postData.imageDimensions = this.cropperState.imageDimensions;\n\n        postData.cropData = cropData;\n      } else {\n        postData.imageDimensions = this.getScaledImageDimensions();\n      }\n\n      if (this.focalPoint) {\n        postData.focalPoint = this.focalPointState;\n      }\n\n      postData.flipData = this.flipData;\n      postData.zoom = this.zoomRatio;\n\n      Craft.sendActionRequest('POST', 'assets/save-image', {data: postData})\n        .then(({data}) => {\n          this.onSave(data);\n          if (replace && Craft.broadcaster) {\n            Craft.broadcaster.postMessage({\n              event: 'saveElement',\n              id: this.assetId,\n            });\n          }\n          this.hide();\n          Craft.cp.runQueue();\n\n          // Refresh Live Preview\n          Craft.Preview.refresh();\n        })\n        .catch(({response}) => {\n          Craft.cp.displayError(response.data.message);\n        })\n        .finally(() => {\n          this.$buttons.find('.btn').removeClass('loading');\n          this.saving = false;\n        });\n    },\n\n    /**\n     * Return image zoom ratio depending on the straighten angle to cover a viewport by given dimensions.\n     *\n     * @param {Object} dimensions\n     */\n    getZoomToCoverRatio: function (dimensions) {\n      // Convert the angle to radians\n      var angleInRadians =\n        Math.abs(this.imageStraightenAngle) * (Math.PI / 180);\n\n      // Calculate the dimensions of the scaled image using the magic of math\n      var scaledWidth =\n        Math.sin(angleInRadians) * dimensions.height +\n        Math.cos(angleInRadians) * dimensions.width;\n      var scaledHeight =\n        Math.sin(angleInRadians) * dimensions.width +\n        Math.cos(angleInRadians) * dimensions.height;\n\n      // Calculate the ratio\n      return Math.max(\n        scaledWidth / dimensions.width,\n        scaledHeight / dimensions.height\n      );\n    },\n\n    /**\n     * Return image zoom ratio depending on the straighten angle to fit inside a viewport by given dimensions.\n     *\n     * @param {Object} dimensions\n     */\n    getZoomToFitRatio: function (dimensions) {\n      // Get the bounding box for a rotated image\n      var boundingBox = this._getImageBoundingBox(dimensions);\n\n      // Scale the bounding box to fit\n      var scale = 1;\n      if (\n        boundingBox.height > this.editorHeight ||\n        boundingBox.width > this.editorWidth\n      ) {\n        var vertScale = this.editorHeight / boundingBox.height;\n        var horiScale = this.editorWidth / boundingBox.width;\n        scale = Math.min(horiScale, vertScale);\n      }\n\n      return scale;\n    },\n\n    /**\n     * Return the combined zoom ratio to fit a rectangle inside image that's been zoomed to fit.\n     */\n    getCombinedZoomRatio: function (dimensions) {\n      return (\n        this.getZoomToCoverRatio(dimensions) /\n        this.getZoomToFitRatio(dimensions)\n      );\n    },\n\n    /**\n     * Draw the grid.\n     *\n     * @private\n     */\n    _showGrid: function () {\n      if (!this.grid) {\n        var strokeOptions = {\n          strokeWidth: 1,\n          stroke: 'rgba(255,255,255,0.5)',\n        };\n\n        var lineCount = 8;\n        var gridWidth = this.viewport.width;\n        var gridHeight = this.viewport.height;\n        var xStep = gridWidth / (lineCount + 1);\n        var yStep = gridHeight / (lineCount + 1);\n\n        var grid = [\n          new fabric.Rect({\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,1)',\n            originX: 'center',\n            originY: 'center',\n            width: gridWidth,\n            height: gridHeight,\n            left: gridWidth / 2,\n            top: gridHeight / 2,\n            fill: 'rgba(255,255,255,0)',\n          }),\n        ];\n\n        var i;\n        for (i = 1; i <= lineCount; i++) {\n          grid.push(\n            new fabric.Line(\n              [i * xStep, 0, i * xStep, gridHeight],\n              strokeOptions\n            )\n          );\n        }\n        for (i = 1; i <= lineCount; i++) {\n          grid.push(\n            new fabric.Line([0, i * yStep, gridWidth, i * yStep], strokeOptions)\n          );\n        }\n\n        this.grid = new fabric.Group(grid, {\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n          originX: 'center',\n          originY: 'center',\n          angle: this.viewport.angle,\n        });\n\n        this.canvas.add(this.grid);\n        this.renderImage();\n      }\n    },\n\n    /**\n     * Hide the grid\n     */\n    _hideGrid: function () {\n      this.canvas.remove(this.grid);\n      this.grid = null;\n      this.renderImage();\n    },\n\n    /**\n     * Remove all the events when hiding the editor.\n     */\n    onFadeOut: function () {\n      this.destroy();\n    },\n\n    /**\n     * Make sure underlying content is not scrolled by accident.\n     */\n    show: function () {\n      this.base();\n      Garnish.$bod.addClass('no-scroll');\n    },\n\n    /**\n     * Allow the content to scroll.\n     */\n    hide: function () {\n      this.removeAllListeners();\n      this.straighteningInput.removeAllListeners();\n      Garnish.$bod.removeClass('no-scroll');\n      this.base();\n    },\n\n    /**\n     * onSave callback.\n     */\n    onSave: function (data) {\n      this.settings.onSave(data);\n      this.trigger('save');\n    },\n\n    /**\n     * Enable the rotation slider.\n     */\n    enableSlider: function () {\n      this.$imageTools.removeClass('hidden');\n    },\n\n    /**\n     * Disable the rotation slider.\n     */\n    disableSlider: function () {\n      this.$imageTools.addClass('hidden');\n    },\n\n    /**\n     * Switch to crop mode.\n     */\n    enableCropMode: function () {\n      var imageDimensions = this.getScaledImageDimensions();\n      this.zoomRatio = this.getZoomToFitRatio(imageDimensions);\n\n      var viewportProperties = {\n        width: this.editorWidth,\n        height: this.editorHeight,\n      };\n\n      var imageProperties = {\n        width: imageDimensions.width * this.zoomRatio,\n        height: imageDimensions.height * this.zoomRatio,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      };\n\n      var callback = () => {\n        this._setFittedImageVerticeCoordinates();\n\n        // Restore cropper\n        var state = this.cropperState;\n        var scaledImageDimensions = this.getScaledImageDimensions();\n        var sizeFactor =\n          scaledImageDimensions.width / state.imageDimensions.width;\n\n        // Restore based on the stored information\n        var cropperData = {\n          left: this.image.left + state.offsetX * sizeFactor * this.zoomRatio,\n          top: this.image.top + state.offsetY * sizeFactor * this.zoomRatio,\n          width: state.width * sizeFactor * this.zoomRatio,\n          height: state.height * sizeFactor * this.zoomRatio,\n        };\n\n        this._showCropper(cropperData);\n\n        if (this.focalPoint) {\n          sizeFactor =\n            scaledImageDimensions.width /\n            this.focalPointState.imageDimensions.width;\n          this.focalPoint.left =\n            this.image.left +\n            this.focalPointState.offsetX * sizeFactor * this.zoomRatio;\n          this.focalPoint.top =\n            this.image.top +\n            this.focalPointState.offsetY * sizeFactor * this.zoomRatio;\n          this.canvas.add(this.focalPoint);\n        }\n      };\n\n      this._editorModeTransition(callback, imageProperties, viewportProperties);\n    },\n\n    /**\n     * Switch out of crop mode.\n     */\n    disableCropMode: function () {\n      var viewportProperties = {};\n\n      this._hideCropper();\n      var imageDimensions = this.getScaledImageDimensions();\n      var targetZoom =\n        this.getZoomToCoverRatio(imageDimensions) * this.scaleFactor;\n      var inverseZoomFactor = targetZoom / this.zoomRatio;\n      this.zoomRatio = targetZoom;\n\n      var imageProperties = {\n        width: imageDimensions.width * this.zoomRatio,\n        height: imageDimensions.height * this.zoomRatio,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      };\n\n      var offsetX = this.clipper.left - this.image.left;\n      var offsetY = this.clipper.top - this.image.top;\n\n      var imageOffsetX = offsetX * inverseZoomFactor;\n      var imageOffsetY = offsetY * inverseZoomFactor;\n      imageProperties.left = this.editorWidth / 2 - imageOffsetX;\n      imageProperties.top = this.editorHeight / 2 - imageOffsetY;\n\n      // Calculate the cropper dimensions after all the zooming\n      viewportProperties.height = this.clipper.height * inverseZoomFactor;\n      viewportProperties.width = this.clipper.width * inverseZoomFactor;\n\n      if (\n        !this.focalPoint ||\n        (this.focalPoint &&\n          !this._isCenterInside(this.focalPoint, this.clipper))\n      ) {\n        if (this.focalPoint) {\n          this.toggleFocalPoint();\n        }\n\n        this._resetFocalPointPosition();\n      }\n\n      var callback = () => {\n        // Reposition focal point correctly\n        if (this.focalPoint) {\n          var sizeFactor =\n            this.getScaledImageDimensions().width /\n            this.focalPointState.imageDimensions.width;\n          this.focalPoint.left =\n            this.image.left +\n            this.focalPointState.offsetX * sizeFactor * this.zoomRatio;\n          this.focalPoint.top =\n            this.image.top +\n            this.focalPointState.offsetY * sizeFactor * this.zoomRatio;\n          this.canvas.add(this.focalPoint);\n        }\n      };\n\n      this._editorModeTransition(callback, imageProperties, viewportProperties);\n    },\n\n    /**\n     * @callback editorModeTransitionCallback\n     */\n    /**\n     * Transition between cropping end editor modes\n     *\n     * @param {editorModeTransitionCallback}\n     * @param {Object} imageProperties\n     * @param {Object} viewportProperties\n     * @private\n     */\n    _editorModeTransition: function (\n      callback,\n      imageProperties,\n      viewportProperties\n    ) {\n      this._queue.pause();\n\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        // Without this it looks semi-broken during animation\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n          this.renderImage();\n        }\n\n        this.image.animate(imageProperties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            callback();\n            this.animationInProgress = false;\n            this.renderImage();\n            this._queue.resume();\n          },\n        });\n\n        this.viewport.animate(viewportProperties, {\n          duration: this.settings.animationDuration,\n        });\n      }\n    },\n\n    _showSpinner: function () {\n      if (!this.$spinner) {\n        this.$spinner = $('<div class=\"spinner big spinner-absolute\"/>');\n      }\n      this.$spinner.appendTo(this.$container.find('.image'));\n    },\n\n    _hideSpinner: function () {\n      this.$spinner.remove();\n    },\n\n    /**\n     * Show the cropper.\n     *\n     * @param {Object} clipperData\n     */\n    _showCropper: function (clipperData) {\n      this._setupCropperLayer(clipperData);\n      this._redrawCropperElements();\n      this.renderCropper();\n    },\n\n    /**\n     * Hide the cropper.\n     */\n    _hideCropper: function () {\n      if (this.clipper) {\n        this.croppingCanvas.remove(this.clipper);\n        this.croppingCanvas.remove(this.croppingShade);\n        this.croppingCanvas.remove(this.cropperHandles);\n        this.croppingCanvas.remove(this.cropperGrid);\n        this.croppingCanvas.remove(this.croppingRectangle);\n\n        this.croppingCanvas = null;\n        this.renderCropper = null;\n      }\n    },\n\n    /**\n     * Draw the cropper.\n     *\n     * @param {Object} clipperData\n     */\n    _setupCropperLayer: function (clipperData) {\n      // Set up the canvas for cropper\n      this.croppingCanvas = new fabric.StaticCanvas('cropping-canvas', {\n        backgroundColor: 'rgba(0,0,0,0)',\n        hoverCursor: 'default',\n        selection: false,\n      });\n\n      this.croppingCanvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      this.renderCropper = () =>\n        Garnish.requestAnimationFrame(\n          this.croppingCanvas.renderAll.bind(this.croppingCanvas)\n        );\n\n      $('#cropping-canvas', this.$editorContainer).css({\n        position: 'absolute',\n        top: 0,\n        left: 0,\n      });\n\n      this.croppingShade = new fabric.Rect({\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n        originX: 'center',\n        originY: 'center',\n        width: this.editorWidth,\n        height: this.editorHeight,\n        fill: 'rgba(0,0,0,0.7)',\n      });\n\n      // Calculate the cropping rectangle size\n      var imageDimensions = this.getScaledImageDimensions();\n      var rectangleRatio =\n        this.imageStraightenAngle === 0\n          ? 1\n          : this.getCombinedZoomRatio(imageDimensions) * 1.2;\n      var rectWidth = imageDimensions.width / rectangleRatio;\n      var rectHeight = imageDimensions.height / rectangleRatio;\n\n      if (this.hasOrientationChanged()) {\n        var temp = rectHeight;\n        rectHeight = rectWidth;\n        rectWidth = temp;\n      }\n\n      // Set up the cropping viewport rectangle\n      this.clipper = new fabric.Rect({\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n        originX: 'center',\n        originY: 'center',\n        width: rectWidth,\n        height: rectHeight,\n        stroke: 'black',\n        fill: 'rgba(128,0,0,1)',\n        strokeWidth: 0,\n      });\n\n      // Set from clipper data\n      if (clipperData) {\n        this.clipper.set(clipperData);\n      }\n\n      this.clipper.globalCompositeOperation = 'destination-out';\n      this.croppingCanvas.add(this.croppingShade);\n      this.croppingCanvas.add(this.clipper);\n    },\n\n    /**\n     * Redraw the cropper boundaries\n     */\n    _redrawCropperElements: function () {\n      if (typeof this._redrawCropperElements._ === 'undefined') {\n        this._redrawCropperElements._ = {};\n      }\n\n      if (this.cropperHandles) {\n        this.croppingCanvas.remove(this.cropperHandles);\n        this.croppingCanvas.remove(this.cropperGrid);\n        this.croppingCanvas.remove(this.croppingRectangle);\n      }\n      this._redrawCropperElements._.lineOptions = {\n        strokeWidth: 4,\n        stroke: 'rgb(255,255,255)',\n        fill: false,\n      };\n\n      this._redrawCropperElements._.gridOptions = {\n        strokeWidth: 2,\n        stroke: 'rgba(255,255,255,0.5)',\n      };\n\n      // Draw the handles\n      this._redrawCropperElements._.pathGroup = [\n        new fabric.Path(\n          'M 0,10 L 0,0 L 10,0',\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M ' +\n            (this.clipper.width - 8) +\n            ',0 L ' +\n            (this.clipper.width + 4) +\n            ',0 L ' +\n            (this.clipper.width + 4) +\n            ',10',\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M ' +\n            (this.clipper.width + 4) +\n            ',' +\n            (this.clipper.height - 8) +\n            ' L' +\n            (this.clipper.width + 4) +\n            ',' +\n            (this.clipper.height + 4) +\n            ' L ' +\n            (this.clipper.width - 8) +\n            ',' +\n            (this.clipper.height + 4),\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M 10,' +\n            (this.clipper.height + 4) +\n            ' L 0,' +\n            (this.clipper.height + 4) +\n            ' L 0,' +\n            (this.clipper.height - 8),\n          this._redrawCropperElements._.lineOptions\n        ),\n      ];\n\n      this.cropperHandles = new fabric.Group(\n        this._redrawCropperElements._.pathGroup,\n        {\n          left: this.clipper.left,\n          top: this.clipper.top,\n          originX: 'center',\n          originY: 'center',\n        }\n      );\n\n      // Don't forget the rectangle\n      this.croppingRectangle = new fabric.Rect({\n        left: this.clipper.left,\n        top: this.clipper.top,\n        width: this.clipper.width,\n        height: this.clipper.height,\n        fill: 'rgba(0,0,0,0)',\n        stroke: 'rgba(255,255,255,0.8)',\n        strokeWidth: 2,\n        originX: 'center',\n        originY: 'center',\n      });\n\n      this.cropperGrid = new fabric.Group(\n        [\n          new fabric.Line(\n            [\n              this.clipper.width * 0.33,\n              0,\n              this.clipper.width * 0.33,\n              this.clipper.height,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              this.clipper.width * 0.66,\n              0,\n              this.clipper.width * 0.66,\n              this.clipper.height,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              0,\n              this.clipper.height * 0.33,\n              this.clipper.width,\n              this.clipper.height * 0.33,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              0,\n              this.clipper.height * 0.66,\n              this.clipper.width,\n              this.clipper.height * 0.66,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n        ],\n        {\n          left: this.clipper.left,\n          top: this.clipper.top,\n          originX: 'center',\n          originY: 'center',\n        }\n      );\n\n      this._redrawCropperElements._.cropTextTop =\n        this.croppingRectangle.top + this.clipper.height / 2 + 12;\n      this._redrawCropperElements._.cropTextBackgroundColor = 'rgba(0,0,0,0)';\n\n      if (\n        this._redrawCropperElements._.cropTextTop + 12 >\n        this.editorHeight - 2\n      ) {\n        this._redrawCropperElements._.cropTextTop -= 24;\n        this._redrawCropperElements._.cropTextBackgroundColor =\n          'rgba(0,0,0,0.5)';\n      }\n\n      this.croppingCanvas.add(this.cropperHandles);\n      this.croppingCanvas.add(this.cropperGrid);\n      this.croppingCanvas.add(this.croppingRectangle);\n    },\n\n    /**\n     * Reposition the cropper when the image editor dimensions change.\n     *\n     * @param {Object} previousImageArea\n     */\n    _repositionCropper: function (previousImageArea) {\n      if (!this.croppingCanvas) {\n        return;\n      }\n\n      // Get the current clipper offset relative to center\n      var currentOffset = {\n        x: this.clipper.left - this.croppingCanvas.width / 2,\n        y: this.clipper.top - this.croppingCanvas.height / 2,\n      };\n\n      // Resize the cropping canvas\n      this.croppingCanvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      // Check by what factor will the new final bounding box be different\n      var currentArea = this._getBoundingRectangle(this.imageVerticeCoords);\n      var areaFactor = currentArea.width / previousImageArea.width;\n\n      // Adjust the cropper size to scale along with the bounding box\n      this.clipper.width = Math.round(this.clipper.width * areaFactor);\n      this.clipper.height = Math.round(this.clipper.height * areaFactor);\n\n      // Adjust the coordinates: re-position clipper in relation to the new center to adjust\n      // for editor size changes and then multiply by the size factor to adjust for image size changes\n      this.clipper.left = this.editorWidth / 2 + currentOffset.x * areaFactor;\n      this.clipper.top = this.editorHeight / 2 + currentOffset.y * areaFactor;\n\n      // Resize the cropping shade\n      this.croppingShade.set({\n        width: this.editorWidth,\n        height: this.editorHeight,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      });\n\n      this._redrawCropperElements();\n      this.renderCropper();\n    },\n\n    /**\n     * Get the dimensions of a bounding rectangle by a set of four coordinates.\n     *\n     * @param {Object} coordinateSet\n     */\n    _getBoundingRectangle: function (coordinateSet) {\n      return {\n        width:\n          Math.max(\n            coordinateSet.a.x,\n            coordinateSet.b.x,\n            coordinateSet.c.x,\n            coordinateSet.d.x\n          ) -\n          Math.min(\n            coordinateSet.a.x,\n            coordinateSet.b.x,\n            coordinateSet.c.x,\n            coordinateSet.d.x\n          ),\n        height:\n          Math.max(\n            coordinateSet.a.y,\n            coordinateSet.b.y,\n            coordinateSet.c.y,\n            coordinateSet.d.y\n          ) -\n          Math.min(\n            coordinateSet.a.y,\n            coordinateSet.b.y,\n            coordinateSet.c.y,\n            coordinateSet.d.y\n          ),\n      };\n    },\n\n    /**\n     * Handle the mouse being clicked.\n     *\n     * @param {Object} ev\n     */\n    _handleMouseDown: function (ev) {\n      // Focal before resize before dragging\n      var focal = this.focalPoint && this._isMouseOver(ev, this.focalPoint);\n      var move = this.croppingCanvas && this._isMouseOver(ev, this.clipper);\n      var handle = this.croppingCanvas && this._cropperHandleHitTest(ev);\n\n      if (handle || move || focal) {\n        this.previousMouseX = ev.pageX;\n        this.previousMouseY = ev.pageY;\n\n        if (focal) {\n          this.draggingFocal = true;\n        } else if (handle) {\n          this.scalingCropper = handle;\n        } else if (move) {\n          this.draggingCropper = true;\n        }\n      }\n    },\n\n    /**\n     * Handle the mouse being moved.\n     *\n     * @param {Object} ev\n     */\n    _handleMouseMove: function (ev) {\n      if (this.mouseMoveEvent !== null) {\n        Garnish.requestAnimationFrame(this._handleMouseMoveInternal.bind(this));\n      }\n      this.mouseMoveEvent = ev;\n    },\n\n    _handleMouseMoveInternal: function () {\n      if (this.mouseMoveEvent === null) {\n        return;\n      }\n\n      if (this.focalPoint && this.draggingFocal) {\n        this._handleFocalDrag(this.mouseMoveEvent);\n        this.storeFocalPointState();\n        this.renderImage();\n      } else if (this.draggingCropper || this.scalingCropper) {\n        if (this.draggingCropper) {\n          this._handleCropperDrag(this.mouseMoveEvent);\n        } else {\n          this._handleCropperResize(this.mouseMoveEvent);\n        }\n\n        this._redrawCropperElements();\n\n        this.storeCropperState();\n        this.renderCropper();\n      } else {\n        this._setMouseCursor(this.mouseMoveEvent);\n      }\n\n      this.previousMouseX = this.mouseMoveEvent.pageX;\n      this.previousMouseY = this.mouseMoveEvent.pageY;\n\n      this.mouseMoveEvent = null;\n    },\n\n    /**\n     * Handle mouse being released.\n     */\n    _handleMouseUp: function () {\n      this.draggingCropper = false;\n      this.scalingCropper = false;\n      this.draggingFocal = false;\n    },\n\n    /**\n     * Handle mouse out\n     *\n     * @param {Object} ev\n     */\n    _handleMouseOut: function (ev) {\n      this._handleMouseUp(ev);\n      this.mouseMoveEvent = ev;\n      this._handleMouseMoveInternal();\n    },\n\n    /**\n     * Handle cropper being dragged.\n     *\n     * @param {Object} ev\n     */\n    _handleCropperDrag: function (ev) {\n      if (typeof this._handleCropperDrag._ === 'undefined') {\n        this._handleCropperDrag._ = {};\n      }\n\n      this._handleCropperDrag._.deltaX = ev.pageX - this.previousMouseX;\n      this._handleCropperDrag._.deltaY = ev.pageY - this.previousMouseY;\n\n      if (\n        this._handleCropperDrag._.deltaX === 0 &&\n        this._handleCropperDrag._.deltaY === 0\n      ) {\n        return false;\n      }\n\n      this._handleCropperDrag._.rectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      this._handleCropperDrag._.vertices = this._getRectangleVertices(\n        this._handleCropperDrag._.rectangle,\n        this._handleCropperDrag._.deltaX,\n        this._handleCropperDrag._.deltaY\n      );\n\n      // If this would drag it outside of the image\n      if (\n        !this.arePointsInsideRectangle(\n          this._handleCropperDrag._.vertices,\n          this.imageVerticeCoords\n        )\n      ) {\n        // Try to find the furthest point in the same general direction where we can drag it\n\n        // Delta iterator setup\n        this._handleCropperDrag._.dxi = 0;\n        this._handleCropperDrag._.dyi = 0;\n        this._handleCropperDrag._.xStep =\n          this._handleCropperDrag._.deltaX > 0 ? -1 : 1;\n        this._handleCropperDrag._.yStep =\n          this._handleCropperDrag._.deltaY > 0 ? -1 : 1;\n\n        // The furthest we can move\n        this._handleCropperDrag._.furthest = 0;\n        this._handleCropperDrag._.furthestDeltas = {};\n\n        // Loop through every combination of dragging it not so far\n        for (\n          this._handleCropperDrag._.dxi = Math.min(\n            Math.abs(this._handleCropperDrag._.deltaX),\n            10\n          );\n          this._handleCropperDrag._.dxi >= 0;\n          this._handleCropperDrag._.dxi--\n        ) {\n          for (\n            this._handleCropperDrag._.dyi = Math.min(\n              Math.abs(this._handleCropperDrag._.deltaY),\n              10\n            );\n            this._handleCropperDrag._.dyi >= 0;\n            this._handleCropperDrag._.dyi--\n          ) {\n            this._handleCropperDrag._.vertices = this._getRectangleVertices(\n              this._handleCropperDrag._.rectangle,\n              this._handleCropperDrag._.dxi *\n                (this._handleCropperDrag._.deltaX > 0 ? 1 : -1),\n              this._handleCropperDrag._.dyi *\n                (this._handleCropperDrag._.deltaY > 0 ? 1 : -1)\n            );\n\n            if (\n              this.arePointsInsideRectangle(\n                this._handleCropperDrag._.vertices,\n                this.imageVerticeCoords\n              )\n            ) {\n              if (\n                this._handleCropperDrag._.dxi + this._handleCropperDrag._.dyi >\n                this._handleCropperDrag._.furthest\n              ) {\n                this._handleCropperDrag._.furthest =\n                  this._handleCropperDrag._.dxi + this._handleCropperDrag._.dyi;\n                this._handleCropperDrag._.furthestDeltas = {\n                  x:\n                    this._handleCropperDrag._.dxi *\n                    (this._handleCropperDrag._.deltaX > 0 ? 1 : -1),\n                  y:\n                    this._handleCropperDrag._.dyi *\n                    (this._handleCropperDrag._.deltaY > 0 ? 1 : -1),\n                };\n              }\n            }\n          }\n        }\n\n        // REALLY can't drag along the cursor movement\n        if (this._handleCropperDrag._.furthest == 0) {\n          return;\n        } else {\n          this._handleCropperDrag._.deltaX =\n            this._handleCropperDrag._.furthestDeltas.x;\n          this._handleCropperDrag._.deltaY =\n            this._handleCropperDrag._.furthestDeltas.y;\n        }\n      }\n\n      this.clipper.set({\n        left: this.clipper.left + this._handleCropperDrag._.deltaX,\n        top: this.clipper.top + this._handleCropperDrag._.deltaY,\n      });\n    },\n\n    /**\n     * Handle focal point being dragged.\n     *\n     * @param {Object} ev\n     */\n    _handleFocalDrag: function (ev) {\n      if (typeof this._handleFocalDrag._ === 'undefined') {\n        this._handleFocalDrag._ = {};\n      }\n\n      if (this.focalPoint) {\n        this._handleFocalDrag._.deltaX = ev.pageX - this.previousMouseX;\n        this._handleFocalDrag._.deltaY = ev.pageY - this.previousMouseY;\n\n        if (\n          this._handleFocalDrag._.deltaX === 0 &&\n          this._handleFocalDrag._.deltaY === 0\n        ) {\n          return;\n        }\n\n        this._handleFocalDrag._.newX =\n          this.focalPoint.left + this._handleFocalDrag._.deltaX;\n        this._handleFocalDrag._.newY =\n          this.focalPoint.top + this._handleFocalDrag._.deltaY;\n\n        // Just make sure that the focal point stays inside the image\n        if (this.currentView === 'crop') {\n          if (\n            !this.arePointsInsideRectangle(\n              [\n                {\n                  x: this._handleFocalDrag._.newX,\n                  y: this._handleFocalDrag._.newY,\n                },\n              ],\n              this.imageVerticeCoords\n            )\n          ) {\n            return;\n          }\n        } else {\n          if (\n            !(\n              this.viewport.left -\n                this.viewport.width / 2 -\n                this._handleFocalDrag._.newX <\n                0 &&\n              this.viewport.left +\n                this.viewport.width / 2 -\n                this._handleFocalDrag._.newX >\n                0 &&\n              this.viewport.top -\n                this.viewport.height / 2 -\n                this._handleFocalDrag._.newY <\n                0 &&\n              this.viewport.top +\n                this.viewport.height / 2 -\n                this._handleFocalDrag._.newY >\n                0\n            )\n          ) {\n            return;\n          }\n        }\n\n        this.focalPoint.set({\n          left: this.focalPoint.left + this._handleFocalDrag._.deltaX,\n          top: this.focalPoint.top + this._handleFocalDrag._.deltaY,\n        });\n      }\n    },\n\n    /**\n     * Set the cropping constraint\n     * @param {string} constraint\n     */\n    setCroppingConstraint: function (constraint) {\n      // In case this caused the sidebar width to change.\n      this.updateSizeAndPosition();\n\n      switch (constraint) {\n        case 'none':\n          this.croppingConstraint = false;\n          break;\n\n        case 'original':\n          this.croppingConstraint = this.originalWidth / this.originalHeight;\n          break;\n\n        case 'current':\n          this.croppingConstraint = this.clipper.width / this.clipper.height;\n          break;\n\n        case 'custom':\n          break;\n        default:\n          this.croppingConstraint = parseFloat(constraint);\n\n          break;\n      }\n    },\n\n    /**\n     * Enforce the cropping constraint\n     */\n    enforceCroppingConstraint: function () {\n      if (typeof this.enforceCroppingConstraint._ === 'undefined') {\n        this.enforceCroppingConstraint._ = {};\n      }\n\n      if (this.animationInProgress || !this.croppingConstraint) {\n        return;\n      }\n\n      this.animationInProgress = true;\n\n      // Mock the clipping rectangle for collision tests\n      this.enforceCroppingConstraint._.rectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      // If wider than it should be\n      if (this.clipper.width > this.clipper.height * this.croppingConstraint) {\n        this.enforceCroppingConstraint._.previousHeight =\n          this.enforceCroppingConstraint._.rectangle.height;\n\n        // Make it taller!\n        this.enforceCroppingConstraint._.rectangle.height =\n          this.clipper.width / this.croppingConstraint;\n\n        // Getting really awkward having to convert between 0;0 being center or top-left corner.\n        this.enforceCroppingConstraint._.rectangle.top -=\n          (this.enforceCroppingConstraint._.rectangle.height -\n            this.enforceCroppingConstraint._.previousHeight) /\n          2;\n\n        // If the clipper would end up out of bounds, make it narrower instead.\n        if (\n          !this.arePointsInsideRectangle(\n            this._getRectangleVertices(\n              this.enforceCroppingConstraint._.rectangle\n            ),\n            this.imageVerticeCoords\n          )\n        ) {\n          this.enforceCroppingConstraint._.rectangle.width =\n            this.clipper.height * this.croppingConstraint;\n          this.enforceCroppingConstraint._.rectangle.height =\n            this.enforceCroppingConstraint._.rectangle.width /\n            this.croppingConstraint;\n        }\n      } else {\n        // Follow the same pattern, if taller than it should be.\n        this.enforceCroppingConstraint._.previousWidth =\n          this.enforceCroppingConstraint._.rectangle.width;\n        this.enforceCroppingConstraint._.rectangle.width =\n          this.clipper.height * this.croppingConstraint;\n        this.enforceCroppingConstraint._.rectangle.left -=\n          (this.enforceCroppingConstraint._.rectangle.width -\n            this.enforceCroppingConstraint._.previousWidth) /\n          2;\n\n        if (\n          !this.arePointsInsideRectangle(\n            this._getRectangleVertices(\n              this.enforceCroppingConstraint._.rectangle\n            ),\n            this.imageVerticeCoords\n          )\n        ) {\n          this.enforceCroppingConstraint._.rectangle.height =\n            this.clipper.width / this.croppingConstraint;\n          this.enforceCroppingConstraint._.rectangle.width =\n            this.enforceCroppingConstraint._.rectangle.height *\n            this.croppingConstraint;\n        }\n      }\n\n      this.enforceCroppingConstraint._.properties = {\n        height: this.enforceCroppingConstraint._.rectangle.height,\n        width: this.enforceCroppingConstraint._.rectangle.width,\n      };\n\n      // Make sure to redraw cropper handles and gridlines when resizing\n      this.clipper.animate(this.enforceCroppingConstraint._.properties, {\n        onChange: () => {\n          this._redrawCropperElements();\n          this.croppingCanvas.renderAll();\n        },\n        duration: this.settings.animationDuration,\n        onComplete: () => {\n          this._redrawCropperElements();\n          this.animationInProgress = false;\n          this.renderCropper();\n          this.storeCropperState();\n        },\n      });\n    },\n\n    /**\n     * Handle cropper being resized.\n     *\n     * @param {Object} ev\n     */\n    _handleCropperResize: function (ev) {\n      if (typeof this._handleCropperResize._ === 'undefined') {\n        this._handleCropperResize._ = {};\n      }\n\n      // Size deltas\n      this._handleCropperResize._.deltaX = ev.pageX - this.previousMouseX;\n      this._handleCropperResize._.deltaY = ev.pageY - this.previousMouseY;\n\n      if (this.scalingCropper === 'b' || this.scalingCropper === 't') {\n        this._handleCropperResize._.deltaX = 0;\n      }\n\n      if (this.scalingCropper === 'l' || this.scalingCropper === 'r') {\n        this._handleCropperResize._.deltaY = 0;\n      }\n\n      if (\n        this._handleCropperResize._.deltaX === 0 &&\n        this._handleCropperResize._.deltaY === 0\n      ) {\n        return;\n      }\n\n      // Translate from center-center origin to absolute coords\n      this._handleCropperResize._.startingRectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      this._handleCropperResize._.rectangle =\n        this._calculateNewCropperSizeByDeltas(\n          this._handleCropperResize._.startingRectangle,\n          this._handleCropperResize._.deltaX,\n          this._handleCropperResize._.deltaY,\n          this.scalingCropper\n        );\n\n      if (\n        this._handleCropperResize._.rectangle.height < 30 ||\n        this._handleCropperResize._.rectangle.width < 30\n      ) {\n        return;\n      }\n\n      if (\n        !this.arePointsInsideRectangle(\n          this._getRectangleVertices(this._handleCropperResize._.rectangle),\n          this.imageVerticeCoords\n        )\n      ) {\n        return;\n      }\n\n      // Translate back to center-center origin.\n      this.clipper.set({\n        top:\n          this._handleCropperResize._.rectangle.top +\n          this._handleCropperResize._.rectangle.height / 2,\n        left:\n          this._handleCropperResize._.rectangle.left +\n          this._handleCropperResize._.rectangle.width / 2,\n        width: this._handleCropperResize._.rectangle.width,\n        height: this._handleCropperResize._.rectangle.height,\n      });\n\n      this._redrawCropperElements();\n    },\n\n    _calculateNewCropperSizeByDeltas: function (\n      startingRectangle,\n      deltaX,\n      deltaY,\n      cropperDirection\n    ) {\n      if (typeof this._calculateNewCropperSizeByDeltas._ === 'undefined') {\n        this._calculateNewCropperSizeByDeltas._ = {};\n      }\n\n      // Center deltas\n      this._calculateNewCropperSizeByDeltas._.topDelta = 0;\n      this._calculateNewCropperSizeByDeltas._.leftDelta = 0;\n\n      this._calculateNewCropperSizeByDeltas._.rectangle = startingRectangle;\n      this._calculateNewCropperSizeByDeltas._.deltaX = deltaX;\n      this._calculateNewCropperSizeByDeltas._.deltaY = deltaY;\n\n      // Lock the aspect ratio if needed\n      if (this.croppingConstraint) {\n        this._calculateNewCropperSizeByDeltas._.change = 0;\n\n        // Take into account the mouse direction and figure out the \"real\" change in cropper size\n        switch (cropperDirection) {\n          case 't':\n            this._calculateNewCropperSizeByDeltas._.change =\n              -this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'b':\n            this._calculateNewCropperSizeByDeltas._.change =\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'r':\n            this._calculateNewCropperSizeByDeltas._.change =\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'l':\n            this._calculateNewCropperSizeByDeltas._.change =\n              -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tr':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? -this._calculateNewCropperSizeByDeltas._.deltaY\n                : this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tl':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? -this._calculateNewCropperSizeByDeltas._.deltaY\n                : -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'br':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? this._calculateNewCropperSizeByDeltas._.deltaY\n                : this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'bl':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? this._calculateNewCropperSizeByDeltas._.deltaY\n                : -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n        }\n\n        if (this.croppingConstraint > 1) {\n          this._calculateNewCropperSizeByDeltas._.deltaX =\n            this._calculateNewCropperSizeByDeltas._.change;\n          this._calculateNewCropperSizeByDeltas._.deltaY =\n            this._calculateNewCropperSizeByDeltas._.deltaX /\n            this.croppingConstraint;\n        } else {\n          this._calculateNewCropperSizeByDeltas._.deltaY =\n            this._calculateNewCropperSizeByDeltas._.change;\n          this._calculateNewCropperSizeByDeltas._.deltaX =\n            this._calculateNewCropperSizeByDeltas._.deltaY *\n            this.croppingConstraint;\n        }\n\n        this._calculateNewCropperSizeByDeltas._.rectangle.height +=\n          this._calculateNewCropperSizeByDeltas._.deltaY;\n        this._calculateNewCropperSizeByDeltas._.rectangle.width +=\n          this._calculateNewCropperSizeByDeltas._.deltaX;\n\n        // Make the cropper compress/expand relative to the correct edge to make it feel \"right\"\n        switch (cropperDirection) {\n          case 't':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX / 2;\n            break;\n          case 'b':\n            this._calculateNewCropperSizeByDeltas._.rectangle.left +=\n              -this._calculateNewCropperSizeByDeltas._.deltaX / 2;\n            break;\n          case 'r':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top +=\n              -this._calculateNewCropperSizeByDeltas._.deltaY / 2;\n            break;\n          case 'l':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY / 2;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tr':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'tl':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'bl':\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n        }\n      } else {\n        // Lock the aspect ratio\n        if (\n          this.shiftKeyHeld &&\n          (cropperDirection === 'tl' ||\n            cropperDirection === 'tr' ||\n            cropperDirection === 'bl' ||\n            cropperDirection === 'br')\n        ) {\n          this._calculateNewCropperSizeByDeltas._.ratio;\n          if (Math.abs(deltaX) > Math.abs(deltaY)) {\n            this._calculateNewCropperSizeByDeltas._.ratio =\n              startingRectangle.width / startingRectangle.height;\n            this._calculateNewCropperSizeByDeltas._.deltaY =\n              this._calculateNewCropperSizeByDeltas._.deltaX /\n              this._calculateNewCropperSizeByDeltas._.ratio;\n            this._calculateNewCropperSizeByDeltas._.deltaY *=\n              cropperDirection === 'tr' || cropperDirection === 'bl' ? -1 : 1;\n          } else {\n            this._calculateNewCropperSizeByDeltas._.ratio =\n              startingRectangle.width / startingRectangle.height;\n            this._calculateNewCropperSizeByDeltas._.deltaX =\n              this._calculateNewCropperSizeByDeltas._.deltaY *\n              this._calculateNewCropperSizeByDeltas._.ratio;\n            this._calculateNewCropperSizeByDeltas._.deltaX *=\n              cropperDirection === 'tr' || cropperDirection === 'bl' ? -1 : 1;\n          }\n        }\n\n        if (cropperDirection.match(/t/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.top +=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n          this._calculateNewCropperSizeByDeltas._.rectangle.height -=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n        }\n        if (cropperDirection.match(/b/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.height +=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n        }\n        if (cropperDirection.match(/r/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.width +=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n        }\n        if (cropperDirection.match(/l/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.left +=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n          this._calculateNewCropperSizeByDeltas._.rectangle.width -=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n        }\n      }\n\n      this._calculateNewCropperSizeByDeltas._.rectangle.top =\n        this._calculateNewCropperSizeByDeltas._.rectangle.top;\n      this._calculateNewCropperSizeByDeltas._.rectangle.left =\n        this._calculateNewCropperSizeByDeltas._.rectangle.left;\n      this._calculateNewCropperSizeByDeltas._.rectangle.width =\n        this._calculateNewCropperSizeByDeltas._.rectangle.width;\n      this._calculateNewCropperSizeByDeltas._.rectangle.height =\n        this._calculateNewCropperSizeByDeltas._.rectangle.height;\n\n      return this._calculateNewCropperSizeByDeltas._.rectangle;\n    },\n\n    /**\n     * Set mouse cursor by it's position over cropper.\n     *\n     * @param {Object} ev\n     */\n    _setMouseCursor: function (ev) {\n      if (typeof this._setMouseCursor._ === 'undefined') {\n        this._setMouseCursor._ = {};\n      }\n\n      if (Garnish.isMobileBrowser(true)) {\n        return;\n      }\n      this._setMouseCursor._.cursor = 'default';\n      this._setMouseCursor._.handle =\n        this.croppingCanvas && this._cropperHandleHitTest(ev);\n      if (this.focalPoint && this._isMouseOver(ev, this.focalPoint)) {\n        this._setMouseCursor._.cursor = 'pointer';\n      } else if (this._setMouseCursor._.handle) {\n        if (\n          this._setMouseCursor._.handle === 't' ||\n          this._setMouseCursor._.handle === 'b'\n        ) {\n          this._setMouseCursor._.cursor = 'ns-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'l' ||\n          this._setMouseCursor._.handle === 'r'\n        ) {\n          this._setMouseCursor._.cursor = 'ew-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'tl' ||\n          this._setMouseCursor._.handle === 'br'\n        ) {\n          this._setMouseCursor._.cursor = 'nwse-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'bl' ||\n          this._setMouseCursor._.handle === 'tr'\n        ) {\n          this._setMouseCursor._.cursor = 'nesw-resize';\n        }\n      } else if (this.croppingCanvas && this._isMouseOver(ev, this.clipper)) {\n        this._setMouseCursor._.cursor = 'move';\n      }\n\n      $('.body').css('cursor', this._setMouseCursor._.cursor);\n    },\n\n    /**\n     * Test whether the mouse cursor is on any cropper handles.\n     *\n     * @param {Object} ev\n     */\n    _cropperHandleHitTest: function (ev) {\n      if (typeof this._cropperHandleHitTest._ === 'undefined') {\n        this._cropperHandleHitTest._ = {};\n      }\n\n      this._cropperHandleHitTest._.parentOffset = this.$croppingCanvas.offset();\n      this._cropperHandleHitTest._.mouseX =\n        ev.pageX - this._cropperHandleHitTest._.parentOffset.left;\n      this._cropperHandleHitTest._.mouseY =\n        ev.pageY - this._cropperHandleHitTest._.parentOffset.top;\n\n      // Compensate for center origin coordinate-wise\n      this._cropperHandleHitTest._.lb =\n        this.clipper.left - this.clipper.width / 2;\n      this._cropperHandleHitTest._.rb =\n        this._cropperHandleHitTest._.lb + this.clipper.width;\n      this._cropperHandleHitTest._.tb =\n        this.clipper.top - this.clipper.height / 2;\n      this._cropperHandleHitTest._.bb =\n        this._cropperHandleHitTest._.tb + this.clipper.height;\n\n      // Left side top/bottom\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb - 3\n      ) {\n        if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.tb + 10 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.tb - 3\n        ) {\n          return 'tl';\n        } else if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.bb + 3 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.bb - 10\n        ) {\n          return 'bl';\n        }\n      }\n      // Right side top/bottom\n      if (\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.rb - 13 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb + 3\n      ) {\n        if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.tb + 10 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.tb - 3\n        ) {\n          return 'tr';\n        } else if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.bb + 2 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.bb - 10\n        ) {\n          return 'br';\n        }\n      }\n\n      // Left or right\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.lb + 3 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb - 3 &&\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb - 10 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb + 10\n      ) {\n        return 'l';\n      }\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb + 1 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.rb - 5 &&\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb - 10 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb + 10\n      ) {\n        return 'r';\n      }\n\n      // Top or bottom\n      if (\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.tb + 4 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb - 2 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb - 10\n      ) {\n        return 't';\n      }\n      if (\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb + 2 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.bb - 4 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb - 10\n      ) {\n        return 'b';\n      }\n\n      return false;\n    },\n\n    /**\n     * Test whether the mouse cursor is on a fabricJS object.\n     *\n     * @param {Object} event\n     * @param {Object} object\n     * @returns {boolean}\n     */\n    _isMouseOver: function (event, object) {\n      if (typeof this._isMouseOver._ === 'undefined') {\n        this._isMouseOver._ = {};\n      }\n\n      this._isMouseOver._.parentOffset = this.$croppingCanvas.offset();\n      this._isMouseOver._.mouseX =\n        event.pageX - this._isMouseOver._.parentOffset.left;\n      this._isMouseOver._.mouseY =\n        event.pageY - this._isMouseOver._.parentOffset.top;\n\n      // Compensate for center origin coordinate-wise\n      this._isMouseOver._.lb = object.left - object.width / 2;\n      this._isMouseOver._.rb = this._isMouseOver._.lb + object.width;\n      this._isMouseOver._.tb = object.top - object.height / 2;\n      this._isMouseOver._.bb = this._isMouseOver._.tb + object.height;\n\n      return (\n        this._isMouseOver._.mouseX >= this._isMouseOver._.lb &&\n        this._isMouseOver._.mouseX <= this._isMouseOver._.rb &&\n        this._isMouseOver._.mouseY >= this._isMouseOver._.tb &&\n        this._isMouseOver._.mouseY <= this._isMouseOver._.bb\n      );\n    },\n\n    /**\n     * Get vertices of a rectangle defined by left,top,height and width properties.\n     * Optionally it's possible to provide offsetX and offsetY values.\n     * Left and top properties of rectangle reference the top-left corner.\n     *\n     * @param {Object} rectangle\n     * @param {number} [offsetX]\n     * @param {number} [offsetY]\n     */\n    _getRectangleVertices: function (rectangle, offsetX, offsetY) {\n      if (typeof this._getRectangleVertices._ === 'undefined') {\n        this._getRectangleVertices._ = {};\n      }\n\n      if (typeof offsetX === 'undefined') {\n        offsetX = 0;\n      }\n      if (typeof offsetY === 'undefined') {\n        offsetY = 0;\n      }\n\n      this._getRectangleVertices._.topLeft = {\n        x: rectangle.left + offsetX,\n        y: rectangle.top + offsetY,\n      };\n\n      this._getRectangleVertices._.topRight = {\n        x: this._getRectangleVertices._.topLeft.x + rectangle.width,\n        y: this._getRectangleVertices._.topLeft.y,\n      };\n      this._getRectangleVertices._.bottomRight = {\n        x: this._getRectangleVertices._.topRight.x,\n        y: this._getRectangleVertices._.topRight.y + rectangle.height,\n      };\n      this._getRectangleVertices._.bottomLeft = {\n        x: this._getRectangleVertices._.topLeft.x,\n        y: this._getRectangleVertices._.bottomRight.y,\n      };\n\n      return [\n        this._getRectangleVertices._.topLeft,\n        this._getRectangleVertices._.topRight,\n        this._getRectangleVertices._.bottomRight,\n        this._getRectangleVertices._.bottomLeft,\n      ];\n    },\n\n    /**\n     * Set image vertice coordinates for an image that's been zoomed to fit.\n     */\n    _setFittedImageVerticeCoordinates: function () {\n      this.imageVerticeCoords = this.getImageVerticeCoords('fit');\n    },\n\n    /**\n     * Get image vertice coords by a zoom mode and taking into account the straightening angle.\n     * The zoomMode can be either \"cover\", \"fit\" or a discrete float value.\n     *\n     * @param {string} zoomMode\n     */\n    getImageVerticeCoords: function (zoomMode) {\n      var angleInRadians =\n        -1 *\n        ((this.hasOrientationChanged() ? 90 : 0) + this.imageStraightenAngle) *\n        (Math.PI / 180);\n\n      var imageDimensions = this.getScaledImageDimensions();\n\n      var ratio;\n\n      if (typeof zoomMode === 'number') {\n        ratio = zoomMode;\n      } else if (zoomMode === 'cover') {\n        ratio = this.getZoomToCoverRatio(imageDimensions);\n      } else {\n        ratio = this.getZoomToFitRatio(imageDimensions);\n      }\n\n      // Get the dimensions of the scaled image\n      var scaledHeight = imageDimensions.height * ratio;\n      var scaledWidth = imageDimensions.width * ratio;\n\n      // Calculate the segments of the containing box for the image.\n      // When referring to top/bottom or right/left segments, these are on the\n      // right-side and bottom projection of the containing box for the zoomed out image.\n      var topVerticalSegment = Math.cos(angleInRadians) * scaledHeight;\n      var bottomVerticalSegment = Math.sin(angleInRadians) * scaledWidth;\n      var rightHorizontalSegment = Math.cos(angleInRadians) * scaledWidth;\n      var leftHorizontalSegment = Math.sin(angleInRadians) * scaledHeight;\n\n      // Calculate the offsets from editor box for the image-containing box\n      var verticalOffset =\n        (this.editorHeight - (topVerticalSegment + bottomVerticalSegment)) / 2;\n      var horizontalOffset =\n        (this.editorWidth - (leftHorizontalSegment + rightHorizontalSegment)) /\n        2;\n\n      // Finally, calculate the image vertice coordinates\n      return {\n        a: {\n          x: horizontalOffset + rightHorizontalSegment,\n          y: verticalOffset,\n        },\n        b: {\n          x: this.editorWidth - horizontalOffset,\n          y: verticalOffset + topVerticalSegment,\n        },\n        c: {\n          x: horizontalOffset + leftHorizontalSegment,\n          y: this.editorHeight - verticalOffset,\n        },\n        d: {\n          x: horizontalOffset,\n          y: verticalOffset + bottomVerticalSegment,\n        },\n      };\n    },\n\n    /**\n     * Debug stuff by continuously rendering a fabric object on canvas.\n     *\n     * @param {Object} fabricObj\n     */\n    _debug: function (fabricObj) {\n      this.canvas.remove(this.debugger);\n      this.debugger = fabricObj;\n      this.canvas.add(this.debugger);\n    },\n\n    /**\n     * Given an array of points in the form of {x: int, y:int} and a rectangle in the form of\n     * {a:{x:int, y:int}, b:{x:int, y:int}, c:{x:int, y:int}} (the fourth vertice is unnecessary)\n     * return true if the point is in the rectangle.\n     *\n     * Adapted from: http://stackoverflow.com/a/2763387/2040791\n     *\n     * @param {Object} points\n     * @param {Object} rectangle\n     */\n    arePointsInsideRectangle: function (points, rectangle) {\n      if (typeof this.arePointsInsideRectangle._ === 'undefined') {\n        this.arePointsInsideRectangle._ = {};\n      }\n\n      // Pre-calculate the vectors and scalar products for two rectangle edges\n      this.arePointsInsideRectangle._.ab = this._getVector(\n        rectangle.a,\n        rectangle.b\n      );\n      this.arePointsInsideRectangle._.bc = this._getVector(\n        rectangle.b,\n        rectangle.c\n      );\n      this.arePointsInsideRectangle._.scalarAbAb = this._getScalarProduct(\n        this.arePointsInsideRectangle._.ab,\n        this.arePointsInsideRectangle._.ab\n      );\n      this.arePointsInsideRectangle._.scalarBcBc = this._getScalarProduct(\n        this.arePointsInsideRectangle._.bc,\n        this.arePointsInsideRectangle._.bc\n      );\n\n      for (\n        this.arePointsInsideRectangle._.i = 0;\n        this.arePointsInsideRectangle._.i < points.length;\n        this.arePointsInsideRectangle._.i++\n      ) {\n        this.arePointsInsideRectangle._.point =\n          points[this.arePointsInsideRectangle._.i];\n\n        // Calculate the vectors for two rectangle sides and for\n        // the vector from vertices a and b to the point P\n        this.arePointsInsideRectangle._.ap = this._getVector(\n          rectangle.a,\n          this.arePointsInsideRectangle._.point\n        );\n        this.arePointsInsideRectangle._.bp = this._getVector(\n          rectangle.b,\n          this.arePointsInsideRectangle._.point\n        );\n\n        // Calculate scalar or dot products for some vector combinations\n        this.arePointsInsideRectangle._.scalarAbAp = this._getScalarProduct(\n          this.arePointsInsideRectangle._.ab,\n          this.arePointsInsideRectangle._.ap\n        );\n        this.arePointsInsideRectangle._.scalarBcBp = this._getScalarProduct(\n          this.arePointsInsideRectangle._.bc,\n          this.arePointsInsideRectangle._.bp\n        );\n\n        this.arePointsInsideRectangle._.projectsOnAB =\n          0 <= this.arePointsInsideRectangle._.scalarAbAp &&\n          this.arePointsInsideRectangle._.scalarAbAp <=\n            this.arePointsInsideRectangle._.scalarAbAb;\n        this.arePointsInsideRectangle._.projectsOnBC =\n          0 <= this.arePointsInsideRectangle._.scalarBcBp &&\n          this.arePointsInsideRectangle._.scalarBcBp <=\n            this.arePointsInsideRectangle._.scalarBcBc;\n\n        if (\n          !(\n            this.arePointsInsideRectangle._.projectsOnAB &&\n            this.arePointsInsideRectangle._.projectsOnBC\n          )\n        ) {\n          return false;\n        }\n      }\n\n      return true;\n    },\n\n    /**\n     * Returns an object representing the vector between points a and b.\n     *\n     * @param {Object} a\n     * @param {Object} b\n     */\n    _getVector: function (a, b) {\n      return {x: b.x - a.x, y: b.y - a.y};\n    },\n\n    /**\n     * Returns the scalar product of two vectors\n     *\n     * @param {Object} a\n     * @param {Object} b\n     */\n    _getScalarProduct: function (a, b) {\n      return a.x * b.x + a.y * b.y;\n    },\n\n    /**\n     * Returns the magnitude of a vector_redrawCropperElements\n     * .\n     *\n     * @param {Object} vector\n     */\n    _getVectorMagnitude: function (vector) {\n      return Math.sqrt(vector.x * vector.x + vector.y * vector.y);\n    },\n\n    /**\n     * Returns the angle between two vectors in degrees with two decimal points\n     *\n     * @param {Object} a\n     * @param {Object} b\n     */\n    _getAngleBetweenVectors: function (a, b) {\n      return (\n        Math.round(\n          ((Math.acos(\n            Math.min(\n              1,\n              this._getScalarProduct(a, b) /\n                (this._getVectorMagnitude(a) * this._getVectorMagnitude(b))\n            )\n          ) *\n            180) /\n            Math.PI) *\n            100\n        ) / 100\n      );\n    },\n\n    /**\n     * Return the rectangle edge crossed by an imaginary line drawn from editor center to a vertex\n     *\n     * @param {Object} rectangle\n     * @param {Object} vertex\n     *\n     * @returns {*}\n     */\n    _getEdgeCrossed: function (rectangle, vertex) {\n      // Determine over which edge the vertex is\n      var edgePoints = [\n        [rectangle.a, rectangle.b],\n        [rectangle.b, rectangle.c],\n        [rectangle.c, rectangle.d],\n        [rectangle.d, rectangle.a],\n      ];\n\n      var centerPoint = {x: this.editorWidth / 2, y: this.editorHeight / 2};\n      var smallestDiff = 180;\n      var edgeCrossed = null;\n\n      // Test each edge\n      for (var edgeIndex = 0; edgeIndex < edgePoints.length; edgeIndex++) {\n        var edge = edgePoints[edgeIndex];\n        var toCenter = this._getVector(edge[0], centerPoint);\n        var edgeVector = this._getVector(edge[0], edge[1]);\n        var toVertex = this._getVector(edge[0], vertex);\n\n        // If the angle between toCenter/toVertex is the sum of\n        // angles between edgeVector/toCenter and edgeVector/toVertex, it means that\n        // the edgeVector is between the other two meaning that this is the offending vertex.\n        // To avoid the rounding errors, we'll take the closest match\n        var diff = Math.abs(\n          this._getAngleBetweenVectors(toCenter, toVertex) -\n            (this._getAngleBetweenVectors(toCenter, edgeVector) +\n              this._getAngleBetweenVectors(edgeVector, toVertex))\n        );\n\n        if (diff < smallestDiff) {\n          smallestDiff = diff;\n          edgeCrossed = edge;\n        }\n      }\n\n      return edgeCrossed;\n    },\n\n    /**\n     * Get the image bounding box by image scaled dimensions, taking ingo account the straightening angle.\n     *\n     * @param {Object} dimensions\n     */\n    _getImageBoundingBox: function (dimensions) {\n      var box = {};\n\n      var angleInRadians =\n        Math.abs(this.imageStraightenAngle) * (Math.PI / 180);\n\n      var proportion = dimensions.height / dimensions.width;\n      box.height =\n        dimensions.width *\n        (Math.sin(angleInRadians) + Math.cos(angleInRadians) * proportion);\n      box.width =\n        dimensions.width *\n        (Math.cos(angleInRadians) + Math.sin(angleInRadians) * proportion);\n\n      if (this.hasOrientationChanged()) {\n        var temp = box.width;\n        box.width = box.height;\n        box.height = temp;\n      }\n\n      return box;\n    },\n  },\n  {\n    defaults: {\n      animationDuration: 100,\n      allowSavingAsNew: true,\n      onSave: $.noop,\n      allowDegreeFractions: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset index class\n */\nCraft.AssetIndex = Craft.BaseElementIndex.extend(\n  {\n    $includeSubfoldersContainer: null,\n    $includeSubfoldersCheckbox: null,\n    showingIncludeSubfoldersCheckbox: false,\n\n    $uploadButton: null,\n    $uploadInput: null,\n    $progressBar: null,\n\n    uploader: null,\n    promptHandler: null,\n    progressBar: null,\n\n    $listedFolders: null,\n    itemDrag: null,\n\n    _uploadTotalFiles: 0,\n    _uploadFileProgress: {},\n    _currentUploaderSettings: {},\n\n    init: function (elementType, $container, settings) {\n      settings = Object.assign({}, Craft.AssetIndex.defaults, settings);\n      this.base(elementType, $container, settings);\n\n      if (this.settings.context === 'index') {\n        this.itemDrag = new Garnish.DragDrop({\n          activeDropTargetClass: 'sel',\n          minMouseDist: 10,\n          hideDraggee: false,\n          moveHelperToCursor: true,\n          activeDropTargetClass: 'active-drop-target',\n          handle: (item) => $(item).closest('tr,li'),\n          filter: () => {\n            const $container = this.itemDrag.$targetItem.closest('tr,li');\n            this.view.elementSelect.selectItem($container);\n            return this._findDraggableItems(this.view.getSelectedElements());\n          },\n          helper: ($item, index) =>\n            $('<div class=\"offset-drag-helper\"/>')\n              .append($item)\n              .css({\n                opacity: Math.max(0.9 - 0.05 * index, 0),\n                width: '',\n                height: '',\n              }),\n          dropTargets: () => {\n            // volume sources\n            let $dropTargets = $(\n              this.$visibleSources\n                .toArray()\n                .filter(\n                  (source) =>\n                    Garnish.hasAttr(source, 'data-folder-id') &&\n                    Garnish.hasAttr(source, 'data-can-move-peer-files-to')\n                )\n            );\n            if (this.sourcePath.length <= 1) {\n              // exclude the current source since we're already at the root of it\n              $dropTargets = $dropTargets.not(this.$source);\n            } else {\n              // parent folders in the source path\n              for (let i = 0; i < this.sourcePath.length - 1; i++) {\n                const step = this.sourcePath[i];\n                if (step.folderId) {\n                  $dropTargets = $dropTargets.add(step.$btn);\n                }\n              }\n            }\n            // folders in the elements listing\n            if (this.$listedFolders) {\n              $dropTargets = $dropTargets\n                .add(\n                  this.$listedFolders\n                    .filter('[data-folder-id]')\n                    .closest('tr,li')\n                )\n                .not(this.view.getSelectedElements());\n            }\n            return $dropTargets;\n          },\n          onDragStart: () => {\n            Garnish.$bod.addClass('dragging');\n            this.itemDrag.$draggee.closest('tr,li').addClass('draggee');\n          },\n          onDragStop: () => {\n            Garnish.$bod.removeClass('dragging');\n\n            const $draggee = this.itemDrag.$draggee;\n            const targetFolderId = this._targetFolderId(\n              this.itemDrag.$activeDropTarget\n            );\n\n            if (!targetFolderId) {\n              $draggee.closest('tr,li').removeClass('draggee');\n              this.itemDrag.returnHelpersToDraggees();\n              return;\n            }\n\n            this.itemDrag.fadeOutHelpers();\n\n            const $folders = $draggee.filter('[data-is-folder]');\n            const $assets = $draggee.not($folders);\n            const folderIds = $folders.toArray().map((item) => {\n              return parseInt($(item).data('folder-id'));\n            });\n            const assetIds = $assets.toArray().map((item) => {\n              return parseInt($(item).data('id'));\n            });\n\n            const mover = new Craft.AssetMover();\n            mover\n              .moveFolders(folderIds, targetFolderId)\n              .then((totalFoldersMoved) => {\n                mover\n                  .moveAssets(assetIds, targetFolderId)\n                  .then((totalAssetsMoved) => {\n                    const totalItemsMoved =\n                      totalFoldersMoved + totalAssetsMoved;\n                    if (totalItemsMoved) {\n                      Craft.cp.displayNotice(\n                        Craft.t(\n                          'app',\n                          '{totalItems, plural, =1{Item} other{Items}} moved.',\n                          {\n                            totalItems: totalItemsMoved,\n                          }\n                        )\n                      );\n                      Craft.elementIndex.updateElements(true);\n                    } else {\n                      $draggee.closest('tr,li').removeClass('draggee');\n                    }\n                  });\n              });\n          },\n        });\n\n        this.addListener(Garnish.$win, 'resize,scroll', '_positionProgressBar');\n      } else {\n        this.addListener(this.$main, 'scroll', '_positionProgressBar');\n\n        if (this.settings.modal) {\n          this.settings.modal.on(\n            'updateSizeAndPosition',\n            this._positionProgressBar.bind(this)\n          );\n        }\n      }\n    },\n\n    _findDraggableItems: function ($items) {\n      return $(\n        $items\n          .toArray()\n          .map((item) => $(item).find('.element:first')[0])\n          .filter((item) => item && Garnish.hasAttr(item, 'data-movable'))\n      );\n    },\n\n    _targetFolderId: function ($dropTarget) {\n      if (!$dropTarget || !$dropTarget.length) {\n        return false;\n      }\n\n      // source?\n      if ($dropTarget.is(this.$visibleSources)) {\n        return $dropTarget.data('folder-id');\n      }\n\n      // source path step?\n      for (let i = 0; i < this.sourcePath.length - 1; i++) {\n        const step = this.sourcePath[i];\n        if ($dropTarget.is(step.$btn)) {\n          return step.folderId;\n        }\n      }\n\n      // folder in the element listing?\n      return $dropTarget.find('.element:first').data('folder-id') || false;\n    },\n\n    afterInit: function () {\n      if (!this.settings.foldersOnly) {\n        this.initForFiles();\n      }\n\n      this.base();\n    },\n\n    /**\n     * Initialize the uploader.\n     *\n     * @private\n     */\n    initForFiles: function () {\n      if (!this.$uploadButton) {\n        this.$uploadButton = $('<button/>', {\n          type: 'button',\n          class: 'btn submit',\n          'data-icon': 'upload',\n          style: 'position: relative; overflow: hidden;',\n          text: Craft.t('app', 'Upload files'),\n        });\n        this.addButton(this.$uploadButton);\n\n        this.$uploadInput = $(\n          '<input type=\"file\" multiple=\"multiple\" name=\"assets-upload\" />'\n        )\n          .hide()\n          .insertBefore(this.$uploadButton);\n      }\n\n      this.promptHandler = new Craft.PromptHandler();\n      this.progressBar = new Craft.ProgressBar(this.$main, false);\n\n      var options = {\n        url: Craft.getActionUrl('assets/upload'),\n        fileInput: this.$uploadInput,\n        dropZone: this.$container,\n      };\n\n      options.events = {\n        fileuploadstart: this._onUploadStart.bind(this),\n        fileuploadprogressall: this._onUploadProgress.bind(this),\n        fileuploaddone: this._onUploadSuccess.bind(this),\n        fileuploadalways: this._onUploadAlways.bind(this),\n        fileuploadfail: this._onUploadFailure.bind(this),\n      };\n\n      if (\n        this.settings.criteria &&\n        typeof this.settings.criteria.kind !== 'undefined'\n      ) {\n        options.allowedKinds = this.settings.criteria.kind;\n      }\n\n      this._currentUploaderSettings = options;\n\n      this.uploader = new Craft.Uploader(this.$uploadButton, options);\n\n      this.$uploadButton.on('click', () => {\n        if (this.$uploadButton.hasClass('disabled')) {\n          return;\n        }\n        if (!this.isIndexBusy) {\n          this.$uploadButton\n            .parent()\n            .find('input[name=assets-upload]')\n            .trigger('click');\n        }\n      });\n    },\n\n    onSelectSource: function () {\n      if (!this.settings.foldersOnly) {\n        const folderId = this.$source.data('folder-id');\n        if (folderId && Garnish.hasAttr(this.$source, 'data-can-upload')) {\n          this.uploader.setParams({\n            folderId: this.$source.attr('data-folder-id'),\n          });\n          this.$uploadButton.removeClass('disabled');\n        } else {\n          this.$uploadButton.addClass('disabled');\n        }\n      }\n\n      this.base();\n    },\n\n    onSourcePathChange: function () {\n      if (!this.settings.foldersOnly && this.sourcePath.length) {\n        const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n        if (currentFolder.folderId) {\n          if (this.uploader) {\n            this.uploader.setParams({\n              folderId: currentFolder.folderId,\n            });\n          }\n\n          // will the user be allowed to move items in this folder?\n          const canMoveSubItems = !!currentFolder.canMoveSubItems;\n          this.settings.selectable =\n            this.settings.selectable || canMoveSubItems;\n          this.settings.multiSelect =\n            this.settings.multiSelect || canMoveSubItems;\n        }\n      }\n\n      this.base();\n    },\n\n    startSearching: function () {\n      // Does this source have subfolders?\n      if (\n        !this.settings.hideSidebar &&\n        this.sourcePath[this.sourcePath.length - 1].hasChildren\n      ) {\n        if (this.$includeSubfoldersContainer === null) {\n          var id =\n            'includeSubfolders-' + Math.floor(Math.random() * 1000000000);\n\n          this.$includeSubfoldersContainer = $(\n            '<div style=\"margin-bottom: -25px; opacity: 0;\"/>'\n          ).insertAfter(this.$search);\n          var $subContainer = $('<div style=\"padding-top: 5px;\"/>').appendTo(\n            this.$includeSubfoldersContainer\n          );\n          this.$includeSubfoldersCheckbox = $(\n            '<input type=\"checkbox\" id=\"' + id + '\" class=\"checkbox\"/>'\n          ).appendTo($subContainer);\n          $('<label class=\"light smalltext\" for=\"' + id + '\"/>')\n            .text(' ' + Craft.t('app', 'Search in subfolders'))\n            .appendTo($subContainer);\n\n          this.addListener(\n            this.$includeSubfoldersCheckbox,\n            'change',\n            function () {\n              this.setSelecetedSourceState(\n                'includeSubfolders',\n                this.$includeSubfoldersCheckbox.prop('checked')\n              );\n              this.updateElements();\n            }\n          );\n        } else {\n          this.$includeSubfoldersContainer\n            .velocity('stop')\n            .removeClass('hidden');\n        }\n\n        var checked = this.getSelectedSourceState('includeSubfolders', false);\n        this.$includeSubfoldersCheckbox.prop('checked', checked);\n\n        this.$includeSubfoldersContainer.velocity(\n          {\n            marginBottom: 0,\n            opacity: 1,\n          },\n          'fast'\n        );\n\n        this.showingIncludeSubfoldersCheckbox = true;\n      }\n\n      this.base();\n    },\n\n    stopSearching: function () {\n      if (this.showingIncludeSubfoldersCheckbox) {\n        this.$includeSubfoldersContainer.velocity('stop');\n\n        this.$includeSubfoldersContainer.velocity(\n          {\n            marginBottom: -25,\n            opacity: 0,\n          },\n          {\n            duration: 'fast',\n            complete: () => {\n              this.$includeSubfoldersContainer.addClass('hidden');\n            },\n          }\n        );\n\n        this.showingIncludeSubfoldersCheckbox = false;\n      }\n\n      this.base();\n    },\n\n    getViewSettings: function () {\n      const settings = {};\n\n      if (this.settings.context === 'index') {\n        // Allow folders to be selected\n        settings.canSelectElement = () => true;\n      }\n\n      return settings;\n    },\n\n    getViewParams: function () {\n      const data = Object.assign(this.base(), {\n        showFolders: this.settings.showFolders && !this.trashed,\n        foldersOnly: this.settings.foldersOnly,\n      });\n\n      if (\n        this.showingIncludeSubfoldersCheckbox &&\n        this.$includeSubfoldersCheckbox.prop('checked')\n      ) {\n        data.criteria.includeSubfolders = true;\n      }\n\n      return data;\n    },\n\n    /**\n     * React on upload submit.\n     *\n     * @private\n     */\n    _onUploadStart: function () {\n      this.setIndexBusy();\n\n      // Initial values\n      this._positionProgressBar();\n      this.progressBar.resetProgressBar();\n      this.progressBar.showProgressBar();\n\n      this.promptHandler.resetPrompts();\n    },\n\n    /**\n     * Update uploaded byte count.\n     */\n    _onUploadProgress: function (event, data) {\n      var progress = parseInt((data.loaded / data.total) * 100, 10);\n      this.progressBar.setProgressPercentage(progress);\n    },\n\n    /**\n     * On upload success.\n     *\n     * @param {Object} event\n     * @param {Object} data\n     * @private\n     */\n    _onUploadSuccess: function (event, data) {\n      const {result} = data;\n\n      // Add the uploaded file to the selected ones, if appropriate\n      this.selectElementAfterUpdate(result.assetId);\n\n      // If there is a prompt, add it to the queue\n      if (result.conflict) {\n        result.prompt = {\n          message: Craft.t('app', result.conflict, {file: result.filename}),\n          choices: [\n            {value: 'keepBoth', title: Craft.t('app', 'Keep both')},\n            {value: 'replace', title: Craft.t('app', 'Replace it')},\n          ],\n        };\n\n        this.promptHandler.addPrompt(result);\n      }\n\n      Craft.cp.runQueue();\n    },\n\n    /**\n     * On upload complete no matter what (success, fail, or abort).\n     */\n    _onUploadAlways: function () {\n      if (this.uploader.isLastUpload()) {\n        this.progressBar.hideProgressBar();\n        this.setIndexAvailable();\n\n        if (this.promptHandler.getPromptCount()) {\n          this.promptHandler.showBatchPrompts(this._uploadFollowup.bind(this));\n        } else {\n          this._updateAfterUpload();\n        }\n      }\n    },\n\n    /**\n     * On Upload Failure.\n     */\n    _onUploadFailure: function (event, data) {\n      const response = data.response();\n      let {message, filename} = response?.jqXHR?.responseJSON || {};\n\n      if (!message) {\n        message = filename\n          ? Craft.t('app', 'Upload failed for “{filename}”.', {filename})\n          : Craft.t('app', 'Upload failed.');\n      }\n\n      Craft.cp.displayError(message);\n    },\n\n    /**\n     * Update the elements after an upload, setting sort to dateModified descending, if not using index.\n     *\n     * @private\n     */\n    _updateAfterUpload: function () {\n      if (this.settings.context !== 'index') {\n        this.clearSearch();\n        this.setSelectedSortAttribute('dateCreated', 'desc');\n      }\n      this.updateElements();\n    },\n\n    /**\n     * Follow up to an upload that triggered at least one conflict resolution prompt.\n     *\n     * @param {Object} returnData\n     * @private\n     */\n    _uploadFollowup: function (returnData) {\n      this.setIndexBusy();\n      this.progressBar.resetProgressBar();\n\n      this.promptHandler.resetPrompts();\n\n      var finalCallback = () => {\n        this.progressBar.hideProgressBar();\n        this.setIndexAvailable();\n        this._updateAfterUpload();\n      };\n\n      this.progressBar.setItemCount(returnData.length);\n\n      var doFollowup = (parameterArray, parameterIndex, callback) => {\n        var data = {};\n        var action = null;\n\n        const followupAlways = () => {\n          parameterIndex++;\n          this.progressBar.incrementProcessedItemCount(1);\n          this.progressBar.updateProgressBar();\n\n          if (parameterIndex === parameterArray.length) {\n            callback();\n          } else {\n            doFollowup(parameterArray, parameterIndex, callback);\n          }\n        };\n        const followupSuccess = (data) => {\n          if (data.assetId) {\n            this.selectElementAfterUpdate(data.assetId);\n          }\n\n          followupAlways();\n        };\n        const followupFailure = (data) => {\n          Craft.cp.displayError(data.message);\n          followupAlways();\n        };\n\n        if (parameterArray[parameterIndex].choice === 'replace') {\n          action = 'assets/replace-file';\n          data.sourceAssetId = parameterArray[parameterIndex].assetId;\n\n          if (parameterArray[parameterIndex].conflictingAssetId) {\n            data.assetId = parameterArray[parameterIndex].conflictingAssetId;\n          } else {\n            data.targetFilename = parameterArray[parameterIndex].filename;\n          }\n        } else if (parameterArray[parameterIndex].choice === 'cancel') {\n          action = 'assets/delete-asset';\n          data.assetId = parameterArray[parameterIndex].assetId;\n        }\n\n        if (!action) {\n          // We don't really need to do another request, so let's pretend that already happened\n          followupSuccess({\n            assetId: parameterArray[parameterIndex].assetId,\n          });\n        } else {\n          Craft.sendActionRequest('POST', action, {data})\n            .then((response) => followupSuccess(response.data))\n            .catch(({response}) => followupFailure(response.data));\n        }\n      };\n\n      this.progressBar.showProgressBar();\n      doFollowup(returnData, 0, finalCallback);\n    },\n\n    /**\n     * Perform actions after updating elements\n     * @private\n     */\n    onUpdateElements: function () {\n      this._onUpdateElements(false, this.view.getAllElements());\n      this.view.on('appendElements', (ev) => {\n        this._onUpdateElements(true, ev.newElements);\n      });\n\n      this.base();\n    },\n\n    /**\n     * Do the after-update initializations\n     * @private\n     */\n    _onUpdateElements: function (append, $newElements) {\n      this.removeListener(this.$elements, 'keydown');\n      this.addListener(this.$elements, 'keydown', this._onKeyDown.bind(this));\n      this.view.elementSelect.on('focusItem', this._onElementFocus.bind(this));\n\n      this.$listedFolders = $newElements.find(\n        '.element[data-is-folder][data-folder-name]'\n      );\n      for (let i = 0; i < this.$listedFolders.length; i++) {\n        const $folder = this.$listedFolders.eq(i);\n        const $label = $folder.find('.label');\n        const $title = $label.find('.title');\n        const folderId = parseInt($folder.data('folder-id'));\n        const folderName = $folder.data('folder-name');\n        const label = Craft.t('app', '{name} folder', {\n          name: folderName,\n        });\n        if (this.settings.disabledFolderIds.includes(folderId)) {\n          $label.attr('aria-label', label);\n          $newElements.has($folder).addClass('disabled');\n          continue;\n        }\n        const sourcePath = $folder.data('source-path');\n        if (sourcePath) {\n          const $a = $('<a/>', {\n            href: Craft.getCpUrl(sourcePath[sourcePath.length - 1].uri),\n            html: $title.html(),\n            role: 'button',\n            'aria-label': label,\n          });\n          $label.empty().append($a);\n          this.addListener($a, 'activate', (ev) => {\n            this.sourcePath = sourcePath;\n            this.clearSearch(false);\n            this.updateElements().then(() => {\n              const firstFocusableEl = this.$elements.find(\n                ':focusable:not(.selectallcontainer)'\n              )[0];\n              if (firstFocusableEl) {\n                firstFocusableEl.focus();\n              }\n            });\n          });\n        }\n      }\n\n      if (this.itemDrag) {\n        const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n        const canMoveSubItems = !!(\n          currentFolder &&\n          currentFolder.folderId &&\n          currentFolder.canMoveSubItems\n        );\n        if (!canMoveSubItems || !append) {\n          this.itemDrag.removeAllItems();\n        }\n        if (canMoveSubItems) {\n          this.itemDrag.addItems(this._findDraggableItems($newElements));\n        }\n      }\n    },\n\n    /**\n     * Handle a keypress\n     * @private\n     */\n    _onKeyDown: function (ev) {\n      if (ev.keyCode === Garnish.SPACE_KEY && ev.shiftKey) {\n        if (Craft.PreviewFileModal.openInstance) {\n          Craft.PreviewFileModal.openInstance.selfDestruct();\n        } else {\n          var $element = this.view.elementSelect.$focusedItem.find('.element');\n\n          if ($element.length) {\n            this._loadPreview($element);\n          }\n        }\n\n        ev.stopPropagation();\n        return false;\n      }\n    },\n\n    /**\n     * Handle element being focused\n     * @private\n     */\n    _onElementFocus: function (ev) {\n      var $element = $(ev.item).find('.element');\n\n      if (Craft.PreviewFileModal.openInstance && $element.length) {\n        this._loadPreview($element);\n      }\n    },\n\n    /**\n     * Load the preview for an asset\n     * @private\n     */\n    _loadPreview: function ($element) {\n      var settings = {};\n\n      if ($element.data('image-width')) {\n        settings.startingWidth = $element.data('image-width');\n        settings.startingHeight = $element.data('image-height');\n      }\n\n      new Craft.PreviewFileModal(\n        $element.data('id'),\n        this.view.elementSelect,\n        settings\n      );\n    },\n\n    /**\n     * @returns {string}\n     */\n    getSourcePathLabel: function () {\n      return Craft.t('app', 'Volume path');\n    },\n\n    /**\n     * @returns {string}\n     */\n    getSourcePathActionLabel: function () {\n      return Craft.t('app', 'Folder actions');\n    },\n\n    getSourcePathActions: function () {\n      const actions = [];\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n\n      if (currentFolder.canCreate) {\n        actions.push({\n          label: Craft.t('app', 'New subfolder'),\n          onSelect: () => {\n            this._createSubfolder();\n          },\n        });\n      }\n\n      if (this.settings.context === 'index') {\n        if (currentFolder.canRename) {\n          actions.push({\n            label: Craft.t('app', 'Rename folder'),\n            onSelect: () => {\n              this._renameFolder();\n            },\n          });\n\n          if (\n            currentFolder.canMove &&\n            this.getMoveTargetSourceKeys(true).length\n          ) {\n            actions.push({\n              label: Craft.t('app', 'Move folder'),\n              onSelect: () => {\n                this._moveFolder();\n              },\n            });\n          }\n\n          if (currentFolder.canDelete) {\n            actions.push({\n              label: Craft.t('app', 'Delete folder'),\n              destructive: true,\n              onSelect: () => {\n                this._deleteFolder();\n              },\n            });\n          }\n        }\n      }\n\n      return actions;\n    },\n\n    _createSubfolder: function () {\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n      const subfolderName = prompt(\n        Craft.t('app', 'Enter the name of the folder')\n      );\n\n      if (subfolderName) {\n        const data = {\n          parentId: currentFolder.folderId,\n          folderName: subfolderName,\n        };\n\n        this.setIndexBusy();\n\n        Craft.sendActionRequest('POST', 'assets/create-folder', {data})\n          .then((response) => {\n            this.setIndexAvailable();\n            Craft.cp.displayNotice(Craft.t('app', 'Folder created.'));\n            this.updateElements(true);\n          })\n          .catch(({response}) => {\n            this.setIndexAvailable();\n            Craft.cp.displayError(response.data.message);\n          });\n      }\n    },\n\n    _deleteFolder: function () {\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n\n      if (\n        confirm(\n          Craft.t('app', 'Really delete folder “{folder}”?', {\n            folder: currentFolder.label,\n          })\n        )\n      ) {\n        const data = {\n          folderId: currentFolder.folderId,\n        };\n\n        this.setIndexBusy();\n\n        Craft.sendActionRequest('POST', 'assets/delete-folder', {data})\n          .then((response) => {\n            this.setIndexAvailable();\n            Craft.cp.displayNotice(Craft.t('app', 'Folder deleted.'));\n            this.sourcePath = this.sourcePath.slice(\n              0,\n              this.sourcePath.length - 1\n            );\n            this.updateElements();\n          })\n          .catch(({response}) => {\n            this.setIndexAvailable();\n            Craft.cp.displayError(response.data.message);\n          });\n      }\n    },\n\n    /**\n     * Rename\n     */\n    _renameFolder: function () {\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n      const newName = prompt(\n        Craft.t('app', 'Rename folder'),\n        currentFolder.label\n      );\n\n      if (!newName || newName === currentFolder.label) {\n        return;\n      }\n\n      this.setIndexBusy();\n\n      Craft.sendActionRequest('POST', 'assets/rename-folder', {\n        data: {\n          folderId: currentFolder.folderId,\n          newName: newName,\n        },\n      })\n        .then((response) => {\n          Craft.cp.displayNotice(Craft.t('app', 'Folder renamed.'));\n          const sourcePath = this.sourcePath.slice();\n          sourcePath[sourcePath.length - 1].label = response.data.newName;\n          sourcePath[sourcePath.length - 1].uri =\n            sourcePath[sourcePath.length - 2].uri + `/${response.data.newName}`;\n          this.sourcePath = sourcePath;\n        })\n        .catch(({response}) => {\n          Craft.cp.displayError(response.data.message);\n        })\n        .finally(() => {\n          this.setIndexAvailable();\n        });\n    },\n\n    getMoveTargetSourceKeys: function (peerFiles) {\n      const attr = peerFiles\n        ? 'data-can-move-peer-files-to'\n        : 'data-can-move-to';\n      return this.$sources\n        .toArray()\n        .filter((source) => {\n          const volumeHandle = $(source).data('volume-handle');\n          return (\n            volumeHandle &&\n            volumeHandle !== 'temp' &&\n            Garnish.hasAttr(source, attr)\n          );\n        })\n        .map((source) => $(source).data('key'));\n    },\n\n    _moveFolder: function () {\n      const currentFolder = this.sourcePath[this.sourcePath.length - 1];\n      const parentFolder = this.sourcePath[this.sourcePath.length - 2];\n\n      const disabledFolderIds = [currentFolder.folderId];\n      if (parentFolder) {\n        disabledFolderIds.push(parentFolder.folderId);\n      }\n\n      new Craft.VolumeFolderSelectorModal({\n        sources: this.getMoveTargetSourceKeys(true),\n        showTitle: true,\n        modalTitle: Craft.t('app', 'Move to'),\n        selectBtnLabel: Craft.t('app', 'Move'),\n        disabledFolderIds: disabledFolderIds,\n        indexSettings: {\n          defaultSource: this.sourceKey,\n          defaultSourcePath: this.sourcePath.slice(\n            0,\n            this.sourcePath.length - 1\n          ),\n        },\n        onSelect: ([targetFolder]) => {\n          this.$sourcePathActionsBtn.focus();\n          const mover = new Craft.AssetMover();\n          mover\n            .moveFolders([currentFolder.folderId], targetFolder.folderId)\n            .then((totalFoldersMoved) => {\n              if (totalFoldersMoved) {\n                Craft.cp.displayNotice(\n                  Craft.t(\n                    'app',\n                    '{totalItems, plural, =1{Item} other{Items}} moved.',\n                    {\n                      totalItems: totalFoldersMoved,\n                    }\n                  )\n                );\n                this.sourcePath = this.sourcePath.slice(\n                  0,\n                  this.sourcePath.length - 1\n                );\n                this.clearSearch(false);\n                this.updateElements();\n              }\n            });\n        },\n      });\n    },\n\n    _positionProgressBar: function () {\n      if (!this.progressBar) {\n        this.progressBar = new Craft.ProgressBar(this.$main, true);\n      }\n\n      var $container = $(),\n        scrollTop = 0,\n        offset = 0;\n\n      if (this.settings.context === 'index') {\n        $container = this.progressBar.$progressBar.closest('#content');\n        scrollTop = Garnish.$win.scrollTop();\n      } else {\n        $container = this.progressBar.$progressBar.closest('.main');\n        scrollTop = this.$main.scrollTop();\n      }\n\n      var containerTop = $container.offset().top;\n      var diff = scrollTop - containerTop;\n      var windowHeight = Garnish.$win.height();\n\n      if ($container.height() > windowHeight) {\n        offset = windowHeight / 2 - 6 + diff;\n      } else {\n        offset = $container.height() / 2 - 6;\n      }\n\n      if (this.settings.context !== 'index') {\n        offset = scrollTop + ($container.height() / 2 - 6);\n      }\n\n      this.progressBar.$progressBar.css({\n        top: offset,\n      });\n    },\n  },\n  {\n    defaults: {\n      showFolders: true,\n      foldersOnly: false,\n      disabledFolderIds: [],\n    },\n  }\n);\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\Asset', Craft.AssetIndex);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset mover class\n */\nCraft.AssetMover = Garnish.Base.extend({\n  moveAssets: function (assetIds, targetFolderId) {\n    const requests = assetIds.map((assetId) => {\n      return {\n        for: 'asset',\n        action: 'assets/move-asset',\n        params: {\n          assetId,\n          folderId: targetFolderId,\n        },\n      };\n    });\n    return this._batchMoveRequests(requests, {\n      conflictChoices: [\n        {\n          value: 'keepBoth',\n          title: Craft.t('app', 'Keep both'),\n        },\n        {\n          value: 'replace',\n          title: Craft.t('app', 'Replace it'),\n        },\n      ],\n      handleConflictChoice: function (prompt) {\n        const params = {\n          folderId: prompt.request.params.folderId,\n          assetId: prompt.assetId,\n        };\n        switch (prompt.choice) {\n          case 'replace':\n            params.force = true;\n            break;\n          case 'keepBoth':\n            params.filename = prompt.suggestedFilename;\n            break;\n        }\n        return {\n          action: 'assets/move-asset',\n          params,\n        };\n      },\n    });\n  },\n\n  moveFolders: function (folderIds, targetFolderId) {\n    return new Promise((resolve, reject) => {\n      const transferList = [];\n      const folderIdsToDelete = [];\n\n      const requests = folderIds.map((folderId) => {\n        return {\n          for: 'folder',\n          action: 'assets/move-folder',\n          params: {\n            folderId,\n            parentId: targetFolderId,\n          },\n          onSuccess: (response) => {\n            if (response.transferList.length) {\n              transferList.push(...response.transferList);\n            }\n            folderIdsToDelete.push(folderId);\n          },\n        };\n      });\n\n      this._batchMoveRequests(requests, {\n        conflictChoices: [\n          {\n            value: 'replace',\n            title: Craft.t(\n              'app',\n              'Replace the folder (all existing files will be deleted)'\n            ),\n          },\n          {\n            value: 'merge',\n            title: Craft.t(\n              'app',\n              'Merge the folder (any conflicting files will be replaced)'\n            ),\n          },\n        ],\n        handleConflictChoice: function (prompt) {\n          const params = {\n            folderId: prompt.folderId,\n            parentId: prompt.parentId,\n          };\n          switch (prompt.choice) {\n            case 'replace':\n              params.force = true;\n              break;\n            case 'merge':\n              params.merge = true;\n              break;\n          }\n          return {\n            action: 'assets/move-folder',\n            params,\n          };\n        },\n      })\n        .then((totalMoved) => {\n          this._processTransferList(transferList).then(() => {\n            this._deleteFolders(folderIdsToDelete).then(() => {\n              resolve(totalMoved);\n            });\n          });\n        })\n        .catch(reject);\n    });\n  },\n\n  _processTransferList: function (transferList) {\n    return this._batchRequests(\n      transferList.map((params) => {\n        return {\n          action: 'assets/move-asset',\n          params,\n        };\n      })\n    );\n  },\n\n  _deleteFolders: function (folderIds) {\n    return this._batchRequests(\n      folderIds.map((folderId) => {\n        return {\n          action: 'assets/delete-folder',\n          params: {folderId},\n        };\n      })\n    );\n  },\n\n  _batchMoveRequests: function (requests, settings) {\n    return new Promise((resolve) => {\n      let totalMoved = 0;\n\n      this._batchRequests(requests).then((responses) => {\n        Craft.elementIndex.promptHandler.resetPrompts();\n\n        // Loop through all the responses\n        for (const response of responses) {\n          if (response.success) {\n            totalMoved++;\n          }\n\n          // Push prompt into prompt array\n          if (response.conflict) {\n            Craft.elementIndex.promptHandler.addPrompt(\n              Object.assign({}, response, {\n                prompt: {\n                  message: response.conflict,\n                  choices: settings.conflictChoices,\n                },\n              })\n            );\n          }\n\n          if (response.error) {\n            Craft.cp.displayError(response.error);\n          }\n        }\n\n        if (!Craft.elementIndex.promptHandler.getPromptCount()) {\n          resolve(totalMoved);\n          return;\n        }\n\n        Craft.elementIndex.promptHandler.showBatchPrompts((prompts) => {\n          Craft.elementIndex.promptHandler.resetPrompts();\n          const nextRequests = [];\n          for (const prompt of prompts) {\n            if (prompt.choice === 'cancel') {\n              continue;\n            }\n            if (settings.handleConflictChoice) {\n              const nextRequest = settings.handleConflictChoice(prompt);\n              if (prompt.request && prompt.request.onSuccess) {\n                nextRequest.onSuccess = prompt.request.onSuccess;\n              }\n              nextRequests.push(nextRequest);\n            }\n          }\n          this._batchMoveRequests(nextRequests, settings).then(\n            (nextTotalMoved) => {\n              resolve(totalMoved + nextTotalMoved);\n            }\n          );\n        });\n      });\n    });\n  },\n\n  _batchRequests: function (requests) {\n    return new Promise((resolve) => {\n      if (!requests.length) {\n        resolve([]);\n        return;\n      }\n\n      Craft.elementIndex.setIndexBusy();\n      Craft.elementIndex._positionProgressBar();\n      Craft.elementIndex.progressBar.resetProgressBar();\n      Craft.elementIndex.progressBar.setItemCount(requests.length);\n      Craft.elementIndex.progressBar.showProgressBar();\n\n      const responses = [];\n      let activeRequests = requests.length;\n\n      for (const request of requests) {\n        Craft.sendActionRequest('POST', request.action, {\n          data: request.params,\n        })\n          .then((response) => {\n            responses.push(Object.assign({}, response.data, {request}));\n            if (response.data.success && request.onSuccess) {\n              request.onSuccess(response.data);\n            }\n          })\n          .catch((failure) => {\n            if (failure.response && failure.response.data) {\n              responses.push(\n                Object.assign({}, failure.response.data, {request})\n              );\n            }\n          })\n          .finally(() => {\n            // Was that the last one?\n            if (--activeRequests === 0) {\n              Craft.elementIndex.setIndexAvailable();\n              Craft.elementIndex.progressBar.hideProgressBar();\n              // If assets were just merged we should get the reference tags updated right away\n              Craft.cp.runQueue();\n              resolve(responses);\n            } else {\n              Craft.elementIndex.progressBar.incrementProcessedItemCount(1);\n              Craft.elementIndex.progressBar.updateProgressBar();\n            }\n          });\n      }\n    });\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset select input\n */\nCraft.AssetSelectInput = Craft.BaseElementSelectInput.extend({\n  $uploadBtn: null,\n  uploader: null,\n  progressBar: null,\n  openPreviewTimeout: null,\n\n  init: function () {\n    this.base.apply(this, arguments);\n\n    if (this.settings.canUpload) {\n      this._attachUploader();\n    }\n\n    this.updateAddElementsBtn();\n\n    this.addListener(\n      this.$elementsContainer,\n      'keydown',\n      this._onKeyDown.bind(this)\n    );\n    this.elementSelect.on('focusItem', this._onElementFocus.bind(this));\n  },\n\n  /**\n   * Handle a keypress\n   * @private\n   */\n  _onKeyDown: function (ev) {\n    if (ev.keyCode === Garnish.SPACE_KEY && ev.shiftKey) {\n      this.openPreview();\n      ev.stopPropagation();\n      return false;\n    }\n  },\n\n  onAddElements: function () {\n    this.$elements\n      .find('.elementthumb')\n      .addClass('open-preview')\n      .on('click', (ev) => {\n        this.clearOpenPreviewTimeout();\n        this.openPreviewTimeout = setTimeout(() => {\n          this.openPreview();\n          this.openPreviewTimeout = null;\n        }, 500);\n      })\n      .on('dblclick', (ev) => {\n        this.clearOpenPreviewTimeout();\n      });\n    this.base();\n  },\n\n  clearOpenPreviewTimeout: function () {\n    if (this.openPreviewTimeout) {\n      clearTimeout(this.openPreviewTimeout);\n      this.openPreviewTimeout = null;\n    }\n  },\n\n  openPreview: function () {\n    if (Craft.PreviewFileModal.openInstance) {\n      Craft.PreviewFileModal.openInstance.selfDestruct();\n    } else {\n      var $element = this.elementSelect.$focusedItem;\n\n      if ($element.length) {\n        this._loadPreview($element);\n      }\n    }\n  },\n\n  /**\n   * Handle element being focused\n   * @private\n   */\n  _onElementFocus: function (ev) {\n    var $element = $(ev.item);\n\n    if (Craft.PreviewFileModal.openInstance && $element.length) {\n      this._loadPreview($element);\n    }\n  },\n\n  /**\n   * Load the preview for an asset\n   * @private\n   */\n  _loadPreview: function ($element) {\n    var settings = {\n      minGutter: 50,\n    };\n\n    if ($element.data('image-width')) {\n      settings.startingWidth = $element.data('image-width');\n      settings.startingHeight = $element.data('image-height');\n    }\n\n    new Craft.PreviewFileModal(\n      $element.data('id'),\n      this.elementSelect,\n      settings\n    );\n  },\n\n  /**\n   * Attach the uploader with drag event handler\n   */\n  _attachUploader: function () {\n    this.progressBar = new Craft.ProgressBar(\n      $('<div class=\"progress-shade\"></div>').appendTo(this.$container)\n    );\n\n    var options = {\n      url: Craft.getActionUrl('assets/upload'),\n      dropZone: this.$container,\n      formData: {\n        fieldId: this.settings.fieldId,\n      },\n    };\n\n    if (this.settings.sourceElementId) {\n      options.formData.elementId = this.settings.sourceElementId;\n    }\n\n    if (this.settings.criteria.siteId) {\n      options.formData.siteId = this.settings.criteria.siteId;\n    }\n\n    if (this.$addElementBtn) {\n      this.$uploadBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn dashed',\n        'data-icon': 'upload',\n        'aria-label':\n          this.settings.limit == 1\n            ? Craft.t('app', 'Upload a file')\n            : Craft.t('app', 'Upload files'),\n        'aria-describedby': this.settings.describedBy,\n        text:\n          this.settings.limit == 1\n            ? Craft.t('app', 'Upload a file')\n            : Craft.t('app', 'Upload files'),\n      }).insertAfter(this.$addElementBtn);\n      options.fileInput = $('<input/>', {\n        type: 'file',\n        class: 'hidden',\n        multiple: this.settings.limit != 1,\n      }).insertAfter(this.$uploadBtn);\n\n      // Trigger a window resize in case the field is inside an element editor HUD\n      Garnish.$win.trigger('resize');\n    }\n\n    // If CSRF protection isn't enabled, these won't be defined.\n    if (\n      typeof Craft.csrfTokenName !== 'undefined' &&\n      typeof Craft.csrfTokenValue !== 'undefined'\n    ) {\n      // Add the CSRF token\n      options.formData[Craft.csrfTokenName] = Craft.csrfTokenValue;\n    }\n\n    if (typeof this.settings.criteria.kind !== 'undefined') {\n      options.allowedKinds = this.settings.criteria.kind;\n    }\n\n    options.canAddMoreFiles = this.canAddMoreFiles.bind(this);\n\n    options.events = {};\n    options.events.fileuploadstart = this._onUploadStart.bind(this);\n    options.events.fileuploadprogressall = this._onUploadProgress.bind(this);\n    options.events.fileuploaddone = this._onUploadComplete.bind(this);\n    options.events.fileuploadfail = this._onUploadFailure.bind(this);\n\n    this.uploader = new Craft.Uploader(this.$container, options);\n\n    if (this.$uploadBtn) {\n      this.$uploadBtn.on('click', (ev) => {\n        // We can't store a reference to the file input, because it gets replaced with a new input\n        // each time a new file is uploaded - see https://stackoverflow.com/a/25034721/1688568\n        this.$uploadBtn.next('input[type=file]').trigger('click');\n      });\n    }\n  },\n\n  enableAddElementsBtn: function () {\n    if (this.$uploadBtn) {\n      this.$uploadBtn.removeClass('hidden');\n    }\n\n    this.base();\n  },\n\n  disableAddElementsBtn: function () {\n    if (this.$uploadBtn) {\n      this.$uploadBtn.addClass('hidden');\n    }\n\n    this.base();\n  },\n\n  /**\n   * Add the freshly uploaded file to the input field.\n   */\n  selectUploadedFile: function (element) {\n    // Check if we're able to add new elements\n    if (!this.canAddMoreElements()) {\n      return;\n    }\n\n    var $newElement = element.$element;\n\n    // Make a couple tweaks\n    $newElement.addClass('removable');\n    $newElement.prepend(\n      '<input type=\"hidden\" name=\"' +\n        this.settings.name +\n        '[]\" value=\"' +\n        element.id +\n        '\">' +\n        '<a class=\"delete icon\" title=\"' +\n        Craft.t('app', 'Remove') +\n        '\"></a>'\n    );\n\n    $newElement.appendTo(this.$elementsContainer);\n\n    var margin = -($newElement.outerWidth() + 10);\n\n    this.$addElementBtn.css('margin-' + Craft.left, margin + 'px');\n\n    var animateCss = {};\n    animateCss['margin-' + Craft.left] = 0;\n    this.$addElementBtn.velocity(animateCss, 'fast');\n\n    this.addElements($newElement);\n\n    delete this.modal;\n  },\n\n  /**\n   * On upload start.\n   */\n  _onUploadStart: function () {\n    this.progressBar.$progressBar.css({\n      top: Math.round(this.$container.outerHeight() / 2) - 6,\n    });\n\n    this.$container.addClass('uploading');\n    this.progressBar.resetProgressBar();\n    this.progressBar.showProgressBar();\n  },\n\n  /**\n   * On upload progress.\n   */\n  _onUploadProgress: function (event, data) {\n    var progress = parseInt((data.loaded / data.total) * 100, 10);\n    this.progressBar.setProgressPercentage(progress);\n  },\n\n  /**\n   * On a file being uploaded.\n   */\n  _onUploadComplete: function (event, data) {\n    if (data.result.error) {\n      Craft.cp.displayError(data.result.error);\n      this.progressBar.hideProgressBar();\n      this.$container.removeClass('uploading');\n    } else {\n      var parameters = {\n        elementId: data.result.assetId,\n        siteId: this.settings.criteria.siteId,\n        thumbSize: this.settings.viewMode,\n      };\n\n      Craft.sendActionRequest('POST', 'elements/get-element-html', {\n        data: parameters,\n      })\n        .then((response) => {\n          var html = $(response.data.html);\n          Craft.appendHeadHtml(response.data.headHtml);\n          this.selectUploadedFile(Craft.getElementInfo(html));\n\n          // Last file\n          if (this.uploader.isLastUpload()) {\n            this.progressBar.hideProgressBar();\n            this.$container.removeClass('uploading');\n            this.$container.trigger('change');\n          }\n        })\n        .catch(({response}) => {\n          Craft.cp.displayError(response.data.message);\n        });\n\n      Craft.cp.runQueue();\n    }\n  },\n\n  /**\n   * On Upload Failure.\n   */\n  _onUploadFailure: function (event, data) {\n    const response = data.response();\n    let {message, filename} = response?.jqXHR?.responseJSON || {};\n\n    if (!message) {\n      message = filename\n        ? Craft.t('app', 'Upload failed for “{filename}”.', {filename})\n        : Craft.t('app', 'Upload failed.');\n    }\n\n    Craft.cp.displayError(message);\n    this.progressBar.hideProgressBar();\n    this.$container.removeClass('uploading');\n  },\n\n  /**\n   * We have to take into account files about to be added as well\n   */\n  canAddMoreFiles: function (slotsTaken) {\n    return (\n      !this.settings.limit ||\n      this.$elements.length + slotsTaken < this.settings.limit\n    );\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset selector modal class\n */\nCraft.AssetSelectorModal = Craft.BaseElementSelectorModal.extend(\n  {\n    $selectTransformBtn: null,\n    _selectedTransform: null,\n\n    init: function (elementType, settings) {\n      settings = $.extend({}, Craft.AssetSelectorModal.defaults, settings);\n\n      this.base(elementType, settings);\n\n      if (settings.transforms.length) {\n        this.createSelectTransformButton(settings.transforms);\n      }\n    },\n\n    createSelectTransformButton: function (transforms) {\n      if (!transforms || !transforms.length) {\n        return;\n      }\n\n      var $btnGroup = $('<div class=\"btngroup\"/>').appendTo(\n        this.$primaryButtons\n      );\n      this.$selectBtn.appendTo($btnGroup);\n\n      this.$selectTransformBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn menubtn disabled',\n        text: Craft.t('app', 'Select transform'),\n      }).appendTo($btnGroup);\n\n      var $menu = $('<div class=\"menu\" data-align=\"right\"></div>').insertAfter(\n          this.$selectTransformBtn\n        ),\n        $menuList = $('<ul></ul>').appendTo($menu);\n\n      for (var i = 0; i < transforms.length; i++) {\n        $(\n          '<li><a data-transform=\"' +\n            transforms[i].handle +\n            '\">' +\n            transforms[i].name +\n            '</a></li>'\n        ).appendTo($menuList);\n      }\n\n      var MenuButton = new Garnish.MenuBtn(this.$selectTransformBtn, {\n        onOptionSelect: this.onSelectTransform.bind(this),\n      });\n      MenuButton.disable();\n\n      this.$selectTransformBtn.data('menuButton', MenuButton);\n    },\n\n    onSelectionChange: function (ev) {\n      var $selectedElements = this.elementIndex.getSelectedElements(),\n        allowTransforms = false;\n\n      if ($selectedElements.length && this.settings.transforms.length) {\n        allowTransforms = true;\n\n        for (var i = 0; i < $selectedElements.length; i++) {\n          if (!$('.element.hasthumb:first', $selectedElements[i]).length) {\n            break;\n          }\n        }\n      }\n\n      var MenuBtn = null;\n\n      if (this.$selectTransformBtn) {\n        MenuBtn = this.$selectTransformBtn.data('menuButton');\n      }\n\n      if (allowTransforms) {\n        if (MenuBtn) {\n          MenuBtn.enable();\n        }\n\n        this.$selectTransformBtn.removeClass('disabled');\n      } else if (this.$selectTransformBtn) {\n        if (MenuBtn) {\n          MenuBtn.disable();\n        }\n\n        this.$selectTransformBtn.addClass('disabled');\n      }\n\n      this.base();\n    },\n\n    onSelectTransform: function (option) {\n      var transform = $(option).data('transform');\n      this.selectImagesWithTransform(transform);\n    },\n\n    selectImagesWithTransform: function (transform) {\n      // First we must get any missing transform URLs\n      if (\n        typeof Craft.AssetSelectorModal.transformUrls[transform] === 'undefined'\n      ) {\n        Craft.AssetSelectorModal.transformUrls[transform] = {};\n      }\n\n      var $selectedElements = this.elementIndex.getSelectedElements(),\n        imageIdsWithMissingUrls = [];\n\n      for (var i = 0; i < $selectedElements.length; i++) {\n        var $item = $($selectedElements[i]),\n          elementId = Craft.getElementInfo($item).id;\n\n        if (\n          typeof Craft.AssetSelectorModal.transformUrls[transform][\n            elementId\n          ] === 'undefined'\n        ) {\n          imageIdsWithMissingUrls.push(elementId);\n        }\n      }\n\n      if (imageIdsWithMissingUrls.length) {\n        this.showFooterSpinner();\n\n        this.fetchMissingTransformUrls(\n          imageIdsWithMissingUrls,\n          transform,\n          () => {\n            this.hideFooterSpinner();\n            this.selectImagesWithTransform(transform);\n          }\n        );\n      } else {\n        this._selectedTransform = transform;\n        this.selectElements();\n        this._selectedTransform = null;\n      }\n    },\n\n    fetchMissingTransformUrls: function (\n      imageIdsWithMissingUrls,\n      transform,\n      callback\n    ) {\n      var elementId = imageIdsWithMissingUrls.pop();\n\n      var data = {\n        assetId: elementId,\n        handle: transform,\n      };\n\n      Craft.sendActionRequest('POST', 'assets/generate-transform', {data})\n        .then((response) => {\n          Craft.AssetSelectorModal.transformUrls[transform][elementId] =\n            response.data.url || false;\n        })\n        .catch(() => {\n          Craft.AssetSelectorModal.transformUrls[transform][elementId] = false;\n        })\n        .finally(() => {\n          // More to load?\n          if (imageIdsWithMissingUrls.length) {\n            this.fetchMissingTransformUrls(\n              imageIdsWithMissingUrls,\n              transform,\n              callback\n            );\n          } else {\n            callback();\n          }\n        });\n    },\n\n    getElementInfo: function ($selectedElements) {\n      var info = this.base($selectedElements);\n\n      if (this._selectedTransform) {\n        for (var i = 0; i < info.length; i++) {\n          var elementId = info[i].id;\n\n          if (\n            typeof Craft.AssetSelectorModal.transformUrls[\n              this._selectedTransform\n            ][elementId] !== 'undefined' &&\n            Craft.AssetSelectorModal.transformUrls[this._selectedTransform][\n              elementId\n            ] !== false\n          ) {\n            info[i].url =\n              Craft.AssetSelectorModal.transformUrls[this._selectedTransform][\n                elementId\n              ];\n          }\n        }\n      }\n\n      return info;\n    },\n\n    onSelect: function (elementInfo) {\n      this.settings.onSelect(elementInfo, this._selectedTransform);\n    },\n  },\n  {\n    defaults: {\n      canSelectImageTransforms: false,\n      transforms: [],\n    },\n\n    transformUrls: {},\n  }\n);\n\n// Register it!\nCraft.registerElementSelectorModalClass(\n  'craft\\\\elements\\\\Asset',\n  Craft.AssetSelectorModal\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Assets field settings\n */\nCraft.AssetsFieldSettings = Garnish.Base.extend({\n  $useSingleFolderInput: null,\n  $sourceInputs: null,\n  $defaultUploadLocationSelect: null,\n  $defaultUploadLocationOptions: null,\n\n  init: function (\n    useSingleFolderToggleId,\n    sourcesFieldId,\n    defaultUploadLocationId\n  ) {\n    this.$useSingleFolderInput = $(`#${useSingleFolderToggleId}`);\n    this.$sourceInputs = $(`#${sourcesFieldId} input`);\n    this.$defaultUploadLocationSelect = $(`#${defaultUploadLocationId}`);\n    this.$defaultUploadLocationOptions =\n      this.$defaultUploadLocationSelect.children('option');\n    this.updateDefaultUploadLocationSelect();\n\n    // Give CheckboxSelect a chance to register its change event first\n    Garnish.requestAnimationFrame(() => {\n      this.addListener(\n        this.$useSingleFolderInput,\n        'change',\n        'updateDefaultUploadLocationSelect'\n      );\n      this.addListener(\n        this.$sourceInputs,\n        'change',\n        'updateDefaultUploadLocationSelect'\n      );\n    });\n  },\n\n  updateDefaultUploadLocationSelect: function () {\n    if (this.$useSingleFolderInput.prop('checked')) {\n      return;\n    }\n\n    const defaultUploadLocationVal = this.$defaultUploadLocationSelect.val();\n    let firstEnabledValue;\n\n    for (let i = 0; i < this.$sourceInputs.length; i++) {\n      const $input = this.$sourceInputs.eq(i);\n      const val = $input.val();\n      const checked = $input.prop('checked');\n      if (val === '*') {\n        if (checked) {\n          this.$defaultUploadLocationOptions.prop('disabled', false);\n          return;\n        }\n      } else {\n        this.getOption(val).prop('disabled', !checked);\n        if (checked && !firstEnabledValue) {\n          firstEnabledValue = val;\n        }\n      }\n    }\n\n    const $selectedOption = this.getOption(defaultUploadLocationVal);\n    if (\n      !$selectedOption.length ||\n      ($selectedOption.prop('disabled') && firstEnabledValue)\n    ) {\n      this.$defaultUploadLocationSelect.val(firstEnabledValue);\n    }\n  },\n\n  getOption: function (val) {\n    return this.$defaultUploadLocationOptions.filter(`[value=\"${val}\"]`);\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * AuthManager class\n */\nCraft.AuthManager = Garnish.Base.extend(\n  {\n    remainingSessionTime: null,\n    checkRemainingSessionTimer: null,\n    showLoginModalTimer: null,\n    decrementLogoutWarningInterval: null,\n\n    showingLogoutWarningModal: false,\n    showingLoginModal: false,\n\n    logoutWarningModal: null,\n    loginModal: null,\n\n    $logoutWarningPara: null,\n    $passwordInput: null,\n    $loginBtn: null,\n    $loginErrorPara: null,\n\n    submitLoginIfLoggedOut: false,\n\n    /**\n     * Init\n     */\n    init: function () {\n      if (Craft.username) {\n        this.updateRemainingSessionTime(Craft.remainingSessionTime);\n      }\n    },\n\n    /**\n     * Sets a timer for the next time to check the auth timeout.\n     */\n    setCheckRemainingSessionTimer: function (seconds) {\n      if (this.checkRemainingSessionTimer) {\n        clearTimeout(this.checkRemainingSessionTimer);\n      }\n\n      this.checkRemainingSessionTimer = setTimeout(\n        this.checkRemainingSessionTime.bind(this),\n        seconds * 1000\n      );\n    },\n\n    /**\n     * Pings the server to see how many seconds are left on the current user session, and handles the response.\n     */\n    checkRemainingSessionTime: function (extendSession) {\n      $.ajax({\n        url: Craft.getActionUrl(\n          'users/session-info',\n          extendSession ? null : 'dontExtendSession=1'\n        ),\n        type: 'GET',\n        dataType: 'json',\n        complete: (jqXHR, textStatus) => {\n          if (textStatus === 'success') {\n            if (\n              typeof jqXHR.responseJSON.csrfTokenValue !== 'undefined' &&\n              typeof Craft.csrfTokenValue !== 'undefined'\n            ) {\n              Craft.csrfTokenValue = jqXHR.responseJSON.csrfTokenValue;\n            }\n\n            this.updateRemainingSessionTime(jqXHR.responseJSON.timeout);\n            this.submitLoginIfLoggedOut = false;\n          } else {\n            this.updateRemainingSessionTime(-1);\n          }\n        },\n      });\n    },\n\n    /**\n     * Updates our record of the auth timeout, and handles it.\n     */\n    updateRemainingSessionTime: function (remainingSessionTime) {\n      this.remainingSessionTime = parseInt(remainingSessionTime);\n\n      // Are we within the warning window?\n      if (\n        this.remainingSessionTime !== -1 &&\n        this.remainingSessionTime < Craft.AuthManager.minSafeSessionTime\n      ) {\n        // Is there still time to renew the session?\n        if (this.remainingSessionTime) {\n          if (!this.showingLogoutWarningModal) {\n            // Show the warning modal\n            this.showLogoutWarningModal();\n          }\n\n          // Will the session expire before the next checkup?\n          if (this.remainingSessionTime < Craft.AuthManager.checkInterval) {\n            if (this.showLoginModalTimer) {\n              clearTimeout(this.showLoginModalTimer);\n            }\n\n            this.showLoginModalTimer = setTimeout(\n              this.showLoginModal.bind(this),\n              this.remainingSessionTime * 1000\n            );\n          }\n        } else {\n          if (this.showingLoginModal) {\n            if (this.submitLoginIfLoggedOut) {\n              this.submitLogin();\n            }\n          } else {\n            // Show the login modal\n            this.showLoginModal();\n          }\n        }\n\n        this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval);\n      } else {\n        // Everything's good!\n        this.hideLogoutWarningModal();\n        this.hideLoginModal();\n\n        // Will be be within the minSafeSessionTime before the next update?\n        if (\n          this.remainingSessionTime !== -1 &&\n          this.remainingSessionTime <\n            Craft.AuthManager.minSafeSessionTime +\n              Craft.AuthManager.checkInterval\n        ) {\n          this.setCheckRemainingSessionTimer(\n            this.remainingSessionTime - Craft.AuthManager.minSafeSessionTime + 1\n          );\n        } else {\n          this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval);\n        }\n      }\n    },\n\n    /**\n     * Shows the logout warning modal.\n     */\n    showLogoutWarningModal: function () {\n      var quickShow;\n\n      if (this.showingLoginModal) {\n        this.hideLoginModal(true);\n        quickShow = true;\n      } else {\n        quickShow = false;\n      }\n\n      this.showingLogoutWarningModal = true;\n\n      if (!this.logoutWarningModal) {\n        let $form = $(\n          '<form id=\"logoutwarningmodal\" class=\"modal alert fitted\"/>'\n        );\n        let $body = $('<div class=\"body\"/>').appendTo($form);\n        let $buttons = $('<div class=\"buttons right\"/>').appendTo($body);\n        let $logoutBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Sign out now'),\n        }).appendTo($buttons);\n        let $renewSessionBtn = $('<button/>', {\n          type: 'submit',\n          class: 'btn submit',\n          text: Craft.t('app', 'Keep me signed in'),\n        }).appendTo($buttons);\n\n        this.$logoutWarningPara = $('<p/>').prependTo($body);\n\n        this.logoutWarningModal = new Garnish.Modal($form, {\n          autoShow: false,\n          closeOtherModals: false,\n          hideOnEsc: false,\n          hideOnShadeClick: false,\n          shadeClass: 'modal-shade dark logoutwarningmodalshade',\n          onFadeIn: function () {\n            if (!Garnish.isMobileBrowser(true)) {\n              // Auto-focus the renew button\n              setTimeout(function () {\n                $renewSessionBtn.trigger('focus');\n              }, 100);\n            }\n          },\n        });\n\n        this.addListener($logoutBtn, 'activate', 'logout');\n        this.addListener($form, 'submit', 'renewSession');\n      }\n\n      if (quickShow) {\n        this.logoutWarningModal.quickShow();\n      } else {\n        this.logoutWarningModal.show();\n      }\n\n      this.updateLogoutWarningMessage();\n\n      this.decrementLogoutWarningInterval = setInterval(\n        this.decrementLogoutWarning.bind(this),\n        1000\n      );\n    },\n\n    /**\n     * Updates the logout warning message indicating that the session is about to expire.\n     */\n    updateLogoutWarningMessage: function () {\n      this.$logoutWarningPara.text(\n        Craft.t('app', 'Your session will expire in {time}.', {\n          time: Craft.secondsToHumanTimeDuration(this.remainingSessionTime),\n        })\n      );\n\n      this.logoutWarningModal.updateSizeAndPosition();\n    },\n\n    decrementLogoutWarning: function () {\n      if (this.remainingSessionTime > 0) {\n        this.remainingSessionTime--;\n        this.updateLogoutWarningMessage();\n      }\n\n      if (this.remainingSessionTime === 0) {\n        clearInterval(this.decrementLogoutWarningInterval);\n      }\n    },\n\n    /**\n     * Hides the logout warning modal.\n     */\n    hideLogoutWarningModal: function (quick) {\n      this.showingLogoutWarningModal = false;\n\n      if (this.logoutWarningModal) {\n        if (quick) {\n          this.logoutWarningModal.quickHide();\n        } else {\n          this.logoutWarningModal.hide();\n        }\n\n        if (this.decrementLogoutWarningInterval) {\n          clearInterval(this.decrementLogoutWarningInterval);\n        }\n      }\n    },\n\n    /**\n     * Shows the login modal.\n     */\n    showLoginModal: function () {\n      var quickShow;\n\n      if (this.showingLogoutWarningModal) {\n        this.hideLogoutWarningModal(true);\n        quickShow = true;\n      } else {\n        quickShow = false;\n      }\n\n      this.showingLoginModal = true;\n\n      if (!this.loginModal) {\n        var $form = $('<form id=\"loginmodal\" class=\"modal alert fitted\"/>'),\n          $body = $(\n            '<div class=\"body\"><h2>' +\n              Craft.t('app', 'Your session has ended.') +\n              '</h2><p>' +\n              Craft.t('app', 'Enter your password to log back in.') +\n              '</p></div>'\n          ).appendTo($form),\n          $inputContainer = $('<div class=\"inputcontainer\">').appendTo($body),\n          $inputsFlexContainer = $('<div class=\"flex\"/>').appendTo(\n            $inputContainer\n          ),\n          $passwordContainer = $('<div class=\"flex-grow\"/>').appendTo(\n            $inputsFlexContainer\n          ),\n          $buttonContainer = $('<div/>').appendTo($inputsFlexContainer),\n          $passwordWrapper = $('<div class=\"passwordwrapper\"/>').appendTo(\n            $passwordContainer\n          );\n\n        this.$passwordInput = $(\n          '<input type=\"password\" class=\"text password fullwidth\" autocomplete=\"current-password\" placeholder=\"' +\n            Craft.t('app', 'Password') +\n            '\"/>'\n        ).appendTo($passwordWrapper);\n        this.$loginBtn = Craft.ui\n          .createSubmitButton({\n            class: 'disabled',\n            label: Craft.t('app', 'Sign in'),\n            spinner: true,\n          })\n          .attr('aria-disabled', 'true')\n          .appendTo($buttonContainer);\n        this.$loginErrorPara = $('<p class=\"error\"/>').appendTo($body);\n\n        this.loginModal = new Garnish.Modal($form, {\n          autoShow: false,\n          closeOtherModals: false,\n          hideOnEsc: false,\n          hideOnShadeClick: false,\n          shadeClass: 'modal-shade dark loginmodalshade',\n          onFadeIn: () => {\n            if (!Garnish.isMobileBrowser(true)) {\n              // Auto-focus the password input\n              setTimeout(() => {\n                this.$passwordInput.trigger('focus');\n              }, 100);\n            }\n          },\n          onFadeOut: () => {\n            this.$passwordInput.val('');\n          },\n        });\n\n        new Craft.PasswordInput(this.$passwordInput, {\n          onToggleInput: ($newPasswordInput) => {\n            this.$passwordInput = $newPasswordInput;\n          },\n        });\n\n        this.addListener(this.$passwordInput, 'input', 'validatePassword');\n        this.addListener($form, 'submit', 'login');\n      }\n\n      if (quickShow) {\n        this.loginModal.quickShow();\n      } else {\n        this.loginModal.show();\n      }\n    },\n\n    /**\n     * Hides the login modal.\n     */\n    hideLoginModal: function (quick) {\n      this.showingLoginModal = false;\n\n      if (this.loginModal) {\n        if (quick) {\n          this.loginModal.quickHide();\n        } else {\n          this.loginModal.hide();\n        }\n      }\n    },\n\n    logout: function () {\n      $.get({\n        url: Craft.getActionUrl('users/logout'),\n        dataType: 'json',\n        success: () => {\n          Craft.redirectTo('');\n        },\n      });\n    },\n\n    renewSession: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      this.hideLogoutWarningModal();\n      this.checkRemainingSessionTime(true);\n    },\n\n    validatePassword: function () {\n      if (this.$passwordInput.val().length >= 6) {\n        this.$loginBtn.removeClass('disabled');\n        this.$loginBtn.removeAttr('aria-disabled');\n        return true;\n      } else {\n        this.$loginBtn.addClass('disabled');\n        this.$loginBtn.attr('aria-disabled', 'true');\n        return false;\n      }\n    },\n\n    login: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      if (this.validatePassword()) {\n        this.$loginBtn.addClass('loading');\n        this.clearLoginError();\n\n        if (typeof Craft.csrfTokenValue !== 'undefined') {\n          // Check the auth status one last time before sending this off,\n          // in case the user has already logged back in from another window/tab\n          this.submitLoginIfLoggedOut = true;\n          this.checkRemainingSessionTime();\n        } else {\n          this.submitLogin();\n        }\n      }\n    },\n\n    submitLogin: function () {\n      var data = {\n        loginName: Craft.username,\n        password: this.$passwordInput.val(),\n      };\n\n      Craft.sendActionRequest('POST', 'users/login', {data})\n        .then((response) => {\n          this.$loginBtn.removeClass('loading');\n          this.hideLoginModal();\n          this.checkRemainingSessionTime();\n        })\n        .catch(({response}) => {\n          this.$loginBtn.removeClass('loading');\n          this.showLoginError(response.data.message || null);\n          Garnish.shake(this.loginModal.$container);\n\n          if (!Garnish.isMobileBrowser(true)) {\n            this.$passwordInput.trigger('focus');\n          }\n        });\n    },\n\n    showLoginError: function (error) {\n      if (error === null || typeof error === 'undefined') {\n        error = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.$loginErrorPara.text(error);\n      this.loginModal.updateSizeAndPosition();\n    },\n\n    clearLoginError: function () {\n      this.showLoginError('');\n    },\n  },\n  {\n    checkInterval: 60,\n    minSafeSessionTime: 120,\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Element index class\n */\nCraft.BaseElementIndex = Garnish.Base.extend(\n  {\n    initialized: false,\n    elementType: null,\n    idPrefix: null,\n\n    instanceState: null,\n    sourceStates: null,\n    sourceStatesStorageKey: null,\n\n    searchTimeout: null,\n    sourceSelect: null,\n\n    $container: null,\n    $main: null,\n    isIndexBusy: false,\n\n    $sidebar: null,\n    showingSidebar: null,\n    sourceKey: null,\n    rootSourceKey: null,\n    sourceViewModes: null,\n    $source: null,\n    $rootSource: null,\n    sourcesByKey: null,\n    $visibleSources: null,\n\n    $sourceActionsContainer: null,\n    $sourceActionsBtn: null,\n\n    $toolbar: null,\n    toolbarOffset: null,\n\n    $searchContainer: null,\n    $search: null,\n    $filterBtn: null,\n    searching: false,\n    searchText: null,\n    sortByScore: null,\n    trashed: false,\n    drafts: false,\n    $clearSearchBtn: null,\n\n    $statusMenuBtn: null,\n    $statusMenuContainer: null,\n    statusMenu: null,\n    status: null,\n\n    $siteMenuBtn: null,\n    siteMenu: null,\n    siteId: null,\n\n    _sourcePath: null,\n    $sourcePathOuterContainer: null,\n    $sourcePathInnerContainer: null,\n    $sourcePathOverflowBtnContainer: null,\n    $sourcePathActionsBtn: null,\n\n    $elements: null,\n    $updateSpinner: null,\n    $viewModeBtnContainer: null,\n    viewModeBtns: null,\n    _viewMode: null,\n    view: null,\n    _autoSelectElements: null,\n    $countSpinner: null,\n    $countContainer: null,\n    $actionsContainer: null,\n    page: 1,\n    resultSet: null,\n    totalResults: null,\n    $exportBtn: null,\n\n    actions: null,\n    actionsHeadHtml: null,\n    actionsBodyHtml: null,\n    $selectAllContainer: null,\n    $selectAllCheckbox: null,\n    showingActionTriggers: false,\n    exporters: null,\n    exportersByType: null,\n    _$triggers: null,\n\n    _cancelToken: null,\n\n    viewMenus: null,\n    activeViewMenu: null,\n    filterHuds: null,\n\n    _activeElement: null,\n\n    get viewMode() {\n      if (this._viewMode === 'structure' && !this.canSortByStructure()) {\n        return 'table';\n      }\n      return this._viewMode;\n    },\n\n    set viewMode(viewMode) {\n      this._viewMode = viewMode;\n    },\n\n    /**\n     * Constructor\n     */\n    init: function (elementType, $container, settings) {\n      this.elementType = elementType;\n      this.$container = $container;\n      this.setSettings(settings, Craft.BaseElementIndex.defaults);\n\n      // Define an ID prefix that can be used for dynamically created elements\n      // ---------------------------------------------------------------------\n\n      this.idPrefix = Craft.randomString(10);\n\n      // Set the state objects\n      // ---------------------------------------------------------------------\n\n      this.instanceState = this.getDefaultInstanceState();\n\n      this.sourceStates = {};\n\n      // Instance states (selected source) are stored by a custom storage key defined in the settings\n      if (this.settings.storageKey) {\n        $.extend(\n          this.instanceState,\n          Craft.getLocalStorage(this.settings.storageKey),\n          {}\n        );\n      }\n\n      // Source states (view mode, etc.) are stored by the element type and context\n      this.sourceStatesStorageKey =\n        'BaseElementIndex.' + this.elementType + '.' + this.settings.context;\n      $.extend(\n        this.sourceStates,\n        Craft.getLocalStorage(this.sourceStatesStorageKey, {})\n      );\n\n      // Find the DOM elements\n      // ---------------------------------------------------------------------\n\n      this.$main = this.$container.find('.main');\n      this.$toolbar = this.$container.find(this.settings.toolbarSelector);\n      this.$statusMenuBtn = this.$toolbar.find('.statusmenubtn:first');\n      this.$statusMenuContainer = this.$statusMenuBtn.parent();\n      this.$siteMenuBtn = this.$container.find('.sitemenubtn:first');\n\n      this.$searchContainer = this.$toolbar.find('.search-container:first');\n      this.$search = this.$searchContainer.children('input:first');\n      this.$filterBtn = this.$searchContainer.children('.filter-btn:first');\n      this.$clearSearchBtn = this.$searchContainer.children('.clear-btn:first');\n\n      this.$sidebar = this.$container.find('.sidebar:first');\n      this.$sourceActionsContainer = this.$sidebar.find('#source-actions');\n\n      this.$elements = this.$container.find('.elements:first');\n      this.$updateSpinner = this.$elements.find('.spinner');\n\n      if (!this.$updateSpinner.length) {\n        this.$updateSpinner = $('<div/>', {\n          class: 'update-spinner spinner spinner-absolute',\n        }).appendTo(this.$elements);\n      }\n\n      this.$countSpinner = this.$container.find('#count-spinner');\n      this.$countContainer = this.$container.find('#count-container');\n      this.$actionsContainer = this.$container.find('#actions-container');\n      this.$exportBtn = this.$container.find('#export-btn');\n\n      // Hide sidebar if needed\n      if (this.settings.hideSidebar) {\n        this.$sidebar.hide();\n        $('.body, .content', this.$container).removeClass('has-sidebar');\n      }\n\n      // Initialize the sources\n      // ---------------------------------------------------------------------\n\n      if (!this.initSources()) {\n        return;\n      }\n\n      // Initialize the status menu\n      // ---------------------------------------------------------------------\n\n      if (this.$statusMenuBtn.length) {\n        this.statusMenu = this.$statusMenuBtn.menubtn().data('menubtn').menu;\n        this.statusMenu.on('optionselect', this._handleStatusChange.bind(this));\n      }\n\n      // Initialize the site menu\n      // ---------------------------------------------------------------------\n\n      // Is there a site menu?\n      if (this.$siteMenuBtn.length) {\n        this.siteMenu = this.$siteMenuBtn.menubtn().data('menubtn').menu;\n\n        // Figure out the initial site\n        var $option = this.siteMenu.$options.filter('.sel:first');\n\n        if (!$option.length) {\n          $option = this.siteMenu.$options.first();\n        }\n\n        if ($option.length) {\n          this._setSite($option.data('site-id'));\n        } else {\n          // No site options -- they must not have any site permissions\n          this.settings.criteria = {id: '0'};\n        }\n\n        this.siteMenu.on('optionselect', this._handleSiteChange.bind(this));\n\n        if (this.siteId) {\n          // Should we be using a different default site?\n          var defaultSiteId =\n            this.settings.defaultSiteId || Craft.cp.getSiteId();\n\n          if (defaultSiteId && defaultSiteId != this.siteId) {\n            // Is that one available here?\n            var $storedSiteOption = this.siteMenu.$options.filter(\n              '[data-site-id=\"' + defaultSiteId + '\"]:first'\n            );\n\n            if ($storedSiteOption.length) {\n              // Todo: switch this to siteMenu.selectOption($storedSiteOption) once Menu is updated to support that\n              $storedSiteOption.trigger('click');\n            }\n          }\n        }\n      } else if (\n        this.settings.criteria &&\n        this.settings.criteria.siteId &&\n        this.settings.criteria.siteId !== '*'\n      ) {\n        this._setSite(this.settings.criteria.siteId);\n      } else {\n        this._setSite(Craft.siteId);\n      }\n\n      // Don't let the criteria override the selected site\n      if (this.settings.criteria && this.settings.criteria.siteId) {\n        delete this.settings.criteria.siteId;\n      }\n\n      // Initialize the search input\n      // ---------------------------------------------------------------------\n\n      // Automatically update the elements after new search text has been sitting for a 1/2 second\n      this.addListener(this.$search, 'input', () => {\n        if (!this.searching && this.$search.val()) {\n          this.startSearching();\n        } else if (this.searching && !this.$search.val()) {\n          this.stopSearching();\n        }\n\n        if (this.searchTimeout) {\n          clearTimeout(this.searchTimeout);\n        }\n\n        this.searchTimeout = setTimeout(\n          this.updateElementsIfSearchTextChanged.bind(this),\n          500\n        );\n      });\n\n      // Update the elements when the Return key is pressed\n      this.addListener(this.$search, 'keypress', (ev) => {\n        if (ev.keyCode === Garnish.RETURN_KEY) {\n          ev.preventDefault();\n\n          if (this.searchTimeout) {\n            clearTimeout(this.searchTimeout);\n          }\n\n          this.updateElementsIfSearchTextChanged();\n        }\n      });\n\n      // Clear the search when the X button is clicked\n      this.addListener(this.$clearSearchBtn, 'click', () => {\n        this.clearSearch(true);\n\n        if (!Garnish.isMobileBrowser(true)) {\n          this.$search.trigger('focus');\n        }\n      });\n\n      // Auto-focus the Search box\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$search.trigger('focus');\n      }\n\n      // View menus\n      this.viewMenus = {};\n\n      // Filter HUDs\n      this.filterHuds = {};\n      this.addListener(this.$filterBtn, 'click', 'showFilterHud');\n\n      // Set the default status\n      // ---------------------------------------------------------------------\n\n      const queryParams =\n        this.settings.context === 'index' ? Craft.getQueryParams() : {};\n\n      if (queryParams.status) {\n        let selector;\n        switch (queryParams.status) {\n          case 'trashed':\n            selector = '[data-trashed]';\n            break;\n          case 'drafts':\n            selector = '[data-drafts]';\n            break;\n          default:\n            selector = `[data-status=\"${queryParams.status}\"]`;\n        }\n\n        const $option = this.statusMenu.$options.filter(selector);\n        if ($option.length) {\n          this.statusMenu.selectOption($option[0]);\n        } else {\n          Craft.setQueryParam('status', null);\n        }\n      }\n\n      // Initialize the Export button\n      // ---------------------------------------------------------------------\n\n      this.addListener(this.$exportBtn, 'click', '_showExportHud');\n\n      // Let everyone know that the UI is initialized\n      // ---------------------------------------------------------------------\n\n      this.initialized = true;\n      this.afterInit();\n\n      // Select the initial source + source path\n      // ---------------------------------------------------------------------\n\n      this.selectDefaultSource();\n\n      const sourcePath = this.getDefaultSourcePath();\n      if (sourcePath !== null) {\n        this.sourcePath = sourcePath;\n      }\n      if (this.settings.context === 'index') {\n        this.addListener(Garnish.$win, 'resize', 'handleResize');\n      }\n      this.handleResize();\n\n      // Respect initial search\n      // ---------------------------------------------------------------------\n      // Has to go after selecting the default source because selecting a source\n      // clears out search params\n\n      if (queryParams.search) {\n        this.startSearching();\n        this.searchText = queryParams.search;\n      }\n\n      // Select the default sort attribute/direction\n      // ---------------------------------------------------------------------\n\n      if (queryParams.sort) {\n        const lastDashPos = queryParams.sort.lastIndexOf('-');\n        if (lastDashPos !== -1) {\n          const attr = queryParams.sort.substring(0, lastDashPos);\n          const dir = queryParams.sort.substring(lastDashPos + 1);\n          this.setSelectedSortAttribute(attr, dir);\n        }\n      }\n\n      // Load the first batch of elements!\n      // ---------------------------------------------------------------------\n\n      // Default to whatever page is in the URL\n      this.setPage(Craft.pageNum);\n\n      this.updateElements(true);\n    },\n\n    afterInit: function () {\n      this.onAfterInit();\n    },\n\n    handleResize: function () {\n      if (this.sourcePath.length && this.settings.showSourcePath) {\n        this._updateSourcePathVisibility();\n      }\n    },\n\n    _createCancelToken: function () {\n      this._cancelToken = axios.CancelToken.source();\n      return this._cancelToken.token;\n    },\n\n    _cancelRequests: function () {\n      if (this._cancelToken) {\n        this._cancelToken.cancel();\n      }\n    },\n\n    getSourceContainer: function () {\n      return this.$sidebar.find('nav > ul');\n    },\n\n    get $sources() {\n      if (!this.sourceSelect) {\n        return undefined;\n      }\n\n      return this.sourceSelect.$items;\n    },\n\n    getSite: function () {\n      if (!this.siteId) {\n        return undefined;\n      }\n      return Craft.sites.find((s) => s.id == this.siteId);\n    },\n\n    initSources: function () {\n      var $sources = this._getSourcesInList(this.getSourceContainer(), true);\n\n      // No source, no party.\n      if ($sources.length === 0) {\n        return false;\n      }\n\n      // The source selector\n      if (!this.sourceSelect) {\n        this.sourceSelect = new Garnish.Select(this.$sidebar.find('nav'), {\n          multi: false,\n          allowEmpty: false,\n          vertical: true,\n          onSelectionChange: this._handleSourceSelectionChange.bind(this),\n        });\n      }\n\n      this.sourcesByKey = {};\n\n      for (let i = 0; i < $sources.length; i++) {\n        this.initSource($($sources[i]));\n      }\n\n      return true;\n    },\n\n    selectDefaultSource: function () {\n      // The `source` query param should always take precedence\n      let sourceKey;\n      if (this.settings.context === 'index') {\n        sourceKey = Craft.getQueryParam('source');\n      }\n\n      if (!sourceKey) {\n        sourceKey = this.getDefaultSourceKey();\n      }\n\n      let $source;\n\n      if (sourceKey) {\n        $source = this.getSourceByKey(sourceKey);\n\n        // Make sure it's visible\n        if (this.$visibleSources.index($source) === -1) {\n          $source = null;\n        }\n      }\n\n      if (!sourceKey || !$source) {\n        // Select the first source by default\n        $source = this.$visibleSources.first();\n      }\n\n      return this.selectSource($source);\n    },\n\n    refreshSources: function () {\n      this.sourceSelect.removeAllItems();\n\n      this.setIndexBusy();\n\n      Craft.sendActionRequest('POST', this.settings.refreshSourcesAction, {\n        data: {\n          context: this.settings.context,\n          elementType: this.elementType,\n        },\n      })\n        .then((response) => {\n          this.setIndexAvailable();\n          this.getSourceContainer().replaceWith(response.data.html);\n          this.initSources();\n          this.selectDefaultSource();\n        })\n        .catch((e) => {\n          if (!axios.isCancel(e)) {\n            this.setIndexAvailable();\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n          }\n        });\n    },\n\n    initSource: function ($source) {\n      this.sourceSelect.addItems($source);\n      this.initSourceToggle($source);\n      this.sourcesByKey[$source.data('key')] = $source;\n\n      if (\n        $source.data('hasNestedSources') &&\n        this.instanceState.expandedSources.indexOf($source.data('key')) !== -1\n      ) {\n        this._expandSource($source);\n      }\n    },\n\n    initSourceToggle: function ($source) {\n      // Remove handlers for the same thing. Just in case.\n      this.deinitSourceToggle($source);\n\n      var $toggle = this._getSourceToggle($source);\n\n      if ($toggle.length) {\n        this.addListener($source, 'dblclick', '_handleSourceDblClick');\n        this.addListener($toggle, 'click', '_handleSourceToggleClick');\n        $source.data('hasNestedSources', true);\n      } else {\n        $source.data('hasNestedSources', false);\n      }\n    },\n\n    deinitSource: function ($source) {\n      this.sourceSelect.removeItems($source);\n      this.deinitSourceToggle($source);\n      delete this.sourcesByKey[$source.data('key')];\n    },\n\n    deinitSourceToggle: function ($source) {\n      if ($source.data('hasNestedSources')) {\n        this.removeListener($source, 'dblclick');\n        this.removeListener(this._getSourceToggle($source), 'click');\n      }\n\n      $source.removeData('hasNestedSources');\n    },\n\n    getDefaultInstanceState: function () {\n      return {\n        selectedSource: null,\n        expandedSources: [],\n      };\n    },\n\n    getDefaultSourceKey: function () {\n      let sourceKey = null;\n\n      if (this.settings.defaultSource) {\n        let $lastSource = null;\n        let refreshSources = false;\n\n        for (const segment of this.settings.defaultSource.split('/')) {\n          if ($lastSource) {\n            this._expandSource($lastSource);\n            refreshSources = true;\n          }\n\n          const testSourceKey =\n            (sourceKey !== null ? `${sourceKey}/` : '') + segment;\n          const $source = this.getSourceByKey(testSourceKey);\n\n          if (!$source) {\n            if ($lastSource) {\n              this._collapseSource($lastSource);\n            }\n            break;\n          }\n\n          $lastSource = $source;\n          sourceKey = testSourceKey;\n        }\n\n        if (refreshSources) {\n          // Make sure that the modal is aware of the newly expanded sources\n          this._setSite(this.siteId);\n        }\n      }\n\n      return sourceKey ?? this.instanceState.selectedSource;\n    },\n\n    /**\n     * @returns {Object[]|null}\n     */\n    getDefaultSourcePath: function () {\n      // @link https://github.com/craftcms/cms/issues/13006\n      if (\n        this.settings.defaultSourcePath !== null &&\n        this.settings.defaultSourcePath[0] !== undefined &&\n        this.settings.defaultSourcePath[0].canView === true &&\n        ((this.sourcePath.length > 0 &&\n          this.sourcePath[0].handle ===\n            this.settings.defaultSourcePath[0].handle) ||\n          this.sourcePath.length === 0)\n      ) {\n        return this.settings.defaultSourcePath;\n      } else {\n        return null;\n      }\n    },\n\n    getDefaultExpandedSources: function () {\n      return this.instanceState.expandedSources;\n    },\n\n    /**\n     * @returns {Object[]}\n     */\n    get sourcePath() {\n      return this._sourcePath || [];\n    },\n\n    /**\n     * @param {Object[]|null} sourcePath\n     */\n    set sourcePath(sourcePath) {\n      this._sourcePath = sourcePath && sourcePath.length ? sourcePath : null;\n\n      if (this.$sourcePathOuterContainer) {\n        this.$sourcePathOuterContainer.remove();\n        this.$sourcePathOuterContainer = null;\n        this.$sourcePathInnerContainer = null;\n        this.$sourcePathOverflowBtnContainer = null;\n        this.$sourcePathActionsBtn = null;\n      }\n\n      if (this._sourcePath && this.settings.showSourcePath) {\n        const actions = this.getSourcePathActions();\n\n        this.$sourcePathOuterContainer = $('<div/>', {\n          class: 'source-path',\n        }).insertBefore(this.$elements);\n        this.$sourcePathInnerContainer = $('<div/>', {\n          class: 'chevron-btns',\n        }).appendTo(this.$sourcePathOuterContainer);\n        const $nav = $('<nav/>', {\n          'aria-label': this.getSourcePathLabel(),\n        }).appendTo(this.$sourcePathInnerContainer);\n        const $ol = $('<ol/>').appendTo($nav);\n\n        let $overflowBtn, overflowMenuId, $overflowUl;\n\n        if (sourcePath.length > 1) {\n          this.$sourcePathOverflowBtnContainer = $('<li/>', {\n            class: 'first-step hidden',\n          }).appendTo($ol);\n\n          overflowMenuId = 'menu' + Math.floor(Math.random() * 1000000);\n          $overflowBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn',\n            title: Craft.t('app', 'More items'),\n            'aria-label': Craft.t('app', 'More items'),\n            'data-disclosure-trigger': true,\n            'aria-controls': overflowMenuId,\n          })\n            .append(\n              $('<span/>', {class: 'btn-body'}).append(\n                $('<span/>', {class: 'label'}).append(\n                  $('<span/>', {'data-icon': 'ellipsis', 'aria-hidden': 'true'})\n                )\n              )\n            )\n            .append($('<span/>', {class: 'chevron-right'}))\n            .appendTo(this.$sourcePathOverflowBtnContainer);\n\n          const $overflowMenu = $('<div/>', {\n            id: overflowMenuId,\n            class: 'menu menu--disclosure',\n          }).appendTo(this.$sourcePathOverflowBtnContainer);\n          $overflowUl = $('<ul/>').appendTo($overflowMenu);\n\n          $overflowBtn.disclosureMenu();\n        }\n\n        for (let i = 0; i < sourcePath.length; i++) {\n          ((i) => {\n            const step = sourcePath[i];\n\n            if ($overflowUl && i < sourcePath.length - 1) {\n              step.$overflowLi = $('<li/>', {\n                class: 'hidden',\n              }).appendTo($overflowUl);\n\n              $('<a/>', {\n                class: 'flex flex-nowrap',\n                href: '#',\n                type: 'button',\n                role: 'button',\n                html: step.icon\n                  ? `<span data-icon=\"${step.icon}\" aria-hidden=\"true\"></span><span>${step.label}</span>`\n                  : step.label,\n              })\n                .appendTo(step.$overflowLi)\n                .on('click', (ev) => {\n                  ev.preventDefault();\n                  $overflowBtn.data('trigger').hide();\n                  this.selectSourcePathStep(i);\n                });\n            }\n\n            const isFirst = i === 0;\n            const isLast = i === sourcePath.length - 1;\n\n            step.$li = $('<li/>').appendTo($ol);\n\n            if (isFirst) {\n              step.$li.addClass('first-step');\n            }\n\n            step.$btn = $('<a/>', {\n              href: step.uri ? Craft.getCpUrl(step.uri) : '#',\n              class: 'btn',\n              role: 'button',\n            });\n\n            if (step.icon) {\n              step.$btn.attr('aria-label', step.label);\n            }\n\n            const $btnBody = $('<span/>', {\n              class: 'btn-body',\n            }).appendTo(step.$btn);\n\n            step.$label = $('<span/>', {\n              class: 'label',\n              html: step.icon\n                ? `<span data-icon=\"${step.icon}\" aria-hidden=\"true\"></span>`\n                : step.label,\n            }).appendTo($btnBody);\n\n            step.$btn.append($('<span class=\"chevron-left\"/>'));\n\n            if (!isLast || !actions.length) {\n              step.$btn.append($('<span class=\"chevron-right\"/>'));\n            } else {\n              step.$btn.addClass('has-action-menu');\n            }\n\n            if (isLast) {\n              step.$btn.addClass('current-step').attr('aria-current', 'page');\n            }\n\n            step.$btn.appendTo(step.$li);\n\n            this.addListener(step.$btn, 'activate', () => {\n              this.selectSourcePathStep(i);\n            });\n          })(i);\n        }\n\n        // Action menu\n        if (actions && actions.length) {\n          const actionBtnLabel = this.getSourcePathActionLabel();\n          const menuId = 'menu' + Math.floor(Math.random() * 1000000);\n          this.$sourcePathActionsBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn current-step',\n            title: actionBtnLabel,\n            'aria-label': actionBtnLabel,\n            'data-disclosure-trigger': true,\n            'aria-controls': menuId,\n          })\n            .append(\n              $('<span/>', {class: 'btn-body'}).append(\n                $('<span/>', {class: 'label'})\n              )\n            )\n            .append($('<span/>', {class: 'chevron-right'}))\n            .appendTo(this.$sourcePathInnerContainer);\n\n          const groupedActions = [\n            actions.filter((a) => !a.destructive && !a.administrative),\n            actions.filter((a) => a.destructive && !a.administrative),\n            actions.filter((a) => a.administrative),\n          ].filter((group) => group.length);\n\n          const $menu = $('<div/>', {\n            id: menuId,\n            class: 'menu menu--disclosure',\n          }).appendTo(this.$sourcePathInnerContainer);\n\n          groupedActions.forEach((group, index) => {\n            if (index !== 0) {\n              $('<hr/>').appendTo($menu);\n            }\n            this._buildSourcePathActionList(group).appendTo($menu);\n          });\n\n          this.$sourcePathActionsBtn.disclosureMenu();\n          this._updateSourcePathVisibility();\n        }\n\n        // Update the URL if we're on the index page\n        if (\n          this.settings.context === 'index' &&\n          typeof sourcePath[sourcePath.length - 1].uri !== 'undefined' &&\n          typeof history != 'undefined'\n        ) {\n          history.replaceState(\n            {},\n            '',\n            Craft.getCpUrl(sourcePath[sourcePath.length - 1].uri)\n          );\n        }\n      }\n\n      this.onSourcePathChange();\n    },\n\n    /**\n     * @returns {string}\n     */\n    getSourcePathLabel: function () {\n      return '';\n    },\n\n    /**\n     * @returns {Object[]}\n     */\n    getSourcePathActions: function () {\n      return [];\n    },\n\n    /**\n     * @returns {string}\n     */\n    getSourcePathActionLabel: function () {\n      return '';\n    },\n\n    _updateSourcePathVisibility: function () {\n      const firstStep = this.sourcePath[0];\n      const lastStep = this.sourcePath[this.sourcePath.length - 1];\n\n      // reset the source path styles\n      if (this.$sourcePathOverflowBtnContainer) {\n        this.$sourcePathOverflowBtnContainer.addClass('hidden');\n        firstStep.$li.addClass('first-step');\n      }\n\n      for (const step of this.sourcePath) {\n        if (step.$overflowLi) {\n          step.$overflowLi.addClass('hidden');\n        }\n        step.$li.removeClass('hidden');\n      }\n\n      lastStep.$label.css('width', '');\n      lastStep.$btn.removeAttr('title');\n\n      let overage = this._checkSourcePathOverage();\n      if (!overage) {\n        return;\n      }\n\n      // show the overflow menu, if we have one\n      if (this.$sourcePathOverflowBtnContainer) {\n        this.$sourcePathOverflowBtnContainer.removeClass('hidden');\n        firstStep.$li.removeClass('first-step');\n\n        for (let i = 0; i < this.sourcePath.length - 1; i++) {\n          const step = this.sourcePath[i];\n          step.$overflowLi.removeClass('hidden');\n          step.$li.addClass('hidden');\n\n          // are we done yet?\n          overage = this._checkSourcePathOverage();\n          if (!overage) {\n            return;\n          }\n        }\n      }\n\n      // if we're still here, truncation is the only remaining strategy\n      if (!lastStep.icon) {\n        const width = lastStep.$label[0].getBoundingClientRect().width;\n        lastStep.$label.width(Math.floor(width - overage));\n        lastStep.$btn.attr('title', lastStep.label);\n      }\n    },\n\n    _checkSourcePathOverage: function () {\n      const outerWidth =\n        this.$sourcePathOuterContainer[0].getBoundingClientRect().width;\n      const innerWidth =\n        this.$sourcePathInnerContainer[0].getBoundingClientRect().width;\n      return Math.max(innerWidth - outerWidth, 0);\n    },\n\n    _buildSourcePathActionList: function (actions) {\n      const $ul = $('<ul/>');\n\n      actions.forEach((action) => {\n        const $a = $('<a/>', {\n          href: '#',\n          type: 'button',\n          role: 'button',\n          'aria-label': action.label,\n          text: action.label,\n        }).on('click', (ev) => {\n          ev.preventDefault();\n          this.$sourcePathActionsBtn.data('trigger').hide();\n          if (action.onSelect) {\n            action.onSelect();\n          }\n        });\n\n        if (action.destructive) {\n          $a.addClass('error');\n        }\n\n        $('<li/>').append($a).appendTo($ul);\n      });\n\n      return $ul;\n    },\n\n    onSourcePathChange: function () {\n      this.settings.onSourcePathChange();\n      this.trigger('sourcePathChange');\n    },\n\n    selectSourcePathStep: function (num) {\n      this.sourcePath = this.sourcePath.slice(0, num + 1);\n      this.sourcePath[num].$btn.focus();\n      this.clearSearch(false);\n      this.updateElements();\n    },\n\n    startSearching: function () {\n      // Show the clear button\n      this.$clearSearchBtn.removeClass('hidden');\n      this.searching = true;\n      this.sortByScore = true;\n\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n    },\n\n    clearSearch: function (updateElements) {\n      if (!this.searching) {\n        return;\n      }\n\n      this.$search.val('');\n\n      if (this.searchTimeout) {\n        clearTimeout(this.searchTimeout);\n      }\n\n      this.stopSearching();\n\n      if (updateElements) {\n        this.updateElementsIfSearchTextChanged();\n      } else {\n        this.searchText = null;\n      }\n    },\n\n    stopSearching: function () {\n      // Hide the clear button\n      this.$clearSearchBtn.addClass('hidden');\n      this.searching = false;\n      this.sortByScore = false;\n\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n    },\n\n    setInstanceState: function (key, value) {\n      if (typeof key === 'object') {\n        $.extend(this.instanceState, key);\n      } else {\n        this.instanceState[key] = value;\n      }\n\n      this.storeInstanceState();\n    },\n\n    storeInstanceState: function () {\n      if (this.settings.storageKey) {\n        Craft.setLocalStorage(this.settings.storageKey, this.instanceState);\n      }\n    },\n\n    getSourceState: function (sourceKey, key, defaultValue) {\n      // account for when all sources are disabled\n      if (sourceKey == undefined) {\n        return null;\n      }\n\n      sourceKey = sourceKey.replace(/\\/.*/, '');\n\n      if (typeof this.sourceStates[sourceKey] === 'undefined') {\n        // Set it now so any modifications to it by whoever's calling this will be stored.\n        this.sourceStates[sourceKey] = {};\n      }\n\n      if (typeof key === 'undefined') {\n        return this.sourceStates[sourceKey];\n      } else if (typeof this.sourceStates[sourceKey][key] !== 'undefined') {\n        return this.sourceStates[sourceKey][key];\n      } else {\n        return typeof defaultValue !== 'undefined' ? defaultValue : null;\n      }\n    },\n\n    getSelectedSourceState: function (key, defaultValue) {\n      return this.getSourceState(\n        this.instanceState.selectedSource,\n        key,\n        defaultValue\n      );\n    },\n\n    setSelecetedSourceState: function (key, value) {\n      var viewState = this.getSelectedSourceState();\n\n      // account for when all sources are disabled\n      if (viewState == null) {\n        viewState = [];\n      }\n\n      if (typeof key === 'object') {\n        for (let k in key) {\n          if (key.hasOwnProperty(k)) {\n            if (key[k] !== null) {\n              viewState[k] = key[k];\n            } else {\n              delete viewState[k];\n            }\n          }\n        }\n      } else if (value !== null) {\n        viewState[key] = value;\n      } else {\n        delete viewState[key];\n      }\n\n      // account for when all sources are disabled\n      let sourceKey = '*';\n      if (this.instanceState.selectedSource != undefined) {\n        // otherwise do what we used to do\n        sourceKey = this.instanceState.selectedSource.replace(/\\/.*/, '');\n      }\n\n      this.sourceStates[sourceKey] = viewState;\n\n      // Clean up sourceStates while we're at it\n      for (let i in this.sourceStates) {\n        if (this.sourceStates.hasOwnProperty(i) && i.includes('/')) {\n          delete this.sourceStates[i];\n        }\n      }\n\n      // Store it in localStorage too\n      Craft.setLocalStorage(this.sourceStatesStorageKey, this.sourceStates);\n    },\n\n    /**\n     * @deprecated in 4.3.0.\n     */\n    storeSortAttributeAndDirection: function () {},\n\n    /**\n     * Sets the page number.\n     */\n    setPage: function (page) {\n      if (this.settings.context !== 'index') {\n        return;\n      }\n\n      page = Math.max(page, 1);\n      this.page = page;\n\n      const url = Craft.getPageUrl(this.page);\n      history.replaceState({}, '', url);\n    },\n\n    _resetCount: function () {\n      this.resultSet = null;\n      this.totalResults = null;\n    },\n\n    updateSourceMenu: function () {\n      if (!this.$sourceActionsContainer.length) {\n        return;\n      }\n\n      if (this.$sourceActionsBtn) {\n        this.$sourceActionsBtn.data('trigger').destroy();\n        this.$sourceActionsContainer.empty();\n        $('#source-actions-menu').remove();\n        this.$sourceActionsBtn = null;\n      }\n\n      const actions = this.getSourceActions();\n      if (!actions.length) {\n        return;\n      }\n\n      const groupedActions = [\n        actions.filter((a) => !a.destructive && !a.administrative),\n        actions.filter((a) => a.destructive && !a.administrative),\n        actions.filter((a) => a.administrative),\n      ].filter((group) => group.length);\n\n      this.$sourceActionsBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn settings icon menubtn',\n        title: Craft.t('app', 'Source settings'),\n        'aria-label': Craft.t('app', 'Source settings'),\n        'aria-controls': 'source-actions-menu',\n      }).appendTo(this.$sourceActionsContainer);\n\n      const $menu = $('<div/>', {\n        id: 'source-actions-menu',\n        class: 'menu menu--disclosure',\n      }).appendTo(this.$sourceActionsContainer);\n\n      groupedActions.forEach((group, index) => {\n        if (index !== 0) {\n          $('<hr/>').appendTo($menu);\n        }\n\n        this._buildActionList(group).appendTo($menu);\n      });\n\n      this.$sourceActionsBtn.disclosureMenu();\n    },\n\n    _buildActionList: function (actions) {\n      const $ul = $('<ul/>');\n\n      actions.forEach((action) => {\n        const $button = $('<button/>', {\n          type: 'button',\n          class: 'menu-option',\n          text: action.label,\n        }).on('click', () => {\n          this.$sourceActionsBtn.data('trigger').hide();\n          if (action.onSelect) {\n            action.onSelect();\n          }\n        });\n\n        if (action.destructive) {\n          $button.addClass('error');\n        }\n\n        $('<li/>').append($button).appendTo($ul);\n      });\n\n      return $ul;\n    },\n\n    getSourceActions: function () {\n      let actions = [];\n\n      if (Craft.userIsAdmin && Craft.allowAdminChanges) {\n        actions.push({\n          label: Craft.t('app', 'Customize sources'),\n          administrative: true,\n          onSelect: () => {\n            this.createCustomizeSourcesModal();\n          },\n        });\n      }\n\n      return actions;\n    },\n\n    updateViewMenu: function () {\n      if (\n        !this.activeViewMenu ||\n        this.activeViewMenu !== this.viewMenus[this.rootSourceKey]\n      ) {\n        if (this.activeViewMenu) {\n          this.activeViewMenu.hideTrigger();\n        }\n        if (!this.viewMenus[this.rootSourceKey]) {\n          this.viewMenus[this.rootSourceKey] = new ViewMenu(\n            this,\n            this.$rootSource\n          );\n        }\n        this.activeViewMenu = this.viewMenus[this.rootSourceKey];\n        this.activeViewMenu.showTrigger();\n      }\n    },\n\n    /**\n     * Returns any additional settings that should be passed to the view instance.\n     */\n    getViewSettings: function () {\n      return {};\n    },\n\n    /**\n     * Returns the data that should be passed to the elementIndex/getElements controller action\n     * when loading elements.\n     */\n    getViewParams: function () {\n      var criteria = {\n        siteId: this.siteId,\n        search: this.searchText,\n        offset: this.settings.batchSize * (this.page - 1),\n        limit: this.settings.batchSize,\n      };\n\n      // Only set drafts/draftOf/trashed params when needed, so we don't potentially override a source's criteria\n      if (\n        this.settings.canHaveDrafts &&\n        (this.drafts || (this.settings.context === 'index' && !this.status))\n      ) {\n        criteria.drafts = this.drafts || null;\n        criteria.savedDraftsOnly = true;\n        if (!this.drafts) {\n          criteria.draftOf = false;\n        }\n      }\n      if (this.trashed) {\n        criteria.trashed = true;\n      }\n\n      if (!Garnish.hasAttr(this.$source, 'data-override-status')) {\n        criteria.status = this.status;\n      }\n\n      $.extend(criteria, this.settings.criteria);\n\n      if (this.sourcePath.length) {\n        const currentStep = this.sourcePath[this.sourcePath.length - 1];\n        if (typeof currentStep.criteria !== 'undefined') {\n          $.extend(criteria, currentStep.criteria);\n        }\n      }\n\n      var params = {\n        context: this.settings.context,\n        elementType: this.elementType,\n        source: this.instanceState.selectedSource,\n        condition: this.settings.condition,\n        referenceElementId: this.settings.referenceElementId,\n        referenceElementSiteId: this.settings.referenceElementSiteId,\n        criteria: criteria,\n        disabledElementIds: this.settings.disabledElementIds,\n        viewState: $.extend({}, this.getSelectedSourceState()),\n        paginated: this._isViewPaginated() ? 1 : 0,\n      };\n\n      // override viewState.mode in case it's different from what's stored\n      params.viewState.mode = this.viewMode;\n\n      if (this.viewMode === 'structure') {\n        params.viewState.mode = 'table';\n        params.viewState.order = 'structure';\n        params.viewState.sort = 'asc';\n\n        if (typeof this.instanceState.collapsedElementIds === 'undefined') {\n          this.instanceState.collapsedElementIds = [];\n        }\n        params.collapsedElementIds = this.instanceState.collapsedElementIds;\n      } else {\n        // Possible that the order/sort isn't entirely accurate if we're sorting by Score\n        const [sortAttribute, sortDirection] =\n          this.getSortAttributeAndDirection();\n        params.viewState.order = sortAttribute;\n        params.viewState.sort = sortDirection;\n      }\n\n      if (\n        this.filterHuds[this.siteId] &&\n        this.filterHuds[this.siteId][this.sourceKey] &&\n        this.filterHuds[this.siteId][this.sourceKey].serialized\n      ) {\n        params.filters =\n          this.filterHuds[this.siteId][this.sourceKey].serialized;\n      }\n\n      // Give plugins a chance to hook in here\n      this.trigger('registerViewParams', {\n        params: params,\n      });\n\n      return params;\n    },\n\n    updateElements: function (preservePagination, pageChanged) {\n      return new Promise((resolve, reject) => {\n        // Ignore if we're not fully initialized yet\n        if (!this.initialized) {\n          reject('The element index isn’t initialized yet.');\n          return;\n        }\n\n        // Cancel any ongoing requests\n        this._cancelRequests();\n\n        this.setIndexBusy();\n\n        // Kill the old view class\n        if (this.view) {\n          this.view.destroy();\n          delete this.view;\n        }\n\n        if (preservePagination !== true) {\n          this.setPage(1);\n          this._resetCount();\n        }\n\n        var params = this.getViewParams();\n\n        Craft.sendActionRequest('POST', this.settings.updateElementsAction, {\n          data: params,\n          cancelToken: this._createCancelToken(),\n        })\n          .then((response) => {\n            this.setIndexAvailable();\n\n            if (this.settings.context === 'index') {\n              if (Craft.cp.fixedHeader) {\n                const headerContainerHeight =\n                  Craft.cp.$headerContainer.height();\n                const maxScrollTop =\n                  this.$main.offset().top - headerContainerHeight;\n                if (maxScrollTop < Garnish.$scrollContainer.scrollTop()) {\n                  Garnish.$scrollContainer.scrollTop(maxScrollTop);\n                }\n              }\n            } else {\n              this.$main.scrollTop(0);\n            }\n\n            this._updateView(params, response.data);\n\n            if (pageChanged) {\n              const $elementContainer = this.view.getElementContainer();\n              Garnish.firstFocusableElement($elementContainer).trigger('focus');\n            }\n\n            resolve();\n          })\n          .catch((e) => {\n            if (!axios.isCancel(e)) {\n              this.setIndexAvailable();\n              Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n            }\n            reject(e);\n          });\n      });\n    },\n\n    updateElementsIfSearchTextChanged: function () {\n      if (\n        this.searchText !==\n        (this.searchText = this.searching ? this.$search.val() : null)\n      ) {\n        if (this.settings.context === 'index') {\n          Craft.setQueryParam('search', this.$search.val());\n        }\n        this.updateElements();\n      }\n    },\n\n    showActionTriggers: function () {\n      // Ignore if they're already shown\n      if (this.showingActionTriggers) {\n        return;\n      }\n\n      if (!this._$triggers) {\n        this._createTriggers();\n      } else {\n        this._$triggers.appendTo(this.$actionsContainer);\n      }\n\n      this.showingActionTriggers = true;\n    },\n\n    submitAction: function (action, actionParams) {\n      // Make sure something's selected\n      var selectedElementIds = this.view.getSelectedElementIds(),\n        totalSelected = selectedElementIds.length;\n\n      if (totalSelected === 0) {\n        return;\n      }\n\n      if (typeof action === 'string') {\n        action = this._findAction(action);\n      }\n\n      if (action.confirm && !confirm(action.confirm)) {\n        return;\n      }\n\n      // Cancel any ongoing requests\n      this._cancelRequests();\n\n      // Get ready to submit\n      var viewParams = this.getViewParams();\n\n      actionParams = actionParams ? Craft.expandPostArray(actionParams) : {};\n      var params = $.extend(viewParams, action.settings || {}, actionParams, {\n        elementAction: action.type,\n        elementIds: selectedElementIds,\n      });\n\n      // Do it\n      this.setIndexBusy();\n      this._autoSelectElements = selectedElementIds;\n\n      if (action.download) {\n        if (Craft.csrfTokenName) {\n          params[Craft.csrfTokenName] = Craft.csrfTokenValue;\n        }\n        Craft.downloadFromUrl(\n          'POST',\n          Craft.getActionUrl(this.settings.submitActionsAction),\n          params\n        )\n          .then((response) => {\n            this.setIndexAvailable();\n          })\n          .catch((e) => {\n            this.setIndexAvailable();\n          });\n      } else {\n        Craft.sendActionRequest('POST', this.settings.submitActionsAction, {\n          data: params,\n          cancelToken: this._createCancelToken(),\n        })\n          .then((response) => {\n            // Update the count text too\n            this._resetCount();\n            this._updateView(viewParams, response.data);\n\n            if (typeof response.data.badgeCounts !== 'undefined') {\n              this._updateBadgeCounts(response.data.badgeCounts);\n            }\n\n            if (response.data.message) {\n              Craft.cp.displaySuccess(response.data.message);\n            }\n\n            this.afterAction(action, params);\n          })\n          .catch(({response}) => {\n            Craft.cp.displayError(response.data.message);\n          })\n          .finally(() => {\n            this.setIndexAvailable();\n          });\n      }\n    },\n\n    _findAction: function (actionClass) {\n      for (var i = 0; i < this.actions.length; i++) {\n        if (this.actions[i].type === actionClass) {\n          return this.actions[i];\n        }\n      }\n      throw `Invalid element action: ${actionClass}`;\n    },\n\n    afterAction: function (action, params) {\n      // There may be a new background job that needs to be run\n      Craft.cp.runQueue();\n\n      this.onAfterAction(action, params);\n    },\n\n    hideActionTriggers: function () {\n      // Ignore if there aren't any\n      if (!this.showingActionTriggers) {\n        return;\n      }\n\n      this._$triggers.detach();\n\n      this.showingActionTriggers = false;\n    },\n\n    updateActionTriggers: function () {\n      // Do we have an action UI to update?\n      if (this.actions) {\n        var totalSelected = this.view.getSelectedElements().length;\n\n        if (totalSelected !== 0) {\n          if (totalSelected === this.view.getEnabledElements().length) {\n            this.$selectAllCheckbox.removeClass('indeterminate');\n            this.$selectAllCheckbox.addClass('checked');\n            this.$selectAllCheckbox.attr('aria-checked', 'true');\n          } else {\n            this.$selectAllCheckbox.addClass('indeterminate');\n            this.$selectAllCheckbox.removeClass('checked');\n            this.$selectAllCheckbox.attr('aria-checked', 'mixed');\n          }\n\n          this.showActionTriggers();\n        } else {\n          this.$selectAllCheckbox.removeClass('indeterminate checked');\n          this.$selectAllCheckbox.attr('aria-checked', 'false');\n          this.hideActionTriggers();\n        }\n      }\n    },\n\n    getSelectedElements: function () {\n      return this.view ? this.view.getSelectedElements() : $();\n    },\n\n    getSelectedElementIds: function () {\n      return this.view ? this.view.getSelectedElementIds() : [];\n    },\n\n    setStatus: function (status) {\n      // Find the option (and make sure it actually exists)\n      var $option = this.statusMenu.$options.filter(\n        'a[data-status=\"' + status + '\"]:first'\n      );\n\n      if ($option.length) {\n        this.statusMenu.selectOption($option[0]);\n      }\n    },\n\n    /**\n     * Returns the selected sort attribute for a source\n     * @param {jQuery} [$source]\n     * @returns {string}\n     */\n    getSelectedSortAttribute: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n\n      if ($source) {\n        const attribute = this.getSourceState($source.data('key'), 'order');\n\n        // Make sure it's valid\n        if (this.getSortOption(attribute, $source)) {\n          return attribute;\n        }\n      }\n\n      return this.getDefaultSort()[0];\n    },\n\n    /**\n     * Returns the selected sort direction for a source\n     * @param {jQuery} [$source]\n     * @returns {string}\n     */\n    getSelectedSortDirection: function ($source) {\n      $source = $source || this.$source;\n      if ($source) {\n        const direction = this.getSourceState($source.data('key'), 'sort');\n\n        // Make sure it's valid\n        if (['asc', 'desc'].includes(direction)) {\n          return direction;\n        }\n      }\n\n      return this.getDefaultSort()[1];\n    },\n\n    /**\n     * @deprecated in 4.3.0. Use setSelectedSortAttribute() instead.\n     */\n    setSortAttribute: function (attr) {\n      this.setSelectedSortAttribute(attr);\n    },\n\n    /**\n     * Sets the selected sort attribute and direction.\n     *\n     * If direction isn’t provided, the attribute’s default direction will be used.\n     *\n     * @param {string} attr\n     * @param {string} [dir]\n     */\n    setSelectedSortAttribute: function (attr, dir) {\n      // If score, keep track of that separately\n      if (attr === 'score') {\n        this.sortByScore = true;\n        if (this.activeViewMenu) {\n          this.activeViewMenu.updateSortField();\n        }\n        return;\n      }\n\n      this.sortByScore = false;\n\n      // Make sure it's valid\n      const sortOption = this.getSortOption(attr);\n      if (!sortOption) {\n        console.warn(`Invalid sort option: ${attr}`);\n        return;\n      }\n\n      if (!dir) {\n        dir = sortOption.defaultDir;\n      }\n\n      const history = [];\n\n      // Remember the previous choices\n      const attributes = [attr];\n\n      // Only include the last attribute if it changed\n      const lastAttr = this.getSelectedSourceState('order');\n      if (lastAttr && lastAttr !== attr) {\n        history.push([lastAttr, this.getSelectedSourceState('sort')]);\n        attributes.push(lastAttr);\n      }\n\n      const oldHistory = this.getSelectedSourceState('orderHistory', []);\n      for (let i = 0; i < oldHistory.length; i++) {\n        const [a] = oldHistory[i];\n        if (a && !attributes.includes(a)) {\n          history.push(oldHistory[i]);\n          attributes.push(a);\n        } else {\n          break;\n        }\n      }\n\n      this.setSelecetedSourceState({\n        order: attr,\n        sort: dir,\n        orderHistory: history,\n      });\n\n      // Update the view menu\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n\n      if (this.settings.context === 'index') {\n        // Update the query string\n        Craft.setQueryParam('sort', `${attr}-${dir}`);\n      }\n    },\n\n    /**\n     * @deprecated in 4.3.0. Use setSelectedSortAttribute() or setSelectedSortDirection() instead.\n     */\n    setSortDirection: function (dir) {\n      this.setSelectedSortDirection(dir);\n    },\n\n    /**\n     * Sets the selected sort direction, maintaining the current sort attribute.\n     * @param {string} dir\n     */\n    setSelectedSortDirection: function (dir) {\n      this.setSelectedSortAttribute(this.getSelectedSortAttribute(), dir);\n    },\n\n    /**\n     * Returns whether we can use the structure view for the current state.\n     * @returns {boolean}\n     */\n    canSortByStructure: function () {\n      return !this.trashed && !this.drafts && !this.searching;\n    },\n\n    /**\n     * Returns the actual sort attribute, which may be different from what's selected.\n     * @returns {string[]}\n     */\n    getSortAttributeAndDirection: function () {\n      if (this.searching && this.sortByScore) {\n        return ['score', 'desc'];\n      }\n\n      return [this.getSelectedSortAttribute(), this.getSelectedSortDirection()];\n    },\n\n    getSortLabel: function (attr) {\n      const sortOption = this.getSortOption(attr);\n      return sortOption ? sortOption.label : null;\n    },\n\n    getSelectedViewMode: function () {\n      return this.getSelectedSourceState('mode') || 'table';\n    },\n\n    /**\n     * Returns the nesting level for a given source, where 1 = the root level\n     * @param {jQuery} $source\n     * @returns {number}\n     */\n    getSourceLevel: function ($source) {\n      return $source.parentsUntil('nav', 'ul.nested').length + 1;\n    },\n\n    /**\n     * Returns a source’s parent, or null if it’s the root source\n     * @param {jQuery} $source\n     * @returns {?jQuery}\n     */\n    getParentSource: function ($source) {\n      const $parent = $source.parent().parent().siblings('a');\n      return $parent.length ? $parent : null;\n    },\n\n    /**\n     * Returns the root level source for a given source.\n     * @param {jQuery} $source\n     * @returns {jQuery}\n     */\n    getRootSource: function ($source) {\n      let $parent;\n      while (($parent = this.getParentSource($source))) {\n        $source = $parent;\n      }\n      return $source;\n    },\n\n    getSourceByKey: function (key) {\n      return this.sourcesByKey[key] || null;\n    },\n\n    selectSource: function (source) {\n      const $source = $(source);\n\n      // return false if there truly are no sources;\n      // don't attempt to check only default/visible sources\n      if (!this.sourcesByKey || !Object.keys(this.sourcesByKey).length) {\n        return false;\n      }\n\n      if (\n        this.$source &&\n        this.$source[0] &&\n        this.$source[0] === $source[0] &&\n        $source.data('key') === this.sourceKey\n      ) {\n        return false;\n      }\n\n      // Hide action triggers if they're currently being shown\n      this.hideActionTriggers();\n\n      this.$source = $source;\n      this.$rootSource = this.getRootSource($source);\n      this.sourceKey = $source.data('key');\n      this.rootSourceKey = this.$rootSource.data('key');\n      this.setInstanceState('selectedSource', this.sourceKey);\n      this.sourceSelect.selectItem($source);\n\n      Craft.cp.updateContentHeading();\n\n      if (this.searching) {\n        // Clear the search value without causing it to update elements\n        this.searchText = null;\n        this.$search.val('');\n        if (this.settings.context === 'index') {\n          Craft.setQueryParam('search', null);\n        }\n        this.stopSearching();\n      }\n\n      // Status menu\n      // ----------------------------------------------------------------------\n\n      if (this.$statusMenuBtn.length) {\n        if (Garnish.hasAttr(this.$source, 'data-override-status')) {\n          this.$statusMenuContainer.addClass('hidden');\n        } else {\n          this.$statusMenuContainer.removeClass('hidden');\n        }\n\n        if (this.trashed) {\n          // Swap to the initial status\n          var $firstOption = this.statusMenu.$options.first();\n          this.setStatus($firstOption.data('status'));\n        }\n      }\n\n      // View mode buttons\n      // ----------------------------------------------------------------------\n\n      // Clear out any previous view mode data\n      if (this.$viewModeBtnContainer) {\n        this.$viewModeBtnContainer.remove();\n      }\n\n      this.viewModeBtns = {};\n      this.viewMode = null;\n\n      // Get the new list of view modes\n      this.sourceViewModes = this.getViewModesForSource();\n\n      // Create the buttons if there's more than one mode available to this source\n      if (this.sourceViewModes.length > 1) {\n        this.$viewModeBtnContainer = $(\n          '<section class=\"btngroup btngroup--exclusive\"/>'\n        )\n          .attr('aria-label', Craft.t('app', 'View'))\n          .insertAfter(this.$searchContainer);\n\n        for (var i = 0; i < this.sourceViewModes.length; i++) {\n          let sourceViewMode = this.sourceViewModes[i];\n\n          let $viewModeBtn = $('<button/>', {\n            type: 'button',\n            class:\n              'btn' +\n              (typeof sourceViewMode.className !== 'undefined'\n                ? ` ${sourceViewMode.className}`\n                : ''),\n            'data-view': sourceViewMode.mode,\n            'data-icon': sourceViewMode.icon,\n            'aria-label': sourceViewMode.title,\n            'aria-pressed': 'false',\n            title: sourceViewMode.title,\n          }).appendTo(this.$viewModeBtnContainer);\n\n          this.viewModeBtns[sourceViewMode.mode] = $viewModeBtn;\n\n          this.addListener(\n            $viewModeBtn,\n            'click',\n            {mode: sourceViewMode.mode},\n            function (ev) {\n              this.selectViewMode(ev.data.mode);\n              this.updateElements();\n            }\n          );\n        }\n      }\n\n      // Figure out which mode we should start with\n      var viewMode = this.getSelectedSourceState('mode');\n\n      // Maintain the structure view for source states that were saved with an older Craft version\n      if (\n        viewMode === 'table' &&\n        this.getSourceState($source.data('key'), 'order') === 'structure'\n      ) {\n        viewMode = 'structure';\n      }\n\n      if (!viewMode || !this.doesSourceHaveViewMode(viewMode)) {\n        // Try to keep using the current view mode\n        if (this.viewMode && this.doesSourceHaveViewMode(this.viewMode)) {\n          viewMode = this.viewMode;\n        }\n        // Just use the first one\n        else {\n          viewMode = this.sourceViewModes[0].mode;\n        }\n      }\n\n      this.selectViewMode(viewMode);\n\n      this.updateSourceMenu();\n      this.updateViewMenu();\n      this.updateFilterBtn();\n\n      this.sourcePath = this.$source.data('default-source-path');\n\n      this.onSelectSource();\n\n      if (this.settings.context === 'index') {\n        const urlParams = Craft.getQueryParams();\n        urlParams.source = this.sourceKey;\n        Craft.setUrl(Craft.getUrl(Craft.path, urlParams));\n      }\n\n      return true;\n    },\n\n    selectSourceByKey: function (key) {\n      var $source = this.getSourceByKey(key);\n\n      if ($source) {\n        return this.selectSource($source);\n      } else {\n        return false;\n      }\n    },\n\n    /**\n     * Returns the available sort attributes for a source (or the selected root source)\n     * @param {jQuery} [$source]\n     * @returns {Object[]}\n     */\n    getSortOptions: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      const sortOptions = ($source ? $source.data('sort-opts') : null) || [];\n\n      // Make sure there's at least one attribute\n      if (!sortOptions.length) {\n        sortOptions.push({\n          label: Craft.t('app', 'Title'),\n          attr: 'title',\n          defaultDir: 'asc',\n        });\n      }\n\n      return sortOptions;\n    },\n\n    /**\n     * Returns info about a sort attribute.\n     * @param {string} attribute\n     * @param {jQuery} [$source]\n     * @returns {?Object}\n     */\n    getSortOption: function (attribute, $source) {\n      return (\n        this.getSortOptions($source).find((o) => o.attr === attribute) || null\n      );\n    },\n\n    /**\n     * Returns the default sort attribute and direction for a source.\n     * @param {jQuery} [$source]\n     * @returns {string[]}\n     */\n    getDefaultSort: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      if ($source) {\n        let defaultSort = $source.data('default-sort');\n        if (defaultSort) {\n          if (typeof defaultSort === 'string') {\n            defaultSort = [defaultSort];\n          }\n\n          // Make sure it's valid\n          const sortOption = this.getSortOption(defaultSort[0], $source);\n          if (sortOption) {\n            // Fill in the default direction if it's not specified\n            if (!defaultSort[1]) {\n              defaultSort[1] = sortOption.defaultDir;\n            }\n\n            return defaultSort;\n          }\n        }\n      }\n\n      // Default to the first sort option\n      const sortOptions = this.getSortOptions($source);\n      return [sortOptions[0].attr, sortOptions[0].defaultDir];\n    },\n\n    /**\n     * Returns the available table columns for a source (or the selected root source)\n     * @param {jQuery} [$source]\n     * @returns {Object[]}\n     */\n    getTableColumnOptions: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      return ($source ? $source.data('table-col-opts') : null) || [];\n    },\n\n    /**\n     * Returns info about a table column.\n     * @param {string} attribute\n     * @param {jQuery} [$source]\n     * @returns {?Object}\n     */\n    getTableColumnOption: function (attribute, $source) {\n      return (\n        this.getTableColumnOptions($source).find((o) => o.attr === attribute) ||\n        null\n      );\n    },\n\n    /**\n     * Returns the default table columns for a source (or the selected root source)\n     * @param {jQuery} [$source]\n     * @returns {string[]}\n     */\n    getDefaultTableColumns: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      return ($source ? $source.data('default-table-cols') : null) || [];\n    },\n\n    /**\n     * Returns the selected sort attribute for a source\n     * @param {jQuery} [$source]\n     * @returns {string[]}\n     */\n    getSelectedTableColumns: function ($source) {\n      $source = $source ? this.getRootSource($source) : this.$rootSource;\n      if ($source) {\n        const attributes = this.getSourceState(\n          $source.data('key'),\n          'tableColumns'\n        );\n\n        if (attributes) {\n          // Only return the valid ones\n          return attributes.filter(\n            (a) => !!this.getTableColumnOption(a, $source)\n          );\n        }\n      }\n\n      return this.getDefaultTableColumns($source);\n    },\n\n    setSelectedTableColumns: function (attributes) {\n      this.setSelecetedSourceState({\n        tableColumns: attributes,\n      });\n\n      // Update the view menu\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateTableColumnField();\n      }\n    },\n\n    getViewModesForSource: function () {\n      var viewModes = [];\n\n      if (Garnish.hasAttr(this.$source, 'data-has-structure')) {\n        viewModes.push({\n          mode: 'structure',\n          title: Craft.t('app', 'Display in a structured table'),\n          icon: Craft.orientation === 'rtl' ? 'structurertl' : 'structure',\n        });\n      }\n\n      viewModes.push({\n        mode: 'table',\n        title: Craft.t('app', 'Display in a table'),\n        icon: 'list',\n      });\n\n      if (this.$source && Garnish.hasAttr(this.$source, 'data-has-thumbs')) {\n        viewModes.push({\n          mode: 'thumbs',\n          title: Craft.t('app', 'Display as thumbnails'),\n          icon: 'grid',\n        });\n      }\n\n      return viewModes;\n    },\n\n    doesSourceHaveViewMode: function (viewMode) {\n      for (var i = 0; i < this.sourceViewModes.length; i++) {\n        if (this.sourceViewModes[i].mode === viewMode) {\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    selectViewMode: function (viewMode, force) {\n      // Make sure that the current source supports it\n      if (!force && !this.doesSourceHaveViewMode(viewMode)) {\n        viewMode = this.sourceViewModes[0].mode;\n      }\n\n      // Has anything changed?\n      if (viewMode === this._viewMode) {\n        return;\n      }\n\n      // Deselect the previous view mode\n      if (\n        this._viewMode &&\n        typeof this.viewModeBtns[this._viewMode] !== 'undefined'\n      ) {\n        this.viewModeBtns[this._viewMode]\n          .removeClass('active')\n          .attr('aria-pressed', 'false');\n      }\n\n      this._viewMode = viewMode;\n      this.setSelecetedSourceState('mode', this._viewMode);\n\n      if (typeof this.viewModeBtns[this._viewMode] !== 'undefined') {\n        this.viewModeBtns[this._viewMode]\n          .addClass('active')\n          .attr('aria-pressed', 'true');\n      }\n\n      // Update the view menu\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n    },\n\n    createView: function (mode, settings) {\n      var viewClass = this.getViewClass(mode);\n      return new viewClass(this, this.$elements, settings);\n    },\n\n    getViewClass: function (mode) {\n      switch (mode) {\n        case 'table':\n        case 'structure':\n          return Craft.TableElementIndexView;\n        case 'thumbs':\n          return Craft.ThumbsElementIndexView;\n        default:\n          throw `View mode \"${mode}\" not supported.`;\n      }\n    },\n\n    rememberDisabledElementId: function (id) {\n      var index = $.inArray(id, this.settings.disabledElementIds);\n\n      if (index === -1) {\n        this.settings.disabledElementIds.push(id);\n      }\n    },\n\n    forgetDisabledElementId: function (id) {\n      var index = $.inArray(id, this.settings.disabledElementIds);\n\n      if (index !== -1) {\n        this.settings.disabledElementIds.splice(index, 1);\n      }\n    },\n\n    enableElements: function ($elements) {\n      $elements\n        .removeClass('disabled')\n        .parents('.disabled')\n        .removeClass('disabled');\n\n      for (var i = 0; i < $elements.length; i++) {\n        var id = $($elements[i]).data('id');\n        this.forgetDisabledElementId(id);\n      }\n\n      this.onEnableElements($elements);\n    },\n\n    disableElements: function ($elements) {\n      $elements.removeClass('sel').addClass('disabled');\n\n      for (var i = 0; i < $elements.length; i++) {\n        var id = $($elements[i]).data('id');\n        this.rememberDisabledElementId(id);\n      }\n\n      this.onDisableElements($elements);\n    },\n\n    getElementById: function (id) {\n      return this.view.getElementById(id);\n    },\n\n    enableElementsById: function (ids) {\n      ids = $.makeArray(ids);\n\n      for (var i = 0; i < ids.length; i++) {\n        var id = ids[i],\n          $element = this.getElementById(id);\n\n        if ($element && $element.length) {\n          this.enableElements($element);\n        } else {\n          this.forgetDisabledElementId(id);\n        }\n      }\n    },\n\n    disableElementsById: function (ids) {\n      ids = $.makeArray(ids);\n\n      for (var i = 0; i < ids.length; i++) {\n        var id = ids[i],\n          $element = this.getElementById(id);\n\n        if ($element && $element.length) {\n          this.disableElements($element);\n        } else {\n          this.rememberDisabledElementId(id);\n        }\n      }\n    },\n\n    selectElementAfterUpdate: function (id) {\n      if (this._autoSelectElements === null) {\n        this._autoSelectElements = [];\n      }\n\n      this._autoSelectElements.push(id);\n    },\n\n    addButton: function ($button) {\n      this.getButtonContainer().append($button);\n    },\n\n    isShowingSidebar: function () {\n      if (this.showingSidebar === null) {\n        this.showingSidebar =\n          this.$sidebar.length && !this.$sidebar.hasClass('hidden');\n      }\n\n      return this.showingSidebar;\n    },\n\n    getButtonContainer: function () {\n      // Is there a predesignated place where buttons should go?\n      if (this.settings.buttonContainer) {\n        return $(this.settings.buttonContainer);\n      } else {\n        var $container = $('#action-buttons');\n\n        if (!$container.length) {\n          $container = $('<div id=\"action-buttons\"/>').appendTo($('#header'));\n        }\n\n        return $container;\n      }\n    },\n\n    setIndexBusy: function () {\n      this.$elements.addClass('busy');\n      this.$updateSpinner.appendTo(this.$elements);\n      this.isIndexBusy = true;\n\n      // Blur the active element, if it's within the element listing pane\n      if (\n        document.activeElement &&\n        this.$elements[0].contains(document.activeElement)\n      ) {\n        this._activeElement = document.activeElement;\n        document.activeElement.blur();\n      }\n\n      let elementsHeight = this.$elements.height();\n      let windowHeight = window.innerHeight;\n      let scrollTop = $(document).scrollTop();\n\n      if (this.settings.context == 'modal') {\n        windowHeight = this.$elements.parents('.modal').height();\n        scrollTop = this.$elements.scrollParent().scrollTop();\n      }\n\n      if (elementsHeight > windowHeight) {\n        let positionTop = Math.floor(scrollTop + windowHeight / 2) - 100;\n        positionTop = Math.floor((positionTop / elementsHeight) * 100);\n\n        document.documentElement.style.setProperty(\n          '--elements-busy-top-position',\n          positionTop + '%'\n        );\n      }\n    },\n\n    setIndexAvailable: function () {\n      this.$elements.removeClass('busy');\n      this.$updateSpinner.remove();\n      this.isIndexBusy = false;\n\n      // Refocus the previously-focused element\n      if (this._activeElement) {\n        if (\n          !document.activeElement ||\n          document.activeElement === document.body\n        ) {\n          if (document.body.contains(this._activeElement)) {\n            this._activeElement.focus();\n          } else if (this._activeElement.id) {\n            $(`#${this._activeElement.id}`).focus();\n          }\n        }\n        this._activeElement = null;\n      }\n    },\n\n    createCustomizeSourcesModal: function () {\n      // Recreate it each time\n      var modal = new Craft.CustomizeSourcesModal(this, {\n        hideOnEsc: false,\n        hideOnShadeClick: false,\n        onHide: function () {\n          modal.destroy();\n        },\n      });\n\n      return modal;\n    },\n\n    disable: function () {\n      if (this.sourceSelect) {\n        this.sourceSelect.disable();\n      }\n\n      if (this.view) {\n        this.view.disable();\n      }\n\n      this.base();\n    },\n\n    enable: function () {\n      if (this.sourceSelect) {\n        this.sourceSelect.enable();\n      }\n\n      if (this.view) {\n        this.view.enable();\n      }\n\n      this.base();\n    },\n\n    onAfterInit: function () {\n      this.settings.onAfterInit();\n      this.trigger('afterInit');\n    },\n\n    onSelectSource: function () {\n      this.settings.onSelectSource(this.sourceKey);\n      this.trigger('selectSource', {sourceKey: this.sourceKey});\n    },\n\n    onSelectSite: function () {\n      this.settings.onSelectSite(this.siteId);\n      this.trigger('selectSite', {siteId: this.siteId});\n    },\n\n    onUpdateElements: function () {\n      this.settings.onUpdateElements();\n      this.trigger('updateElements');\n    },\n\n    onSelectionChange: function () {\n      this.settings.onSelectionChange();\n      this.trigger('selectionChange');\n    },\n\n    onEnableElements: function ($elements) {\n      this.settings.onEnableElements($elements);\n      this.trigger('enableElements', {elements: $elements});\n    },\n\n    onDisableElements: function ($elements) {\n      this.settings.onDisableElements($elements);\n      this.trigger('disableElements', {elements: $elements});\n    },\n\n    onAfterAction: function (action, params) {\n      this.settings.onAfterAction(action, params);\n      this.trigger('afterAction', {action: action, params: params});\n    },\n\n    // UI state handlers\n    // -------------------------------------------------------------------------\n\n    _handleSourceSelectionChange: function () {\n      // If the selected source was just removed (maybe because its parent was collapsed),\n      // there won't be a selected source\n      if (!this.sourceSelect.totalSelected) {\n        this.sourceSelect.selectItem(this.$visibleSources.first());\n        return;\n      }\n\n      if (this.selectSource(this.sourceSelect.$selectedItems)) {\n        this.updateElements();\n      }\n    },\n\n    _handleActionTriggerSubmit: function (ev) {\n      ev.preventDefault();\n\n      var $form = $(ev.currentTarget);\n\n      // Make sure Craft.ElementActionTrigger isn't overriding this\n      if ($form.hasClass('disabled') || $form.data('custom-handler')) {\n        return;\n      }\n\n      this.submitAction($form.data('action'), Garnish.getPostData($form));\n    },\n\n    _handleMenuActionTriggerSubmit: function (ev) {\n      var $option = $(ev.option);\n\n      // Make sure Craft.ElementActionTrigger isn't overriding this\n      if ($option.hasClass('disabled') || $option.data('custom-handler')) {\n        return;\n      }\n\n      this.submitAction($option.data('action'));\n    },\n\n    _handleStatusChange: function (ev) {\n      this.statusMenu.$options.removeClass('sel');\n      var $option = $(ev.selectedOption).addClass('sel');\n      this.$statusMenuBtn.html($option.html());\n\n      this.trashed = false;\n      this.drafts = false;\n      this.status = null;\n      let queryParam = null;\n\n      if (Garnish.hasAttr($option, 'data-trashed')) {\n        this.trashed = true;\n        queryParam = 'trashed';\n      } else if (Garnish.hasAttr($option, 'data-drafts')) {\n        this.drafts = true;\n        queryParam = 'drafts';\n      } else {\n        this.status = queryParam = $option.data('status') || null;\n      }\n\n      if (this.activeViewMenu) {\n        this.activeViewMenu.updateSortField();\n      }\n\n      if (this.settings.context === 'index') {\n        Craft.setQueryParam('status', queryParam);\n      }\n\n      this.updateElements();\n    },\n\n    _handleSiteChange: function (ev) {\n      this.siteMenu.$options.removeClass('sel');\n      var $option = $(ev.selectedOption).addClass('sel');\n      this.$siteMenuBtn.html($option.html());\n      this._setSite($option.data('site-id'));\n      if (this.initialized) {\n        this.updateElements();\n      }\n      this.onSelectSite();\n    },\n\n    _setSite: function (siteId) {\n      let firstSite = this.siteId === null;\n      this.siteId = siteId;\n\n      this.updateSourceVisibility();\n\n      if (\n        this.initialized &&\n        !firstSite &&\n        (!this.$source || !this.$source.length) &&\n        this.$visibleSources.length\n      ) {\n        this.selectSource(this.$visibleSources[0]);\n      }\n\n      // Hide any empty-nester headings\n      var $headings = this.getSourceContainer().children('.heading');\n      var $heading;\n\n      for (let i = 0; i < $headings.length; i++) {\n        $heading = $headings.eq(i);\n        if ($heading.has('> ul > li:not(.hidden)').length !== 0) {\n          $heading.removeClass('hidden');\n        } else {\n          $heading.addClass('hidden');\n        }\n      }\n\n      if (this.initialized) {\n        if (this.settings.context === 'index') {\n          // Remember this site for later\n          Craft.cp.setSiteId(siteId);\n        }\n\n        this.updateFilterBtn();\n      }\n    },\n\n    updateSourceVisibility: function () {\n      this.$visibleSources = $();\n\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = this.$sources.eq(i);\n\n        if (\n          !Garnish.hasAttr($source, 'data-disabled') &&\n          (typeof $source.data('sites') === 'undefined' ||\n            $source\n              .data('sites')\n              .toString()\n              .split(',')\n              .indexOf(this.siteId.toString()) !== -1)\n        ) {\n          $source.parent().removeClass('hidden');\n          this.$visibleSources = this.$visibleSources.add($source);\n        } else {\n          $source.parent().addClass('hidden');\n\n          // Is this the currently selected source?\n          if (this.$source && this.$source.get(0) === $source.get(0)) {\n            this.$source = null;\n            this.$rootSource = null;\n            this.sourceKey = null;\n            this.rootSourceKey = null;\n          }\n        }\n      }\n    },\n\n    _handleSelectionChange: function () {\n      this.updateActionTriggers();\n      this.onSelectionChange();\n    },\n\n    _handleSourceDblClick: function (ev) {\n      this._toggleSource($(ev.currentTarget));\n      ev.stopPropagation();\n    },\n\n    _handleSourceToggleClick: function (ev) {\n      this._toggleSource($(ev.currentTarget).prev('a'));\n      ev.stopPropagation();\n    },\n\n    // Source managemnet\n    // -------------------------------------------------------------------------\n\n    _getSourcesInList: function ($list, topLevel) {\n      let $sources = $list.find('> li:not(.heading) > a');\n      if (topLevel) {\n        $sources = $sources.add($list.find('> li.heading > ul > li > a'));\n      }\n      return $sources;\n    },\n\n    _getChildSources: function ($source) {\n      var $list = $source.siblings('ul');\n      return this._getSourcesInList($list);\n    },\n\n    _getSourceToggle: function ($source) {\n      return $source.siblings('.toggle');\n    },\n\n    _toggleSource: function ($source) {\n      if ($source.parent('li').hasClass('expanded')) {\n        this._collapseSource($source);\n      } else {\n        this._expandSource($source);\n      }\n    },\n\n    _expandSource: function ($source) {\n      $source.next('.toggle').attr({\n        'aria-expanded': 'true',\n        'aria-label': Craft.t('app', 'Hide nested sources'),\n      });\n      $source.parent('li').addClass('expanded');\n\n      var $childSources = this._getChildSources($source);\n      for (let i = 0; i < $childSources.length; i++) {\n        this.initSource($($childSources[i]));\n        if (this.$visibleSources) {\n          this.$visibleSources = this.$visibleSources.add($childSources[i]);\n        }\n      }\n\n      var key = $source.data('key');\n      if (this.instanceState.expandedSources.indexOf(key) === -1) {\n        this.instanceState.expandedSources.push(key);\n        this.storeInstanceState();\n      }\n    },\n\n    _collapseSource: function ($source) {\n      $source.next('.toggle').attr({\n        'aria-expanded': 'false',\n        'aria-label': Craft.t('app', 'Show nested sources'),\n      });\n      $source.parent('li').removeClass('expanded');\n\n      var $childSources = this._getChildSources($source);\n      for (let i = 0; i < $childSources.length; i++) {\n        this.deinitSource($($childSources[i]));\n        this.$visibleSources = this.$visibleSources.not($childSources[i]);\n      }\n\n      var i = this.instanceState.expandedSources.indexOf($source.data('key'));\n      if (i !== -1) {\n        this.instanceState.expandedSources.splice(i, 1);\n        this.storeInstanceState();\n      }\n    },\n\n    // View\n    // -------------------------------------------------------------------------\n\n    _isViewPaginated: function () {\n      return this.settings.context === 'index' && this.viewMode !== 'structure';\n    },\n\n    _updateView: function (params, response) {\n      // Cleanup\n      // -------------------------------------------------------------\n\n      // Get rid of the old action triggers regardless of whether the new batch has actions or not\n      if (this.actions) {\n        this.hideActionTriggers();\n        this.actions =\n          this.actionsHeadHtml =\n          this.actionsBodyHtml =\n          this._$triggers =\n            null;\n      }\n\n      // Update the count text\n      // -------------------------------------------------------------\n\n      if (this.$countContainer.length) {\n        this.$countSpinner.removeClass('hidden');\n        this.$countContainer.html('');\n\n        this._countResults()\n          .then((total) => {\n            this.$countSpinner.addClass('hidden');\n\n            let itemLabel = Craft.elementTypeNames[this.elementType]\n              ? Craft.elementTypeNames[this.elementType][2]\n              : this.settings.elementTypeName.toLowerCase();\n            let itemsLabel = Craft.elementTypeNames[this.elementType]\n              ? Craft.elementTypeNames[this.elementType][3]\n              : this.settings.elementTypePluralName.toLowerCase();\n\n            if (!this._isViewPaginated()) {\n              let countLabel = Craft.t(\n                'app',\n                '{total, number} {total, plural, =1{{item}} other{{items}}}',\n                {\n                  total: total,\n                  item: itemLabel,\n                  items: itemsLabel,\n                }\n              );\n              this.$countContainer.text(countLabel);\n            } else {\n              let first = Math.min(\n                this.settings.batchSize * (this.page - 1) + 1,\n                total\n              );\n              let last = Math.min(first + (this.settings.batchSize - 1), total);\n              let countLabel = Craft.t(\n                'app',\n                '{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}',\n                {\n                  first: first,\n                  last: last,\n                  total: total,\n                  item: itemLabel,\n                  items: itemsLabel,\n                }\n              );\n\n              let $paginationContainer = $(\n                '<div class=\"flex pagination\"/>'\n              ).appendTo(this.$countContainer);\n              let totalPages = Math.max(\n                Math.ceil(total / this.settings.batchSize),\n                1\n              );\n\n              const $paginationNav = $('<nav/>', {\n                class: 'flex',\n                'aria-label': Craft.t('app', '{element} pagination', {\n                  element: itemLabel,\n                }),\n              }).appendTo($paginationContainer);\n\n              let $prevBtn = $('<button/>', {\n                role: 'button',\n                class:\n                  'page-link prev-page' + (this.page > 1 ? '' : ' disabled'),\n                disabled: this.page === 1,\n                title: Craft.t('app', 'Previous Page'),\n              }).appendTo($paginationNav);\n              let $nextBtn = $('<button/>', {\n                role: 'button',\n                class:\n                  'page-link next-page' +\n                  (this.page < totalPages ? '' : ' disabled'),\n                disabled: this.page === totalPages,\n                title: Craft.t('app', 'Next Page'),\n              }).appendTo($paginationNav);\n\n              $('<div/>', {\n                class: 'page-info',\n                text: countLabel,\n              }).appendTo($paginationContainer);\n\n              if (this.page > 1) {\n                this.addListener($prevBtn, 'click', function () {\n                  this.removeListener($prevBtn, 'click');\n                  this.removeListener($nextBtn, 'click');\n                  this.setPage(this.page - 1);\n                  this.updateElements(true, true);\n                });\n              }\n\n              if (this.page < totalPages) {\n                this.addListener($nextBtn, 'click', function () {\n                  this.removeListener($prevBtn, 'click');\n                  this.removeListener($nextBtn, 'click');\n                  this.setPage(this.page + 1);\n                  this.updateElements(true, true);\n                });\n              }\n            }\n          })\n          .catch(() => {\n            this.$countSpinner.addClass('hidden');\n          });\n      }\n\n      // Update the view with the new container + elements HTML\n      // -------------------------------------------------------------\n\n      this.$elements.html(response.html);\n      Craft.appendHeadHtml(response.headHtml);\n      Craft.appendBodyHtml(response.bodyHtml);\n\n      // Batch actions setup\n      // -------------------------------------------------------------\n\n      this.$selectAllContainer = this.$elements.find(\n        '.selectallcontainer:first'\n      );\n\n      if (response.actions && response.actions.length) {\n        if (this.$selectAllContainer.length) {\n          this.actions = response.actions;\n          this.actionsHeadHtml = response.actionsHeadHtml;\n          this.actionsBodyHtml = response.actionsBodyHtml;\n\n          // Create the select all checkbox\n          this.$selectAllCheckbox = $('<div class=\"checkbox\"/>')\n            .prependTo(this.$selectAllContainer)\n            .attr({\n              role: 'checkbox',\n              tabindex: '0',\n              'aria-checked': 'false',\n              'aria-label': Craft.t('app', 'Select all'),\n            });\n\n          this.addListener(this.$selectAllCheckbox, 'click', function () {\n            if (this.view.getSelectedElements().length === 0) {\n              this.view.selectAllElements();\n            } else {\n              this.view.deselectAllElements();\n            }\n          });\n\n          this.addListener(this.$selectAllCheckbox, 'keydown', function (ev) {\n            if (ev.keyCode === Garnish.SPACE_KEY) {\n              ev.preventDefault();\n\n              $(ev.currentTarget).trigger('click');\n            }\n          });\n        }\n      } else {\n        if (!this.$selectAllContainer.siblings().length) {\n          this.$selectAllContainer.parent('.header').remove();\n        }\n        this.$selectAllContainer.remove();\n      }\n\n      // Exporters setup\n      // -------------------------------------------------------------\n\n      this.exporters = response.exporters;\n      this.exportersByType = Craft.index(this.exporters || [], (e) => e.type);\n\n      if (this.exporters && this.exporters.length) {\n        this.$exportBtn.removeClass('hidden');\n      } else {\n        this.$exportBtn.addClass('hidden');\n      }\n\n      // Create the view\n      // -------------------------------------------------------------\n\n      // Should we make the view selectable?\n      const selectable = this.actions || this.settings.selectable;\n      const settings = Object.assign(\n        {\n          context: this.settings.context,\n          batchSize:\n            this.settings.context !== 'index' || this.viewMode === 'structure'\n              ? this.settings.batchSize\n              : null,\n          params: params,\n          selectable: selectable,\n          multiSelect: this.actions || this.settings.multiSelect,\n          canSelectElement: this.settings.canSelectElement,\n          checkboxMode: !!this.actions,\n          onSelectionChange: this._handleSelectionChange.bind(this),\n        },\n        this.getViewSettings()\n      );\n\n      this.view = this.createView(this.getSelectedViewMode(), settings);\n\n      // Auto-select elements\n      // -------------------------------------------------------------\n\n      if (this._autoSelectElements) {\n        if (selectable) {\n          for (var i = 0; i < this._autoSelectElements.length; i++) {\n            this.view.selectElementById(this._autoSelectElements[i]);\n          }\n        }\n\n        this._autoSelectElements = null;\n      }\n\n      // Trigger the event\n      // -------------------------------------------------------------\n\n      this.onUpdateElements();\n    },\n\n    _updateBadgeCounts: function (badgeCounts) {\n      for (let sourceKey in badgeCounts) {\n        if (badgeCounts.hasOwnProperty(sourceKey)) {\n          const $source = this.getSourceByKey(sourceKey);\n          if ($source) {\n            let $badge = $source.children('.badge');\n            if (badgeCounts[sourceKey] !== null) {\n              if (!$badge.length) {\n                $badge = $('<span class=\"badge\"/>').appendTo($source);\n              }\n              $badge.text(badgeCounts[sourceKey]);\n            } else if ($badge) {\n              $badge.remove();\n            }\n          }\n        }\n      }\n    },\n\n    _countResults: function () {\n      return new Promise((resolve, reject) => {\n        if (this.totalResults !== null) {\n          resolve(this.totalResults);\n        } else {\n          var params = this.getViewParams();\n          delete params.criteria.offset;\n          delete params.criteria.limit;\n\n          // Make sure we've got an active result set ID\n          if (this.resultSet === null) {\n            this.resultSet = Math.floor(Math.random() * 100000000);\n          }\n          params.resultSet = this.resultSet;\n\n          Craft.sendActionRequest('POST', this.settings.countElementsAction, {\n            data: params,\n            cancelToken: this._createCancelToken(),\n          })\n            .then((response) => {\n              if (response.data.resultSet == this.resultSet) {\n                this.totalResults = response.data.count;\n                resolve(response.data.count);\n              } else {\n                reject();\n              }\n            })\n            .catch(reject);\n        }\n      });\n    },\n\n    _createTriggers: function () {\n      var triggers = [],\n        safeMenuActions = [],\n        destructiveMenuActions = [];\n\n      var i;\n\n      for (i = 0; i < this.actions.length; i++) {\n        var action = this.actions[i];\n\n        if (action.trigger) {\n          var $form = $(\n            '<form id=\"' +\n              Craft.formatInputId(action.type) +\n              '-actiontrigger\"/>'\n          )\n            .data('action', action)\n            .append(action.trigger);\n\n          $form.find('.btn').addClass('secondary');\n\n          this.addListener($form, 'submit', '_handleActionTriggerSubmit');\n          triggers.push($form);\n        } else {\n          if (!action.destructive) {\n            safeMenuActions.push(action);\n          } else {\n            destructiveMenuActions.push(action);\n          }\n        }\n      }\n\n      var $btn;\n\n      if (safeMenuActions.length || destructiveMenuActions.length) {\n        var $menuTrigger = $('<form/>');\n\n        $btn = $('<button/>', {\n          type: 'button',\n          class: 'btn secondary menubtn',\n          'data-icon': 'settings',\n          title: Craft.t('app', 'Actions'),\n        }).appendTo($menuTrigger);\n\n        var $menu = $('<ul class=\"menu\"/>').appendTo($menuTrigger),\n          $safeList = this._createMenuTriggerList(safeMenuActions, false),\n          $destructiveList = this._createMenuTriggerList(\n            destructiveMenuActions,\n            true\n          );\n\n        if ($safeList) {\n          $safeList.appendTo($menu);\n        }\n\n        if ($safeList && $destructiveList) {\n          $('<hr/>').appendTo($menu);\n        }\n\n        if ($destructiveList) {\n          $destructiveList.appendTo($menu);\n        }\n\n        triggers.push($menuTrigger);\n      }\n\n      this._$triggers = $();\n\n      for (i = 0; i < triggers.length; i++) {\n        var $div = $('<div/>').append(triggers[i]);\n        this._$triggers = this._$triggers.add($div);\n      }\n\n      this._$triggers.appendTo(this.$actionsContainer);\n      Craft.appendHeadHtml(this.actionsHeadHtml);\n      Craft.appendBodyHtml(this.actionsBodyHtml);\n\n      Craft.initUiElements(this._$triggers);\n\n      if ($btn) {\n        $btn\n          .data('menubtn')\n          .on('optionSelect', this._handleMenuActionTriggerSubmit.bind(this));\n      }\n    },\n\n    _showExportHud: function () {\n      this.$exportBtn.addClass('active');\n      this.$exportBtn.attr('aria-expanded', 'true');\n\n      var $form = $('<form/>', {\n        class: 'export-form',\n      });\n\n      var typeOptions = [];\n      for (var i = 0; i < this.exporters.length; i++) {\n        typeOptions.push({\n          label: this.exporters[i].name,\n          value: this.exporters[i].type,\n        });\n      }\n      var $typeField = Craft.ui\n        .createSelectField({\n          label: Craft.t('app', 'Export Type'),\n          options: typeOptions,\n          class: 'fullwidth',\n        })\n        .appendTo($form);\n\n      var $formatField = Craft.ui\n        .createSelectField({\n          label: Craft.t('app', 'Format'),\n          options: [\n            {label: 'CSV', value: 'csv'},\n            {label: 'JSON', value: 'json'},\n            {label: 'XML', value: 'xml'},\n          ],\n          class: 'fullwidth',\n        })\n        .appendTo($form);\n\n      let $typeSelect = $typeField.find('select');\n      this.addListener($typeSelect, 'change', () => {\n        let type = $typeSelect.val();\n        if (this.exportersByType[type].formattable) {\n          $formatField.removeClass('hidden');\n        } else {\n          $formatField.addClass('hidden');\n        }\n      });\n      $typeSelect.trigger('change');\n\n      // Only show the Limit field if there aren't any selected elements\n      var selectedElementIds = this.view.getSelectedElementIds();\n\n      if (!selectedElementIds.length) {\n        var $limitField = Craft.ui\n          .createTextField({\n            label: Craft.t('app', 'Limit'),\n            placeholder: Craft.t('app', 'No limit'),\n            type: 'number',\n            min: 1,\n          })\n          .appendTo($form);\n      }\n\n      const $submitBtn = Craft.ui\n        .createSubmitButton({\n          class: 'fullwidth',\n          label: Craft.t('app', 'Export'),\n          spinner: true,\n        })\n        .appendTo($form);\n\n      const $exportSubmit = new Garnish.MultiFunctionBtn($submitBtn);\n\n      var hud = new Garnish.HUD(this.$exportBtn, $form);\n\n      hud.on('hide', () => {\n        this.$exportBtn.removeClass('active');\n        this.$exportBtn.attr('aria-expanded', 'false');\n      });\n\n      var submitting = false;\n\n      this.addListener($form, 'submit', function (ev) {\n        ev.preventDefault();\n        if (submitting) {\n          return;\n        }\n\n        submitting = true;\n        $exportSubmit.busyEvent();\n\n        var params = this.getViewParams();\n        delete params.criteria.offset;\n        delete params.criteria.limit;\n        delete params.collapsedElementIds;\n\n        params.type = $typeField.find('select').val();\n        params.format = $formatField.find('select').val();\n\n        if (selectedElementIds.length) {\n          params.criteria.id = selectedElementIds;\n        } else {\n          var limit = parseInt($limitField.find('input').val());\n          if (limit && !isNaN(limit)) {\n            params.criteria.limit = limit;\n          }\n        }\n\n        if (Craft.csrfTokenValue) {\n          params[Craft.csrfTokenName] = Craft.csrfTokenValue;\n        }\n\n        Craft.downloadFromUrl(\n          'POST',\n          Craft.getActionUrl('element-indexes/export'),\n          params\n        )\n          .catch((e) => {\n            if (!axios.isCancel(e)) {\n              Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n            }\n          })\n          .finally(() => {\n            submitting = false;\n            $exportSubmit.successEvent();\n          });\n      });\n    },\n\n    _createMenuTriggerList: function (actions, destructive) {\n      if (actions && actions.length) {\n        var $ul = $('<ul/>');\n\n        for (var i = 0; i < actions.length; i++) {\n          $('<li/>')\n            .append(\n              $('<a/>', {\n                id: Craft.formatInputId(actions[i].type) + '-actiontrigger',\n                class: destructive ? 'error' : null,\n                data: {\n                  action: actions[i],\n                },\n                text: actions[i].name,\n              })\n            )\n            .appendTo($ul);\n        }\n\n        return $ul;\n      }\n    },\n\n    showFilterHud: function () {\n      if (!this.filterHuds[this.siteId]) {\n        this.filterHuds[this.siteId] = {};\n      }\n      if (!this.filterHuds[this.siteId][this.sourceKey]) {\n        this.filterHuds[this.siteId][this.sourceKey] = new FilterHud(\n          this,\n          this.sourceKey,\n          this.siteId\n        );\n        this.updateFilterBtn();\n      } else {\n        this.filterHuds[this.siteId][this.sourceKey].show();\n      }\n    },\n\n    updateFilterBtn: function () {\n      this.$filterBtn.removeClass('active');\n\n      if (\n        this.filterHuds[this.siteId] &&\n        this.filterHuds[this.siteId][this.sourceKey]\n      ) {\n        this.$filterBtn\n          .attr(\n            'aria-controls',\n            this.filterHuds[this.siteId][this.sourceKey].id\n          )\n          .attr(\n            'aria-expanded',\n            this.filterHuds[this.siteId][this.sourceKey].showing\n              ? 'true'\n              : 'false'\n          );\n\n        if (\n          this.filterHuds[this.siteId][this.sourceKey].showing ||\n          this.filterHuds[this.siteId][this.sourceKey].hasRules()\n        ) {\n          this.$filterBtn.addClass('active');\n        }\n      } else {\n        this.$filterBtn.attr('aria-controls', null);\n      }\n    },\n  },\n  {\n    defaults: {\n      context: 'index',\n      modal: null,\n      storageKey: null,\n      condition: null,\n      referenceElementId: null,\n      referenceElementSiteId: null,\n      criteria: null,\n      batchSize: 100,\n      disabledElementIds: [],\n      selectable: false,\n      multiSelect: false,\n      canSelectElement: null,\n      buttonContainer: null,\n      hideSidebar: false,\n      toolbarSelector: '.toolbar:first',\n      refreshSourcesAction: 'element-indexes/get-source-tree-html',\n      updateElementsAction: 'element-indexes/get-elements',\n      countElementsAction: 'element-indexes/count-elements',\n      submitActionsAction: 'element-indexes/perform-action',\n      defaultSiteId: null,\n      defaultSource: null,\n      defaultSourcePath: null,\n      showSourcePath: true,\n      canHaveDrafts: false,\n\n      elementTypeName: Craft.t('app', 'Element'),\n      elementTypePluralName: Craft.t('app', 'Elements'),\n\n      onAfterInit: $.noop,\n      onSelectSource: $.noop,\n      onSelectSite: $.noop,\n      onUpdateElements: $.noop,\n      onSelectionChange: $.noop,\n      onSourcePathChange: $.noop,\n      onEnableElements: $.noop,\n      onDisableElements: $.noop,\n      onAfterAction: $.noop,\n    },\n  }\n);\n\nconst ViewMenu = Garnish.Base.extend({\n  elementIndex: null,\n  $source: null,\n  sourceKey: null,\n  menu: null,\n  id: null,\n\n  $trigger: null,\n  $container: null,\n  $sortField: null,\n  $sortAttributeSelect: null,\n  $sortDirectionPicker: null,\n  sortDirectionListbox: null,\n  $tableColumnsField: null,\n  $tableColumnsContainer: null,\n  $revertContainer: null,\n  $revertBtn: null,\n  $closeBtn: null,\n\n  init: function (elementIndex, $source) {\n    this.elementIndex = elementIndex;\n    this.$source = $source;\n    this.sourceKey = $source.data('key');\n    this.id = `view-menu-${Math.floor(Math.random() * 1000000000)}`;\n\n    this.$trigger = $('<button/>', {\n      type: 'button',\n      class: 'btn menubtn hidden',\n      text: Craft.t('app', 'View'),\n      'aria-label': Craft.t('app', 'View settings'),\n      'aria-controls': this.id,\n      'data-icon': 'sliders',\n    }).appendTo(this.elementIndex.$toolbar);\n\n    this.$container = $('<div/>', {\n      id: this.id,\n      class: 'menu menu--disclosure element-index-view-menu',\n      'data-align': 'right',\n    }).appendTo(Garnish.$bod);\n\n    this._buildMenu();\n\n    this.addListener(this.$container, 'mousedown', (ev) => {\n      ev.stopPropagation();\n    });\n\n    this.menu = new Garnish.DisclosureMenu(this.$trigger);\n\n    this.menu.on('show', () => {\n      this.$trigger.addClass('active');\n    });\n\n    this.menu.on('hide', () => {\n      this.$trigger.removeClass('active');\n\n      // Move all checked table column checkboxes to the top once it's fully faded out\n      setTimeout(() => {\n        this.tidyTableColumnField();\n      }, Garnish.FX_DURATION);\n    });\n  },\n\n  showTrigger: function () {\n    this.$trigger.removeClass('hidden');\n  },\n\n  hideTrigger: function () {\n    this.$trigger.data('trigger').hide();\n    this.$trigger.addClass('hidden');\n    this.menu.hide();\n  },\n\n  updateSortField: function () {\n    if (this.$sortField) {\n      if (this.elementIndex.viewMode === 'structure') {\n        this.$sortField.addClass('hidden');\n        this.$tableColumnsField.addClass('first-child');\n      } else {\n        this.$sortField.removeClass('hidden');\n        this.$tableColumnsField.removeClass('first-child');\n      }\n    }\n\n    let [attribute, direction] =\n      this.elementIndex.getSortAttributeAndDirection();\n\n    // Add/remove a score option\n    const $scoreOption = this.$sortAttributeSelect.children(\n      'option[value=\"score\"]'\n    );\n\n    // If searching by score, just keep showing the actual selection\n    if (this.elementIndex.searching) {\n      if (!$scoreOption.length) {\n        this.$sortAttributeSelect.prepend(\n          $('<option/>', {\n            value: 'score',\n            text: Craft.t('app', 'Score'),\n          })\n        );\n      }\n    } else if ($scoreOption.length) {\n      $scoreOption.remove();\n    }\n\n    this.$sortAttributeSelect.val(attribute);\n    this.sortDirectionListbox.select(direction === 'asc' ? 0 : 1);\n\n    if (attribute === 'score') {\n      this.sortDirectionListbox.disable();\n      this.$sortDirectionPicker.addClass('disabled');\n    } else {\n      this.sortDirectionListbox.enable();\n      this.$sortDirectionPicker.removeClass('disabled');\n    }\n  },\n\n  updateTableColumnField: function () {\n    const attributes = this.elementIndex.getSelectedTableColumns();\n    let $lastContainer, lastIndex;\n\n    attributes.forEach((attribute) => {\n      const $checkbox = this.$tableColumnsContainer.find(\n        `input[value=\"${attribute}\"]`\n      );\n      if (!$checkbox.prop('checked')) {\n        $checkbox.prop('checked', true);\n      }\n      const $container = $checkbox.parent();\n\n      // Do we need to move it up?\n      if ($lastContainer && $container.index() < lastIndex) {\n        $container.insertAfter($lastContainer);\n      }\n\n      $lastContainer = $container;\n      lastIndex = $container.index();\n    });\n\n    // See if we need to uncheck any checkboxes\n    const $checkboxes = this._getTableColumnCheckboxes();\n    for (let i = 0; i < $checkboxes.length; i++) {\n      const $checkbox = $checkboxes.eq(i);\n      if ($checkbox.prop('checked') && !attributes.includes($checkbox.val())) {\n        $checkbox.prop('checked', false);\n      }\n    }\n  },\n\n  tidyTableColumnField: function () {\n    const defaultOrder = this.elementIndex\n      .getTableColumnOptions(this.$source)\n      .map((column) => column.attr)\n      .reduce((obj, attr, index) => {\n        return {...obj, [attr]: index};\n      }, {});\n\n    this.$tableColumnsContainer\n      .children()\n      .sort((a, b) => {\n        const checkboxA = $(a).children('input[type=\"checkbox\"]')[0];\n        const checkboxB = $(b).children('input[type=\"checkbox\"]')[0];\n        if (checkboxA.checked && checkboxB.checked) {\n          return 0;\n        }\n        if (checkboxA.checked || checkboxB.checked) {\n          return checkboxA.checked ? -1 : 1;\n        }\n        return defaultOrder[checkboxA.value] < defaultOrder[checkboxB.value]\n          ? -1\n          : 1;\n      })\n      .appendTo(this.$tableColumnsContainer);\n  },\n\n  revert: function () {\n    this.elementIndex.setSelecetedSourceState({\n      order: null,\n      sort: null,\n      tableColumns: null,\n    });\n\n    this.updateSortField();\n    this.updateTableColumnField();\n    this.tidyTableColumnField();\n\n    this.$revertBtn.remove();\n    this.$revertBtn = null;\n\n    this.$closeBtn.focus();\n    this.elementIndex.updateElements();\n  },\n\n  _buildMenu: function () {\n    const $metaContainer = $('<div class=\"meta\"/>').appendTo(this.$container);\n    this.$sortField = this._createSortField().appendTo($metaContainer);\n    this.$tableColumnsField =\n      this._createTableColumnsField().appendTo($metaContainer);\n    this.updateSortField();\n\n    this.$sortAttributeSelect.focus();\n\n    const $footerContainer = $('<div/>', {\n      class: 'flex menu-footer',\n    }).appendTo(this.$container);\n\n    this.$revertContainer = $('<div/>', {\n      class: 'flex-grow',\n    }).appendTo($footerContainer);\n\n    // Only create the revert button if there's a custom view state\n    if (\n      this.elementIndex.getSelectedSourceState('order') ||\n      this.elementIndex.getSelectedSourceState('sort') ||\n      this.elementIndex.getSelectedSourceState('tableColumns')\n    ) {\n      this._createRevertBtn();\n    }\n\n    this.$closeBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Close'),\n    })\n      .appendTo($footerContainer)\n      .on('click', () => {\n        this.menu.hide();\n      });\n  },\n\n  _createSortField: function () {\n    const $container = $('<div class=\"flex\"/>');\n\n    const $sortAttributeSelectContainer = Craft.ui\n      .createSelect({\n        options: this.elementIndex.getSortOptions(this.$source).map((o) => {\n          return {\n            label: Craft.escapeHtml(o.label),\n            value: o.attr,\n          };\n        }),\n      })\n      .addClass('fullwidth')\n      .appendTo($('<div class=\"flex-grow\"/>').appendTo($container));\n\n    this.$sortAttributeSelect = $sortAttributeSelectContainer\n      .children('select')\n      .attr({\n        'aria-label': Craft.t('app', 'Sort attribute'),\n      });\n\n    this.$sortDirectionPicker = $('<section/>', {\n      class: 'btngroup btngroup--exclusive',\n      'aria-label': Craft.t('app', 'Sort direction'),\n    })\n      .append(\n        $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          title: Craft.t('app', 'Sort ascending'),\n          'aria-label': Craft.t('app', 'Sort ascending'),\n          'aria-pressed': 'false',\n          'data-icon': 'asc',\n          'data-dir': 'asc',\n        })\n      )\n      .append(\n        $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          title: Craft.t('app', 'Sort descending'),\n          'aria-label': Craft.t('app', 'Sort descending'),\n          'aria-pressed': 'false',\n          'data-icon': 'desc',\n          'data-dir': 'desc',\n        })\n      )\n      .appendTo($container);\n\n    this.sortDirectionListbox = new Craft.Listbox(this.$sortDirectionPicker, {\n      onChange: ($selectedOption) => {\n        const direction = $selectedOption.data('dir');\n        if (direction !== this.elementIndex.getSelectedSortDirection()) {\n          this.elementIndex.setSelectedSortAttribute(\n            this.$sortAttributeSelect.val(),\n            $selectedOption.data('dir')\n          );\n\n          if (!this.elementIndex.sortByScore) {\n            // In case it's actually the structure view\n            this.elementIndex.selectViewMode(this.elementIndex.viewMode);\n          }\n\n          this.elementIndex.updateElements();\n          this._createRevertBtn();\n        }\n      },\n    });\n\n    this.$sortAttributeSelect.on('change', () => {\n      this.elementIndex.setSelectedSortAttribute(\n        this.$sortAttributeSelect.val(),\n        null,\n        false\n      );\n\n      // In case it's actually the structure view\n      this.elementIndex.selectViewMode(this.elementIndex.viewMode);\n\n      this.elementIndex.updateElements();\n      this._createRevertBtn();\n    });\n\n    const $field = Craft.ui.createField($container, {\n      label: Craft.t('app', 'Sort by'),\n      fieldset: true,\n    });\n    $field.addClass('sort-field');\n    return $field;\n  },\n\n  _getTableColumnCheckboxes: function () {\n    return this.$tableColumnsContainer.find('input[type=\"checkbox\"]');\n  },\n\n  _createTableColumnsField: function () {\n    const columns = this.elementIndex.getTableColumnOptions(this.$source);\n\n    if (!columns.length) {\n      return $();\n    }\n\n    this.$tableColumnsContainer = $('<div/>');\n\n    columns.forEach((column) => {\n      $('<div class=\"element-index-view-menu-table-column\"/>')\n        .append('<div class=\"icon move\"/>')\n        .append(\n          Craft.ui.createCheckbox({\n            label: Craft.escapeHtml(column.label),\n            value: column.attr,\n          })\n        )\n        .appendTo(this.$tableColumnsContainer);\n    });\n\n    this.updateTableColumnField();\n    this.tidyTableColumnField();\n\n    new Garnish.DragSort(this.$tableColumnsContainer.children(), {\n      handle: '.move',\n      axis: 'y',\n      onSortChange: () => {\n        this._onTableColumnChange();\n      },\n    });\n\n    this._getTableColumnCheckboxes().on('change', (ev) => {\n      this._onTableColumnChange();\n    });\n\n    const $field = Craft.ui.createField(this.$tableColumnsContainer, {\n      label: Craft.t('app', 'Table Columns'),\n      fieldset: true,\n    });\n    $field.addClass('table-columns-field');\n    return $field;\n  },\n\n  _onTableColumnChange: function () {\n    const columns = [];\n    const $selectedCheckboxes =\n      this._getTableColumnCheckboxes().filter(':checked');\n    for (let i = 0; i < $selectedCheckboxes.length; i++) {\n      columns.push($selectedCheckboxes.eq(i).val());\n    }\n\n    // Only commit the change if it's different from the current column selections\n    // (maybe an unchecked column was dragged, etc.)\n    if (\n      Craft.compare(\n        columns,\n        this.elementIndex.getSelectedTableColumns(this.$source)\n      )\n    ) {\n      return;\n    }\n\n    this.elementIndex.setSelectedTableColumns(columns, false);\n    this.elementIndex.updateElements();\n    this._createRevertBtn();\n  },\n\n  _createRevertBtn: function () {\n    if (this.$revertBtn) {\n      return;\n    }\n\n    this.$revertBtn = $('<button/>', {\n      type: 'button',\n      class: 'light',\n      text: Craft.t('app', 'Use defaults'),\n    })\n      .appendTo(this.$revertContainer)\n      .on('click', () => {\n        this.revert();\n      });\n  },\n\n  destroy: function () {\n    this.menu.destroy();\n    delete this.menu;\n    this.base();\n  },\n});\n\nconst FilterHud = Garnish.HUD.extend({\n  elementIndex: null,\n  sourceKey: null,\n  siteId: null,\n  id: null,\n  loading: true,\n  serialized: null,\n  $clearBtn: null,\n  cleared: false,\n\n  init: function (elementIndex, sourceKey, siteId) {\n    this.elementIndex = elementIndex;\n    this.sourceKey = sourceKey;\n    this.siteId = siteId;\n    this.id = `filter-${Math.floor(Math.random() * 1000000000)}`;\n\n    const $loadingContent = $('<div/>')\n      .append(\n        $('<div/>', {\n          class: 'spinner',\n        })\n      )\n      .append(\n        $('<div/>', {\n          text: Craft.t('app', 'Loading'),\n          class: 'visually-hidden',\n          'aria-role': 'alert',\n        })\n      );\n\n    this.base(this.elementIndex.$filterBtn, $loadingContent, {\n      hudClass: 'hud element-filter-hud loading',\n    });\n\n    this.$hud.attr({\n      id: this.id,\n      'aria-live': 'polite',\n      'aria-busy': 'false',\n    });\n    this.$tip.remove();\n    this.$tip = null;\n\n    this.$body.on('submit', (ev) => {\n      ev.preventDefault();\n      this.hide();\n    });\n\n    Craft.sendActionRequest('POST', 'element-indexes/filter-hud', {\n      data: {\n        elementType: this.elementIndex.elementType,\n        source: this.sourceKey,\n        condition: this.elementIndex.settings.condition,\n        id: `${this.id}-filters`,\n      },\n    })\n      .then((response) => {\n        this.loading = false;\n        this.$hud.removeClass('loading');\n        $loadingContent.remove();\n\n        this.$main.append(response.data.hudHtml);\n        Craft.appendHeadHtml(response.data.headHtml);\n        Craft.appendBodyHtml(response.data.bodyHtml);\n\n        const $btnContainer = $('<div/>', {\n          class: 'flex flex-nowrap',\n        }).appendTo(this.$main);\n        $('<div/>', {\n          class: 'flex-grow',\n        }).appendTo($btnContainer);\n        this.$clearBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Cancel'),\n        }).appendTo($btnContainer);\n        $('<button/>', {\n          type: 'submit',\n          class: 'btn secondary',\n          text: Craft.t('app', 'Apply'),\n        }).appendTo($btnContainer);\n        this.$clearBtn.on('click', () => {\n          this.clear();\n        });\n\n        this.$hud.find('.condition-container').on('htmx:beforeRequest', () => {\n          this.setBusy();\n        });\n\n        this.$hud.find('.condition-container').on('htmx:load', () => {\n          this.setReady();\n          this.updateSizeAndPosition(true);\n        });\n        this.setFocus();\n      })\n      .catch(() => {\n        Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n      });\n\n    this.$hud.css('position', 'fixed');\n\n    this.addListener(Garnish.$win, 'scroll,resize', () => {\n      this.updateSizeAndPosition(true);\n    });\n  },\n\n  addListener: function (elem, events, data, func) {\n    if (elem === this.$main && events === 'resize') {\n      return;\n    }\n    this.base(elem, events, data, func);\n  },\n\n  setBusy: function () {\n    this.$hud.attr('aria-busy', 'true');\n\n    $('<div/>', {\n      class: 'visually-hidden',\n      text: Craft.t('app', 'Loading'),\n    }).insertAfter(this.$main.find('.htmx-indicator'));\n  },\n\n  setReady: function () {\n    this.$hud.attr('aria-busy', 'false');\n  },\n\n  setFocus: function () {\n    Garnish.setFocusWithin(this.$main);\n  },\n\n  clear: function () {\n    this.cleared = true;\n    this.hide();\n  },\n\n  updateSizeAndPositionInternal: function () {\n    const searchOffset =\n      this.elementIndex.$searchContainer[0].getBoundingClientRect();\n\n    // Ensure HUD is scrollable if content falls off-screen\n    const windowHeight = Garnish.$win.height();\n    let hudHeight;\n    const availableSpace = windowHeight - searchOffset.bottom;\n\n    if (this.$body.height() > availableSpace) {\n      hudHeight = windowHeight - searchOffset.bottom - 10;\n    }\n\n    this.$hud.css({\n      width: this.elementIndex.$searchContainer.outerWidth() - 2,\n      top: searchOffset.top + this.elementIndex.$searchContainer.outerHeight(),\n      left: searchOffset.left + 1,\n      height: hudHeight ? `${hudHeight}px` : 'unset',\n      overflowY: hudHeight ? 'scroll' : 'unset',\n    });\n  },\n\n  onShow: function () {\n    this.base();\n\n    // Cancel => Clear\n    if (this.$clearBtn) {\n      this.$clearBtn.text(Craft.t('app', 'Clear'));\n    }\n\n    this.elementIndex.updateFilterBtn();\n    this.setFocus();\n  },\n\n  onHide: function () {\n    this.base();\n\n    // If something changed, update the elements\n    if (this.serialized !== (this.serialized = this.serialize())) {\n      this.elementIndex.updateElements();\n    }\n\n    if (this.cleared) {\n      this.destroy();\n    } else {\n      this.$hud.detach();\n      this.$shade.detach();\n    }\n\n    this.elementIndex.updateFilterBtn();\n    this.elementIndex.$filterBtn.focus();\n  },\n\n  hasRules: function () {\n    return this.$main.has('.condition-rule').length !== 0;\n  },\n\n  serialize: function () {\n    return !this.cleared && this.hasRules() ? this.$body.serialize() : null;\n  },\n\n  destroy: function () {\n    this.base();\n    delete this.elementIndex.filterHuds[this.siteId][this.sourceKey];\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Base Element Index View\n */\nCraft.BaseElementIndexView = Garnish.Base.extend(\n  {\n    $container: null,\n    $loadingMoreSpinner: null,\n    $elementContainer: null,\n    $scroller: null,\n\n    elementIndex: null,\n    elementSelect: null,\n\n    loadingMore: false,\n\n    _totalVisible: null,\n    _morePending: null,\n    _handleEnableElements: null,\n    _handleDisableElements: null,\n\n    get thumbLoader() {\n      console.warn(\n        'Craft.BaseElementIndexView::thumbLoader is deprecated. Craft.cp.elementThumbLoader should be used instead.'\n      );\n      return Craft.cp.elementThumbLoader;\n    },\n\n    init: function (elementIndex, container, settings) {\n      this.elementIndex = elementIndex;\n      this.$container = $(container);\n      this.setSettings(settings, Craft.BaseElementIndexView.defaults);\n\n      // Create a \"loading-more\" spinner\n      this.$loadingMoreSpinner = $(\n        '<div class=\"centeralign hidden\">' +\n          '<div class=\"spinner loadingmore\"></div>' +\n          '</div>'\n      ).insertAfter(this.$container);\n\n      // Get the actual elements container and its child elements\n      this.$elementContainer = this.getElementContainer();\n      var $elements = this.$elementContainer.children();\n\n      this.setTotalVisible($elements.length);\n      this.setMorePending(\n        this.settings.batchSize && $elements.length == this.settings.batchSize\n      );\n\n      // Load thumbnails\n      Craft.cp.elementThumbLoader.load($elements);\n\n      if (this.settings.selectable) {\n        this.elementSelect = new Garnish.Select(\n          this.$elementContainer,\n          $(\n            $elements\n              .toArray()\n              .filter((element) => this.canSelectElement($(element)))\n          ),\n          {\n            multi: this.settings.multiSelect,\n            vertical: this.isVerticalList(),\n            handle:\n              this.settings.context === 'index'\n                ? '.checkbox, .element:first'\n                : null,\n            filter: ':not(a):not(.toggle)',\n            checkboxMode: this.settings.checkboxMode,\n            onSelectionChange: this.onSelectionChange.bind(this),\n          }\n        );\n\n        this._handleEnableElements = (ev) => {\n          this.elementSelect.addItems(ev.elements);\n        };\n\n        this._handleDisableElements = (ev) => {\n          this.elementSelect.removeItems(ev.elements);\n        };\n\n        this.elementIndex.on('enableElements', this._handleEnableElements);\n        this.elementIndex.on('disableElements', this._handleDisableElements);\n      }\n\n      // Enable inline element editing if this is an index page\n      if (this.settings.context === 'index') {\n        this._handleElementEditing = (ev) => {\n          var $target = $(ev.target);\n\n          if ($target.prop('nodeName') === 'A') {\n            // Let the link do its thing\n            return;\n          }\n\n          var $element;\n\n          if ($target.hasClass('element')) {\n            $element = $target;\n          } else {\n            $element = $target.closest('.element');\n\n            if (!$element.length) {\n              return;\n            }\n          }\n\n          if (Garnish.hasAttr($element, 'data-editable')) {\n            Craft.createElementEditor($element.data('type'), $element);\n          }\n        };\n\n        if (!this.elementIndex.trashed) {\n          this.addListener(\n            this.$elementContainer,\n            'dblclick,taphold',\n            this._handleElementEditing\n          );\n        }\n      }\n\n      // Give sub-classes a chance to do post-initialization stuff here\n      this.afterInit();\n\n      // Set up lazy-loading\n      if (this.settings.batchSize) {\n        if (this.settings.context === 'index') {\n          this.$scroller = Garnish.$scrollContainer;\n        } else {\n          this.$scroller = this.elementIndex.$main;\n        }\n\n        this.$scroller.scrollTop(0);\n        this.addListener(this.$scroller, 'scroll', 'maybeLoadMore');\n        this.maybeLoadMore();\n      }\n    },\n\n    canSelectElement: function ($element) {\n      if ($element.hasClass('disabled')) {\n        return false;\n      }\n      if (this.settings.canSelectElement) {\n        return this.settings.canSelectElement($element);\n      }\n      return !!$element.data('id');\n    },\n\n    getElementContainer: function () {\n      throw 'Classes that extend Craft.BaseElementIndexView must supply a getElementContainer() method.';\n    },\n\n    afterInit: function () {},\n\n    getAllElements: function () {\n      return this.$elementContainer.children();\n    },\n\n    getEnabledElements: function () {\n      return this.$elementContainer.children(':not(.disabled)');\n    },\n\n    getElementById: function (id) {\n      var $element = this.$elementContainer.children(\n        '[data-id=\"' + id + '\"]:first'\n      );\n\n      if ($element.length) {\n        return $element;\n      } else {\n        return null;\n      }\n    },\n\n    getSelectedElements: function () {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      return this.elementSelect.$selectedItems;\n    },\n\n    getSelectedElementIds: function () {\n      let $selectedElements;\n      try {\n        $selectedElements = this.getSelectedElements();\n      } catch (e) {}\n\n      let ids = [];\n      if ($selectedElements) {\n        for (var i = 0; i < $selectedElements.length; i++) {\n          ids.push($selectedElements.eq(i).data('id'));\n        }\n      }\n      return ids;\n    },\n\n    selectElement: function ($element) {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      this.elementSelect.selectItem($element, true);\n      return true;\n    },\n\n    selectElementById: function (id) {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      var $element = this.getElementById(id);\n\n      if ($element) {\n        this.elementSelect.selectItem($element, true);\n        return true;\n      } else {\n        return false;\n      }\n    },\n\n    selectAllElements: function () {\n      this.elementSelect.selectAll();\n    },\n\n    deselectAllElements: function () {\n      this.elementSelect.deselectAll();\n    },\n\n    getElementCheckbox: function (element) {\n      return $(element).find('[role=\"checkbox\"]');\n    },\n\n    isVerticalList: function () {\n      return false;\n    },\n\n    getTotalVisible: function () {\n      return this._totalVisible;\n    },\n\n    setTotalVisible: function (totalVisible) {\n      this._totalVisible = totalVisible;\n    },\n\n    getMorePending: function () {\n      return this._morePending;\n    },\n\n    setMorePending: function (morePending) {\n      this._morePending = morePending;\n    },\n\n    /**\n     * Checks if the user has reached the bottom of the scroll area, and if so, loads the next batch of elemets.\n     */\n    maybeLoadMore: function () {\n      if (this.canLoadMore()) {\n        this.loadMore();\n      }\n    },\n\n    /**\n     * Returns whether the user has reached the bottom of the scroll area.\n     */\n    canLoadMore: function () {\n      if (!this.getMorePending() || !this.settings.batchSize) {\n        return false;\n      }\n\n      // Check if the user has reached the bottom of the scroll area\n      var containerHeight;\n\n      if (this.$scroller[0] === Garnish.$win[0]) {\n        var winHeight = Garnish.$win.innerHeight(),\n          winScrollTop = Garnish.$win.scrollTop(),\n          containerOffset = this.$container.offset().top;\n        containerHeight = this.$container.height();\n\n        return winHeight + winScrollTop >= containerOffset + containerHeight;\n      } else {\n        var containerScrollHeight = this.$scroller.prop('scrollHeight'),\n          containerScrollTop = this.$scroller.scrollTop();\n        containerHeight = this.$scroller.outerHeight();\n\n        return (\n          containerScrollHeight - containerScrollTop <= containerHeight + 15\n        );\n      }\n    },\n\n    /**\n     * Loads the next batch of elements.\n     */\n    loadMore: function () {\n      if (\n        !this.getMorePending() ||\n        this.loadingMore ||\n        !this.settings.batchSize\n      ) {\n        return;\n      }\n\n      this.loadingMore = true;\n      this.$loadingMoreSpinner.removeClass('hidden');\n      this.removeListener(this.$scroller, 'scroll');\n\n      Craft.sendActionRequest('POST', this.settings.loadMoreElementsAction, {\n        data: this.getLoadMoreParams(),\n      })\n        .then((response) => {\n          this.loadingMore = false;\n          this.$loadingMoreSpinner.addClass('hidden');\n\n          let $newElements = $(response.data.html);\n\n          this.appendElements($newElements);\n          Craft.appendHeadHtml(response.data.headHtml);\n          Craft.appendBodyHtml(response.data.bodyHtml);\n\n          if (this.elementSelect) {\n            this.elementSelect.addItems($newElements.filter(':not(.disabled)'));\n            this.elementIndex.updateActionTriggers();\n          }\n\n          this.setTotalVisible(this.getTotalVisible() + $newElements.length);\n          this.setMorePending($newElements.length == this.settings.batchSize);\n\n          // Is there room to load more right now?\n          this.addListener(this.$scroller, 'scroll', 'maybeLoadMore');\n          this.maybeLoadMore();\n        })\n        .catch((e) => {\n          this.loadingMore = false;\n          this.$loadingMoreSpinner.addClass('hidden');\n        });\n    },\n\n    getLoadMoreParams: function () {\n      // Use the same params that were passed when initializing this view\n      var params = $.extend(true, {}, this.settings.params);\n      params.criteria.offset = this.getTotalVisible();\n      return params;\n    },\n\n    appendElements: function ($newElements) {\n      $newElements.appendTo(this.$elementContainer);\n      Craft.cp.elementThumbLoader.load($newElements);\n      this.onAppendElements($newElements);\n    },\n\n    onAppendElements: function ($newElements) {\n      this.settings.onAppendElements($newElements);\n      this.trigger('appendElements', {\n        newElements: $newElements,\n      });\n    },\n\n    onSelectionChange: function () {\n      this.settings.onSelectionChange();\n      this.trigger('selectionChange');\n\n      // Update checkboxes\n      if (this.settings.checkboxMode) {\n        const $items = this.elementSelect.$items.each((index, item) => {\n          if (this.elementSelect.isSelected(item)) {\n            this.getElementCheckbox(item).attr('aria-checked', 'true');\n          } else {\n            this.getElementCheckbox(item).attr('aria-checked', 'false');\n          }\n        });\n      }\n    },\n\n    disable: function () {\n      if (this.elementSelect) {\n        this.elementSelect.disable();\n      }\n    },\n\n    enable: function () {\n      if (this.elementSelect) {\n        this.elementSelect.enable();\n      }\n    },\n\n    destroy: function () {\n      // Remove the \"loading-more\" spinner, since we added that outside of the view container\n      this.$loadingMoreSpinner.remove();\n\n      // Delete the element select\n      if (this.elementSelect) {\n        this.elementIndex.off('enableElements', this._handleEnableElements);\n        this.elementIndex.off('disableElements', this._handleDisableElements);\n\n        this.elementSelect.destroy();\n        delete this.elementSelect;\n      }\n\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      context: 'index',\n      batchSize: null,\n      params: null,\n      selectable: false,\n      multiSelect: false,\n      canSelectElement: null,\n      checkboxMode: false,\n      loadMoreElementsAction: 'element-indexes/get-more-elements',\n      onAppendElements: $.noop,\n      onSelectionChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Select input\n */\nCraft.BaseElementSelectInput = Garnish.Base.extend(\n  {\n    elementSelect: null,\n    elementSort: null,\n    modal: null,\n    elementEditor: null,\n\n    $container: null,\n    $form: null,\n    $elementsContainer: null,\n    $elements: null,\n    $addElementBtn: null,\n    $spinner: null,\n\n    _initialized: false,\n\n    get thumbLoader() {\n      console.warn(\n        'Craft.BaseElementSelectInput::thumbLoader is deprecated. Craft.cp.elementThumbLoader should be used instead.'\n      );\n      return Craft.cp.elementThumbLoader;\n    },\n\n    init: function (settings) {\n      // Normalize the settings and set them\n      // ---------------------------------------------------------------------\n\n      // Are they still passing in a bunch of arguments?\n      if (!$.isPlainObject(settings)) {\n        // Loop through all of the old arguments and apply them to the settings\n        var normalizedSettings = {},\n          args = [\n            'id',\n            'name',\n            'elementType',\n            'sources',\n            'criteria',\n            'sourceElementId',\n            'limit',\n            'modalStorageKey',\n            'fieldId',\n          ];\n\n        for (var i = 0; i < args.length; i++) {\n          if (typeof arguments[i] !== 'undefined') {\n            normalizedSettings[args[i]] = arguments[i];\n          } else {\n            break;\n          }\n        }\n\n        settings = normalizedSettings;\n      }\n\n      this.setSettings(settings, Craft.BaseElementSelectInput.defaults);\n\n      // Apply the storage key prefix\n      if (this.settings.modalStorageKey) {\n        this.modalStorageKey =\n          'BaseElementSelectInput.' + this.settings.modalStorageKey;\n      }\n\n      // No reason for this to be sortable if we're only allowing 1 selection\n      if (this.settings.limit == 1 || this.settings.maintainHierarchy) {\n        this.settings.sortable = false;\n      }\n\n      this.$container = this.getContainer();\n      this.$form = this.$container.closest('form');\n\n      // Store a reference to this class\n      this.$container.data('elementSelect', this);\n\n      this.$elementsContainer = this.getElementsContainer();\n      this.$addElementBtn = this.getAddElementsBtn();\n      this.$spinner = this.getSpinner();\n\n      this.initElementSelect();\n      this.initElementSort();\n      this.resetElements();\n\n      if (this.$addElementBtn) {\n        this.addListener(this.$addElementBtn, 'activate', 'showModal');\n      }\n\n      Garnish.requestAnimationFrame(() => {\n        this._initialized = true;\n      });\n    },\n\n    get totalSelected() {\n      return this.$elements.length;\n    },\n\n    getContainer: function () {\n      return $('#' + this.settings.id);\n    },\n\n    getElementsContainer: function () {\n      return this.$container.children('.elements');\n    },\n\n    getElements: function () {\n      return this.$elementsContainer.find('.element');\n    },\n\n    getAddElementsBtn: function () {\n      return this.$container.find('.btn.add:first');\n    },\n\n    getSpinner: function () {\n      return this.$container.find('.spinner');\n    },\n\n    initElementSelect: function () {\n      if (this.settings.selectable) {\n        this.elementSelect = new Garnish.Select({\n          multi: this.settings.sortable,\n          filter: ':not(.delete)',\n        });\n      }\n    },\n\n    initElementSort: function () {\n      if (this.settings.sortable) {\n        this.elementSort = new Garnish.DragSort({\n          container: this.$elementsContainer,\n          filter: this.settings.selectable\n            ? () => {\n                // Only return all the selected items if the target item is selected\n                if (this.elementSort.$targetItem.hasClass('sel')) {\n                  return this.elementSelect.getSelectedItems();\n                } else {\n                  return this.elementSort.$targetItem;\n                }\n              }\n            : null,\n          ignoreHandleSelector: '.delete',\n          axis: this.getElementSortAxis(),\n          collapseDraggees: true,\n          magnetStrength: 4,\n          helperLagBase: 1.5,\n          onSortChange: this.settings.selectable\n            ? () => {\n                this.elementSelect.resetItemOrder();\n              }\n            : null,\n        });\n      }\n    },\n\n    getElementSortAxis: function () {\n      return this.settings.viewMode === 'list' ? 'y' : null;\n    },\n\n    canAddMoreElements: function () {\n      return (\n        !this.settings.limit || this.$elements.length < this.settings.limit\n      );\n    },\n\n    updateAddElementsBtn: function () {\n      if (this.canAddMoreElements()) {\n        this.enableAddElementsBtn();\n      } else {\n        this.disableAddElementsBtn();\n      }\n    },\n\n    enableAddElementsBtn: function () {\n      if (this.$addElementBtn) {\n        this.$addElementBtn.removeClass('hidden');\n      }\n\n      this.updateButtonContainer();\n    },\n\n    disableAddElementsBtn: function () {\n      if (this.$addElementBtn) {\n        this.$addElementBtn.addClass('hidden');\n      }\n\n      this.updateButtonContainer();\n    },\n\n    showSpinner: function () {\n      if (this.$spinner) {\n        this.$spinner.removeClass('hidden');\n      }\n\n      this.updateButtonContainer();\n    },\n\n    hideSpinner: function () {\n      if (this.$spinner) {\n        this.$spinner.addClass('hidden');\n      }\n\n      this.updateButtonContainer();\n    },\n\n    updateButtonContainer: function () {\n      const $container =\n        this.$addElementBtn && this.$addElementBtn.parent('.flex');\n      if ($container && $container.length) {\n        if ($container.children(':not(.hidden)').length) {\n          $container.removeClass('hidden');\n        } else {\n          $container.addClass('hidden');\n        }\n      }\n    },\n\n    focusNextLogicalElement: function () {\n      if (this.canAddMoreElements()) {\n        // If can add more elements, focus ADD button\n        let $btn = this.$addElementBtn;\n\n        if ($btn) {\n          $btn.get(0).focus();\n        }\n      } else {\n        // If can't add more elements, focus on the final remove\n        this.focusLastRemoveBtn();\n      }\n    },\n\n    focusLastRemoveBtn: function () {\n      const $removeBtns = this.$container.find('.delete');\n\n      if (!$removeBtns.length) return;\n\n      $removeBtns.last()[0].focus();\n    },\n\n    resetElements: function () {\n      if (this.$elements !== null) {\n        this.removeElements(this.$elements);\n      } else {\n        this.$elements = $();\n      }\n\n      this.addElements(this.getElements());\n    },\n\n    addElements: function ($elements) {\n      Craft.cp.elementThumbLoader.load($elements);\n\n      if (this.settings.selectable) {\n        this.elementSelect.addItems($elements);\n      }\n\n      if (this.settings.sortable) {\n        this.elementSort.addItems($elements);\n      }\n\n      if (this.settings.editable) {\n        this._handleShowElementEditor = (ev) => {\n          var $element = $(ev.currentTarget);\n          if (\n            Garnish.hasAttr($element, 'data-editable') &&\n            !$element.hasClass('disabled') &&\n            !$element.hasClass('loading')\n          ) {\n            this.elementEditor = this.createElementEditor($element);\n          }\n        };\n\n        this.addListener($elements, 'dblclick', this._handleShowElementEditor);\n\n        if ($.isTouchCapable()) {\n          this.addListener($elements, 'taphold', this._handleShowElementEditor);\n        }\n      }\n\n      $elements.find('.delete').on('click dblclick', (ev) => {\n        this.removeElement($(ev.currentTarget).closest('.element'));\n        // Prevent this from acting as one of a double-click\n        ev.stopPropagation();\n      });\n\n      $elements.on('keydown', (ev) => {\n        if ([Garnish.BACKSPACE_KEY, Garnish.DELETE_KEY].includes(ev.keyCode)) {\n          ev.stopPropagation();\n          ev.preventDefault();\n          const $elements = this.elementSelect.getSelectedItems();\n          for (let i = 0; i < $elements.length; i++) {\n            this.removeElement($elements.eq(i));\n          }\n        }\n      });\n\n      this.$elements = this.$elements.add($elements);\n\n      this.updateAddElementsBtn();\n\n      this.onAddElements();\n    },\n\n    createElementEditor: function ($element, settings) {\n      settings = Object.assign(\n        {\n          elementSelectInput: this,\n          prevalidate: this.settings.prevalidate,\n        },\n        settings\n      );\n\n      return Craft.createElementEditor(\n        this.settings.elementType,\n        $element,\n        settings\n      );\n    },\n\n    replaceElement: function (elementId, replacementId) {\n      return new Promise((resolve, reject) => {\n        const $existing = this.$elements.filter(`[data-id=\"${elementId}\"]`);\n\n        if (!$existing.length) {\n          reject(`No element selected with an ID of ${elementId}.`);\n          return;\n        }\n\n        this.showSpinner();\n\n        const data = {\n          elementId: replacementId,\n          siteId: this.settings.criteria.siteId,\n          thumbSize: this.settings.viewMode,\n        };\n\n        Craft.sendActionRequest('POST', 'elements/get-element-html', {data})\n          .then((response) => {\n            this.removeElement($existing);\n            const elementInfo = Craft.getElementInfo(response.data.html);\n            this.selectElements([elementInfo]);\n            resolve();\n          })\n          .catch(({response}) => {\n            if (response && response.data && response.data.message) {\n              Craft.cp.displayError(response.data.message);\n            } else {\n              Craft.cp.displayError();\n            }\n\n            reject(response.data.message);\n          })\n          .finally(() => {\n            this.hideSpinner();\n          });\n      });\n    },\n\n    removeElements: function ($elements) {\n      if (this.settings.selectable) {\n        this.elementSelect.removeItems($elements);\n      }\n\n      if (this.modal) {\n        var ids = [];\n\n        for (var i = 0; i < $elements.length; i++) {\n          var id = $elements.eq(i).data('id');\n\n          if (id) {\n            ids.push(id);\n          }\n        }\n\n        if (ids.length) {\n          this.modal.elementIndex.enableElementsById(ids);\n        }\n      }\n\n      // Disable the hidden input in case the form is submitted before this element gets removed from the DOM\n      $elements.children('input').prop('disabled', true);\n\n      // Move the focus to the next element in the list, if there is one\n      let $nextDeleteBtn;\n      if (this.settings.selectable) {\n        const lastElementIndex = this.$elements.index($elements.last());\n        $nextDeleteBtn = this.$elements\n          .eq(lastElementIndex + 1)\n          .find('.delete');\n      }\n      if ($nextDeleteBtn.length) {\n        $nextDeleteBtn.focus();\n      } else {\n        this.focusNextLogicalElement();\n      }\n\n      this.$elements = this.$elements.not($elements);\n      this.updateAddElementsBtn();\n\n      this.onRemoveElements();\n    },\n\n    removeElement: function ($element) {\n      if (this.settings.maintainHierarchy) {\n        // Find any descendants this element might have\n        const $allElements = $element.add(\n          $element.parent().siblings('ul').find('.element')\n        );\n\n        // Remove any inputs from the form data\n        $('[name]', $allElements).removeAttr('name');\n\n        // Remove our record of them all at once\n        this.removeElements($allElements);\n\n        // Animate them away one at a time\n        for (let i = 0; i < $allElements.length; i++) {\n          this._animateStructureElementAway($allElements, i);\n        }\n      } else {\n        // Remove any inputs from the form data\n        $('[name]', $element).removeAttr('name');\n        this.removeElements($element);\n        this.animateElementAway($element, () => {\n          $element.remove();\n        });\n      }\n    },\n\n    animateElementAway: function ($element, callback) {\n      $element.css('z-index', 0);\n\n      var animateCss = {\n        opacity: -1,\n      };\n      animateCss['margin-' + Craft.left] = -(\n        $element.outerWidth() + parseInt($element.css('margin-' + Craft.right))\n      );\n\n      if (this.settings.viewMode === 'list' || this.$elements.length === 0) {\n        animateCss['margin-bottom'] = -(\n          $element.outerHeight() + parseInt($element.css('margin-bottom'))\n        );\n      }\n\n      $element.velocity(\n        animateCss,\n        Craft.BaseElementSelectInput.REMOVE_FX_DURATION,\n        () => {\n          if (callback) {\n            callback();\n          }\n        }\n      );\n    },\n\n    showModal: function () {\n      // Make sure we haven't reached the limit\n      if (!this.canAddMoreElements()) {\n        return;\n      }\n\n      if (!this.modal) {\n        this.modal = this.createModal();\n      } else {\n        this.modal.show();\n      }\n    },\n\n    createModal: function () {\n      return Craft.createElementSelectorModal(\n        this.settings.elementType,\n        this.getModalSettings()\n      );\n    },\n\n    getModalSettings: function () {\n      return $.extend(\n        {\n          closeOtherModals: false,\n          storageKey: this.modalStorageKey,\n          sources: this.settings.sources,\n          condition: this.settings.condition,\n          referenceElementId: this.settings.referenceElementId,\n          referenceElementSiteId: this.settings.referenceElementSiteId,\n          criteria: this.settings.criteria,\n          multiSelect: this.settings.limit != 1,\n          hideOnSelect: !this.settings.maintainHierarchy,\n          showSiteMenu: this.settings.showSiteMenu,\n          disabledElementIds: this.getDisabledElementIds(),\n          onSelect: this.onModalSelect.bind(this),\n          onHide: this.onModalHide.bind(this),\n          triggerElement: this.$addElementBtn,\n          modalTitle: Craft.t('app', 'Choose'),\n        },\n        this.settings.modalSettings\n      );\n    },\n\n    getSelectedElementIds: function () {\n      var ids = [];\n\n      for (var i = 0; i < this.$elements.length; i++) {\n        ids.push(this.$elements.eq(i).data('id'));\n      }\n\n      return ids;\n    },\n\n    getDisabledElementIds: function () {\n      var ids = this.getSelectedElementIds();\n\n      if (!this.settings.allowSelfRelations && this.settings.sourceElementId) {\n        ids.push(this.settings.sourceElementId);\n      }\n\n      if (this.settings.disabledElementIds) {\n        ids.push(...this.settings.disabledElementIds);\n      }\n\n      return ids;\n    },\n\n    onModalSelect: function (elements) {\n      if (this.settings.maintainHierarchy) {\n        this.selectStructuredElements(elements);\n      } else {\n        if (this.settings.limit) {\n          // Cut off any excess elements\n          var slotsLeft = this.settings.limit - this.$elements.length;\n\n          if (elements.length > slotsLeft) {\n            elements = elements.slice(0, slotsLeft);\n          }\n        }\n\n        this.selectElements(elements);\n        this.updateDisabledElementsInModal();\n      }\n    },\n\n    onModalHide: function () {\n      // If the modal has a condition and a reference element, recreate it each time it’s opened\n      // in case something about the edited element is going to affect the condition\n      if (\n        this.modal &&\n        this.settings.condition &&\n        this.settings.referenceElementId\n      ) {\n        this.modal.destroy();\n        this.modal = null;\n      }\n\n      // If can add more elements, do default behavior of focus on \"Add\" button\n      if (this.canAddMoreElements()) return;\n\n      setTimeout(() => {\n        this.focusNextLogicalElement();\n      }, 200);\n    },\n\n    selectElements: function (elements) {\n      for (let i = 0; i < elements.length; i++) {\n        let elementInfo = elements[i],\n          $element = this.createNewElement(elementInfo);\n\n        this.appendElement($element);\n        this.addElements($element);\n        this.animateElementIntoPlace(elementInfo.$element, $element);\n\n        // Override the element reference with the new one\n        elementInfo.$element = $element;\n      }\n\n      this.onSelectElements(elements);\n    },\n\n    selectStructuredElements: function (elements) {\n      // Disable the modal\n      this.modal.disable();\n      this.modal.disableCancelBtn();\n      this.modal.disableSelectBtn();\n      this.modal.showFooterSpinner();\n\n      // Get the new element HTML\n      var selectedElementIds = this.getSelectedElementIds();\n\n      for (var i = 0; i < elements.length; i++) {\n        selectedElementIds.push(elements[i].id);\n      }\n\n      var data = {\n        elementIds: selectedElementIds,\n        siteId: elements[0].siteId,\n        containerId: this.settings.id,\n        name: this.settings.name,\n        branchLimit: this.settings.branchLimit,\n        selectionLabel: this.settings.selectionLabel,\n        elementType: this.settings.elementType,\n      };\n\n      const onResponse = () => {\n        this.modal.enable();\n        this.modal.enableCancelBtn();\n        this.modal.enableSelectBtn();\n        this.modal.hideFooterSpinner();\n      };\n      Craft.sendActionRequest(\n        'POST',\n        'relational-fields/structured-input-html',\n        {data}\n      )\n        .then((response) => {\n          onResponse();\n          var $newInput = $(response.data.html),\n            $newElementsContainer = $newInput.children('.elements');\n\n          this.$elementsContainer.replaceWith($newElementsContainer);\n          this.$elementsContainer = $newElementsContainer;\n          this.resetElements();\n\n          var filteredElements = [];\n\n          for (var i = 0; i < elements.length; i++) {\n            var element = elements[i],\n              $element = this.getElementById(element.id);\n\n            if ($element) {\n              this.animateElementIntoPlace(element.$element, $element);\n              filteredElements.push(element);\n            }\n          }\n\n          this.updateDisabledElementsInModal();\n          this.modal.hide();\n          this.onSelectElements(filteredElements);\n        })\n        .catch(({response}) => {\n          onResponse();\n        });\n    },\n\n    createNewElement: function (elementInfo) {\n      var $element = elementInfo.$element.clone();\n      var removeText = Craft.t('app', 'Remove {label}', {\n        label: Craft.escapeHtml(elementInfo.label),\n      });\n      // Make a couple tweaks\n      Craft.setElementSize(\n        $element,\n        this.settings.viewMode === 'large' ? 'large' : 'small'\n      );\n      $element\n        .addClass('removable')\n        .prepend(\n          $('<input/>', {\n            type: 'hidden',\n            name: this.settings.name + (this.settings.single ? '' : '[]'),\n            value: elementInfo.id,\n          })\n        )\n        .prepend(\n          $('<button/>', {\n            type: 'button',\n            class: 'delete icon',\n            title: Craft.t('app', 'Remove'),\n            'aria-label': removeText,\n          })\n        );\n\n      return $element;\n    },\n\n    appendElement: function ($element) {\n      $element.appendTo(this.$elementsContainer);\n    },\n\n    animateElementIntoPlace: function ($modalElement, $inputElement) {\n      var origOffset = $modalElement.offset(),\n        destOffset = $inputElement.offset(),\n        $helper = $inputElement.clone().appendTo(Garnish.$bod);\n\n      $inputElement.css('visibility', 'hidden');\n\n      $helper.css({\n        position: 'absolute',\n        zIndex: 10000,\n        top: origOffset.top,\n        left: origOffset.left,\n      });\n\n      var animateCss = {\n        top: destOffset.top,\n        left: destOffset.left,\n      };\n\n      $helper.velocity(\n        animateCss,\n        Craft.BaseElementSelectInput.ADD_FX_DURATION,\n        function () {\n          $helper.remove();\n          $inputElement.css('visibility', 'visible');\n        }\n      );\n    },\n\n    updateDisabledElementsInModal: function () {\n      if (this.modal.elementIndex) {\n        this.modal.elementIndex.disableElementsById(\n          this.getDisabledElementIds()\n        );\n      }\n    },\n\n    getElementById: function (id) {\n      for (var i = 0; i < this.$elements.length; i++) {\n        var $element = this.$elements.eq(i);\n\n        if ($element.data('id') == id) {\n          return $element;\n        }\n      }\n    },\n\n    onSelectElements: function (elements) {\n      this.trigger('selectElements', {elements});\n      this.settings.onSelectElements(elements);\n      this.$container.trigger('change');\n    },\n\n    onAddElements: function () {\n      this.trigger('addElements');\n      this.settings.onAddElements();\n      this.$container.trigger('change');\n    },\n\n    onRemoveElements: function () {\n      this.trigger('removeElements');\n      this.settings.onRemoveElements();\n      this.$container.trigger('change');\n    },\n\n    _animateStructureElementAway: function ($allElements, i) {\n      let callback;\n\n      // Is this the last one?\n      if (i === $allElements.length - 1) {\n        callback = () => {\n          const $li = $allElements.first().parent().parent();\n          const $ul = $li.parent();\n\n          if ($ul[0] === this.$elementsContainer[0] || $li.siblings().length) {\n            $li.remove();\n          } else {\n            $ul.remove();\n          }\n        };\n      }\n\n      const func = () => {\n        this.animateElementAway($allElements.eq(i), callback);\n      };\n\n      if (i === 0) {\n        func();\n      } else {\n        setTimeout(func, 100 * i);\n      }\n    },\n  },\n  {\n    ADD_FX_DURATION: 200,\n    REMOVE_FX_DURATION: 200,\n\n    defaults: {\n      id: null,\n      name: null,\n      fieldId: null,\n      elementType: null,\n      sources: null,\n      condition: null,\n      referenceElementId: null,\n      referenceElementSiteId: null,\n      criteria: {},\n      allowSelfRelations: false,\n      sourceElementId: null,\n      disabledElementIds: null,\n      viewMode: 'list',\n      single: false,\n      maintainHierarchy: false,\n      branchLimit: null,\n      limit: null,\n      showSiteMenu: false,\n      modalStorageKey: null,\n      modalSettings: {},\n      onAddElements: $.noop,\n      onSelectElements: $.noop,\n      onRemoveElements: $.noop,\n      sortable: true,\n      selectable: true,\n      editable: true,\n      prevalidate: false,\n      editorSettings: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element selector modal class\n */\nCraft.BaseElementSelectorModal = Garnish.Modal.extend(\n  {\n    elementType: null,\n    elementIndex: null,\n\n    supportSidebarToggleView: false,\n\n    $body: null,\n    $content: null,\n    $footer: null,\n    $selectBtn: null,\n    $sidebar: null,\n    $sources: null,\n    $sourceToggles: null,\n    $sidebarToggleBtn: null,\n    $sidebarCloseBtn: null,\n    $mainHeading: null,\n    $main: null,\n    $search: null,\n    $elements: null,\n    $tbody: null,\n    $primaryButtons: null,\n    $secondaryButtons: null,\n    $cancelBtn: null,\n\n    init: function (elementType, settings) {\n      this.elementType = elementType;\n      this.setSettings(settings, Craft.BaseElementSelectorModal.defaults);\n      const headingId = 'elementSelectorModalHeading-' + Date.now();\n\n      // Build the modal\n      const $container = $('<div/>', {\n        class: 'modal elementselectormodal',\n        'aria-labelledby': headingId,\n      }).appendTo(Garnish.$bod);\n      const $headingContainer = $('<div/>', {\n        class: this.settings.showTitle ? 'header' : 'visually-hidden',\n      }).appendTo($container);\n      $('<h1/>', {\n        id: headingId,\n        text: this.settings.modalTitle,\n      }).appendTo($headingContainer);\n      const $body = $('<div/>', {\n        class: 'body',\n      })\n        .append($('<div/>', {class: 'spinner big'}))\n        .appendTo($container);\n      this.$footer = $('<div/>', {\n        class: 'footer',\n      }).appendTo($container);\n\n      if (this.settings.fullscreen) {\n        $container.addClass('fullscreen');\n        this.settings.minGutter = 0;\n      }\n\n      this.base($container, this.settings);\n\n      this.$secondaryButtons = $(\n        '<div class=\"buttons left secondary-buttons\"/>'\n      ).appendTo(this.$footer);\n      this.$primaryButtons = $('<div class=\"buttons right\"/>').appendTo(\n        this.$footer\n      );\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$primaryButtons);\n      this.$selectBtn = Craft.ui\n        .createSubmitButton({\n          class: 'disabled',\n          label: this.settings.selectBtnLabel,\n          spinner: true,\n        })\n        .attr('aria-disabled', 'true')\n        .appendTo(this.$primaryButtons);\n\n      this.$body = $body;\n\n      this.addListener(this.$cancelBtn, 'activate', 'cancel');\n      this.addListener(this.$selectBtn, 'activate', 'selectElements');\n    },\n\n    updateModalBottomPadding: function () {\n      const footerHeight = this.$footer.outerHeight();\n      const bottomPadding = parseInt(this.$container.css('padding-bottom'));\n\n      if (footerHeight !== bottomPadding) {\n        this.$container.css('padding-bottom', footerHeight);\n      }\n    },\n\n    updateSidebarView: function () {\n      if (!this.supportSidebarToggleView) return;\n\n      if (this.sidebarShouldBeHidden()) {\n        if (!this.$sidebarToggleBtn) this.buildSidebarToggleView();\n      } else {\n        if (this.$sidebarToggleBtn) this.resetView();\n      }\n    },\n\n    sidebarShouldBeHidden: function () {\n      const contentWidth = this.$container.outerWidth();\n      return contentWidth < 550;\n    },\n\n    resetView: function () {\n      if (this.$mainHeader) {\n        this.$mainHeader.remove();\n      }\n\n      if (this.$sidebarHeader) {\n        this.$sidebarHeader.remove();\n      }\n\n      this.$sidebarToggleBtn = null;\n      this.$body.addClass('has-sidebar');\n      this.$content.addClass('has-sidebar');\n      this.$sidebar.removeClass('hidden');\n    },\n\n    buildSidebarToggleView: function () {\n      if (this.$sidebarToggleBtn || !this.sidebarShouldBeHidden()) return;\n\n      this.$sidebarHeader = $('<div class=\"sidebar-header\"/>').prependTo(\n        this.$sidebar\n      );\n\n      this.$sidebarCloseBtn = Craft.ui\n        .createButton({\n          class: 'nav-close close-btn',\n        })\n        .attr('aria-label', Craft.t('app', 'Close'))\n        .removeClass('btn')\n        .appendTo(this.$sidebarHeader);\n\n      this.$mainHeader = $('<div class=\"main-header\"/>').prependTo(this.$main);\n      this.$mainHeading = $(\n        `<h2 class=\"main-heading\">${this.getActiveSourceName()}</h2>`\n      ).appendTo(this.$mainHeader);\n\n      const buttonConfig = {\n        toggle: true,\n        controls: 'modal-sidebar',\n        class: 'nav-toggle',\n      };\n      this.$sidebarToggleBtn = Craft.ui\n        .createButton(buttonConfig)\n        .removeClass('btn')\n        .attr('aria-label', Craft.t('app', 'Show sidebar'))\n        .appendTo(this.$mainHeader);\n\n      this.$sidebar.attr('id', 'modal-sidebar');\n\n      this.closeSidebar();\n\n      this.addListener(this.$sidebarToggleBtn, 'click', () => {\n        this.toggleSidebar();\n      });\n\n      this.addListener(this.$sidebarCloseBtn, 'click', () => {\n        this.toggleSidebar();\n      });\n    },\n\n    sidebarIsOpen: function () {\n      return this.$sidebarToggleBtn.attr('aria-expanded') === 'true';\n    },\n\n    toggleSidebar: function () {\n      if (this.sidebarIsOpen()) {\n        this.closeSidebar();\n      } else {\n        this.openSidebar();\n      }\n    },\n\n    openSidebar: function () {\n      this.$body.addClass('has-sidebar');\n      this.$content.addClass('has-sidebar');\n      this.$sidebar.removeClass('hidden');\n      this.$sidebarToggleBtn.attr('aria-expanded', 'true');\n      this.$sidebar.find(':focusable').first().focus();\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.closeSidebar();\n\n        // If the focus is currently inside the sidebar, refocus the toggle\n        const $focusedEl = Garnish.getFocusedElement();\n        if ($.contains(this.$sidebar.get(0), $focusedEl.get(0)))\n          this.$sidebarToggleBtn.focus();\n      });\n    },\n\n    closeSidebar: function () {\n      if (!this.$sidebarToggleBtn) return;\n\n      if (this.sidebarIsOpen()) {\n        Garnish.uiLayerManager.removeLayer();\n        this.$sidebar.addClass('hidden');\n        this.$sidebarToggleBtn.attr('aria-expanded', 'false');\n      }\n\n      this.$body.removeClass('has-sidebar');\n      this.$content.removeClass('has-sidebar');\n    },\n\n    getActiveSourceName: function () {\n      return this.$sidebar.find('.sel').text();\n    },\n\n    onFadeIn: function () {\n      if (!this.elementIndex) {\n        this._createElementIndex();\n      } else {\n        // make sure we're able to scroll the entire elementIndex if more elements were added\n        // after modal was first initialised\n        this.updateModalBottomPadding();\n\n        // Auto-focus the Search box\n        if (!Garnish.isMobileBrowser(true)) {\n          this.elementIndex.$search.trigger('focus');\n        }\n      }\n\n      this.base();\n    },\n\n    onSelectionChange: function () {\n      this.updateSelectBtnState();\n    },\n\n    onSelectSource: function () {\n      this.updateHeading();\n      this.updateModalBottomPadding();\n    },\n\n    updateHeading: function () {\n      if (!this.$mainHeading) return;\n\n      this.$mainHeading.text(this.getActiveSourceName());\n    },\n\n    updateSelectBtnState: function () {\n      if (this.$selectBtn) {\n        if (this.hasSelection()) {\n          this.enableSelectBtn();\n        } else {\n          this.disableSelectBtn();\n        }\n      }\n    },\n\n    hasSelection: function () {\n      return (\n        this.elementIndex && this.elementIndex.getSelectedElements().length\n      );\n    },\n\n    enableSelectBtn: function () {\n      this.$selectBtn.removeClass('disabled').attr('aria-disabled', 'false');\n    },\n\n    disableSelectBtn: function () {\n      this.$selectBtn.addClass('disabled').attr('aria-disabled', 'true');\n    },\n\n    enableCancelBtn: function () {\n      this.$cancelBtn.removeClass('disabled');\n    },\n\n    disableCancelBtn: function () {\n      this.$cancelBtn.addClass('disabled');\n    },\n\n    showFooterSpinner: function () {\n      this.$selectBtn.addClass('loading');\n    },\n\n    hideFooterSpinner: function () {\n      this.$selectBtn.removeClass('loading');\n    },\n\n    cancel: function () {\n      if (!this.$cancelBtn.hasClass('disabled')) {\n        this.hide();\n      }\n    },\n\n    selectElements: function () {\n      if (this.hasSelection()) {\n        // TODO: This code shouldn't know about views' elementSelect objects\n        if (this.elementIndex.view && this.elementIndex.view.elementSelect) {\n          this.elementIndex.view.elementSelect.clearMouseUpTimeout();\n        }\n\n        var $selectedElements = this.elementIndex.getSelectedElements(),\n          elementInfo = this.getElementInfo($selectedElements);\n\n        this.onSelect(elementInfo);\n\n        if (this.settings.disableElementsOnSelect) {\n          this.elementIndex.disableElements(\n            this.elementIndex.getSelectedElements()\n          );\n        }\n\n        if (this.settings.hideOnSelect) {\n          this.hide();\n        }\n      }\n    },\n\n    getElementInfo: function ($selectedElements) {\n      var info = [];\n\n      for (var i = 0; i < $selectedElements.length; i++) {\n        var $element = $($selectedElements[i]);\n        var elementInfo = Craft.getElementInfo($element);\n\n        info.push(elementInfo);\n      }\n\n      return info;\n    },\n\n    onShow: function () {\n      this.updateSelectBtnState();\n\n      // Add listeners again since they get removed during modal close\n      this.addListener(Garnish.$win, 'resize', this.updateSidebarView);\n      this.addListener(Garnish.$win, 'resize', this.updateModalBottomPadding);\n\n      this.updateModalBottomPadding();\n      this.updateSidebarView();\n      this.base();\n    },\n\n    onHide: function () {\n      this.closeSidebar();\n      this.base();\n    },\n\n    onSelect: function (elementInfo) {\n      this.settings.onSelect(elementInfo);\n    },\n\n    disable: function () {\n      if (this.elementIndex) {\n        this.elementIndex.disable();\n      }\n\n      this.base();\n    },\n\n    enable: function () {\n      if (this.elementIndex) {\n        this.elementIndex.enable();\n      }\n\n      this.base();\n    },\n\n    getElementIndexParams: function () {\n      // Get the modal body HTML based on the settings\n      const params = {\n        context: 'modal',\n        elementType: this.elementType,\n        sources: this.settings.sources,\n      };\n\n      if (\n        this.settings.showSiteMenu !== null &&\n        this.settings.showSiteMenu !== 'auto'\n      ) {\n        params.showSiteMenu = this.settings.showSiteMenu ? '1' : '0';\n      }\n\n      return params;\n    },\n\n    _createElementIndex: function () {\n      Craft.sendActionRequest('POST', this.settings.bodyAction, {\n        data: this.getElementIndexParams(),\n      }).then((response) => {\n        this.$body.html(response.data.html);\n\n        if (this.$body.has('.sidebar:not(.hidden)').length) {\n          this.$body.addClass('has-sidebar');\n          this.supportSidebarToggleView = true;\n        }\n\n        // Initialize the element index\n        this.elementIndex = Craft.createElementIndex(\n          this.elementType,\n          this.$body,\n          this.getIndexSettings()\n        );\n\n        this.$main = this.elementIndex.$main;\n        this.$sidebar = this.elementIndex.$sidebar;\n        this.$content = this.$body.find('.content');\n\n        this.updateSidebarView();\n        this.updateModalBottomPadding();\n\n        // Double-clicking or double-tapping should select the elements\n        this.addListener(\n          this.elementIndex.$elements,\n          'doubletap',\n          function (ev, touchData) {\n            // Make sure the touch targets are the same\n            // (they may be different if Command/Ctrl/Shift-clicking on multiple elements quickly)\n            // and make sure the element is actually selectable\n            if (\n              touchData.firstTap.target === touchData.secondTap.target &&\n              this.elementIndex.view.elementSelect.getItemIndex(\n                touchData.firstTap.target\n              ) != -1\n            ) {\n              this.selectElements();\n            }\n          }\n        );\n\n        this.on('updateSizeAndPosition', () => {\n          this.elementIndex.handleResize();\n        });\n\n        this.updateSelectBtnState();\n      });\n    },\n\n    getIndexSettings: function () {\n      return Object.assign(\n        {\n          context: 'modal',\n          modal: this,\n          storageKey: this.settings.storageKey,\n          condition: this.settings.condition,\n          referenceElementId: this.settings.referenceElementId,\n          referenceElementSiteId: this.settings.referenceElementSiteId,\n          criteria: this.settings.criteria,\n          disabledElementIds: this.settings.disabledElementIds,\n          selectable: true,\n          multiSelect: this.settings.multiSelect,\n          buttonContainer: this.$secondaryButtons,\n          onSelectionChange: () => {\n            if (this.elementIndex) {\n              this.onSelectionChange();\n            }\n          },\n          onSourcePathChange: () => {\n            if (this.elementIndex) {\n              this.onSelectionChange();\n            }\n          },\n          onSelectSource: this.onSelectSource.bind(this),\n          hideSidebar: this.settings.hideSidebar,\n          defaultSiteId: this.settings.defaultSiteId,\n          defaultSource: this.settings.defaultSource,\n          defaultSourcePath: this.settings.defaultSourcePath,\n          showSourcePath: this.settings.showSourcePath,\n        },\n        this.settings.indexSettings\n      );\n    },\n  },\n  {\n    defaults: {\n      fullscreen: false,\n      resizable: true,\n      storageKey: null,\n      sources: null,\n      condition: null,\n      referenceElementId: null,\n      referenceElementSiteId: null,\n      criteria: null,\n      multiSelect: false,\n      showSiteMenu: null,\n      disabledElementIds: [],\n      disableElementsOnSelect: false,\n      hideOnSelect: true,\n      modalTitle: Craft.t('app', 'Select element'),\n      showTitle: false,\n      selectBtnLabel: Craft.t('app', 'Select'),\n      onCancel: $.noop,\n      onSelect: $.noop,\n      hideSidebar: false,\n      defaultSiteId: null,\n      defaultSource: null,\n      defaultSourcePath: null,\n      showSourcePath: true,\n      bodyAction: 'element-selector-modals/body',\n      indexSettings: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Input Generator\n */\nCraft.BaseInputGenerator = Garnish.Base.extend({\n  $source: null,\n  $target: null,\n  $form: null,\n  settings: null,\n\n  listening: null,\n  timeout: null,\n\n  init: function (source, target, settings) {\n    this.$source = $(source);\n    this.$target = $(target);\n    this.$form = this.$source.closest('form');\n\n    this.setSettings(settings);\n\n    this.startListening();\n  },\n\n  setNewSource: function (source) {\n    var listening = this.listening;\n    this.stopListening();\n\n    this.$source = $(source);\n\n    if (listening) {\n      this.startListening();\n    }\n  },\n\n  startListening: function () {\n    if (this.listening) {\n      return;\n    }\n\n    this.listening = true;\n\n    this.addListener(this.$source, 'input', 'onSourceTextChange');\n    this.addListener(this.$target, 'input', 'onTargetTextChange');\n    this.addListener(this.$form, 'submit', 'onFormSubmit');\n  },\n\n  stopListening: function () {\n    if (!this.listening) {\n      return;\n    }\n\n    this.listening = false;\n\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.removeAllListeners(this.$source);\n    this.removeAllListeners(this.$target);\n    this.removeAllListeners(this.$form);\n  },\n\n  onSourceTextChange: function () {\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.timeout = setTimeout(this.updateTarget.bind(this), 250);\n  },\n\n  onTargetTextChange: function () {\n    if (this.$target.get(0) === document.activeElement) {\n      this.stopListening();\n    }\n  },\n\n  onFormSubmit: function () {\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.updateTarget();\n  },\n\n  updateTarget: function () {\n    if (!this.$target.is(':visible')) {\n      return;\n    }\n\n    var sourceVal = this.$source.val();\n\n    if (typeof sourceVal === 'undefined') {\n      // The source input may not exist anymore\n      return;\n    }\n\n    var targetVal = this.generateTargetValue(sourceVal);\n\n    this.$target.val(targetVal);\n\n    for (let i = 0; i < this.$target.length; i++) {\n      this.$target[i].dispatchEvent(\n        new InputEvent('input', {\n          inputType: 'insertText',\n        })\n      );\n      this.$target[i].dispatchEvent(new Event('input'));\n    }\n\n    // If the target already has focus, select its whole value to mimic\n    // the behavior if the value had already been generated and they just tabbed in\n    if (this.$target.is(':focus')) {\n      Craft.selectFullValue(this.$target);\n    }\n  },\n\n  generateTargetValue: function (sourceVal) {\n    return sourceVal;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Category index class\n */\nCraft.CategoryIndex = Craft.BaseElementIndex.extend({\n  editableGroups: null,\n  $newCategoryBtnGroup: null,\n  $newCategoryBtn: null,\n\n  init: function (elementType, $container, settings) {\n    this.editableGroups = [];\n    this.on('selectSource', this.updateButton.bind(this));\n    this.on('selectSite', this.updateButton.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  afterInit: function () {\n    // Find which of the visible groups the user has permission to create new categories in\n    this.editableGroups = Craft.editableCategoryGroups.filter(\n      (g) => !!this.getSourceByKey(`group:${g.uid}`)\n    );\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific category group in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultGroupHandle !== 'undefined'\n    ) {\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = $(this.$sources[i]);\n        if ($source.data('handle') === defaultGroupHandle) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateButton: function () {\n    if (!this.$source) {\n      return;\n    }\n\n    // Get the handle of the selected source\n    const selectedSourceHandle = this.$source.data('handle');\n\n    // Update the New Category button\n    // ---------------------------------------------------------------------\n\n    if (this.editableGroups.length) {\n      // Remove the old button, if there is one\n      if (this.$newCategoryBtnGroup) {\n        this.$newCategoryBtnGroup.remove();\n      }\n\n      // Determine if they are viewing a group that they have permission to create categories in\n      const selectedGroup = this.editableGroups.find(\n        (g) => g.handle === selectedSourceHandle\n      );\n\n      this.$newCategoryBtnGroup = $(\n        '<div class=\"btngroup submit\" data-wrapper/>'\n      );\n      let $menuBtn;\n      const menuId = 'new-category-menu-' + Craft.randomString(10);\n\n      // If they are, show a primary \"New category\" button, and a dropdown of the other groups (if any).\n      // Otherwise only show a menu button\n      if (selectedGroup) {\n        const visibleLabel =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New category')\n            : Craft.t('app', 'New {group} category', {\n                group: selectedGroup.name,\n              });\n        const ariaLabel =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New category in the {group} category group', {\n                group: selectedGroup.name,\n              })\n            : visibleLabel;\n\n        const role = this.settings.context === 'index' ? 'link' : null;\n\n        this.$newCategoryBtn = Craft.ui\n          .createButton({\n            label: visibleLabel,\n            ariaLabel: ariaLabel,\n            spinner: true,\n            role: role,\n          })\n          .addClass('submit add icon')\n          .appendTo(this.$newCategoryBtnGroup);\n\n        this.addListener(this.$newCategoryBtn, 'click mousedown', (ev) => {\n          // If this is the element index, check for Ctrl+clicks and middle button clicks\n          if (\n            this.settings.context === 'index' &&\n            ((ev.type === 'click' && Garnish.isCtrlKeyPressed(ev)) ||\n              (ev.type === 'mousedown' && ev.originalEvent.button === 1))\n          ) {\n            window.open(Craft.getUrl(`categories/${selectedGroup.handle}/new`));\n          } else if (ev.type === 'click') {\n            this._createCategory(selectedGroup.id);\n          }\n        });\n\n        if (this.editableGroups.length > 1) {\n          $menuBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn submit menubtn btngroup-btn-last',\n            'aria-controls': menuId,\n            'data-disclosure-trigger': '',\n            'aria-label': Craft.t(\n              'app',\n              'New category, choose a category group'\n            ),\n          }).appendTo(this.$newCategoryBtnGroup);\n        }\n      } else {\n        this.$newCategoryBtn = $menuBtn = Craft.ui\n          .createButton({\n            label: Craft.t('app', 'New category'),\n            ariaLabel: Craft.t('app', 'New category, choose a category group'),\n            spinner: true,\n          })\n          .addClass('submit add icon menubtn btngroup-btn-last')\n          .attr('aria-controls', menuId)\n          .attr('data-disclosure-trigger', '')\n          .appendTo(this.$newCategoryBtnGroup);\n      }\n\n      this.addButton(this.$newCategoryBtnGroup);\n\n      if ($menuBtn) {\n        const $menuContainer = $('<div/>', {\n          id: menuId,\n          class: 'menu menu--disclosure',\n        }).appendTo(this.$newCategoryBtnGroup);\n        const $ul = $('<ul/>').appendTo($menuContainer);\n\n        for (const group of this.editableGroups) {\n          const anchorRole =\n            this.settings.context === 'index' ? 'link' : 'button';\n          if (this.settings.context === 'index' || group !== selectedGroup) {\n            const $li = $('<li/>').appendTo($ul);\n            const $a = $('<a/>', {\n              role: anchorRole === 'button' ? 'button' : null,\n              href: '#', // Allows for click listener and tab order\n              type: anchorRole === 'button' ? 'button' : null,\n              text: Craft.t('app', 'New {group} category', {\n                group: group.name,\n              }),\n            }).appendTo($li);\n            this.addListener($a, 'click', () => {\n              $menuBtn.data('trigger').hide();\n              this._createCategory(group.id);\n            });\n\n            if (anchorRole === 'button') {\n              this.addListener($a, 'keydown', (event) => {\n                if (event.keyCode === Garnish.SPACE_KEY) {\n                  event.preventDefault();\n                  $menuBtn.data('trigger').hide();\n                  this._createCategory(group.id);\n                }\n              });\n            }\n          }\n        }\n\n        new Garnish.DisclosureMenu($menuBtn);\n      }\n    }\n\n    // Update the URL if we're on the Categories index\n    // ---------------------------------------------------------------------\n\n    if (this.settings.context === 'index') {\n      let uri = 'categories';\n\n      if (selectedSourceHandle) {\n        uri += '/' + selectedSourceHandle;\n      }\n\n      Craft.setPath(uri);\n    }\n  },\n\n  _createCategory: function (groupId) {\n    if (this.$newCategoryBtn.hasClass('loading')) {\n      console.warn('New category creation already in progress.');\n      return;\n    }\n\n    // Find the group\n    const group = this.editableGroups.find((s) => s.id === groupId);\n\n    if (!group) {\n      throw `Invalid category group ID: ${groupId}`;\n    }\n\n    this.$newCategoryBtn.addClass('loading');\n\n    Craft.sendActionRequest('POST', 'elements/create', {\n      data: {\n        elementType: this.elementType,\n        siteId: this.siteId,\n        groupId: groupId,\n      },\n    })\n      .then((ev) => {\n        if (this.settings.context === 'index') {\n          document.location.href = Craft.getUrl(ev.data.cpEditUrl, {fresh: 1});\n        } else {\n          const slideout = Craft.createElementEditor(this.elementType, {\n            siteId: this.siteId,\n            elementId: ev.data.element.id,\n            draftId: ev.data.element.draftId,\n            params: {\n              fresh: 1,\n            },\n          });\n          slideout.on('submit', () => {\n            // Make sure the right group is selected\n            const groupSourceKey = `group:${group.uid}`;\n\n            if (this.sourceKey !== groupSourceKey) {\n              this.selectSourceByKey(groupSourceKey);\n            }\n\n            this.clearSearch();\n            this.selectElementAfterUpdate(ev.data.element.id);\n            this.updateElements();\n          });\n        }\n      })\n      .finally(() => {\n        this.$newCategoryBtn.removeClass('loading');\n      });\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass(\n  'craft\\\\elements\\\\Category',\n  Craft.CategoryIndex\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Category select input\n * @deprecated in 4.3.0. Use Craft.BaseElementSelectInput instead.\n */\nCraft.CategorySelectInput = Craft.BaseElementSelectInput.extend({\n  setSettings: function () {\n    this.base.apply(this, arguments);\n    this.settings.sortable = false;\n  },\n\n  getModalSettings: function () {\n    var settings = this.base();\n    settings.hideOnSelect = false;\n    return settings;\n  },\n\n  getElements: function () {\n    return this.$elementsContainer.find('.element');\n  },\n\n  onModalSelect: function (elements) {\n    // Disable the modal\n    this.modal.disable();\n    this.modal.disableCancelBtn();\n    this.modal.disableSelectBtn();\n    this.modal.showFooterSpinner();\n\n    // Get the new category HTML\n    var selectedCategoryIds = this.getSelectedElementIds();\n\n    for (var i = 0; i < elements.length; i++) {\n      selectedCategoryIds.push(elements[i].id);\n    }\n\n    var data = {\n      categoryIds: selectedCategoryIds,\n      siteId: elements[0].siteId,\n      id: this.settings.id,\n      name: this.settings.name,\n      branchLimit: this.settings.branchLimit,\n      selectionLabel: this.settings.selectionLabel,\n    };\n\n    const onResponse = () => {\n      this.modal.enable();\n      this.modal.enableCancelBtn();\n      this.modal.enableSelectBtn();\n      this.modal.hideFooterSpinner();\n    };\n    Craft.sendActionRequest('POST', 'categories/input-html', {data})\n      .then((response) => {\n        onResponse();\n        var $newInput = $(response.data.html),\n          $newElementsContainer = $newInput.children('.elements');\n\n        this.$elementsContainer.replaceWith($newElementsContainer);\n        this.$elementsContainer = $newElementsContainer;\n        this.resetElements();\n\n        var filteredElements = [];\n\n        for (var i = 0; i < elements.length; i++) {\n          var element = elements[i],\n            $element = this.getElementById(element.id);\n\n          if ($element) {\n            this.animateElementIntoPlace(element.$element, $element);\n            filteredElements.push(element);\n          }\n        }\n\n        this.updateDisabledElementsInModal();\n        this.modal.hide();\n        this.onSelectElements(filteredElements);\n      })\n      .catch(({response}) => {\n        onResponse();\n      });\n  },\n\n  removeElement: function ($element) {\n    // Find any descendants this category might have\n    const $allCategories = $element.add(\n      $element.parent().siblings('ul').find('.element')\n    );\n\n    // Remove our record of them all at once\n    this.removeElements($allCategories);\n\n    // Animate them away one at a time\n    for (let i = 0; i < $allCategories.length; i++) {\n      this._animateCategoryAway($allCategories, i);\n    }\n  },\n\n  _animateCategoryAway: function ($allCategories, i) {\n    let callback;\n\n    // Is this the last one?\n    if (i === $allCategories.length - 1) {\n      callback = () => {\n        const $li = $allCategories.first().parent().parent();\n        const $ul = $li.parent();\n\n        if ($ul[0] === this.$elementsContainer[0] || $li.siblings().length) {\n          $li.remove();\n        } else {\n          $ul.remove();\n        }\n      };\n    }\n\n    const func = () => {\n      this.animateElementAway($allCategories.eq(i), callback);\n    };\n\n    if (i === 0) {\n      func();\n    } else {\n      setTimeout(func, 100 * i);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Craft Charts\n */\n\nCraft.charts = {};\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.DataTable\n */\nCraft.charts.DataTable = Garnish.Base.extend({\n  columns: null,\n  rows: null,\n\n  init: function (data) {\n    let columns = data.columns;\n    let rows = data.rows;\n\n    rows.forEach((d) => {\n      $.each(d, function (cellIndex) {\n        var column = columns[cellIndex];\n\n        var parseTime;\n\n        switch (column.type) {\n          case 'date':\n            parseTime = d3.timeParse('%Y-%m-%d');\n            d[cellIndex] = parseTime(d[cellIndex]);\n            break;\n\n          case 'datetime':\n            parseTime = d3.timeParse('%Y-%m-%d %H:00:00');\n            d[cellIndex] = parseTime(d[cellIndex]);\n            break;\n\n          case 'percent':\n            d[cellIndex] = d[cellIndex] / 100;\n            break;\n\n          case 'number':\n            d[cellIndex] = +d[cellIndex];\n            break;\n\n          default:\n          // do nothing\n        }\n      });\n    });\n\n    this.columns = columns;\n    this.rows = rows;\n  },\n});\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Tip\n */\n\nCraft.charts.Tip = Garnish.Base.extend({\n  $container: null,\n  $tip: null,\n\n  init: function ($container) {\n    this.$container = $container;\n\n    this.$tip = $('<div class=\"tooltip\"></div>').appendTo(this.$container);\n\n    this.hide();\n  },\n\n  setContent: function (html) {\n    this.$tip.html(html);\n  },\n\n  setPosition: function (position) {\n    this.$tip.css('left', `${position.left}px`);\n    this.$tip.css('top', `${position.top}px`);\n  },\n\n  show: function () {\n    this.$tip.css('display', 'block');\n  },\n\n  hide: function () {\n    this.$tip.css('display', 'none');\n  },\n});\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.BaseChart\n */\nCraft.charts.BaseChart = Garnish.Base.extend(\n  {\n    $container: null,\n    $chart: null,\n\n    chartBaseClass: 'cp-chart',\n    dataTable: null,\n\n    formatLocale: null,\n    timeFormatLocale: null,\n    orientation: null,\n\n    svg: null,\n    width: null,\n    height: null,\n\n    init: function (container, settings) {\n      this.$container = container;\n\n      this.setSettings(Craft.charts.BaseChart.defaults);\n      this.setSettings(settings);\n\n      var globalSettings = {\n        formats: window.d3Formats,\n        formatLocaleDefinition: window.d3FormatLocaleDefinition,\n        timeFormatLocaleDefinition: window.d3TimeFormatLocaleDefinition,\n      };\n\n      this.setSettings(globalSettings);\n\n      d3.select(window).on('resize', () => {\n        this.resize();\n      });\n    },\n\n    setSettings: function (settings, defaults) {\n      var baseSettings =\n        typeof this.settings === 'undefined' ? {} : this.settings;\n      this.settings = $.extend(true, {}, baseSettings, defaults, settings);\n    },\n\n    draw: function (dataTable, settings) {\n      // Settings and chart attributes\n\n      this.setSettings(settings);\n\n      this.dataTable = dataTable;\n      this.formatLocale = d3.formatLocale(this.settings.formatLocaleDefinition);\n      this.timeFormatLocale = d3.timeFormatLocale(\n        this.settings.timeFormatLocaleDefinition\n      );\n      this.orientation = this.settings.orientation;\n\n      // Set (or reset) the chart element\n\n      if (this.$chart) {\n        this.$chart.remove();\n      }\n\n      var className = this.chartBaseClass;\n\n      if (this.settings.chartClass) {\n        className += ' ' + this.settings.chartClass;\n      }\n\n      this.$chart = $(`<div class=\"${className}\" />`).appendTo(this.$container);\n    },\n\n    resize: function () {\n      this.draw(this.dataTable, this.settings);\n    },\n\n    onAfterDrawTicks: function () {\n      // White border for ticks' text\n      $('.tick', this.$chart).each(function (tickKey, tick) {\n        var $tickText = $('text', tick);\n\n        var $clone = $tickText.clone();\n        $clone.appendTo(tick);\n\n        $tickText.attr('stroke', '#ffffff');\n        $tickText.attr('stroke-width', 3);\n      });\n    },\n  },\n  {\n    defaults: {\n      formatLocaleDefinition: null,\n      timeFormatLocaleDefinition: null,\n      formats: {\n        numberFormat: ',.2f',\n        percentFormat: ',.2%',\n        currencyFormat: '$,.2f',\n        shortDateFormats: {\n          day: '%-m/%-d',\n          month: '%-m/%y',\n          year: '%Y',\n        },\n      },\n      margin: {top: 0, right: 0, bottom: 0, left: 0},\n      chartClass: null,\n      colors: ['#0594D1', '#DE3800', '#FF9A00', '#009802', '#9B009B'],\n    },\n  }\n);\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Area\n */\nCraft.charts.Area = Craft.charts.BaseChart.extend(\n  {\n    tip: null,\n    drawingArea: null,\n\n    init: function (container, settings) {\n      this.base(container, Craft.charts.Area.defaults);\n\n      this.setSettings(settings);\n    },\n\n    draw: function (dataTable, settings) {\n      this.base(dataTable, settings);\n\n      if (this.tip) {\n        this.tip = null;\n      }\n\n      var margin = this.getChartMargin();\n\n      this.width = this.$chart.width() - margin.left - margin.right;\n      this.height = this.$chart.height() - margin.top - margin.bottom;\n\n      // Append SVG to chart element\n\n      var svg = {\n        width: this.width + (margin.left + margin.right),\n        height: this.height + (margin.top + margin.bottom),\n        translateX: this.orientation !== 'rtl' ? margin.left : margin.right,\n        translateY: margin.top,\n      };\n\n      this.svg = d3\n        .select(this.$chart.get(0))\n        .append('svg')\n        .attr('width', svg.width)\n        .attr('height', svg.height);\n\n      this.drawingArea = this.svg\n        .append('g')\n        .attr('transform', `translate(${svg.translateX},${svg.translateY})`);\n\n      // Draw elements\n\n      this.drawTicks();\n      this.drawAxes();\n      this.drawChart();\n      this.drawTipTriggers();\n    },\n\n    drawTicks: function () {\n      // Draw X ticks\n\n      var x = this.getX(true);\n      var xTicks = 3;\n      var xAxis = d3\n        .axisBottom(x)\n        .tickFormat(this.getXFormatter())\n        .ticks(xTicks);\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'x ticks-axis')\n        .attr('transform', `translate(0, ${this.height})`)\n        .call(xAxis);\n\n      // Draw Y ticks\n\n      var y = this.getY();\n      var yTicks = 2;\n      var yAxis;\n\n      if (this.orientation !== 'rtl') {\n        yAxis = d3\n          .axisLeft(y)\n          .tickFormat(this.getYFormatter())\n          .tickValues(this.getYTickValues())\n          .ticks(yTicks);\n\n        this.drawingArea.append('g').attr('class', 'y ticks-axis').call(yAxis);\n      } else {\n        yAxis = d3\n          .axisRight(y)\n          .tickFormat(this.getYFormatter())\n          .tickValues(this.getYTickValues())\n          .ticks(yTicks);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'y ticks-axis')\n          .attr('transform', `translate(${this.width},0)`)\n          .call(yAxis);\n      }\n\n      // On after draw ticks\n\n      this.onAfterDrawTicks();\n    },\n\n    drawAxes: function () {\n      if (this.settings.xAxis.showAxis) {\n        var x = this.getX();\n        var xAxis = d3.axisBottom(x).ticks(0).tickSizeOuter(0);\n        this.drawingArea\n          .append('g')\n          .attr('class', 'x axis')\n          .attr('transform', `translate(0, ${this.height})`)\n          .call(xAxis);\n      }\n\n      if (this.settings.yAxis.showAxis) {\n        var y = this.getY();\n        var chartPadding = 0;\n        var yAxis;\n\n        if (this.orientation === 'rtl') {\n          yAxis = d3.axisLeft(y).ticks(0);\n          this.drawingArea\n            .append('g')\n            .attr('class', 'y axis')\n            .attr('transform', `translate(${this.width - chartPadding}, 0)`)\n            .call(yAxis);\n        } else {\n          yAxis = d3.axisRight(y).ticks(0);\n          this.drawingArea\n            .append('g')\n            .attr('class', 'y axis')\n            .attr('transform', `translate(${chartPadding}, 0)`)\n            .call(yAxis);\n        }\n      }\n    },\n\n    drawChart: function () {\n      var x = this.getX(true);\n      var y = this.getY();\n\n      // X & Y grid lines\n\n      if (this.settings.xAxis.gridlines) {\n        var xLineAxis = d3.axisBottom(x);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'x grid-line')\n          .attr('transform', `translate(0,${this.height})`)\n          .call(xLineAxis.tickSize(-this.height, 0, 0).tickFormat(''));\n      }\n\n      var yTicks = 2;\n\n      if (this.settings.yAxis.gridlines) {\n        var yLineAxis = d3.axisLeft(y);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'y grid-line')\n          .attr('transform', 'translate(0 , 0)')\n          .call(\n            yLineAxis\n              .tickSize(-this.width, 0)\n              .tickFormat('')\n              .tickValues(this.getYTickValues())\n              .ticks(yTicks)\n          );\n      }\n\n      // Line\n\n      var line = d3\n        .line()\n        .x(function (d) {\n          return x(d[0]);\n        })\n        .y(function (d) {\n          return y(d[1]);\n        });\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'chart-line')\n        .append('path')\n        .datum(this.dataTable.rows)\n        .style('fill', 'none')\n        .style('stroke', this.settings.colors[0])\n        .style('stroke-width', '3px')\n        .attr('d', line);\n\n      // Area\n\n      var area = d3\n        .area()\n        .x(function (d) {\n          return x(d[0]);\n        })\n        .y0(this.height)\n        .y1(function (d) {\n          return y(d[1]);\n        });\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'chart-area')\n        .append('path')\n        .datum(this.dataTable.rows)\n        .style('fill', this.settings.colors[0])\n        .style('fill-opacity', '0.3')\n        .attr('d', area);\n\n      // Plots\n\n      if (this.settings.plots) {\n        this.drawingArea\n          .append('g')\n          .attr('class', 'plots')\n          .selectAll('circle')\n          .data(this.dataTable.rows)\n          .enter()\n          .append('circle')\n          .style('fill', this.settings.colors[0])\n          .attr('class', (d, index) => `plot plot-${index}`)\n          .attr('r', 4)\n          .attr('cx', (d) => x(d[0]))\n          .attr('cy', (d) => y(d[1]));\n      }\n    },\n\n    drawTipTriggers: function () {\n      if (this.settings.tips) {\n        if (!this.tip) {\n          this.tip = new Craft.charts.Tip(this.$chart);\n        }\n\n        // Define xAxisTickInterval\n\n        var chartMargin = this.getChartMargin();\n        var tickSizeOuter = 6;\n        var length =\n          this.drawingArea.select('.x path.domain').node().getTotalLength() -\n          chartMargin.left -\n          chartMargin.right -\n          tickSizeOuter * 2;\n        var xAxisTickInterval = length / (this.dataTable.rows.length - 1);\n\n        // Tip trigger width\n\n        var tipTriggerWidth = Math.max(0, xAxisTickInterval);\n\n        // Draw triggers\n\n        var x = this.getX(true);\n        var y = this.getY();\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'tip-triggers')\n          .selectAll('rect')\n          .data(this.dataTable.rows)\n          .enter()\n          .append('rect')\n          .attr('class', 'tip-trigger')\n          .style('fill', 'transparent')\n          .style('fill-opacity', '1')\n          .attr('width', tipTriggerWidth)\n          .attr('height', this.height)\n          .attr('x', (d) => x(d[0]) - tipTriggerWidth / 2)\n          .on('mouseover', (d, index) => {\n            // Expand plot\n\n            this.drawingArea.select('.plot-' + index).attr('r', 5);\n\n            // Set tip content\n\n            var $content = $('<div />');\n            var $xValue = $('<div class=\"x-value\" />').appendTo($content);\n            var $yValue = $('<div class=\"y-value\" />').appendTo($content);\n\n            $xValue.html(this.getXFormatter()(d[0]));\n            $yValue.html(this.getYFormatter()(d[1]));\n\n            var content = $content.get(0);\n\n            this.tip.setContent(content);\n\n            // Set tip position\n\n            var margin = this.getChartMargin();\n\n            var offset = 24;\n            var top = y(d[1]) + offset;\n            var left;\n\n            if (this.orientation !== 'rtl') {\n              left = x(d[0]) + margin.left + offset;\n\n              var calcLeft =\n                this.$chart.offset().left + left + this.tip.$tip.width();\n              var maxLeft =\n                this.$chart.offset().left + this.$chart.width() - offset;\n\n              if (calcLeft > maxLeft) {\n                left = x(d[0]) - (this.tip.$tip.width() + offset);\n              }\n            } else {\n              left = x(d[0]) - (this.tip.$tip.width() + margin.left + offset);\n            }\n\n            if (left < 0) {\n              left = x(d[0]) + margin.left + offset;\n            }\n\n            var position = {\n              top: top,\n              left: left,\n            };\n\n            this.tip.setPosition(position);\n\n            // Show tip\n\n            this.tip.show();\n          })\n          .on('mouseout', (d, index) => {\n            // Unexpand Plot\n            this.drawingArea.select('.plot-' + index).attr('r', 4);\n\n            // Hide tip\n            this.tip.hide();\n          });\n      }\n    },\n\n    getChartMargin: function () {\n      var margin = this.settings.margin;\n\n      // Estimate the max width of y ticks and set it as the left margin\n\n      var values = this.getYTickValues();\n      var yTicksMaxWidth = 0;\n\n      $.each(values, (key, value) => {\n        var characterWidth = 8;\n\n        var formatter = this.getYFormatter();\n\n        var formattedValue = formatter(value);\n        var computedTickWidth = formattedValue.length * characterWidth;\n\n        if (computedTickWidth > yTicksMaxWidth) {\n          yTicksMaxWidth = computedTickWidth;\n        }\n      });\n\n      yTicksMaxWidth += 10;\n\n      margin.left = yTicksMaxWidth;\n\n      return margin;\n    },\n\n    getX: function (padded) {\n      var xDomainMin = d3.min(this.dataTable.rows, function (d) {\n        return d[0];\n      });\n\n      var xDomainMax = d3.max(this.dataTable.rows, function (d) {\n        return d[0];\n      });\n\n      var xDomain = [xDomainMin, xDomainMax];\n\n      if (this.orientation === 'rtl') {\n        xDomain = [xDomainMax, xDomainMin];\n      }\n\n      var left = 0;\n      var right = 0;\n\n      if (padded) {\n        left = 0;\n        right = 0;\n      }\n\n      var x = d3.scaleTime().range([left, this.width - right]);\n\n      x.domain(xDomain);\n\n      return x;\n    },\n\n    getY: function () {\n      var yDomain = [0, this.getYMaxValue()];\n\n      var y = d3.scaleLinear().range([this.height, 0]);\n\n      y.domain(yDomain);\n\n      return y;\n    },\n\n    getXFormatter: function () {\n      var formatter;\n\n      if (this.settings.xAxis.formatter !== $.noop) {\n        formatter = this.settings.xAxis.formatter(this);\n      } else {\n        formatter = Craft.charts.utils.getTimeFormatter(\n          this.timeFormatLocale,\n          this.settings\n        );\n      }\n\n      return formatter;\n    },\n\n    getYFormatter: function () {\n      var formatter;\n\n      if (this.settings.yAxis.formatter !== $.noop) {\n        formatter = this.settings.yAxis.formatter(this);\n      } else {\n        formatter = Craft.charts.utils.getNumberFormatter(\n          this.formatLocale,\n          this.dataTable.columns[1].type,\n          this.settings\n        );\n      }\n\n      return formatter;\n    },\n\n    getYMaxValue: function () {\n      return d3.max(this.dataTable.rows, function (d) {\n        return d[1];\n      });\n    },\n\n    getYTickValues: function () {\n      var maxValue = this.getYMaxValue();\n\n      if (maxValue > 1) {\n        return [maxValue / 2, maxValue];\n      } else {\n        return [0, maxValue];\n      }\n    },\n  },\n  {\n    defaults: {\n      chartClass: 'area',\n      margin: {top: 25, right: 5, bottom: 25, left: 0},\n      plots: true,\n      tips: true,\n      xAxis: {\n        gridlines: false,\n        showAxis: true,\n        formatter: $.noop,\n      },\n      yAxis: {\n        gridlines: true,\n        showAxis: false,\n        formatter: $.noop,\n      },\n    },\n  }\n);\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Utils\n */\nCraft.charts.utils = {\n  getDuration: function (seconds) {\n    var secondsNum = parseInt(seconds, 10);\n\n    var duration = {\n      hours: Math.floor(secondsNum / 3600),\n      minutes: Math.floor((secondsNum - duration.hours * 3600) / 60),\n      seconds: secondsNum - duration.hours * 3600 - duration.minutes * 60,\n    };\n\n    if (duration.hours < 10) {\n      duration.hours = `0${duration.hours}`;\n    }\n\n    if (duration.minutes < 10) {\n      duration.minutes = `0${duration.minutes}`;\n    }\n\n    if (duration.seconds < 10) {\n      duration.seconds = `0${duration.seconds}`;\n    }\n\n    return `${duration.hours}:${duration.minutes}:${duration.seconds}`;\n  },\n\n  getTimeFormatter: function (timeFormatLocale, chartSettings) {\n    switch (chartSettings.dataScale) {\n      case 'year':\n        return timeFormatLocale.format('%Y');\n\n      case 'month':\n        return timeFormatLocale.format(\n          chartSettings.formats.shortDateFormats.month\n        );\n\n      case 'hour':\n        return timeFormatLocale.format(\n          `${chartSettings.formats.shortDateFormats.day} %H:00:00`\n        );\n\n      default:\n        return timeFormatLocale.format(\n          chartSettings.formats.shortDateFormats.day\n        );\n    }\n  },\n\n  getNumberFormatter: function (formatLocale, type, chartSettings) {\n    switch (type) {\n      case 'currency':\n        return formatLocale.format(chartSettings.formats.currencyFormat);\n\n      case 'percent':\n        return formatLocale.format(chartSettings.formats.percentFormat);\n\n      case 'time':\n        return Craft.charts.utils.getDuration;\n\n      case 'number':\n        return formatLocale.format(chartSettings.formats.numberFormat);\n    }\n  },\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Color input\n */\nCraft.ColorInput = Garnish.Base.extend(\n  {\n    $container: null,\n    $input: null,\n    $colorContainer: null,\n    $colorPreview: null,\n    $colorInput: null,\n\n    init: function (container) {\n      this.$container = $(container);\n      this.$input = this.$container.find('.color-input');\n      this.$colorContainer = this.$container.children('.color');\n      this.$colorPreview = this.$colorContainer.children('.color-preview');\n\n      this.createColorInput();\n      this.handleTextChange();\n\n      this.addListener(this.$input, 'input', 'handleTextChange');\n    },\n\n    createColorInput: function () {\n      var input = document.createElement('input');\n      input.setAttribute('type', 'color');\n\n      if (input.type !== 'color') {\n        // The browser doesn't support input[type=color]\n        return;\n      }\n\n      this.$colorContainer.removeClass('static');\n      this.$colorInput = $(input)\n        .addClass('color-preview-input')\n        .attr({\n          'aria-controls': this.$input.attr('id'),\n          'aria-label': Craft.t('app', 'Color picker'),\n        })\n        .appendTo(this.$colorPreview);\n\n      this.addListener(this.$colorInput, 'click', function (ev) {\n        ev.stopPropagation();\n      });\n\n      this.addListener(this.$colorContainer, 'click', function () {\n        this.$colorInput.trigger('click');\n      });\n\n      this.addListener(this.$colorInput, 'input', 'updateColor');\n    },\n\n    updateColor: function () {\n      this.$input.val(this.$colorInput.val());\n      this.handleTextChange();\n    },\n\n    handleTextChange: function () {\n      let val = this.$input.val();\n\n      if (val !== (val = Craft.trim(val))) {\n        this.$input.val(val);\n      }\n\n      // Chop off the #\n      if (val.length && val[0] === '#') {\n        val = val.substring(1);\n        this.$input.val(val);\n      }\n\n      // If empty, set the preview to transparent\n      if (!val.length) {\n        this.$colorPreview.css('background-color', '');\n        return;\n      }\n\n      // Now normalize it for the UI stuff\n      if (val.length === 3) {\n        val = val[0].repeat(2) + val[1].repeat(2) + val[2].repeat(2);\n      }\n\n      if (val.match(/^[0-9a-f]{6}$/i)) {\n        this.$colorPreview.css('background-color', `#${val}`);\n        if (this.$colorInput) {\n          this.$colorInput.val(`#${val}`);\n        }\n      } else {\n        this.$colorPreview.css('background-color', '');\n      }\n    },\n  },\n  {\n    _browserSupportsColorInputs: null,\n\n    doesBrowserSupportColorInputs: function () {\n      if (Craft.ColorInput._browserSupportsColorInputs === null) {\n      }\n\n      return Craft.ColorInput._browserSupportsColorInputs;\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * CP Screen Slideout\n */\nCraft.CpScreenSlideout = Craft.Slideout.extend(\n  {\n    action: null,\n\n    namespace: null,\n\n    showingLoadSpinner: false,\n    hasTabs: false,\n    hasCpLink: false,\n    hasSidebar: false,\n\n    $header: null,\n    $toolbar: null,\n    $tabContainer: null,\n    $loadSpinner: null,\n    $editLink: null,\n    $sidebarBtn: null,\n\n    $body: null,\n    $content: null,\n\n    $sidebar: null,\n\n    $footer: null,\n    $noticeContainer: null,\n    $cancelBtn: null,\n    $saveBtn: null,\n\n    tabManager: null,\n    showingSidebar: false,\n\n    cancelToken: null,\n    ignoreFailedRequest: false,\n    fieldsWithErrors: null,\n\n    init: function (action, settings) {\n      this.action = action;\n      this.setSettings(settings, Craft.CpScreenSlideout.defaults);\n\n      this.fieldsWithErrors = [];\n\n      // Header\n      this.$header = $('<header/>', {class: 'pane-header'});\n      this.$toolbar = $('<div/>', {class: 'so-toolbar'}).appendTo(this.$header);\n      this.$tabContainer = $('<div/>', {class: 'pane-tabs'}).appendTo(\n        this.$toolbar\n      );\n      this.$loadSpinner = $('<div/>', {\n        class: 'spinner',\n        title: Craft.t('app', 'Loading'),\n        'aria-label': Craft.t('app', 'Loading'),\n      }).appendTo(this.$toolbar);\n      this.$editLink = $('<a/>', {\n        target: '_blank',\n        class: 'btn header-btn hidden',\n        title: Craft.t('app', 'Open the full edit page in a new tab'),\n        'aria-label': Craft.t('app', 'Open the full edit page in a new tab'),\n        'data-icon': 'external',\n      }).appendTo(this.$toolbar);\n      this.$sidebarBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn header-btn hidden sidebar-btn',\n        title: Craft.t('app', 'Show sidebar'),\n        'aria-label': Craft.t('app', 'Show sidebar'),\n        'data-icon': `sidebar-${Garnish.ltr ? 'right' : 'left'}`,\n        'aria-expanded': 'false',\n      }).appendTo(this.$toolbar);\n\n      this.addListener(this.$sidebarBtn, 'click', (ev) => {\n        ev.preventDefault();\n        if (!this.showingSidebar) {\n          this.showSidebar();\n        } else {\n          this.hideSidebar();\n        }\n      });\n\n      // Body\n      this.$body = $('<div/>', {class: 'so-body'});\n\n      // Content\n      this.$content = $('<div/>', {class: 'so-content'}).appendTo(this.$body);\n\n      // Sidebar\n      this.$sidebar = $('<div/>', {\n        class: 'so-sidebar details hidden',\n      }).appendTo(this.$body);\n\n      // Footer\n      this.$footer = $('<div/>', {class: 'so-footer hidden'});\n      this.$noticeContainer = $('<div/>', {class: 'so-notice'}).appendTo(\n        this.$footer\n      );\n      $('<div/>', {class: 'flex-grow'}).appendTo(this.$footer);\n      const $btnContainer = $('<div/>', {class: 'flex flex-nowrap'}).appendTo(\n        this.$footer\n      );\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo($btnContainer);\n      this.$saveBtn = Craft.ui\n        .createSubmitButton({\n          label: Craft.t('app', 'Save'),\n          spinner: true,\n        })\n        .appendTo($btnContainer);\n\n      let $contents = this.$header.add(this.$body).add(this.$footer);\n\n      this.base($contents, {\n        containerElement: 'form',\n        containerAttributes: {\n          id: `cp-screen-${Math.floor(Math.random() * 100000000)}`,\n          action: '',\n          method: 'post',\n          novalidate: '',\n          class: 'cp-screen',\n        },\n        closeOnEsc: false,\n        closeOnShadeClick: false,\n      });\n\n      this.$container.data('cpScreen', this);\n      this.on('beforeClose', () => {\n        this.hideSidebar();\n      });\n\n      // Register shortcuts & events\n      Garnish.uiLayerManager.registerShortcut(\n        {\n          keyCode: Garnish.S_KEY,\n          ctrl: true,\n        },\n        (ev) => {\n          this.handleSubmit(ev);\n        }\n      );\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.closeMeMaybe();\n      });\n      this.addListener(this.$cancelBtn, 'click', () => {\n        this.closeMeMaybe();\n      });\n      this.addListener(this.$shade, 'click', () => {\n        this.closeMeMaybe();\n      });\n      this.addListener(this.$container, 'click', (ev) => {\n        const $target = $(event.target);\n\n        if (\n          this.showingSidebar &&\n          !$target.closest(this.$sidebarBtn).length &&\n          !$target.closest(this.$sidebar).length\n        ) {\n          this.hideSidebar();\n        }\n      });\n      this.addListener(this.$container, 'submit', 'handleSubmit');\n\n      this.load();\n    },\n\n    /**\n     * @param {Object} [data={}]\n     * @param {boolean} [refreshInitialData=true]\n     * @returns {Promise}\n     */\n    load: function (data, refreshInitialData) {\n      return new Promise((resolve, reject) => {\n        this.trigger('beforeLoad');\n        this.showLoadSpinner();\n\n        if (this.cancelToken) {\n          this.ignoreFailedRequest = true;\n          this.cancelToken.cancel();\n        }\n\n        this.cancelToken = axios.CancelToken.source();\n\n        Craft.sendActionRequest(\n          'GET',\n          this.action,\n          $.extend(\n            {\n              params: Object.assign({}, this.getParams(), this.settings.params),\n              cancelToken: this.cancelToken.token,\n              headers: {\n                'X-Craft-Container-Id': this.$container.attr('id'),\n              },\n            },\n            this.settings.requestOptions\n          )\n        )\n          .then((response) => {\n            this.update(response.data)\n              .then(() => {\n                if (refreshInitialData !== false) {\n                  this.$container.data('delta-names', response.data.deltaNames);\n                  this.$container.data(\n                    'initial-delta-values',\n                    response.data.initialDeltaValues\n                  );\n                  this.$container.data(\n                    'initialSerializedValue',\n                    this.$container.serialize()\n                  );\n                }\n                resolve();\n              })\n              .catch((e) => {\n                reject(e);\n              });\n          })\n          .catch((e) => {\n            if (!this.ignoreFailedRequest) {\n              Craft.cp.displayError();\n              reject(e);\n            }\n            this.ignoreFailedRequest = false;\n          })\n          .finally(() => {\n            this.hideLoadSpinner();\n            this.cancelToken = null;\n          });\n      });\n    },\n\n    getParams: function () {\n      return {};\n    },\n\n    updateHeaderVisibility: function () {\n      // Should the header be shown regardless of viewport size?\n      const forceShow =\n        this.settings.showHeader ||\n        this.hasTabs ||\n        this.hasCpLink ||\n        this.showingLoadSpinner;\n\n      if (forceShow || this.hasSidebar) {\n        this.$header.removeClass('hidden');\n      } else {\n        this.$header.addClass('hidden');\n      }\n\n      if (forceShow) {\n        this.$header.addClass('so-visible');\n      } else {\n        this.$header.removeClass('so-visible');\n      }\n    },\n\n    showLoadSpinner: function () {\n      this.$loadSpinner.removeClass('hidden');\n      this.showingLoadSpinner = true;\n      this.updateHeaderVisibility();\n    },\n\n    hideLoadSpinner: function () {\n      this.$loadSpinner.addClass('hidden');\n      this.showingLoadSpinner = false;\n      this.updateHeaderVisibility();\n    },\n\n    /**\n     * @param {Object} data\n     * @returns {Promise}\n     */\n    update: function (data) {\n      return new Promise((resolve) => {\n        this.namespace = data.namespace;\n        this.$content.html(data.content);\n\n        if (data.submitButtonLabel) {\n          this.$saveBtn.text(data.submitButtonLabel);\n        }\n\n        this.updateTabs(data.tabs);\n\n        if (data.formAttributes) {\n          Craft.setElementAttributes(this.$container, data.formAttributes);\n        }\n\n        if (data.editUrl) {\n          this.$editLink.removeClass('hidden').attr('href', data.editUrl);\n          this.hasCpLink = true;\n        } else {\n          this.$editLink.addClass('hidden');\n          this.hasCpLink = false;\n        }\n\n        if (data.sidebar) {\n          this.$container.addClass('has-sidebar');\n          this.$sidebarBtn.removeClass('hidden');\n          this.$sidebar.html(data.sidebar);\n\n          // Open outbound links in new windows\n          this.$sidebar.find('a').each(function () {\n            if (\n              this.hostname.length &&\n              typeof $(this).attr('target') === 'undefined'\n            ) {\n              $(this).attr('target', '_blank');\n            }\n          });\n\n          this.hasSidebar = true;\n        } else {\n          this.$container.removeClass('has-sidebar');\n          this.$sidebarBtn.addClass('hidden');\n          this.$sidebar.addClass('hidden').html('');\n          this.hasSidebar = false;\n        }\n\n        if (data.notice) {\n          this.$noticeContainer.html(data.notice);\n        } else {\n          this.$noticeContainer.empty();\n        }\n\n        this.updateHeaderVisibility();\n        this.$footer.removeClass('hidden');\n\n        Garnish.requestAnimationFrame(() => {\n          Craft.appendHeadHtml(data.headHtml);\n          Craft.appendBodyHtml(data.bodyHtml);\n\n          Craft.initUiElements(this.$content);\n          Craft.cp.elementThumbLoader.load($(this.$content));\n\n          if (data.sidebar) {\n            Craft.initUiElements(this.$sidebar);\n            Craft.cp.elementThumbLoader.load(this.$sidebar);\n          }\n\n          if (!Garnish.isMobileBrowser()) {\n            Craft.setFocusWithin(this.$content);\n          }\n\n          resolve();\n          this.trigger('load');\n        });\n      });\n    },\n\n    updateTabs: function (tabs) {\n      if (this.tabManager) {\n        this.tabManager.destroy();\n        this.tabManager = null;\n        this.$tabContainer.html('');\n      }\n\n      this.hasTabs = !!tabs;\n\n      if (this.hasTabs) {\n        const $tabContainer = $(tabs);\n        this.$tabContainer.replaceWith($tabContainer);\n        this.$tabContainer = $tabContainer;\n        this.tabManager = new Craft.Tabs(this.$tabContainer);\n        this.tabManager.on('deselectTab', (ev) => {\n          $(ev.$tab.attr('href')).addClass('hidden');\n        });\n        this.tabManager.on('selectTab', (ev) => {\n          $(ev.$tab.attr('href')).removeClass('hidden');\n          Garnish.$win.trigger('resize');\n          this.$body.trigger('scroll');\n        });\n      }\n    },\n\n    showSidebar: function () {\n      if (this.showingSidebar) {\n        return;\n      }\n\n      this.$body.scrollTop(0).addClass('no-scroll');\n\n      this.$sidebar\n        .off('transitionend.so')\n        .css(this._closedSidebarStyles())\n        .removeClass('hidden');\n\n      // Hack to force CSS animations\n      this.$sidebar[0].offsetWidth;\n\n      this.$sidebar.css(this._openedSidebarStyles());\n\n      if (!Garnish.isMobileBrowser()) {\n        this.$sidebar.one('transitionend.so', () => {\n          Craft.setFocusWithin(this.$sidebar);\n        });\n      }\n\n      Craft.trapFocusWithin(this.$sidebar);\n\n      this.$sidebarBtn.addClass('active').attr({\n        'aria-expanded': 'true',\n      });\n\n      Garnish.$win.trigger('resize');\n      this.$sidebar.trigger('scroll');\n\n      Garnish.uiLayerManager.addLayer();\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.hideSidebar();\n      });\n\n      this.showingSidebar = true;\n    },\n\n    hideSidebar: function () {\n      if (!this.showingSidebar) {\n        return;\n      }\n\n      this.$body.removeClass('no-scroll');\n\n      this.$sidebar\n        .off('transitionend.so')\n        .css(this._closedSidebarStyles())\n        .one('transitionend.so', () => {\n          this.$sidebar.addClass('hidden');\n          this.$sidebarBtn.focus();\n        });\n\n      this.$sidebarBtn.removeClass('active').attr({\n        'aria-expanded': 'false',\n      });\n\n      Garnish.uiLayerManager.removeLayer();\n\n      this.showingSidebar = false;\n    },\n\n    _openedSidebarStyles: function () {\n      return {\n        [Garnish.ltr ? 'right' : 'left']: '0',\n      };\n    },\n\n    _closedSidebarStyles: function () {\n      return {\n        [Garnish.ltr ? 'right' : 'left']: '-350px',\n      };\n    },\n\n    showSubmitSpinner: function () {\n      this.$saveBtn.addClass('loading');\n    },\n\n    hideSubmitSpinner: function () {\n      this.$saveBtn.removeClass('loading');\n    },\n\n    handleSubmit: function (ev) {\n      ev.preventDefault();\n      this.submit();\n    },\n\n    submit: function () {\n      this.showSubmitSpinner();\n\n      const data = Craft.findDeltaData(\n        this.$container.data('initialSerializedValue'),\n        this.$container.serialize(),\n        this.$container.data('delta-names'),\n        null,\n        this.$container.data('initial-delta-values')\n      );\n\n      Craft.sendActionRequest('POST', null, {\n        data,\n        headers: {\n          'X-Craft-Namespace': this.namespace,\n        },\n      })\n        .then((response) => {\n          this.handleSubmitResponse(response);\n        })\n        .catch((error) => {\n          this.handleSubmitError(error);\n        })\n        .finally(() => {\n          this.hideSubmitSpinner();\n        });\n    },\n\n    handleSubmitResponse: function (response) {\n      this.clearErrors();\n      const data = response.data || {};\n      if (data.message) {\n        Craft.cp.displaySuccess(data.message, data.notificationSettings);\n      }\n      this.trigger('submit', {\n        response: response,\n        data: (data.modelName && data[data.modelName]) || {},\n      });\n      if (this.settings.closeOnSubmit) {\n        this.close();\n      }\n    },\n\n    handleSubmitError: function (error) {\n      if (\n        !error.isAxiosError ||\n        !error.response ||\n        !error.response.status === 400\n      ) {\n        Craft.cp.displayError();\n        throw error;\n      }\n\n      const data = error.response.data || {};\n      Craft.cp.displayError(data.message);\n      if (data.errors) {\n        this.showErrors(data.errors);\n      }\n    },\n\n    /**\n     * @param {string[]} errors\n     */\n    showErrors: function (errors) {\n      this.clearErrors();\n\n      Object.entries(errors).forEach(([name, fieldErrors]) => {\n        const $field = this.$container.find(`[data-attribute=\"${name}\"]`);\n        if ($field) {\n          Craft.ui.addErrorsToField($field, fieldErrors);\n          this.fieldsWithErrors.push($field);\n        }\n      });\n    },\n\n    clearErrors: function () {\n      this.fieldsWithErrors.forEach(($field) => {\n        Craft.ui.clearErrorsFromField($field);\n      });\n    },\n\n    isDirty: function () {\n      return (\n        typeof this.$container.data('initialSerializedValue') !== 'undefined' &&\n        this.$container.serialize() !==\n          this.$container.data('initialSerializedValue')\n      );\n    },\n\n    closeMeMaybe: function () {\n      if (!this.isOpen) {\n        return;\n      }\n\n      if (\n        !this.isDirty() ||\n        confirm(\n          Craft.t(\n            'app',\n            'Are you sure you want to close this screen? Any changes will be lost.'\n          )\n        )\n      ) {\n        this.close();\n      }\n    },\n\n    close: function () {\n      this.base();\n\n      if (this.cancelToken) {\n        this.ignoreFailedRequest = true;\n        this.cancelToken.cancel();\n      }\n    },\n  },\n  {\n    defaults: {\n      params: {},\n      requestOptions: {},\n      showHeader: null,\n      closeOnSubmit: true,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n// Use old jQuery prefilter behavior\n// see https://jquery.com/upgrade-guide/3.5/\nvar rxhtmlTag =\n  /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\\/\\0>\\x20\\t\\r\\n\\f]*)[^>]*)\\/>/gi;\njQuery.htmlPrefilter = function (html) {\n  return html.replace(rxhtmlTag, '<$1></$2>');\n};\n\n// Set all the standard Craft.* stuff\n$.extend(Craft, {\n  navHeight: 48,\n\n  /**\n   * @callback indexKeyCallback\n   * @param {Object} currentValue\n   * @param {number} [index]\n   * @returns {string}\n   */\n  /**\n   * Indexes an array of objects by a specified key\n   *\n   * @param {Object[]} arr\n   * @param {(string|indexKeyCallback)} key\n   */\n  index: function (arr, key) {\n    if (!$.isArray(arr)) {\n      throw 'The first argument passed to Craft.index() must be an array.';\n    }\n\n    return arr.reduce((index, obj, i) => {\n      index[typeof key === 'string' ? obj[key] : key(obj, i)] = obj;\n      return index;\n    }, {});\n  },\n\n  /**\n   * Groups an array of objects by a specified key\n   *\n   * @param {Object[]} arr\n   * @param {(string|indexKeyCallback)} key\n   */\n  group: function (arr, key) {\n    if (!$.isArray(arr)) {\n      throw 'The first argument passed to Craft.group() must be an array.';\n    }\n\n    let index = {};\n\n    return arr.reduce((grouped, obj, i) => {\n      const thisKey = typeof key === 'string' ? obj[key] : key(obj, i);\n      if (!index.hasOwnProperty(thisKey)) {\n        index[thisKey] = [[], thisKey];\n        grouped.push(index[thisKey]);\n      }\n      index[thisKey][0].push(obj);\n      return grouped;\n    }, []);\n  },\n\n  /**\n   * Get a translated message.\n   *\n   * @param {string} category\n   * @param {string} message\n   * @param {Object} params\n   * @returns {string}\n   */\n  t: function (category, message, params) {\n    if (\n      typeof Craft.translations[category] !== 'undefined' &&\n      typeof Craft.translations[category][message] !== 'undefined'\n    ) {\n      message = Craft.translations[category][message];\n    }\n\n    if (params) {\n      return this.formatMessage(message, params);\n    }\n\n    return message;\n  },\n\n  formatMessage: function (pattern, args) {\n    let tokens;\n    if ((tokens = this._tokenizePattern(pattern)) === false) {\n      throw 'Message pattern is invalid.';\n    }\n    for (let i = 0; i < tokens.length; i++) {\n      let token = tokens[i];\n      if (typeof token === 'object') {\n        if ((tokens[i] = this._parseToken(token, args)) === false) {\n          throw 'Message pattern is invalid.';\n        }\n      }\n    }\n    return tokens.join('');\n  },\n\n  _tokenizePattern: function (pattern) {\n    let depth = 1,\n      start,\n      pos;\n    // Get an array of the string characters (factoring in 3+ byte chars)\n    const chars = [...pattern];\n    if ((start = pos = chars.indexOf('{')) === -1) {\n      return [pattern];\n    }\n    let tokens = [chars.slice(0, pos).join('')];\n    while (true) {\n      let open = chars.indexOf('{', pos + 1);\n      let close = chars.indexOf('}', pos + 1);\n      if (open === -1) {\n        open = false;\n      }\n      if (close === -1) {\n        close = false;\n      }\n      if (open === false && close === false) {\n        break;\n      }\n      if (open === false) {\n        open = chars.length;\n      }\n      if (close > open) {\n        depth++;\n        pos = open;\n      } else {\n        depth--;\n        pos = close;\n      }\n      if (depth === 0) {\n        tokens.push(\n          chars\n            .slice(start + 1, pos)\n            .join('')\n            .split(',', 3)\n        );\n        start = pos + 1;\n        tokens.push(chars.slice(start, open).join(''));\n        start = open;\n      }\n\n      if (depth !== 0 && (open === false || close === false)) {\n        break;\n      }\n    }\n    if (depth !== 0) {\n      return false;\n    }\n\n    return tokens;\n  },\n\n  _parseToken: function (token, args) {\n    // parsing pattern based on ICU grammar:\n    // http://icu-project.org/apiref/icu4c/classMessageFormat.html#details\n    const param = Craft.trim(token[0]);\n    if (typeof args[param] === 'undefined') {\n      return `{${token.join(',')}}`;\n    }\n    const arg = args[param];\n    const type =\n      typeof token[1] !== 'undefined' ? Craft.trim(token[1]) : 'none';\n    switch (type) {\n      case 'number':\n        return (() => {\n          let format =\n            typeof token[2] !== 'undefined' ? Craft.trim(token[2]) : null;\n          if (format !== null && format !== 'integer') {\n            throw `Message format 'number' is only supported for integer values.`;\n          }\n          let number = Craft.formatNumber(arg);\n          let pos;\n          if (format === null && (pos = `${arg}`.indexOf('.')) !== -1) {\n            number += `.${arg.substring(pos + 1)}`;\n          }\n          return number;\n        })();\n      case 'none':\n        return arg;\n      case 'select':\n        return (() => {\n          /* http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html\n                        selectStyle = (selector '{' message '}')+\n                        */\n          if (typeof token[2] === 'undefined') {\n            return false;\n          }\n          let select = this._tokenizePattern(token[2]);\n          let c = select.length;\n          let message = false;\n          for (let i = 0; i + 1 < c; i++) {\n            if (Garnish.isArray(select[i]) || !Garnish.isArray(select[i + 1])) {\n              return false;\n            }\n            let selector = Craft.trim(select[i++]);\n            if (\n              (message === false && selector === 'other') ||\n              selector == arg\n            ) {\n              message = select[i].join(',');\n            }\n          }\n          if (message === false) {\n            return false;\n          }\n          return this.formatMessage(message, args);\n        })();\n      case 'plural':\n        return (() => {\n          /* http://icu-project.org/apiref/icu4c/classicu_1_1PluralFormat.html\n                        pluralStyle = [offsetValue] (selector '{' message '}')+\n                        offsetValue = \"offset:\" number\n                        selector = explicitValue | keyword\n                        explicitValue = '=' number  // adjacent, no white space in between\n                        keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+\n                        message: see MessageFormat\n                        */\n          if (typeof token[2] === 'undefined') {\n            return false;\n          }\n          let plural = this._tokenizePattern(token[2]);\n          const c = plural.length;\n          let message = false;\n          let offset = 0;\n          for (let i = 0; i + 1 < c; i++) {\n            if (\n              typeof plural[i] === 'object' ||\n              typeof plural[i + 1] !== 'object'\n            ) {\n              return false;\n            }\n            let selector = Craft.trim(plural[i++]);\n            let selectorChars = [...selector];\n\n            if (i === 1 && selector.substring(0, 7) === 'offset:') {\n              let pos = [...selector.replace(/[\\n\\r\\t]/g, ' ')].indexOf(' ', 7);\n              if (pos === -1) {\n                throw 'Message pattern is invalid.';\n              }\n              offset = parseInt(\n                Craft.trim(selectorChars.slice(7, pos).join(''))\n              );\n              selector = Craft.trim(\n                selectorChars\n                  .slice(pos + 1, pos + 1 + selectorChars.length)\n                  .join('')\n              );\n            }\n            if (\n              (message === false && selector === 'other') ||\n              (selector[0] === '=' &&\n                parseInt(\n                  selectorChars.slice(1, 1 + selectorChars.length).join('')\n                ) === arg) ||\n              (selector === 'one' && arg - offset === 1)\n            ) {\n              message = (\n                typeof plural[i] === 'string' ? [plural[i]] : plural[i]\n              )\n                .map((p) => {\n                  return p.replace('#', arg - offset);\n                })\n                .join(',');\n            }\n          }\n          if (message === false) {\n            return false;\n          }\n          return this.formatMessage(message, args);\n        })();\n      default:\n        throw `Message format '${type}' is not supported.`;\n    }\n  },\n\n  formatDate: function (date) {\n    if (typeof date !== 'object') {\n      date = new Date(date);\n    }\n\n    return $.datepicker.formatDate(Craft.datepickerOptions.dateFormat, date);\n  },\n\n  /**\n   * Formats a number.\n   *\n   * @param {string} number\n   * @param {string} [format] D3 format\n   * @returns {string}\n   */\n  formatNumber: function (number, format) {\n    if (typeof format == 'undefined') {\n      format = ',.0f';\n    }\n\n    var formatter = d3.formatLocale(d3FormatLocaleDefinition).format(format);\n\n    return formatter(number);\n  },\n\n  /**\n   * @param {string} key\n   * @param {boolean} shift\n   * @param {boolean} alt\n   */\n  shortcutText: function (key, shift, alt) {\n    if (Craft.clientOs === 'Mac') {\n      return (alt ? '⌥' : '') + (shift ? '⇧' : '') + '⌘' + key;\n    }\n    return 'Ctrl+' + (alt ? 'Alt+' : '') + (shift ? 'Shift+' : '') + key;\n  },\n\n  /**\n   * Escapes some HTML.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  escapeHtml: function (str) {\n    return $('<div/>').text(str).html();\n  },\n\n  /**\n   * Escapes special regular expression characters.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  escapeRegex: function (str) {\n    // h/t https://stackoverflow.com/a/9310752\n    return str.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n  },\n\n  /**\n   * Returns the text in a string that might contain HTML tags.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  getText: function (str) {\n    return $('<div/>').html(str).text();\n  },\n\n  /**\n   * Encodes a URI copmonent. Mirrors PHP's rawurlencode().\n   *\n   * @param {string} str\n   * @returns {string}\n   * @see http://stackoverflow.com/questions/1734250/what-is-the-equivalent-of-javascripts-encodeuricomponent-in-php\n   */\n  encodeUriComponent: function (str) {\n    str = encodeURIComponent(str);\n\n    var differences = {\n      '!': '%21',\n      '*': '%2A',\n      \"'\": '%27',\n      '(': '%28',\n      ')': '%29',\n    };\n\n    for (var chr in differences) {\n      var re = new RegExp('\\\\' + chr, 'g');\n      str = str.replace(re, differences[chr]);\n    }\n\n    return str;\n  },\n\n  /**\n   * Selects the full value of a given text input.\n   *\n   * @param {(jQuery|HTMLElement|string)} input\n   */\n  selectFullValue: function (input) {\n    var $input = $(input);\n    var val = $input.val();\n\n    // Does the browser support setSelectionRange()?\n    if (typeof $input[0].setSelectionRange !== 'undefined') {\n      // Select the whole value\n      var length = val.length * 2;\n      $input[0].setSelectionRange(0, length);\n    } else {\n      // Refresh the value to get the cursor positioned at the end\n      $input.val(val);\n    }\n  },\n\n  /**\n   * Formats an ID out of an input name.\n   *\n   * @param {string} inputName\n   * @returns {string}\n   */\n  formatInputId: function (inputName) {\n    return this.rtrim(inputName.replace(/[^\\w\\-]+/g, '-'), '-');\n  },\n\n  /**\n   * @param {string} [path]\n   * @param {(Object|string)} [params]\n   * @param {string} [baseUrl]\n   * @returns {string}\n   */\n  getUrl: function (path, params, baseUrl) {\n    if (typeof path !== 'string') {\n      path = '';\n    }\n\n    // Normalize the params\n    let anchor = null;\n    if ($.isPlainObject(params)) {\n      if (typeof params['#'] !== 'undefined') {\n        anchor = params['#'];\n        delete params['#'];\n      }\n    } else if (typeof params === 'string') {\n      let anchorPos = params.indexOf('#');\n      if (anchorPos !== -1) {\n        anchor = params.substring(anchorPos + 1);\n        params = params.substring(0, anchorPos);\n      }\n      params = Object.fromEntries(new URLSearchParams(params).entries());\n    } else {\n      params = {};\n    }\n\n    // Was there already an anchor on the path?\n    let anchorPos = path.indexOf('#');\n    if (anchorPos !== -1) {\n      // Only keep it if the params didn't specify a new anchor\n      if (!anchor) {\n        anchor = path.substring(anchorPos + 1);\n      }\n      path = path.substring(0, anchorPos);\n    }\n\n    // Were there already any query string params in the path?\n    let qsPos = path.indexOf('?');\n    if (qsPos !== -1) {\n      params = $.extend(\n        Object.fromEntries(\n          new URLSearchParams(path.substring(qsPos + 1)).entries()\n        ),\n        params\n      );\n      path = path.substring(0, qsPos);\n    }\n\n    // Return path if it appears to be an absolute URL.\n    if (path.search('://') !== -1 || path[0] === '/') {\n      return (\n        path +\n        (!$.isEmptyObject(params) ? `?${$.param(params)}` : '') +\n        (anchor ? `#${anchor}` : '')\n      );\n    }\n\n    path = Craft.trim(path, '/');\n\n    // Put it all together\n    let url;\n\n    if (baseUrl) {\n      url = baseUrl;\n\n      if (path && Craft.pathParam) {\n        // Does baseUrl already contain a path?\n        var pathMatch = url.match(\n          new RegExp('[&?]' + Craft.escapeRegex(Craft.pathParam) + '=[^&]+')\n        );\n        if (pathMatch) {\n          url = url.replace(\n            pathMatch[0],\n            Craft.rtrim(pathMatch[0], '/') + '/' + path\n          );\n          path = '';\n        }\n      }\n    } else {\n      url = Craft.baseUrl;\n    }\n\n    // Does the base URL already have a query string?\n    qsPos = url.indexOf('?');\n    if (qsPos !== -1) {\n      params = $.extend(\n        Object.fromEntries(\n          new URLSearchParams(url.substring(qsPos + 1)).entries()\n        ),\n        params\n      );\n      url = url.substring(0, qsPos);\n    }\n\n    if (!Craft.omitScriptNameInUrls && path) {\n      if (Craft.usePathInfo || !Craft.pathParam) {\n        // Make sure that the script name is in the URL\n        if (url.search(Craft.scriptName) === -1) {\n          url = Craft.rtrim(url, '/') + '/' + Craft.scriptName;\n        }\n      } else {\n        // Move the path into the query string params\n\n        // Is the path param already set?\n        if (typeof params[Craft.pathParam] !== 'undefined') {\n          let basePath = Craft.rtrim(params[Craft.pathParam]);\n          path = basePath + (path ? '/' + path : '');\n        }\n\n        params[Craft.pathParam] = path;\n        path = null;\n      }\n    }\n\n    if (path) {\n      url = Craft.rtrim(url, '/') + '/' + path;\n    }\n\n    if (!$.isEmptyObject(params)) {\n      url += `?${$.param(params)}`;\n    }\n\n    if (anchor) {\n      url += `#${anchor}`;\n    }\n\n    return url;\n  },\n\n  /**\n   * @param {string} [path]\n   * @param {(Object|string)} [params]\n   * @returns {string}\n   */\n  getCpUrl: function (path, params) {\n    return this.getUrl(path, params, Craft.baseCpUrl);\n  },\n\n  /**\n   * @param {string} [path]\n   * @param {(Object|string)} [params]\n   * @returns {string}\n   */\n  getSiteUrl: function (path, params) {\n    return this.getUrl(path, params, Craft.baseSiteUrl);\n  },\n\n  /**\n   * Returns an action URL.\n   *\n   * @param {string} action\n   * @param {(Object|string)} [params]\n   * @returns {string}\n   */\n  getActionUrl: function (action, params) {\n    return Craft.getUrl(action, params, Craft.actionUrl);\n  },\n\n  /**\n   * Redirects the window to a given URL.\n   *\n   * @param {string} url\n   */\n  redirectTo: function (url) {\n    document.location.href = this.getUrl(url);\n  },\n\n  /**\n   * Replaces the page’s current URL.\n   *\n   * The location hash will be left intact, unless the given URL specifies one.\n   *\n   * @param {string} url\n   */\n  setUrl: function (url) {\n    if (typeof history === 'undefined') {\n      return;\n    }\n\n    if (!url.match(/#/)) {\n      url += document.location.hash;\n    }\n\n    history.replaceState({}, '', url);\n  },\n\n  /**\n   * Replaces the page’s current URL based on the given path, leaving the current query string and hash intact.\n   *\n   * @param {string} path\n   */\n  setPath: function (path) {\n    this.path = path;\n    this.setUrl(Craft.getUrl(path, document.location.search));\n  },\n\n  /**\n   * Replaces the page’s current URL based on the given query param name and value, leaving the current URI, other query params, and hash intact.\n   *\n   * @param {string} name\n   * @param {*} value\n   */\n  setQueryParam(name, value) {\n    const baseUrl = document.location.origin + document.location.pathname;\n    const params = this.getQueryParams();\n\n    if (typeof value !== 'undefined' && value !== null && value !== false) {\n      params[name] = value;\n    } else {\n      delete params[name];\n    }\n\n    this.setUrl(Craft.getUrl(baseUrl, params));\n  },\n\n  /**\n   * Returns the current URL with a certain page added to it.\n   *\n   * @param {int} page\n   * @returns {string}\n   */\n  getPageUrl: function (page) {\n    let url = document.location.origin + document.location.pathname;\n    url = Craft.rtrim(url, '/');\n\n    let qs = document.location.search\n      ? document.location.search.substring(1)\n      : '';\n\n    // query string-based pagination?\n    if (Craft.pageTrigger[0] === '?') {\n      const pageParam = Craft.pageTrigger.substring(1);\n      // remove the existing page param\n      if (document.location.search) {\n        const params = Object.fromEntries(new URLSearchParams(qs).entries());\n        delete params[pageParam];\n        qs = $.param(params);\n      }\n      if (page !== 1) {\n        qs += (qs !== '' ? '&' : '') + `${pageParam}=${page}`;\n      }\n    } else {\n      // Remove the existing page segment(s)\n      url = url.replace(\n        new RegExp('/' + Craft.escapeRegex(Craft.pageTrigger) + '\\\\d+$'),\n        ''\n      );\n\n      if (page !== 1) {\n        url += `/${Craft.pageTrigger}${page}`;\n      }\n    }\n\n    return url + (qs ? `?${qs}` : '') + document.location.hash;\n  },\n\n  /**\n   * Returns a hidden CSRF token input, if CSRF protection is enabled.\n   *\n   * @returns {string}\n   */\n  getCsrfInput: function () {\n    if (Craft.csrfTokenName) {\n      return (\n        '<input type=\"hidden\" name=\"' +\n        Craft.csrfTokenName +\n        '\" value=\"' +\n        Craft.csrfTokenValue +\n        '\"/>'\n      );\n    } else {\n      return '';\n    }\n  },\n\n  /**\n   * @callback postActionRequestCallback\n   * @param {?Object} response\n   * @param {string} textStatus\n   * @param {Object} jqXHR\n   */\n  /**\n   * Posts an action request to the server.\n   *\n   * @param {string} action\n   * @param {Object} [data]\n   * @param {postActionRequestCallback} [callback]\n   * @param {Object} [options]\n   * @returns {Object}\n   * @deprecated in 3.4.6. sendActionRequest() should be used instead\n   */\n  postActionRequest: function (action, data, callback, options) {\n    // Make 'data' optional\n    if (typeof data === 'function') {\n      options = callback;\n      callback = data;\n      data = {};\n    }\n\n    options = options || {};\n\n    if (options.contentType && options.contentType.match(/\\bjson\\b/)) {\n      if (typeof data === 'object') {\n        data = JSON.stringify(data);\n      }\n      options.contentType = 'application/json; charset=utf-8';\n    }\n\n    var jqXHR = $.ajax(\n      $.extend(\n        {\n          url: Craft.getActionUrl(action),\n          type: 'POST',\n          dataType: 'json',\n          headers: this._actionHeaders(),\n          data: data,\n          success: callback,\n          error: function (jqXHR, textStatus, errorThrown) {\n            // Ignore incomplete requests, likely due to navigating away from the page\n            // h/t https://stackoverflow.com/a/22107079/1688568\n            if (jqXHR.readyState !== 4) {\n              return;\n            }\n\n            if (jqXHR.status !== 400) {\n              if (typeof Craft.cp !== 'undefined') {\n                Craft.cp.displayError();\n              } else {\n                alert(Craft.t('app', 'A server error occurred.'));\n              }\n            }\n\n            if (callback) {\n              callback(\n                jqXHR.status === 400 ? jqXHR.responseJSON : null,\n                textStatus,\n                jqXHR\n              );\n            }\n          },\n        },\n        options\n      )\n    );\n\n    // Call the 'send' callback\n    if (typeof options.send === 'function') {\n      options.send(jqXHR);\n    }\n\n    return jqXHR;\n  },\n\n  _actionHeaders: function () {\n    let headers = {\n      'X-Registered-Asset-Bundles': Object.keys(\n        Craft.registeredAssetBundles\n      ).join(','),\n      'X-Registered-Js-Files': Object.keys(Craft.registeredJsFiles).join(','),\n    };\n\n    if (Craft.csrfTokenValue) {\n      headers['X-CSRF-Token'] = Craft.csrfTokenValue;\n    }\n\n    return headers;\n  },\n\n  /**\n   * Sends a request to a Craft/plugin action\n   * @param {string} method The request action to use ('GET' or 'POST')\n   * @param {?string} [action] The action to request\n   * @param {Object} [options] Axios request options\n   * @returns {Promise}\n   * @since 3.4.6\n   */\n  sendActionRequest: function (method, action, options = {}) {\n    if ($.isPlainObject(action)) {\n      options = action;\n      action = null;\n    }\n\n    if (method.toUpperCase() === 'POST' && action && options.data) {\n      // Avoid conflicting `action` params\n      if (typeof options.data === 'string') {\n        const namespace =\n          options && options.headers && options.headers['X-Craft-Namespace'];\n        const actionName = this.namespaceInputName('action', namespace);\n        options.data += `&${actionName}=${action}`;\n      } else {\n        delete options.data.action;\n      }\n    }\n\n    return new Promise((resolve, reject) => {\n      options = options ? $.extend({}, options) : {};\n      options.method = method;\n      options.url = action ? Craft.getActionUrl(action) : Craft.getCpUrl();\n      options.headers = $.extend(\n        {\n          'X-Requested-With': 'XMLHttpRequest',\n        },\n        options.headers || {},\n        this._actionHeaders()\n      );\n      options.params = $.extend({}, options.params || {}, {\n        // Force Safari to not load from cache\n        v: new Date().getTime(),\n      });\n      axios.request(options).then(resolve).catch(reject);\n    });\n  },\n\n  /**\n   * Sends a request to the Craftnet API.\n   * @param {string} method The request action to use ('GET' or 'POST')\n   * @param {string} uri The API endpoint URI\n   * @param {Object} options Axios request options\n   * @returns {Promise}\n   * @since 3.3.16\n   */\n  sendApiRequest: function (method, uri, options) {\n    return new Promise((resolve, reject) => {\n      options = options ? $.extend({}, options) : {};\n      let cancelToken = options.cancelToken || null;\n\n      // Get the latest headers\n      this._getApiHeaders(cancelToken)\n        .then((apiHeaders) => {\n          // Send the API request\n          options.method = method;\n          options.baseURL = Craft.baseApiUrl;\n          options.url = uri;\n          options.headers = $.extend(apiHeaders, options.headers || {});\n          options.params = $.extend(\n            Craft.apiParams || {},\n            options.params || {},\n            {\n              // Force Safari to not load from cache\n              v: new Date().getTime(),\n            }\n          );\n\n          // Force the API to process the Craft headers if this is the first API request\n          if (!this._apiHeaders) {\n            options.params.processCraftHeaders = 1;\n          }\n\n          if (Craft.httpProxy) {\n            options.proxy = Craft.httpProxy;\n          }\n\n          axios\n            .request(options)\n            .then((apiResponse) => {\n              // Process the response headers\n              this._processApiHeaders(apiResponse.headers, cancelToken)\n                .then(() => {\n                  // Finally return the API response data\n                  resolve(apiResponse.data);\n                })\n                .catch(reject);\n            })\n            .catch(reject);\n        })\n        .catch(reject);\n    });\n  },\n\n  _loadingApiHeaders: false,\n  _apiHeaders: null,\n  _apiHeaderWaitlist: [],\n\n  /**\n   * Returns the headers that should be sent with API requests.\n   *\n   * @param {Object} [cancelToken]\n   * @returns {Promise}\n   */\n  _getApiHeaders: function (cancelToken) {\n    return new Promise((resolve, reject) => {\n      // Are we already loading them?\n      if (this._loadingApiHeaders) {\n        this._apiHeaderWaitlist.push([resolve, reject]);\n        return;\n      }\n\n      // Are the headers already cached?\n      if (this._apiHeaders) {\n        resolve(this._apiHeaders);\n        return;\n      }\n\n      this._loadingApiHeaders = true;\n      this.sendActionRequest('POST', 'app/api-headers', {\n        cancelToken: cancelToken,\n      })\n        .then((response) => {\n          // Make sure we even are waiting for these anymore\n          if (!this._loadingApiHeaders) {\n            reject(e);\n            return;\n          }\n\n          resolve(response.data);\n        })\n        .catch((e) => {\n          this._rejectApiRequests(reject, e);\n        });\n    });\n  },\n\n  _processApiHeaders: function (headers, cancelToken) {\n    return new Promise((resolve, reject) => {\n      // Have we already processed them?\n      if (this._apiHeaders) {\n        resolve();\n        return;\n      }\n\n      this.sendActionRequest('POST', 'app/process-api-response-headers', {\n        data: {\n          headers: headers,\n        },\n        cancelToken: cancelToken,\n      })\n        .then((response) => {\n          // Make sure we even are waiting for these anymore\n          if (!this._loadingApiHeaders) {\n            reject(e);\n            return;\n          }\n\n          this._apiHeaders = response.data;\n          this._loadingApiHeaders = false;\n\n          resolve();\n\n          // Was anything else waiting for them?\n          while (this._apiHeaderWaitlist.length) {\n            this._apiHeaderWaitlist.shift()[0](this._apiHeaders);\n          }\n        })\n        .catch((e) => {\n          this._rejectApiRequests(reject, e);\n        });\n    });\n  },\n\n  _rejectApiRequests: function (reject, e) {\n    this._loadingApiHeaders = false;\n    reject(e);\n    while (this._apiHeaderWaitlist.length) {\n      this._apiHeaderWaitlist.shift()[1](e);\n    }\n  },\n\n  /**\n   * Clears the cached API headers.\n   */\n  clearCachedApiHeaders: function () {\n    this._apiHeaders = null;\n    this._loadingApiHeaders = false;\n\n    // Reject anything in the header waitlist\n    while (this._apiHeaderWaitlist.length) {\n      this._apiHeaderWaitlist.shift()[1]();\n    }\n  },\n\n  /**\n   * Requests a URL and downloads the response.\n   *\n   * @param {string} method the request method to use\n   * @param {string} url the URL\n   * @param {(string|Object)} [body] the request body, if method = POST\n   * @returns {Promise}\n   */\n  downloadFromUrl: function (method, url, body) {\n    return new Promise((resolve, reject) => {\n      // h/t https://nehalist.io/downloading-files-from-post-requests/\n      let request = new XMLHttpRequest();\n      request.open(method, url, true);\n      if (typeof body === 'object') {\n        request.setRequestHeader(\n          'Content-Type',\n          'application/json; charset=UTF-8'\n        );\n        body = JSON.stringify(body);\n      } else {\n        request.setRequestHeader(\n          'Content-Type',\n          'application/x-www-form-urlencoded; charset=UTF-8'\n        );\n      }\n      request.responseType = 'blob';\n\n      request.onload = () => {\n        // Only handle status code 200\n        if (request.status === 200) {\n          // Try to find out the filename from the content disposition `filename` value\n          let disposition = request.getResponseHeader('content-disposition');\n          let matches = /\"([^\"]*)\"/.exec(disposition);\n          let filename =\n            matches != null && matches[1] ? matches[1] : 'Download';\n\n          // Encode the download into an anchor href\n          let contentType = request.getResponseHeader('content-type');\n          let blob = new Blob([request.response], {type: contentType});\n          let link = document.createElement('a');\n          link.href = window.URL.createObjectURL(blob);\n          link.download = filename;\n          document.body.appendChild(link);\n          link.click();\n          document.body.removeChild(link);\n\n          resolve();\n        } else {\n          reject();\n        }\n      };\n\n      request.send(body);\n    });\n  },\n\n  /**\n   * Converts a comma-delimited string into an array.\n   *\n   * @param {string} str\n   * @returns array\n   */\n  stringToArray: function (str) {\n    if (typeof str !== 'string') {\n      return str;\n    }\n\n    var arr = str.split(',');\n    for (var i = 0; i < arr.length; i++) {\n      arr[i] = $.trim(arr[i]);\n    }\n    return arr;\n  },\n\n  /**\n   * @callback findDeltaDataCallback\n   * @param {string} deltaName\n   * @param {Array} params\n   */\n  /**\n   * Compares old and new post data, and removes any values that haven't\n   * changed within the given list of delta namespaces.\n   *\n   * @param {string} oldData\n   * @param {string} newData\n   * @param {Object} deltaNames\n   * @param {findDeltaDataCallback} [callback] Callback function that should be called whenever a new group of modified params has been found\n   * @param {Object} [initialDeltaValues] Initial delta values. If undefined, `Craft.initialDeltaValues` will be used.\n   * @param {Object} [modifiedDeltaNames} List of delta names that should be considered modified regardles of their param values\n   * @returns {string}\n   */\n  findDeltaData: function (\n    oldData,\n    newData,\n    deltaNames,\n    callback,\n    initialDeltaValues,\n    modifiedDeltaNames\n  ) {\n    // Make sure oldData and newData are always strings. This is important because further below String.split is called.\n    oldData = typeof oldData === 'string' ? oldData : '';\n    newData = typeof newData === 'string' ? newData : '';\n    deltaNames = $.isArray(deltaNames) ? deltaNames : [];\n    initialDeltaValues = $.isPlainObject(initialDeltaValues)\n      ? initialDeltaValues\n      : {};\n    modifiedDeltaNames = $.isArray(modifiedDeltaNames)\n      ? modifiedDeltaNames\n      : [];\n\n    // Sort the delta namespaces from least -> most specific\n    deltaNames.sort(function (a, b) {\n      if (a.length === b.length) {\n        return 0;\n      }\n      return a.length > b.length ? 1 : -1;\n    });\n\n    // Group all of the old & new params by namespace\n    var groupedOldParams = this._groupParamsByDeltaNames(\n      oldData.split('&'),\n      deltaNames,\n      false,\n      initialDeltaValues\n    );\n    var groupedNewParams = this._groupParamsByDeltaNames(\n      newData.split('&'),\n      deltaNames,\n      true,\n      false\n    );\n\n    // Figure out which of the new params should actually be posted\n    var params = groupedNewParams.__root__;\n    for (var n = 0; n < deltaNames.length; n++) {\n      if (\n        Craft.inArray(deltaNames[n], modifiedDeltaNames) ||\n        (typeof groupedNewParams[deltaNames[n]] === 'object' &&\n          (typeof groupedOldParams[deltaNames[n]] !== 'object' ||\n            JSON.stringify(groupedOldParams[deltaNames[n]]) !==\n              JSON.stringify(groupedNewParams[deltaNames[n]])))\n      ) {\n        params = params.concat(groupedNewParams[deltaNames[n]]);\n        params.push('modifiedDeltaNames[]=' + deltaNames[n]);\n        if (callback) {\n          callback(deltaNames[n], groupedNewParams[deltaNames[n]]);\n        }\n      }\n    }\n\n    return params.join('&');\n  },\n\n  /**\n   * @param {Object} params\n   * @param {Object} deltaNames\n   * @param {boolean} withRoot\n   * @param {(boolean|Object)} initialValues\n   * @returns {Object}\n   * @private\n   */\n  _groupParamsByDeltaNames: function (\n    params,\n    deltaNames,\n    withRoot,\n    initialValues\n  ) {\n    const grouped = {};\n\n    if (withRoot) {\n      grouped.__root__ = [];\n    }\n\n    const encodeURIComponentExceptEqualChar = (o) =>\n      encodeURIComponent(o).replace('%3D', '=');\n\n    params = params.map((p) => decodeURIComponent(p));\n\n    paramLoop: for (let p = 0; p < params.length; p++) {\n      // loop through the delta names from most -> least specific\n      for (let n = deltaNames.length - 1; n >= 0; n--) {\n        const paramName = params[p].substring(0, deltaNames[n].length + 1);\n        if (\n          paramName === deltaNames[n] + '=' ||\n          paramName === deltaNames[n] + '['\n        ) {\n          if (typeof grouped[deltaNames[n]] === 'undefined') {\n            grouped[deltaNames[n]] = [];\n          }\n          grouped[deltaNames[n]].push(\n            encodeURIComponentExceptEqualChar(params[p])\n          );\n          continue paramLoop;\n        }\n      }\n\n      if (withRoot) {\n        grouped.__root__.push(encodeURIComponentExceptEqualChar(params[p]));\n      }\n    }\n\n    if (initialValues) {\n      const serializeParam = (name, value) => {\n        if ($.isArray(value) || $.isPlainObject(value)) {\n          value = $.param(value);\n        } else if (typeof value === 'string') {\n          value = encodeURIComponent(value);\n        } else if (value === null) {\n          value = '';\n        }\n        return `${encodeURIComponent(name)}=${value}`;\n      };\n\n      for (let name in initialValues) {\n        if (initialValues.hasOwnProperty(name)) {\n          if ($.isPlainObject(initialValues[name])) {\n            grouped[name] = [];\n            for (let subName in initialValues[name]) {\n              if (initialValues[name].hasOwnProperty(subName)) {\n                grouped[name].push(\n                  serializeParam(\n                    `${name}[${subName}]`,\n                    initialValues[name][subName]\n                  )\n                );\n              }\n            }\n          } else {\n            grouped[name] = [serializeParam(name, initialValues[name])];\n          }\n        }\n      }\n    }\n\n    return grouped;\n  },\n\n  /**\n   * Expands an object of POST array-style strings into an actual array.\n   *\n   * @param {Object} arr\n   * @returns {Array}\n   */\n  expandPostArray: function (arr) {\n    var expanded = {};\n    var i;\n\n    for (var key in arr) {\n      if (!arr.hasOwnProperty(key)) {\n        continue;\n      }\n\n      var value = arr[key],\n        m = key.match(/^(\\w+)(\\[.*)?/),\n        keys;\n\n      if (m[2]) {\n        // Get all of the nested keys\n        keys = m[2].match(/\\[[^\\[\\]]*\\]/g);\n\n        // Chop off the brackets\n        for (i = 0; i < keys.length; i++) {\n          keys[i] = keys[i].substring(1, keys[i].length - 1);\n        }\n      } else {\n        keys = [];\n      }\n\n      keys.unshift(m[1]);\n\n      var parentElem = expanded;\n\n      for (i = 0; i < keys.length; i++) {\n        if (i < keys.length - 1) {\n          if (typeof parentElem[keys[i]] !== 'object') {\n            // Figure out what this will be by looking at the next key\n            if (!keys[i + 1] || parseInt(keys[i + 1]) == keys[i + 1]) {\n              parentElem[keys[i]] = [];\n            } else {\n              parentElem[keys[i]] = {};\n            }\n          }\n\n          parentElem = parentElem[keys[i]];\n        } else {\n          // Last one. Set the value\n          if (!keys[i]) {\n            keys[i] = parentElem.length;\n          }\n\n          parentElem[keys[i]] = value;\n        }\n      }\n    }\n\n    return expanded;\n  },\n\n  /**\n   * Creates a form element populated with hidden inputs based on a string of serialized form data.\n   *\n   * @param {string} data\n   * @returns {(jQuery|HTMLElement)}\n   */\n  createForm: function (data) {\n    var $form = $('<form/>', {\n      attr: {\n        method: 'post',\n        action: '',\n        'accept-charset': 'UTF-8',\n      },\n    });\n\n    if (typeof data === 'string') {\n      var values = data.split('&');\n      var chunks;\n      for (var i = 0; i < values.length; i++) {\n        chunks = values[i].split('=', 2);\n        $('<input/>', {\n          type: 'hidden',\n          name: decodeURIComponent(chunks[0]),\n          value: decodeURIComponent(chunks[1] || ''),\n        }).appendTo($form);\n      }\n    }\n\n    return $form;\n  },\n\n  /**\n   * Compares two variables and returns whether they are equal in value.\n   * Recursively compares array and object values.\n   *\n   * @param {*} obj1\n   * @param {*} obj2\n   * @param {boolean} [sortObjectKeys] Whether object keys should be sorted before being compared. Default is true.\n   * @returns boolean\n   */\n  compare: function (obj1, obj2, sortObjectKeys) {\n    // Compare the types\n    if (typeof obj1 !== typeof obj2) {\n      return false;\n    }\n\n    if (typeof obj1 === 'object' && obj1 !== null && obj2 !== null) {\n      // Compare the lengths\n      if (obj1.length !== obj2.length) {\n        return false;\n      }\n\n      // Is one of them an array but the other is not?\n      if (obj1 instanceof Array !== obj2 instanceof Array) {\n        return false;\n      }\n\n      // If they're actual objects (not arrays), compare the keys\n      if (!(obj1 instanceof Array)) {\n        if (typeof sortObjectKeys === 'undefined' || sortObjectKeys === true) {\n          if (\n            !Craft.compare(\n              Craft.getObjectKeys(obj1).sort(),\n              Craft.getObjectKeys(obj2).sort()\n            )\n          ) {\n            return false;\n          }\n        } else {\n          if (\n            !Craft.compare(Craft.getObjectKeys(obj1), Craft.getObjectKeys(obj2))\n          ) {\n            return false;\n          }\n        }\n      }\n\n      // Compare each value\n      for (var i in obj1) {\n        if (!obj1.hasOwnProperty(i)) {\n          continue;\n        }\n\n        if (!Craft.compare(obj1[i], obj2[i])) {\n          return false;\n        }\n      }\n\n      // All clear\n      return true;\n    } else {\n      return obj1 === obj2;\n    }\n  },\n\n  /**\n   * Returns an array of an object's keys.\n   *\n   * @param {Object} obj\n   * @returns {string[]}\n   */\n  getObjectKeys: function (obj) {\n    var keys = [];\n\n    for (var key in obj) {\n      if (!obj.hasOwnProperty(key)) {\n        continue;\n      }\n\n      keys.push(key);\n    }\n\n    return keys;\n  },\n\n  /**\n   * Takes an array or string of chars, and places a backslash before each one, returning the combined string.\n   *\n   * Userd by ltrim() and rtrim()\n   *\n   * @param {(string|Object)} chars\n   * @returns {string}\n   */\n  escapeChars: function (chars) {\n    if (!Garnish.isArray(chars)) {\n      chars = chars.split();\n    }\n\n    var escaped = '';\n\n    for (var i = 0; i < chars.length; i++) {\n      escaped += '\\\\' + chars[i];\n    }\n\n    return escaped;\n  },\n\n  /**\n   * Trim characters off of the beginning of a string.\n   *\n   * @param {string} str\n   * @param {(string|Object)} [chars] The characters to trim off. Defaults to a space if left blank.\n   * @returns {string}\n   */\n  ltrim: function (str, chars) {\n    if (!str) {\n      return str;\n    }\n    if (typeof chars === 'undefined') {\n      chars = ' \\t\\n\\r\\0\\x0B';\n    }\n    var re = new RegExp('^[' + Craft.escapeChars(chars) + ']+');\n    return str.replace(re, '');\n  },\n\n  /**\n   * Trim characters off of the end of a string.\n   *\n   * @param {string} str\n   * @param {(string|Object)} [chars] The characters to trim off. Defaults to a space if left blank.\n   * @returns {string}\n   */\n  rtrim: function (str, chars) {\n    if (!str) {\n      return str;\n    }\n    if (typeof chars === 'undefined') {\n      chars = ' \\t\\n\\r\\0\\x0B';\n    }\n    var re = new RegExp('[' + Craft.escapeChars(chars) + ']+$');\n    return str.replace(re, '');\n  },\n\n  /**\n   * Trim characters off of the beginning and end of a string.\n   *\n   * @param {string} str\n   * @param {(string|Object)} [chars] The characters to trim off. Defaults to a space if left blank.\n   * @returns {string}\n   */\n  trim: function (str, chars) {\n    str = Craft.ltrim(str, chars);\n    str = Craft.rtrim(str, chars);\n    return str;\n  },\n\n  /**\n   * Returns whether a string starts with another string.\n   *\n   * @param {string} str\n   * @param {string} substr\n   * @returns {boolean}\n   */\n  startsWith: function (str, substr) {\n    return str.substring(0, substr.length) === substr;\n  },\n\n  /**\n   * @callback filterArrayCallback\n   * @param {*} value\n   * @param {number} index\n   * @return {boolean}\n   */\n  /**\n   * Filters an array.\n   *\n   * @param {Object} arr\n   * @param {filterArrayCallback} [callback] A user-defined callback function. If null, we'll just remove any elements that equate to false.\n   * @returns {Array}\n   */\n  filterArray: function (arr, callback) {\n    var filtered = [];\n\n    for (var i = 0; i < arr.length; i++) {\n      var include;\n\n      if (typeof callback === 'function') {\n        include = callback(arr[i], i);\n      } else {\n        include = arr[i];\n      }\n\n      if (include) {\n        filtered.push(arr[i]);\n      }\n    }\n\n    return filtered;\n  },\n\n  /**\n   * Returns whether an element is in an array (unlike jQuery.inArray(), which returns the element’s index, or -1).\n   *\n   * @param {*} elem\n   * @param {(Object|Array)} arr\n   * @returns {boolean}\n   */\n  inArray: function (elem, arr) {\n    if ($.isPlainObject(arr)) {\n      arr = Object.values(arr);\n    }\n    return arr.includes(elem);\n  },\n\n  /**\n   * Removes an element from an array.\n   *\n   * @param {*} elem\n   * @param {Array} arr\n   * @returns {boolean} Whether the element could be found or not.\n   */\n  removeFromArray: function (elem, arr) {\n    var index = $.inArray(elem, arr);\n    if (index !== -1) {\n      arr.splice(index, 1);\n      return true;\n    } else {\n      return false;\n    }\n  },\n\n  /**\n   * Returns the last element in an array.\n   *\n   * @param {Array} arr\n   * @returns {*}\n   */\n  getLast: function (arr) {\n    if (!arr.length) {\n      return null;\n    } else {\n      return arr[arr.length - 1];\n    }\n  },\n\n  /**\n   * Makes the first character of a string uppercase.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  uppercaseFirst: function (str) {\n    return str.charAt(0).toUpperCase() + str.slice(1);\n  },\n\n  /**\n   * Makes the first character of a string lowercase.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  lowercaseFirst: function (str) {\n    return str.charAt(0).toLowerCase() + str.slice(1);\n  },\n\n  parseUrl: function (url) {\n    var m = url.match(\n      /^(?:(https?):\\/\\/|\\/\\/)([^\\/\\:]*)(?:\\:(\\d+))?(\\/[^\\?]*)?(?:\\?([^#]*))?(#.*)?/\n    );\n    if (!m) {\n      return {};\n    }\n    return {\n      scheme: m[1],\n      host: m[2] + (m[3] ? ':' + m[3] : ''),\n      hostname: m[2],\n      port: m[3] || null,\n      path: m[4] || '/',\n      query: m[5] || null,\n      hash: m[6] || null,\n    };\n  },\n\n  getQueryParams: function () {\n    return Object.fromEntries(\n      new URLSearchParams(window.location.search).entries()\n    );\n  },\n\n  getQueryParam: function (name) {\n    // h/t https://stackoverflow.com/a/901144/1688568\n    const params = new Proxy(new URLSearchParams(window.location.search), {\n      get: (searchParams, prop) => searchParams.get(prop),\n    });\n    return params[name];\n  },\n\n  isSameHost: function (url) {\n    var requestUrlInfo = this.parseUrl(document.location.href);\n    if (!requestUrlInfo) {\n      return false;\n    }\n    var urlInfo = this.parseUrl(url);\n    if (!urlInfo) {\n      return false;\n    }\n    return requestUrlInfo.host === urlInfo.host;\n  },\n\n  /**\n   * Converts a number of seconds into a human-facing time duration.\n   */\n  secondsToHumanTimeDuration: function (seconds, showSeconds) {\n    if (typeof showSeconds === 'undefined') {\n      showSeconds = true;\n    }\n\n    var secondsInWeek = 604800,\n      secondsInDay = 86400,\n      secondsInHour = 3600,\n      secondsInMinute = 60;\n\n    var weeks = Math.floor(seconds / secondsInWeek);\n    seconds = seconds % secondsInWeek;\n\n    var days = Math.floor(seconds / secondsInDay);\n    seconds = seconds % secondsInDay;\n\n    var hours = Math.floor(seconds / secondsInHour);\n    seconds = seconds % secondsInHour;\n\n    var minutes;\n\n    if (showSeconds) {\n      minutes = Math.floor(seconds / secondsInMinute);\n      seconds = seconds % secondsInMinute;\n    } else {\n      minutes = Math.round(seconds / secondsInMinute);\n      seconds = 0;\n    }\n\n    var timeComponents = [];\n\n    if (weeks) {\n      timeComponents.push(\n        weeks +\n          ' ' +\n          (weeks === 1 ? Craft.t('app', 'week') : Craft.t('app', 'weeks'))\n      );\n    }\n\n    if (days) {\n      timeComponents.push(\n        days +\n          ' ' +\n          (days === 1 ? Craft.t('app', 'day') : Craft.t('app', 'days'))\n      );\n    }\n\n    if (hours) {\n      timeComponents.push(\n        hours +\n          ' ' +\n          (hours === 1 ? Craft.t('app', 'hour') : Craft.t('app', 'hours'))\n      );\n    }\n\n    if (minutes || (!showSeconds && !weeks && !days && !hours)) {\n      timeComponents.push(\n        minutes +\n          ' ' +\n          (minutes === 1 ? Craft.t('app', 'minute') : Craft.t('app', 'minutes'))\n      );\n    }\n\n    if (seconds || (showSeconds && !weeks && !days && !hours && !minutes)) {\n      timeComponents.push(\n        seconds +\n          ' ' +\n          (seconds === 1 ? Craft.t('app', 'second') : Craft.t('app', 'seconds'))\n      );\n    }\n\n    return timeComponents.join(', ');\n  },\n\n  /**\n   * Converts extended ASCII characters to ASCII.\n   *\n   * @param {string} str\n   * @param {Object} [charMap]\n   * @returns {string}\n   */\n  asciiString: function (str, charMap) {\n    // Normalize NFD chars to NFC\n    str = str.normalize('NFC');\n\n    var asciiStr = '';\n    var char;\n\n    for (var i = 0; i < str.length; i++) {\n      char = str.charAt(i);\n      asciiStr +=\n        typeof (charMap || Craft.asciiCharMap)[char] === 'string'\n          ? (charMap || Craft.asciiCharMap)[char]\n          : char;\n    }\n\n    return asciiStr;\n  },\n\n  uuid: function () {\n    if (typeof crypto.randomUUID === 'function') {\n      return crypto.randomUUID();\n    }\n\n    // h/t https://stackoverflow.com/a/2117523/1688568\n    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>\n      (\n        c ^\n        (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))\n      ).toString(16)\n    );\n  },\n\n  /**\n   * @param {string} name\n   * @param {string} [namespace]\n   * @returns {string}\n   */\n  namespaceInputName: function (name, namespace) {\n    if (!namespace) {\n      return name;\n    }\n\n    return name.replace(/([^'\"\\[\\]]+)([^'\"]*)/, `${namespace}[$1]$2`);\n  },\n\n  /**\n   * @param {string} id\n   * @param {string} [namespace]\n   * @returns {string}\n   */\n  namespaceId: function (id, namespace) {\n    return Craft.formatInputId(namespace ? `${namespace}-${id}` : id);\n  },\n\n  randomString: function (length) {\n    // h/t https://stackoverflow.com/a/1349426/1688568\n    var result = '';\n    var characters =\n      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n    for (var i = 0; i < length; i++) {\n      result += characters.charAt(Math.floor(Math.random() * 62));\n    }\n    return result;\n  },\n\n  /**\n   * Creates a validation error list.\n   *\n   * @param {Object} errors\n   * @returns {jQuery}\n   */\n  createErrorList: function (errors) {\n    var $ul = $(document.createElement('ul')).addClass('errors');\n\n    for (var i = 0; i < errors.length; i++) {\n      var $li = $(document.createElement('li'));\n      $li.appendTo($ul);\n      $li.html(errors[i]);\n    }\n\n    return $ul;\n  },\n\n  /**\n   * Appends HTML to the page `<head>`.\n   *\n   * @param {string} html\n   */\n  appendHeadHtml: function (html) {\n    if (!html) {\n      return;\n    }\n\n    // Prune out any link tags that are already included\n    var $existingCss = $('link[href]');\n\n    if ($existingCss.length) {\n      var existingCss = [];\n      var href;\n\n      for (var i = 0; i < $existingCss.length; i++) {\n        href = $existingCss.eq(i).attr('href').replace(/&/g, '&amp;');\n        existingCss.push(Craft.escapeRegex(href));\n      }\n\n      const regexp = new RegExp(\n        '<link\\\\s[^>]*href=\"(?:' + existingCss.join('|') + ')\".*?></link>',\n        'g'\n      );\n\n      html = html.replace(regexp, '');\n    }\n\n    $('head').append(html);\n  },\n\n  /**\n   * Appends HTML to the page `<body>`.\n   *\n   * @param {string} html\n   */\n  appendBodyHtml: function (html) {\n    if (!html) {\n      return;\n    }\n\n    // Prune out any script tags that are already included\n    var $existingJs = $('script[src]');\n\n    if ($existingJs.length) {\n      var existingJs = [];\n      var src;\n\n      for (var i = 0; i < $existingJs.length; i++) {\n        src = $existingJs.eq(i).attr('src').replace(/&/g, '&amp;');\n        existingJs.push(Craft.escapeRegex(src));\n      }\n\n      var regexp = new RegExp(\n        '<script\\\\s[^>]*src=\"(?:' + existingJs.join('|') + ')\".*?></script>',\n        'g'\n      );\n\n      html = html.replace(regexp, '');\n    }\n\n    Garnish.$bod.append(html);\n  },\n\n  /**\n   * Appends HTML to the page `<body>`.\n   *\n   * @deprecated in 4.0.0. `appendBodyHtml()` should be used instead\n   */\n  appendFootHtml: function (html) {\n    console.warn(\n      'Craft.appendFootHtml() is deprecated. Craft.appendBodyHtml() should be used instead.'\n    );\n    this.appendBodyHtml(html);\n  },\n\n  /**\n   * Initializes any common UI elements in a given container.\n   *\n   * @param {Object} $container\n   */\n  initUiElements: function ($container) {\n    $('.grid', $container).grid();\n    $('.info', $container).infoicon();\n    $('.checkbox-select', $container).checkboxselect();\n    $('.fieldtoggle', $container).fieldtoggle();\n    $('.lightswitch', $container).lightswitch();\n    $('.nicetext', $container).nicetext();\n    $('.formsubmit', $container).formsubmit();\n    $('.menubtn:not([data-disclosure-trigger])', $container).menubtn();\n    $('[data-disclosure-trigger]', $container).disclosureMenu();\n    $('.datetimewrapper', $container).datetime();\n    $(\n      '.datewrapper > input[type=\"date\"], .timewrapper > input[type=\"time\"]',\n      $container\n    ).datetimeinput();\n\n    // Open outbound links in new windows\n    // hat tip: https://stackoverflow.com/a/2911045/1688568\n    $('a', $container).each(function () {\n      if (\n        this.hostname.length &&\n        this.hostname !== location.hostname &&\n        typeof $(this).attr('target') === 'undefined'\n      ) {\n        $(this).attr('rel', 'noopener').attr('target', '_blank');\n      }\n    });\n  },\n\n  _elementIndexClasses: {},\n  _elementSelectorModalClasses: {},\n  _elementEditorClasses: {},\n\n  /**\n   * Registers an element index class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementIndexClass: function (elementType, func) {\n    if (typeof this._elementIndexClasses[elementType] !== 'undefined') {\n      throw (\n        'An element index class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementIndexClasses[elementType] = func;\n  },\n\n  /**\n   * Registers an element selector modal class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementSelectorModalClass: function (elementType, func) {\n    if (typeof this._elementSelectorModalClasses[elementType] !== 'undefined') {\n      throw (\n        'An element selector modal class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementSelectorModalClasses[elementType] = func;\n  },\n\n  /**\n   * Registers an element editor class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementEditorClass: function (elementType, func) {\n    if (typeof this._elementEditorClasses[elementType] !== 'undefined') {\n      throw (\n        'An element editor class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementEditorClasses[elementType] = func;\n  },\n\n  /**\n   * Creates a new element index for a given element type.\n   *\n   * @param {string} elementType\n   * @param {jQuery} $container\n   * @param {Object} settings\n   * @returns {BaseElementIndex}\n   */\n  createElementIndex: function (elementType, $container, settings) {\n    var func;\n\n    if (typeof this._elementIndexClasses[elementType] !== 'undefined') {\n      func = this._elementIndexClasses[elementType];\n    } else {\n      func = Craft.BaseElementIndex;\n    }\n\n    return new func(elementType, $container, settings);\n  },\n\n  /**\n   * Creates a new element selector modal for a given element type.\n   *\n   * @param {string} elementType\n   * @param {Object} settings\n   */\n  createElementSelectorModal: function (elementType, settings) {\n    var func;\n\n    if (typeof this._elementSelectorModalClasses[elementType] !== 'undefined') {\n      func = this._elementSelectorModalClasses[elementType];\n    } else {\n      func = Craft.BaseElementSelectorModal;\n    }\n\n    return new func(elementType, settings);\n  },\n\n  /**\n   * Creates a new element editor slideout for a given element type.\n   *\n   * @param {string} elementType\n   * @param {(jQuery|HTMLElement|string)} element\n   * @param {Object} settings\n   */\n  createElementEditor: function (elementType, element, settings) {\n    // Param mapping\n    if (typeof settings === 'undefined' && $.isPlainObject(element)) {\n      // (settings)\n      settings = element;\n      element = null;\n    } else if (typeof settings !== 'object') {\n      settings = {};\n    }\n\n    if (!settings.elementType) {\n      settings.elementType = elementType;\n    }\n\n    return new Craft.ElementEditorSlideout(element, settings);\n  },\n\n  /**\n   * Retrieves a value from localStorage if it exists.\n   *\n   * @param {string} key\n   * @param {*} defaultValue\n   */\n  getLocalStorage: function (key, defaultValue) {\n    key = 'Craft-' + Craft.systemUid + '.' + key;\n\n    if (\n      typeof localStorage !== 'undefined' &&\n      typeof localStorage[key] !== 'undefined'\n    ) {\n      return JSON.parse(localStorage[key]);\n    } else {\n      return defaultValue;\n    }\n  },\n\n  /**\n   * Saves a value to localStorage.\n   *\n   * @param {string} key\n   * @param {*} value\n   */\n  setLocalStorage: function (key, value) {\n    if (typeof localStorage !== 'undefined') {\n      key = 'Craft-' + Craft.systemUid + '.' + key;\n\n      // localStorage might be filled all the way up.\n      // Especially likely if this is a private window in Safari 8+, where localStorage technically exists,\n      // but has a max size of 0 bytes.\n      try {\n        localStorage[key] = JSON.stringify(value);\n      } catch (e) {}\n    }\n  },\n\n  /**\n   * Removes a value from localStorage.\n   * @param {string} key\n   */\n  removeLocalStorage: function (key) {\n    if (typeof localStorage !== 'undefined') {\n      localStorage.removeItem(`Craft-${Craft.systemUid}.${key}`);\n    }\n  },\n\n  /**\n   * Returns a cookie value, if it exists, otherwise returns `false`\n   * @returns {(string|boolean)}\n   */\n  getCookie: function (name) {\n    // Adapted from https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie\n    return document.cookie.replace(\n      new RegExp(\n        `(?:(?:^|.*;\\\\s*)Craft-${Craft.systemUid}:${name}\\\\s*\\\\=\\\\s*([^;]*).*$)|^.*$`\n      ),\n      '$1'\n    );\n  },\n\n  /**\n   * Sets a cookie value.\n   * @param {string} name\n   * @param {string} value\n   * @param {Object} [options]\n   * @param {string} [options.path] The cookie path.\n   * @param {string} [options.domain] The cookie domain. Defaults to the `defaultCookieDomain` config setting.\n   * @param {number} [options.maxAge] The max age of the cookie (in seconds)\n   * @param {Date} [options.expires] The expiry date of the cookie. Defaults to none (session-based cookie).\n   * @param {boolean} [options.secure] Whether this is a secure cookie. Defaults to the `useSecureCookies`\n   * config setting.\n   * @param {string} [options.sameSite] The SameSite value (`lax` or `strict`). Defaults to the\n   * `sameSiteCookieValue` config setting.\n   */\n  setCookie: function (name, value, options) {\n    options = $.extend({}, this.defaultCookieOptions, options);\n    let cookie = `Craft-${Craft.systemUid}:${name}=${encodeURIComponent(\n      value\n    )}`;\n    if (options.path) {\n      cookie += `;path=${options.path}`;\n    }\n    if (options.domain) {\n      cookie += `;domain=${options.domain}`;\n    }\n    if (options.maxAge) {\n      cookie += `;max-age-in-seconds=${options.maxAge}`;\n    } else if (options.expires) {\n      cookie += `;expires=${options.expires.toUTCString()}`;\n    }\n    if (options.secure) {\n      cookie += ';secure';\n    }\n    document.cookie = cookie;\n  },\n\n  /**\n   * Removes a cookie\n   * @param {string} name\n   */\n  removeCookie: function (name) {\n    this.setCookie(name, '', new Date('1970-01-01T00:00:00'));\n  },\n\n  /**\n   * Returns element information from its DOM element.\n   *\n   * @param {(jQuery|HTMLElement|string)} element\n   * @returns {Object}\n   */\n  getElementInfo: function (element) {\n    var $element = $(element);\n\n    if (!$element.hasClass('element')) {\n      $element = $element.find('.element:first');\n    }\n\n    return {\n      id: $element.data('id'),\n      siteId: $element.data('site-id'),\n      label: $element.data('label'),\n      status: $element.data('status'),\n      url: $element.data('url'),\n      hasThumb: $element.hasClass('hasthumb'),\n      $element: $element,\n    };\n  },\n\n  /**\n   * Changes an element to the requested size.\n   *\n   * @param {(jQuery|HTMLElement|string))} element\n   * @param {string} size\n   */\n  setElementSize: function (element, size) {\n    var $element = $(element);\n\n    if (size !== 'small' && size !== 'large') {\n      size = 'small';\n    }\n\n    if ($element.hasClass(size)) {\n      return;\n    }\n\n    var otherSize = size === 'small' ? 'large' : 'small';\n\n    $element.addClass(size).removeClass(otherSize);\n\n    if ($element.hasClass('hasthumb')) {\n      var $oldImg = $element.find('> .elementthumb > img'),\n        imgSize = size === 'small' ? '30' : '100',\n        $newImg = $('<img/>', {\n          sizes: imgSize + 'px',\n          srcset: $oldImg.attr('srcset') || $oldImg.attr('data-pfsrcset'),\n        });\n\n      $oldImg.replaceWith($newImg);\n\n      picturefill({\n        elements: [$newImg[0]],\n      });\n    }\n  },\n\n  /**\n   * Submits a form.\n   * @param {Object} $form\n   * @param {Object} [options]\n   * @param {string} [options.action] The `action` param value override\n   * @param {string} [options.redirect] The `redirect` param value override\n   * @param {string} [options.confirm] A confirmation message that should be shown to the user before submit\n   * @param {Object} [options.params] Additional params that should be added to the form, defined as name/value pairs\n   * @param {Object} [options.data] Additional data to be passed to the submit event\n   * @param {boolean} [options.retainScroll] Whether the scroll position should be stored and reapplied on the next page load\n   */\n  submitForm: function ($form, options) {\n    if (typeof options === 'undefined') {\n      options = {};\n    }\n\n    if (options.confirm && !confirm(options.confirm)) {\n      return;\n    }\n\n    if (options.action) {\n      $('<input/>', {\n        type: 'hidden',\n        name: 'action',\n        val: options.action,\n      }).appendTo($form);\n    }\n\n    if (options.redirect) {\n      $('<input/>', {\n        type: 'hidden',\n        name: 'redirect',\n        val: options.redirect,\n      }).appendTo($form);\n    }\n\n    if (options.params) {\n      for (let name in options.params) {\n        let value = options.params[name];\n        $('<input/>', {\n          type: 'hidden',\n          name: name,\n          val: value,\n        }).appendTo($form);\n      }\n    }\n\n    if (options.retainScroll) {\n      this.setLocalStorage('scrollY', window.scrollY);\n    }\n\n    $form.trigger($.extend({type: 'submit'}, options.data));\n  },\n\n  /**\n   * Traps focus within a container, so when focus is tabbed out of it, it’s cycled back into it.\n   * @param {Object} container\n   */\n  trapFocusWithin: function (container) {\n    Garnish.trapFocusWithin(container);\n  },\n\n  /**\n   * Sets focus to the first focusable element within a container.\n   * @param {Object} container\n   */\n  setFocusWithin: function (container) {\n    Garnish.setFocusWithin(container);\n  },\n\n  /**\n   * Reduces an input’s value to characters that match the given regex pattern.\n   * @param {jQuery|HTMLElement} input\n   * @param {RegExp} regex\n   */\n  filterInputVal: function (input, regex) {\n    const $input = $(input);\n    const val = $input.val();\n    let selectionStart = $input[0].selectionStart;\n    let newVal = '';\n    for (let i = 0; i < val.length; i++) {\n      if (val[i].match(regex)) {\n        newVal += val[i];\n      } else if (i < selectionStart) {\n        selectionStart--;\n      }\n    }\n    if (newVal !== val) {\n      $input.val(newVal);\n      $input[0].setSelectionRange(selectionStart, selectionStart);\n    }\n  },\n\n  /**\n   * Reduces an input’s value to numeric characters.\n   * @param {jQuery|HTMLElement} input\n   * @param {RegExp} regex\n   */\n  filterNumberInputVal: function (input) {\n    this.filterInputVal(input, /[0-9.,\\-]/);\n  },\n\n  /**\n   * Sets/removes attributes on an element.\n   *\n   * Attributes set to `null` or `false` will be removed.\n   *\n   * @param {(jQuery|HTMLElement|string)} element\n   * @param {Object} attributes\n   */\n  setElementAttributes: function (element, attributes) {\n    const $element = $(element);\n\n    for (let name in attributes) {\n      if (!attributes.hasOwnProperty(name)) {\n        continue;\n      }\n\n      let value = attributes[name];\n\n      if (value === null || value === false) {\n        $element.removeAttr(name);\n      } else if (value === true) {\n        $element.attr(name, '');\n      } else if ($.isArray(value) || $.isPlainObject(value)) {\n        if (Craft.dataAttributes.includes(name)) {\n          // Make sure it's an object\n          value = Object.assign({}, value);\n          for (let n in value) {\n            if (!value.hasOwnProperty(n)) {\n              continue;\n            }\n            let subValue = value[n];\n            if (subValue === null || subValue === false) {\n              continue;\n            }\n            if ($.isPlainObject(subValue) || $.isArray(subValue)) {\n              subValue = JSON.stringify(subValue);\n            } else if (subValue === true) {\n              subValue = '';\n            } else {\n              subValue = this.escapeHtml(subValue);\n            }\n            $element.attr(`${name}-${n}`, subValue);\n          }\n        } else if (name === 'class') {\n          // Make sure it's an array\n          if ($.isPlainObject(value)) {\n            value = Object.values(value);\n          }\n          for (let c of value) {\n            $element.addClass(c);\n          }\n        } else if (name === 'style') {\n          $element.css(value);\n        } else {\n          $element.attr(name, JSON.stringify(value));\n        }\n      } else {\n        $element.attr(name, this.escapeHtml(value));\n      }\n    }\n  },\n\n  isVisible: function () {\n    return (\n      typeof document.visibilityState === 'undefined' ||\n      document.visibilityState === 'visible'\n    );\n  },\n\n  useMobileStyles: function () {\n    return Garnish.isMobileBrowser() || document.body.clientWidth < 600;\n  },\n});\n\n// -------------------------------------------\n//  Broadcast channel\n// -------------------------------------------\n\nCraft.pageId = Craft.uuid();\n\nif (typeof BroadcastChannel !== 'undefined') {\n  const channelName = `CraftCMS:${Craft.appId}`;\n  Craft.broadcaster = new BroadcastChannel(channelName);\n  Craft.messageReceiver = new BroadcastChannel(channelName);\n\n  Craft.messageReceiver.addEventListener('message', (ev) => {\n    if (ev.data.event === 'saveElement') {\n      // Are there any instances of the same element on the page?\n      const $elements = $(\n        `div.element[data-id=\"${ev.data.id}\"][data-settings]`\n      );\n      if (!$elements.length) {\n        return;\n      }\n      const data = {\n        type: $elements.data('type'),\n        id: ev.data.id,\n        instances: [],\n      };\n      for (let i = 0; i < $elements.length; i++) {\n        const $element = $elements.eq(i);\n        data.instances.push(\n          Object.assign(\n            {\n              siteId: $element.data('site-id'),\n            },\n            $element.data('settings')\n          )\n        );\n      }\n      Craft.sendActionRequest('POST', 'app/render-element', {data}).then(\n        ({data}) => {\n          for (let i = 0; i < $elements.length; i++) {\n            const $element = $elements.eq(i);\n            if (data.elementHtml[i]) {\n              const $replacement = $(data.elementHtml[i]);\n              for (let attribute of $replacement[0].attributes) {\n                if (attribute.name === 'class') {\n                  $element.addClass(attribute.value);\n                } else {\n                  $element.attr(attribute.name, attribute.value);\n                }\n              }\n              const $inputs = $element.find('input,button').detach();\n              $element.html($replacement.html());\n              if ($inputs.length) {\n                $inputs.prependTo($element);\n              }\n            }\n          }\n          Craft.cp.elementThumbLoader.load($elements);\n        }\n      );\n    }\n  });\n}\n\n// -------------------------------------------\n//  Custom jQuery plugins\n// -------------------------------------------\n\n$.extend($.fn, {\n  animateLeft: function (pos, duration, easing, complete) {\n    if (Craft.orientation === 'ltr') {\n      return this.velocity({left: pos}, duration, easing, complete);\n    } else {\n      return this.velocity({right: pos}, duration, easing, complete);\n    }\n  },\n\n  animateRight: function (pos, duration, easing, complete) {\n    if (Craft.orientation === 'ltr') {\n      return this.velocity({right: pos}, duration, easing, complete);\n    } else {\n      return this.velocity({left: pos}, duration, easing, complete);\n    }\n  },\n\n  /**\n   * Disables elements by adding a .disabled class and preventing them from receiving focus.\n   */\n  disable: function () {\n    return this.each(function () {\n      var $elem = $(this);\n      $elem.addClass('disabled');\n\n      if ($elem.data('activatable')) {\n        $elem.removeAttr('tabindex');\n      }\n    });\n  },\n\n  /**\n   * Enables elements by removing their .disabled class and allowing them to receive focus.\n   */\n  enable: function () {\n    return this.each(function () {\n      var $elem = $(this);\n      $elem.removeClass('disabled');\n\n      if ($elem.data('activatable')) {\n        $elem.attr('tabindex', '0');\n      }\n    });\n  },\n\n  /**\n   * Sets the element as the container of a grid.\n   */\n  grid: function () {\n    return this.each(function () {\n      var $container = $(this),\n        settings = {};\n\n      if ($container.data('item-selector')) {\n        settings.itemSelector = $container.data('item-selector');\n      }\n      if ($container.data('cols')) {\n        settings.cols = parseInt($container.data('cols'));\n      }\n      if ($container.data('max-cols')) {\n        settings.maxCols = parseInt($container.data('max-cols'));\n      }\n      if ($container.data('min-col-width')) {\n        settings.minColWidth = parseInt($container.data('min-col-width'));\n      }\n      if ($container.data('mode')) {\n        settings.mode = $container.data('mode');\n      }\n      if ($container.data('fill-mode')) {\n        settings.fillMode = $container.data('fill-mode');\n      }\n      if ($container.data('col-class')) {\n        settings.colClass = $container.data('col-class');\n      }\n      if ($container.data('snap-to-grid')) {\n        settings.snapToGrid = !!$container.data('snap-to-grid');\n      }\n\n      new Craft.Grid(this, settings);\n    });\n  },\n\n  infoicon: function () {\n    return this.each(function () {\n      new Craft.InfoIcon(this);\n    });\n  },\n\n  /**\n   * Sets the element as a container for a checkbox select.\n   */\n  checkboxselect: function () {\n    return this.each(function () {\n      if (!$.data(this, 'checkboxselect')) {\n        new Garnish.CheckboxSelect(this);\n      }\n    });\n  },\n\n  /**\n   * Sets the element as a field toggle trigger.\n   */\n  fieldtoggle: function () {\n    return this.each(function () {\n      if (!$.data(this, 'fieldtoggle')) {\n        new Craft.FieldToggle(this);\n      }\n    });\n  },\n\n  lightswitch: function (settings, settingName, settingValue) {\n    // param mapping\n    if (settings === 'settings') {\n      if (typeof settingName === 'string') {\n        settings = {};\n        settings[settingName] = settingValue;\n      } else {\n        settings = settingName;\n      }\n\n      return this.each(function () {\n        var obj = $.data(this, 'lightswitch');\n        if (obj) {\n          obj.setSettings(settings);\n        }\n      });\n    } else {\n      if (!$.isPlainObject(settings)) {\n        settings = {};\n      }\n\n      return this.each(function () {\n        var thisSettings = $.extend({}, settings);\n\n        if (Garnish.hasAttr(this, 'data-value')) {\n          thisSettings.value = $(this).attr('data-value');\n        }\n\n        if (Garnish.hasAttr(this, 'data-indeterminate-value')) {\n          thisSettings.indeterminateValue = $(this).attr(\n            'data-indeterminate-value'\n          );\n        }\n\n        if (!$.data(this, 'lightswitch')) {\n          new Craft.LightSwitch(this, thisSettings);\n        }\n      });\n    }\n  },\n\n  nicetext: function () {\n    return this.each(function () {\n      if (!$.data(this, 'nicetext')) {\n        new Garnish.NiceText(this);\n      }\n    });\n  },\n\n  formsubmit: function () {\n    // Secondary form submit buttons\n    return this.on('click', function (ev) {\n      let $btn = $(ev.currentTarget);\n      let params = $btn.data('params') || {};\n      if ($btn.data('param')) {\n        params[$btn.data('param')] = $btn.data('value');\n      }\n\n      let $anchor = $btn.data('menu') ? $btn.data('menu').$anchor : $btn;\n      let $form = $anchor.attr('data-form')\n        ? $('#' + $anchor.attr('data-form'))\n        : $anchor.closest('form');\n\n      Craft.submitForm($form, {\n        confirm: $btn.data('confirm'),\n        action: $btn.data('action'),\n        redirect: $btn.data('redirect'),\n        params: params,\n        data: $.extend(\n          {\n            customTrigger: $btn,\n          },\n          $btn.data('event-data')\n        ),\n      });\n    });\n  },\n\n  menubtn: function () {\n    return this.each(function () {\n      var $btn = $(this);\n\n      if (!$btn.data('menubtn') && $btn.next().hasClass('menu')) {\n        var settings = {};\n\n        if ($btn.data('menu-anchor')) {\n          settings.menuAnchor = $btn.data('menu-anchor');\n        }\n\n        new Garnish.MenuBtn($btn, settings);\n      }\n    });\n  },\n\n  disclosureMenu: function () {\n    return this.each(function () {\n      const $trigger = $(this);\n      // Only instantiate if it's not already a disclosure trigger, and it references a disclosure content\n      if (!$trigger.data('trigger') && $trigger.attr('aria-controls')) {\n        new Garnish.DisclosureMenu($trigger);\n      }\n    });\n  },\n\n  datetime: function () {\n    return this.each(function () {\n      let $wrapper = $(this);\n      let $inputs = $wrapper.find('input:not([name$=\"[timezone]\"])');\n      let checkValue = () => {\n        let hasValue = false;\n        for (let i = 0; i < $inputs.length; i++) {\n          if ($inputs.eq(i).val()) {\n            hasValue = true;\n            break;\n          }\n        }\n        if (hasValue) {\n          if (!$wrapper.children('.clear-btn').length) {\n            let $btn = $('<button/>', {\n              type: 'button',\n              class: 'clear-btn',\n              title: Craft.t('app', 'Clear'),\n              'aria-label': Craft.t('app', 'Clear'),\n            })\n              .appendTo($wrapper)\n              .on('click', () => {\n                for (let i = 0; i < $inputs.length; i++) {\n                  $inputs.eq(i).val('').trigger('input').trigger('change');\n                }\n                $btn.remove();\n                $inputs.first().filter('[type=\"text\"]').focus();\n              });\n          }\n        } else {\n          $wrapper.children('.clear-btn').remove();\n        }\n      };\n      $inputs.on('change', checkValue);\n      checkValue();\n    });\n  },\n\n  datetimeinput: function () {\n    return this.each(function () {\n      const $input = $(this);\n      const checkValue = () => {\n        if ($input.val() === '') {\n          $input.addClass('empty-value');\n        } else {\n          $input.removeClass('empty-value');\n        }\n      };\n      $input.on('input', checkValue);\n      checkValue();\n    });\n  },\n});\n\n// Override Garnish.NiceText.charsLeftHtml() to be more accessible\nGarnish.NiceText.charsLeftHtml = (charsLeft) => {\n  return Craft.t(\n    'app',\n    '<span class=\"visually-hidden\">Characters left:</span> {chars, number}',\n    {\n      chars: charsLeft,\n    }\n  );\n};\n\nGarnish.$doc.ready(function () {\n  Craft.initUiElements();\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Customize Sources modal\n */\nCraft.CustomizeSourcesModal = Garnish.Modal.extend({\n  elementIndex: null,\n  $elementIndexSourcesContainer: null,\n\n  $sidebar: null,\n  $sidebarToggleBtn: null,\n  $sourcesContainer: null,\n  $sourcesHeader: null,\n  $sourcesHeading: null,\n  $sourceSettingsContainer: null,\n  $sourceSettingsHeader: null,\n  $addSourceMenu: null,\n  addSourceMenu: null,\n  $footer: null,\n  $footerBtnContainer: null,\n  $saveBtn: null,\n  $cancelBtn: null,\n  $loadingSpinner: null,\n\n  sourceSort: null,\n  sources: null,\n  selectedSource: null,\n\n  elementTypeName: null,\n  baseSortOptions: null,\n  availableTableAttributes: null,\n  customFieldAttributes: null,\n\n  conditionBuilderHtml: null,\n  conditionBuilderJs: null,\n  userGroups: null,\n\n  init: function (elementIndex, settings) {\n    this.base();\n\n    this.setSettings(settings, {\n      resizable: true,\n    });\n\n    this.elementIndex = elementIndex;\n    this.$elementIndexSourcesContainer = this.elementIndex.$sidebar\n      .children('nav')\n      .children('ul');\n\n    const $container = $(\n      '<form class=\"modal customize-sources-modal\"/>'\n    ).appendTo(Garnish.$bod);\n\n    this.$sidebar = $('<div class=\"cs-sidebar block-types\"/>')\n      .appendTo($container)\n      .attr({\n        role: 'navigation',\n        'aria-label': Craft.t('app', 'Source'),\n      });\n    this.$sourcesContainer = $('<div class=\"sources\">').appendTo(this.$sidebar);\n    this.$sourceSettingsContainer = $('<div class=\"source-settings\">').appendTo(\n      $container\n    );\n\n    this.$footer = $('<div class=\"footer\"/>').appendTo($container);\n    this.$footerBtnContainer = $('<div class=\"buttons right\"/>').appendTo(\n      this.$footer\n    );\n    this.$cancelBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Cancel'),\n    }).appendTo(this.$footerBtnContainer);\n    this.$saveBtn = Craft.ui\n      .createSubmitButton({\n        class: 'disabled',\n        label: Craft.t('app', 'Save'),\n        spinner: true,\n      })\n      .appendTo(this.$footerBtnContainer);\n\n    this.$loadingSpinner = $('<div class=\"spinner\"/>').appendTo(\n      this.$sourceSettingsContainer\n    );\n\n    this.setContainer($container);\n    this.show();\n\n    Craft.sendActionRequest(\n      'POST',\n      'element-index-settings/get-customize-sources-modal-data',\n      {\n        data: {\n          elementType: this.elementIndex.elementType,\n        },\n      }\n    )\n      .then((response) => {\n        this.$saveBtn.removeClass('disabled');\n        this.buildModal(response.data);\n      })\n      .finally(() => {\n        this.$loadingSpinner.remove();\n        Garnish.setFocusWithin(this.$sidebar);\n      });\n\n    this.addListener(this.$cancelBtn, 'click', 'hide');\n    this.addListener(this.$saveBtn, 'click', 'save');\n    this.addListener(this.$container, 'submit', 'save');\n  },\n\n  buildModal: function (response) {\n    this.baseSortOptions = response.baseSortOptions;\n    this.defaultSortOptions = response.defaultSortOptions;\n    this.availableTableAttributes = response.availableTableAttributes;\n    this.customFieldAttributes = response.customFieldAttributes;\n    this.elementTypeName = response.elementTypeName;\n    this.conditionBuilderHtml = response.conditionBuilderHtml;\n    this.conditionBuilderJs = response.conditionBuilderJs;\n    this.userGroups = response.userGroups;\n\n    if (response.headHtml) {\n      Craft.appendHeadHtml(response.headHtml);\n    }\n    if (response.bodyHtml) {\n      Craft.appendBodyHtml(response.bodyHtml);\n    }\n\n    // Create the source item sorter\n    this.sourceSort = new Garnish.DragSort({\n      handle: '.move',\n      axis: 'y',\n    });\n\n    // Create the sources\n    this.sources = [];\n\n    for (let i = 0; i < response.sources.length; i++) {\n      this.sources.push(this.addSource(response.sources[i]));\n    }\n\n    if (!this.selectedSource && typeof this.sources[0] !== 'undefined') {\n      this.sources[0].select();\n    }\n\n    const $menuBtnContainer = $(\n      '<div class=\"buttons left\" data-wrapper/>'\n    ).appendTo(this.$footer);\n    const $menuBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn menubtn add icon',\n      'aria-label': Craft.t('app', 'Add…'),\n      'aria-controls': 'add-source-menu',\n      title: Craft.t('app', 'Add…'),\n      'data-disclosure-trigger': '',\n    }).appendTo($menuBtnContainer);\n\n    this.$addSourceMenu = $('<div/>', {\n      id: 'add-source-menu',\n      class: 'menu menu--disclosure',\n    }).appendTo($menuBtnContainer);\n\n    const addSource = (sourceData) => {\n      const source = this.addSource(sourceData, true);\n      Garnish.scrollContainerToElement(this.$sidebar, source.$item);\n      source.select();\n      this.addSourceMenu.hide();\n    };\n\n    const $newHeadingBtn = $('<button/>', {\n      type: 'button',\n      class: 'menu-option',\n      text: Craft.t('app', 'New heading'),\n    }).on('click', () => {\n      addSource({\n        type: 'heading',\n      });\n      this.focusLabelInput();\n    });\n\n    const $newCustomSourceBtn = $('<button/>', {\n      type: 'button',\n      class: 'menu-option',\n      text: Craft.t('app', 'New custom source'),\n      'data-type': 'custom',\n    }).on('click', () => {\n      const sortOptions = this.baseSortOptions.slice(0);\n      sortOptions.push(this.defaultSortOptions);\n\n      addSource({\n        type: 'custom',\n        key: `custom:${Craft.uuid()}`,\n        sortOptions: sortOptions,\n        defaultSort: [sortOptions[0].attr, sortOptions[1].defaultDir],\n        tableAttributes: [],\n        availableTableAttributes: [],\n      });\n      this.focusLabelInput();\n    });\n\n    const $ul = $('<ul/>')\n      .append($('<li/>').append($newHeadingBtn))\n      .appendTo(this.$addSourceMenu);\n\n    if (response.conditionBuilderHtml) {\n      $('<li/>').append($newCustomSourceBtn).appendTo($ul);\n    }\n\n    if (Craft.useMobileStyles()) {\n      this.buildSidebarToggleView();\n    }\n\n    // Add resize listener to enable/disable sidebar toggle view\n    this.addListener(Garnish.$win, 'resize', this.updateSidebarView);\n\n    this.addSourceMenu = new Garnish.DisclosureMenu($menuBtn);\n  },\n\n  focusLabelInput: function () {\n    this.selectedSource.$labelInput.trigger('focus');\n  },\n\n  getSourceName: function () {\n    return this.selectedSource\n      ? this.selectedSource.sourceData.label\n      : this.sources[0].sourceData.label;\n  },\n\n  updateSidebarView: function () {\n    if (Craft.useMobileStyles()) {\n      if (!this.$sidebarToggleBtn) this.buildSidebarToggleView();\n    } else {\n      if (this.$sidebarToggleBtn) this.resetView();\n    }\n  },\n\n  resetView: function () {\n    if (this.$sourceSettingsHeader) {\n      this.$sourceSettingsHeader.remove();\n    }\n\n    if (this.$sourcesHeader) {\n      this.$sourcesHeader.remove();\n    }\n\n    this.$sidebarToggleBtn = null;\n    this.$container.removeClass('sidebar-hidden');\n  },\n\n  updateHeading: function () {\n    if (!this.$sourcesHeading) return;\n\n    this.$sourcesHeading.text(this.getSourceName());\n  },\n\n  buildSidebarToggleView: function () {\n    this.$sourcesHeader = $('<div class=\"sources-header\"/>')\n      .addClass('sidebar-header')\n      .prependTo(this.$sourcesContainer);\n\n    this.$sidebarCloseBtn = Craft.ui\n      .createButton({\n        class: 'nav-close close-btn',\n      })\n      .attr('aria-label', Craft.t('app', 'Close'))\n      .removeClass('btn')\n      .appendTo(this.$sourcesHeader);\n\n    this.$sourcesHeading = $('<h1 class=\"main-heading\"/>').text(\n      this.getSourceName()\n    );\n\n    this.$sourceSettingsHeader = $('<div class=\"source-settings-header\"/>')\n      .addClass('main-header')\n      .append(this.$sourcesHeading)\n      .prependTo(this.$sourceSettingsContainer);\n\n    // Toggle sidebar button\n    const buttonConfig = {\n      toggle: true,\n      controls: 'modal-sidebar',\n      class: 'nav-toggle',\n    };\n\n    this.$sidebarToggleBtn = Craft.ui\n      .createButton(buttonConfig)\n      .removeClass('btn')\n      .attr('aria-label', Craft.t('app', 'Show sidebar'))\n      .appendTo(this.$sourceSettingsHeader);\n\n    this.closeSidebar();\n\n    // Add listeners\n    this.addListener(this.$sidebarToggleBtn, 'click', () => {\n      this.toggleSidebar();\n    });\n\n    this.addListener(this.$sidebarCloseBtn, 'click', () => {\n      this.toggleSidebar();\n      this.$sidebarToggleBtn.trigger('focus');\n    });\n  },\n\n  toggleSidebar: function () {\n    if (this.sidebarIsOpen()) {\n      this.closeSidebar();\n    } else {\n      this.openSidebar();\n    }\n  },\n\n  openSidebar: function () {\n    this.$container.removeClass('sidebar-hidden');\n    this.$sidebarToggleBtn.attr('aria-expanded', 'true');\n    this.$sidebar.find(':focusable').first().focus();\n\n    Garnish.uiLayerManager.addLayer(this.$sidebar);\n\n    Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n      this.closeSidebar();\n\n      if (Garnish.focusIsInside(this.$sidebar)) {\n        this.$sidebarToggleBtn.focus();\n      }\n    });\n  },\n\n  closeSidebar: function () {\n    this.$container.addClass('sidebar-hidden');\n\n    if (this.$sidebarToggleBtn) {\n      this.$sidebarToggleBtn.attr('aria-expanded', 'false');\n    }\n\n    // if sidebar is topmost layer, remove layer\n    if (Garnish.uiLayerManager.currentLayer.$container.hasClass('cs-sidebar')) {\n      Garnish.uiLayerManager.removeLayer();\n    }\n  },\n\n  sidebarIsOpen: function () {\n    return this.$sidebarToggleBtn.attr('aria-expanded') === 'true';\n  },\n\n  addSource: function (sourceData, isNew) {\n    const $item = $('<div class=\"customize-sources-item\"/>').appendTo(\n      this.$sourcesContainer\n    );\n    const $itemLabel = $('<div class=\"label customize-sources-item__btn\"/>')\n      .attr({\n        tabindex: '0',\n        role: 'button',\n      })\n      .appendTo($item);\n    const $itemInput = $('<input type=\"hidden\"/>').appendTo($item);\n    $(\n      `<a class=\"move icon customize-sources-item__move\" title=\"${Craft.t(\n        'app',\n        'Reorder'\n      )}\" role=\"button\"></a>`\n    ).appendTo($item);\n\n    let source;\n\n    if (sourceData.type === 'heading') {\n      $item.addClass('heading');\n      $itemInput.attr('name', 'sourceOrder[][heading]');\n      source = new Craft.CustomizeSourcesModal.Heading(\n        this,\n        $item,\n        $itemLabel,\n        $itemInput,\n        sourceData,\n        isNew\n      );\n      source.updateItemLabel(sourceData.heading);\n    } else {\n      $itemInput.attr('name', 'sourceOrder[][key]').val(sourceData.key);\n      if (sourceData.type === 'native') {\n        source = new Craft.CustomizeSourcesModal.Source(\n          this,\n          $item,\n          $itemLabel,\n          $itemInput,\n          sourceData,\n          isNew\n        );\n      } else {\n        source = new Craft.CustomizeSourcesModal.CustomSource(\n          this,\n          $item,\n          $itemLabel,\n          $itemInput,\n          sourceData,\n          isNew\n        );\n      }\n      source.updateItemLabel(sourceData.label);\n\n      // Select this by default?\n      if (sourceData.key === this.elementIndex.rootSourceKey) {\n        source.select();\n      }\n    }\n\n    this.sourceSort.addItems($item);\n    return source;\n  },\n\n  save: function (ev) {\n    if (ev) {\n      ev.preventDefault();\n    }\n\n    if (\n      this.$saveBtn.hasClass('disabled') ||\n      this.$saveBtn.hasClass('loading')\n    ) {\n      return;\n    }\n\n    this.$saveBtn.addClass('loading');\n\n    Craft.sendActionRequest(\n      'POST',\n      'element-index-settings/save-customize-sources-modal-settings',\n      {\n        data:\n          this.$container.serialize() +\n          `&elementType=${this.elementIndex.elementType}`,\n      }\n    )\n      .then(({data}) => {\n        // Figure out which source to select\n        let sourceKey = null;\n        if (\n          this.selectedSource &&\n          this.selectedSource.sourceData.key &&\n          !data.disabledSourceKeys.includes(this.selectedSource.sourceData.key)\n        ) {\n          sourceKey = this.selectedSource.sourceData.key;\n        } else if (!this.elementIndex.sourceKey) {\n          sourceKey = this.elementIndex.$visibleSources.first().data('key');\n        }\n\n        if (sourceKey) {\n          this.elementIndex.selectSourceByKey(sourceKey);\n        }\n\n        window.location.reload();\n      })\n      .catch(() => {\n        Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n      })\n      .finally(() => {\n        this.$saveBtn.removeClass('loading');\n      });\n  },\n\n  appendIndexSourceItem: function ($sourceItem, $lastSourceItem) {\n    if (!$lastSourceItem) {\n      $sourceItem.prependTo(this.$elementIndexSourcesContainer);\n    } else {\n      const isHeading = $sourceItem.hasClass('heading');\n      if ($lastSourceItem.hasClass('heading') && !isHeading) {\n        // First source to be placed below a new heading\n        $sourceItem.appendTo($lastSourceItem.children('ul'));\n      } else {\n        if (isHeading) {\n          // New heading. Swap $lastSourceItem with the top level <li> if it's nested\n          const $lastTopLevelSource = $lastSourceItem\n            .parentsUntil(this.$elementIndexSourcesContainer, 'li')\n            .last();\n          if ($lastTopLevelSource.length) {\n            $lastSourceItem = $lastTopLevelSource;\n          }\n        }\n        $sourceItem.insertAfter($lastSourceItem);\n      }\n    }\n  },\n\n  destroy: function () {\n    for (let i = 0; i < this.sources.length; i++) {\n      this.sources[i].destroy();\n    }\n\n    if (this.addSourceMenu) {\n      this.addSourceMenu.destroy();\n      this.$addSourceMenu.remove();\n    }\n\n    delete this.sources;\n    this.base();\n  },\n});\n\nCraft.CustomizeSourcesModal.BaseSource = Garnish.Base.extend({\n  modal: null,\n\n  $item: null,\n  $itemLabel: null,\n  $itemInput: null,\n  $settingsContainer: null,\n\n  sourceData: null,\n  isNew: null,\n\n  init: function (modal, $item, $itemLabel, $itemInput, sourceData, isNew) {\n    this.modal = modal;\n    this.$item = $item;\n    this.$itemLabel = $itemLabel;\n    this.$itemInput = $itemInput;\n    this.sourceData = sourceData;\n    this.isNew = isNew;\n\n    this.$item.data('source', this);\n\n    this.addListener(this.$itemLabel, 'click', 'select');\n    this.addListener(this.$itemLabel, 'keypress', (e) =>\n      Garnish.handleActivatingKeypress(e, this.select.bind(this))\n    );\n  },\n\n  isHeading: function () {\n    return false;\n  },\n\n  isNative: function () {\n    return false;\n  },\n\n  isSelected: function () {\n    return this.modal.selectedSource === this;\n  },\n\n  select: function () {\n    if (this.isSelected()) {\n      return;\n    }\n\n    if (this.modal.selectedSource) {\n      this.modal.selectedSource.deselect();\n    }\n\n    this.$item.addClass('sel');\n    this.$itemLabel.attr({\n      'aria-current': 'true',\n    });\n    this.modal.selectedSource = this;\n    this.modal.updateHeading();\n\n    if (!this.$settingsContainer) {\n      this.$settingsContainer = $('<div/>').appendTo(\n        this.modal.$sourceSettingsContainer\n      );\n      this.createSettings(this.$settingsContainer);\n    } else {\n      this.$settingsContainer.removeClass('hidden');\n    }\n\n    this.modal.$sourceSettingsContainer.scrollTop(0);\n  },\n\n  createSettings: function () {},\n\n  getIndexSourceItem: function () {},\n\n  deselect: function () {\n    this.$item.removeClass('sel');\n    this.$itemLabel.attr({\n      'aria-current': 'false',\n    });\n    this.modal.selectedSource = null;\n    this.$settingsContainer.addClass('hidden');\n  },\n\n  updateItemLabel: function (val) {\n    if (val) {\n      this.$itemLabel.text(val);\n    } else {\n      this.$itemLabel.html('&nbsp;');\n    }\n  },\n\n  destroy: function () {\n    this.modal.sourceSort.removeItems(this.$item);\n    this.modal.sources.splice($.inArray(this, this.modal.sources), 1);\n\n    if (this.isSelected()) {\n      this.deselect();\n\n      if (this.modal.sources.length) {\n        this.modal.sources[0].select();\n      }\n\n      Garnish.setFocusWithin(this.modal.$sourceSettingsContainer);\n    }\n\n    this.$item.data('source', null);\n    this.$item.remove();\n\n    if (this.$settingsContainer) {\n      this.$settingsContainer.remove();\n    }\n\n    this.base();\n  },\n});\n\nCraft.CustomizeSourcesModal.Source =\n  Craft.CustomizeSourcesModal.BaseSource.extend({\n    $sortAttributeSelect: null,\n    $sortDirectionPicker: null,\n    $sortDirectionInput: null,\n    sortDirectionListbox: null,\n\n    isNative: function () {\n      return true;\n    },\n\n    createSettings: function ($container) {\n      Craft.ui\n        .createLightswitchField({\n          label: Craft.t('app', 'Enabled'),\n          name: `sources[${this.sourceData.key}][enabled]`,\n          on: !this.sourceData.disabled,\n        })\n        .appendTo($container);\n      this.createSortField($container);\n      this.createTableAttributesField($container);\n    },\n\n    createSortField: function ($container) {\n      const $inputContainer = $('<div class=\"flex\"/>');\n\n      const $sortAttributeSelectContainer = Craft.ui\n        .createSelect({\n          name: `sources[${this.sourceData.key}][defaultSort][0]`,\n          options: this.sourceData.sortOptions.map((o) => {\n            return {\n              label: Craft.escapeHtml(o.label),\n              value: o.attr,\n            };\n          }),\n          value: this.sourceData.defaultSort[0],\n        })\n        .addClass('fullwidth')\n        .appendTo($('<div/>').appendTo($inputContainer));\n\n      this.$sortAttributeSelect = $sortAttributeSelectContainer\n        .children('select')\n        .attr('aria-label', Craft.t('app', 'Sort attribute'));\n\n      this.$sortDirectionPicker = $('<section/>', {\n        class: 'btngroup btngroup--exclusive',\n        'aria-label': Craft.t('app', 'Sort direction'),\n      })\n        .append(\n          $('<button/>', {\n            type: 'button',\n            class: 'btn',\n            title: Craft.t('app', 'Sort ascending'),\n            'aria-label': Craft.t('app', 'Sort ascending'),\n            'aria-pressed': 'false',\n            'data-icon': 'asc',\n            'data-dir': 'asc',\n          })\n        )\n        .append(\n          $('<button/>', {\n            type: 'button',\n            class: 'btn',\n            title: Craft.t('app', 'Sort descending'),\n            'aria-label': Craft.t('app', 'Sort descending'),\n            'aria-pressed': 'false',\n            'data-icon': 'desc',\n            'data-dir': 'desc',\n          })\n        )\n        .appendTo($inputContainer);\n\n      this.$sortDirectionInput = $('<input/>', {\n        type: 'hidden',\n        name: `sources[${this.sourceData.key}][defaultSort][1]`,\n      }).appendTo($inputContainer);\n\n      this.sortDirectionListbox = new Craft.Listbox(this.$sortDirectionPicker, {\n        onChange: ($selectedOption) => {\n          this.$sortDirectionInput.val($selectedOption.data('dir'));\n        },\n      });\n\n      this.$sortAttributeSelect.on('change', () => {\n        this.handleSortAttributeChange();\n      });\n\n      this.handleSortAttributeChange(true);\n\n      Craft.ui\n        .createField($inputContainer, {\n          label: Craft.t('app', 'Default Sort'),\n          fieldset: true,\n        })\n        .appendTo($container)\n        .addClass('sort-field');\n    },\n\n    handleSortAttributeChange: function (useDefaultDir) {\n      const attr = this.$sortAttributeSelect.val();\n\n      if (attr === 'structure') {\n        this.sortDirectionListbox.select(0);\n        this.sortDirectionListbox.disable();\n        this.$sortDirectionPicker.addClass('disabled');\n      } else {\n        this.sortDirectionListbox.enable();\n        this.$sortDirectionPicker.removeClass('disabled');\n\n        const dir = useDefaultDir\n          ? this.sourceData.defaultSort[1]\n          : this.sourceData.sortOptions.find((o) => o.attr === attr).defaultDir;\n        this.sortDirectionListbox.select(dir === 'asc' ? 0 : 1);\n      }\n    },\n\n    createTableAttributesField: function ($container) {\n      const availableTableAttributes = this.availableTableAttributes();\n\n      if (\n        !this.sourceData.tableAttributes.length &&\n        !availableTableAttributes.length\n      ) {\n        return;\n      }\n\n      const $columnCheckboxes = $('<div/>');\n      const selectedAttributes = [];\n\n      $(\n        `<input type=\"hidden\" name=\"sources[${this.sourceData.key}][tableAttributes][]\" value=\"\"/>`\n      ).appendTo($columnCheckboxes);\n\n      // Add the selected columns, in the selected order\n      for (let i = 0; i < this.sourceData.tableAttributes.length; i++) {\n        let [key, label] = this.sourceData.tableAttributes[i];\n        $columnCheckboxes.append(\n          this.createTableColumnOption(key, label, true)\n        );\n        selectedAttributes.push(key);\n      }\n\n      // Add the rest\n      for (let i = 0; i < availableTableAttributes.length; i++) {\n        const [key, label] = availableTableAttributes[i];\n        if (!Craft.inArray(key, selectedAttributes)) {\n          $columnCheckboxes.append(\n            this.createTableColumnOption(key, label, false)\n          );\n        }\n      }\n\n      new Garnish.DragSort($columnCheckboxes.children(), {\n        handle: '.move',\n        axis: 'y',\n      });\n\n      Craft.ui\n        .createField($columnCheckboxes, {\n          label: Craft.t('app', 'Default Table Columns'),\n          instructions: Craft.t(\n            'app',\n            'Choose which table columns should be visible for this source by default.'\n          ),\n        })\n        .appendTo($container);\n    },\n\n    availableTableAttributes: function () {\n      const attributes = this.modal.availableTableAttributes.slice(0);\n      attributes.push(...this.sourceData.availableTableAttributes);\n      return attributes;\n    },\n\n    createTableColumnOption: function (key, label, checked) {\n      return $('<div class=\"customize-sources-table-column\"/>')\n        .append('<div class=\"icon move\"/>')\n        .append(\n          Craft.ui.createCheckbox({\n            label: Craft.escapeHtml(label),\n            name: `sources[${this.sourceData.key}][tableAttributes][]`,\n            value: key,\n            checked: checked,\n          })\n        );\n    },\n\n    getIndexSourceItem: function () {\n      const $source = this.modal.elementIndex.getSourceByKey(\n        this.sourceData.key\n      );\n\n      if ($source) {\n        return $source.closest('li');\n      }\n    },\n  });\n\nCraft.CustomizeSourcesModal.CustomSource =\n  Craft.CustomizeSourcesModal.Source.extend({\n    $labelInput: null,\n\n    createSettings: function ($container) {\n      const $labelField = Craft.ui\n        .createTextField({\n          label: Craft.t('app', 'Label'),\n          name: `sources[${this.sourceData.key}][label]`,\n          value: this.sourceData.label,\n        })\n        .appendTo($container);\n      this.$labelInput = $labelField.find('.text');\n      const defaultId = `condition${Math.floor(Math.random() * 1000000)}`;\n\n      const swapPlaceholders = (str) =>\n        str\n          .replace(/__ID__/g, defaultId)\n          .replace(\n            /__SOURCE_KEY__(?=-)/g,\n            Craft.formatInputId(this.sourceData.key)\n          )\n          .replace(/__SOURCE_KEY__/g, this.sourceData.key);\n\n      const conditionBuilderHtml =\n        this.sourceData.conditionBuilderHtml ||\n        swapPlaceholders(this.modal.conditionBuilderHtml);\n      const conditionBuilderJs =\n        this.sourceData.conditionBuilderJs ||\n        swapPlaceholders(this.modal.conditionBuilderJs);\n\n      Craft.ui\n        .createField($('<div/>').append(conditionBuilderHtml), {\n          id: 'criteria',\n          label: Craft.t('app', '{type} Criteria', {\n            type: this.modal.elementTypeName,\n          }),\n        })\n        .appendTo($container);\n      Craft.appendBodyHtml(conditionBuilderJs);\n\n      this.createSortField($container);\n      this.createTableAttributesField($container);\n\n      if (this.modal.userGroups.length) {\n        Craft.ui\n          .createCheckboxSelectField({\n            label: Craft.t('app', 'User Groups'),\n            instructions: Craft.t(\n              'app',\n              'Choose which user groups should have access to this source.'\n            ),\n            name: `sources[${this.sourceData.key}][userGroups]`,\n            options: this.modal.userGroups,\n            values: this.sourceData.userGroups || '*',\n            showAllOption: true,\n          })\n          .appendTo($container);\n      }\n\n      $container.append('<hr/>');\n\n      this.$deleteBtn = $('<a class=\"error delete\"/>')\n        .attr({\n          role: 'button',\n          tabindex: '0',\n        })\n        .text(Craft.t('app', 'Delete custom source'))\n        .appendTo($container);\n\n      this.addListener(this.$labelInput, 'input', 'handleLabelInputChange');\n      this.addListener(this.$deleteBtn, 'click', 'destroy');\n      this.addListener(this.$deleteBtn, 'keypress', (e) => {\n        Garnish.handleActivatingKeypress(e, this.destroy.bind(this));\n      });\n    },\n\n    availableTableAttributes: function () {\n      const attributes = this.base();\n      if (this.isNew) {\n        attributes.push(...this.modal.customFieldAttributes);\n      }\n      return attributes;\n    },\n\n    handleLabelInputChange: function () {\n      this.updateItemLabel(this.$labelInput.val());\n    },\n\n    getIndexSourceItem: function () {\n      let $source = this.base();\n      let $label;\n\n      if ($source) {\n        $label = $source.find('.label');\n      } else {\n        $label = $('<span/>', {class: 'label'});\n        $source = $('<li/>').append(\n          $('<a/>', {\n            'data-key': this.sourceData.key,\n          }).append($label)\n        );\n      }\n\n      if (this.$labelInput) {\n        let label = Craft.trim(this.$labelInput.val());\n        if (label === '') {\n          label = Craft.t('app', '(blank)');\n        }\n        $label.text(label);\n      }\n\n      return $source;\n    },\n  });\n\nCraft.CustomizeSourcesModal.Heading =\n  Craft.CustomizeSourcesModal.BaseSource.extend({\n    $labelInput: null,\n    $deleteBtn: null,\n\n    isHeading: function () {\n      return true;\n    },\n\n    createSettings: function ($container) {\n      const $labelField = Craft.ui\n        .createTextField({\n          label: Craft.t('app', 'Heading'),\n          instructions: Craft.t(\n            'app',\n            'This can be left blank if you just want an unlabeled separator.'\n          ),\n          value: this.sourceData.heading || '',\n        })\n        .appendTo($container);\n      this.$labelInput = $labelField.find('.text');\n\n      $container.append('<hr/>');\n\n      this.$deleteBtn = $('<a class=\"error delete\"/>')\n        .text(Craft.t('app', 'Delete heading'))\n        .attr({\n          role: 'button',\n          tabindex: '0',\n        })\n        .appendTo($container);\n\n      this.addListener(this.$labelInput, 'input', 'handleLabelInputChange');\n      this.addListener(this.$deleteBtn, 'click', 'destroy');\n      this.addListener(this.$deleteBtn, 'keypress', (e) => {\n        Garnish.handleActivatingKeypress(e, this.destroy.bind(this));\n      });\n    },\n\n    handleLabelInputChange: function () {\n      this.updateItemLabel(this.$labelInput.val());\n    },\n\n    updateItemLabel: function (val) {\n      this.$itemLabel.html(\n        (val\n          ? Craft.escapeHtml(val)\n          : `<em>${Craft.t('app', '(blank)')}</em>`) + '&nbsp;'\n      );\n      this.$itemInput.val(val);\n    },\n\n    getIndexSourceItem: function () {\n      const label =\n        (this.$labelInput ? this.$labelInput.val() : null) ||\n        this.sourceData.heading ||\n        '';\n      return $('<li class=\"heading\"/>')\n        .append($('<span/>').text(label))\n        .append('<ul/>');\n    },\n  });\n","/** global: Craft */\n/** global: Garnish */\n/**\n * DataTableSorter\n */\nCraft.DataTableSorter = Garnish.DragSort.extend(\n  {\n    $table: null,\n\n    init: function (table, settings) {\n      this.$table = $(table);\n      var $rows = this.$table.children('tbody').children(':not(.filler)');\n\n      settings = $.extend({}, Craft.DataTableSorter.defaults, settings);\n\n      settings.container = this.$table.children('tbody');\n      settings.helper = this.getHelper.bind(this);\n      settings.caboose = '<tr/>';\n      settings.axis = Garnish.Y_AXIS;\n      settings.magnetStrength = 4;\n      settings.helperLagBase = 1.5;\n\n      this.base($rows, settings);\n    },\n\n    getHelper: function ($helperRow) {\n      var $helper = $(\n          '<div class=\"' + this.settings.helperClass + '\"/>'\n        ).appendTo(Garnish.$bod),\n        $table = $('<table/>').appendTo($helper),\n        $tbody = $('<tbody/>').appendTo($table);\n\n      $helperRow.appendTo($tbody);\n\n      // Copy the table width and classes\n      $table.width(this.$table.width());\n      $table.prop('className', this.$table.prop('className'));\n\n      // Copy the column widths\n      var $firstRow = this.$table.find('tr:first'),\n        $cells = $firstRow.children(),\n        $helperCells = $helperRow.children();\n\n      for (var i = 0; i < $helperCells.length; i++) {\n        $($helperCells[i]).width($($cells[i]).width());\n      }\n\n      return $helper;\n    },\n  },\n  {\n    defaults: {\n      handle: '.move',\n      helperClass: 'datatablesorthelper',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Delete User Modal\n */\nCraft.DeleteUserModal = Garnish.Modal.extend(\n  {\n    id: null,\n    userId: null,\n\n    $deleteActionRadios: null,\n    $deleteSubmitBtn: null,\n\n    userSelect: null,\n    _deleting: false,\n\n    init: function (userId, settings) {\n      this.id = Math.floor(Math.random() * 1000000000);\n      this.userId = userId;\n      settings = $.extend(Craft.DeleteUserModal.defaults, settings);\n\n      let $form = $(\n        '<form class=\"modal fitted deleteusermodal\" method=\"post\" accept-charset=\"UTF-8\">' +\n          Craft.getCsrfInput() +\n          '<input type=\"hidden\" name=\"action\" value=\"users/delete-user\"/>' +\n          (!Garnish.isArray(this.userId)\n            ? '<input type=\"hidden\" name=\"userId\" value=\"' + this.userId + '\"/>'\n            : '') +\n          (settings.redirect\n            ? '<input type=\"hidden\" name=\"redirect\" value=\"' +\n              settings.redirect +\n              '\"/>'\n            : '') +\n          '</form>'\n      ).appendTo(Garnish.$bod);\n      let $body = $(\n        '<div class=\"body\">' +\n          '<div class=\"content-summary\">' +\n          '<p>' +\n          Craft.t('app', 'What do you want to do with their content?') +\n          '</p>' +\n          '<ul class=\"bullets\"></ul>' +\n          '</div>' +\n          '<div class=\"options\">' +\n          '<label><input type=\"radio\" name=\"contentAction\" value=\"transfer\"/> ' +\n          Craft.t('app', 'Transfer it to:') +\n          '</label>' +\n          '<div id=\"transferselect' +\n          this.id +\n          '\" class=\"elementselect\">' +\n          '<div class=\"elements\"></div>' +\n          '<button type=\"button\" class=\"btn add icon dashed\">' +\n          Craft.t('app', 'Choose a user') +\n          '</button>' +\n          '</div>' +\n          '</div>' +\n          '<div>' +\n          '<label class=\"error\"><input type=\"radio\" name=\"contentAction\" value=\"delete\"/> ' +\n          Craft.t('app', 'Delete their content') +\n          '</label>' +\n          '</div>' +\n          '</div>'\n      ).appendTo($form);\n      let $buttons = $('<div class=\"buttons right\"/>').appendTo($body);\n      let $cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo($buttons);\n\n      if (settings.contentSummary.length) {\n        for (let i = 0; i < settings.contentSummary.length; i++) {\n          $body\n            .find('ul')\n            .append($('<li/>', {text: settings.contentSummary[i]}));\n        }\n      } else {\n        $body.find('ul').remove();\n      }\n\n      this.$deleteActionRadios = $body.find('input[type=radio]');\n      this.$deleteSubmitBtn = Craft.ui\n        .createSubmitButton({\n          class: 'disabled',\n          label: this._submitBtnLabel(false),\n          spinner: true,\n        })\n        .appendTo($buttons);\n\n      var idParam;\n\n      if (Garnish.isArray(this.userId)) {\n        idParam = ['and'];\n\n        for (let i = 0; i < this.userId.length; i++) {\n          idParam.push('not ' + this.userId[i]);\n        }\n      } else {\n        idParam = 'not ' + this.userId;\n      }\n\n      this.userSelect = new Craft.BaseElementSelectInput({\n        id: 'transferselect' + this.id,\n        name: 'transferContentTo',\n        elementType: 'craft\\\\elements\\\\User',\n        criteria: {\n          id: idParam,\n        },\n        limit: 1,\n        modalSettings: {\n          closeOtherModals: false,\n        },\n        onSelectElements: () => {\n          this.updateSizeAndPosition();\n\n          if (!this.$deleteActionRadios.first().prop('checked')) {\n            this.$deleteActionRadios.first().trigger('click');\n          } else {\n            this.validateDeleteInputs();\n          }\n        },\n        onRemoveElements: this.validateDeleteInputs.bind(this),\n        selectable: false,\n        editable: false,\n      });\n\n      this.addListener($cancelBtn, 'click', 'hide');\n\n      this.addListener(\n        this.$deleteActionRadios,\n        'change',\n        'validateDeleteInputs'\n      );\n      this.addListener($form, 'submit', 'handleSubmit');\n\n      this.base($form, settings);\n    },\n\n    _submitBtnLabel: function (withContent) {\n      let message = withContent\n        ? 'Delete {num, plural, =1{user} other{users}} and content'\n        : 'Delete {num, plural, =1{user} other{users}}';\n\n      return Craft.t('app', message, {\n        num: Garnish.isArray(this.userId) ? this.userId.length : 1,\n      });\n    },\n\n    validateDeleteInputs: function () {\n      var validates = false;\n\n      if (this.$deleteActionRadios.eq(1).prop('checked')) {\n        validates = true;\n        this.$deleteSubmitBtn.find('.label').text(this._submitBtnLabel(true));\n      } else {\n        this.$deleteSubmitBtn.find('.label').text(this._submitBtnLabel(false));\n        if (this.$deleteActionRadios.eq(0).prop('checked')) {\n          validates = !!this.userSelect.totalSelected;\n        }\n      }\n\n      this.updateSizeAndPosition();\n\n      if (validates) {\n        this.$deleteSubmitBtn.removeClass('disabled');\n      } else {\n        this.$deleteSubmitBtn.addClass('disabled');\n      }\n\n      return validates;\n    },\n\n    handleSubmit: function (ev) {\n      if (this._deleting || !this.validateDeleteInputs()) {\n        ev.preventDefault();\n        return;\n      }\n\n      this.$deleteSubmitBtn.addClass('loading');\n      this.disable();\n      this.userSelect.disable();\n      this._deleting = true;\n\n      // Let the onSubmit callback prevent the form from getting submitted\n      try {\n        if (this.settings.onSubmit() === false) {\n          ev.preventDefault();\n        }\n      } catch (e) {\n        ev.preventDefault();\n        this.$deleteSubmitBtn.removeClass('loading');\n        throw e;\n      }\n    },\n\n    onFadeIn: function () {\n      // Auto-focus the first radio\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$deleteActionRadios.first().trigger('focus');\n      }\n\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      contentSummary: [],\n      onSubmit: $.noop,\n      redirect: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.DynamicGenerator = Craft.BaseInputGenerator.extend({\n  callback: $.noop,\n\n  init: function (source, target, callback) {\n    this.callback = callback;\n    this.base(source, target);\n  },\n\n  generateTargetValue: function (sourceVal) {\n    return this.callback(sourceVal);\n  },\n});\n","/* jshint -W083 */\n/**\n * Editable table class\n */\nCraft.EditableTable = Garnish.Base.extend(\n  {\n    initialized: false,\n\n    id: null,\n    baseName: null,\n    columns: null,\n    sorter: null,\n    biggestId: -1,\n\n    $table: null,\n    $tbody: null,\n    $addRowBtn: null,\n    $tableParent: null,\n    $statusMessage: null,\n\n    rowCount: 0,\n    hasMaxRows: false,\n    hasMinRows: false,\n\n    radioCheckboxes: null,\n\n    init: function (id, baseName, columns, settings) {\n      this.id = id;\n      this.baseName = baseName;\n      this.columns = columns;\n      this.setSettings(settings, Craft.EditableTable.defaults);\n      this.radioCheckboxes = {};\n\n      this.$table = $('#' + id);\n      this.$tbody = this.$table.children('tbody');\n      this.$tableParent = this.$table.parent();\n      this.$statusMessage = this.$tableParent.find('[data-status-message]');\n      this.rowCount = this.$tbody.find('tr').length;\n\n      // Is this already an editable table?\n      if (this.$table.data('editable-table')) {\n        console.warn('Double-instantiating an editable table on an element');\n        this.$table.data('editable-table').destroy();\n      }\n\n      this.$table.data('editable-table', this);\n\n      this.sorter = new Craft.DataTableSorter(this.$table, {\n        helperClass: 'editabletablesorthelper',\n        copyDraggeeInputValuesToHelper: true,\n        onSortChange: () => {\n          this.updateAllRows();\n        },\n      });\n\n      if (this.isVisible()) {\n        this.initialize();\n      } else {\n        // Give everything a chance to initialize\n        window.setTimeout(this.initializeIfVisible.bind(this), 500);\n      }\n\n      if (this.settings.minRows && this.rowCount < this.settings.minRows) {\n        for (var i = this.rowCount; i < this.settings.minRows; i++) {\n          this.addRow();\n        }\n      }\n    },\n\n    isVisible: function () {\n      return this.$table.parent().height() > 0;\n    },\n\n    initialize: function () {\n      if (this.initialized) {\n        return false;\n      }\n\n      this.initialized = true;\n      this.removeListener(Garnish.$win, 'resize');\n\n      var $rows = this.$tbody.children();\n\n      for (var i = 0; i < $rows.length; i++) {\n        this.createRowObj($rows[i]);\n      }\n\n      const $container = this.$table.parent('.input');\n      if ($container.length && this.$table.width() > $container.width()) {\n        $container.css('overflow-x', 'auto');\n      }\n\n      this.$addRowBtn = this.$table.next('.add');\n      this.updateAddRowButton();\n      this.addListener(this.$addRowBtn, 'activate', 'addRow');\n      return true;\n    },\n    initializeIfVisible: function () {\n      this.removeListener(Garnish.$win, 'resize');\n\n      if (this.isVisible()) {\n        this.initialize();\n      } else {\n        this.addListener(Garnish.$win, 'resize', 'initializeIfVisible');\n      }\n    },\n    updateAddRowButton: function () {\n      if (!this.canAddRow()) {\n        this.$addRowBtn.css('opacity', '0.2');\n        this.$addRowBtn.css('pointer-events', 'none');\n        this.$addRowBtn.attr('aria-disabled', 'true');\n      } else {\n        this.$addRowBtn.css('opacity', '1');\n        this.$addRowBtn.css('pointer-events', 'auto');\n        this.$addRowBtn.attr('aria-disabled', 'false');\n      }\n    },\n    updateAllRows: function () {\n      if (this.settings.staticRows) {\n        return;\n      }\n      const $rows = this.$table.find('> tbody > tr');\n      for (let i = 0; i < $rows.length; i++) {\n        this.updateRow($rows.eq(i));\n      }\n    },\n    updateRow: function ($row) {\n      if (this.settings.staticRows) {\n        return;\n      }\n\n      const $deleteBtn = $row.find('button.delete');\n\n      if ($deleteBtn.length) {\n        $deleteBtn.attr(\n          'aria-label',\n          Craft.t('app', 'Delete row {index}', {\n            index: $row.index() + 1,\n          })\n        );\n        if (this.canDeleteRow()) {\n          $deleteBtn.removeAttr('disabled').removeClass('disabled');\n        } else {\n          $deleteBtn.attr('disabled', 'disabled').addClass('disabled');\n        }\n      }\n    },\n    /**\n     * @deprecated\n     */\n    updateDeleteRowButton: function (rowId) {\n      this.updateRow(this.$table.find(`tr[data-id=\"${rowId}\"]`));\n    },\n    updateStatusMessage: function () {\n      this.$statusMessage.empty();\n      let message;\n\n      if (!this.canAddRow()) {\n        message = Craft.t(\n          'app',\n          'Row could not be added. Maximum number of rows reached.'\n        );\n      } else {\n        message = Craft.t(\n          'app',\n          'Row could not be deleted. Minimum number of rows reached.'\n        );\n      }\n\n      setTimeout(() => {\n        this.$statusMessage.text(message);\n      }, 250);\n    },\n    canDeleteRow: function () {\n      if (!this.settings.allowDelete) {\n        return false;\n      }\n\n      return this.rowCount > this.settings.minRows;\n    },\n    deleteRow: function (row) {\n      if (!this.canDeleteRow()) {\n        this.updateStatusMessage();\n        return;\n      }\n\n      this.sorter.removeItems(row.$tr);\n      row.$tr.remove();\n\n      this.rowCount--;\n\n      this.updateAllRows();\n      this.updateAddRowButton();\n\n      if (this.rowCount === 0) {\n        this.$table.addClass('hidden');\n        this.$addRowBtn.trigger('focus');\n      } else {\n        // Focus element in previous row\n        this.$tbody.find(':focusable').last().trigger('focus');\n      }\n\n      // onDeleteRow callback\n      this.settings.onDeleteRow(row.$tr);\n\n      row.destroy();\n    },\n    canAddRow: function () {\n      if (!this.settings.allowAdd) {\n        return false;\n      }\n\n      if (this.settings.maxRows) {\n        return this.rowCount < this.settings.maxRows;\n      }\n\n      return true;\n    },\n    addRow: function (focus, prepend) {\n      if (!this.canAddRow()) {\n        this.updateStatusMessage();\n        return;\n      }\n\n      var rowId = this.settings.rowIdPrefix + (this.biggestId + 1),\n        $tr = this.createRow(\n          rowId,\n          this.columns,\n          this.baseName,\n          $.extend({}, this.settings.defaultValues)\n        );\n\n      if (prepend) {\n        $tr.prependTo(this.$tbody);\n      } else {\n        $tr.appendTo(this.$tbody);\n      }\n\n      var row = this.createRowObj($tr);\n      this.sorter.addItems($tr);\n\n      // Focus the first input in the row\n      if (focus !== false) {\n        $tr\n          .find('input:visible,textarea:visible,select:visible')\n          .first()\n          .trigger('focus');\n      }\n\n      this.rowCount++;\n      this.updateAllRows();\n      this.updateAddRowButton();\n      this.$table.removeClass('hidden');\n\n      // onAddRow callback\n      this.settings.onAddRow($tr);\n\n      return row;\n    },\n\n    createRow: function (rowId, columns, baseName, values) {\n      return Craft.EditableTable.createRow(\n        rowId,\n        columns,\n        baseName,\n        values,\n        this.settings.allowReorder,\n        this.settings.allowDelete\n      );\n    },\n\n    createRowObj: function ($tr) {\n      return new Craft.EditableTable.Row(this, $tr);\n    },\n\n    focusOnPrevRow: function ($tr, tdIndex, blurTd) {\n      var $prevTr = $tr.prev('tr');\n      var prevRow;\n\n      if ($prevTr.length) {\n        prevRow = $prevTr.data('editable-table-row');\n      } else {\n        prevRow = this.addRow(false, true);\n      }\n\n      // Focus on the same cell in the previous row\n      if (!prevRow) {\n        return;\n      }\n\n      if (!prevRow.$tds[tdIndex]) {\n        return;\n      }\n\n      if ($(prevRow.$tds[tdIndex]).hasClass('disabled')) {\n        if ($prevTr) {\n          this.focusOnPrevRow($prevTr, tdIndex, blurTd);\n        }\n        return;\n      }\n\n      var $input = $('textarea,input.text', prevRow.$tds[tdIndex]);\n      if ($input.length) {\n        $(blurTd).trigger('blur');\n        $input.trigger('focus');\n      }\n    },\n\n    focusOnNextRow: function ($tr, tdIndex, blurTd) {\n      var $nextTr = $tr.next('tr');\n      var nextRow;\n\n      if ($nextTr.length) {\n        nextRow = $nextTr.data('editable-table-row');\n      } else {\n        nextRow = this.addRow(false);\n      }\n\n      // Focus on the same cell in the next row\n      if (!nextRow) {\n        return;\n      }\n\n      if (!nextRow.$tds[tdIndex]) {\n        return;\n      }\n\n      if ($(nextRow.$tds[tdIndex]).hasClass('disabled')) {\n        if ($nextTr) {\n          this.focusOnNextRow($nextTr, tdIndex, blurTd);\n        }\n        return;\n      }\n\n      var $input = $('textarea,input.text', nextRow.$tds[tdIndex]);\n      if ($input.length) {\n        $(blurTd).trigger('blur');\n        $input.trigger('focus');\n      }\n    },\n\n    importData: function (data, row, tdIndex) {\n      let lines = data.split(/\\r?\\n|\\r/);\n      for (let i = 0; i < lines.length; i++) {\n        let values = lines[i].split('\\t');\n        for (let j = 0; j < values.length; j++) {\n          let value = values[j];\n          row.$tds\n            .eq(tdIndex + j)\n            .find('textarea,input[type!=hidden]')\n            .val(value)\n            .trigger('input');\n        }\n\n        // move onto the next row\n        let $nextTr = row.$tr.next('tr');\n        if ($nextTr.length) {\n          row = $nextTr.data('editable-table-row');\n        } else {\n          row = this.addRow(false);\n        }\n      }\n    },\n\n    destroy: function () {\n      this.$table.removeData('editable-table');\n      this.base();\n    },\n  },\n  {\n    textualColTypes: [\n      'autosuggest',\n      'color',\n      'date',\n      'email',\n      'multiline',\n      'number',\n      'singleline',\n      'template',\n      'time',\n      'url',\n    ],\n    defaults: {\n      rowIdPrefix: '',\n      defaultValues: {},\n      allowAdd: false,\n      allowReorder: false,\n      allowDelete: false,\n      minRows: null,\n      maxRows: null,\n      onAddRow: $.noop,\n      onDeleteRow: $.noop,\n    },\n\n    createRow: function (\n      rowId,\n      columns,\n      baseName,\n      values,\n      allowReorder,\n      allowDelete\n    ) {\n      var $tr = $('<tr/>', {\n        'data-id': rowId,\n      });\n\n      for (var colId in columns) {\n        if (!columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        var col = columns[colId],\n          value = typeof values[colId] !== 'undefined' ? values[colId] : '',\n          $cell;\n\n        if (col.type === 'heading') {\n          $cell = $('<th/>', {\n            scope: 'row',\n            class: col['class'],\n            html: value,\n          });\n        } else {\n          var name = baseName + '[' + rowId + '][' + colId + ']';\n\n          $cell = $('<td/>', {\n            class: `${col.class} ${col.type}-cell`,\n            width: col.width,\n          });\n\n          if (Craft.inArray(col.type, Craft.EditableTable.textualColTypes)) {\n            $cell.addClass('textual');\n          }\n\n          if (col.code) {\n            $cell.addClass('code');\n          }\n\n          switch (col.type) {\n            case 'checkbox':\n              $('<div class=\"checkbox-wrapper\"/>')\n                .append(\n                  Craft.ui.createCheckbox({\n                    name: name,\n                    value: col.value || '1',\n                    checked: !!value,\n                  })\n                )\n                .appendTo($cell);\n              break;\n\n            case 'color':\n              Craft.ui\n                .createColorInput({\n                  name: name,\n                  value: value,\n                  small: true,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'date':\n              Craft.ui\n                .createDateInput({\n                  name: name,\n                  value: value,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'lightswitch':\n              Craft.ui\n                .createLightswitch({\n                  name: name,\n                  value: col.value || '1',\n                  on: !!value,\n                  small: true,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'select':\n              Craft.ui\n                .createSelect({\n                  name: name,\n                  options: col.options,\n                  value:\n                    value ||\n                    (function () {\n                      for (var key in col.options) {\n                        if (\n                          col.options.hasOwnProperty(key) &&\n                          col.options[key].default\n                        ) {\n                          return typeof col.options[key].value !== 'undefined'\n                            ? col.options[key].value\n                            : key;\n                        }\n                      }\n                      return null;\n                    })(),\n                  class: 'small',\n                })\n                .appendTo($cell);\n              break;\n\n            case 'time':\n              Craft.ui\n                .createTimeInput({\n                  name: name,\n                  value: value,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'email':\n            case 'url':\n              Craft.ui\n                .createTextInput({\n                  name: name,\n                  value: value,\n                  type: col.type,\n                  placeholder: col.placeholder || null,\n                })\n                .appendTo($cell);\n              break;\n\n            default:\n              $('<textarea/>', {\n                name: name,\n                rows: col.rows || 1,\n                val: value,\n                placeholder: col.placeholder,\n              }).appendTo($cell);\n          }\n        }\n\n        $cell.appendTo($tr);\n      }\n\n      if (allowReorder) {\n        $('<td/>', {\n          class: 'thin action',\n        })\n          .append(\n            $('<a/>', {\n              class: 'move icon',\n              title: Craft.t('app', 'Reorder'),\n              role: 'button',\n              type: 'button',\n            })\n          )\n          .appendTo($tr);\n      }\n\n      if (allowDelete) {\n        $('<td/>', {\n          class: 'thin action',\n        })\n          .append(\n            $('<button/>', {\n              class: 'delete icon',\n              title: Craft.t('app', 'Delete'),\n              type: 'button',\n            })\n          )\n          .appendTo($tr);\n      }\n\n      return $tr;\n    },\n  }\n);\n\n/**\n * Editable table row class\n */\nCraft.EditableTable.Row = Garnish.Base.extend(\n  {\n    table: null,\n    id: null,\n    niceTexts: null,\n\n    $tr: null,\n    $tds: null,\n    tds: null,\n    $textareas: null,\n    $deleteBtn: null,\n\n    init: function (table, tr) {\n      this.table = table;\n      this.$tr = $(tr);\n      this.$tds = this.$tr.children();\n      this.tds = [];\n      this.id = this.$tr.attr('data-id');\n\n      this.$tr.data('editable-table-row', this);\n\n      // Get the row ID, sans prefix\n      var id = parseInt(\n        this.id.substring(this.table.settings.rowIdPrefix.length)\n      );\n\n      if (id > this.table.biggestId) {\n        this.table.biggestId = id;\n      }\n\n      this.$textareas = $();\n      this.niceTexts = [];\n      var textareasByColId = {};\n\n      var i = 0;\n      var colId, col, td, $textarea, $checkbox;\n\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        col = this.table.columns[colId];\n        td = this.tds[colId] = this.$tds[i];\n\n        if (Craft.inArray(col.type, Craft.EditableTable.textualColTypes)) {\n          $textarea = $('textarea', td);\n          this.$textareas = this.$textareas.add($textarea);\n\n          this.addListener($textarea, 'focus', 'onTextareaFocus');\n          this.addListener($textarea, 'mousedown', 'ignoreNextTextareaFocus');\n\n          this.niceTexts.push(\n            new Garnish.NiceText($textarea, {\n              onHeightChange: this.onTextareaHeightChange.bind(this),\n            })\n          );\n\n          this.addListener(\n            $textarea,\n            'keypress',\n            {tdIndex: i, type: col.type},\n            'handleKeypress'\n          );\n          this.addListener(\n            $textarea,\n            'input',\n            {type: col.type},\n            'validateValue'\n          );\n          $textarea.trigger('input');\n\n          if (col.type !== 'multiline') {\n            this.addListener(\n              $textarea,\n              'paste',\n              {tdIndex: i, type: col.type},\n              'handlePaste'\n            );\n          }\n\n          textareasByColId[colId] = $textarea;\n        } else if (col.type === 'checkbox') {\n          $checkbox = $('input[type=\"checkbox\"]', td);\n\n          if (col.radioMode) {\n            if (typeof this.table.radioCheckboxes[colId] === 'undefined') {\n              this.table.radioCheckboxes[colId] = [];\n            }\n            this.table.radioCheckboxes[colId].push($checkbox[0]);\n            this.addListener(\n              $checkbox,\n              'change',\n              {colId},\n              'onRadioCheckboxChange'\n            );\n          }\n\n          if (col.toggle) {\n            this.addListener($checkbox, 'change', {colId}, function (ev) {\n              this.applyToggleCheckbox(ev.data.colId);\n            });\n          }\n        }\n\n        if (!$(td).hasClass('disabled')) {\n          this.addListener(td, 'click', {td}, function (ev) {\n            if (ev.target === ev.data.td) {\n              $(ev.data.td).find('textarea,input,select,.lightswitch').focus();\n            }\n          });\n        }\n\n        i++;\n      }\n\n      // Now that all of the text cells have been nice-ified, let's normalize the heights\n      this.onTextareaHeightChange();\n\n      // See if we need to apply any checkbox toggles now that we've indexed all the TDs\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n        col = this.table.columns[colId];\n        if (col.type === 'checkbox' && col.toggle) {\n          this.applyToggleCheckbox(colId);\n        }\n      }\n\n      // Now look for any autopopulate columns\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        col = this.table.columns[colId];\n\n        if (\n          col.autopopulate &&\n          typeof textareasByColId[col.autopopulate] !== 'undefined' &&\n          !textareasByColId[colId].val()\n        ) {\n          new Craft.HandleGenerator(\n            textareasByColId[colId],\n            textareasByColId[col.autopopulate],\n            {\n              allowNonAlphaStart: true,\n            }\n          );\n        }\n      }\n\n      var $deleteBtn = this.$tr.children().last().find('.delete');\n      this.addListener($deleteBtn, 'click', 'deleteRow');\n\n      var $inputs = this.$tr.find('input,textarea,select,.lightswitch');\n      this.addListener($inputs, 'focus', function (ev) {\n        $(ev.currentTarget).closest('td:not(.disabled)').addClass('focus');\n      });\n      this.addListener($inputs, 'blur', function (ev) {\n        $(ev.currentTarget).closest('td').removeClass('focus');\n      });\n    },\n\n    onTextareaFocus: function (ev) {\n      this.onTextareaHeightChange();\n\n      var $textarea = $(ev.currentTarget);\n\n      if ($textarea.data('ignoreNextFocus')) {\n        $textarea.data('ignoreNextFocus', false);\n        return;\n      }\n\n      window.setTimeout(function () {\n        Craft.selectFullValue($textarea);\n      }, 0);\n    },\n\n    onRadioCheckboxChange: function (ev) {\n      if (ev.currentTarget.checked) {\n        for (\n          var i = 0;\n          i < this.table.radioCheckboxes[ev.data.colId].length;\n          i++\n        ) {\n          var checkbox = this.table.radioCheckboxes[ev.data.colId][i];\n          checkbox.checked = checkbox === ev.currentTarget;\n        }\n      }\n    },\n\n    applyToggleCheckbox: function (checkboxColId) {\n      var checkboxCol = this.table.columns[checkboxColId];\n      var checked = $('input[type=\"checkbox\"]', this.tds[checkboxColId]).prop(\n        'checked'\n      );\n      var colId, colIndex, neg;\n      for (var i = 0; i < checkboxCol.toggle.length; i++) {\n        colId = checkboxCol.toggle[i];\n        colIndex = this.table.colum;\n        neg = colId[0] === '!';\n        if (neg) {\n          colId = colId.substring(1);\n        }\n        if ((checked && !neg) || (!checked && neg)) {\n          $(this.tds[colId])\n            .removeClass('disabled')\n            .find('textarea, input')\n            .prop('disabled', false);\n        } else {\n          $(this.tds[colId])\n            .addClass('disabled')\n            .find('textarea, input')\n            .prop('disabled', true);\n        }\n      }\n    },\n\n    ignoreNextTextareaFocus: function (ev) {\n      $.data(ev.currentTarget, 'ignoreNextFocus', true);\n    },\n\n    handleKeypress: function (ev) {\n      var keyCode = ev.keyCode ? ev.keyCode : ev.charCode;\n      var ctrl = Garnish.isCtrlKeyPressed(ev);\n\n      // Going to the next/previous row?\n      if (\n        keyCode === Garnish.RETURN_KEY &&\n        (ev.data.type !== 'multiline' || ctrl)\n      ) {\n        ev.preventDefault();\n        if (ev.shiftKey) {\n          this.table.focusOnPrevRow(\n            this.$tr,\n            ev.data.tdIndex,\n            ev.currentTarget\n          );\n        } else {\n          this.table.focusOnNextRow(\n            this.$tr,\n            ev.data.tdIndex,\n            ev.currentTarget\n          );\n        }\n        return;\n      }\n    },\n\n    handlePaste: function (ev) {\n      let data = Craft.trim(\n        ev.originalEvent.clipboardData.getData('Text'),\n        ' \\n\\r'\n      );\n      if (!data.match(/[\\t\\r\\n]/)) {\n        return;\n      }\n      ev.preventDefault();\n      this.table.importData(data, this, ev.data.tdIndex);\n    },\n\n    validateValue: function (ev) {\n      if (ev.data.type === 'multiline') {\n        return;\n      }\n\n      if (ev.data.type === 'number') {\n        Craft.filterNumberInputVal(ev.currentTarget);\n        return;\n      }\n\n      // Strip any newlines\n      const safeValue = ev.currentTarget.value.replace(/[\\r\\n]/g, '');\n      if (safeValue !== ev.currentTarget.value) {\n        ev.currentTarget.value = safeValue;\n      }\n    },\n\n    onTextareaHeightChange: function () {\n      // Keep all the textareas' heights in sync\n      var tallestTextareaHeight = -1;\n\n      for (var i = 0; i < this.niceTexts.length; i++) {\n        if (this.niceTexts[i].height > tallestTextareaHeight) {\n          tallestTextareaHeight = this.niceTexts[i].height;\n        }\n      }\n\n      this.$textareas.css('min-height', tallestTextareaHeight);\n\n      // If the <td> is still taller, go with that instead\n      var tdHeight = this.$textareas\n        .filter(':visible')\n        .first()\n        .parent()\n        .height();\n\n      if (tdHeight > tallestTextareaHeight) {\n        this.$textareas.css('min-height', tdHeight);\n      }\n    },\n\n    deleteRow: function () {\n      this.table.deleteRow(this);\n    },\n  },\n  {\n    /** @deprecated */\n    numericKeyCodes: [\n      9 /* (tab) */, 8 /* (delete) */, 37, 38, 39, 40 /* (arrows) */, 45,\n      91 /* (minus) */, 46, 190 /* period */, 48, 49, 50, 51, 52, 53, 54, 55,\n      56, 57 /* (0-9) */,\n    ],\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Action Trigger\n */\nCraft.ElementActionTrigger = Garnish.Base.extend(\n  {\n    maxLevels: null,\n    newChildUrl: null,\n    $trigger: null,\n    $selectedItems: null,\n    triggerEnabled: true,\n\n    init: function (settings) {\n      if (!$.isPlainObject(settings)) {\n        settings = {};\n      }\n\n      // batch => bulk\n      if (typeof settings.batch !== 'undefined') {\n        settings.bulk = settings.batch;\n        delete settings.batch;\n      }\n      Object.defineProperty(settings, 'batch', {\n        get() {\n          return this.bulk;\n        },\n        set(v) {\n          this.bulk = v;\n        },\n      });\n\n      this.setSettings(settings, Craft.ElementActionTrigger.defaults);\n\n      this.$trigger = $(\n        '#' + settings.type.replace(/[\\[\\]\\\\]+/g, '-') + '-actiontrigger'\n      );\n\n      // Do we have a custom handler?\n      if (this.settings.activate) {\n        // Prevent the element index's click handler\n        this.$trigger.data('custom-handler', true);\n\n        // Is this a custom trigger?\n        if (this.$trigger.prop('nodeName') === 'FORM') {\n          this.addListener(this.$trigger, 'submit', 'handleTriggerActivation');\n        } else {\n          this.addListener(\n            this.$trigger,\n            'activate',\n            'handleTriggerActivation'\n          );\n        }\n      }\n\n      this.updateTrigger();\n      Craft.elementIndex.on('selectionChange', this.updateTrigger.bind(this));\n    },\n\n    updateTrigger: function () {\n      // Ignore if the last element was just unselected\n      if (Craft.elementIndex.getSelectedElements().length === 0) {\n        return;\n      }\n\n      if (this.validateSelection()) {\n        this.enableTrigger();\n      } else {\n        this.disableTrigger();\n      }\n    },\n\n    /**\n     * Determines if this action can be performed on the currently selected elements.\n     *\n     * @returns {boolean}\n     */\n    validateSelection: function () {\n      this.$selectedItems = Craft.elementIndex.getSelectedElements();\n\n      if (!this.settings.bulk && this.$selectedItems.length > 1) {\n        return false;\n      }\n\n      if (this.settings.requireId && this.$selectedItems.is('[data-id=\"\"]')) {\n        return false;\n      }\n\n      if (typeof this.settings.validateSelection === 'function') {\n        return this.settings.validateSelection(this.$selectedItems);\n      }\n\n      return true;\n    },\n\n    enableTrigger: function () {\n      if (this.triggerEnabled) {\n        return;\n      }\n\n      this.$trigger.removeClass('disabled').removeAttr('aria-disabled');\n      this.triggerEnabled = true;\n    },\n\n    disableTrigger: function () {\n      if (!this.triggerEnabled) {\n        return;\n      }\n\n      this.$trigger.addClass('disabled').attr('aria-disabled', 'true');\n      this.triggerEnabled = false;\n    },\n\n    handleTriggerActivation: function () {\n      if (this.triggerEnabled) {\n        this.settings.activate(this.$selectedItems);\n      }\n    },\n  },\n  {\n    defaults: {\n      type: null,\n      bulk: true,\n      requireId: true,\n      validateSelection: null,\n      activate: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Element Editor\n */\nCraft.ElementEditor = Garnish.Base.extend(\n  {\n    isFullPage: null,\n    $container: null,\n    $tabContainer: null,\n    $contentContainer: null,\n    $revisionBtn: null,\n    $revisionLabel: null,\n    $spinner: null,\n    $expandSiteStatusesBtn: null,\n    $statusIcon: null,\n    $previewBtn: null,\n\n    $editMetaBtn: null,\n    metaHud: null,\n    $nameTextInput: null,\n    $saveMetaBtn: null,\n\n    $siteStatusPane: null,\n    $globalLightswitch: null,\n    $siteLightswitches: null,\n    $additionalSiteField: null,\n\n    siteIds: null,\n    newSiteIds: null,\n\n    enableAutosave: null,\n    lastSerializedValue: null,\n    listeningForChanges: false,\n    pauseLevel: 0,\n    timeout: null,\n    cancelToken: null,\n    ignoreFailedRequest: false,\n    queue: null,\n    submittingForm: false,\n\n    duplicatedElements: null,\n    failed: false,\n    httpStatus: null,\n    httpError: null,\n\n    openingPreview: false,\n    preview: null,\n    activatedPreviewToken: false,\n    previewTokenQueue: null,\n    previewLinks: null,\n    scrollY: null,\n\n    hiddenTipsStorageKey: 'Craft-' + Craft.systemUid + '.TipField.hiddenTips',\n\n    get tipDismissBtn() {\n      return this.$container.find('.tip-dismiss-btn');\n    },\n\n    get slideout() {\n      return this.$container.data('slideout');\n    },\n\n    init: function (container, settings) {\n      this.$container = $(container);\n\n      if (this.$container.prop('tagName') !== 'FORM') {\n        throw 'Element editors may only be used with forms.';\n      }\n\n      if (this.$container.data('elementEditor')) {\n        console.warn('Double-instantiating an element editor on an element.');\n        this.$container.data('elementEditor').destroy();\n      }\n\n      this.$container.data('elementEditor', this);\n      this.$container.attr('data-element-editor', '');\n\n      this.setSettings(settings, Craft.ElementEditor.defaults);\n\n      this.isFullPage = this.$container[0] === Craft.cp.$primaryForm[0];\n\n      if (this.isFullPage) {\n        this.$tabContainer = $('#tabs');\n        this.$contentContainer = $('#content');\n      } else {\n        this.$tabContainer = this.slideout.$tabContainer;\n        this.$contentContainer = this.slideout.$content;\n      }\n\n      this.queue = this._createQueue();\n      this.previewTokenQueue = this._createQueue();\n\n      this.duplicatedElements = {};\n      this.enableAutosave = Craft.autosaveDrafts;\n      this.previewLinks = [];\n\n      this.siteIds = Object.keys(this.settings.siteStatuses).map((siteId) => {\n        return parseInt(siteId);\n      });\n\n      this.$revisionBtn = this.$container.find('.context-btn');\n      this.$revisionLabel = this.$container.find('.revision-label');\n      this.$previewBtn = this.$container.find('.preview-btn');\n\n      const $spinnerContainer = this.isFullPage\n        ? $('#page-title')\n        : this.slideout.$toolbar;\n      this.$spinner = $('<div/>', {\n        class: 'revision-spinner spinner hidden',\n        title: Craft.t('app', 'Saving'),\n      }).appendTo($spinnerContainer);\n      this.$statusIcon = $('<div/>', {\n        class: `revision-status ${this.isFullPage ? 'invisible' : 'hidden'}`,\n      }).appendTo($spinnerContainer);\n      this.$statusMessage = $('<div/>', {\n        class: 'revision-status-message visually-hidden',\n        'aria-live': 'polite',\n      }).appendTo($spinnerContainer);\n\n      this.$expandSiteStatusesBtn = $('.expand-status-btn');\n\n      if (this.settings.canEditMultipleSites) {\n        this.addListener(\n          this.$expandSiteStatusesBtn,\n          'click',\n          'expandSiteStatuses'\n        );\n      }\n\n      if (this.settings.previewTargets.length && this.isFullPage) {\n        if (this.settings.enablePreview) {\n          this.addListener(this.$previewBtn, 'click', 'openPreview');\n        }\n\n        const $previewBtnContainer = this.$container.find(\n          '.preview-btn-container'\n        );\n\n        if (this.settings.previewTargets.length === 1) {\n          const [target] = this.settings.previewTargets;\n          this.createPreviewLink(target)\n            .addClass('view-btn btn')\n            .attr('aria-label', Craft.t('app', 'View'))\n            .appendTo($previewBtnContainer);\n        } else {\n          this.createShareMenu($previewBtnContainer);\n        }\n      }\n\n      // If this is a revision, we're done here\n      if (this.settings.revisionId) {\n        return;\n      }\n\n      // Override the serializer to use our own\n      this.$container.data('serializer', () => this.serializeForm(true));\n      this.$container.data('initialSerializedValue', this.serializeForm(true));\n\n      if (this.isFullPage) {\n        this.addListener(this.$container, 'submit', 'handleSubmit');\n      }\n\n      if (this.settings.isProvisionalDraft) {\n        this.initForProvisionalDraft();\n      } else if (this.settings.draftId && !this.settings.isUnpublishedDraft) {\n        this.initForDraft();\n      } else if (!this.settings.canSaveCanonical) {\n        // Override the save shortcut to create a draft too\n        this.addListener(this.$container, 'submit.saveShortcut', (ev) => {\n          if (ev.saveShortcut) {\n            ev.preventDefault();\n            this.createDraft();\n            this.removeListener(this.$container, 'submit.saveShortcut');\n          }\n        });\n      }\n\n      this.listenForChanges();\n\n      this.addListener(this.$statusIcon, 'click', () => {\n        this.showStatusHud(this.$statusIcon);\n      });\n\n      // handle closing tips\n      this.handleDismissibleTips();\n\n      if (this.isFullPage && Craft.messageReceiver) {\n        // Listen on Craft.broadcaster to ignore any messages sent by this very page\n        Craft.broadcaster.addEventListener('message', (ev) => {\n          if (\n            (ev.data.event === 'saveDraft' &&\n              ev.data.canonicalId === this.settings.canonicalId &&\n              (ev.data.draftId === this.settings.draftId ||\n                (ev.data.isProvisionalDraft && !this.settings.draftId))) ||\n            (ev.data.event === 'saveElement' &&\n              ev.data.id === this.settings.canonicalId &&\n              !this.settings.draftId)\n          ) {\n            Craft.setLocalStorage('scrollY', window.scrollY);\n            window.location.reload();\n          } else if (\n            ev.data.event === 'deleteDraft' &&\n            ev.data.canonicalId === this.settings.canonicalId &&\n            ev.data.draftId === this.settings.draftId\n          ) {\n            const url = new URL(window.location.href);\n            url.searchParams.delete('draftId');\n            if (url.href !== document.location.href) {\n              window.location.href = url;\n            } else {\n              Craft.setLocalStorage('scrollY', window.scrollY);\n              window.location.reload();\n            }\n          }\n        });\n      }\n    },\n\n    _createQueue: function () {\n      const queue = new Craft.Queue();\n      queue.on('beforeRun', () => {\n        this.showSpinner();\n      });\n      queue.on('afterRun', () => {\n        this.hideSpinner();\n      });\n      return queue;\n    },\n\n    get namespace() {\n      if (this.isFullPage) {\n        return null;\n      }\n\n      return this.slideout.namespace;\n    },\n\n    namespaceInputName(name) {\n      return Craft.namespaceInputName(name, this.namespace);\n    },\n\n    namespaceId(id) {\n      return Craft.namespaceId(id, this.namespace);\n    },\n\n    listenForChanges: function () {\n      if (\n        this.listeningForChanges ||\n        this.pauseLevel > 0 ||\n        !this.enableAutosave ||\n        !this.settings.canCreateDrafts\n      ) {\n        return;\n      }\n\n      this.listeningForChanges = true;\n\n      // Listen for events on the body when editing a full page form, so we don’t miss events from Live Preview\n      const $target = this.isFullPage ? Garnish.$bod : this.$container;\n\n      this.addListener(\n        $target,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup',\n        (ev) => {\n          if ($(ev.target).is(this.statusIcons())) {\n            return;\n          }\n          clearTimeout(this.timeout);\n          // If they are typing, wait half a second before checking the form\n          if (['keypress', 'keyup', 'change'].includes(ev.type)) {\n            this.timeout = setTimeout(this.checkForm.bind(this), 500);\n          } else {\n            this.checkForm();\n          }\n        }\n      );\n    },\n\n    stopListeningForChanges: function () {\n      if (!this.listeningForChanges) {\n        return;\n      }\n\n      this.removeListener(\n        Garnish.$bod,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup'\n      );\n      clearTimeout(this.timeout);\n      this.listeningForChanges = false;\n    },\n\n    pause: function () {\n      this.pauseLevel++;\n      this.stopListeningForChanges();\n    },\n\n    resume: function () {\n      if (this.pauseLevel === 0) {\n        throw 'Craft.ElementEditor::resume() should only be called after pause().';\n      }\n\n      // Only actually resume operation if this has been called the same\n      // number of times that pause() was called\n      this.pauseLevel--;\n      if (this.pauseLevel === 0) {\n        if (this.enableAutosave) {\n          this.checkForm();\n          this.listenForChanges();\n        }\n      }\n    },\n\n    initForProvisionalDraft: function () {\n      let $discardButton = this.$container.find('.discard-changes-btn');\n\n      if (!$discardButton.length) {\n        let initialHeight, scrollTop;\n\n        let $noticeContainer;\n        if (this.isFullPage) {\n          initialHeight = $('#content').height();\n          scrollTop = Garnish.$win.scrollTop();\n          $noticeContainer = Craft.cp.$noticeContainer;\n        } else {\n          $noticeContainer = this.$container.find('.so-notice');\n        }\n\n        const $notice = $('<div/>', {\n          class: 'draft-notice',\n        })\n          .append(\n            $('<div/>', {\n              class: 'draft-icon',\n              'aria-hidden': 'true',\n              'data-icon': 'edit',\n            })\n          )\n          .append(\n            $('<p/>', {\n              text: Craft.t('app', 'Showing your unsaved changes.'),\n            })\n          )\n          .appendTo($noticeContainer);\n\n        $discardButton = $('<button/>', {\n          type: 'button',\n          class: 'discard-changes-btn btn',\n          text: Craft.t('app', 'Discard'),\n        }).appendTo($notice);\n\n        if (this.isFullPage) {\n          const heightDiff = $('#content').height() - initialHeight;\n          Garnish.$win.scrollTop(scrollTop + heightDiff);\n\n          // If there isn’t enough content to simulate the same scroll position, slide it down instead\n          if (Garnish.$win.scrollTop() === scrollTop) {\n            // Disable pointer events until half a second after the animation is complete\n            Craft.cp.$contentContainer.css('pointer-events', 'none');\n\n            $('#content-header').css('min-height', 'auto');\n            const height = $noticeContainer.height();\n            $noticeContainer\n              .css({height: height - heightDiff, overflow: 'hidden'})\n              .velocity({height: height}, 'fast', () => {\n                $('#content-header').css('min-height', '');\n                $noticeContainer.css({height: '', overflow: ''});\n\n                setTimeout(() => {\n                  Craft.cp.$contentContainer.css('pointer-events', '');\n                }, 300);\n              });\n          }\n        }\n      }\n\n      this.addListener(\n        $discardButton,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup',\n        (ev) => {\n          ev.stopPropagation();\n        }\n      );\n\n      this.addListener($discardButton, 'click', () => {\n        if (\n          confirm(\n            Craft.t('app', 'Are you sure you want to discard your changes?')\n          )\n        ) {\n          this.queue.unshift(\n            () =>\n              new Promise((resolve, reject) => {\n                if (this.isFullPage) {\n                  Craft.submitForm(this.$container, {\n                    action: 'elements/delete-draft',\n                    redirect: this.settings.hashedCpEditUrl,\n                    params: {\n                      draftId: this.settings.draftId,\n                      provisional: 1,\n                    },\n                  });\n                } else {\n                  Craft.sendActionRequest('POST', 'elements/delete-draft', {\n                    data: {\n                      elementId: this.settings.canonicalId,\n                      draftId: this.settings.draftId,\n                      provisional: 1,\n                    },\n                  })\n                    .then((response) => {\n                      Craft.cp.displaySuccess(response.data.message);\n                      this.slideout.close();\n                    })\n                    .catch(reject);\n                }\n              })\n          );\n        }\n      });\n    },\n\n    initForDraft: function () {\n      // Create the edit draft button\n      this.createEditMetaBtn();\n\n      if (this.settings.canSaveCanonical) {\n        Garnish.uiLayerManager.registerShortcut(\n          {\n            keyCode: Garnish.S_KEY,\n            ctrl: true,\n            alt: true,\n          },\n          () => {\n            Craft.submitForm(this.$container, {\n              action: 'elements/apply-draft',\n              redirect: this.settings.hashedCpEditUrl,\n            });\n          },\n          0\n        );\n      }\n    },\n\n    expandSiteStatuses: function () {\n      this.removeListener(this.$expandSiteStatusesBtn, 'click');\n      this.$expandSiteStatusesBtn.velocity({opacity: 0}, 'fast', () => {\n        this.$expandSiteStatusesBtn.remove();\n      });\n\n      const $enabledForSiteField = this.$container.find(\n        `.enabled-for-site-${this.settings.siteId}-field`\n      );\n      this.$siteStatusPane = $enabledForSiteField.parent();\n\n      // If this is a revision, just show the site statuses statically and be done\n      if (this.settings.revisionId) {\n        this._getOtherSupportedSites().forEach((s) =>\n          this._createSiteStatusField(s)\n        );\n        return;\n      }\n\n      $enabledForSiteField.addClass('nested');\n      const $globalField = Craft.ui\n        .createLightswitchField({\n          label: Craft.t('app', 'Enabled for all sites'),\n          name: this.namespaceInputName('enabled'),\n        })\n        .insertBefore($enabledForSiteField);\n      $globalField.find('label').css('font-weight', 'bold');\n      this.$globalLightswitch = $globalField.find('.lightswitch');\n\n      if (!this.settings.revisionId) {\n        this._showField($globalField);\n      }\n\n      // Figure out what the \"Enabled everywhere\" lightswitch would have been set to when the page first loaded\n      const siteStatusValues = Object.values(this.settings.siteStatuses);\n      const hasEnabled = siteStatusValues.includes(true);\n      const hasDisabled = siteStatusValues.includes(false);\n      const originalEnabledValue =\n        hasEnabled && hasDisabled ? '-' : hasEnabled ? '1' : '';\n      const originalSerializedStatus =\n        encodeURIComponent(\n          this.namespaceInputName(`enabledForSite[${this.settings.siteId}]`)\n        ) +\n        '=' +\n        (this.settings.enabledForSite ? '1' : '');\n\n      this.$siteLightswitches = $enabledForSiteField\n        .find('.lightswitch')\n        .on('change', this._updateGlobalStatus.bind(this));\n\n      this._getOtherSupportedSites().forEach((s) =>\n        this._createSiteStatusField(s)\n      );\n\n      let serializedStatuses =\n        encodeURIComponent(this.namespaceInputName('enabled')) +\n        `=${originalEnabledValue}`;\n      for (let i = 0; i < this.$siteLightswitches.length; i++) {\n        const $input = this.$siteLightswitches.eq(i).data('lightswitch').$input;\n        serializedStatuses +=\n          '&' + encodeURIComponent($input.attr('name')) + '=' + $input.val();\n      }\n\n      this.$container.data(\n        'initialSerializedValue',\n        this.$container\n          .data('initialSerializedValue')\n          .replace(originalSerializedStatus, serializedStatuses)\n      );\n\n      if (this.lastSerializedValue) {\n        this.lastSerializedValue = this.lastSerializedValue.replace(\n          originalSerializedStatus,\n          serializedStatuses\n        );\n      }\n\n      // Are there additional sites that can be added?\n      if (\n        this.settings.additionalSites &&\n        this.settings.additionalSites.length &&\n        this.isFullPage\n      ) {\n        this._createAddlSiteField();\n      }\n\n      // Focus on first lightswitch\n      this.$globalLightswitch.focus();\n\n      this.$globalLightswitch.on('change', this._updateSiteStatuses.bind(this));\n      this._updateGlobalStatus();\n    },\n\n    /**\n     * @returns {Array}\n     */\n    _getOtherSupportedSites: function () {\n      return Craft.sites.filter(\n        (s) => s.id != this.settings.siteId && this.siteIds.includes(s.id)\n      );\n    },\n\n    _showField: function ($field) {\n      const height = $field.height();\n      $field\n        .css({\n          overflow: 'hidden',\n          'min-height': 'auto',\n        })\n        .height(0)\n        .velocity({height}, 'fast', () => {\n          $field.css({\n            overflow: '',\n            height: '',\n            'min-height': '',\n          });\n        });\n    },\n\n    _removeField: function ($field) {\n      $field\n        .css({\n          overflow: 'hidden',\n          'min-height': 'auto',\n        })\n        .velocity({height: 0}, 'fast', () => {\n          $field.remove();\n        });\n    },\n\n    _updateGlobalStatus: function () {\n      let allEnabled = true,\n        allDisabled = true;\n      this.$siteLightswitches.each(function () {\n        const enabled = $(this).data('lightswitch').on;\n        if (enabled) {\n          allDisabled = false;\n        } else {\n          allEnabled = false;\n        }\n        if (!allEnabled && !allDisabled) {\n          return false;\n        }\n      });\n      if (allEnabled) {\n        this.$globalLightswitch.data('lightswitch').turnOn(true);\n      } else if (allDisabled) {\n        this.$globalLightswitch.data('lightswitch').turnOff(true);\n      } else {\n        this.$globalLightswitch.data('lightswitch').turnIndeterminate(true);\n      }\n    },\n\n    _updateSiteStatuses: function () {\n      const enabled = this.$globalLightswitch.data('lightswitch').on;\n      this.$siteLightswitches.each(function () {\n        if (enabled) {\n          $(this).data('lightswitch').turnOn(true);\n        } else {\n          $(this).data('lightswitch').turnOff(true);\n        }\n      });\n    },\n\n    _createSiteStatusField: function (site, status) {\n      const $field = Craft.ui.createLightswitchField({\n        fieldClass: `enabled-for-site-${site.id}-field`,\n        label: site.name,\n        name: this.namespaceInputName(`enabledForSite[${site.id}]`),\n        on:\n          typeof status != 'undefined'\n            ? status\n            : this.settings.siteStatuses.hasOwnProperty(site.id)\n            ? this.settings.siteStatuses[site.id]\n            : true,\n        disabled: !!this.settings.revisionId,\n      });\n\n      if (this.$additionalSiteField) {\n        $field.insertBefore(this.$additionalSiteField);\n      } else {\n        $field.appendTo(this.$siteStatusPane);\n      }\n\n      if (!this.settings.revisionId) {\n        $field.addClass('nested');\n        const $lightswitch = $field\n          .find('.lightswitch')\n          .on('change', this._updateGlobalStatus.bind(this));\n        this.$siteLightswitches = this.$siteLightswitches.add($lightswitch);\n      }\n\n      this._showField($field);\n\n      return $field;\n    },\n\n    _createAddlSiteField: function () {\n      const additionalSites = Craft.sites.filter((site) => {\n        return (\n          !this.siteIds.includes(site.id) &&\n          this.settings.additionalSites.some((s) => s.siteId == site.id)\n        );\n      });\n\n      if (!additionalSites.length) {\n        return;\n      }\n\n      const selectLabelId = 'add-site-label';\n\n      const $addlSiteSelectLabel = $('<span/>', {\n        text: Craft.t('app', 'Add a site...'),\n        class: 'visually-hidden',\n        id: selectLabelId,\n      });\n\n      const $addlSiteSelectContainer = Craft.ui\n        .createSelect({\n          options: [\n            {label: Craft.t('app', 'Add a site…')},\n            ...additionalSites.map((s) => {\n              return {label: s.name, value: s.id};\n            }),\n          ],\n          labelledBy: selectLabelId,\n        })\n        .addClass('fullwidth');\n\n      this.$additionalSiteField = Craft.ui\n        .createField($addlSiteSelectContainer, {})\n        .addClass('nested add')\n        .appendTo(this.$siteStatusPane);\n\n      $addlSiteSelectLabel.prependTo(this.$additionalSiteField);\n\n      const $addlSiteSelect = $addlSiteSelectContainer.find('select');\n\n      $addlSiteSelect.on('change', () => {\n        const siteId = parseInt($addlSiteSelect.val());\n        const site = Craft.sites.find((s) => s.id === siteId);\n\n        if (!site) {\n          return;\n        }\n\n        const addlSiteInfo = this.settings.additionalSites.find(\n          (s) => s.siteId == site.id\n        );\n        this._createSiteStatusField(site, addlSiteInfo.enabledByDefault);\n        this._updateGlobalStatus();\n\n        $addlSiteSelect.val('').find(`option[value=\"${siteId}\"]`).remove();\n\n        if (this.newSiteIds === null) {\n          this.newSiteIds = [];\n        }\n\n        this.siteIds.push(siteId);\n        this.newSiteIds.push(siteId);\n\n        // Was that the last site?\n        if ($addlSiteSelect.find('option').length === 1) {\n          this._removeField(this.$additionalSiteField);\n        }\n      });\n\n      this._showField(this.$additionalSiteField);\n    },\n\n    showStatusHud: function (target) {\n      let bodyHtml;\n\n      if (!this.failed) {\n        bodyHtml = `<p>${this._saveSuccessMessage()}</p>`;\n      } else {\n        bodyHtml = `<p class=\"error\"><strong>${this._saveFailMessage()}</strong></p>`;\n\n        if (this.httpError) {\n          bodyHtml += `<p class=\"http-error code\">${Craft.escapeHtml(\n            this.httpError\n          )}</p>`;\n        }\n\n        if (this.httpStatus === 400) {\n          bodyHtml += `<button class=\"btn refresh-btn\">${Craft.t(\n            'app',\n            'Refresh'\n          )}</button>`;\n        }\n      }\n\n      const hud = new Garnish.HUD(target, bodyHtml, {\n        hudClass: 'hud revision-status-hud',\n        onHide: function () {\n          hud.destroy();\n        },\n      });\n\n      hud.$mainContainer.find('.refresh-btn').on('click', () => {\n        window.location.reload();\n      });\n    },\n\n    /**\n     * @returns {string}\n     */\n    _saveSuccessMessage: function () {\n      return this.settings.isProvisionalDraft ||\n        this.settings.isUnpublishedDraft\n        ? Craft.t('app', 'Your changes have been stored.')\n        : Craft.t('app', 'The draft has been saved.');\n    },\n\n    /**\n     * @returns {string}\n     */\n    _saveFailMessage: function () {\n      return this.settings.isProvisionalDraft ||\n        this.settings.isUnpublishedDraft\n        ? Craft.t('app', 'Your changes could not be stored.')\n        : Craft.t('app', 'The draft could not be saved.');\n    },\n\n    spinners: function () {\n      return this.preview\n        ? this.$spinner.add(this.preview.$spinner)\n        : this.$spinner;\n    },\n\n    showSpinner: function () {\n      this.spinners().removeClass('hidden');\n    },\n\n    hideSpinner: function () {\n      this.spinners().addClass('hidden');\n    },\n\n    statusIcons: function () {\n      return this.preview\n        ? this.$statusIcon.add(this.preview.$statusIcon)\n        : this.$statusIcon;\n    },\n\n    statusMessage: function () {\n      return this.preview\n        ? this.$statusMessage.add(this.preview.$statusMessage)\n        : this.$statusMessage;\n    },\n\n    createEditMetaBtn: function () {\n      const $btnGroup = this.$container.find('.context-btngroup');\n      this.$editMetaBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn edit icon',\n        'aria-expanded': 'false',\n        'aria-label': Craft.t('app', 'Edit draft settings'),\n        title: Craft.t('app', 'Edit draft settings'),\n      }).appendTo($btnGroup);\n      $btnGroup.find('.btngroup-btn-last').removeClass('btngroup-btn-last');\n      this.addListener(this.$editMetaBtn, 'click', 'showMetaHud');\n    },\n\n    createPreviewLink: function (target, label) {\n      const $a = $('<a/>', {\n        href: this.getTokenizedPreviewUrl(target.url, null, false),\n        text: label || Craft.t('app', 'View'),\n        target: '_blank',\n        data: {\n          targetUrl: target.url,\n          targetLabel: target.label,\n        },\n      });\n\n      this.addListener($a, 'click', () => {\n        setTimeout(() => {\n          this.activatePreviewToken();\n        }, 1);\n      });\n\n      this.previewLinks.push($a);\n      return $a;\n    },\n\n    updatePreviewLinks: function () {\n      this.previewLinks.forEach(($a) => {\n        this.updatePreviewLinkHref($a);\n        if (this.activatedPreviewToken) {\n          this.removeListener($a, 'click');\n        }\n      });\n    },\n\n    updatePreviewLinkHref: function ($a) {\n      $a.attr(\n        'href',\n        this.getTokenizedPreviewUrl($a.data('targetUrl'), null, false)\n      );\n    },\n\n    activatePreviewToken: function () {\n      if (this.settings.isLive) {\n        // don't do anything yet, but leave the event in case we need it later\n        return;\n      }\n\n      this.activatedPreviewToken = true;\n      this.updatePreviewLinks();\n    },\n\n    createShareMenu: function ($container) {\n      const $btn = $('<button/>', {\n        type: 'button',\n        class: 'view-btn btn menubtn',\n        text: Craft.t('app', 'View'),\n      }).appendTo($container);\n\n      const $menu = $('<div/>', {class: 'menu'}).appendTo($container);\n      const $ul = $('<ul/>').appendTo($menu);\n\n      this.settings.previewTargets.forEach((target) => {\n        $('<li/>')\n          .append(this.createPreviewLink(target, target.label))\n          .appendTo($ul);\n      });\n\n      new Garnish.MenuBtn($btn);\n    },\n\n    getPreviewTokenParams: function () {\n      const params = {\n        elementType: this.settings.elementType,\n        canonicalId: this.settings.canonicalId,\n        siteId: this.settings.siteId,\n        revisionId: this.settings.revisionId,\n        previewToken: this.settings.previewToken,\n      };\n\n      if (this.settings.draftId && !this.settings.isProvisionalDraft) {\n        params.draftId = this.settings.draftId;\n      }\n\n      return params;\n    },\n\n    getPreviewToken: function () {\n      return this.previewTokenQueue.push(() => {\n        return new Promise((resolve, reject) => {\n          if (this.activatedPreviewToken) {\n            resolve(this.settings.previewToken);\n            return;\n          }\n\n          Craft.sendActionRequest('POST', 'preview/create-token', {\n            data: this.getPreviewTokenParams(),\n          })\n            .then(() => {\n              this.activatePreviewToken();\n              resolve(this.settings.previewToken);\n            })\n            .catch(reject);\n        });\n      });\n    },\n\n    /**\n     * @param {string} url\n     * @param {?string} [randoParam]\n     * @param {boolean} [asPromise=false]\n     * @returns {(Promise|string)}\n     */\n    getTokenizedPreviewUrl: function (url, randoParam, asPromise) {\n      if (typeof asPromise === 'undefined') {\n        asPromise = true;\n      }\n\n      const params = {};\n\n      if (randoParam || !this.settings.isLive) {\n        // Randomize the URL so CDNs don't return cached pages\n        params[randoParam || 'x-craft-preview'] = Craft.randomString(10);\n      }\n\n      if (this.settings.siteToken) {\n        params[Craft.siteToken] = this.settings.siteToken;\n      }\n\n      // No need for a token if we're looking at a live element\n      if (this.settings.isLive) {\n        const previewUrl = Craft.getUrl(url, params);\n\n        if (asPromise) {\n          return new Promise((resolve) => {\n            resolve(previewUrl);\n          });\n        }\n\n        return previewUrl;\n      }\n\n      if (!this.settings.previewToken) {\n        throw 'Missing preview token';\n      }\n\n      params[Craft.tokenParam] = this.settings.previewToken;\n      const previewUrl = Craft.getUrl(url, params);\n\n      if (this.activatedPreviewToken) {\n        if (asPromise) {\n          return new Promise((resolve) => {\n            resolve(previewUrl);\n          });\n        }\n\n        return previewUrl;\n      }\n\n      if (asPromise) {\n        return new Promise((resolve, reject) => {\n          this.getPreviewToken()\n            .then(() => {\n              resolve(previewUrl);\n            })\n            .catch(reject);\n        });\n      }\n\n      const createTokenParams = this.getPreviewTokenParams();\n      createTokenParams.redirect = previewUrl;\n      return Craft.getActionUrl('preview/create-token', createTokenParams);\n    },\n\n    getPreview: function () {\n      if (!this.preview) {\n        this.preview = new Craft.Preview(this);\n        if (!this.enableAutosave) {\n          this.preview.on('open', () => {\n            this.enableAutosave = true;\n            this.listenForChanges();\n          });\n          this.preview.on('close', () => {\n            this.enableAutosave = false;\n            this.stopListeningForChanges();\n\n            // Hide the status icon if the save was successful\n            const $statusIcons = this.statusIcons();\n            if ($statusIcons.hasClass('checkmark-icon')) {\n              $statusIcons.addClass('hidden');\n            }\n          });\n        }\n        this.preview.on('close', () => {\n          if (this.scrollY) {\n            window.scrollTo(0, this.scrollY);\n            this.scrollY = null;\n          }\n        });\n      }\n      return this.preview;\n    },\n\n    openPreview: function () {\n      if (Garnish.hasAttr(this.$previewBtn, 'aria-disabled')) {\n        return;\n      }\n\n      this.$previewBtn.attr('aria-disabled', true);\n      this.$previewBtn.addClass('loading');\n\n      this.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            this.openingPreview = true;\n            this.ensureIsDraftOrRevision(true)\n              .then(() => {\n                this.scrollY = window.scrollY;\n                this.$previewBtn.removeAttr('aria-disabled');\n                this.$previewBtn.removeClass('loading');\n                this.getPreview().open();\n                this.openingPreview = false;\n                resolve();\n              })\n              .catch(reject);\n          })\n      );\n    },\n\n    ensureIsDraftOrRevision: function (onlyIfChanged) {\n      return new Promise((resolve, reject) => {\n        if (!this.settings.draftId && !this.settings.revisionId) {\n          if (\n            onlyIfChanged &&\n            this.serializeForm(true) ===\n              this.$container.data('initialSerializedValue')\n          ) {\n            resolve();\n            return;\n          }\n\n          this.createDraft().then(resolve).catch(reject);\n        } else {\n          resolve();\n        }\n      });\n    },\n\n    serializeForm: function (removeActionParams) {\n      let data = this.$container.serialize();\n\n      if (this.isPreviewActive()) {\n        // Replace the temp input with the preview form data\n        data = data.replace(\n          '__PREVIEW_FIELDS__=1',\n          this.preview.$editor.serialize()\n        );\n      }\n\n      if (removeActionParams && !this.settings.isUnpublishedDraft) {\n        // Remove action and redirect params\n        const actionName = this.namespaceInputName('action');\n        const redirectName = this.namespaceInputName('redirect');\n        data = data.replace(\n          new RegExp(`&${Craft.escapeRegex(actionName)}=[^&]*`),\n          ''\n        );\n        data = data.replace(\n          new RegExp(`&${Craft.escapeRegex(redirectName)}=[^&]*`),\n          ''\n        );\n      }\n\n      return data;\n    },\n\n    /**\n     * @param {boolean} [force=false]\n     * @returns {Promise}\n     */\n    checkForm: function (force) {\n      return this.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            // If this isn't a draft and there's no active preview, then there's nothing to check\n            if (\n              this.settings.revisionId ||\n              this.pauseLevel > 0 ||\n              !this.enableAutosave ||\n              !this.settings.canCreateDrafts\n            ) {\n              resolve();\n              return;\n            }\n\n            clearTimeout(this.timeout);\n            this.timeout = null;\n\n            // If we haven't had a chance to fetch the initial data yet, try again in a bit\n            if (\n              typeof this.$container.data('initialSerializedValue') ===\n              'undefined'\n            ) {\n              this.timeout = setTimeout(this.checkForm.bind(this), 500);\n              return;\n            }\n\n            // Has anything changed?\n            const data = this.serializeForm(true);\n            if (\n              !force &&\n              data ===\n                (this.lastSerializedValue ||\n                  this.$container.data('initialSerializedValue'))\n            ) {\n              resolve();\n              return;\n            }\n\n            this.saveDraft(data)\n              .then(resolve)\n              .catch((e) => {\n                console.warn('Couldn’t save draft:', e);\n                reject(e);\n              });\n          })\n      );\n    },\n\n    isPreviewActive: function () {\n      return this.preview && this.preview.isActive;\n    },\n\n    createDraft: function () {\n      return this.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            this.saveDraft(this.serializeForm(true))\n              .then(resolve)\n              .catch(reject);\n          })\n      );\n    },\n\n    /**\n     * @param {Object} data\n     * @returns {Promise}\n     */\n    saveDraft: function (data) {\n      return new Promise((resolve, reject) => {\n        // Ignore if we're already submitting the main form\n        if (this.submittingForm) {\n          reject('Form already being submitted.');\n          return;\n        }\n\n        this.lastSerializedValue = data;\n        this.failed = false;\n        this.httpStatus = null;\n        this.httpError = null;\n        this.cancelToken = axios.CancelToken.source();\n\n        this.statusIcons()\n          .velocity('stop')\n          .css('opacity', '')\n          .removeClass('hidden invisible checkmark-icon alert-icon fade-out')\n          .addClass('hidden');\n\n        // Clear previous status message\n        this.statusMessage().empty();\n\n        if (this.$saveMetaBtn) {\n          this.$saveMetaBtn.addClass('active');\n        }\n\n        // Prep the data to be saved, keeping track of the first input name for each delta group\n        let modifiedFieldNames = [];\n        let preparedData = this.prepareData(\n          data,\n          !this.settings.isUnpublishedDraft\n            ? (deltaName, params) => {\n                if (params.length) {\n                  modifiedFieldNames.push(\n                    decodeURIComponent(params[0].split('=')[0])\n                  );\n                }\n              }\n            : null\n        );\n\n        const extraData = {\n          [this.namespaceInputName('visibleLayoutElements')]:\n            this.settings.visibleLayoutElements,\n        };\n\n        // Are we saving a provisional draft?\n        if (this.settings.isProvisionalDraft || !this.settings.draftId) {\n          extraData[this.namespaceInputName('provisional')] = 1;\n        }\n\n        const selectedTabId = this.$contentContainer\n          .children('[data-layout-tab]:not(.hidden)')\n          .data('id');\n        if (selectedTabId) {\n          extraData[this.namespaceInputName('selectedTab')] = selectedTabId;\n        }\n\n        preparedData += `&${$.param(extraData)}`;\n\n        Craft.sendActionRequest('POST', 'elements/save-draft', {\n          cancelToken: this.cancelToken.token,\n          headers: this._saveHeaders,\n          data: preparedData,\n        })\n          .then((response) => {\n            // capture the new selected tab ID, in case it just changed\n            const newSelectedTabId = this.$contentContainer\n              .children('[data-layout-tab]:not(.hidden)')\n              .data('id');\n\n            this._afterSaveDraft();\n\n            const createdProvisionalDraft = !this.settings.draftId;\n\n            if (createdProvisionalDraft) {\n              this.settings.isProvisionalDraft = true;\n              this.$revisionLabel.append(\n                $('<span/>', {\n                  text: ` — ${Craft.t('app', 'Edited')}`,\n                })\n              );\n            }\n\n            if (this.isFullPage) {\n              if (response.data.title) {\n                this.$container.find('.screen-title').text(response.data.title);\n              }\n\n              if (response.data.docTitle) {\n                document.title = response.data.docTitle;\n              }\n            }\n\n            if (!this.settings.isProvisionalDraft) {\n              this.$revisionLabel.text(response.data.draftName);\n              this.settings.draftName = response.data.draftName;\n            }\n\n            let revisionMenu = this.$revisionBtn.data('menubtn')\n              ? this.$revisionBtn.data('menubtn').menu\n              : null;\n\n            // Did we just add a site?\n            if (this.newSiteIds) {\n              // Do we need to create the revision menu?\n              if (!revisionMenu) {\n                this.$revisionBtn.removeClass('disabled').addClass('menubtn');\n                new Garnish.MenuBtn(this.$revisionBtn);\n                revisionMenu = this.$revisionBtn.data('menubtn').menu;\n                revisionMenu.$container.removeClass('hidden');\n              }\n              this.newSiteIds.forEach((siteId) => {\n                const $option = revisionMenu.$options.filter(\n                  `[data-site-id=${siteId}]`\n                );\n                const siteSettings = this.settings.additionalSites.find(\n                  (s) => s.siteId == siteId\n                );\n                if (\n                  !siteSettings ||\n                  typeof siteSettings.enabledByDefault === 'undefined' ||\n                  siteSettings.enabledByDefault\n                ) {\n                  $option\n                    .find('.status')\n                    .removeClass('disabled')\n                    .addClass('enabled');\n                }\n                const $li = $option.parent().removeClass('hidden');\n                $li.closest('.site-group').removeClass('hidden');\n              });\n              revisionMenu.$container\n                .find('.revision-hr')\n                .removeClass('hidden');\n              this.newSiteIds = null;\n            }\n\n            if (this.settings.isProvisionalDraft) {\n              if (createdProvisionalDraft) {\n                // Replace the action\n                this.$container\n                  .find('input.action-input')\n                  .attr('value', 'elements/apply-draft');\n\n                // Update the editor settings\n                this.settings.draftId = response.data.draftId;\n                this.settings.isLive = false;\n                this.previewToken = null;\n\n                this.initForProvisionalDraft();\n              }\n            } else if (revisionMenu) {\n              revisionMenu.$options\n                .filter('.sel')\n                .find('.draft-name')\n                .text(response.data.draftName);\n              revisionMenu.$options\n                .filter('.sel')\n                .find('.draft-meta')\n                .text(\n                  response.data.creator\n                    ? Craft.t('app', 'Saved {timestamp} by {creator}', {\n                        timestamp: response.data.timestamp,\n                        creator: response.data.creator,\n                      })\n                    : Craft.t('app', 'Saved {timestamp}', {\n                        timestamp: response.data.timestamp,\n                      })\n                );\n            }\n\n            // Did the controller send us updated preview targets?\n            if (\n              response.data.previewTargets &&\n              JSON.stringify(response.data.previewTargets) !==\n                JSON.stringify(this.settings.previewTargets)\n            ) {\n              this.updatePreviewTargets(response.data.previewTargets);\n            }\n\n            if (createdProvisionalDraft) {\n              this.updatePreviewLinks();\n              this.trigger('createProvisionalDraft');\n            }\n\n            if (this.$nameTextInput) {\n              this.checkMetaValues();\n            }\n\n            for (const oldId in response.data.duplicatedElements) {\n              if (\n                oldId != this.settings.canonicalId &&\n                response.data.duplicatedElements.hasOwnProperty(oldId)\n              ) {\n                this.duplicatedElements[oldId] =\n                  response.data.duplicatedElements[oldId];\n              }\n            }\n\n            // Add missing field modified indicators\n            const selectors = response.data.modifiedAttributes\n              .map((attr) => {\n                attr = this.namespaceInputName(attr);\n                return `[name=\"${attr}\"],[name^=\"${attr}[\"]`;\n              })\n              .concat(modifiedFieldNames.map((name) => `[name=\"${name}\"]`));\n\n            const $fields = $(selectors.join(','))\n              .parents()\n              .filter('.flex-fields > .field:not(:has(> .status-badge))');\n            for (let i = 0; i < $fields.length; i++) {\n              $fields.eq(i).prepend(\n                $('<div/>', {\n                  class: 'status-badge modified',\n                  title: Craft.t('app', 'This field has been modified.'),\n                }).append(\n                  $('<span/>', {\n                    class: 'visually-hidden',\n                    html: Craft.t('app', 'This field has been modified.'),\n                  })\n                )\n              );\n            }\n\n            // Keep track of whether anything changed while we were waiting.\n            // If not, we can safely update lastSerializedValue after swapping out the fields\n            const noChanges = this.serializeForm(true) === data;\n\n            // Update the visible elements\n            let $allTabContainers = $();\n            const visibleLayoutElements = {};\n            let changedElements = false;\n\n            for (let i = 0; i < response.data.missingElements.length; i++) {\n              const tabInfo = response.data.missingElements[i];\n              let $tabContainer = this.$contentContainer.children(\n                `[data-layout-tab=\"${tabInfo.uid}\"]`\n              );\n\n              if (!$tabContainer.length) {\n                $tabContainer = $('<div/>', {\n                  id: this.namespaceId(tabInfo.id),\n                  class: 'flex-fields',\n                  'data-id': tabInfo.id,\n                  'data-layout-tab': tabInfo.uid,\n                });\n                if (tabInfo.id !== selectedTabId) {\n                  $tabContainer.addClass('hidden');\n                }\n                $tabContainer.appendTo(this.$contentContainer);\n              }\n\n              $allTabContainers = $allTabContainers.add($tabContainer);\n\n              for (let j = 0; j < tabInfo.elements.length; j++) {\n                const elementInfo = tabInfo.elements[j];\n\n                if (elementInfo.html !== false) {\n                  if (!visibleLayoutElements[tabInfo.uid]) {\n                    visibleLayoutElements[tabInfo.uid] = [];\n                  }\n                  visibleLayoutElements[tabInfo.uid].push(elementInfo.uid);\n\n                  if (typeof elementInfo.html === 'string') {\n                    const $oldElement = $tabContainer.children(\n                      `[data-layout-element=\"${elementInfo.uid}\"]`\n                    );\n                    const $newElement = $(elementInfo.html);\n                    if ($oldElement.length) {\n                      $oldElement.replaceWith($newElement);\n                    } else {\n                      $newElement.appendTo($tabContainer);\n                    }\n                    Craft.initUiElements($newElement);\n                    changedElements = true;\n                  }\n                } else {\n                  const $oldElement = $tabContainer.children(\n                    `[data-layout-element=\"${elementInfo.uid}\"]`\n                  );\n                  if (\n                    !$oldElement.length ||\n                    !Garnish.hasAttr(\n                      $oldElement,\n                      'data-layout-element-placeholder'\n                    )\n                  ) {\n                    const $placeholder = $('<div/>', {\n                      class: 'hidden',\n                      'data-layout-element': elementInfo.uid,\n                      'data-layout-element-placeholder': '',\n                    });\n\n                    if ($oldElement.length) {\n                      $oldElement.replaceWith($placeholder);\n                    } else {\n                      $placeholder.appendTo($tabContainer);\n                    }\n\n                    changedElements = true;\n                  }\n                }\n              }\n            }\n\n            // Remove any unused tab content containers\n            // (`[data-layout-tab=\"\"]` == unconditional containers, so ignore those)\n            const $unusedTabContainers = this.$contentContainer\n              .children('[data-layout-tab]')\n              .not($allTabContainers)\n              .not('[data-layout-tab=\"\"]');\n            if ($unusedTabContainers.length) {\n              $unusedTabContainers.remove();\n              changedElements = true;\n            }\n\n            // Make the first tab visible if no others are\n            if (!$allTabContainers.filter(':not(.hidden)').length) {\n              $allTabContainers.first().removeClass('hidden');\n            }\n\n            this.settings.visibleLayoutElements = visibleLayoutElements;\n\n            // Update the tabs\n            let tabManager;\n            if (this.isFullPage) {\n              Craft.cp.updateTabs(response.data.tabs);\n              tabManager = Craft.cp.tabManager;\n            } else {\n              this.slideout.updateTabs(response.data.tabs);\n              tabManager = this.slideout.tabManager;\n            }\n\n            // was a new tab selected after the autosave request was kicked off?\n            if (\n              selectedTabId &&\n              newSelectedTabId &&\n              selectedTabId !== newSelectedTabId\n            ) {\n              const $newSelectedTab = tabManager.$tabs.filter(\n                `[data-id=\"${newSelectedTabId}\"]`\n              );\n              if ($newSelectedTab.length) {\n                // if the new tab is visible - switch to it\n                tabManager.selectTab($newSelectedTab);\n              } else {\n                // if the new tab is not visible (e.g. hidden by a condition)\n                // switch to the first tab\n                tabManager.selectTab(tabManager.$tabs.first());\n              }\n            }\n\n            Craft.appendHeadHtml(response.data.headHtml);\n            Craft.appendBodyHtml(response.data.bodyHtml);\n\n            // Did any layout elements get added or removed?\n            if (changedElements) {\n              if (response.data.initialDeltaValues) {\n                Object.assign(\n                  this.$container.data('initial-delta-values'),\n                  response.data.initialDeltaValues\n                );\n              }\n\n              if (noChanges) {\n                // Update our record of the last serialized value to avoid a pointless resave\n                this.lastSerializedValue = this.serializeForm(true);\n              }\n            }\n\n            // re-grab dismissible tips, re-attach listener, hide on re-load\n            this.handleDismissibleTips();\n\n            this.afterUpdate(data);\n\n            if (Craft.broadcaster) {\n              Craft.broadcaster.postMessage({\n                pageId: Craft.pageId,\n                event: 'saveDraft',\n                canonicalId: this.settings.canonicalId,\n                draftId: this.settings.draftId,\n                isProvisionalDraft: this.settings.isProvisionalDraft,\n              });\n            }\n\n            resolve();\n          })\n          .catch((e) => {\n            this._afterSaveDraft();\n\n            if (!this.ignoreFailedRequest) {\n              this.failed = true;\n              if (e && e.response) {\n                this.httpStatus = e.response.status;\n                this.httpError = e.response.data\n                  ? e.response.data.message\n                  : null;\n              }\n              this._showFailStatus();\n              reject(e);\n            }\n\n            this.ignoreFailedRequest = false;\n          });\n      });\n    },\n\n    _afterSaveDraft: function () {\n      if (this.$saveMetaBtn) {\n        this.$saveMetaBtn.removeClass('active');\n      }\n    },\n\n    _showFailStatus: function () {\n      this.statusIcons()\n        .velocity('stop')\n        .css('opacity', '')\n        .removeClass('hidden checkmark-icon')\n        .addClass('alert-icon');\n\n      this.setStatusMessage(this._saveFailMessage());\n    },\n\n    /**\n     * @param {string} data\n     * @param {findDeltaDataCallback} [deltaCallback] Callback function that should be passed to `Craft.findDeltaData()`\n     * @returns {string}\n     */\n    prepareData: function (data, deltaCallback) {\n      // Filter out anything that hasn't changed since the last time the form was submitted\n      data = Craft.findDeltaData(\n        this.$container.data('initialSerializedValue'),\n        data,\n        this.$container.data('delta-names'),\n        deltaCallback,\n        this.$container.data('initial-delta-values'),\n        this.$container.data('modified-delta-names')\n      );\n\n      // Swap out element IDs with their duplicated ones\n      data = this.swapDuplicatedElementIds(data);\n\n      const extraData = {};\n\n      // Add the draft info\n      if (this.settings.draftId) {\n        extraData[this.namespaceInputName('draftId')] = this.settings.draftId;\n\n        if (this.settings.isProvisionalDraft) {\n          extraData[this.namespaceInputName('provisional')] = 1;\n        }\n      }\n\n      if (this.settings.draftName !== null) {\n        extraData[this.namespaceInputName('draftName')] =\n          this.settings.draftName;\n      }\n\n      if (!$.isEmptyObject(extraData)) {\n        data += `&${$.param(extraData)}`;\n      }\n\n      return data;\n    },\n\n    get _saveHeaders() {\n      const headers = {\n        'content-type': 'application/x-www-form-urlencoded',\n      };\n\n      if (this.namespace) {\n        headers['X-Craft-Namespace'] = this.namespace;\n      }\n\n      return headers;\n    },\n\n    /**\n     * @param {string} data\n     * @returns {string}\n     */\n    swapDuplicatedElementIds: function (data) {\n      const idsRE = Object.keys(this.duplicatedElements).join('|');\n      if (idsRE === '') {\n        return data;\n      }\n      const lb = encodeURIComponent('[');\n      const rb = encodeURIComponent(']');\n      let namespacedFields = this.namespaceInputName('fields');\n\n      if (this.isFullPage) {\n        namespacedFields = Craft.escapeRegex(namespacedFields);\n      } else {\n        // don't escape namespaced input names, but URI encode them (for cases like: cnuvbcxlgq[fields])\n        namespacedFields = encodeURIComponent(namespacedFields);\n      }\n\n      // Keep replacing field IDs until data stops changing\n      while (true) {\n        if (\n          data ===\n          (data = data\n            // &fields[...][X]\n            .replace(\n              new RegExp(\n                `(&${namespacedFields}${lb}[^=]+${rb}${lb})(${idsRE})(${rb})`,\n                'g'\n              ),\n              (m, pre, id, post) => {\n                if (!this._filterFieldInputName(pre)) {\n                  return m;\n                }\n                return pre + this.duplicatedElements[id] + post;\n              }\n            )\n            // &fields[...=X\n            .replace(\n              new RegExp(`&(${namespacedFields}${lb}[^=]+)=(${idsRE})\\\\b`, 'g'),\n              (m, name, id) => {\n                // Ignore param names that end in `[enabled]`, `[type]`, etc.\n                // (`[sortOrder]` should pass here, which could be set to a specific order index, but *not* `[sortOrder][]`!)\n                if (\n                  !this._filterFieldInputName(name) ||\n                  name.match(\n                    new RegExp(`${lb}(enabled|sortOrder|type|typeId)${rb}$`)\n                  )\n                ) {\n                  return m;\n                }\n                return `&${name}=${this.duplicatedElements[id]}`;\n              }\n            ))\n        ) {\n          break;\n        }\n      }\n      return data;\n    },\n\n    _filterFieldInputName: function (name) {\n      // Find the last referenced field handle\n      const lb = encodeURIComponent('[');\n      const rb = encodeURIComponent(']');\n      const nestedNames = name.match(\n        new RegExp(`(\\\\bfields|${lb}fields${rb})${lb}.+?${rb}`, 'g')\n      );\n      if (!nestedNames) {\n        throw `Unexpected input name: ${name}`;\n      }\n      const lastHandle = nestedNames[nestedNames.length - 1].match(\n        new RegExp(`(?:\\\\bfields|${lb}fields${rb})${lb}(.+?)${rb}`)\n      )[1];\n      return Craft.fieldsWithoutContent.includes(lastHandle);\n    },\n\n    updatePreviewTargets: function (previewTargets) {\n      previewTargets.forEach((newTarget) => {\n        const currentTarget = this.settings.previewTargets.find(\n          (t) => t.label === newTarget.label\n        );\n        if (currentTarget) {\n          currentTarget.url = newTarget.url;\n        }\n\n        const $previewLink = this.previewLinks.find(\n          ($a) => $a.data('targetLabel') === newTarget.label\n        );\n        if ($previewLink) {\n          $previewLink.data('targetUrl', newTarget.url);\n          this.updatePreviewLinkHref($previewLink);\n        }\n      });\n    },\n\n    afterUpdate: function (data) {\n      this.$container.data('initialSerializedValue', data);\n      this.$container.data('initial-delta-values', {});\n\n      const $statusIcons = this.statusIcons()\n        .velocity('stop')\n        .css('opacity', '')\n        .removeClass('hidden')\n        .addClass('checkmark-icon');\n\n      this.setStatusMessage(this._saveSuccessMessage());\n\n      if (!Craft.autosaveDrafts) {\n        // Fade the icon out after a couple seconds, since it won't be accurate as content continues to change\n        $statusIcons.velocity('stop').velocity(\n          {\n            opacity: 0,\n          },\n          {\n            delay: 2000,\n            complete: () => {\n              $statusIcons.addClass('hidden');\n            },\n          }\n        );\n      }\n\n      this.trigger('update');\n    },\n\n    setStatusMessage: function (message) {\n      this.statusIcons().attr('title', message);\n      this.statusMessage()\n        .empty()\n        .append(\n          $('<span/>', {\n            class: 'visually-hidden',\n            text: message,\n          })\n        );\n    },\n\n    showMetaHud: function () {\n      if (!this.metaHud) {\n        this.createMetaHud();\n        this.onMetaHudShow();\n      } else {\n        this.metaHud.show();\n      }\n\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$nameTextInput.trigger('focus');\n      }\n    },\n\n    createMetaHud: function () {\n      const $hudBody = $('<div/>');\n\n      // Add the Name field\n      const $nameField = $(\n        '<div class=\"field\"><div class=\"heading\"><label for=\"draft-name\">' +\n          Craft.t('app', 'Draft Name') +\n          '</label></div></div>'\n      ).appendTo($hudBody);\n      const $nameInputContainer = $('<div class=\"input\"/>').appendTo(\n        $nameField\n      );\n      this.$nameTextInput = $(\n        '<input type=\"text\" class=\"text fullwidth\" id=\"draft-name\"/>'\n      )\n        .appendTo($nameInputContainer)\n        .val(this.settings.draftName);\n\n      // HUD footer\n      const $footer = $('<div class=\"hud-footer flex flex-center\"/>').appendTo(\n        $hudBody\n      );\n\n      $('<div class=\"flex-grow\"></div>').appendTo($footer);\n      this.$saveMetaBtn = $('<button/>', {\n        type: 'submit',\n        class: 'btn submit disabled',\n        'aria-disabled': 'true',\n        text: Craft.t('app', 'Save'),\n      }).appendTo($footer);\n\n      this.metaHud = new Garnish.HUD(this.$editMetaBtn, $hudBody, {\n        onSubmit: this.saveMeta.bind(this),\n      });\n\n      this.addListener(this.$nameTextInput, 'input', 'checkMetaValues');\n\n      this.metaHud.on('show', this.onMetaHudShow.bind(this));\n      this.metaHud.on('hide', this.onMetaHudHide.bind(this));\n      this.metaHud.on('escape', this.onMetaHudEscape.bind(this));\n    },\n\n    onMetaHudShow: function () {\n      this.$editMetaBtn.addClass('active');\n      this.$editMetaBtn.attr('aria-expanded', 'true');\n    },\n\n    onMetaHudHide: function () {\n      this.$editMetaBtn.removeClass('active');\n      this.$editMetaBtn.attr('aria-expanded', 'false');\n\n      if (Garnish.focusIsInside(this.metaHud.$body)) {\n        this.$editMetaBtn.trigger('focus');\n      }\n    },\n\n    onMetaHudEscape: function () {\n      this.$nameTextInput.val(this.settings.draftName);\n    },\n\n    checkMetaValues: function () {\n      if (\n        this.$nameTextInput.val() &&\n        this.$nameTextInput.val() !== this.settings.draftName\n      ) {\n        this.$saveMetaBtn.removeClass('disabled');\n        this.$saveMetaBtn.removeAttr('aria-disabled');\n        return true;\n      }\n\n      this.$saveMetaBtn.addClass('disabled');\n      this.$saveMetaBtn.attr('aria-disabled', 'true');\n      return false;\n    },\n\n    shakeMetaHud: function () {\n      Garnish.shake(this.metaHud.$hud);\n    },\n\n    saveMeta: function () {\n      return new Promise((resolve, reject) => {\n        if (!this.checkMetaValues()) {\n          this.shakeMetaHud();\n          reject();\n          return;\n        }\n\n        this.settings.draftName = this.$nameTextInput.val();\n        this.metaHud.hide();\n        this.checkForm(true).then(resolve).catch(reject);\n      });\n    },\n\n    handleSubmit: function (ev) {\n      ev.preventDefault();\n      ev.stopPropagation();\n\n      // Prevent double form submits\n      if (this.submittingForm) {\n        return;\n      }\n\n      // If this a draft and was this a normal save (either via submit button or save shortcut),\n      // then trigger an autosave\n      if (\n        this.settings.draftId &&\n        !this.settings.isUnpublishedDraft &&\n        !this.settings.isProvisionalDraft &&\n        (typeof ev.autosave === 'undefined' || ev.autosave) &&\n        (ev.saveShortcut ||\n          (ev.customTrigger &&\n            ev.customTrigger.data('action') === 'elements/save-draft')) &&\n        this.enableAutosave\n      ) {\n        this.checkForm(true);\n        return;\n      }\n\n      this.submittingForm = true;\n\n      // Prevent the normal unload confirmation dialog\n      Craft.cp.$confirmUnloadForms = Craft.cp.$confirmUnloadForms.not(\n        this.$container\n      );\n\n      // Abort the current save request if there is one\n      if (this.cancelToken) {\n        this.ignoreFailedRequest = true;\n        this.cancelToken.cancel();\n      }\n\n      this.trigger('beforeSubmit');\n\n      // Duplicate the form with normalized data\n      const data = this.prepareData(this.serializeForm(false));\n\n      if (this.isFullPage) {\n        this.stopListeningForChanges();\n        const $form = Craft.createForm(data);\n        $form.appendTo(Garnish.$bod);\n        $form.submit();\n      } else {\n        this.slideout.showSubmitSpinner();\n        Craft.sendActionRequest('POST', null, {\n          headers: this._saveHeaders,\n          data,\n        })\n          .then((response) => {\n            this.slideout.handleSubmitResponse(response);\n          })\n          .catch((error) => {\n            this.slideout.handleSubmitError(error);\n          })\n          .finally(() => {\n            this.submittingForm = false;\n            this.slideout.hideSubmitSpinner();\n          });\n      }\n    },\n\n    handleDismissibleTips: function () {\n      this.addListener(this.tipDismissBtn, 'click', (e) => {\n        this.hideTip(e);\n      });\n    },\n\n    getHiddenTipsUids: function () {\n      return Craft.getLocalStorage('dismissedTips', []);\n    },\n\n    setHiddenTipsUids: function (uids) {\n      Craft.setLocalStorage('dismissedTips', uids);\n    },\n\n    hideTip: function (ev) {\n      const targetElement = ev.target;\n      if (targetElement) {\n        const $targetParent = $(targetElement).closest('.readable');\n        if ($targetParent.length) {\n          const layoutElementUid = $targetParent.data('layout-element');\n          $targetParent.remove();\n          // add info to local storage\n          if (typeof Storage !== 'undefined') {\n            const hiddenTips = this.getHiddenTipsUids();\n            if (!hiddenTips.includes(layoutElementUid)) {\n              hiddenTips.push(layoutElementUid);\n              this.setHiddenTipsUids(hiddenTips);\n            }\n          }\n        }\n      }\n    },\n  },\n  {\n    defaults: {\n      additionalSites: [],\n      canCreateDrafts: false,\n      canEditMultipleSites: false,\n      canSaveCanonical: false,\n      canonicalId: null,\n      draftId: null,\n      draftName: null,\n      elementType: null,\n      enablePreview: false,\n      enabled: false,\n      enabledForSite: false,\n      hashedCpEditUrl: null,\n      isLive: false,\n      isProvisionalDraft: false,\n      isUnpublishedDraft: false,\n      previewTargets: [],\n      previewToken: null,\n      revisionId: null,\n      siteId: null,\n      siteStatuses: null,\n      siteToken: null,\n      visibleLayoutElements: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Editor Slideout\n */\nCraft.ElementEditorSlideout = Craft.CpScreenSlideout.extend(\n  {\n    $element: null,\n\n    init: function (element, settings) {\n      this.$element = $(element);\n\n      settings = Object.assign(\n        {},\n        Craft.ElementEditorSlideout.defaults,\n        settings,\n        {\n          showHeader: true,\n        }\n      );\n      this.base('elements/edit', settings);\n\n      this.on('load', () => {\n        const editor = this.$container.data('elementEditor');\n        if (editor) {\n          editor.on('beforeSubmit', () => {\n            Object.keys(this.settings.saveParams).forEach((name) => {\n              $('<input/>', {\n                class: 'hidden',\n                name: editor.namespaceInputName(name),\n                value: this.settings.saveParams[name],\n              }).appendTo(this.$container);\n            });\n          });\n        }\n      });\n\n      this.on('submit', (ev) => {\n        if (Craft.broadcaster) {\n          Craft.broadcaster.postMessage({\n            event: 'saveElement',\n            id: ev.response.data.element.id,\n          });\n        }\n\n        // Pass the response data off to onSaveElement() for backwards compatibility\n        if (this.settings.onSaveElement) {\n          const data = Object.assign(\n            {},\n            ev.response.data,\n            ev.response.data.element\n          );\n          delete data.element;\n          delete data.modelName;\n          delete data.message;\n          this.settings.onSaveElement(data);\n        }\n\n        // Refresh Live Preview\n        Craft.Preview.refresh();\n      });\n    },\n\n    getParams: function () {\n      const params = {};\n\n      if (this.settings.elementType) {\n        params.elementType = this.settings.elementType;\n      }\n\n      if (this.settings.elementId) {\n        params.elementId = this.settings.elementId;\n      } else if (this.$element && this.$element.data('id')) {\n        params.elementId = this.$element.data('id');\n      }\n\n      if (this.settings.draftId) {\n        params.draftId = this.settings.draftId;\n      } else if (this.$element && this.$element.data('draft-id')) {\n        params.draftId = this.$element.data('draft-id');\n      } else if (this.settings.revisionId) {\n        params.revisionId = this.settings.revisionId;\n      } else if (this.$element && this.$element.data('revision-id')) {\n        params.revisionId = this.$element.data('revision-id');\n      }\n\n      if (this.settings.siteId) {\n        params.siteId = this.settings.siteId;\n      } else if (this.$element && this.$element.data('site-id')) {\n        params.siteId = this.$element.data('site-id');\n      }\n\n      if (this.settings.prevalidate) {\n        params.prevalidate = 1;\n      }\n\n      return params;\n    },\n\n    handleSubmit: function (ev) {\n      this.$container.data('elementEditor').handleSubmit(ev);\n    },\n  },\n  {\n    defaults: {\n      elementId: null,\n      draftId: null,\n      revisionId: null,\n      elementType: null,\n      siteId: null,\n      prevalidate: false,\n      saveParams: {},\n      onSaveElement: null,\n      validators: [],\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\nCraft.ElementFieldSettings = Garnish.Base.extend({\n  allowMultipleSources: null,\n  $maintainHierarchyField: null,\n  $maintainHierarchyInput: null,\n  $sourcesField: null,\n  $sourceSelect: null,\n  $branchLimitField: null,\n  $maxRelationsField: null,\n  $minRelationsField: null,\n\n  init: function (\n    allowMultipleSources,\n    maintainHierarchyFieldId,\n    sourcesFieldId,\n    branchLimitFieldId,\n    minRelationsFieldId,\n    maxRelationsFieldId\n  ) {\n    this.allowMultipleSources = allowMultipleSources;\n    this.$maintainHierarchyField = $(`#${maintainHierarchyFieldId}`);\n    this.$maintainHierarchyInput = this.$maintainHierarchyField.find(\n      'input[type=\"checkbox\"]'\n    );\n    this.$sourcesField = $(`#${sourcesFieldId}`);\n    if (!this.allowMultipleSources) {\n      this.$sourceSelect = this.$sourcesField.find('select');\n    }\n    this.$branchLimitField = $(`#${branchLimitFieldId}`);\n    this.$minRelationsField = $(`#${minRelationsFieldId}`);\n    this.$maxRelationsField = $(`#${maxRelationsFieldId}`);\n\n    this.updateLimitFields();\n    this.addListener(\n      this.$maintainHierarchyInput,\n      'change',\n      'updateLimitFields'\n    );\n\n    if (this.allowMultipleSources) {\n      this.$sourcesField.find('[type=checkbox]').each(\n        function (index, checkbox) {\n          this.addListener(\n            $(checkbox),\n            'change',\n            'updateMaintainHierarchyField'\n          );\n        }.bind(this)\n      );\n    } else {\n      this.addListener(\n        this.$sourceSelect,\n        'change',\n        'updateMaintainHierarchyField'\n      );\n    }\n    this.updateMaintainHierarchyField();\n  },\n\n  updateLimitFields: function () {\n    if (\n      !this.$maintainHierarchyField.hasClass('hidden') &&\n      this.$maintainHierarchyInput.is(':checked')\n    ) {\n      this.$minRelationsField.addClass('hidden');\n      this.$maxRelationsField.addClass('hidden');\n      this.$branchLimitField.removeClass('hidden');\n    } else {\n      this.$branchLimitField.addClass('hidden');\n      this.$minRelationsField.removeClass('hidden');\n      this.$maxRelationsField.removeClass('hidden');\n    }\n  },\n\n  updateMaintainHierarchyField: function () {\n    let showField;\n    if (this.allowMultipleSources) {\n      const $checkedInputs = this.$sourcesField.find(\n        '[type=\"checkbox\"]:checked'\n      );\n      showField =\n        $checkedInputs.length === 1 && $checkedInputs.data('structure-id');\n    } else {\n      showField = this.$sourceSelect\n        .children('option:selected')\n        .data('structure-id');\n    }\n\n    if (showField) {\n      this.$maintainHierarchyField.removeClass('hidden');\n    } else {\n      this.$maintainHierarchyField.addClass('hidden');\n    }\n\n    this.updateLimitFields();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Base Element Index View\n */\nCraft.ElementThumbLoader = Garnish.Base.extend(\n  {\n    queue: null,\n    workers: [],\n\n    init: function () {\n      this.queue = [];\n\n      for (var i = 0; i < 3; i++) {\n        this.workers.push(new Craft.ElementThumbLoader.Worker(this));\n      }\n    },\n\n    load: function ($elements) {\n      // Only immediately load the visible images\n      let $thumbs = $elements.find('.elementthumb');\n      for (let i = 0; i < $thumbs.length; i++) {\n        let $thumb = $thumbs.eq(i);\n        let $scrollParent = $thumb.scrollParent();\n        if ($scrollParent.prop('nodeName') === 'FIELDSET') {\n          $scrollParent = $scrollParent.scrollParent();\n        }\n        if ($scrollParent[0] === document.body) {\n          $scrollParent = Garnish.$doc;\n        }\n        if (this.isVisible($thumb, $scrollParent)) {\n          this.addToQueue($thumb[0]);\n        } else {\n          let key = 'thumb' + Math.floor(Math.random() * 1000000);\n          Craft.ElementThumbLoader.invisibleThumbs[key] = [\n            this,\n            $thumb,\n            $scrollParent,\n          ];\n          $scrollParent.on(\n            `scroll.${key}`,\n            {\n              $thumb: $thumb,\n              $scrollParent: $scrollParent,\n              key: key,\n            },\n            (ev) => {\n              if (this.isVisible(ev.data.$thumb, ev.data.$scrollParent)) {\n                delete Craft.ElementThumbLoader.invisibleThumbs[ev.data.key];\n                $scrollParent.off(`scroll.${ev.data.key}`);\n                this.addToQueue(ev.data.$thumb[0]);\n              }\n            }\n          );\n        }\n      }\n    },\n\n    addToQueue: function (thumb) {\n      this.queue.push(thumb);\n\n      // See if there are any inactive workers\n      for (var i = 0; i < this.workers.length; i++) {\n        if (!this.workers[i].active) {\n          this.workers[i].loadNext();\n        }\n      }\n    },\n\n    isVisible: function ($thumb, $scrollParent) {\n      let thumbOffset = $thumb.offset().top;\n      let scrollParentOffset, scrollParentHeight;\n      if ($scrollParent[0] === document) {\n        scrollParentOffset = $scrollParent.scrollTop();\n        scrollParentHeight = Garnish.$win.height();\n      } else {\n        scrollParentOffset = $scrollParent.offset().top;\n        scrollParentHeight = $scrollParent.height();\n      }\n      return (\n        thumbOffset > scrollParentOffset &&\n        thumbOffset < scrollParentOffset + scrollParentHeight + 1000\n      );\n    },\n\n    destroy: function () {\n      for (var i = 0; i < this.workers.length; i++) {\n        this.workers[i].destroy();\n      }\n\n      this.base();\n    },\n  },\n  {\n    invisibleThumbs: {},\n    retryAll: function () {\n      for (let key in Craft.ElementThumbLoader.invisibleThumbs) {\n        let [queue, $thumb, $scrollParent] =\n          Craft.ElementThumbLoader.invisibleThumbs[key];\n        delete Craft.ElementThumbLoader.invisibleThumbs[key];\n        $scrollParent.off(`scroll.${key}`);\n        queue.load($thumb.parent());\n      }\n    },\n  }\n);\n\nCraft.ElementThumbLoader.Worker = Garnish.Base.extend({\n  loader: null,\n  active: false,\n\n  init: function (loader) {\n    this.loader = loader;\n  },\n\n  loadNext: function () {\n    var container = this.loader.queue.shift();\n    if (typeof container === 'undefined') {\n      this.active = false;\n      return;\n    }\n\n    this.active = true;\n    var $container = $(container);\n    if ($container.find('img').length) {\n      this.loadNext();\n      return;\n    }\n    var $img = $('<img/>', {\n      sizes: $container.attr('data-sizes'),\n      srcset: $container.attr('data-srcset'),\n      alt: $container.attr('data-alt') || '',\n    });\n    this.addListener($img, 'load,error', 'loadNext');\n    $img.appendTo($container);\n    picturefill({\n      elements: [$img[0]],\n    });\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Elevated Session Form\n */\nCraft.ElevatedSessionForm = Garnish.Base.extend({\n  $form: null,\n  inputs: null,\n\n  init: function (form, inputs) {\n    this.$form = $(form);\n\n    // Only check specific inputs?\n    if (typeof inputs !== 'undefined') {\n      this.inputs = [];\n      inputs = $.makeArray(inputs);\n\n      for (var i = 0; i < inputs.length; i++) {\n        var $inputs = $(inputs[i]);\n\n        for (var j = 0; j < $inputs.length; j++) {\n          var $input = $inputs.eq(j);\n\n          this.inputs.push({\n            input: $input,\n            val: Garnish.getInputPostVal($input),\n          });\n        }\n      }\n    }\n\n    this.addListener(this.$form, 'submit', 'handleFormSubmit');\n  },\n\n  handleFormSubmit: function (ev) {\n    // Ignore if we're in the middle of getting the elevated session timeout\n    if (Craft.elevatedSessionManager.fetchingTimeout) {\n      ev.preventDefault();\n      ev.stopImmediatePropagation();\n      return;\n    }\n\n    // Are we only interested in certain inputs?\n    if (this.inputs) {\n      var inputsChanged = false;\n      var $input;\n\n      for (var i = 0; i < this.inputs.length; i++) {\n        $input = this.inputs[i].input;\n        // Is this a password input?\n        if ($input.data('passwordInput')) {\n          $input = $input.data('passwordInput').$currentInput;\n        }\n\n        // Has this input's value changed?\n        if (Garnish.getInputPostVal($input) !== this.inputs[i].val) {\n          inputsChanged = true;\n          break;\n        }\n      }\n\n      if (!inputsChanged) {\n        // No need to interrupt the submit\n        return;\n      }\n    }\n\n    // Prevent the form from submitting until the user has an elevated session\n    ev.preventDefault();\n    ev.stopImmediatePropagation();\n    Craft.elevatedSessionManager.requireElevatedSession(\n      this.submitForm.bind(this)\n    );\n  },\n\n  submitForm: function () {\n    // Don't let handleFormSubmit() interrupt this time\n    this.disable();\n    this.$form.trigger('submit');\n    this.enable();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Elevated Session Manager\n */\nCraft.ElevatedSessionManager = Garnish.Base.extend(\n  {\n    fetchingTimeout: false,\n\n    passwordModal: null,\n    $passwordInput: null,\n    $submitBtn: null,\n    $errorPara: null,\n\n    callback: null,\n\n    /**\n     * @callback requireElevatedSessionCallback\n     */\n    /**\n     * Requires that the user has an elevated session.\n     *\n     * @param {requireElevatedSessionCallback} callback The callback function that should be called once the user has an elevated session\n     */\n    requireElevatedSession: function (callback) {\n      this.callback = callback;\n\n      // Check the time remaining on the user’s elevated session (if any)\n      this.fetchingTimeout = true;\n\n      Craft.sendActionRequest('POST', 'users/get-elevated-session-timeout')\n        .then((response) => {\n          this.fetchingTimeout = false;\n          if (\n            response.data.timeout === false ||\n            response.data.timeout >=\n              Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout\n          ) {\n            this.callback();\n          } else {\n            // Show the password modal\n            this.showPasswordModal();\n          }\n        })\n        .catch(() => {\n          this.fetchingTimeout = false;\n        });\n    },\n\n    showPasswordModal: function () {\n      if (!this.passwordModal) {\n        var $passwordModal = $(\n            '<form id=\"elevatedsessionmodal\" class=\"modal secure fitted\"/>'\n          ),\n          $body = $(\n            '<div class=\"body\"><p>' +\n              Craft.t('app', 'Enter your password to continue.') +\n              '</p></div>'\n          ).appendTo($passwordModal),\n          $inputContainer = $('<div class=\"inputcontainer\">').appendTo($body),\n          $inputsFlexContainer = $('<div class=\"flex\"/>').appendTo(\n            $inputContainer\n          ),\n          $passwordContainer = $('<div class=\"flex-grow\"/>').appendTo(\n            $inputsFlexContainer\n          ),\n          $buttonContainer = $('<td/>').appendTo($inputsFlexContainer),\n          $passwordWrapper = $('<div class=\"passwordwrapper\"/>').appendTo(\n            $passwordContainer\n          );\n\n        this.$passwordInput = $(\n          '<input type=\"password\" class=\"text password fullwidth\" placeholder=\"' +\n            Craft.t('app', 'Password') +\n            '\" autocomplete=\"current-password\"/>'\n        ).appendTo($passwordWrapper);\n        this.$submitBtn = Craft.ui\n          .createSubmitButton({\n            class: 'disabled',\n            label: Craft.t('app', 'Submit'),\n            spinner: true,\n          })\n          .appendTo($buttonContainer);\n        this.$errorPara = $('<p class=\"error\"/>').appendTo($body);\n\n        this.passwordModal = new Garnish.Modal($passwordModal, {\n          closeOtherModals: false,\n          onFadeIn: () => {\n            setTimeout(this.focusPasswordInput.bind(this), 100);\n          },\n          onFadeOut: () => {\n            this.$passwordInput.val('');\n          },\n        });\n\n        new Craft.PasswordInput(this.$passwordInput, {\n          onToggleInput: ($newPasswordInput) => {\n            this.$passwordInput = $newPasswordInput;\n          },\n        });\n\n        this.addListener(this.$passwordInput, 'input', 'validatePassword');\n        this.addListener($passwordModal, 'submit', 'submitPassword');\n      } else {\n        this.passwordModal.show();\n      }\n    },\n\n    focusPasswordInput: function () {\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$passwordInput.trigger('focus');\n      }\n    },\n\n    validatePassword: function () {\n      if (this.$passwordInput.val().length >= 6) {\n        this.$submitBtn.removeClass('disabled');\n        return true;\n      } else {\n        this.$submitBtn.addClass('disabled');\n        return false;\n      }\n    },\n\n    submitPassword: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      if (!this.validatePassword()) {\n        return;\n      }\n\n      this.$submitBtn.addClass('loading');\n      this.clearLoginError();\n\n      var data = {\n        currentPassword: this.$passwordInput.val(),\n      };\n\n      Craft.sendActionRequest('POST', 'users/start-elevated-session', {data})\n        .then((response) => {\n          this.$submitBtn.removeClass('loading');\n          this.passwordModal.hide();\n          this.callback();\n        })\n        .catch(({response}) => {\n          this.$submitBtn.removeClass('loading');\n          this.showPasswordError(\n            response.data.message || Craft.t('app', 'Incorrect password.')\n          );\n          Garnish.shake(this.passwordModal.$container);\n          this.focusPasswordInput();\n        });\n    },\n\n    showPasswordError: function (error) {\n      if (error === null || typeof error === 'undefined') {\n        error = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.$errorPara.text(error);\n      this.passwordModal.updateSizeAndPosition();\n    },\n\n    clearLoginError: function () {\n      this.showPasswordError('');\n    },\n  },\n  {\n    minSafeElevatedSessionTimeout: 5,\n  }\n);\n\n// Instantiate it\nCraft.elevatedSessionManager = new Craft.ElevatedSessionManager();\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Entry index class\n */\nCraft.EntryIndex = Craft.BaseElementIndex.extend({\n  publishableSections: null,\n  $newEntryBtnGroup: null,\n  $newEntryBtn: null,\n\n  init: function (elementType, $container, settings) {\n    this.publishableSections = [];\n    this.on('selectSource', this.updateButton.bind(this));\n    this.on('selectSite', this.updateButton.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  afterInit: function () {\n    // Find which of the visible sections the user has permission to create new entries in\n    this.publishableSections = Craft.publishableSections.filter(\n      (s) => !!this.getSourceByKey(`section:${s.uid}`)\n    );\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific section in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultSectionHandle !== 'undefined'\n    ) {\n      if (defaultSectionHandle === 'singles') {\n        return 'singles';\n      }\n\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = $(this.$sources[i]);\n        if ($source.data('handle') === defaultSectionHandle) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateButton: function () {\n    if (!this.$source) {\n      return;\n    }\n\n    let handle;\n\n    // Get the handle of the selected source\n    if (this.$source.data('key') === 'singles') {\n      handle = 'singles';\n    } else {\n      handle = this.$source.data('handle');\n    }\n\n    // Update the New Entry button\n    // ---------------------------------------------------------------------\n\n    if (this.publishableSections.length) {\n      // Remove the old button, if there is one\n      if (this.$newEntryBtnGroup) {\n        this.$newEntryBtnGroup.remove();\n      }\n\n      // Determine if they are viewing a section that they have permission to create entries in\n      const selectedSection = this.publishableSections.find(\n        (s) => s.handle === handle\n      );\n\n      this.$newEntryBtnGroup = $('<div class=\"btngroup submit\" data-wrapper/>');\n      let $menuBtn;\n      const menuId = 'new-entry-menu-' + Craft.randomString(10);\n\n      // If they are, show a primary \"New entry\" button, and a dropdown of the other sections (if any).\n      // Otherwise only show a menu button\n      if (selectedSection) {\n        const visibleLabel =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New entry')\n            : Craft.t('app', 'New {section} entry', {\n                section: selectedSection.name,\n              });\n\n        const ariaLabel =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New entry in the {section} section', {\n                section: selectedSection.name,\n              })\n            : visibleLabel;\n\n        // In index contexts, the button functions as a link\n        // In non-index contexts, the button triggers a slideout editor\n        const role = this.settings.context === 'index' ? 'link' : null;\n\n        this.$newEntryBtn = Craft.ui\n          .createButton({\n            label: visibleLabel,\n            ariaLabel: ariaLabel,\n            spinner: true,\n            role: role,\n          })\n          .addClass('submit add icon')\n          .appendTo(this.$newEntryBtnGroup);\n\n        this.addListener(this.$newEntryBtn, 'click mousedown', (ev) => {\n          // If this is the element index, check for Ctrl+clicks and middle button clicks\n          if (\n            this.settings.context === 'index' &&\n            ((ev.type === 'click' && Garnish.isCtrlKeyPressed(ev)) ||\n              (ev.type === 'mousedown' && ev.originalEvent.button === 1))\n          ) {\n            window.open(Craft.getUrl(`entries/${selectedSection.handle}/new`));\n          } else if (ev.type === 'click') {\n            this._createEntry(selectedSection.id);\n          }\n        });\n\n        if (this.publishableSections.length > 1) {\n          $menuBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn submit menubtn btngroup-btn-last',\n            'aria-controls': menuId,\n            'data-disclosure-trigger': '',\n            'aria-label': Craft.t('app', 'New entry, choose a section'),\n          }).appendTo(this.$newEntryBtnGroup);\n        }\n      } else {\n        this.$newEntryBtn = $menuBtn = Craft.ui\n          .createButton({\n            label: Craft.t('app', 'New entry'),\n            ariaLabel: Craft.t('app', 'New entry, choose a section'),\n            spinner: true,\n          })\n          .addClass('submit add icon menubtn btngroup-btn-last')\n          .attr('aria-controls', menuId)\n          .attr('data-disclosure-trigger', '')\n          .appendTo(this.$newEntryBtnGroup);\n      }\n\n      this.addButton(this.$newEntryBtnGroup);\n\n      if ($menuBtn) {\n        const $menuContainer = $('<div/>', {\n          id: menuId,\n          class: 'menu menu--disclosure',\n        }).appendTo(this.$newEntryBtnGroup);\n        const $ul = $('<ul/>').appendTo($menuContainer);\n\n        for (const section of this.publishableSections) {\n          const anchorRole =\n            this.settings.context === 'index' ? 'link' : 'button';\n          if (\n            (this.settings.context === 'index' &&\n              $.inArray(this.siteId, section.sites) !== -1) ||\n            (this.settings.context !== 'index' && section !== selectedSection)\n          ) {\n            const $li = $('<li/>').appendTo($ul);\n            const $a = $('<a/>', {\n              role: anchorRole === 'button' ? 'button' : null,\n              href: '#', // Allows for click listener and tab order\n              type: anchorRole === 'button' ? 'button' : null,\n              text: Craft.t('app', 'New {section} entry', {\n                section: section.name,\n              }),\n            }).appendTo($li);\n            this.addListener($a, 'click', () => {\n              $menuBtn.data('trigger').hide();\n              this._createEntry(section.id);\n            });\n\n            if (anchorRole === 'button') {\n              this.addListener($a, 'keydown', (event) => {\n                if (event.keyCode === Garnish.SPACE_KEY) {\n                  event.preventDefault();\n                  $menuBtn.data('trigger').hide();\n                  this._createEntry(section.id);\n                }\n              });\n            }\n          }\n        }\n\n        new Garnish.DisclosureMenu($menuBtn);\n      }\n    }\n\n    // Update the URL if we're on the Entries index\n    // ---------------------------------------------------------------------\n\n    if (this.settings.context === 'index') {\n      let uri = 'entries';\n\n      if (handle) {\n        uri += '/' + handle;\n      }\n\n      Craft.setPath(uri);\n    }\n  },\n\n  _createEntry: function (sectionId) {\n    if (this.$newEntryBtn.hasClass('loading')) {\n      console.warn('New entry creation already in progress.');\n      return;\n    }\n\n    // Find the section\n    const section = this.publishableSections.find((s) => s.id === sectionId);\n\n    if (!section) {\n      throw `Invalid section ID: ${sectionId}`;\n    }\n\n    this.$newEntryBtn.addClass('loading');\n\n    Craft.sendActionRequest('POST', 'entries/create', {\n      data: {\n        siteId: this.siteId,\n        section: section.handle,\n      },\n    })\n      .then(({data}) => {\n        if (this.settings.context === 'index') {\n          document.location.href = Craft.getUrl(data.cpEditUrl, {fresh: 1});\n        } else {\n          const slideout = Craft.createElementEditor(this.elementType, {\n            siteId: this.siteId,\n            elementId: data.entry.id,\n            draftId: data.entry.draftId,\n            params: {\n              fresh: 1,\n            },\n          });\n          slideout.on('submit', () => {\n            // Make sure the right section is selected\n            const sectionSourceKey = `section:${section.uid}`;\n\n            if (this.sourceKey !== sectionSourceKey) {\n              this.selectSourceByKey(sectionSourceKey);\n            }\n\n            this.clearSearch();\n            this.setSelectedSortAttribute('dateCreated', 'desc');\n            this.selectElementAfterUpdate(data.entry.id);\n            this.updateElements();\n          });\n        }\n      })\n      .finally(() => {\n        this.$newEntryBtn.removeClass('loading');\n      });\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\Entry', Craft.EntryIndex);\n","/** global: Craft */\n/** global: Garnish */\nCraft.FieldLayoutDesigner = Garnish.Base.extend(\n  {\n    $container: null,\n    $configInput: null,\n    $tabContainer: null,\n    $newTabBtn: null,\n    $sidebar: null,\n    $libraryToggle: null,\n    $selectedLibrary: null,\n    $fieldLibrary: null,\n    $uiLibrary: null,\n    $uiLibraryElements: null,\n    $fieldSearch: null,\n    $clearFieldSearchBtn: null,\n    $fieldGroups: null,\n    $fields: null,\n\n    tabGrid: null,\n    elementDrag: null,\n\n    _config: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.FieldLayoutDesigner.defaults);\n\n      this.$configInput = this.$container.children('input[data-config-input]');\n      this._config = JSON.parse(this.$configInput.val());\n      if (!this._config.tabs) {\n        this._config.tabs = [];\n      }\n\n      let $workspace = this.$container.children('.fld-workspace');\n      this.$tabContainer = $workspace.children('.fld-tabs');\n      this.$newTabBtn = $workspace.children('.fld-new-tab-btn');\n      this.$sidebar = this.$container.children('.fld-sidebar');\n\n      this.$fieldLibrary = this.$selectedLibrary =\n        this.$sidebar.children('.fld-field-library');\n      let $fieldSearchContainer = this.$fieldLibrary.children('.search');\n      this.$fieldSearch = $fieldSearchContainer.children('input');\n      this.$clearFieldSearchBtn = $fieldSearchContainer.children('.clear');\n      this.$fieldGroups = this.$sidebar.find('.fld-field-group');\n      this.$fields = this.$fieldGroups.children('.fld-element');\n      this.$uiLibrary = this.$sidebar.children('.fld-ui-library');\n      this.$uiLibraryElements = this.$uiLibrary.children();\n\n      // Set up the layout grids\n      this.tabGrid = new Craft.Grid(this.$tabContainer, {\n        itemSelector: '.fld-tab',\n        minColWidth: 24 * 11,\n        fillMode: 'grid',\n        snapToGrid: 24,\n      });\n\n      let $tabs = this.$tabContainer.children();\n      for (let i = 0; i < $tabs.length; i++) {\n        this.initTab($($tabs[i]));\n      }\n\n      this.elementDrag = new Craft.FieldLayoutDesigner.ElementDrag(this);\n\n      if (this.settings.customizableTabs) {\n        this.tabDrag = new Craft.FieldLayoutDesigner.TabDrag(this);\n\n        this.addListener(this.$newTabBtn, 'activate', 'addTab');\n      }\n\n      // Set up the sidebar\n      if (this.settings.customizableUi) {\n        let $libraryPicker = this.$sidebar.children('.btngroup');\n        new Craft.Listbox($libraryPicker, {\n          onChange: ($selectedOption) => {\n            this.$selectedLibrary.addClass('hidden');\n            this.$selectedLibrary =\n              this[`$${$selectedOption.data('library')}Library`].removeClass(\n                'hidden'\n              );\n          },\n        });\n      }\n\n      this.addListener(this.$fieldSearch, 'input', () => {\n        let val = this.$fieldSearch.val().toLowerCase().replace(/['\"]/g, '');\n        if (!val) {\n          this.$fieldLibrary.find('.filtered').removeClass('filtered');\n          this.$clearFieldSearchBtn.addClass('hidden');\n          return;\n        }\n\n        this.$clearFieldSearchBtn.removeClass('hidden');\n        let $matches = this.$fields\n          .filter(`[data-keywords*=\"${val}\"]`)\n          .add(\n            this.$fieldGroups\n              .filter(`[data-name*=\"${val}\"]`)\n              .children('.fld-element')\n          )\n          .removeClass('filtered');\n        this.$fields.not($matches).addClass('filtered');\n\n        // hide any groups that don't have any results\n        for (let i = 0; i < this.$fieldGroups.length; i++) {\n          let $group = this.$fieldGroups.eq(i);\n          if ($group.find('.fld-element:not(.hidden):not(.filtered)').length) {\n            $group.removeClass('filtered');\n          } else {\n            $group.addClass('filtered');\n          }\n        }\n      });\n\n      this.addListener(this.$fieldSearch, 'keydown', (ev) => {\n        switch (ev.keyCode) {\n          case Garnish.ESC_KEY:\n            this.$fieldSearch.val('').trigger('input');\n            break;\n          case Garnish.RETURN_KEY:\n            // they most likely don't want to submit the form from here\n            ev.preventDefault();\n            break;\n        }\n      });\n\n      // Clear the search when the X button is clicked\n      this.addListener(this.$clearFieldSearchBtn, 'click', () => {\n        this.$fieldSearch.val('').trigger('input');\n      });\n    },\n\n    initTab: function ($tab) {\n      return new Craft.FieldLayoutDesigner.Tab(this, $tab);\n    },\n\n    removeFieldByHandle: function (attribute) {\n      this.$fields\n        .filter(`[data-attribute=\"${attribute}\"]:first`)\n        .removeClass('hidden')\n        .closest('.fld-field-group')\n        .removeClass('hidden');\n    },\n\n    addTab: function () {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      const name = Craft.escapeHtml(\n        prompt(Craft.t('app', 'Give your tab a name.'))\n      );\n\n      if (!name) {\n        return;\n      }\n\n      const $tab = $(`\n<div class=\"fld-tab\">\n  <div class=\"tabs\">\n    <div class=\"tab sel draggable\">\n      <span>${name}</span>\n      <a class=\"settings icon\" title=\"${Craft.t('app', 'Settings')}\"></a>\n    </div>\n  </div>\n  <div class=\"fld-tabcontent\"></div>\n</div>\n`).appendTo(this.$tabContainer);\n\n      this.tabGrid.addItems($tab);\n      this.tabDrag.addItems($tab);\n\n      const tab = this.initTab($tab);\n      tab.updatePositionInConfig();\n    },\n\n    get config() {\n      return this._config;\n    },\n\n    set config(config) {\n      this._config = config;\n      this.$configInput.val(JSON.stringify(config));\n    },\n\n    updateConfig: function (callback) {\n      const config = callback(this.config);\n      if (config !== false) {\n        this.config = config;\n      }\n    },\n  },\n  {\n    defaults: {\n      customizableTabs: true,\n      customizableUi: true,\n    },\n\n    createSlideout: function (contents, js) {\n      const $body = $('<div/>', {class: 'fld-element-settings-body'});\n      $('<div/>', {class: 'fields', html: contents}).appendTo($body);\n      const $footer = $('<div/>', {class: 'fld-element-settings-footer'});\n      $('<div/>', {class: 'flex-grow'}).appendTo($footer);\n      const $cancelBtn = Craft.ui\n        .createButton({\n          label: Craft.t('app', 'Close'),\n          spinner: true,\n        })\n        .appendTo($footer);\n      Craft.ui\n        .createSubmitButton({\n          class: 'secondary',\n          label: Craft.t('app', 'Apply'),\n          spinner: true,\n        })\n        .appendTo($footer);\n      const $contents = $body.add($footer);\n\n      const slideout = new Craft.Slideout($contents, {\n        containerElement: 'form',\n        containerAttributes: {\n          action: '',\n          method: 'post',\n          novalidate: '',\n          class: 'fld-element-settings',\n        },\n      });\n      slideout.on('open', () => {\n        // Hold off a sec until it's positioned...\n        Garnish.requestAnimationFrame(() => {\n          // Focus on the first text input\n          slideout.$container.find('.text:first').trigger('focus');\n        });\n      });\n\n      $cancelBtn.on('click', () => {\n        slideout.close();\n      });\n\n      if (js) {\n        eval(js);\n      }\n\n      Craft.initUiElements(slideout.$container);\n\n      return slideout;\n    },\n  }\n);\n\nCraft.FieldLayoutDesigner.Tab = Garnish.Base.extend({\n  designer: null,\n  uid: null,\n  $container: null,\n  slideout: null,\n  destroyed: false,\n\n  init: function (designer, $container) {\n    this.designer = designer;\n    this.$container = $container;\n    this.$container.data('fld-tab', this);\n    this.uid = this.$container.data('uid');\n\n    // New tab?\n    if (!this.uid) {\n      this.uid = Craft.uuid();\n      this.config = {\n        uid: this.uid,\n        name: this.$container.find('.tabs .tab span').text(),\n        elements: [],\n      };\n      this.$container.data(\n        'settings-namespace',\n        this.designer.$container\n          .data('new-tab-settings-namespace')\n          .replace(/\\bTAB_UID\\b/g, this.uid)\n      );\n      this.$container.data(\n        'settings-html',\n        this.designer.$container\n          .data('new-tab-settings-html')\n          .replace(/\\bTAB_UID\\b/g, this.uid)\n          .replace(/\\bTAB_NAME\\b/g, this.config.name)\n      );\n      this.$container.data(\n        'settings-js',\n        this.designer.$container\n          .data('new-tab-settings-js')\n          .replace(/\\bTAB_UID\\b/g, this.uid)\n      );\n    }\n\n    if (this.designer.settings.customizableTabs) {\n      this.settingsNamespace = this.$container.data('settings-namespace');\n      this.createMenu();\n    }\n\n    // initialize the elements\n    const $elements = this.$container.children('.fld-tabcontent').children();\n\n    for (let i = 0; i < $elements.length; i++) {\n      this.initElement($($elements[i]));\n    }\n  },\n\n  createMenu: function () {\n    const $editBtn = this.$container.find('.tabs .settings');\n\n    $('<div class=\"menu\" data-align=\"center\"/>')\n      .insertAfter($editBtn)\n      .append(\n        $('<ul/>')\n          .append(\n            $('<li/>').append(\n              $('<a/>', {\n                'data-action': 'settings',\n                text: Craft.t('app', 'Settings'),\n              })\n            )\n          )\n          .append(\n            $('<li/>').append(\n              $('<a/>', {\n                'data-action': 'remove',\n                text: Craft.t('app', 'Remove'),\n              })\n            )\n          )\n      )\n      .append($('<hr/>'))\n      .append(\n        $('<ul/>')\n          .append(\n            $('<li/>').append(\n              $('<a/>', {\n                'data-action': 'moveLeft',\n                text: Craft.t('app', 'Move to the left'),\n              })\n            )\n          )\n          .append(\n            $('<li/>').append(\n              $('<a/>', {\n                'data-action': 'moveRight',\n                text: Craft.t('app', 'Move to the right'),\n              })\n            )\n          )\n      );\n\n    let menuBtn = new Garnish.MenuBtn($editBtn, {\n      onOptionSelect: this.onTabOptionSelect.bind(this),\n    });\n\n    menuBtn.menu.on('show', () => {\n      if (this.$container.prev('.fld-tab').length) {\n        menuBtn.menu.$container\n          .find('[data-action=moveLeft]')\n          .removeClass('disabled');\n      } else {\n        menuBtn.menu.$container\n          .find('[data-action=moveLeft]')\n          .addClass('disabled');\n      }\n\n      if (this.$container.next('.fld-tab').length) {\n        menuBtn.menu.$container\n          .find('[data-action=moveRight]')\n          .removeClass('disabled');\n      } else {\n        menuBtn.menu.$container\n          .find('[data-action=moveRight]')\n          .addClass('disabled');\n      }\n    });\n  },\n\n  onTabOptionSelect: function (option) {\n    if (!this.designer.settings.customizableTabs) {\n      return;\n    }\n\n    let $option = $(option);\n    let action = $option.data('action');\n\n    switch (action) {\n      case 'settings':\n        if (!this.slideout) {\n          this.createSettings();\n        } else {\n          this.slideout.open();\n        }\n        break;\n      case 'remove':\n        this.destroy();\n        break;\n      case 'moveLeft':\n        let $prev = this.$container.prev('.fld-tab');\n        if ($prev.length) {\n          this.$container.insertBefore($prev);\n          this.updatePositionInConfig();\n        }\n        break;\n      case 'moveRight':\n        let $next = this.$container.next('.fld-tab');\n        if ($next.length) {\n          this.$container.insertAfter($next);\n          this.updatePositionInConfig();\n        }\n        break;\n    }\n  },\n\n  createSettings: function () {\n    const settingsHtml = this.$container.data('settings-html');\n    const settingsJs = this.$container.data('settings-js');\n    this.slideout = Craft.FieldLayoutDesigner.createSlideout(\n      settingsHtml,\n      settingsJs\n    );\n\n    this.slideout.$container.on('submit', (ev) => {\n      ev.preventDefault();\n      this.applySettings();\n    });\n  },\n\n  applySettings: function () {\n    if (!this.slideout.$container.find('[name$=\"[name]\"]').val()) {\n      Craft.cp.displayError(Craft.t('app', 'You must specify a tab name.'));\n      return;\n    }\n\n    // update the UI\n    let $submitBtn = this.slideout.$container\n      .find('button[type=submit]')\n      .addClass('loading');\n\n    const config = $.extend({}, this.config);\n    delete config.elements;\n\n    Craft.sendActionRequest('POST', 'fields/apply-layout-tab-settings', {\n      data: {\n        config: config,\n        settingsNamespace: this.settingsNamespace,\n        settings: this.slideout.$container.serialize(),\n      },\n    })\n      .then((response) => {\n        this.updateConfig((config) =>\n          $.extend(response.data.config, {elements: config.elements})\n        );\n        const $label = this.$container.find('.tabs .tab span');\n        const $indicator = $label.children('.fld-indicator');\n        if (response.data.hasConditions) {\n          if (!$indicator.length) {\n            $label.append(\n              $('<div/>', {\n                class: 'fld-indicator',\n                title: Craft.t('app', 'This tab is conditional'),\n                'aria-label': Craft.t('app', 'This tab is conditional'),\n                'data-icon': 'condition',\n                role: 'img',\n              })\n            );\n          }\n        } else if ($indicator.length) {\n          $indicator.remove();\n        }\n        this.slideout.close();\n      })\n      .catch((e) => {\n        Craft.cp.displayError();\n        console.error(e);\n      })\n      .finally(() => {\n        $submitBtn.removeClass('loading');\n        this.slideout.close();\n      });\n  },\n\n  initElement: function ($element) {\n    return new Craft.FieldLayoutDesigner.Element(this, $element);\n  },\n\n  get index() {\n    return this.designer.config.tabs.findIndex((c) => c.uid === this.uid);\n  },\n\n  get config() {\n    if (!this.uid) {\n      throw 'Tab is missing its UID';\n    }\n    let config = this.designer.config.tabs.find((c) => c.uid === this.uid);\n    if (!config) {\n      config = {\n        uid: this.uid,\n        elements: [],\n      };\n      this.config = config;\n    }\n    return config;\n  },\n\n  set config(config) {\n    if (this.destroyed) {\n      return;\n    }\n\n    // Is the name changing?\n    if (config.name && config.name !== this.config.name) {\n      this.$container.find('.tabs .tab span').text(config.name);\n    }\n\n    const designerConfig = this.designer.config;\n    const index = this.index;\n    if (index !== -1) {\n      designerConfig.tabs[index] = config;\n    } else {\n      const newIndex = $.inArray(\n        this.$container[0],\n        this.$container.parent().children('.fld-tab')\n      );\n      designerConfig.tabs.splice(newIndex, 0, config);\n    }\n    this.designer.config = designerConfig;\n  },\n\n  updateConfig: function (callback) {\n    if (this.destroyed) {\n      return;\n    }\n\n    const config = callback(this.config);\n    if (config !== false) {\n      this.config = config;\n    }\n  },\n\n  updatePositionInConfig: function () {\n    if (this.destroyed) {\n      return;\n    }\n\n    this.designer.updateConfig((config) => {\n      const tabConfig = this.config;\n      const oldIndex = this.index;\n      const newIndex = $.inArray(\n        this.$container[0],\n        this.$container.parent().children('.fld-tab')\n      );\n      if (oldIndex !== -1) {\n        config.tabs.splice(oldIndex, 1);\n      }\n      config.tabs.splice(newIndex, 0, tabConfig);\n      return config;\n    });\n  },\n\n  destroy: function () {\n    if (this.destroyed) {\n      return;\n    }\n\n    this.destroyed = true;\n\n    this.designer.updateConfig((config) => {\n      const index = this.index;\n      if (index === -1) {\n        return false;\n      }\n      config.tabs.splice(index, 1);\n      return config;\n    });\n\n    // First destroy the tab's elements\n    let $elements = this.$container.find('.fld-element');\n    for (let i = 0; i < $elements.length; i++) {\n      $elements.eq(i).data('fld-element').destroy();\n    }\n\n    this.designer.tabGrid.removeItems(this.$container);\n    this.designer.tabDrag.removeItems(this.$container);\n    this.$container.remove();\n\n    this.base();\n  },\n});\n\nCraft.FieldLayoutDesigner.Element = Garnish.Base.extend({\n  tab: null,\n  $container: null,\n  $settingsContainer: null,\n  $editBtn: null,\n\n  uid: null,\n  isField: false,\n  attribute: null,\n  requirable: false,\n  hasCustomWidth: false,\n  hasSettings: false,\n  settingsNamespace: null,\n  slideout: null,\n\n  init: function (tab, $container) {\n    this.tab = tab;\n    this.$container = $container;\n    this.$container.data('fld-element', this);\n    this.uid = this.$container.data('uid');\n\n    // New element?\n    if (!this.uid) {\n      this.uid = Craft.uuid();\n      this.config = $.extend(this.$container.data('config'), {uid: this.uid});\n    }\n\n    this.isField = this.$container.hasClass('fld-field');\n    this.requirable =\n      this.isField && Garnish.hasAttr(this.$container, 'data-requirable');\n\n    if (this.isField) {\n      this.attribute = this.$container.data('attribute');\n    }\n\n    this.settingsNamespace = this.$container\n      .data('settings-namespace')\n      .replace(/\\bELEMENT_UID\\b/g, this.uid);\n    let settingsHtml = (this.$container.data('settings-html') || '').replace(\n      /\\bELEMENT_UID\\b/g,\n      this.uid\n    );\n    let isRequired =\n      this.requirable && this.$container.hasClass('fld-required');\n    this.hasCustomWidth =\n      this.tab.designer.settings.customizableUi &&\n      Garnish.hasAttr(this.$container, 'data-has-custom-width');\n    this.hasSettings = settingsHtml || this.requirable;\n\n    if (this.hasSettings) {\n      // create the setting container\n      this.$settingsContainer = $('<div/>', {\n        class: 'hidden',\n      });\n\n      // create the edit button\n      this.$editBtn = $('<a/>', {\n        role: 'button',\n        tabindex: 0,\n        class: 'settings icon',\n        title: Craft.t('app', 'Edit'),\n      });\n\n      const showSettings = () => {\n        if (!this.slideout) {\n          this.createSettings(settingsHtml, isRequired);\n        } else {\n          this.slideout.open();\n        }\n      };\n\n      this.$editBtn.on('click', showSettings);\n      this.$container.on('dblclick', showSettings);\n    }\n\n    this.initUi();\n\n    // cleanup\n    this.$container.attr('data-keywords', null);\n    this.$container.attr('data-settings-html', null);\n  },\n\n  initUi: function () {\n    if (this.hasCustomWidth) {\n      let widthSlider = new Craft.SlidePicker(this.config.width || 100, {\n        min: 25,\n        max: 100,\n        step: 25,\n        valueLabel: (width) => {\n          return Craft.t('app', '{pct} width', {pct: `${width}%`});\n        },\n        onChange: (width) => {\n          this.updateConfig((config) => {\n            config.width = width;\n            return config;\n          });\n        },\n      });\n      widthSlider.$container.appendTo(this.$container);\n    }\n\n    if (this.hasSettings) {\n      this.$editBtn.appendTo(this.$container);\n    }\n  },\n\n  createSettings: function (settingsHtml, isRequired) {\n    const settingsJs = (this.$container.data('settings-js') || '').replace(\n      /\\bELEMENT_UID\\b/g,\n      this.uid\n    );\n    this.slideout = Craft.FieldLayoutDesigner.createSlideout(\n      settingsHtml,\n      settingsJs\n    );\n\n    this.slideout.$container.on('submit', (ev) => {\n      ev.preventDefault();\n      this.applySettings();\n    });\n\n    if (this.requirable) {\n      const $fieldsContainer = this.slideout.$container.find('.fields:first');\n      Craft.ui\n        .createLightswitchField({\n          label: Craft.t('app', 'Required'),\n          name: `${this.settingsNamespace}[required]`,\n          on: isRequired,\n        })\n        .prependTo($fieldsContainer);\n    }\n\n    this.trigger('createSettings');\n  },\n\n  applySettings: function () {\n    // update the UI\n    let $submitBtn = this.slideout.$container\n      .find('button[type=submit]')\n      .addClass('loading');\n\n    Craft.sendActionRequest('POST', 'fields/apply-layout-element-settings', {\n      data: {\n        config: this.config,\n        settingsNamespace: this.settingsNamespace,\n        settings: this.slideout.$container.serialize(),\n      },\n    })\n      .then((response) => {\n        this.config = response.data.config;\n        this.$editBtn.detach();\n        this.$container.html($(response.data.selectorHtml).html());\n        this.initUi();\n      })\n      .catch((e) => {\n        Craft.cp.displayError();\n        console.error(e);\n      })\n      .finally(() => {\n        $submitBtn.removeClass('loading');\n        this.updateRequiredClass();\n        this.slideout.close();\n      });\n  },\n\n  updateRequiredClass: function () {\n    if (!this.requirable) {\n      return;\n    }\n\n    if (this.config.required) {\n      this.$container.addClass('fld-required');\n    } else {\n      this.$container.removeClass('fld-required');\n    }\n  },\n\n  get index() {\n    const tabConfig = this.tab.config;\n    if (typeof tabConfig === 'undefined') {\n      return -1;\n    }\n    return tabConfig.elements.findIndex((c) => c.uid === this.uid);\n  },\n\n  get config() {\n    if (!this.uid) {\n      throw 'Tab is missing its UID';\n    }\n    let config = this.tab.config.elements.find((c) => c.uid === this.uid);\n    if (!config) {\n      config = {\n        uid: this.uid,\n      };\n      this.config = config;\n    }\n    return config;\n  },\n\n  set config(config) {\n    const tabConfig = this.tab.config;\n    const index = this.index;\n    if (index !== -1) {\n      tabConfig.elements[index] = config;\n    } else {\n      const newIndex = $.inArray(\n        this.$container[0],\n        this.$container.parent().children('.fld-element')\n      );\n      tabConfig.elements.splice(newIndex, 0, config);\n    }\n    this.tab.config = tabConfig;\n  },\n\n  updateConfig: function (callback) {\n    const config = callback(this.config);\n    if (config !== false) {\n      this.config = config;\n    }\n  },\n\n  updatePositionInConfig: function () {\n    this.tab.updateConfig((config) => {\n      const elementConfig = this.config;\n      const oldIndex = this.index;\n      const newIndex = $.inArray(\n        this.$container[0],\n        this.$container.parent().children('.fld-element')\n      );\n      if (oldIndex !== -1) {\n        config.elements.splice(oldIndex, 1);\n      }\n      config.elements.splice(newIndex, 0, elementConfig);\n      return config;\n    });\n  },\n\n  destroy: function () {\n    this.tab.updateConfig((config) => {\n      const index = this.index;\n      if (index === -1) {\n        return false;\n      }\n      config.elements.splice(index, 1);\n      return config;\n    });\n\n    this.tab.designer.elementDrag.removeItems(this.$container);\n    this.$container.remove();\n\n    if (this.isField) {\n      this.tab.designer.removeFieldByHandle(this.attribute);\n    }\n\n    this.base();\n  },\n});\n\nCraft.FieldLayoutDesigner.BaseDrag = Garnish.Drag.extend({\n  designer: null,\n  $insertion: null,\n  showingInsertion: false,\n  $caboose: null,\n\n  /**\n   * Constructor\n   */\n  init: function (designer, settings) {\n    this.designer = designer;\n    this.base(this.findItems(), settings);\n  },\n\n  /**\n   * On Drag Start\n   */\n  onDragStart: function () {\n    this.base();\n\n    // Create the insertion\n    this.$insertion = this.createInsertion();\n\n    // Add the caboose\n    this.$caboose = this.createCaboose();\n    this.$items = $().add(this.$items.add(this.$caboose));\n\n    Garnish.$bod.addClass('dragging');\n  },\n\n  removeCaboose: function () {\n    this.$items = this.$items.not(this.$caboose);\n    this.$caboose.remove();\n  },\n\n  swapDraggeeWithInsertion: function () {\n    this.$insertion.insertBefore(this.$draggee);\n    this.$draggee.detach();\n    this.$items = $().add(this.$items.not(this.$draggee).add(this.$insertion));\n    this.showingInsertion = true;\n  },\n\n  swapInsertionWithDraggee: function () {\n    this.$insertion.replaceWith(this.$draggee);\n    this.$items = $().add(this.$items.not(this.$insertion).add(this.$draggee));\n    this.showingInsertion = false;\n  },\n\n  /**\n   * Sets the item midpoints up front so we don't have to keep checking on every mouse move\n   */\n  setMidpoints: function () {\n    for (let i = 0; i < this.$items.length; i++) {\n      let $item = $(this.$items[i]);\n      let offset = $item.offset();\n\n      // Skip library elements\n      if ($item.hasClass('unused')) {\n        continue;\n      }\n\n      $item.data('midpoint', {\n        left: offset.left + $item.outerWidth() / 2,\n        top: offset.top + $item.outerHeight() / 2,\n      });\n    }\n  },\n\n  /**\n   * Returns the closest item to the cursor.\n   */\n  getClosestItem: function () {\n    this.getClosestItem._closestItem = null;\n    this.getClosestItem._closestItemMouseDiff = null;\n\n    for (\n      this.getClosestItem._i = 0;\n      this.getClosestItem._i < this.$items.length;\n      this.getClosestItem._i++\n    ) {\n      this.getClosestItem._$item = $(this.$items[this.getClosestItem._i]);\n\n      this.getClosestItem._midpoint =\n        this.getClosestItem._$item.data('midpoint');\n      if (!this.getClosestItem._midpoint) {\n        continue;\n      }\n\n      this.getClosestItem._mouseDiff = Garnish.getDist(\n        this.getClosestItem._midpoint.left,\n        this.getClosestItem._midpoint.top,\n        this.mouseX,\n        this.mouseY\n      );\n\n      if (\n        this.getClosestItem._closestItem === null ||\n        this.getClosestItem._mouseDiff <\n          this.getClosestItem._closestItemMouseDiff\n      ) {\n        this.getClosestItem._closestItem = this.getClosestItem._$item[0];\n        this.getClosestItem._closestItemMouseDiff =\n          this.getClosestItem._mouseDiff;\n      }\n    }\n\n    return this.getClosestItem._closestItem;\n  },\n\n  checkForNewClosestItem: function () {\n    // Is there a new closest item?\n    this.checkForNewClosestItem._closestItem = this.getClosestItem();\n\n    if (this.checkForNewClosestItem._closestItem === this.$insertion[0]) {\n      return;\n    }\n\n    if (\n      this.showingInsertion &&\n      $.inArray(this.$insertion[0], this.$items) <\n        $.inArray(this.checkForNewClosestItem._closestItem, this.$items) &&\n      $.inArray(this.checkForNewClosestItem._closestItem, this.$caboose) === -1\n    ) {\n      this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem);\n    } else {\n      this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem);\n    }\n\n    this.$items = $().add(this.$items.add(this.$insertion));\n    this.showingInsertion = true;\n    this.designer.tabGrid.refreshCols(true);\n    this.setMidpoints();\n  },\n\n  /**\n   * On Drag Stop\n   */\n  onDragStop: function () {\n    if (this.showingInsertion) {\n      this.swapInsertionWithDraggee();\n    }\n\n    this.removeCaboose();\n\n    this.designer.tabGrid.refreshCols(true);\n\n    // return the helpers to the draggees\n    let offset = this.$draggee.offset();\n    if (!offset || (offset.top === 0 && offset.left === 0)) {\n      this.$draggee\n        .css({\n          display: this.draggeeDisplay,\n          visibility: 'visible',\n          opacity: 0,\n        })\n        .velocity({opacity: 1}, Garnish.FX_DURATION);\n      this.helpers[0].velocity({opacity: 0}, Garnish.FX_DURATION, () => {\n        this._showDraggee();\n      });\n    } else {\n      this.returnHelpersToDraggees();\n    }\n\n    this.base();\n\n    Garnish.$bod.removeClass('dragging');\n  },\n});\n\nCraft.FieldLayoutDesigner.TabDrag = Craft.FieldLayoutDesigner.BaseDrag.extend({\n  /**\n   * Constructor\n   */\n  init: function (designer) {\n    let settings = {\n      handle: '.tab',\n    };\n\n    this.base(designer, settings);\n  },\n\n  findItems: function () {\n    return this.designer.$tabContainer.find('> div.fld-tab');\n  },\n\n  /**\n   * On Drag Start\n   */\n  onDragStart: function () {\n    this.base();\n    this.swapDraggeeWithInsertion();\n    this.setMidpoints();\n  },\n\n  swapDraggeeWithInsertion: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$draggee);\n    this.designer.tabGrid.addItems(this.$insertion);\n  },\n\n  swapInsertionWithDraggee: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$insertion);\n    this.designer.tabGrid.addItems(this.$draggee);\n  },\n\n  /**\n   * On Drag\n   */\n  onDrag: function () {\n    this.checkForNewClosestItem();\n    this.base();\n  },\n\n  /**\n   * On Drag Stop\n   */\n  onDragStop: function () {\n    this.base();\n\n    // \"show\" the tab, but make it invisible\n    this.$draggee.css({\n      display: this.draggeeDisplay,\n      visibility: 'hidden',\n    });\n\n    this.$draggee.data('fld-tab').updatePositionInConfig();\n  },\n\n  /**\n   * Creates the caboose\n   */\n  createCaboose: function () {\n    let $caboose = $('<div class=\"fld-tab fld-tab-caboose\"/>').appendTo(\n      this.designer.$tabContainer\n    );\n    this.designer.tabGrid.addItems($caboose);\n    return $caboose;\n  },\n\n  /**\n   * Removes the caboose\n   */\n  removeCaboose: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$caboose);\n  },\n\n  /**\n   * Creates the insertion\n   */\n  createInsertion: function () {\n    let $tab = this.$draggee.find('.tab');\n\n    return $(`\n<div class=\"fld-tab fld-insertion\" style=\"height: ${this.$draggee.height()}px;\">\n  <div class=\"tabs\"><div class=\"tab sel draggable\" style=\"width: ${$tab.outerWidth()}px; height: ${\n      $tab.outerHeight() + 2\n    }px;\"></div></div>\n  <div class=\"fld-tabcontent\" style=\"height: ${\n    this.$draggee.find('.fld-tabcontent').height() - 2\n  }px;\"></div>\n</div>\n`);\n  },\n});\n\nCraft.FieldLayoutDesigner.ElementDrag =\n  Craft.FieldLayoutDesigner.BaseDrag.extend({\n    draggingLibraryElement: false,\n    draggingField: false,\n    originalTab: null,\n\n    /**\n     * On Drag Start\n     */\n    onDragStart: function () {\n      this.base();\n\n      // Are we dragging an element from the library?\n      this.draggingLibraryElement = this.$draggee.hasClass('unused');\n\n      // Is it a field?\n      this.draggingField = this.$draggee.hasClass('fld-field');\n\n      // keep UI elements visible\n      if (this.draggingLibraryElement && !this.draggingField) {\n        this.$draggee.css({\n          display: this.draggeeDisplay,\n          visibility: 'visible',\n        });\n      }\n\n      // Swap the draggee with the insertion if dragging a selected item\n      if (!this.draggingLibraryElement) {\n        this.originalTab = this.$draggee.closest('.fld-tab').data('fld-tab');\n        this.swapDraggeeWithInsertion();\n      } else {\n        this.originalTab = null;\n      }\n\n      this.setMidpoints();\n    },\n\n    /**\n     * On Drag\n     */\n    onDrag: function () {\n      if (this.isDraggeeMandatory() || this.isHoveringOverTab()) {\n        this.checkForNewClosestItem();\n      } else if (this.showingInsertion) {\n        this.$insertion.remove();\n        this.$items = $().add(this.$items.not(this.$insertion));\n        this.showingInsertion = false;\n        this.designer.tabGrid.refreshCols(true);\n        this.setMidpoints();\n      }\n\n      this.base();\n    },\n\n    isDraggeeMandatory: function () {\n      return Garnish.hasAttr(this.$draggee, 'data-mandatory');\n    },\n\n    isHoveringOverTab: function () {\n      for (let i = 0; i < this.designer.tabGrid.$items.length; i++) {\n        if (\n          Garnish.hitTest(\n            this.mouseX,\n            this.mouseY,\n            this.designer.tabGrid.$items.eq(i)\n          )\n        ) {\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    findItems: function () {\n      // Return all of the used + unused fields\n      return this.designer.$tabContainer\n        .find('.fld-element')\n        .add(this.designer.$sidebar.find('.fld-element'));\n    },\n\n    /**\n     * Creates the caboose\n     */\n    createCaboose: function () {\n      let $caboose = $();\n      let $fieldContainers = this.designer.$tabContainer.find(\n        '> .fld-tab > .fld-tabcontent'\n      );\n\n      for (let i = 0; i < $fieldContainers.length; i++) {\n        $caboose = $caboose.add($('<div/>').appendTo($fieldContainers[i]));\n      }\n\n      return $caboose;\n    },\n\n    /**\n     * Creates the insertion\n     */\n    createInsertion: function () {\n      return $(\n        `<div class=\"fld-element fld-insertion\" style=\"height: ${this.$draggee.outerHeight()}px;\"/>`\n      );\n    },\n\n    /**\n     * On Drag Stop\n     */\n    onDragStop: function () {\n      let showingInsertion = this.showingInsertion;\n      if (showingInsertion) {\n        if (this.draggingLibraryElement) {\n          // Create a new element based on that one\n          const $element = this.$draggee.clone().removeClass('unused');\n\n          if (this.draggingField) {\n            // Hide the library field\n            this.$draggee\n              .css({visibility: 'inherit', display: 'field'})\n              .addClass('hidden');\n\n            // Hide the group too?\n            if (\n              this.$draggee.siblings('.fld-field:not(.hidden)').length === 0\n            ) {\n              this.$draggee.closest('.fld-field-group').addClass('hidden');\n            }\n          }\n\n          // Set this.$draggee to the clone, as if we were dragging that all along\n          this.$draggee = $element;\n\n          // Remember it for later\n          this.addItems($element);\n        }\n      } else if (!this.draggingLibraryElement) {\n        let $libraryElement = this.draggingField\n          ? this.designer.$fields.filter(\n              `[data-attribute=\"${this.$draggee.data('attribute')}\"]:first`\n            )\n          : this.designer.$uiLibraryElements.filter(\n              `[data-type=\"${this.$draggee.data('type')}\"]:first`\n            );\n\n        if (this.draggingField) {\n          // show the field in the library\n          $libraryElement.removeClass('hidden');\n          $libraryElement.closest('.fld-field-group').removeClass('hidden');\n        }\n\n        // Destroy the original element\n        this.$draggee.data('fld-element').destroy();\n\n        // Set this.$draggee to the library element, as if we were dragging that all along\n        this.$draggee = $libraryElement;\n      }\n\n      this.base();\n\n      this.$draggee.css({\n        display: this.draggeeDisplay,\n        visibility:\n          this.draggingField || showingInsertion ? 'hidden' : 'visible',\n      });\n\n      if (showingInsertion) {\n        const tab = this.$draggee.closest('.fld-tab').data('fld-tab');\n        let element;\n\n        if (this.draggingLibraryElement) {\n          element = tab.initElement(this.$draggee);\n        } else {\n          element = this.$draggee.data('fld-element');\n\n          // New tab?\n          if (tab !== this.originalTab) {\n            const config = element.config;\n\n            this.originalTab.updateConfig((config) => {\n              const index = element.index;\n              if (index === -1) {\n                return false;\n              }\n              config.elements.splice(index, 1);\n              return config;\n            });\n\n            this.$draggee.data('fld-element').tab = tab;\n            element.config = config;\n          }\n        }\n\n        element.updatePositionInConfig();\n      }\n    },\n  });\n","/** global: Craft */\n/** global: Garnish */\n/**\n * FieldToggle\n */\nCraft.FieldToggle = Garnish.Base.extend({\n  $toggle: null,\n  targetPrefix: null,\n  targetSelector: null,\n  reverseTargetSelector: null,\n\n  _$target: null,\n  _$reverseTarget: null,\n  type: null,\n\n  init: function (toggle) {\n    this.$toggle = $(toggle);\n\n    // Is this already a field toggle?\n    if (this.$toggle.data('fieldtoggle')) {\n      console.warn('Double-instantiating a field toggle on an element');\n      this.$toggle.data('fieldtoggle').destroy();\n    }\n\n    this.$toggle.data('fieldtoggle', this);\n\n    this.type = this.getType();\n\n    if (this.type === 'select' || this.type === 'fieldset') {\n      this.targetPrefix = this.$toggle.attr('data-target-prefix') || '';\n    } else {\n      this.targetSelector = this.normalizeTargetSelector(\n        this.$toggle.data('target')\n      );\n      this.reverseTargetSelector = this.normalizeTargetSelector(\n        this.$toggle.data('reverse-target')\n      );\n    }\n\n    this.findTargets();\n\n    switch (this.type) {\n      case 'link':\n        this.addListener(this.$toggle, 'click', 'onToggleChange');\n        break;\n      case 'fieldset':\n        this.addListener(\n          this.$toggle.find('input'),\n          'change',\n          'onToggleChange'\n        );\n        break;\n      default:\n        this.addListener(this.$toggle, 'change', 'onToggleChange');\n        this.onToggleChange();\n    }\n  },\n\n  normalizeTargetSelector: function (selector) {\n    if (selector && !selector.match(/^[#\\.]/)) {\n      selector = '#' + selector;\n    }\n\n    return selector;\n  },\n\n  getType: function () {\n    let nodeName = this.$toggle.prop('nodeName');\n    if (\n      (nodeName === 'INPUT' && this.$toggle.attr('type') === 'checkbox') ||\n      this.$toggle.attr('role') === 'checkbox' ||\n      this.$toggle.attr('role') === 'switch'\n    ) {\n      return 'checkbox';\n    }\n\n    switch (nodeName) {\n      case 'SELECT':\n        if (Garnish.hasAttr(this.$toggle, 'data-boolean-menu')) {\n          return 'booleanMenu';\n        }\n        return 'select';\n      case 'A':\n        return 'link';\n      default:\n        return 'fieldset';\n    }\n  },\n\n  findTargets: function () {\n    if (this.type === 'select' || this.type === 'fieldset') {\n      var toggleVal = this.getToggleVal();\n      this._$target = $(\n        this.normalizeTargetSelector(this.targetPrefix + this.getToggleVal())\n      );\n    } else {\n      if (this.targetSelector) {\n        this._$target = $(this.targetSelector);\n      }\n\n      if (this.reverseTargetSelector) {\n        this._$reverseTarget = $(this.reverseTargetSelector);\n      }\n    }\n  },\n\n  getToggleVal: function () {\n    switch (this.type) {\n      case 'checkbox':\n        if (typeof this.$toggle.prop('checked') !== 'undefined') {\n          return this.$toggle.prop('checked');\n        }\n        return this.$toggle.attr('aria-checked') === 'true';\n\n      case 'booleanMenu':\n        const boolean = this.$toggle.data('boolean');\n        if (typeof boolean !== 'undefined') {\n          return boolean;\n        }\n        const val = this.$toggle.val();\n        return val && val !== '0';\n\n      default:\n        let postVal;\n        if (this.type === 'fieldset') {\n          postVal = this.$toggle.find('input:checked:first').val();\n        } else {\n          postVal = Garnish.getInputPostVal(this.$toggle);\n        }\n\n        // Normalize the value\n        return typeof postVal === 'undefined' || postVal === null\n          ? null\n          : postVal.replace(/[^\\w]+/g, '-');\n    }\n  },\n\n  onToggleChange: function () {\n    if (this.type === 'select' || this.type === 'fieldset') {\n      this.hideTarget(this._$target);\n      this.findTargets();\n      this.showTarget(this._$target);\n    } else {\n      this.findTargets();\n\n      if (this.type === 'link') {\n        this.onToggleChange._show =\n          this.$toggle.hasClass('collapsed') ||\n          !this.$toggle.hasClass('expanded');\n      } else {\n        this.onToggleChange._show = !!this.getToggleVal();\n      }\n\n      if (this.onToggleChange._show) {\n        this.showTarget(this._$target);\n        this.hideTarget(this._$reverseTarget);\n      } else {\n        this.hideTarget(this._$target);\n        this.showTarget(this._$reverseTarget);\n      }\n\n      delete this.onToggleChange._show;\n    }\n  },\n\n  showTarget: function ($target) {\n    if ($target && $target.length) {\n      this.showTarget._currentHeight = $target.height();\n\n      $target.removeClass('hidden');\n\n      if (this.type !== 'select' && this.type !== 'fieldset') {\n        if (this.type === 'link') {\n          this.$toggle.removeClass('collapsed');\n          this.$toggle.addClass('expanded');\n        }\n\n        for (let i = 0; i < $target.length; i++) {\n          (($t) => {\n            if ($t.prop('nodeName') !== 'SPAN') {\n              $t.height('auto');\n              this.showTarget._targetHeight = $t.height();\n              $t.css({\n                height: this.showTarget._currentHeight,\n                overflow: 'hidden',\n              });\n\n              $t.velocity('stop');\n\n              $t.velocity(\n                {height: this.showTarget._targetHeight},\n                'fast',\n                function () {\n                  $t.css({\n                    height: '',\n                    overflow: '',\n                  });\n                }\n              );\n            }\n          })($target.eq(i));\n        }\n\n        delete this.showTarget._targetHeight;\n      }\n\n      delete this.showTarget._currentHeight;\n\n      // Trigger a resize event in case there are any grids in the target that need to initialize\n      Garnish.$win.trigger('resize');\n    }\n  },\n\n  hideTarget: function ($target) {\n    if ($target && $target.length) {\n      if (this.type === 'select' || this.type === 'fieldset') {\n        $target.addClass('hidden');\n      } else {\n        if (this.type === 'link') {\n          this.$toggle.removeClass('expanded');\n          this.$toggle.addClass('collapsed');\n        }\n\n        for (let i = 0; i < $target.length; i++) {\n          (($t) => {\n            if ($t.hasClass('hidden')) {\n              return;\n            }\n            if ($t.prop('nodeName') === 'SPAN') {\n              $t.addClass('hidden');\n            } else {\n              $t.css('overflow', 'hidden');\n              $t.velocity('stop');\n              $t.velocity({height: 0}, 'fast', function () {\n                $t.addClass('hidden');\n              });\n            }\n          })($target.eq(i));\n        }\n      }\n    }\n  },\n\n  destroy: function () {\n    this.$toggle.removeData('fieldtoggle');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.Grid = Garnish.Base.extend(\n  {\n    $container: null,\n\n    $items: null,\n    items: null,\n    totalCols: null,\n    colGutterDrop: null,\n    colPctWidth: null,\n\n    possibleItemColspans: null,\n    possibleItemPositionsByColspan: null,\n\n    itemPositions: null,\n    itemColspansByPosition: null,\n\n    layouts: null,\n    layout: null,\n    itemHeights: null,\n    leftPadding: null,\n\n    _refreshingCols: false,\n    _refreshColsAfterRefresh: false,\n    _forceRefreshColsAfterRefresh: false,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n\n      // Is this already a grid?\n      if (this.$container.data('grid')) {\n        console.warn('Double-instantiating a grid on an element');\n        this.$container.data('grid').destroy();\n      }\n\n      this.$container.data('grid', this);\n\n      this.setSettings(settings, Craft.Grid.defaults);\n\n      // Set the refreshCols() proxy that container resizes will trigger\n      this.handleContainerHeightProxy = () => {\n        this.refreshCols(false, true);\n      };\n\n      this.$items = this.$container.children(this.settings.itemSelector);\n      this.setItems();\n      this.refreshCols(true, false);\n\n      Garnish.$doc.ready(() => {\n        this.refreshCols(false, false);\n      });\n    },\n\n    addItems: function (items) {\n      this.$items = $().add(this.$items.add(items));\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    removeItems: function (items) {\n      this.$items = $().add(this.$items.not(items));\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    resetItemOrder: function () {\n      this.$items = $().add(this.$items);\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    setItems: function () {\n      this.setItems._ = {};\n\n      this.items = [];\n\n      for (\n        this.setItems._.i = 0;\n        this.setItems._.i < this.$items.length;\n        this.setItems._.i++\n      ) {\n        this.items.push($(this.$items[this.setItems._.i]));\n      }\n\n      delete this.setItems._;\n    },\n\n    refreshCols: function (force) {\n      if (this._refreshingCols) {\n        this._refreshColsAfterRefresh = true;\n        if (force) {\n          this._forceRefreshColsAfterRefresh = true;\n        }\n        return;\n      }\n\n      this._refreshingCols = true;\n\n      if (!this.items.length) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      this.refreshCols._ = {};\n\n      // Check to see if the grid is actually visible\n      this.refreshCols._.oldHeight = this.$container[0].style.height;\n      this.$container[0].style.height = 1;\n      this.refreshCols._.scrollHeight = this.$container[0].scrollHeight;\n      this.$container[0].style.height = this.refreshCols._.oldHeight;\n\n      if (this.refreshCols._.scrollHeight === 0) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      if (this.settings.cols) {\n        this.refreshCols._.totalCols = this.settings.cols;\n      } else {\n        this.refreshCols._.totalCols = Math.floor(\n          this.$container.width() / this.settings.minColWidth\n        );\n\n        // If we're adding a new column, require an extra 20 pixels in case a scrollbar shows up\n        if (\n          this.totalCols !== null &&\n          this.refreshCols._.totalCols > this.totalCols\n        ) {\n          this.refreshCols._.totalCols = Math.floor(\n            (this.$container.width() - 20) / this.settings.minColWidth\n          );\n        }\n\n        if (\n          this.settings.maxCols &&\n          this.refreshCols._.totalCols > this.settings.maxCols\n        ) {\n          this.refreshCols._.totalCols = this.settings.maxCols;\n        }\n      }\n\n      if (this.refreshCols._.totalCols === 0) {\n        this.refreshCols._.totalCols = 1;\n      }\n\n      // Same number of columns as before?\n      if (force !== true && this.totalCols === this.refreshCols._.totalCols) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      this.totalCols = this.refreshCols._.totalCols;\n      this.colGutterDrop =\n        (this.settings.gutter * (this.totalCols - 1)) / this.totalCols;\n\n      // Temporarily stop listening to container resizes\n      this.removeListener(this.$container, 'resize');\n\n      if (this.settings.fillMode === 'grid') {\n        this.refreshCols._.itemIndex = 0;\n\n        while (this.refreshCols._.itemIndex < this.items.length) {\n          // Append the next X items and figure out which one is the tallest\n          this.refreshCols._.tallestItemHeight = -1;\n          this.refreshCols._.colIndex = 0;\n\n          for (\n            this.refreshCols._.i = this.refreshCols._.itemIndex;\n            this.refreshCols._.i <\n              this.refreshCols._.itemIndex + this.totalCols &&\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.itemHeight = this.items[this.refreshCols._.i]\n              .height('auto')\n              .height();\n\n            if (\n              this.refreshCols._.itemHeight >\n              this.refreshCols._.tallestItemHeight\n            ) {\n              this.refreshCols._.tallestItemHeight =\n                this.refreshCols._.itemHeight;\n            }\n\n            this.refreshCols._.colIndex++;\n          }\n\n          if (this.settings.snapToGrid) {\n            this.refreshCols._.remainder =\n              this.refreshCols._.tallestItemHeight % this.settings.snapToGrid;\n\n            if (this.refreshCols._.remainder) {\n              this.refreshCols._.tallestItemHeight +=\n                this.settings.snapToGrid - this.refreshCols._.remainder;\n            }\n          }\n\n          // Now set their heights to the tallest one\n          for (\n            this.refreshCols._.i = this.refreshCols._.itemIndex;\n            this.refreshCols._.i <\n              this.refreshCols._.itemIndex + this.totalCols &&\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.items[this.refreshCols._.i].height(\n              this.refreshCols._.tallestItemHeight\n            );\n          }\n\n          // set the this.refreshCols._.itemIndex pointer to the next one up\n          this.refreshCols._.itemIndex += this.totalCols;\n        }\n      } else {\n        this.removeListener(this.$items, 'resize');\n\n        // If there's only one column, sneak out early\n        if (this.totalCols === 1) {\n          this.$container.height('auto');\n          this.$items\n            .show()\n            .css({\n              position: 'relative',\n              width: 'auto',\n              top: 0,\n            })\n            .css(Craft.left, 0);\n        } else {\n          this.$items.css('position', 'absolute');\n          this.colPctWidth = 100 / this.totalCols;\n\n          // The setup\n\n          this.layouts = [];\n\n          this.itemPositions = [];\n          this.itemColspansByPosition = [];\n\n          // Figure out all of the possible colspans for each item,\n          // as well as all the possible positions for each item at each of its colspans\n\n          this.possibleItemColspans = [];\n          this.possibleItemPositionsByColspan = [];\n          this.itemHeightsByColspan = [];\n\n          for (\n            this.refreshCols._.item = 0;\n            this.refreshCols._.item < this.items.length;\n            this.refreshCols._.item++\n          ) {\n            this.possibleItemColspans[this.refreshCols._.item] = [];\n            this.possibleItemPositionsByColspan[this.refreshCols._.item] = {};\n            this.itemHeightsByColspan[this.refreshCols._.item] = {};\n\n            this.refreshCols._.$item =\n              this.items[this.refreshCols._.item].show();\n            this.refreshCols._.positionRight =\n              this.refreshCols._.$item.data('position') === 'right';\n            this.refreshCols._.positionLeft =\n              this.refreshCols._.$item.data('position') === 'left';\n            this.refreshCols._.minColspan = this.refreshCols._.$item.data(\n              'colspan'\n            )\n              ? this.refreshCols._.$item.data('colspan')\n              : this.refreshCols._.$item.data('min-colspan')\n              ? this.refreshCols._.$item.data('min-colspan')\n              : 1;\n            this.refreshCols._.maxColspan = this.refreshCols._.$item.data(\n              'colspan'\n            )\n              ? this.refreshCols._.$item.data('colspan')\n              : this.refreshCols._.$item.data('max-colspan')\n              ? this.refreshCols._.$item.data('max-colspan')\n              : this.totalCols;\n\n            if (this.refreshCols._.minColspan > this.totalCols) {\n              this.refreshCols._.minColspan = this.totalCols;\n            }\n            if (this.refreshCols._.maxColspan > this.totalCols) {\n              this.refreshCols._.maxColspan = this.totalCols;\n            }\n\n            for (\n              this.refreshCols._.colspan = this.refreshCols._.minColspan;\n              this.refreshCols._.colspan <= this.refreshCols._.maxColspan;\n              this.refreshCols._.colspan++\n            ) {\n              // Get the height for this colspan\n              this.refreshCols._.$item.css(\n                'width',\n                this.getItemWidthCss(this.refreshCols._.colspan)\n              );\n              this.itemHeightsByColspan[this.refreshCols._.item][\n                this.refreshCols._.colspan\n              ] = this.refreshCols._.$item.outerHeight();\n\n              this.possibleItemColspans[this.refreshCols._.item].push(\n                this.refreshCols._.colspan\n              );\n              this.possibleItemPositionsByColspan[this.refreshCols._.item][\n                this.refreshCols._.colspan\n              ] = [];\n\n              if (this.refreshCols._.positionLeft) {\n                this.refreshCols._.minPosition = 0;\n                this.refreshCols._.maxPosition = 0;\n              } else if (this.refreshCols._.positionRight) {\n                this.refreshCols._.minPosition =\n                  this.totalCols - this.refreshCols._.colspan;\n                this.refreshCols._.maxPosition = this.refreshCols._.minPosition;\n              } else {\n                this.refreshCols._.minPosition = 0;\n                this.refreshCols._.maxPosition =\n                  this.totalCols - this.refreshCols._.colspan;\n              }\n\n              for (\n                this.refreshCols._.position = this.refreshCols._.minPosition;\n                this.refreshCols._.position <= this.refreshCols._.maxPosition;\n                this.refreshCols._.position++\n              ) {\n                this.possibleItemPositionsByColspan[this.refreshCols._.item][\n                  this.refreshCols._.colspan\n                ].push(this.refreshCols._.position);\n              }\n            }\n          }\n\n          // Find all the possible layouts\n\n          this.refreshCols._.colHeights = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.totalCols;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.colHeights.push(0);\n          }\n\n          this.createLayouts(0, [], [], this.refreshCols._.colHeights, 0);\n\n          // Now find the layout that looks the best.\n\n          // First find the layouts with the highest number of used columns\n          this.refreshCols._.layoutTotalCols = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.layouts.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.layoutTotalCols[this.refreshCols._.i] = 0;\n\n            for (\n              this.refreshCols._.j = 0;\n              this.refreshCols._.j < this.totalCols;\n              this.refreshCols._.j++\n            ) {\n              if (\n                this.layouts[this.refreshCols._.i].colHeights[\n                  this.refreshCols._.j\n                ]\n              ) {\n                this.refreshCols._.layoutTotalCols[this.refreshCols._.i]++;\n              }\n            }\n          }\n\n          this.refreshCols._.highestTotalCols = Math.max.apply(\n            null,\n            this.refreshCols._.layoutTotalCols\n          );\n\n          // Filter out the ones that aren't using as many columns as they could be\n          for (\n            this.refreshCols._.i = this.layouts.length - 1;\n            this.refreshCols._.i >= 0;\n            this.refreshCols._.i--\n          ) {\n            if (\n              this.refreshCols._.layoutTotalCols[this.refreshCols._.i] !==\n              this.refreshCols._.highestTotalCols\n            ) {\n              this.layouts.splice(this.refreshCols._.i, 1);\n            }\n          }\n\n          // Find the layout(s) with the least overall height\n          this.refreshCols._.layoutHeights = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.layouts.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.layoutHeights.push(\n              Math.max.apply(\n                null,\n                this.layouts[this.refreshCols._.i].colHeights\n              )\n            );\n          }\n\n          this.refreshCols._.shortestHeight = Math.min.apply(\n            null,\n            this.refreshCols._.layoutHeights\n          );\n          this.refreshCols._.shortestLayouts = [];\n          this.refreshCols._.emptySpaces = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.refreshCols._.layoutHeights.length;\n            this.refreshCols._.i++\n          ) {\n            if (\n              this.refreshCols._.layoutHeights[this.refreshCols._.i] ===\n              this.refreshCols._.shortestHeight\n            ) {\n              this.refreshCols._.shortestLayouts.push(\n                this.layouts[this.refreshCols._.i]\n              );\n\n              // Now get its total empty space, including any trailing empty space\n              this.refreshCols._.emptySpace =\n                this.layouts[this.refreshCols._.i].emptySpace;\n\n              for (\n                this.refreshCols._.j = 0;\n                this.refreshCols._.j < this.totalCols;\n                this.refreshCols._.j++\n              ) {\n                this.refreshCols._.emptySpace +=\n                  this.refreshCols._.shortestHeight -\n                  this.layouts[this.refreshCols._.i].colHeights[\n                    this.refreshCols._.j\n                  ];\n              }\n\n              this.refreshCols._.emptySpaces.push(\n                this.refreshCols._.emptySpace\n              );\n            }\n          }\n\n          // And the layout with the least empty space is...\n          this.layout =\n            this.refreshCols._.shortestLayouts[\n              $.inArray(\n                Math.min.apply(null, this.refreshCols._.emptySpaces),\n                this.refreshCols._.emptySpaces\n              )\n            ];\n\n          // Set the item widths and left positions\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.css = {\n              width: this.getItemWidthCss(\n                this.layout.colspans[this.refreshCols._.i]\n              ),\n            };\n            this.refreshCols._.css[Craft.left] = this.getItemLeftPosCss(\n              this.layout.positions[this.refreshCols._.i]\n            );\n            this.items[this.refreshCols._.i].css(this.refreshCols._.css);\n          }\n\n          // If every item is at position 0, then let them lay out au naturel\n          if (this.isSimpleLayout()) {\n            this.$container.height('auto');\n            this.$items.css({\n              position: 'relative',\n              top: 0,\n              'margin-bottom': this.settings.gutter + 'px',\n            });\n          } else {\n            this.$items.css('position', 'absolute');\n\n            // Now position the items\n            this.positionItems();\n\n            // Update the positions as the items' heigthts change\n            this.addListener(this.$items, 'resize', 'onItemResize');\n          }\n        }\n      }\n\n      this.completeRefreshCols();\n\n      // Resume container resize listening\n      this.addListener(\n        this.$container,\n        'resize',\n        this.handleContainerHeightProxy\n      );\n\n      this.onRefreshCols();\n    },\n\n    completeRefreshCols: function () {\n      // Delete the internal variable object\n      if (typeof this.refreshCols._ !== 'undefined') {\n        delete this.refreshCols._;\n      }\n\n      this._refreshingCols = false;\n\n      if (this._refreshColsAfterRefresh) {\n        var force = this._forceRefreshColsAfterRefresh;\n        this._refreshColsAfterRefresh = false;\n        this._forceRefreshColsAfterRefresh = false;\n\n        Garnish.requestAnimationFrame(() => {\n          this.refreshCols(force);\n        });\n      }\n    },\n\n    getItemWidth: function (colspan) {\n      return this.colPctWidth * colspan;\n    },\n\n    getItemWidthCss: function (colspan) {\n      return (\n        'calc(' +\n        this.getItemWidth(colspan) +\n        '% - ' +\n        this.colGutterDrop +\n        'px)'\n      );\n    },\n\n    getItemWidthInPx: function (colspan) {\n      return (\n        (this.getItemWidth(colspan) / 100) * this.$container.width() -\n        this.colGutterDrop\n      );\n    },\n\n    getItemLeftPosCss: function (position) {\n      return (\n        'calc(' +\n        '(' +\n        this.getItemWidth(1) +\n        '% + ' +\n        (this.settings.gutter - this.colGutterDrop) +\n        'px) * ' +\n        position +\n        ')'\n      );\n    },\n\n    getItemLeftPosInPx: function (position) {\n      return (\n        ((this.getItemWidth(1) / 100) * this.$container.width() +\n          (this.settings.gutter - this.colGutterDrop)) *\n        position\n      );\n    },\n\n    createLayouts: function (\n      item,\n      prevPositions,\n      prevColspans,\n      prevColHeights,\n      prevEmptySpace\n    ) {\n      new Craft.Grid.LayoutGenerator(this).createLayouts(\n        item,\n        prevPositions,\n        prevColspans,\n        prevColHeights,\n        prevEmptySpace\n      );\n    },\n\n    isSimpleLayout: function () {\n      this.isSimpleLayout._ = {};\n\n      for (\n        this.isSimpleLayout._.i = 0;\n        this.isSimpleLayout._.i < this.layout.positions.length;\n        this.isSimpleLayout._.i++\n      ) {\n        if (this.layout.positions[this.isSimpleLayout._.i] !== 0) {\n          delete this.isSimpleLayout._;\n          return false;\n        }\n      }\n\n      delete this.isSimpleLayout._;\n      return true;\n    },\n\n    positionItems: function () {\n      this.positionItems._ = {};\n\n      this.positionItems._.colHeights = [];\n\n      for (\n        this.positionItems._.i = 0;\n        this.positionItems._.i < this.totalCols;\n        this.positionItems._.i++\n      ) {\n        this.positionItems._.colHeights.push(0);\n      }\n\n      for (\n        this.positionItems._.i = 0;\n        this.positionItems._.i < this.items.length;\n        this.positionItems._.i++\n      ) {\n        this.positionItems._.endingCol =\n          this.layout.positions[this.positionItems._.i] +\n          this.layout.colspans[this.positionItems._.i] -\n          1;\n        this.positionItems._.affectedColHeights = [];\n\n        for (\n          this.positionItems._.col =\n            this.layout.positions[this.positionItems._.i];\n          this.positionItems._.col <= this.positionItems._.endingCol;\n          this.positionItems._.col++\n        ) {\n          this.positionItems._.affectedColHeights.push(\n            this.positionItems._.colHeights[this.positionItems._.col]\n          );\n        }\n\n        this.positionItems._.top = Math.max.apply(\n          null,\n          this.positionItems._.affectedColHeights\n        );\n        if (this.positionItems._.top > 0) {\n          this.positionItems._.top += this.settings.gutter;\n        }\n\n        this.items[this.positionItems._.i].css('top', this.positionItems._.top);\n\n        // Now add the new heights to those columns\n        for (\n          this.positionItems._.col =\n            this.layout.positions[this.positionItems._.i];\n          this.positionItems._.col <= this.positionItems._.endingCol;\n          this.positionItems._.col++\n        ) {\n          this.positionItems._.colHeights[this.positionItems._.col] =\n            this.positionItems._.top +\n            this.itemHeightsByColspan[this.positionItems._.i][\n              this.layout.colspans[this.positionItems._.i]\n            ];\n        }\n      }\n\n      // Set the container height\n      this.$container.height(\n        Math.max.apply(null, this.positionItems._.colHeights)\n      );\n\n      delete this.positionItems._;\n    },\n\n    onItemResize: function (ev) {\n      this.onItemResize._ = {};\n\n      // Prevent this from bubbling up to the container, which has its own resize listener\n      ev.stopPropagation();\n\n      this.onItemResize._.item = $.inArray(ev.currentTarget, this.$items);\n\n      if (this.onItemResize._.item !== -1) {\n        // Update the height and reposition the items\n        this.onItemResize._.newHeight =\n          this.items[this.onItemResize._.item].outerHeight();\n\n        if (\n          this.onItemResize._.newHeight !==\n          this.itemHeightsByColspan[this.onItemResize._.item][\n            this.layout.colspans[this.onItemResize._.item]\n          ]\n        ) {\n          this.itemHeightsByColspan[this.onItemResize._.item][\n            this.layout.colspans[this.onItemResize._.item]\n          ] = this.onItemResize._.newHeight;\n          this.positionItems(false);\n        }\n      }\n\n      delete this.onItemResize._;\n    },\n\n    onRefreshCols: function () {\n      this.trigger('refreshCols');\n      this.settings.onRefreshCols();\n    },\n\n    destroy: function () {\n      this.$container.removeData('grid');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      itemSelector: '.item',\n      cols: null,\n      maxCols: null,\n      minColWidth: 320,\n      gutter: 14,\n      fillMode: 'top',\n      colClass: 'col',\n      snapToGrid: null,\n\n      onRefreshCols: $.noop,\n    },\n  }\n);\n\nCraft.Grid.LayoutGenerator = Garnish.Base.extend({\n  grid: null,\n  _: null,\n\n  init: function (grid) {\n    this.grid = grid;\n  },\n\n  createLayouts: function (\n    item,\n    prevPositions,\n    prevColspans,\n    prevColHeights,\n    prevEmptySpace\n  ) {\n    this._ = {};\n\n    // Loop through all possible colspans\n    for (\n      this._.c = 0;\n      this._.c < this.grid.possibleItemColspans[item].length;\n      this._.c++\n    ) {\n      this._.colspan = this.grid.possibleItemColspans[item][this._.c];\n\n      // Loop through all the possible positions for this colspan,\n      // and find the one that is closest to the top\n\n      this._.tallestColHeightsByPosition = [];\n\n      for (\n        this._.p = 0;\n        this._.p <\n        this.grid.possibleItemPositionsByColspan[item][this._.colspan].length;\n        this._.p++\n      ) {\n        this._.position =\n          this.grid.possibleItemPositionsByColspan[item][this._.colspan][\n            this._.p\n          ];\n\n        this._.colHeightsForPosition = [];\n        this._.endingCol = this._.position + this._.colspan - 1;\n\n        for (\n          this._.col = this._.position;\n          this._.col <= this._.endingCol;\n          this._.col++\n        ) {\n          this._.colHeightsForPosition.push(prevColHeights[this._.col]);\n        }\n\n        this._.tallestColHeightsByPosition[this._.p] = Math.max.apply(\n          null,\n          this._.colHeightsForPosition\n        );\n      }\n\n      // And the shortest position for this colspan is...\n      this._.p = $.inArray(\n        Math.min.apply(null, this._.tallestColHeightsByPosition),\n        this._.tallestColHeightsByPosition\n      );\n      this._.position =\n        this.grid.possibleItemPositionsByColspan[item][this._.colspan][\n          this._.p\n        ];\n\n      // Now log the colspan/position placement\n      this._.positions = prevPositions.slice(0);\n      this._.colspans = prevColspans.slice(0);\n      this._.colHeights = prevColHeights.slice(0);\n      this._.emptySpace = prevEmptySpace;\n\n      this._.positions.push(this._.position);\n      this._.colspans.push(this._.colspan);\n\n      // Add the new heights to those columns\n      this._.tallestColHeight = this._.tallestColHeightsByPosition[this._.p];\n      this._.endingCol = this._.position + this._.colspan - 1;\n\n      for (\n        this._.col = this._.position;\n        this._.col <= this._.endingCol;\n        this._.col++\n      ) {\n        this._.emptySpace +=\n          this._.tallestColHeight - this._.colHeights[this._.col];\n        this._.colHeights[this._.col] =\n          this._.tallestColHeight +\n          this.grid.itemHeightsByColspan[item][this._.colspan];\n      }\n\n      // If this is the last item, create the layout\n      if (item === this.grid.items.length - 1) {\n        this.grid.layouts.push({\n          positions: this._.positions,\n          colspans: this._.colspans,\n          colHeights: this._.colHeights,\n          emptySpace: this._.emptySpace,\n        });\n      } else {\n        // Dive deeper\n        this.grid.createLayouts(\n          item + 1,\n          this._.positions,\n          this._.colspans,\n          this._.colHeights,\n          this._.emptySpace\n        );\n      }\n    }\n\n    delete this._;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.HandleGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    var handle = sourceVal.replace(/<(.*?)>/g, '');\n\n    // Remove inner-word punctuation\n    handle = handle.replace(/['\"‘’“”\\[\\]\\(\\)\\{\\}:]/g, '');\n\n    // Make it lowercase\n    handle = handle.toLowerCase();\n\n    // Convert extended ASCII characters to basic ASCII\n    handle = Craft.asciiString(handle);\n\n    if (!this.settings.allowNonAlphaStart) {\n      // Handle must start with a letter\n      handle = handle.replace(/^[^a-z]+/, '');\n    }\n\n    // Get the \"words\"\n    var words = Craft.filterArray(handle.split(/[^a-z0-9]+/));\n    handle = '';\n\n    if (Craft.handleCasing === 'snake') {\n      return words.join('_');\n    }\n\n    // Make it camelCase\n    for (let i = 0; i < words.length; i++) {\n      if (Craft.handleCasing !== 'pascal' && i === 0) {\n        handle += words[i];\n      } else {\n        handle += words[i].charAt(0).toUpperCase() + words[i].substring(1);\n      }\n    }\n\n    return handle;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Image upload class for user photos, site icon and logo.\n */\nCraft.ImageUpload = Garnish.Base.extend(\n  {\n    $container: null,\n    progressBar: null,\n    uploader: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.ImageUpload.defaults);\n      this.initImageUpload();\n    },\n\n    initImageUpload: function () {\n      this.$container = $(this.settings.containerSelector);\n      this.progressBar = new Craft.ProgressBar(\n        $('<div class=\"progress-shade\"></div>').appendTo(this.$container)\n      );\n\n      var options = {\n        url: Craft.getActionUrl(this.settings.uploadAction),\n        formData: this.settings.postParameters,\n        fileInput: this.$container.find(this.settings.fileInputSelector),\n        paramName: this.settings.uploadParamName,\n      };\n\n      // If CSRF protection isn't enabled, these won't be defined.\n      if (\n        typeof Craft.csrfTokenName !== 'undefined' &&\n        typeof Craft.csrfTokenValue !== 'undefined'\n      ) {\n        // Add the CSRF token\n        options.formData[Craft.csrfTokenName] = Craft.csrfTokenValue;\n      }\n\n      options.events = {};\n      options.events.fileuploadstart = this._onUploadStart.bind(this);\n      options.events.fileuploadprogressall = this._onUploadProgress.bind(this);\n      options.events.fileuploaddone = this._onUploadComplete.bind(this);\n      options.events.fileuploadfail = this._onUploadFailure.bind(this);\n\n      this.uploader = new Craft.Uploader(this.$container, options);\n\n      this.initButtons();\n    },\n\n    initButtons: function () {\n      this.$container\n        .find(this.settings.uploadButtonSelector)\n        .on('click', (ev) => {\n          this.$container\n            .find(this.settings.fileInputSelector)\n            .trigger('click');\n        });\n\n      this.$container\n        .find(this.settings.deleteButtonSelector)\n        .on('click', (ev) => {\n          if (\n            confirm(\n              Craft.t('app', 'Are you sure you want to delete this image?')\n            )\n          ) {\n            $(ev.currentTarget)\n              .parent()\n              .append('<div class=\"blocking-modal\"></div>');\n\n            Craft.sendActionRequest('POST', this.settings.deleteAction, {\n              data: this.settings.postParameters,\n            }).then(({data}) => {\n              this.refreshImage(data);\n            });\n          }\n        });\n    },\n\n    refreshImage: function (response) {\n      $(this.settings.containerSelector).replaceWith(response.html);\n      this.settings.onAfterRefreshImage(response);\n      this.initImageUpload();\n    },\n\n    /**\n     * On upload start.\n     */\n    _onUploadStart: function (event) {\n      this.progressBar.$progressBar.css({\n        top: Math.round(this.$container.outerHeight() / 2) - 6,\n      });\n\n      this.$container.addClass('uploading');\n      this.progressBar.resetProgressBar();\n      this.progressBar.showProgressBar();\n    },\n\n    /**\n     * On upload progress.\n     */\n    _onUploadProgress: function (event, data) {\n      var progress = parseInt((data.loaded / data.total) * 100, 10);\n      this.progressBar.setProgressPercentage(progress);\n    },\n\n    /**\n     * On a file being uploaded.\n     */\n    _onUploadComplete: function (event, data) {\n      if (data.result.error) {\n        Craft.cp.displayError(data.result.error);\n      } else {\n        var html = $(data.result.html);\n        this.refreshImage(data.result);\n      }\n\n      // Last file\n      if (this.uploader.isLastUpload()) {\n        this.progressBar.hideProgressBar();\n        this.$container.removeClass('uploading');\n      }\n    },\n\n    /**\n     * On Upload Failure.\n     */\n    _onUploadFailure: function (event, data) {\n      const response = data.response();\n      let {message, filename} = response?.jqXHR?.responseJSON || {};\n\n      if (!message) {\n        message = filename\n          ? Craft.t('app', 'Upload failed for “{filename}”.', {filename})\n          : Craft.t('app', 'Upload failed.');\n      }\n\n      Craft.cp.displayError(message);\n      this.progressBar.hideProgressBar();\n      this.$container.removeClass('uploading');\n    },\n  },\n  {\n    defaults: {\n      postParameters: {},\n      uploadAction: '',\n      deleteAction: '',\n      fileInputSelector: '',\n\n      onAfterRefreshImage: $.noop,\n      containerSelector: null,\n\n      uploadButtonSelector: null,\n      deleteButtonSelector: null,\n\n      uploadParamName: 'files',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Info icon class\n */\nCraft.InfoIcon = Garnish.Base.extend({\n  $container: null,\n  $icon: null,\n  $liveRegion: null,\n  content: null,\n  hud: null,\n\n  init: function (icon) {\n    this.$icon = $(icon);\n    this.$liveRegion = $('<span/>', {\n      role: 'status',\n      class: 'visually-hidden',\n    });\n\n    if (this.$icon.data('infoicon')) {\n      console.warn('Double-instantiating an info icon on an element');\n      this.content = this.$icon.data('infoicon').content;\n      this.$icon.data('infoicon').destroy();\n    } else {\n      this.content = this.$icon.html();\n      this.$icon\n        .html('')\n        .attr({\n          tabindex: 0,\n          role: 'button',\n          type: 'button',\n          'aria-label': Craft.t('app', 'More info'),\n        })\n        .wrap(\n          $('<span/>', {\n            class: 'infoicon-container',\n          })\n        );\n\n      this.$container = this.$icon.parent();\n      this.$container.append(this.$liveRegion);\n    }\n\n    this.$icon.data('infoicon', this);\n\n    if (\n      this.$icon[0].previousSibling &&\n      this.$icon[0].previousSibling.nodeType === Node.TEXT_NODE\n    ) {\n      // Make sure it's in a .nowrap container\n      const $parent = this.$icon.parent();\n      if (!$parent.hasClass('nowrap')) {\n        // Find the last word in the text\n        const m = this.$icon[0].previousSibling.nodeValue.match(/[^\\s\\-]+\\s*$/);\n        if (m) {\n          this.$icon[0].previousSibling.nodeValue =\n            this.$icon[0].previousSibling.nodeValue.substring(0, m.index);\n          $('<span/>', {\n            class: 'nowrap',\n            html: m[0].replace(/\\s+$/, '') + ' ',\n          })\n            .insertAfter(this.$icon[0].previousSibling)\n            .append(this.$icon);\n        }\n      }\n    }\n\n    this.addListener(this.$icon, 'click', (ev) => {\n      ev.preventDefault();\n      ev.stopPropagation();\n      this.showHud();\n    });\n\n    this.addListener(this.$icon, 'keydown', (ev) => {\n      if (\n        !(this.hud && this.hud.showing) &&\n        [Garnish.SPACE_KEY, Garnish.RETURN_KEY].includes(ev.keyCode)\n      ) {\n        ev.preventDefault();\n        ev.stopPropagation();\n        this.showHud();\n      }\n    });\n  },\n\n  showHud: function (ev) {\n    if (!this.hud) {\n      this.hud = new Garnish.HUD(this.$icon, this.content, {\n        hudClass: 'hud info-hud',\n        closeOtherHUDs: false,\n        onShow: () => {\n          Garnish.uiLayerManager.registerShortcut(Garnish.SPACE_KEY, () => {\n            this.hud.hide();\n          });\n\n          this.$liveRegion.html('');\n\n          setTimeout(() => {\n            this.$liveRegion.html(this.content);\n          }, 200);\n        },\n        onHide: () => {\n          this.$liveRegion.html('');\n        },\n      });\n      Craft.initUiElements(this.hud.$body);\n    } else {\n      this.hud.show();\n    }\n  },\n\n  destroy: function () {\n    this.$icon.removeData('infoicon');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Light Switch\n */\nCraft.LightSwitch = Garnish.Base.extend(\n  {\n    settings: null,\n    $outerContainer: null,\n    $innerContainer: null,\n    $input: null,\n    small: false,\n    on: false,\n    indeterminate: false,\n    dragger: null,\n\n    dragStartMargin: null,\n\n    init: function (outerContainer, settings) {\n      this.$outerContainer = $(outerContainer);\n\n      // Is this already a lightswitch?\n      if (this.$outerContainer.data('lightswitch')) {\n        console.warn('Double-instantiating a lightswitch on an element');\n        this.$outerContainer.data('lightswitch').destroy();\n      }\n\n      this.$outerContainer.data('lightswitch', this);\n\n      this.small = this.$outerContainer.hasClass('small');\n\n      this.setSettings(settings, Craft.LightSwitch.defaults);\n\n      this.$innerContainer = this.$outerContainer.find(\n        '.lightswitch-container:first'\n      );\n      this.$input = this.$outerContainer.find('input:first');\n\n      // If the input is disabled, go no further\n      if (this.$input.prop('disabled')) {\n        return;\n      }\n\n      this.on = this.$outerContainer.hasClass('on');\n      this.indeterminate = this.$outerContainer.hasClass('indeterminate');\n\n      this.addListener(this.$outerContainer, 'mousedown', '_onMouseDown');\n      this.addListener(this.$outerContainer, 'keydown', '_onKeyDown');\n\n      this.dragger = new Garnish.BaseDrag(this.$outerContainer, {\n        axis: Garnish.X_AXIS,\n        ignoreHandleSelector: null,\n        onDragStart: this._onDragStart.bind(this),\n        onDrag: this._onDrag.bind(this),\n        onDragStop: this._onDragStop.bind(this),\n      });\n\n      // Does the input have on/off labels?\n      let $wrapper = this.$outerContainer.parent(\n        '.lightswitch-inner-container'\n      );\n      if ($wrapper.length) {\n        this.addListener(\n          $wrapper.children('span[data-toggle=\"off\"]'),\n          'click',\n          this.turnOff\n        );\n        this.addListener(\n          $wrapper.children('span[data-toggle=\"on\"]'),\n          'click',\n          this.turnOn\n        );\n      }\n    },\n\n    turnOn: function (muteEvent) {\n      var changed = !this.on;\n\n      this.on = true;\n      this.indeterminate = false;\n\n      this.$outerContainer.addClass('dragging');\n\n      if (Garnish.prefersReducedMotion()) {\n        this.$innerContainer.css('margin-' + Craft.left, 0);\n      } else {\n        var animateCss = {};\n        animateCss['margin-' + Craft.left] = 0;\n        this.$innerContainer\n          .velocity('stop')\n          .velocity(\n            animateCss,\n            Craft.LightSwitch.animationDuration,\n            this._onSettle.bind(this)\n          );\n      }\n\n      this.$input.val(this.settings.value);\n      this.$outerContainer.addClass('on');\n      this.$outerContainer.removeClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'true');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    turnOff: function (muteEvent) {\n      var changed = this.on || this.indeterminate;\n\n      this.on = false;\n      this.indeterminate = false;\n\n      this.$outerContainer.addClass('dragging');\n\n      if (Garnish.prefersReducedMotion()) {\n        this.$innerContainer.css('margin-' + Craft.left, this._getOffMargin());\n      } else {\n        var animateCss = {};\n        animateCss['margin-' + Craft.left] = this._getOffMargin();\n        this.$innerContainer\n          .velocity('stop')\n          .velocity(\n            animateCss,\n            Craft.LightSwitch.animationDuration,\n            this._onSettle.bind(this)\n          );\n      }\n\n      this.$input.val('');\n      this.$outerContainer.removeClass('on');\n      this.$outerContainer.removeClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'false');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    turnIndeterminate: function (muteEvent) {\n      var changed = !this.indeterminate;\n\n      this.on = false;\n      this.indeterminate = true;\n\n      this.$outerContainer.addClass('dragging');\n      var animateCss = {};\n      animateCss['margin-' + Craft.left] = this._getOffMargin() / 2;\n      this.$innerContainer\n        .velocity('stop')\n        .velocity(\n          animateCss,\n          Craft.LightSwitch.animationDuration,\n          this._onSettle.bind(this)\n        );\n\n      this.$input.val(this.settings.indeterminateValue);\n      this.$outerContainer.removeClass('on');\n      this.$outerContainer.addClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'mixed');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    toggle: function () {\n      if (this.indeterminate || !this.on) {\n        this.turnOn();\n      } else {\n        this.turnOff();\n      }\n    },\n\n    onChange: function () {\n      this.trigger('change');\n      this.settings.onChange(this.on);\n      this.$outerContainer.trigger('change');\n    },\n\n    _onMouseDown: function () {\n      this.addListener(Garnish.$doc, 'mouseup', '_onMouseUp');\n    },\n\n    _onMouseUp: function () {\n      this.removeListener(Garnish.$doc, 'mouseup');\n\n      // Was this a click?\n      if (!this.dragger.dragging) {\n        this.toggle();\n      }\n    },\n\n    _onKeyDown: function (event) {\n      switch (event.keyCode) {\n        case Garnish.SPACE_KEY: {\n          this.toggle();\n          event.preventDefault();\n          break;\n        }\n        case Garnish.RIGHT_KEY: {\n          if (Craft.orientation === 'ltr') {\n            this.turnOn();\n          } else {\n            this.turnOff();\n          }\n\n          event.preventDefault();\n          break;\n        }\n        case Garnish.LEFT_KEY: {\n          if (Craft.orientation === 'ltr') {\n            this.turnOff();\n          } else {\n            this.turnOn();\n          }\n\n          event.preventDefault();\n          break;\n        }\n      }\n    },\n\n    _getMargin: function () {\n      return parseInt(this.$innerContainer.css('margin-' + Craft.left));\n    },\n\n    _onDragStart: function () {\n      this.$outerContainer.addClass('dragging');\n      this.dragStartMargin = this._getMargin();\n    },\n\n    _onDrag: function () {\n      var margin;\n\n      if (Craft.orientation === 'ltr') {\n        margin = this.dragStartMargin + this.dragger.mouseDistX;\n      } else {\n        margin = this.dragStartMargin - this.dragger.mouseDistX;\n      }\n\n      if (margin < this._getOffMargin()) {\n        margin = this._getOffMargin();\n      } else if (margin > 0) {\n        margin = 0;\n      }\n\n      this.$innerContainer.css('margin-' + Craft.left, margin);\n    },\n\n    _onDragStop: function () {\n      var margin = this._getMargin();\n\n      if (margin > this._getOffMargin() / 2) {\n        this.turnOn();\n      } else {\n        this.turnOff();\n      }\n    },\n\n    _onSettle: function () {\n      this.$outerContainer.removeClass('dragging');\n    },\n\n    destroy: function () {\n      this.$outerContainer.removeData('lightswitch');\n      this.base();\n      this.dragger.destroy();\n    },\n\n    _getOffMargin: function () {\n      return this.small ? -10 : -12;\n    },\n  },\n  {\n    animationDuration: 100,\n    defaults: {\n      value: '1',\n      indeterminateValue: '-',\n      onChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Listbox\n */\nCraft.Listbox = Garnish.Base.extend(\n  {\n    $container: null,\n    $options: null,\n    $selectedOption: null,\n    selectedOptionIndex: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.Listbox.defaults);\n\n      // Is this already a listbox?\n      if (this.$container.data('listbox')) {\n        console.warn('Double-instantiating a listbox on an element');\n        this.$container.data('listbox').destroy();\n      }\n\n      this.$container.data('listbox', this);\n      // todo: drop [role=option] in Craft 5\n      this.$options = this.$container.find('button,[role=option]');\n\n      // is there already a selected option?\n      // todo: drop [aria-selected=true] & attr normalization in Craft 5\n      this.$selectedOption = this.$options\n        .filter('[aria-pressed=true],[aria-selected=true]')\n        .removeAttr('aria-selected')\n        .attr('aria-pressed', 'true');\n      if (this.$selectedOption.length) {\n        this.selectedOptionIndex = this.$options.index(this.$selectedOption);\n      } else {\n        this.$selectedOption = null;\n      }\n\n      this.addListener(this.$options, 'click', (ev) => {\n        this.select(this.$options.index($(ev.currentTarget)));\n        ev.preventDefault();\n      });\n    },\n\n    select: function (index) {\n      if (\n        index < 0 ||\n        index >= this.$options.length ||\n        index === this.selectedOptionIndex\n      ) {\n        return;\n      }\n\n      if (this.$selectedOption) {\n        this.$selectedOption\n          .removeClass(this.settings.selectedClass)\n          .attr('aria-pressed', 'false');\n      }\n\n      this.$selectedOption = this.$options\n        .eq(index)\n        .addClass(this.settings.selectedClass)\n        .attr('aria-pressed', 'true');\n\n      this.selectedOptionIndex = index;\n\n      this.settings.onChange(this.$selectedOption, index);\n      this.trigger('change', {\n        $selectedOption: this.$selectedOption,\n        selectedOptionIndex: index,\n      });\n    },\n\n    disable: function () {\n      this.base();\n      this.$container.attr('aria-disabled', 'true');\n    },\n\n    enable: function () {\n      this.base();\n      this.$container.removeAttr('aria-disabled');\n    },\n\n    destroy: function () {\n      this.$container.removeData('listbox');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      selectedClass: 'active',\n      focusClass: 'focus',\n      onChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Live Preview\n */\nCraft.LivePreview = Garnish.Base.extend(\n  {\n    $extraFields: null,\n    $trigger: null,\n    $shade: null,\n    $editorContainer: null,\n    $editor: null,\n    $dragHandle: null,\n    $previewContainer: null,\n    $iframeContainer: null,\n    $iframe: null,\n    $fieldPlaceholder: null,\n\n    previewUrl: null,\n    token: null,\n    basePostData: null,\n    inPreviewMode: false,\n    fields: null,\n    lastPostData: null,\n    updateIframeInterval: null,\n    loading: false,\n    checkAgain: false,\n\n    dragger: null,\n    dragStartEditorWidth: null,\n\n    _slideInOnIframeLoad: false,\n\n    _scrollX: null,\n    _scrollY: null,\n\n    _editorWidth: null,\n    _editorWidthInPx: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.LivePreview.defaults);\n\n      // Should preview requests use a specific URL?\n      // This won't affect how the request gets routed (the action param will override it),\n      // but it will allow the templates to change behavior based on the request URI.\n      if (this.settings.previewUrl) {\n        this.previewUrl = this.settings.previewUrl;\n      } else {\n        this.previewUrl = Craft.baseSiteUrl.replace(/\\/+$/, '') + '/';\n      }\n\n      // Load the preview over SSL if the current request is\n      if (document.location.protocol === 'https:') {\n        this.previewUrl = this.previewUrl.replace(/^http:/, 'https:');\n      }\n\n      // Set the base post data\n      this.basePostData = $.extend({}, this.settings.previewParams);\n\n      // Find the DOM elements\n      this.$extraFields = $(this.settings.extraFields);\n      this.$trigger = $(this.settings.trigger);\n      this.$fieldPlaceholder = $('<div/>');\n\n      // Set the initial editor width\n      this.editorWidth = Craft.getLocalStorage(\n        'LivePreview.editorWidth',\n        Craft.LivePreview.defaultEditorWidth\n      );\n\n      // Event Listeners\n      this.addListener(this.$trigger, 'activate', 'toggle');\n\n      Craft.cp.on('beforeSaveShortcut', () => {\n        if (this.inPreviewMode) {\n          this.moveFieldsBack();\n        }\n      });\n\n      Craft.Preview.instances.push(this);\n    },\n\n    get editorWidth() {\n      return this._editorWidth;\n    },\n\n    get editorWidthInPx() {\n      return this._editorWidthInPx;\n    },\n\n    set editorWidth(width) {\n      var inPx;\n\n      // Is this getting set in pixels?\n      if (width >= 1) {\n        inPx = width;\n        width /= Garnish.$win.width();\n      } else {\n        inPx = Math.round(width * Garnish.$win.width());\n      }\n\n      // Make sure it's no less than the minimum\n      if (inPx < Craft.LivePreview.minEditorWidthInPx) {\n        inPx = Craft.LivePreview.minEditorWidthInPx;\n        width = inPx / Garnish.$win.width();\n      }\n\n      this._editorWidth = width;\n      this._editorWidthInPx = inPx;\n    },\n\n    toggle: function () {\n      if (this.inPreviewMode) {\n        this.exit();\n      } else {\n        this.enter();\n      }\n    },\n\n    enter: function () {\n      if (this.inPreviewMode) {\n        return;\n      }\n\n      if (!this.token) {\n        this.createToken();\n        return;\n      }\n\n      this.trigger('beforeEnter');\n\n      $(document.activeElement).trigger('blur');\n\n      if (!this.$editor) {\n        this.$shade = $('<div/>', {class: 'modal-shade dark'}).appendTo(\n          Garnish.$bod\n        );\n        this.$previewContainer = $('<div/>', {\n          class: 'lp-preview-container',\n        }).appendTo(Garnish.$bod);\n        this.$iframeContainer = $('<div/>', {\n          class: 'lp-iframe-container',\n        }).appendTo(this.$previewContainer);\n        this.$editorContainer = $('<div/>', {\n          class: 'lp-editor-container',\n        }).appendTo(Garnish.$bod);\n\n        var $editorHeader = $('<header/>', {class: 'flex'}).appendTo(\n          this.$editorContainer\n        );\n        this.$editor = $('<form/>', {class: 'lp-editor'}).appendTo(\n          this.$editorContainer\n        );\n        this.$dragHandle = $('<div/>', {class: 'lp-draghandle'}).appendTo(\n          this.$editorContainer\n        );\n        var $closeBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Close Preview'),\n        }).appendTo($editorHeader);\n        $('<div/>', {class: 'flex-grow'}).appendTo($editorHeader);\n        let $saveBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit',\n          text: Craft.t('app', 'Save'),\n        }).appendTo($editorHeader);\n\n        this.dragger = new Garnish.BaseDrag(this.$dragHandle, {\n          axis: Garnish.X_AXIS,\n          onDragStart: this._onDragStart.bind(this),\n          onDrag: this._onDrag.bind(this),\n          onDragStop: this._onDragStop.bind(this),\n        });\n\n        this.addListener($closeBtn, 'click', 'exit');\n        this.addListener($saveBtn, 'click', 'save');\n      }\n\n      // Set the sizes\n      this.handleWindowResize();\n      this.addListener(Garnish.$win, 'resize', 'handleWindowResize');\n\n      this.$editorContainer.css(Craft.left, -this.editorWidthInPx + 'px');\n      this.$previewContainer.css(Craft.right, -this.getIframeWidth());\n\n      // Move all the fields into the editor rather than copying them\n      // so any JS that's referencing the elements won't break.\n      this.fields = [];\n      var $fields = $(this.settings.fields);\n\n      for (var i = 0; i < $fields.length; i++) {\n        var $field = $($fields[i]),\n          $clone = this._getClone($field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter($field);\n        $field.detach();\n        this.$fieldPlaceholder.replaceWith($clone);\n        $field.appendTo(this.$editor);\n\n        this.fields.push({\n          $field: $field,\n          $clone: $clone,\n        });\n      }\n\n      if (this.updateIframe()) {\n        this._slideInOnIframeLoad = true;\n      } else {\n        this.slideIn();\n      }\n\n      Craft.ElementThumbLoader.retryAll();\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.exit();\n      });\n\n      this.inPreviewMode = true;\n      this.trigger('enter');\n    },\n\n    createToken: function () {\n      const data = {previewAction: this.settings.previewAction};\n      Craft.sendActionRequest('POST', 'live-preview/create-token', {data}).then(\n        (response) => {\n          this.token = response.data.token;\n          this.enter();\n        }\n      );\n    },\n\n    save: function () {\n      Craft.cp.submitPrimaryForm();\n    },\n\n    handleWindowResize: function () {\n      // Reset the width so the min width is enforced\n      this.editorWidth = this.editorWidth;\n\n      // Update the editor/iframe sizes\n      this.updateWidths();\n    },\n\n    slideIn: function () {\n      $('html').addClass('noscroll');\n      this.$shade.velocity('fadeIn');\n\n      this.$editorContainer\n        .show()\n        .velocity('stop')\n        .animateLeft(0, 'slow', () => {\n          this.trigger('slideIn');\n          Garnish.$win.trigger('resize');\n        });\n\n      this.$previewContainer\n        .show()\n        .velocity('stop')\n        .animateRight(0, 'slow', () => {\n          this.updateIframeInterval = setInterval(\n            this.updateIframe.bind(this),\n            1000\n          );\n        });\n    },\n\n    exit: function () {\n      if (!this.inPreviewMode) {\n        return;\n      }\n\n      this.trigger('beforeExit');\n\n      $('html').removeClass('noscroll');\n\n      this.removeListener(Garnish.$win, 'resize');\n      Garnish.uiLayerManager.removeLayer();\n\n      if (this.updateIframeInterval) {\n        clearInterval(this.updateIframeInterval);\n      }\n\n      this.moveFieldsBack();\n\n      this.$shade.delay(200).velocity('fadeOut');\n\n      this.$editorContainer\n        .velocity('stop')\n        .animateLeft(-this.editorWidthInPx, 'slow', () => {\n          for (var i = 0; i < this.fields.length; i++) {\n            this.fields[i].$newClone.remove();\n          }\n          this.$editorContainer.hide();\n          this.trigger('slideOut');\n        });\n\n      this.$previewContainer\n        .velocity('stop')\n        .animateRight(-this.getIframeWidth(), 'slow', () => {\n          this.$previewContainer.hide();\n        });\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.inPreviewMode = false;\n      this.trigger('exit');\n    },\n\n    moveFieldsBack: function () {\n      for (var i = 0; i < this.fields.length; i++) {\n        var field = this.fields[i];\n        field.$newClone = this._getClone(field.$field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter(field.$field);\n        field.$field.detach();\n        this.$fieldPlaceholder.replaceWith(field.$newClone);\n        field.$clone.replaceWith(field.$field);\n      }\n\n      Garnish.$win.trigger('resize');\n    },\n\n    getIframeWidth: function () {\n      return Garnish.$win.width() - this.editorWidthInPx;\n    },\n\n    updateWidths: function () {\n      this.$editorContainer.css('width', this.editorWidthInPx + 'px');\n      this.$previewContainer.width(this.getIframeWidth());\n    },\n\n    updateIframe: function (force) {\n      if (force) {\n        this.lastPostData = null;\n      }\n\n      if (!this.inPreviewMode) {\n        return false;\n      }\n\n      if (this.loading) {\n        this.checkAgain = true;\n        return false;\n      }\n\n      // Has the post data changed?\n      var postData = $.extend(\n        Garnish.getPostData(this.$editor),\n        Garnish.getPostData(this.$extraFields)\n      );\n\n      if (\n        !this.lastPostData ||\n        !Craft.compare(postData, this.lastPostData, false)\n      ) {\n        this.lastPostData = postData;\n        this.loading = true;\n\n        var $doc = this.$iframe\n          ? $(this.$iframe[0].contentWindow.document)\n          : null;\n\n        this._scrollX = $doc ? $doc.scrollLeft() : 0;\n        this._scrollY = $doc ? $doc.scrollTop() : 0;\n\n        $.ajax({\n          url:\n            this.previewUrl +\n            (this.previewUrl.indexOf('?') !== -1 ? '&' : '?') +\n            Craft.tokenParam +\n            '=' +\n            this.token,\n          method: 'POST',\n          data: $.extend({}, postData, this.basePostData),\n          headers: {\n            'X-Craft-Token': this.token,\n          },\n          xhrFields: {\n            withCredentials: true,\n          },\n          crossDomain: true,\n          success: this.handleSuccess.bind(this),\n          error: this.handleError.bind(this),\n        });\n\n        return true;\n      } else {\n        return false;\n      }\n    },\n\n    forceUpdateIframe: function () {\n      return this.updateIframe(true);\n    },\n\n    handleSuccess: function (data) {\n      var html =\n        data +\n        '<script type=\"text/javascript\">window.scrollTo(' +\n        this._scrollX +\n        ', ' +\n        this._scrollY +\n        ');</script>';\n\n      // Create a new iframe\n      var $iframe = $('<iframe class=\"lp-preview\" frameborder=\"0\"/>');\n      if (this.$iframe) {\n        $iframe.insertBefore(this.$iframe);\n      } else {\n        $iframe.appendTo(this.$iframeContainer);\n      }\n\n      this.addListener($iframe, 'load', function () {\n        if (this.$iframe) {\n          this.$iframe.remove();\n        }\n        this.$iframe = $iframe;\n\n        if (this._slideInOnIframeLoad) {\n          this.slideIn();\n          this._slideInOnIframeLoad = false;\n        }\n\n        this.removeListener($iframe, 'load');\n      });\n\n      Garnish.requestAnimationFrame(() => {\n        $iframe[0].contentWindow.document.open();\n        $iframe[0].contentWindow.document.write(html);\n        $iframe[0].contentWindow.document.close();\n        this.onResponse();\n      });\n    },\n\n    handleError: function () {\n      this.onResponse();\n    },\n\n    onResponse: function () {\n      this.loading = false;\n\n      if (this.checkAgain) {\n        this.checkAgain = false;\n        this.updateIframe();\n      }\n    },\n\n    _getClone: function ($field) {\n      var $clone = $field.clone();\n\n      // clone() won't account for input values that have changed since the original HTML set them\n      Garnish.copyInputValues($field, $clone);\n\n      // Remove any id= attributes\n      $clone.attr('id', '');\n      $clone.find('[id]').attr('id', '');\n\n      return $clone;\n    },\n\n    _onDragStart: function () {\n      this.dragStartEditorWidth = this.editorWidthInPx;\n      this.$previewContainer.addClass('dragging');\n    },\n\n    _onDrag: function () {\n      if (Craft.orientation === 'ltr') {\n        this.editorWidth = this.dragStartEditorWidth + this.dragger.mouseDistX;\n      } else {\n        this.editorWidth = this.dragStartEditorWidth - this.dragger.mouseDistX;\n      }\n\n      this.updateWidths();\n    },\n\n    _onDragStop: function () {\n      this.$previewContainer.removeClass('dragging');\n      Craft.setLocalStorage('LivePreview.editorWidth', this.editorWidth);\n    },\n\n    destroy: function () {\n      Craft.Preview.instances = Craft.Preview.instances.filter(\n        (o) => o !== this\n      );\n      this.base();\n    },\n  },\n  {\n    defaultEditorWidth: 0.33,\n    minEditorWidthInPx: 320,\n    instances: [],\n\n    defaults: {\n      trigger: '.livepreviewbtn',\n      fields: null,\n      extraFields: null,\n      previewUrl: null,\n      previewAction: null,\n      previewParams: {},\n    },\n  }\n);\n\nCraft.LivePreview.init = function (settings) {\n  Craft.livePreview = new Craft.LivePreview(settings);\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Password Input\n */\nCraft.PasswordInput = Garnish.Base.extend(\n  {\n    $passwordWrapper: null,\n    $passwordInput: null,\n    $textInput: null,\n    $currentInput: null,\n\n    $showPasswordToggle: null,\n    showingPassword: null,\n\n    init: function (passwordInput, settings) {\n      this.$passwordInput = $(passwordInput);\n      this.$passwordWrapper = this.$passwordInput.parent('.passwordwrapper');\n      this.settings = $.extend({}, Craft.PasswordInput.defaults, settings);\n\n      // Is this already a password input?\n      if (this.$passwordInput.data('passwordInput')) {\n        console.warn('Double-instantiating a password input on an element');\n        this.$passwordInput.data('passwordInput').destroy();\n      }\n\n      this.$passwordInput.data('passwordInput', this);\n\n      this.$showPasswordToggle = $(\n        '<button type=\"button\" class=\"invisible\" />'\n      );\n      this.$showPasswordToggle.addClass('password-toggle');\n      this.$showPasswordToggle.insertAfter(this.$passwordInput);\n\n      this.initInputFocusEvents(this.$passwordInput);\n      this.addListener(this.$showPasswordToggle, 'click', 'onClick');\n      this.hidePassword();\n\n      this.addListener(\n        this.$passwordWrapper.closest('form'),\n        'submit',\n        'hidePassword'\n      );\n    },\n\n    setCurrentInput: function ($input) {\n      if (this.$currentInput) {\n        // Swap the inputs, while preventing the focus animation\n        $input.insertAfter(this.$currentInput);\n        this.$currentInput.detach();\n        $input.trigger('focus');\n\n        // Restore the input value\n        $input.val(this.$currentInput.val());\n      }\n\n      this.$currentInput = $input;\n\n      this.addListener(\n        this.$currentInput,\n        'keypress,keyup,change,blur',\n        'onInputChange'\n      );\n    },\n\n    updateToggleLabel: function (label) {\n      this.$showPasswordToggle.text(label);\n    },\n\n    initInputFocusEvents: function ($input) {\n      this.addListener($input, 'focus', function () {\n        this.$passwordWrapper.addClass('focus');\n      });\n      this.addListener($input, 'blur', function () {\n        this.$passwordWrapper.removeClass('focus');\n      });\n    },\n\n    showPassword: function () {\n      if (this.showingPassword) {\n        return;\n      }\n\n      if (!this.$textInput) {\n        this.$textInput = this.$passwordInput.clone(true);\n        this.$textInput.attr({\n          type: 'text',\n          autocapitalize: 'off',\n        });\n        this.initInputFocusEvents(this.$textInput);\n      }\n\n      this.setCurrentInput(this.$textInput);\n      this.updateToggleLabel(Craft.t('app', 'Hide'));\n      this.showingPassword = true;\n    },\n\n    hidePassword: function () {\n      // showingPassword could be null, which is acceptable\n      if (this.showingPassword === false) {\n        return;\n      }\n\n      this.setCurrentInput(this.$passwordInput);\n      this.updateToggleLabel(Craft.t('app', 'Show'));\n      this.showingPassword = false;\n    },\n\n    togglePassword: function () {\n      if (this.showingPassword) {\n        this.hidePassword();\n      } else {\n        this.showPassword();\n      }\n\n      this.settings.onToggleInput(this.$currentInput);\n    },\n\n    onInputChange: function () {\n      if (this.$currentInput.val()) {\n        this.$showPasswordToggle.removeClass('invisible');\n      } else {\n        this.$showPasswordToggle.addClass('invisible');\n      }\n    },\n\n    onClick: function (ev) {\n      if (this.$currentInput[0].setSelectionRange) {\n        var selectionStart = this.$currentInput[0].selectionStart,\n          selectionEnd = this.$currentInput[0].selectionEnd;\n\n        this.togglePassword();\n        this.$currentInput[0].setSelectionRange(selectionStart, selectionEnd);\n      } else {\n        this.togglePassword();\n      }\n    },\n\n    destroy: function () {\n      this.$passwordInput.removeData('passwordInput');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      onToggleInput: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Preview\n */\nCraft.Preview = Garnish.Base.extend(\n  {\n    elementEditor: null,\n\n    $shade: null,\n    $editorContainer: null,\n    $editor: null,\n    $spinner: null,\n    $statusIcon: null,\n    $dragHandle: null,\n    $previewWrapper: null,\n    $previewContainer: null,\n    $previewSkipLink: null,\n    $bumperLink: null,\n    $notifier: null,\n    $iframeContainer: null,\n    $previewHeader: null,\n    $targetBtn: null,\n    $targetMenu: null,\n    $deviceTypeContainer: null,\n    $orientationBtn: null,\n    $refreshBtn: null,\n    $deviceMask: null,\n    $devicePreviewContainer: null,\n    $iframe: null,\n    iframeLoaded: false,\n    $tempInput: null,\n    $fieldPlaceholder: null,\n\n    isActive: false,\n    isVisible: false,\n    activeTarget: 0,\n\n    animationDuration: 'slow',\n\n    currentDeviceType: 'desktop',\n    deviceOrientation: null,\n    deviceWidth: '',\n    deviceHeight: '',\n    deviceMaskDimensions: {\n      phone: {\n        width: 375,\n        height: 753,\n      },\n      tablet: {\n        width: 768,\n        height: 1110,\n      },\n    },\n\n    draftId: null,\n    url: null,\n    fields: null,\n\n    iframeHeight: null,\n    scrollTop: null,\n    scrollLeft: null,\n\n    dragger: null,\n    dragStartEditorWidth: null,\n\n    _updateIframeProxy: null,\n\n    _editorWidth: null,\n    _editorWidthInPx: null,\n\n    init: function (elementEditor) {\n      this.elementEditor = elementEditor;\n\n      this._updateIframeProxy = this.updateIframe.bind(this);\n\n      this.$tempInput = $('<input/>', {\n        type: 'hidden',\n        name: '__PREVIEW_FIELDS__',\n        value: '1',\n      });\n      this.$fieldPlaceholder = $('<div/>');\n\n      // Set the initial editor width\n      this.editorWidth = Craft.getLocalStorage(\n        'LivePreview.editorWidth',\n        Craft.Preview.defaultEditorWidth\n      );\n\n      Craft.Preview.instances.push(this);\n    },\n\n    get editorWidth() {\n      return this._editorWidth;\n    },\n\n    get editorWidthInPx() {\n      return this._editorWidthInPx;\n    },\n\n    set editorWidth(width) {\n      var inPx;\n\n      // Is this getting set in pixels?\n      if (width >= 1) {\n        inPx = width;\n        width /= Garnish.$win.width();\n      } else {\n        inPx = Math.round(width * Garnish.$win.width());\n      }\n\n      // Make sure it's no less than the minimum\n      if (inPx < Craft.Preview.minEditorWidthInPx) {\n        inPx = Craft.Preview.minEditorWidthInPx;\n        width = inPx / Garnish.$win.width();\n      }\n\n      this._editorWidth = width;\n      this._editorWidthInPx = inPx;\n    },\n\n    open: function () {\n      if (this.isActive) {\n        return;\n      }\n\n      this.isActive = true;\n      this.trigger('beforeOpen');\n\n      $(document.activeElement).trigger('blur');\n\n      if (!this.$editor) {\n        const previewSkipLinkText = Craft.t('app', 'Skip to {title}', {\n          title: Craft.t('app', 'Top of preview'),\n        });\n\n        this.$shade = $('<div/>', {class: 'modal-shade dark'}).appendTo(\n          Garnish.$bod\n        );\n        this.$previewWrapper = $('<div/>', {\n          role: 'dialog',\n          'aria-modal': 'true',\n          'aria-labelledby': 'lp-preview-heading',\n        }).appendTo(Garnish.$bod);\n        this.$modalLabel = $('<h2/>', {\n          id: 'lp-preview-heading',\n          class: 'visually-hidden',\n          html: Craft.t('app', 'Preview'),\n        }).appendTo(this.$previewWrapper);\n        this.$editorContainer = $('<div/>', {\n          class: 'lp-editor-container',\n        }).appendTo(this.$previewWrapper);\n        this.$previewContainer = $('<div/>', {\n          class: 'lp-preview-container',\n          id: 'lp-preview-container',\n        }).appendTo(this.$previewWrapper);\n        this.$notifier = $('<span/>', {\n          class: 'visually-hidden',\n          'aria-live': 'assertive',\n        }).appendTo(this.$previewContainer);\n\n        var $editorHeader = $('<header/>', {class: 'flex'}).appendTo(\n          this.$editorContainer\n        );\n        this.$editor = $('<form/>', {class: 'lp-editor'}).appendTo(\n          this.$editorContainer\n        );\n        this.$dragHandle = $('<div/>', {class: 'lp-draghandle'}).appendTo(\n          this.$editorContainer\n        );\n        var $closeBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Close Preview'),\n        }).appendTo($editorHeader);\n        $('<div/>', {class: 'flex-grow'}).appendTo($editorHeader);\n        this.$spinner = $('<div/>', {\n          class: 'spinner hidden',\n          title: Craft.t('app', 'Saving'),\n        }).appendTo($editorHeader);\n        this.$statusIcon = $('<div/>', {class: 'invisible'}).appendTo(\n          $editorHeader\n        );\n        this.$statusMessage = $('<span/>', {\n          class: 'visually-hidden',\n          'aria-live': 'polite',\n        }).appendTo($editorHeader);\n        this.$previewSkipLink = $('<a/>', {\n          class: 'skip-link btn',\n          href: '#lp-preview-container',\n          html: previewSkipLinkText,\n        }).appendTo($editorHeader);\n\n        if (Craft.Pro) {\n          this.$previewHeader = $('<header/>', {\n            class: 'lp-preview-header',\n          }).appendTo(this.$previewContainer);\n\n          // Preview targets\n          if (this.elementEditor.settings.previewTargets.length > 1) {\n            this.$targetBtn = $('<button/>', {\n              type: 'button',\n              class: 'btn menubtn',\n              text: this.elementEditor.settings.previewTargets[0].label,\n            }).appendTo(this.$previewHeader);\n            this.$targetMenu = $('<div/>', {\n              class: 'menu lp-target-menu',\n            }).insertAfter(this.$targetBtn);\n            const $ul = $('<ul/>', {class: 'padded'}).appendTo(\n              this.$targetMenu\n            );\n            let $li, $a;\n            for (\n              let i = 0;\n              i < this.elementEditor.settings.previewTargets.length;\n              i++\n            ) {\n              $li = $('<li/>').appendTo($ul);\n              $a = $('<a/>', {\n                data: {target: i},\n                text: this.elementEditor.settings.previewTargets[i].label,\n                class: i === 0 ? 'sel' : null,\n              }).appendTo($li);\n            }\n            new Garnish.MenuBtn(this.$targetBtn, {\n              onOptionSelect: (option) => {\n                this.switchTarget($(option).data('target'));\n              },\n            });\n\n            $('<div class=\"flex-grow\"/>').appendTo(this.$previewHeader);\n          }\n\n          this._buildDeviceTypeFieldset();\n\n          $('<div class=\"flex-grow\"/>').appendTo(this.$previewHeader);\n          const $buttonContainer = $('<div class=\"buttons\"/>').appendTo(\n            this.$previewHeader\n          );\n\n          // Orientation toggle\n          this.$orientationBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn disabled',\n            'data-icon': 'rotate',\n            'aria-disabled': 'true',\n            text: Craft.t('app', 'Rotate'),\n            'aria-label': Craft.t('app', 'Rotate'),\n          }).appendTo($buttonContainer);\n          this.addListener(this.$orientationBtn, 'click', 'switchOrientation');\n\n          // Refresh button\n          this.$refreshBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn',\n            text: Craft.t('app', 'Refresh'),\n            'data-icon': 'refresh',\n          }).appendTo($buttonContainer);\n          this.addListener(this.$refreshBtn, 'click', () => {\n            this.updateIframe(false, true);\n          });\n\n          // Get the last stored orientation\n          this.deviceOrientation = Craft.getLocalStorage(\n            'LivePreview.orientation'\n          );\n        }\n\n        this.$iframeContainer = $('<div/>', {\n          class: 'lp-iframe-container',\n        }).appendTo(this.$previewContainer);\n        this.$devicePreviewContainer = $('<div/>', {\n          class: 'lp-device-preview-container',\n        }).appendTo(this.$iframeContainer);\n        this.$deviceMask = $('<div/>', {\n          class: 'lp-device-mask',\n        }).appendTo(this.$iframeContainer);\n\n        /* Prevents focus trap bug caused by iframe as last element */\n        this.$bumperLink = $('<a/>', {\n          class: 'skip-link btn lp-preview-container__bumper-link',\n          html: previewSkipLinkText,\n          href: '#lp-preview-container',\n        });\n        this.$bumperLink.appendTo(this.$previewContainer);\n\n        this.dragger = new Garnish.BaseDrag(this.$dragHandle, {\n          axis: Garnish.X_AXIS,\n          onDragStart: this._onDragStart.bind(this),\n          onDrag: this._onDrag.bind(this),\n          onDragStop: this._onDragStop.bind(this),\n        });\n\n        this.addListener($closeBtn, 'click', 'close');\n        this.addListener(this.$statusIcon, 'click', () => {\n          this.elementEditor.showStatusHud(this.$statusIcon);\n        });\n      }\n\n      // Set the sizes\n      this.handleWindowResize();\n      this.addListener(Garnish.$win, 'resize', 'handleWindowResize');\n\n      this.$editorContainer.css(Craft.left, -this.editorWidthInPx + 'px');\n      this.$previewContainer.css(Craft.right, -this.getIframeWidth());\n\n      // Find the fields, excluding nested fields\n      this.fields = [];\n      var $fields = $('#content .field').not($('#content .field .field'));\n\n      if ($fields.length) {\n        // Insert our temporary input before the first field so we know where to swap in the serialized form values\n        this.$tempInput.insertBefore($fields.get(0));\n\n        // Move all the fields into the editor rather than copying them\n        // so any JS that's referencing the elements won't break.\n        for (let i = 0; i < $fields.length; i++) {\n          let $field = $($fields[i]),\n            $clone = this._getClone($field);\n\n          // It's important that the actual field is added to the DOM *after* the clone,\n          // so any radio buttons in the field get deselected from the clone rather than the actual field.\n          this.$fieldPlaceholder.insertAfter($field);\n          $field.detach();\n          this.$fieldPlaceholder.replaceWith($clone);\n          $field.appendTo(this.$editor);\n\n          this.fields.push({\n            $field: $field,\n            $clone: $clone,\n          });\n        }\n      }\n\n      this.updateIframe();\n\n      this.elementEditor.on('update', this._updateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.trigger('open');\n    },\n\n    _getDeviceTypeTranslation: function (type) {\n      let translation;\n      switch (type) {\n        case 'phone':\n          translation = Craft.t('app', 'Mobile');\n          break;\n        case 'tablet':\n          translation = Craft.t('app', 'Tablet');\n          break;\n        default:\n          translation = Craft.t('app', 'Desktop');\n          break;\n      }\n      return translation;\n    },\n\n    _getDeviceOrientationTranslation: function (orientation) {\n      return orientation === 'portrait'\n        ? Craft.t('app', 'Portrait')\n        : Craft.t('app', 'Landscape');\n    },\n\n    _buildDeviceTypeFieldset: function () {\n      // Device type buttons\n      this.$deviceTypeContainer = $('<section/>', {\n        class: 'btngroup lp-device-type',\n        'aria-label': Craft.t('app', 'Device type'),\n      }).appendTo(this.$previewHeader);\n      $('<button/>', {\n        type: 'button',\n        class: 'btn lp-device-type-btn--desktop active',\n        title: Craft.t('app', 'Desktop'),\n        'aria-label': Craft.t('app', 'Desktop'),\n        'aria-pressed': 'true',\n        data: {\n          width: '',\n          height: '',\n          deviceType: 'desktop',\n        },\n      }).appendTo(this.$deviceTypeContainer);\n      $('<button/>', {\n        type: 'button',\n        class: 'btn lp-device-type-btn--tablet',\n        title: Craft.t('app', 'Tablet'),\n        'aria-label': Craft.t('app', 'Tablet'),\n        'aria-pressed': 'false',\n        data: {\n          width: 768,\n          height: 1024,\n          deviceType: 'tablet',\n        },\n      }).appendTo(this.$deviceTypeContainer);\n      $('<button/>', {\n        type: 'button',\n        class: 'btn lp-device-type-btn--phone',\n        title: Craft.t('app', 'Mobile'),\n        'aria-label': Craft.t('app', 'Mobile'),\n        'aria-pressed': 'false',\n        data: {\n          width: 375,\n          height: 667,\n          deviceType: 'phone',\n        },\n      }).appendTo(this.$deviceTypeContainer);\n\n      // Add functionality\n      this.deviceBtnGroup = new Craft.Listbox(this.$deviceTypeContainer, {\n        onChange: ($selectedOption) => {\n          this.switchDeviceType($selectedOption);\n        },\n      });\n    },\n\n    _activeTarget: function () {\n      return this.elementEditor.settings.previewTargets[this.activeTarget];\n    },\n\n    /**\n     * @returns {boolean}\n     * @private\n     */\n    _autoRefresh: function () {\n      const target = this._activeTarget();\n      return typeof typeof target.refresh === 'undefined' || !!target.refresh;\n    },\n\n    switchTarget: function (i) {\n      this.activeTarget = i;\n      this.$targetBtn.text(this.elementEditor.settings.previewTargets[i].label);\n      this.$targetMenu.find('a.sel').removeClass('sel');\n      this.$targetMenu.find('a').eq(i).addClass('sel');\n      this.updateIframe(true);\n      this.trigger('switchTarget', {\n        previewTarget: this.elementEditor.settings.previewTargets[i],\n      });\n    },\n\n    handleWindowResize: function () {\n      // Reset the width so the min width is enforced\n      this.editorWidth = this.editorWidth;\n\n      // Update the editor/iframe sizes\n      this.updateWidths();\n    },\n\n    slideIn: function () {\n      if (!this.isActive || this.isVisible) {\n        return;\n      }\n\n      $('html').addClass('noscroll');\n      this.$shade.velocity('fadeIn');\n\n      this.$editorContainer\n        .show()\n        .velocity('stop')\n        .animateLeft(\n          0,\n          Garnish.getUserPreferredAnimationDuration(this.animationDuration),\n          () => {\n            this.trigger('slideIn');\n            Garnish.$win.trigger('resize');\n          }\n        );\n\n      this.$previewContainer\n        .show()\n        .velocity('stop')\n        .animateRight(\n          0,\n          Garnish.getUserPreferredAnimationDuration(this.animationDuration)\n        );\n\n      this.isVisible = true;\n\n      Garnish.uiLayerManager.addLayer(this.$previewWrapper);\n      Garnish.hideModalBackgroundLayers();\n      Craft.setFocusWithin(this.$previewWrapper);\n      Craft.trapFocusWithin(this.$previewWrapper);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.close();\n      });\n    },\n\n    close: function () {\n      if (!this.isActive || !this.isVisible) {\n        return;\n      }\n\n      this.trigger('beforeClose');\n\n      $('html').removeClass('noscroll');\n\n      this.removeListener(Garnish.$win, 'resize');\n      Garnish.uiLayerManager.removeLayer();\n      Garnish.resetModalBackgroundLayerVisibility();\n\n      // Remove our temporary input and move the preview fields back into place\n      this.$tempInput.detach();\n      this.moveFieldsBack();\n\n      // Delay shade fade-out when animation is present\n      if (Garnish.prefersReducedMotion()) {\n        this.$shade.velocity('fadeOut');\n      } else {\n        this.$shade.delay(200).velocity('fadeOut');\n      }\n\n      this.$editorContainer\n        .velocity('stop')\n        .animateLeft(\n          -this.editorWidthInPx,\n          Garnish.getUserPreferredAnimationDuration(this.animationDuration),\n          () => {\n            for (var i = 0; i < this.fields.length; i++) {\n              this.fields[i].$newClone.remove();\n            }\n            this.$editorContainer.hide();\n            this.trigger('slideOut');\n          }\n        );\n\n      this.$previewContainer\n        .velocity('stop')\n        .animateRight(\n          -this.getIframeWidth(),\n          Garnish.getUserPreferredAnimationDuration(this.animationDuration),\n          () => {\n            this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n            this.$previewContainer.hide();\n          }\n        );\n\n      this.elementEditor.off('update', this._updateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      if (this.elementEditor.$previewBtn) {\n        this.elementEditor.$previewBtn.focus();\n      }\n\n      this.isActive = false;\n      this.isVisible = false;\n      this.trigger('close');\n    },\n\n    moveFieldsBack: function () {\n      for (var i = 0; i < this.fields.length; i++) {\n        var field = this.fields[i];\n        field.$newClone = this._getClone(field.$field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter(field.$field);\n        field.$field.detach();\n        this.$fieldPlaceholder.replaceWith(field.$newClone);\n        field.$clone.replaceWith(field.$field);\n      }\n\n      Garnish.$win.trigger('resize');\n      Garnish.$doc.trigger('scroll');\n    },\n\n    getIframeWidth: function () {\n      return Garnish.$win.width() - this.editorWidthInPx;\n    },\n\n    updateWidths: function () {\n      this.$editorContainer.css('width', this.editorWidthInPx + 'px');\n      this.$previewContainer.width(this.getIframeWidth());\n      if (this._devicePreviewIsActive()) {\n        this.updateDevicePreview();\n      }\n    },\n\n    _useIframeResizer: function () {\n      return Craft.previewIframeResizerOptions !== false;\n    },\n\n    /**\n     * @param {boolean} [resetScroll=false]\n     * @param {boolean} [refresh]\n     */\n    updateIframe: function (resetScroll, refresh) {\n      if (!this.isActive) {\n        return false;\n      }\n\n      // Ignore non-boolean resetScroll values\n      resetScroll = resetScroll === true;\n\n      // If the draft ID has changed or there's no iframe, we definitely need to refresh\n      if (\n        this.draftId !== (this.draftId = this.elementEditor.settings.draftId) ||\n        !this.$iframe\n      ) {\n        refresh = true;\n      }\n\n      const target = this._activeTarget();\n      if (typeof refresh === 'undefined') {\n        refresh = resetScroll || this._autoRefresh();\n      }\n\n      this.trigger('beforeUpdateIframe', {\n        previewTarget: target,\n        resetScroll: resetScroll,\n        refresh: refresh,\n      });\n\n      // If this is an existing preview target, make sure it wants to be refreshed automatically\n      if (!refresh) {\n        this.slideIn();\n        return;\n      }\n\n      this.elementEditor\n        .getTokenizedPreviewUrl(target.url, 'x-craft-live-preview')\n        .then((url) => {\n          // Maintain the current scroll position?\n          let sameHost;\n          if (resetScroll) {\n            this.scrollTop = null;\n            this.scrollLeft = null;\n          } else if (this.iframeLoaded && this.$iframe) {\n            if (this._useIframeResizer()) {\n              this.iframeHeight = this.$iframe.height();\n              this.scrollTop = this.$iframeContainer.scrollTop();\n              this.scrollLeft = this.$iframeContainer.scrollLeft();\n            } else {\n              sameHost = Craft.isSameHost(url);\n              if (sameHost && this.$iframe[0].contentWindow) {\n                this.scrollTop = $(\n                  this.$iframe[0].contentWindow.document\n                ).scrollTop();\n\n                this.scrollLeft = $(\n                  this.$iframe[0].contentWindow.document\n                ).scrollLeft();\n              }\n            }\n          }\n\n          this.iframeLoaded = false;\n\n          var $iframe = $('<iframe/>', {\n            class: 'lp-preview',\n            frameborder: 0,\n            src: url,\n            title: Craft.t('app', 'Preview'),\n          });\n\n          if (this.$iframe) {\n            this.$iframe.replaceWith($iframe);\n          } else {\n            $iframe.appendTo(this.$devicePreviewContainer);\n          }\n\n          // Keep the iframe height consistent with its content\n          if (this._useIframeResizer()) {\n            if (!resetScroll && this.iframeHeight !== null) {\n              $iframe.height(this.iframeHeight);\n              this.$iframeContainer.scrollTop(this.scrollTop);\n              this.$iframeContainer.scrollLeft(this.scrollLeft);\n            }\n\n            iFrameResize(\n              $.extend(\n                {\n                  checkOrigin: false,\n                  // Allow iframe scrolling until we've successfully initialized the resizer\n                  scrolling: true,\n                  onInit: (iframe) => {\n                    this.iframeLoaded = true;\n                    this.iframeHeight = null;\n                    this.scrollTop = null;\n                    this.scrollLeft = null;\n                    iframe.scrolling = 'no';\n                  },\n                },\n                Craft.previewIframeResizerOptions || {}\n              ),\n              $iframe[0]\n            );\n          } else {\n            $iframe.on('load', () => {\n              this.iframeLoaded = true;\n              if (!resetScroll && sameHost) {\n                if (this.scrollTop !== null) {\n                  $($iframe[0].contentWindow.document).scrollTop(\n                    this.scrollTop\n                  );\n                }\n\n                if (this.scrollLeft !== null) {\n                  $($iframe[0].contentWindow.document).scrollLeft(\n                    this.scrollLeft\n                  );\n                }\n              }\n            });\n          }\n\n          this.url = url;\n          this.$iframe = $iframe;\n\n          if (this._devicePreviewIsActive()) {\n            this.updateDevicePreview();\n          }\n\n          this.trigger('afterUpdateIframe', {\n            previewTarget:\n              this.elementEditor.settings.previewTargets[this.activeTarget],\n            $iframe: this.$iframe,\n          });\n\n          this.slideIn();\n        });\n    },\n\n    _devicePreviewIsActive: function () {\n      return this.currentDeviceType !== 'desktop';\n    },\n\n    _updateNotifier: function () {\n      this.$notifier.html = '';\n\n      const translation =\n        this.currentDeviceType === 'desktop'\n          ? 'Previewing {type} device'\n          : 'Previewing {type} device in {orientation}';\n      let params = {\n        type: this._getDeviceTypeTranslation(this.currentDeviceType),\n      };\n\n      if (this.currentDeviceType !== 'desktop') {\n        params = {\n          ...params,\n          ...{\n            orientation: this._getDeviceOrientationTranslation(\n              this.deviceOrientation\n            ),\n          },\n        };\n      }\n\n      const message = Craft.t('app', translation, params);\n\n      setTimeout(() => {\n        this.$notifier.text(message);\n      }, 200);\n    },\n\n    switchDeviceType: function ($option) {\n      this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n\n      const newDeviceType = $option.data('deviceType');\n      // Bail if we’re just smashing the same button\n      if (newDeviceType === this.currentDeviceType) {\n        return false;\n      }\n\n      // Store new device type data\n      this.currentDeviceType = newDeviceType;\n      this.deviceWidth = $option.data('width');\n      this.deviceHeight = $option.data('height');\n\n      if (this.currentDeviceType === 'desktop') {\n        // Disable the orientation button\n        this.$orientationBtn.addClass('disabled').attr('aria-disabled', 'true');\n\n        this.$iframeContainer.removeClass(\n          'lp-iframe-container--has-device-preview'\n        );\n      } else {\n        // Enable the orientation button\n        this.$orientationBtn\n          .removeClass('disabled')\n          .removeAttr('aria-disabled');\n\n        this.$iframeContainer.addClass(\n          'lp-iframe-container--has-device-preview'\n        );\n      }\n\n      // Add the tablet class if needed\n      if (this.currentDeviceType === 'tablet') {\n        this.$iframeContainer.addClass('lp-iframe-container--tablet');\n      } else {\n        this.$iframeContainer.removeClass('lp-iframe-container--tablet');\n      }\n\n      this._updateNotifier();\n\n      if (this.currentDeviceType !== 'desktop') {\n        this.updateDevicePreview();\n      }\n    },\n\n    switchOrientation: function () {\n      if (!this._devicePreviewIsActive()) {\n        return false;\n      }\n\n      // Switch to whichever orientation is currently not stored\n      if (!this.deviceOrientation || this.deviceOrientation === 'portrait') {\n        this.deviceOrientation = 'landscape';\n      } else {\n        this.deviceOrientation = 'portrait';\n      }\n\n      // Store the new one\n      Craft.setLocalStorage('LivePreview.orientation', this.deviceOrientation);\n\n      // Allow the animation to take place\n      this.$iframeContainer.addClass('lp-iframe-container--rotating');\n\n      // Update the device preview\n      this.updateDevicePreview();\n      this._updateNotifier();\n\n      setTimeout(() => {\n        this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n      }, 300);\n    },\n\n    updateDevicePreview: function () {\n      // Figure out the best zoom\n      let hZoom = 1;\n      let wZoom = 1;\n      let zoom = 1;\n      let previewHeight = this.$previewContainer.height() - 50 - 48; // 50px for the header bar and 24px clearance\n      let previewWidth = this.$previewContainer.width() - 48;\n      let maskHeight = this.deviceMaskDimensions[this.currentDeviceType].height;\n      let maskWidth = this.deviceMaskDimensions[this.currentDeviceType].width;\n\n      if (this.deviceOrientation === 'landscape') {\n        if (previewWidth < maskHeight) {\n          hZoom = previewWidth / maskHeight;\n        }\n        if (previewHeight < maskWidth) {\n          wZoom = previewHeight / maskWidth;\n        }\n      } else {\n        if (previewHeight < maskHeight) {\n          hZoom = previewHeight / maskHeight;\n        }\n        if (previewWidth < maskWidth) {\n          wZoom = previewWidth / maskWidth;\n        }\n      }\n\n      zoom = hZoom;\n      if (wZoom < hZoom) {\n        zoom = wZoom;\n      }\n\n      // Figure out the css values\n      const translate = -(100 / zoom / 2);\n      const rotationDeg =\n        this.deviceOrientation === 'landscape' ? '-90deg' : '0deg';\n\n      // Apply first to the device mask\n      this.$deviceMask.css({\n        width: this.deviceMaskDimensions[this.currentDeviceType].width + 'px',\n        height: this.deviceMaskDimensions[this.currentDeviceType].height + 'px',\n        transform:\n          'scale(' +\n          zoom +\n          ') translate(' +\n          translate +\n          '%, ' +\n          translate +\n          '%) rotate(' +\n          rotationDeg +\n          ')',\n      });\n\n      if (this.deviceOrientation === 'landscape') {\n        this.$devicePreviewContainer.css({\n          width: this.deviceHeight + 'px',\n          height: this.deviceWidth + 'px',\n          transform:\n            'scale(' +\n            zoom +\n            ') translate(' +\n            translate +\n            '%, ' +\n            translate +\n            '%)',\n          marginTop: 0,\n          marginLeft: '-' + 12 * zoom + 'px',\n        });\n      } else {\n        this.$devicePreviewContainer.css({\n          width: this.deviceWidth + 'px',\n          height: this.deviceHeight + 'px',\n          transform:\n            'scale(' +\n            zoom +\n            ') translate(' +\n            translate +\n            '%, ' +\n            translate +\n            '%)',\n          marginTop: '-' + 12 * zoom + 'px',\n          marginLeft: 0,\n        });\n      }\n    },\n\n    _getClone: function ($field) {\n      var $clone = $field.clone();\n\n      // clone() won't account for input values that have changed since the original HTML set them\n      Garnish.copyInputValues($field, $clone);\n\n      // Remove any id= attributes\n      $clone.attr('id', '');\n      $clone.find('[id]').attr('id', '');\n\n      // Disable anything with a name attribute\n      $clone.find('[name]').prop('disabled', true);\n\n      return $clone;\n    },\n\n    _onDragStart: function () {\n      this.dragStartEditorWidth = this.editorWidthInPx;\n      this.$previewContainer.addClass('dragging');\n    },\n\n    _onDrag: function () {\n      if (Craft.orientation === 'ltr') {\n        this.editorWidth = this.dragStartEditorWidth + this.dragger.mouseDistX;\n      } else {\n        this.editorWidth = this.dragStartEditorWidth - this.dragger.mouseDistX;\n      }\n\n      this.updateWidths();\n    },\n\n    _onDragStop: function () {\n      this.$previewContainer.removeClass('dragging');\n      Craft.setLocalStorage('LivePreview.editorWidth', this.editorWidth);\n    },\n\n    destroy: function () {\n      Craft.Preview.instances = Craft.Preview.instances.filter(\n        (o) => o !== this\n      );\n      this.base();\n    },\n  },\n  {\n    defaultEditorWidth: 0.33,\n    minEditorWidthInPx: 320,\n    instances: [],\n\n    refresh: function () {\n      for (preview of Craft.Preview.instances) {\n        preview.updateIframe();\n      }\n      for (preview of Craft.LivePreview.instances) {\n        preview.forceUpdateIframe();\n      }\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Preview File Modal\n */\nCraft.PreviewFileModal = Garnish.Modal.extend(\n  {\n    assetId: null,\n    $spinner: null,\n    $triggerElement: null,\n    $bumperButtonStart: null,\n    $bumperButtonEnd: null,\n    elementSelect: null,\n    type: null,\n    loaded: null,\n    requestId: 0,\n\n    /**\n     * Initialize the preview file modal.\n     * @returns {*|void}\n     */\n    init: function (assetId, elementSelect, settings) {\n      settings = $.extend(this.defaultSettings, settings);\n      this.$triggerElement = Garnish.getFocusedElement();\n\n      settings.onHide = this._onHide.bind(this);\n\n      if (Craft.PreviewFileModal.openInstance) {\n        var instance = Craft.PreviewFileModal.openInstance;\n\n        if (instance.assetId !== assetId) {\n          instance.loadAsset(\n            assetId,\n            settings.startingWidth,\n            settings.startingHeight\n          );\n          instance.elementSelect = elementSelect;\n        }\n\n        return this.destroy();\n      }\n\n      Craft.PreviewFileModal.openInstance = this;\n      this.elementSelect = elementSelect;\n\n      this.$container = $('<div class=\"modal previewmodal loading\"/>').appendTo(\n        Garnish.$bod\n      );\n\n      this.base(\n        this.$container,\n        $.extend(\n          {\n            resizable: true,\n          },\n          settings\n        )\n      );\n\n      // Cut the flicker, just show the nice person the preview.\n      if (this.$container) {\n        this.$container.velocity('stop');\n        this.$container.show().css('opacity', 1);\n\n        this.$shade.velocity('stop');\n        this.$shade.show().css('opacity', 1);\n\n        Garnish.setFocusWithin(this.$container);\n      }\n\n      // Add bumper elements to maintain focus trap\n      this.$bumperButtonStart = Craft.ui.createButton({\n        html: Craft.t('app', 'Close Preview'),\n        class: 'skip-link',\n      });\n\n      this.addListener(this.$bumperButtonStart, 'click', () => {\n        this.hide();\n      });\n      this.$bumperButtonEnd = this.$bumperButtonStart.clone(true);\n\n      this.loadAsset(assetId, settings.startingWidth, settings.startingHeight);\n    },\n\n    /**\n     * When hiding, remove all traces and focus last focused element.\n     * @private\n     */\n    _onHide: function () {\n      Craft.PreviewFileModal.openInstance = null;\n      if (this.elementSelect) {\n        this.elementSelect.focusItem(this.elementSelect.$focusedItem);\n      } else if (this.$triggerElement && this.$triggerElement.length) {\n        this.$triggerElement.trigger('focus');\n      }\n\n      this.$shade.remove();\n\n      return this.destroy();\n    },\n\n    _addBumperButtons: function () {\n      this.$container\n        .prepend(this.$bumperButtonStart)\n        .append(this.$bumperButtonEnd);\n    },\n\n    _addModalName: function () {\n      const headingId = 'preview-heading';\n\n      $('<h1/>', {\n        class: 'visually-hidden',\n        id: headingId,\n        text: Craft.t('app', 'Preview file'),\n      }).prependTo(this.$container);\n\n      this.$container.attr('aria-labelledby', headingId);\n    },\n\n    /**\n     * Disappear immediately forever.\n     * @returns {boolean}\n     */\n    selfDestruct: function () {\n      var instance = Craft.PreviewFileModal.openInstance;\n\n      instance.hide();\n      instance.$shade.remove();\n      instance.destroy();\n\n      Craft.PreviewFileModal.openInstance = null;\n      Craft.focalPoint.destruct();\n      Craft.focalPoint = null;\n\n      return true;\n    },\n\n    /**\n     * Load an asset, using starting width and height, if applicable\n     * @param {number} assetId\n     * @param {number} [startingWidth]\n     * @param {number} [startingHeight]\n     */\n    loadAsset: function (assetId, startingWidth, startingHeight) {\n      this.assetId = assetId;\n\n      this.$container.empty();\n      this.loaded = false;\n\n      this.desiredHeight = null;\n      this.desiredWidth = null;\n\n      var containerHeight = Garnish.$win.height() * 0.66;\n      var containerWidth = Math.min(\n        (containerHeight / 3) * 4,\n        Garnish.$win.width() - this.settings.minGutter * 2\n      );\n      containerHeight = (containerWidth / 4) * 3;\n\n      if (startingWidth && startingHeight) {\n        var ratio = startingWidth / startingHeight;\n        containerWidth = Math.min(\n          startingWidth,\n          Garnish.$win.width() - this.settings.minGutter * 2\n        );\n        containerHeight = Math.min(\n          containerWidth / ratio,\n          Garnish.$win.height() - this.settings.minGutter * 2\n        );\n        containerWidth = containerHeight * ratio;\n\n        // This might actually have put width over the viewport limits, so doublecheck\n        if (\n          containerWidth >\n          Math.min(\n            startingWidth,\n            Garnish.$win.width() - this.settings.minGutter * 2\n          )\n        ) {\n          containerWidth = Math.min(\n            startingWidth,\n            Garnish.$win.width() - this.settings.minGutter * 2\n          );\n          containerHeight = containerWidth / ratio;\n        }\n      }\n\n      this._resizeContainer(containerWidth, containerHeight);\n\n      this.$spinner = $('<div class=\"spinner centeralign\"></div>').appendTo(\n        this.$container\n      );\n      var top =\n          this.$container.height() / 2 - this.$spinner.height() / 2 + 'px',\n        left = this.$container.width() / 2 - this.$spinner.width() / 2 + 'px';\n\n      this.$spinner.css({left: left, top: top, position: 'absolute'});\n      this.requestId++;\n\n      let data = {assetId: assetId, requestId: this.requestId};\n      let onResponse = () => {\n        this.$container.removeClass('loading');\n        this.$spinner.remove();\n        this.loaded = true;\n      };\n      Craft.sendActionRequest('POST', 'assets/preview-file', {data})\n        .then((response) => {\n          onResponse();\n\n          if (response.data.requestId != this.requestId) {\n            return;\n          }\n\n          if (!response.data.previewHtml) {\n            this.$container.addClass('zilch');\n            this.$container.append(\n              $('<p/>', {text: Craft.t('app', 'No preview available.')})\n            );\n            this._addBumperButtons();\n            return;\n          }\n\n          this.$container.removeClass('zilch');\n          this.$container.attr('data-asset-id', this.assetId);\n          this.$container.append(response.data.previewHtml);\n          this._addBumperButtons();\n          this._addModalName();\n          Craft.appendHeadHtml(response.data.headHtml);\n          Craft.appendBodyHtml(response.data.bodyHtml);\n        })\n        .catch(({response}) => {\n          onResponse();\n          Craft.cp.displayError(response.data.message);\n          this.hide();\n        });\n    },\n\n    /**\n     * Resize the container to specified dimensions\n     * @param {number} containerWidth\n     * @param {number} containerHeight\n     * @private\n     */\n    _resizeContainer: function (containerWidth, containerHeight) {\n      this.$container.css({\n        width: containerWidth,\n        'min-width': containerWidth,\n        'max-width': containerWidth,\n        height: containerHeight,\n        'min-height': containerHeight,\n        'max-height': containerHeight,\n        top: (Garnish.$win.height() - containerHeight) / 2,\n        left: (Garnish.$win.width() - containerWidth) / 2,\n      });\n    },\n  },\n  {\n    defaultSettings: {\n      startingWidth: null,\n      startingHeight: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.ProgressBar = Garnish.Base.extend({\n  $progressBar: null,\n  $innerProgressBar: null,\n  $progressBarStatus: null,\n\n  _itemCount: 0,\n  _processedItemCount: 0,\n  _displaySteps: false,\n\n  init: function ($element, displaySteps) {\n    if (displaySteps) {\n      this._displaySteps = true;\n    }\n\n    this.$progressBar = $('<div class=\"progressbar pending hidden\"/>').appendTo(\n      $element\n    );\n    this.$innerProgressBar = $('<div class=\"progressbar-inner\"/>').appendTo(\n      this.$progressBar\n    );\n    this.$progressBarStatus = $(\n      '<div class=\"progressbar-status hidden\" />'\n    ).insertAfter(this.$progressBar);\n\n    this.resetProgressBar();\n  },\n\n  /**\n   * Reset the progress bar\n   */\n  resetProgressBar: function () {\n    // Since setting the progress percentage implies that there is progress to be shown\n    // It removes the pending class - we must add it back.\n    this.setProgressPercentage(100);\n    this.$progressBar.addClass('pending');\n\n    // Reset all the counters\n    this.setItemCount(1);\n    this.setProcessedItemCount(0);\n    this.$progressBarStatus.html('');\n\n    if (this._displaySteps) {\n      this.$progressBar.addClass('has-status');\n    }\n  },\n\n  /**\n   * Fade to invisible, hide it using a class and reset opacity to visible\n   */\n  hideProgressBar: function () {\n    this.$progressBar.addClass('hidden');\n    this.$progressBarStatus.addClass('hidden');\n  },\n\n  showProgressBar: function () {\n    this.$progressBar.removeClass('hidden');\n    this.$progressBarStatus.removeClass('hidden');\n  },\n\n  setItemCount: function (count) {\n    this._itemCount = count;\n  },\n\n  incrementItemCount: function (count) {\n    this._itemCount += count;\n  },\n\n  setProcessedItemCount: function (count) {\n    this._processedItemCount = count;\n  },\n\n  incrementProcessedItemCount: function (count) {\n    this._processedItemCount += count;\n  },\n\n  updateProgressBar: function () {\n    // Only fools would allow accidental division by zero.\n    this._itemCount = Math.max(this._itemCount, 1);\n\n    var width = Math.min(\n      100,\n      Math.round((100 * this._processedItemCount) / this._itemCount)\n    );\n\n    this.setProgressPercentage(width);\n\n    if (this._displaySteps) {\n      this.$progressBarStatus.html(\n        this._processedItemCount + ' / ' + this._itemCount\n      );\n    }\n  },\n\n  setProgressPercentage: function (percentage, animate) {\n    if (percentage === 0) {\n      this.$progressBar.addClass('pending');\n    } else {\n      this.$progressBar.removeClass('pending');\n\n      if (animate) {\n        this.$innerProgressBar\n          .velocity('stop')\n          .velocity({width: percentage + '%'}, 'fast');\n      } else {\n        this.$innerProgressBar.velocity('stop').width(percentage + '%');\n      }\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.PromptHandler = Garnish.Base.extend({\n  modal: null,\n  $modalContainerDiv: null,\n  $prompt: null,\n  $promptApplyToRemainingContainer: null,\n  $promptApplyToRemainingCheckbox: null,\n  $promptApplyToRemainingLabel: null,\n  $pomptChoices: null,\n\n  _prompts: [],\n  _promptBatchCallback: $.noop,\n  _promptBatchReturnData: [],\n  _promptBatchNum: 0,\n\n  resetPrompts: function () {\n    this._prompts = [];\n    this._promptBatchCallback = $.noop;\n    this._promptBatchReturnData = [];\n    this._promptBatchNum = 0;\n  },\n\n  addPrompt: function (prompt) {\n    this._prompts.push(prompt);\n  },\n\n  getPromptCount: function () {\n    return this._prompts.length;\n  },\n\n  showBatchPrompts: function (callback) {\n    this._promptBatchCallback = callback;\n    this._promptBatchReturnData = [];\n    this._promptBatchNum = 0;\n\n    this._showNextPromptInBatch();\n  },\n\n  _showNextPromptInBatch: function () {\n    var prompt = this._prompts[this._promptBatchNum].prompt,\n      remainingInBatch = this._prompts.length - (this._promptBatchNum + 1);\n\n    this._showPrompt(\n      prompt.message,\n      prompt.choices,\n      this._handleBatchPromptSelection.bind(this),\n      remainingInBatch\n    );\n  },\n\n  /**\n   * Handles a prompt choice selection.\n   *\n   * @param {string} choice\n   * @param {boolean} applyToRemaining\n   * @private\n   */\n  _handleBatchPromptSelection: function (choice, applyToRemaining) {\n    var prompt = this._prompts[this._promptBatchNum],\n      remainingInBatch = this._prompts.length - (this._promptBatchNum + 1);\n\n    // Record this choice\n    var choiceData = $.extend(prompt, {choice});\n    this._promptBatchReturnData.push(choiceData);\n\n    // Are there any remaining items in the batch?\n    if (remainingInBatch) {\n      // Get ready to deal with the next prompt\n      this._promptBatchNum++;\n\n      // Apply the same choice to the remaining items?\n      if (applyToRemaining) {\n        this._handleBatchPromptSelection(choice, true);\n      } else {\n        // Show the next prompt\n        this._showNextPromptInBatch();\n      }\n    } else {\n      // All done! Call the callback\n      if (typeof this._promptBatchCallback === 'function') {\n        this._promptBatchCallback(this._promptBatchReturnData);\n      }\n    }\n  },\n\n  /**\n   * @callback showPromptCallback\n   * @param {string} choice\n   * @param {boolean} applyToRemaining\n   */\n  /**\n   * Show the user prompt with a given message and choices, plus an optional \"Apply to remaining\" checkbox.\n   *\n   * @param {string} message\n   * @param {Array} choices\n   * @param {showPromptCallback} callback\n   * @param {number} itemsToGo\n   */\n  _showPrompt: function (message, choices, callback, itemsToGo) {\n    this._promptCallback = callback;\n\n    if (this.modal === null) {\n      this.modal = new Garnish.Modal({closeOtherModals: false});\n    }\n\n    if (this.$modalContainerDiv === null) {\n      this.$modalContainerDiv = $(\n        '<div class=\"modal fitted prompt-modal\"></div>'\n      )\n        .addClass()\n        .appendTo(Garnish.$bod);\n    }\n\n    this.$prompt = $('<div class=\"body\"></div>').appendTo(\n      this.$modalContainerDiv.empty()\n    );\n\n    this.$promptMessage = $('<p class=\"prompt-msg\"/>').appendTo(this.$prompt);\n\n    this.$promptChoices = $('<div class=\"options\"></div>').appendTo(\n      this.$prompt\n    );\n\n    this.$promptApplyToRemainingContainer = $(\n      '<label class=\"assets-applytoremaining\"/>'\n    )\n      .appendTo(this.$prompt)\n      .hide();\n    this.$promptApplyToRemainingCheckbox = $(\n      '<input type=\"checkbox\"/>'\n    ).appendTo(this.$promptApplyToRemainingContainer);\n    this.$promptApplyToRemainingLabel = $('<span/>').appendTo(\n      this.$promptApplyToRemainingContainer\n    );\n\n    this.$promptButtons = $('<div class=\"buttons right\"/>').appendTo(\n      this.$prompt\n    );\n\n    this.modal.setContainer(this.$modalContainerDiv);\n\n    this.$promptMessage.html(message);\n\n    let $cancelBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Cancel'),\n    }).appendTo(this.$promptButtons);\n    let $submitBtn = $('<button/>', {\n      type: 'submit',\n      class: 'btn submit disabled',\n      text: Craft.t('app', 'OK'),\n    }).appendTo(this.$promptButtons);\n\n    for (var i = 0; i < choices.length; i++) {\n      var $radioButtonHtml = $(\n          '<div><label><input type=\"radio\" name=\"promptAction\" value=\"' +\n            choices[i].value +\n            '\"/> ' +\n            choices[i].title +\n            '</label></div>'\n        ).appendTo(this.$promptChoices),\n        $radioButton = $radioButtonHtml.find('input');\n\n      this.addListener($radioButton, 'click', function () {\n        $submitBtn.removeClass('disabled');\n      });\n    }\n\n    this.addListener($submitBtn, 'activate', function (ev) {\n      var choice = $(ev.currentTarget)\n          .parents('.modal')\n          .find('input[name=promptAction]:checked')\n          .val(),\n        applyToRemaining = this.$promptApplyToRemainingCheckbox.prop('checked');\n\n      this._selectPromptChoice(choice, applyToRemaining);\n    });\n\n    this.addListener($cancelBtn, 'activate', function () {\n      var choice = 'cancel',\n        applyToRemaining = this.$promptApplyToRemainingCheckbox.prop('checked');\n\n      this._selectPromptChoice(choice, applyToRemaining);\n    });\n\n    if (itemsToGo) {\n      this.$promptApplyToRemainingContainer.show();\n      this.$promptApplyToRemainingLabel.html(\n        ' ' +\n          Craft.t('app', 'Apply this to the {number} remaining conflicts?', {\n            number: itemsToGo,\n          })\n      );\n    }\n\n    this.modal.show();\n    this.modal.removeListener(Garnish.Modal.$shade, 'click');\n    this.addListener(Garnish.Modal.$shade, 'click', '_cancelPrompt');\n  },\n\n  /**\n   * Handles when a user selects one of the prompt choices.\n   *\n   * @param {string} choice\n   * @param {boolean} applyToRemaining\n   * @private\n   */\n  _selectPromptChoice: function (choice, applyToRemaining) {\n    this.$prompt.fadeOut('fast', () => {\n      this.modal.hide();\n      this._promptCallback(choice, applyToRemaining);\n    });\n  },\n\n  /**\n   * Cancels the prompt.\n   */\n  _cancelPrompt: function () {\n    this._selectPromptChoice('cancel', true);\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Queue\n */\nCraft.Queue = Garnish.Base.extend({\n  running: false,\n  paused: false,\n  pausedForVisibility: false,\n  jobs: null,\n\n  get length() {\n    return this.jobs.length;\n  },\n\n  get isPaused() {\n    return this.paused || this.pausedForVisibility;\n  },\n\n  init: function () {\n    this.jobs = [];\n\n    Garnish.$doc.on('visibilitychange', () => {\n      if (this.pausedForVisibility && Craft.isVisible()) {\n        this.pausedForVisibility = false;\n        this._resume();\n      }\n    });\n  },\n\n  /**\n   * Adds a job to the queue.\n   * @param {function} job\n   * @returns {Promise}\n   */\n  push: function (job) {\n    return this._add(job, 'push');\n  },\n\n  /**\n   * Adds a job to the beginning of the queue.\n   * @param {function} job\n   * @returns {Promise}\n   */\n  unshift: function (job) {\n    return this._add(job, 'unshift');\n  },\n\n  pause: function () {\n    if (!this.paused) {\n      this.paused = true;\n      if (!this.pausedForVisibility) {\n        this.trigger('pause');\n      }\n    }\n  },\n\n  resume: function () {\n    if (this.paused) {\n      this.paused = false;\n      this._resume();\n    }\n  },\n\n  /**\n   * Adds a job to the queue.\n   * @param {function} job\n   * @param {string} method\n   * @returns {Promise}\n   * @private\n   */\n  _add: function (job, method) {\n    return new Promise((resolve, reject) => {\n      this.jobs[method](() => {\n        return new Promise((qResolve, qReject) => {\n          job()\n            .then((value) => {\n              // ...arguments doesn't work here :(\n              resolve(value);\n              qResolve();\n            })\n            .catch((value) => {\n              // ...arguments doesn't work here :(\n              reject(value);\n              qReject();\n            });\n        });\n      });\n\n      if (!this.running) {\n        this.trigger('beforeRun');\n        this.running = true;\n        this._exec();\n      }\n    });\n  },\n\n  clear: function () {\n    this.jobs.length = 0;\n  },\n\n  /**\n   * Runs the next job in the queue.\n   * @private\n   */\n  _exec: function () {\n    if (!this.jobs.length) {\n      this.running = false;\n      this.trigger('afterRun');\n      return;\n    }\n\n    if (!this.pausedForVisibility && !Craft.isVisible()) {\n      this.pausedForVisibility = true;\n      if (!this.paused) {\n        this.trigger('pause');\n      }\n    }\n\n    if (this.paused || this.pausedForVisibility) {\n      return;\n    }\n\n    this.trigger('beforeExec');\n    const job = this.jobs.shift();\n    job().finally(() => {\n      this.trigger('afterExec');\n      this._exec();\n    });\n  },\n\n  _resume: function () {\n    if (!this.isPaused) {\n      this.trigger('resume');\n      this._exec();\n    }\n  },\n});\n\nCraft.queue = new Craft.Queue();\n","(function ($) {\n  /** global: Craft */\n  /** global: Garnish */\n  /**\n   * Slide Picker\n   */\n  Craft.SlidePicker = Garnish.Base.extend(\n    {\n      min: null,\n      max: null,\n      totalSteps: null,\n      value: null,\n      label: null,\n      describedBy: null,\n\n      $container: null,\n      $buttons: null,\n\n      init: function (value, settings) {\n        this.setSettings(settings, Craft.SlidePicker.defaults);\n\n        this.$container = $('<div/>', {\n          class: 'slide-picker',\n          role: 'slider',\n          tabindex: 0,\n        });\n\n        this.refresh();\n        this.setValue(value, false);\n\n        this.addListener(this.$container, 'keydown', (ev) => {\n          switch (ev.keyCode) {\n            case Garnish.UP_KEY:\n              this.setValue(this.value + this.settings.step);\n              ev.preventDefault();\n              break;\n            case Garnish.DOWN_KEY:\n              this.setValue(this.value - this.settings.step);\n              ev.preventDefault();\n              break;\n            case Garnish.RIGHT_KEY:\n              if (Craft.orientation === 'ltr') {\n                this.setValue(this.value + this.settings.step);\n              } else {\n                this.setValue(this.value - this.settings.step);\n              }\n              ev.preventDefault();\n              break;\n            case Garnish.LEFT_KEY:\n              if (Craft.orientation === 'ltr') {\n                this.setValue(this.value - this.settings.step);\n              } else {\n                this.setValue(this.value + this.settings.step);\n              }\n              ev.preventDefault();\n              break;\n            case Garnish.HOME_KEY:\n              this.setValue(this.min);\n              ev.preventDefault();\n              break;\n            case Garnish.END_KEY:\n              this.setValue(this.max);\n              ev.preventDefault();\n              break;\n          }\n        });\n      },\n\n      refresh: function () {\n        // Figure out what the min/max values are\n        this.min = this._min();\n        this.max = this._max();\n        this.totalSteps = (this.max - this.min) / this.settings.step;\n\n        // Set label\n        this.label = this.settings.label;\n        this.describedBy = this.settings.describedBy;\n\n        if (!Number.isInteger(this.totalSteps)) {\n          throw 'Invalid SlidePicker config';\n        }\n\n        if (this.$buttons) {\n          this.$buttons.remove();\n        }\n\n        this.$container.attr('aria-valuemin', this.min);\n        this.$container.attr('aria-valuemax', this.max);\n\n        if (this.label) {\n          this.$container.attr('aria-label', this.label);\n        }\n\n        if (this.describedBy) {\n          this.$container.attr('aria-describedby', this.describedBy);\n        }\n\n        this.$buttons = $();\n\n        // Create the buttons\n        for (\n          let value = this.min;\n          value <= this.max;\n          value += this.settings.step\n        ) {\n          this.$buttons = this.$buttons.add(\n            $('<a/>', {\n              title: this.settings.valueLabel(value),\n              data: {value},\n            })\n          );\n        }\n\n        this.$buttons.appendTo(this.$container);\n\n        if (this.value !== null) {\n          let value = this.value;\n          this.value = null;\n          this.setValue(value, false);\n        }\n\n        this.addListener(this.$buttons, 'mouseover', (ev) => {\n          this.$buttons.removeClass('active-hover last-active-hover');\n          $(ev.currentTarget)\n            .addClass('active-hover last-active-hover')\n            .prevAll()\n            .addClass('active-hover');\n        });\n\n        this.addListener(this.$buttons, 'mouseout', () => {\n          this.$buttons.removeClass('active-hover');\n        });\n\n        this.addListener(this.$buttons, 'click', (ev) => {\n          this.setValue($.data(ev.currentTarget, 'value'));\n          ev.stopPropagation();\n          this.$container.focus();\n        });\n      },\n\n      setValue: function (value, triggerEvent) {\n        value = Math.max(Math.min(value, this.max), this.min);\n\n        if (this.value === (this.value = value)) {\n          return;\n        }\n\n        this.$container.attr({\n          'aria-valuenow': this.value,\n          'aria-valuetext': this.settings.valueLabel(this.value),\n        });\n\n        this.$buttons.removeClass('last-active active');\n        let $activeButton = this.$buttons.eq(\n          (this.value - this.min) / this.settings.step\n        );\n        $activeButton.add($activeButton.prevAll()).addClass('active');\n        $activeButton.addClass('last-active');\n\n        if (triggerEvent !== false) {\n          this.settings.onChange(value);\n        }\n      },\n\n      _min: function () {\n        if (typeof this.settings.min === 'function') {\n          return this.settings.min();\n        }\n        return this.settings.min;\n      },\n\n      _max: function () {\n        if (typeof this.settings.max === 'function') {\n          return this.settings.max();\n        }\n        return this.settings.max;\n      },\n    },\n    {\n      defaults: {\n        min: 0,\n        max: 100,\n        step: 10,\n        valueLabel: null,\n        onChange: $.noop,\n      },\n    }\n  );\n})(jQuery);\n","/** global: Garnish */\n\nCraft.SlideRuleInput = Garnish.Base.extend({\n  $container: null,\n  $options: null,\n  $selectedOption: null,\n  $input: null,\n  value: null,\n\n  startPositionX: null,\n\n  init: function (id, settings) {\n    this.setSettings(settings, Craft.SlideRuleInput.defaultSettings);\n\n    this.value = 0;\n    this.graduationsMin = -70;\n    this.graduationsMax = 70;\n    this.slideMin = -45;\n    this.slideMax = 45;\n\n    this.$container = $('#' + id);\n    this.$overlay = $('<div class=\"overlay\"></div>').appendTo(this.$container);\n    this.$cursor = $('<div class=\"cursor\"></div>').appendTo(this.$container);\n    this.$graduations = $('<div class=\"graduations\"></div>').appendTo(\n      this.$container\n    );\n    this.$graduationsUl = $('<ul></ul>').appendTo(this.$graduations);\n\n    this.$container.attr({\n      role: 'slider',\n      tabindex: '0',\n      'aria-valuemin': this.slideMin,\n      'aria-valuemax': this.slideMax,\n      'aria-valuenow': '0',\n      'aria-valuetext': Craft.t(\n        'app',\n        '{num, number} {num, plural, =1{degree} other{degrees}}',\n        {\n          num: 0,\n        }\n      ),\n    });\n\n    for (var i = this.graduationsMin; i <= this.graduationsMax; i++) {\n      var $li = $(\n        '<li class=\"graduation\" data-graduation=\"' +\n          i +\n          '\"><div class=\"label\">' +\n          i +\n          '</div></li>'\n      ).appendTo(this.$graduationsUl);\n\n      if (i % 5 === 0) {\n        $li.addClass('main-graduation');\n      }\n\n      if (i === 0) {\n        $li.addClass('selected');\n      }\n    }\n\n    this.$options = this.$container.find('.graduation');\n\n    this.addListener(this.$container, 'resize', this._handleResize.bind(this));\n    this.addListener(\n      this.$container,\n      'tapstart',\n      this._handleTapStart.bind(this)\n    );\n    this.addListener(Garnish.$bod, 'tapmove', this._handleTapMove.bind(this));\n    this.addListener(Garnish.$bod, 'tapend', this._handleTapEnd.bind(this));\n    this.addListener(\n      this.$container,\n      'keydown',\n      this._handleKeypress.bind(this)\n    );\n\n    // Set to zero\n\n    // this.setValue(0);\n\n    setTimeout(() => {\n      // (n -1) options because the border is placed on the left of the 10px box\n      this.graduationsCalculatedWidth = (this.$options.length - 1) * 10;\n      this.$graduationsUl.css(\n        'left',\n        -this.graduationsCalculatedWidth / 2 + this.$container.width() / 2\n      );\n    }, 50);\n  },\n\n  _handleResize: function () {\n    var left = this.valueToPosition(this.value);\n    this.$graduationsUl.css('left', left);\n  },\n\n  _handleKeypress: function (event) {\n    const current = parseInt(this.$container.attr('aria-valuenow'), 10);\n\n    switch (event.keyCode) {\n      case Garnish.UP_KEY:\n      case Garnish.RIGHT_KEY:\n        this.setValue(current + 1);\n        break;\n      case Garnish.DOWN_KEY:\n      case Garnish.LEFT_KEY:\n        this.setValue(current - 1);\n        break;\n      case Garnish.PAGE_UP_KEY:\n        this.setValue(current + 10);\n        break;\n      case Garnish.PAGE_DOWN_KEY:\n        this.setValue(current - 10);\n        break;\n      case Garnish.HOME_KEY:\n        this.setValue(this.slideMin);\n        break;\n      case Garnish.END_KEY:\n        this.setValue(this.slideMax);\n        break;\n    }\n\n    this.onChange();\n  },\n\n  _handleTapStart: function (ev, touch) {\n    ev.preventDefault();\n\n    this.startPositionX = touch.position.x;\n    this.startLeft = this.$graduationsUl.position().left;\n\n    this.dragging = true;\n    this.onStart();\n  },\n\n  _handleTapMove: function (ev, touch) {\n    if (this.dragging) {\n      ev.preventDefault();\n\n      var curX = this.startPositionX - touch.position.x;\n      var left = this.startLeft - curX;\n      var value = this.positionToValue(left);\n\n      this.setValue(value);\n\n      this.onChange();\n    }\n  },\n\n  setValue: function (value) {\n    var left = this.valueToPosition(value);\n    if (value < this.slideMin) {\n      value = this.slideMin;\n      left = this.valueToPosition(value);\n    } else if (value > this.slideMax) {\n      value = this.slideMax;\n      left = this.valueToPosition(value);\n    }\n\n    this.$graduationsUl.css('left', left);\n\n    if (value >= this.slideMin && value <= this.slideMax) {\n      this.$options.removeClass('selected');\n\n      $.each(this.$options, function (key, option) {\n        if ($(option).data('graduation') > 0) {\n          if ($(option).data('graduation') <= value) {\n            $(option).addClass('selected');\n          }\n        }\n        if ($(option).data('graduation') < 0) {\n          if ($(option).data('graduation') >= value) {\n            $(option).addClass('selected');\n          }\n        }\n\n        if ($(option).data('graduation') == 0) {\n          $(option).addClass('selected');\n        }\n      });\n    }\n\n    this.$container.attr({\n      'aria-valuenow': value,\n      'aria-valuetext': Craft.t(\n        'app',\n        '{num, number} {num, plural, =1{degree} other{degrees}}',\n        {num: parseInt(value, 10)}\n      ),\n    });\n    this.value = value;\n  },\n\n  _handleTapEnd: function (ev) {\n    if (this.dragging) {\n      ev.preventDefault();\n      this.dragging = false;\n      this.onEnd();\n    }\n  },\n\n  positionToValue: function (position) {\n    var scaleMin = this.graduationsMin * -1;\n    var scaleMax = (this.graduationsMin - this.graduationsMax) * -1;\n\n    return (\n      ((this.$graduations.width() / 2 + position * -1) /\n        this.graduationsCalculatedWidth) *\n        scaleMax -\n      scaleMin\n    );\n  },\n\n  valueToPosition: function (value) {\n    var scaleMin = this.graduationsMin * -1;\n    var scaleMax = (this.graduationsMin - this.graduationsMax) * -1;\n\n    return -(\n      ((value + scaleMin) * this.graduationsCalculatedWidth) / scaleMax -\n      this.$graduations.width() / 2\n    );\n  },\n\n  onStart: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onStart(this);\n    }\n  },\n\n  onChange: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onChange(this);\n    }\n  },\n\n  onEnd: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onEnd(this);\n    }\n  },\n\n  defaultSettings: {\n    onStart: $.noop,\n    onChange: $.noop,\n    onEnd: $.noop,\n  },\n});\n","(function ($) {\n  /** global: Craft */\n  /** global: Garnish */\n  /**\n   * Slide Picker\n   */\n  Craft.Slideout = Garnish.Base.extend(\n    {\n      $outerContainer: null,\n      $container: null,\n      $shade: null,\n      isOpen: false,\n\n      init: function (contents, settings) {\n        this.setSettings(settings, Craft.Slideout.defaults);\n\n        if (!Craft.useMobileStyles()) {\n          this.$shade = $('<div class=\"slideout-shade\"/>').appendTo(\n            Garnish.$bod\n          );\n\n          if (this.settings.closeOnShadeClick) {\n            this.addListener(this.$shade, 'click', (ev) => {\n              ev.stopPropagation();\n              this.close();\n            });\n          }\n        }\n\n        this.$outerContainer = $('<div/>', {\n          class: 'slideout-container hidden',\n        });\n        this.$container = $(\n          `<${this.settings.containerElement}/>`,\n          this.settings.containerAttributes\n        )\n          .attr('data-slideout', '')\n          .addClass('slideout')\n          .append(contents)\n          .data('slideout', this)\n          .appendTo(this.$outerContainer);\n\n        Garnish.addModalAttributes(this.$outerContainer);\n\n        if (Craft.useMobileStyles()) {\n          this.$container.addClass('so-mobile');\n        }\n\n        Craft.trapFocusWithin(this.$container);\n\n        if (this.settings.autoOpen) {\n          this.open();\n        }\n      },\n\n      open: function () {\n        if (this.isOpen) {\n          return;\n        }\n\n        this.setTriggerElement(document.activeElement);\n\n        this._cancelTransitionListeners();\n\n        // Move the shade + container to the end of <body> so they get the highest sub-z-indexes\n        if (this.$shade) {\n          this.$shade.appendTo(Garnish.$bod).show();\n        }\n\n        this.$outerContainer.appendTo(Garnish.$bod).removeClass('hidden');\n\n        if (Craft.useMobileStyles()) {\n          this.$container.css('top', '100vh');\n        } else {\n          this.$container.css(Garnish.ltr ? 'left' : 'right', '100vw');\n        }\n\n        this.$container.one('transitionend.slideout', () => {\n          Craft.setFocusWithin(this.$container);\n        });\n\n        if (this.$shade) {\n          this.$shade[0].offsetWidth;\n          this.$shade.addClass('so-visible');\n        }\n\n        this.$container[0].offsetWidth;\n        Craft.Slideout.addPanel(this);\n\n        this.enable();\n        Garnish.uiLayerManager.addLayer(this.$outerContainer);\n        Garnish.hideModalBackgroundLayers();\n\n        if (this.settings.closeOnEsc) {\n          Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n            this.close();\n          });\n        }\n\n        this.isOpen = true;\n        this.trigger('open');\n      },\n\n      setTriggerElement: function (trigger) {\n        this.settings.triggerElement = trigger;\n      },\n\n      close: function () {\n        if (!this.isOpen) {\n          return;\n        }\n\n        this.trigger('beforeClose');\n        this.disable();\n        this.isOpen = false;\n\n        this._cancelTransitionListeners();\n\n        if (this.$shade) {\n          this.$shade\n            .removeClass('so-visible')\n            .one('transitionend.slideout', () => {\n              this.$shade.hide();\n            });\n        }\n\n        Craft.Slideout.removePanel(this);\n        Garnish.uiLayerManager.removeLayer();\n        Garnish.resetModalBackgroundLayerVisibility();\n        this.$container.one('transitionend.slideout', () => {\n          this.$outerContainer.addClass('hidden');\n          this.trigger('close');\n        });\n\n        if (this.settings.triggerElement) {\n          this.settings.triggerElement.focus();\n        }\n      },\n\n      _cancelTransitionListeners: function () {\n        if (this.$shade) {\n          this.$shade.off('transitionend.slideout');\n        }\n\n        this.$container.off('transitionend.slideout');\n      },\n\n      /**\n       * Destroy\n       */\n      destroy: function () {\n        if (this.$shade) {\n          this.$shade.remove();\n          this.$shade = null;\n        }\n\n        this.$outerContainer.remove();\n        this.$outerContainer = null;\n        this.$container = null;\n\n        this.base();\n      },\n    },\n    {\n      defaults: {\n        containerElement: 'div',\n        containerAttributes: {},\n        autoOpen: true,\n        closeOnEsc: true,\n        closeOnShadeClick: true,\n        triggerElement: null,\n      },\n      openPanels: [],\n      addPanel: function (panel) {\n        Craft.Slideout.openPanels.unshift(panel);\n        if (Craft.useMobileStyles()) {\n          panel.$container.css('top', 0);\n        } else {\n          Craft.Slideout.updateStyles();\n        }\n      },\n      removePanel: function (panel) {\n        Craft.Slideout.openPanels = Craft.Slideout.openPanels.filter(\n          (m) => m !== panel\n        );\n        if (Craft.useMobileStyles()) {\n          panel.$container.css('top', '100vh');\n        } else {\n          panel.$container.css(Garnish.ltr ? 'left' : 'right', '100vw');\n          Craft.Slideout.updateStyles();\n        }\n      },\n      updateStyles: function () {\n        const totalPanels = Craft.Slideout.openPanels.length;\n        Craft.Slideout.openPanels.forEach((panel, i) => {\n          panel.$container.css(\n            Garnish.ltr ? 'left' : 'right',\n            `${50 * ((totalPanels - i) / totalPanels)}vw`\n          );\n        });\n\n        if (totalPanels !== 0) {\n          Garnish.$bod.addClass('no-scroll');\n        } else {\n          Garnish.$bod.removeClass('no-scroll');\n        }\n      },\n    }\n  );\n})(jQuery);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Slug Generator\n */\nCraft.SlugGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    sourceVal = sourceVal.replace(/<(.*?)>/g, '');\n\n    // Remove inner-word punctuation\n    sourceVal = sourceVal.replace(/['\"‘’“”\\[\\]\\(\\)\\{\\}:]/g, '');\n\n    // Make it lowercase\n    if (!Craft.allowUppercaseInSlug) {\n      sourceVal = sourceVal.toLowerCase();\n    }\n\n    if (Craft.limitAutoSlugsToAscii) {\n      // Convert extended ASCII characters to basic ASCII\n      sourceVal = Craft.asciiString(sourceVal, this.settings.charMap);\n    }\n\n    // Get the \"words\". Split on anything that is not alphanumeric.\n    // Reference: http://www.regular-expressions.info/unicode.html\n    var words = Craft.filterArray(\n      XRegExp.matchChain(sourceVal, [XRegExp('[\\\\p{L}\\\\p{N}\\\\p{M}]+')])\n    );\n\n    if (words.length) {\n      return words.join(Craft.slugWordSeparator);\n    } else {\n      return '';\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Structure class\n */\nCraft.Structure = Garnish.Base.extend(\n  {\n    id: null,\n\n    $container: null,\n    state: null,\n    structureDrag: null,\n\n    /**\n     * Init\n     */\n    init: function (id, container, settings) {\n      this.id = id;\n      this.$container = $(container);\n      this.setSettings(settings, Craft.Structure.defaults);\n\n      // Is this already a structure?\n      if (this.$container.data('structure')) {\n        console.warn('Double-instantiating a structure on an element');\n        this.$container.data('structure').destroy();\n      }\n\n      this.$container.data('structure', this);\n\n      this.state = {};\n\n      if (this.settings.storageKey) {\n        $.extend(\n          this.state,\n          Craft.getLocalStorage(this.settings.storageKey, {})\n        );\n      }\n\n      if (typeof this.state.collapsedElementIds === 'undefined') {\n        this.state.collapsedElementIds = [];\n      }\n\n      var $parents = this.$container.find('ul').prev('.row');\n\n      for (var i = 0; i < $parents.length; i++) {\n        var $row = $($parents[i]),\n          $li = $row.parent(),\n          $toggle = $(\n            '<div class=\"toggle\" title=\"' +\n              Craft.t('app', 'Show/hide children') +\n              '\"/>'\n          ).prependTo($row);\n\n        if (\n          $.inArray(\n            $row.children('.element').data('id'),\n            this.state.collapsedElementIds\n          ) !== -1\n        ) {\n          $li.addClass('collapsed');\n        }\n\n        this.initToggle($toggle);\n      }\n\n      if (this.settings.sortable) {\n        this.structureDrag = new Craft.StructureDrag(\n          this,\n          this.settings.maxLevels\n        );\n      }\n\n      if (this.settings.newChildUrl) {\n        this.initNewChildMenus(this.$container.find('.add'));\n      }\n    },\n\n    initToggle: function ($toggle) {\n      $toggle.on('click', (ev) => {\n        var $li = $(ev.currentTarget).closest('li'),\n          elementId = $li.children('.row').find('.element:first').data('id'),\n          viewStateKey = $.inArray(elementId, this.state.collapsedElementIds);\n\n        if ($li.hasClass('collapsed')) {\n          $li.removeClass('collapsed');\n\n          if (viewStateKey !== -1) {\n            this.state.collapsedElementIds.splice(viewStateKey, 1);\n          }\n        } else {\n          $li.addClass('collapsed');\n\n          if (viewStateKey === -1) {\n            this.state.collapsedElementIds.push(elementId);\n          }\n        }\n\n        if (this.settings.storageKey) {\n          Craft.setLocalStorage(this.settings.storageKey, this.state);\n        }\n      });\n    },\n\n    initNewChildMenus: function ($addBtns) {\n      this.addListener($addBtns, 'click', 'onNewChildMenuClick');\n    },\n\n    onNewChildMenuClick: function (ev) {\n      var $btn = $(ev.currentTarget);\n\n      if (!$btn.data('menubtn')) {\n        var elementId = $btn.parent().children('.element').data('id'),\n          newChildUrl = Craft.getUrl(\n            this.settings.newChildUrl,\n            'parentId=' + elementId\n          );\n\n        $(\n          '<div class=\"menu\"><ul><li><a href=\"' +\n            newChildUrl +\n            '\">' +\n            Craft.t('app', 'New child') +\n            '</a></li></ul></div>'\n        ).insertAfter($btn);\n\n        var menuBtn = new Garnish.MenuBtn($btn);\n        menuBtn.showMenu();\n      }\n    },\n\n    getIndent: function (level) {\n      return (\n        Craft.Structure.baseIndent + (level - 1) * Craft.Structure.nestedIndent\n      );\n    },\n\n    addElement: function ($element) {\n      var $li = $('<li data-level=\"1\"/>').appendTo(this.$container),\n        $row = $(\n          '<div class=\"row\" style=\"margin-' +\n            Craft.left +\n            ': -' +\n            Craft.Structure.baseIndent +\n            'px; padding-' +\n            Craft.left +\n            ': ' +\n            Craft.Structure.baseIndent +\n            'px;\">'\n        ).appendTo($li);\n\n      $row.append($element);\n\n      if (this.settings.sortable) {\n        $row.append(\n          '<a class=\"move icon\" title=\"' + Craft.t('app', 'Move') + '\"></a>'\n        );\n        this.structureDrag.addItems($li);\n      }\n\n      if (this.settings.newChildUrl) {\n        var $addBtn = $(\n          '<a class=\"add icon\" title=\"' + Craft.t('app', 'New child') + '\"></a>'\n        ).appendTo($row);\n        this.initNewChildMenus($addBtn);\n      }\n\n      $row.css('margin-bottom', -30);\n      $row.velocity({'margin-bottom': 0}, 'fast');\n    },\n\n    removeElement: function ($element) {\n      var $li = $element.parent().parent();\n\n      if (this.settings.sortable) {\n        this.structureDrag.removeItems($li);\n      }\n\n      var $parentUl;\n\n      if (!$li.siblings().length) {\n        $parentUl = $li.parent();\n      }\n\n      $li\n        .css('visibility', 'hidden')\n        .velocity({marginBottom: -$li.height()}, 'fast', () => {\n          $li.remove();\n\n          if (typeof $parentUl !== 'undefined') {\n            this._removeUl($parentUl);\n          }\n        });\n    },\n\n    _removeUl: function ($ul) {\n      $ul.siblings('.row').children('.toggle').remove();\n      $ul.remove();\n    },\n\n    destroy: function () {\n      this.$container.removeData('structure');\n      this.base();\n    },\n  },\n  {\n    baseIndent: 8,\n    nestedIndent: 35,\n\n    defaults: {\n      storageKey: null,\n      sortable: false,\n      newChildUrl: null,\n      maxLevels: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Structure drag class\n */\nCraft.StructureDrag = Garnish.Drag.extend({\n  structure: null,\n  maxLevels: null,\n  draggeeLevel: null,\n\n  $helperLi: null,\n  $targets: null,\n  draggeeHeight: null,\n\n  init: function (structure, maxLevels) {\n    this.structure = structure;\n    this.maxLevels = maxLevels;\n\n    this.$insertion = $('<li class=\"draginsertion\"/>');\n\n    var $items = this.structure.$container.find('li');\n\n    this.base($items, {\n      handle: '.element:first, .move:first',\n      helper: this.getHelper.bind(this),\n    });\n  },\n\n  getHelper: function ($helper) {\n    this.$helperLi = $helper;\n    var $ul = $('<ul class=\"structure draghelper\"/>').append($helper);\n    $helper.css(\n      'padding-' + Craft.left,\n      this.$draggee.css('padding-' + Craft.left)\n    );\n    $helper.find('.move').removeAttr('title');\n    return $ul;\n  },\n\n  onDragStart: function () {\n    this.$targets = $();\n\n    // Recursively find each of the targets, in the order they appear to be in\n    this.findTargets(this.structure.$container);\n\n    // How deep does the rabbit hole go?\n    this.draggeeLevel = 0;\n    var $level = this.$draggee;\n    do {\n      this.draggeeLevel++;\n      $level = $level.find('> ul > li');\n    } while ($level.length);\n\n    // Collapse the draggee\n    this.draggeeHeight = this.$draggee.height();\n    this.$draggee.velocity(\n      {\n        height: 0,\n      },\n      'fast',\n      () => {\n        this.$draggee.addClass('hidden');\n      }\n    );\n    this.base();\n\n    this.addListener(Garnish.$doc, 'keydown', function (ev) {\n      if (ev.keyCode === Garnish.ESC_KEY) {\n        this.cancelDrag();\n      }\n    });\n  },\n\n  findTargets: function ($ul) {\n    var $lis = $ul.children().not(this.$draggee);\n\n    for (var i = 0; i < $lis.length; i++) {\n      var $li = $($lis[i]);\n      this.$targets = this.$targets.add($li.children('.row'));\n\n      if (!$li.hasClass('collapsed')) {\n        this.findTargets($li.children('ul'));\n      }\n    }\n  },\n\n  onDrag: function () {\n    if (this._.$closestTarget) {\n      this._.$closestTarget.removeClass('draghover');\n      this.$insertion.remove();\n    }\n\n    // First let's find the closest target\n    this._.$closestTarget = null;\n    this._.closestTargetPos = null;\n    this._.closestTargetYDiff = null;\n    this._.closestTargetOffset = null;\n    this._.closestTargetHeight = null;\n\n    for (this._.i = 0; this._.i < this.$targets.length; this._.i++) {\n      this._.$target = $(this.$targets[this._.i]);\n      this._.targetOffset = this._.$target.offset();\n      this._.targetHeight = this._.$target.outerHeight();\n      this._.targetYMidpoint =\n        this._.targetOffset.top + this._.targetHeight / 2;\n      this._.targetYDiff = Math.abs(this.mouseY - this._.targetYMidpoint);\n\n      if (\n        this._.i === 0 ||\n        (this.mouseY >= this._.targetOffset.top + 5 &&\n          this._.targetYDiff < this._.closestTargetYDiff)\n      ) {\n        this._.$closestTarget = this._.$target;\n        this._.closestTargetPos = this._.i;\n        this._.closestTargetYDiff = this._.targetYDiff;\n        this._.closestTargetOffset = this._.targetOffset;\n        this._.closestTargetHeight = this._.targetHeight;\n      } else {\n        // Getting colder\n        break;\n      }\n    }\n\n    if (!this._.$closestTarget) {\n      return;\n    }\n\n    // Are we hovering above the first row?\n    if (\n      this._.closestTargetPos === 0 &&\n      this.mouseY < this._.closestTargetOffset.top + 5\n    ) {\n      this.$insertion.prependTo(this.structure.$container);\n    } else {\n      this._.$closestTargetLi = this._.$closestTarget.parent();\n      this._.closestTargetLevel = this._.$closestTargetLi.data('level');\n\n      // Is there a next row?\n      if (this._.closestTargetPos < this.$targets.length - 1) {\n        this._.$nextTargetLi = $(\n          this.$targets[this._.closestTargetPos + 1]\n        ).parent();\n        this._.nextTargetLevel = this._.$nextTargetLi.data('level');\n      } else {\n        this._.$nextTargetLi = null;\n        this._.nextTargetLevel = null;\n      }\n\n      // Are we hovering between this row and the next one?\n      this._.hoveringBetweenRows =\n        this.mouseY >=\n        this._.closestTargetOffset.top + this._.closestTargetHeight - 5;\n\n      /**\n       * Scenario 1: Both rows have the same level.\n       *\n       *     * Row 1\n       *     ----------------------\n       *     * Row 2\n       */\n\n      if (\n        this._.$nextTargetLi &&\n        this._.nextTargetLevel == this._.closestTargetLevel\n      ) {\n        if (this._.hoveringBetweenRows) {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel - 1\n          ) {\n            // Position the insertion after the closest target\n            this.$insertion.insertAfter(this._.$closestTargetLi);\n          }\n        } else {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel\n          ) {\n            this._.$closestTarget.addClass('draghover');\n          }\n        }\n      } else if (\n        /**\n         * Scenario 2: Next row is a child of this one.\n         *\n         *     * Row 1\n         *     ----------------------\n         *         * Row 2\n         */\n        this._.$nextTargetLi &&\n        this._.nextTargetLevel > this._.closestTargetLevel\n      ) {\n        if (\n          !this.maxLevels ||\n          this.maxLevels >= this._.nextTargetLevel + this.draggeeLevel - 1\n        ) {\n          if (this._.hoveringBetweenRows) {\n            // Position the insertion as the first child of the closest target\n            this.$insertion.insertBefore(this._.$nextTargetLi);\n          } else {\n            this._.$closestTarget.addClass('draghover');\n            this.$insertion.appendTo(this._.$closestTargetLi.children('ul'));\n          }\n        }\n      } else {\n        /**\n         * Scenario 3: Next row is a child of a parent node, or there is no next row.\n         *\n         *         * Row 1\n         *     ----------------------\n         *     * Row 2\n         */\n        if (this._.hoveringBetweenRows) {\n          // Determine which <li> to position the insertion after\n          this._.draggeeX = this.mouseX - this.targetItemMouseDiffX;\n\n          if (Craft.orientation === 'rtl') {\n            this._.draggeeX += this.$helperLi.width();\n          }\n\n          this._.$parentLis = this._.$closestTarget.parentsUntil(\n            this.structure.$container,\n            'li'\n          );\n          this._.$closestParentLi = null;\n          this._.closestParentLiXDiff = null;\n          this._.closestParentLevel = null;\n\n          for (this._.i = 0; this._.i < this._.$parentLis.length; this._.i++) {\n            this._.$parentLi = $(this._.$parentLis[this._.i]);\n            this._.parentLiX = this._.$parentLi.offset().left;\n\n            if (Craft.orientation === 'rtl') {\n              this._.parentLiX += this._.$parentLi.width();\n            }\n\n            this._.parentLiXDiff = Math.abs(this._.parentLiX - this._.draggeeX);\n            this._.parentLevel = this._.$parentLi.data('level');\n\n            if (\n              (!this.maxLevels ||\n                this.maxLevels >= this._.parentLevel + this.draggeeLevel - 1) &&\n              (!this._.$closestParentLi ||\n                (this._.parentLiXDiff < this._.closestParentLiXDiff &&\n                  (!this._.$nextTargetLi ||\n                    this._.parentLevel >= this._.nextTargetLevel)))\n            ) {\n              this._.$closestParentLi = this._.$parentLi;\n              this._.closestParentLiXDiff = this._.parentLiXDiff;\n              this._.closestParentLevel = this._.parentLevel;\n            }\n          }\n\n          if (this._.$closestParentLi) {\n            this.$insertion.insertAfter(this._.$closestParentLi);\n          }\n        } else {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel\n          ) {\n            this._.$closestTarget.addClass('draghover');\n          }\n        }\n      }\n    }\n  },\n\n  cancelDrag: function () {\n    this.$insertion.remove();\n\n    if (this._.$closestTarget) {\n      this._.$closestTarget.removeClass('draghover');\n    }\n\n    this.onMouseUp();\n  },\n\n  onDragStop: function () {\n    // Are we repositioning the draggee?\n    if (\n      this._.$closestTarget &&\n      (this.$insertion.parent().length ||\n        this._.$closestTarget.hasClass('draghover'))\n    ) {\n      var $draggeeParent, moved;\n\n      // Are we about to leave the draggee's original parent childless?\n      if (!this.$draggee.siblings().length) {\n        $draggeeParent = this.$draggee.parent();\n      }\n\n      if (this.$insertion.parent().length) {\n        // Make sure the insertion isn't right next to the draggee\n        var $closestSiblings = this.$insertion\n          .next()\n          .add(this.$insertion.prev());\n\n        if ($.inArray(this.$draggee[0], $closestSiblings) === -1) {\n          this.$insertion.replaceWith(this.$draggee);\n          moved = true;\n        } else {\n          this.$insertion.remove();\n          moved = false;\n        }\n      } else {\n        var $ul = this._.$closestTargetLi.children('ul');\n\n        // Make sure this is a different parent than the draggee's\n        if (!$draggeeParent || !$ul.length || $ul[0] !== $draggeeParent[0]) {\n          if (!$ul.length) {\n            var $toggle = $(\n              '<div class=\"toggle\" title=\"' +\n                Craft.t('app', 'Show/hide children') +\n                '\"/>'\n            ).prependTo(this._.$closestTarget);\n            this.structure.initToggle($toggle);\n\n            $ul = $('<ul>').appendTo(this._.$closestTargetLi);\n          } else if (this._.$closestTargetLi.hasClass('collapsed')) {\n            this._.$closestTarget.children('.toggle').trigger('click');\n          }\n\n          this.$draggee.appendTo($ul);\n          moved = true;\n        } else {\n          moved = false;\n        }\n      }\n\n      // Remove the class either way\n      this._.$closestTarget.removeClass('draghover');\n\n      if (moved) {\n        // Now deal with the now-childless parent\n        if ($draggeeParent) {\n          this.structure._removeUl($draggeeParent);\n        }\n\n        // Has the level changed?\n        var newLevel =\n          this.$draggee.parentsUntil(this.structure.$container, 'li').length +\n          1;\n\n        var animateCss;\n\n        if (newLevel != this.$draggee.data('level')) {\n          // Correct the helper's padding if moving to/from level 1\n          if (this.$draggee.data('level') == 1) {\n            animateCss = {};\n            animateCss['padding-' + Craft.left] = 38;\n            this.$helperLi.velocity(animateCss, 'fast');\n          } else if (newLevel == 1) {\n            animateCss = {};\n            animateCss['padding-' + Craft.left] = Craft.Structure.baseIndent;\n            this.$helperLi.velocity(animateCss, 'fast');\n          }\n\n          this.setLevel(this.$draggee, newLevel);\n        }\n\n        // Make it real\n        var $element = this.$draggee.children('.row').children('.element');\n\n        var data = {\n          structureId: this.structure.id,\n          elementId: $element.data('id'),\n          siteId: $element.data('site-id'),\n          prevId: this.$draggee\n            .prev()\n            .children('.row')\n            .children('.element')\n            .data('id'),\n          parentId: this.$draggee\n            .parent('ul')\n            .parent('li')\n            .children('.row')\n            .children('.element')\n            .data('id'),\n        };\n\n        Craft.sendActionRequest('POST', 'structures/move-element', {data}).then(\n          (response) => {\n            Craft.cp.displaySuccess(Craft.t('app', 'New order saved.'));\n          }\n        );\n      }\n    }\n\n    // Animate things back into place\n    this.$draggee\n      .velocity('stop')\n      .removeClass('hidden')\n      .velocity(\n        {\n          height: this.draggeeHeight,\n        },\n        'fast',\n        () => {\n          this.$draggee.css('height', 'auto');\n        }\n      );\n\n    this.returnHelpersToDraggees();\n\n    this.base();\n  },\n\n  setLevel: function ($li, level) {\n    $li.data('level', level);\n\n    var indent = this.structure.getIndent(level);\n\n    var css = {};\n    css['margin-' + Craft.left] = '-' + indent + 'px';\n    css['padding-' + Craft.left] = indent + 'px';\n    this.$draggee.children('.row').css(css);\n\n    var $childLis = $li.children('ul').children();\n\n    for (var i = 0; i < $childLis.length; i++) {\n      this.setLevel($($childLis[i]), level + 1);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.StructureTableSorter = Garnish.DragSort.extend(\n  {\n    tableView: null,\n    structureId: null,\n    maxLevels: null,\n\n    _basePadding: null,\n    _helperMargin: null,\n\n    _$firstRowCells: null,\n    _$titleHelperCell: null,\n\n    _titleHelperCellOuterWidth: null,\n\n    _ancestors: null,\n    _updateAncestorsFrame: null,\n\n    _draggeeLevel: null,\n    _draggeeLevelDelta: null,\n    draggingLastElements: null,\n    _loadingDraggeeLevelDelta: false,\n\n    _targetLevel: null,\n    _targetLevelBounds: null,\n\n    _positionChanged: null,\n\n    /**\n     * Constructor\n     */\n    init: function (tableView, $elements, settings) {\n      this.tableView = tableView;\n      this.structureId = this.tableView.$table.data('structure-id');\n      this.maxLevels = parseInt(this.tableView.$table.attr('data-max-levels'));\n\n      this._basePadding = 14 + (this.tableView.elementIndex.actions ? 34 : 24); // see _elements/tableview/elements.html\n      this._helperMargin = this.tableView.elementIndex.actions ? 54 : 0;\n\n      settings = $.extend({}, Craft.StructureTableSorter.defaults, settings, {\n        handle: '.move',\n        collapseDraggees: true,\n        singleHelper: true,\n        helperSpacingY: 2,\n        magnetStrength: 4,\n        helper: this.getHelper.bind(this),\n        helperLagBase: 1.5,\n        axis: Garnish.Y_AXIS,\n      });\n\n      this.base($elements, settings);\n    },\n\n    /**\n     * Returns the draggee rows (including any descendent rows).\n     */\n    findDraggee: function () {\n      this._draggeeLevel = this._targetLevel = this.$targetItem.data('level');\n      this._draggeeLevelDelta = 0;\n\n      var $draggee = $(this.$targetItem),\n        $nextRow = this.$targetItem.next();\n\n      while ($nextRow.length) {\n        // See if this row is a descendant of the draggee\n        var nextRowLevel = $nextRow.data('level');\n\n        if (nextRowLevel <= this._draggeeLevel) {\n          break;\n        }\n\n        // Is this the deepest descendant we've seen so far?\n        var nextRowLevelDelta = nextRowLevel - this._draggeeLevel;\n\n        if (nextRowLevelDelta > this._draggeeLevelDelta) {\n          this._draggeeLevelDelta = nextRowLevelDelta;\n        }\n\n        // Add it and prep the next row\n        $draggee = $draggee.add($nextRow);\n        $nextRow = $nextRow.next();\n      }\n\n      // Are we dragging the last elements on the page?\n      this.draggingLastElements = !$nextRow.length;\n\n      // Do we have a maxLevels to enforce,\n      // and does it look like this draggee has descendants we don't know about yet?\n      if (\n        this.maxLevels &&\n        this.draggingLastElements &&\n        this.tableView.getMorePending()\n      ) {\n        // Only way to know the true descendant level delta is to ask PHP\n        this._loadingDraggeeLevelDelta = true;\n\n        var data = this._getAjaxBaseData(this.$targetItem);\n\n        Craft.sendActionRequest('POST', 'structures/get-element-level-delta', {\n          data,\n        }).then((response) => {\n          this._loadingDraggeeLevelDelta = false;\n\n          if (this.dragging) {\n            this._draggeeLevelDelta = response.data.delta;\n            this.drag(false);\n          }\n        });\n      }\n\n      return $draggee;\n    },\n\n    /**\n     * Returns the drag helper.\n     */\n    getHelper: function ($helperRow) {\n      var $outerContainer = $(\n          '<div class=\"elements datatablesorthelper\"/>'\n        ).appendTo(Garnish.$bod),\n        $innerContainer = $('<div class=\"tableview\"/>').appendTo(\n          $outerContainer\n        ),\n        $table = $('<table class=\"data\"/>').appendTo($innerContainer),\n        $tbody = $('<tbody/>').appendTo($table);\n\n      $helperRow.appendTo($tbody);\n\n      // Copy the column widths\n      this._$firstRowCells = this.tableView.$elementContainer\n        .children('tr:first')\n        .children();\n      var $helperCells = $helperRow.children();\n\n      for (var i = 0; i < $helperCells.length; i++) {\n        var $helperCell = $($helperCells[i]);\n\n        // Skip the checkbox cell\n        if ($helperCell.hasClass('checkbox-cell')) {\n          $helperCell.remove();\n          continue;\n        }\n\n        // Hard-set the cell widths\n        var $firstRowCell = $(this._$firstRowCells[i]);\n        var width = $firstRowCell[0].getBoundingClientRect().width;\n\n        $firstRowCell.css('width', width + 'px');\n        $helperCell.css('width', width + 'px');\n\n        // Is this the title cell?\n        if (Garnish.hasAttr($firstRowCell, 'data-titlecell')) {\n          this._$titleHelperCell = $helperCell;\n          var padding = parseInt($firstRowCell.css('padding-' + Craft.left));\n          this._titleHelperCellOuterWidth = width;\n\n          $helperCell.css('padding-' + Craft.left, this._basePadding);\n        }\n      }\n\n      return $outerContainer;\n    },\n\n    /**\n     * Returns whether the draggee can be inserted before a given item.\n     */\n    canInsertBefore: function ($item) {\n      if (this._loadingDraggeeLevelDelta) {\n        return false;\n      }\n\n      return this._getLevelBounds($item.prev(), $item) !== false;\n    },\n\n    /**\n     * Returns whether the draggee can be inserted after a given item.\n     */\n    canInsertAfter: function ($item) {\n      if (this._loadingDraggeeLevelDelta) {\n        return false;\n      }\n\n      return this._getLevelBounds($item, $item.next()) !== false;\n    },\n\n    // Events\n    // -------------------------------------------------------------------------\n\n    /**\n     * On Drag Start\n     */\n    onDragStart: function () {\n      // Get the initial set of ancestors, before the item gets moved\n      this._ancestors = this._getAncestors(\n        this.$targetItem,\n        this.$targetItem.data('level')\n      );\n\n      // Set the initial target level bounds\n      this._setTargetLevelBounds();\n\n      // Check to see if we should load more elements now\n      this.tableView.maybeLoadMore();\n\n      this.base();\n    },\n\n    /**\n     * On Drag\n     */\n    onDrag: function () {\n      this.base();\n      this._updateIndent();\n    },\n\n    /**\n     * On Insertion Point Change\n     */\n    onInsertionPointChange: function () {\n      this._setTargetLevelBounds();\n      this._updateAncestorsBeforeRepaint();\n      this.base();\n    },\n\n    /**\n     * On Drag Stop\n     */\n    onDragStop: function () {\n      this._positionChanged = false;\n      this.base();\n\n      // Update the draggee's padding if the position just changed\n      // ---------------------------------------------------------------------\n\n      if (this._targetLevel != this._draggeeLevel) {\n        var levelDiff = this._targetLevel - this._draggeeLevel;\n\n        for (var i = 0; i < this.$draggee.length; i++) {\n          var $draggee = $(this.$draggee[i]),\n            oldLevel = $draggee.data('level'),\n            newLevel = oldLevel + levelDiff,\n            padding = this._basePadding + this._getLevelIndent(newLevel);\n\n          $draggee.data('level', newLevel);\n          $draggee.find('.element').data('level', newLevel);\n          $draggee\n            .children('[data-titlecell]:first')\n            .css('padding-' + Craft.left, padding);\n        }\n\n        this._positionChanged = true;\n      }\n\n      // Keep in mind this could have also been set by onSortChange()\n      if (this._positionChanged) {\n        // Tell the server about the new position\n        // -----------------------------------------------------------------\n\n        var data = this._getAjaxBaseData(this.$draggee);\n\n        // Find the previous sibling/parent, if there is one\n        var $prevRow = this.$draggee.first().prev();\n\n        while ($prevRow.length) {\n          var prevRowLevel = $prevRow.data('level');\n\n          if (prevRowLevel == this._targetLevel) {\n            data.prevId = $prevRow.data('id');\n            break;\n          }\n\n          if (prevRowLevel < this._targetLevel) {\n            data.parentId = $prevRow.data('id');\n\n            // Is this row collapsed?\n            var $toggle = $prevRow.find('> th > .toggle');\n\n            if (!$toggle.hasClass('expanded')) {\n              // Make it look expanded\n              $toggle.addClass('expanded');\n\n              // Add a temporary row\n              var $spinnerRow = this.tableView._createSpinnerRowAfter($prevRow);\n\n              // Remove the target item\n              if (this.tableView.elementSelect) {\n                this.tableView.elementSelect.removeItems(this.$targetItem);\n              }\n\n              this.removeItems(this.$targetItem);\n              this.$targetItem.remove();\n              this.tableView._totalVisible--;\n            }\n\n            break;\n          }\n\n          $prevRow = $prevRow.prev();\n        }\n\n        Craft.sendActionRequest('POST', 'structures/move-element', {data})\n          .then((response) => {\n            Craft.cp.displaySuccess(Craft.t('app', 'New position saved.'));\n            this.onPositionChange();\n\n            // Were we waiting on this to complete so we can expand the new parent?\n            if ($spinnerRow && $spinnerRow.parent().length) {\n              $spinnerRow.remove();\n              this.tableView._expandElement($toggle, true);\n            }\n\n            // See if we should run any pending tasks\n            Craft.cp.runQueue();\n          })\n          .catch(({response}) => {\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n            this.tableView.elementIndex.updateElements();\n            return;\n          });\n      }\n    },\n\n    onSortChange: function () {\n      if (this.tableView.elementSelect) {\n        this.tableView.elementSelect.resetItemOrder();\n      }\n\n      this._positionChanged = true;\n      this.base();\n    },\n\n    onPositionChange: function () {\n      Garnish.requestAnimationFrame(() => {\n        this.trigger('positionChange');\n        this.settings.onPositionChange();\n      });\n    },\n\n    onReturnHelpersToDraggees: function () {\n      this._$firstRowCells.css('width', '');\n\n      // If we were dragging the last elements on the page and ended up loading any additional elements in,\n      // there could be a gap between the last draggee item and whatever now comes after it.\n      // So remove the post-draggee elements and possibly load up the next batch.\n      if (this.draggingLastElements && this.tableView.getMorePending()) {\n        // Update the element index's record of how many items are actually visible\n        this.tableView._totalVisible +=\n          this.newDraggeeIndexes[0] - this.oldDraggeeIndexes[0];\n\n        var $postDraggeeItems = this.$draggee.last().nextAll();\n\n        if ($postDraggeeItems.length) {\n          this.removeItems($postDraggeeItems);\n          $postDraggeeItems.remove();\n          this.tableView.maybeLoadMore();\n        }\n      }\n\n      this.base();\n    },\n\n    /**\n     * Returns the min and max levels that the draggee could occupy between\n     * two given rows, or false if it’s not going to work out.\n     */\n    _getLevelBounds: function ($prevRow, $nextRow) {\n      // Can't go any lower than the next row, if there is one\n      if ($nextRow && $nextRow.length) {\n        this._getLevelBounds._minLevel = $nextRow.data('level');\n      } else {\n        this._getLevelBounds._minLevel = 1;\n      }\n\n      // Can't go any higher than the previous row + 1\n      if ($prevRow && $prevRow.length) {\n        this._getLevelBounds._maxLevel = $prevRow.data('level') + 1;\n      } else {\n        this._getLevelBounds._maxLevel = 1;\n      }\n\n      // Does this structure have a max level?\n      if (this.maxLevels) {\n        // Make sure it's going to fit at all here\n        if (\n          this._getLevelBounds._minLevel != 1 &&\n          this._getLevelBounds._minLevel + this._draggeeLevelDelta >\n            this.maxLevels\n        ) {\n          return false;\n        }\n\n        // Limit the max level if we have to\n        if (\n          this._getLevelBounds._maxLevel + this._draggeeLevelDelta >\n          this.maxLevels\n        ) {\n          this._getLevelBounds._maxLevel =\n            this.maxLevels - this._draggeeLevelDelta;\n\n          if (this._getLevelBounds._maxLevel < this._getLevelBounds._minLevel) {\n            this._getLevelBounds._maxLevel = this._getLevelBounds._minLevel;\n          }\n        }\n      }\n\n      return {\n        min: this._getLevelBounds._minLevel,\n        max: this._getLevelBounds._maxLevel,\n      };\n    },\n\n    /**\n     * Determines the min and max possible levels at the current draggee's position.\n     */\n    _setTargetLevelBounds: function () {\n      this._targetLevelBounds = this._getLevelBounds(\n        this.$draggee.first().prev(),\n        this.$draggee.last().next()\n      );\n    },\n\n    /**\n     * Determines the target level based on the current mouse position.\n     */\n    _updateIndent: function (forcePositionChange) {\n      // Figure out the target level\n      // ---------------------------------------------------------------------\n\n      // How far has the cursor moved?\n      this._updateIndent._mouseDist = this.realMouseX - this.mousedownX;\n\n      // Flip that if this is RTL\n      if (Craft.orientation === 'rtl') {\n        this._updateIndent._mouseDist *= -1;\n      }\n\n      // What is that in indentation levels?\n      this._updateIndent._indentationDist = Math.round(\n        this._updateIndent._mouseDist / Craft.StructureTableSorter.LEVEL_INDENT\n      );\n\n      // Combine with the original level to get the new target level\n      this._updateIndent._targetLevel =\n        this._draggeeLevel + this._updateIndent._indentationDist;\n\n      // Contain it within our min/max levels\n      if (this._updateIndent._targetLevel < this._targetLevelBounds.min) {\n        this._updateIndent._indentationDist +=\n          this._targetLevelBounds.min - this._updateIndent._targetLevel;\n        this._updateIndent._targetLevel = this._targetLevelBounds.min;\n      } else if (\n        this._updateIndent._targetLevel > this._targetLevelBounds.max\n      ) {\n        this._updateIndent._indentationDist -=\n          this._updateIndent._targetLevel - this._targetLevelBounds.max;\n        this._updateIndent._targetLevel = this._targetLevelBounds.max;\n      }\n\n      // Has the target level changed?\n      if (\n        this._targetLevel !==\n        (this._targetLevel = this._updateIndent._targetLevel)\n      ) {\n        // Target level is changing, so update the ancestors\n        this._updateAncestorsBeforeRepaint();\n      }\n\n      // Update the UI\n      // ---------------------------------------------------------------------\n\n      // How far away is the cursor from the exact target level distance?\n      this._updateIndent._targetLevelMouseDiff =\n        this._updateIndent._mouseDist -\n        this._updateIndent._indentationDist *\n          Craft.StructureTableSorter.LEVEL_INDENT;\n\n      // What's the magnet impact of that?\n      this._updateIndent._magnetImpact = Math.round(\n        this._updateIndent._targetLevelMouseDiff / 15\n      );\n\n      // Put it on a leash\n      if (\n        Math.abs(this._updateIndent._magnetImpact) >\n        Craft.StructureTableSorter.MAX_GIVE\n      ) {\n        this._updateIndent._magnetImpact =\n          (this._updateIndent._magnetImpact > 0 ? 1 : -1) *\n          Craft.StructureTableSorter.MAX_GIVE;\n      }\n\n      // Apply the new margin/width\n      this._updateIndent._closestLevelMagnetIndent =\n        this._getLevelIndent(this._targetLevel) +\n        this._updateIndent._magnetImpact;\n      this.helpers[0].css(\n        'margin-' + Craft.left,\n        this._updateIndent._closestLevelMagnetIndent + this._helperMargin\n      );\n      this._$titleHelperCell.css(\n        'width',\n        this._titleHelperCellOuterWidth -\n          this._updateIndent._closestLevelMagnetIndent\n      );\n    },\n\n    /**\n     * Returns the indent size for a given level\n     */\n    _getLevelIndent: function (level) {\n      return (level - 1) * Craft.StructureTableSorter.LEVEL_INDENT;\n    },\n\n    /**\n     * Returns the base data that should be sent with StructureController Ajax requests.\n     */\n    _getAjaxBaseData: function ($row) {\n      return {\n        structureId: this.structureId,\n        elementId: $row.data('id'),\n        siteId: $row.find('.element:first').data('site-id'),\n      };\n    },\n\n    /**\n     * Returns a row's ancestor rows\n     */\n    _getAncestors: function ($row, targetLevel) {\n      this._getAncestors._ancestors = [];\n\n      if (targetLevel != 0) {\n        this._getAncestors._level = targetLevel;\n        this._getAncestors._$prevRow = $row.prev();\n\n        while (this._getAncestors._$prevRow.length) {\n          if (\n            this._getAncestors._$prevRow.data('level') <\n            this._getAncestors._level\n          ) {\n            this._getAncestors._ancestors.unshift(this._getAncestors._$prevRow);\n            this._getAncestors._level =\n              this._getAncestors._$prevRow.data('level');\n\n            // Did we just reach the top?\n            if (this._getAncestors._level == 0) {\n              break;\n            }\n          }\n\n          this._getAncestors._$prevRow = this._getAncestors._$prevRow.prev();\n        }\n      }\n\n      return this._getAncestors._ancestors;\n    },\n\n    /**\n     * Prepares to have the ancestors updated before the screen is repainted.\n     */\n    _updateAncestorsBeforeRepaint: function () {\n      if (this._updateAncestorsFrame) {\n        Garnish.cancelAnimationFrame(this._updateAncestorsFrame);\n      }\n\n      this._updateAncestorsFrame = Garnish.requestAnimationFrame(\n        this._updateAncestors.bind(this)\n      );\n    },\n\n    _updateAncestors: function () {\n      this._updateAncestorsFrame = null;\n\n      // Update the old ancestors\n      // -----------------------------------------------------------------\n\n      for (\n        this._updateAncestors._i = 0;\n        this._updateAncestors._i < this._ancestors.length;\n        this._updateAncestors._i++\n      ) {\n        this._updateAncestors._$ancestor =\n          this._ancestors[this._updateAncestors._i];\n\n        // One less descendant now\n        this._updateAncestors._$ancestor.data(\n          'descendants',\n          this._updateAncestors._$ancestor.data('descendants') - 1\n        );\n\n        // Is it now childless?\n        if (this._updateAncestors._$ancestor.data('descendants') == 0) {\n          // Remove its toggle\n          this._updateAncestors._$ancestor\n            .find('> th > .toggle:first')\n            .remove();\n        }\n      }\n\n      // Update the new ancestors\n      // -----------------------------------------------------------------\n\n      this._updateAncestors._newAncestors = this._getAncestors(\n        this.$targetItem,\n        this._targetLevel\n      );\n\n      for (\n        this._updateAncestors._i = 0;\n        this._updateAncestors._i < this._updateAncestors._newAncestors.length;\n        this._updateAncestors._i++\n      ) {\n        this._updateAncestors._$ancestor =\n          this._updateAncestors._newAncestors[this._updateAncestors._i];\n\n        // One more descendant now\n        this._updateAncestors._$ancestor.data(\n          'descendants',\n          this._updateAncestors._$ancestor.data('descendants') + 1\n        );\n\n        // Is this its first child?\n        if (this._updateAncestors._$ancestor.data('descendants') == 1) {\n          // Create its toggle\n          const ancestorTitle = this._updateAncestors._$ancestor.data('title');\n          $(\n            '<button class=\"toggle expanded\" type=\"button\" aria-expanded=\"true\" title=\"' +\n              Craft.t('app', 'Show/hide children') +\n              '\" aria-label=\"' +\n              Craft.t('app', 'Show {title} children', {title: ancestorTitle}) +\n              '\"></button>'\n          ).insertAfter(\n            this._updateAncestors._$ancestor.find('> th .move:first')\n          );\n        }\n      }\n\n      this._ancestors = this._updateAncestors._newAncestors;\n\n      delete this._updateAncestors._i;\n      delete this._updateAncestors._$ancestor;\n      delete this._updateAncestors._newAncestors;\n    },\n  },\n  {\n    HELPER_MARGIN: 0,\n    LEVEL_INDENT: 44,\n    MAX_GIVE: 22,\n\n    defaults: {\n      onPositionChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Table Element Index View\n */\nCraft.TableElementIndexView = Craft.BaseElementIndexView.extend({\n  $table: null,\n  $tableCaption: null,\n  $selectedSortHeader: null,\n  $statusMessage: null,\n\n  structureTableSort: null,\n\n  _totalVisiblePostStructureTableDraggee: null,\n  _morePendingPostStructureTableDraggee: false,\n\n  _broadcastListener: null,\n\n  getElementContainer: function () {\n    // Save a reference to the table\n    this.$table = this.$container.find('table:first');\n    return this.$table.children('tbody:first');\n  },\n\n  afterInit: function () {\n    // Set table caption\n    this.$tableCaption = this.$table.find('caption');\n\n    this.$statusMessage = this.$table.parent().find('[data-status-message]');\n\n    // Set the sort header\n    this.initTableHeaders();\n\n    // Add callback for after elements are updated\n    this.elementIndex.on('updateElements', () => {\n      this._updateScreenReaderStatus();\n    });\n\n    // Create the Structure Table Sorter\n    if (\n      this.elementIndex.settings.context === 'index' &&\n      this.elementIndex.viewMode === 'structure' &&\n      Garnish.hasAttr(this.$table, 'data-structure-id')\n    ) {\n      this.structureTableSort = new Craft.StructureTableSorter(\n        this,\n        this.getAllElements()\n      );\n    } else {\n      this.structureTableSort = null;\n    }\n\n    // Handle expand/collapse toggles for Structures\n    if (this.elementIndex.viewMode === 'structure') {\n      this.addListener(this.$elementContainer, 'click', function (ev) {\n        var $target = $(ev.target);\n\n        if ($target.hasClass('toggle')) {\n          if (this._collapseElement($target) === false) {\n            this._expandElement($target);\n          }\n        }\n      });\n    }\n\n    // Set up the broadcast listener\n    if (Craft.messageReceiver) {\n      this._broadcastListener = (ev) => {\n        if (ev.data.event === 'saveElement') {\n          const $rows = this.$table.find(\n            `> tbody > tr[data-id=\"${ev.data.id}\"]`\n          );\n          if ($rows.length) {\n            const data = {\n              elementType: this.elementIndex.elementType,\n              source: this.elementIndex.sourceKey,\n              id: ev.data.id,\n              siteId: this.elementIndex.siteId,\n            };\n            Craft.sendActionRequest(\n              'POST',\n              'element-indexes/element-table-html',\n              {data}\n            ).then(({data}) => {\n              for (let i = 0; i < $rows.length; i++) {\n                const $row = $rows.eq(i);\n                $row\n                  .find('> th[data-titlecell] .element')\n                  .replaceWith(data.elementHtml);\n                for (let attribute in data.attributeHtml) {\n                  if (data.attributeHtml.hasOwnProperty(attribute)) {\n                    $row\n                      .find(`> td[data-attr=\"${attribute}\"]`)\n                      .html(data.attributeHtml[attribute]);\n                  }\n                }\n              }\n              Craft.cp.elementThumbLoader.load($rows);\n            });\n          }\n        }\n      };\n\n      Craft.messageReceiver.addEventListener(\n        'message',\n        this._broadcastListener\n      );\n    }\n  },\n\n  initTableHeaders: function () {\n    let selectedSortAttr, selectedSortDir;\n    if (this.elementIndex.viewMode === 'structure') {\n      selectedSortAttr = 'structure';\n      selectedSortDir = 'asc';\n    } else {\n      [selectedSortAttr, selectedSortDir] =\n        this.elementIndex.getSortAttributeAndDirection();\n    }\n\n    const $tableHeaders = this.$table\n      .children('thead')\n      .children()\n      .children('[data-attribute]');\n\n    for (let i = 0; i < $tableHeaders.length; i++) {\n      const $header = $tableHeaders.eq(i);\n      const attr = $header.attr('data-attribute');\n      let sortValue = 'none';\n\n      // Is this the selected sort attribute?\n      if (attr === selectedSortAttr) {\n        this.$selectedSortHeader = $header;\n        sortValue = selectedSortDir === 'asc' ? 'ascending' : 'descending';\n        $header.addClass('ordered ' + selectedSortDir);\n        this.makeColumnSortable($header, true);\n      } else {\n        // Is this attribute sortable?\n        if (this.elementIndex.getSortOption(attr)) {\n          this.makeColumnSortable($header);\n        }\n      }\n\n      $header.attr('aria-sort', sortValue);\n    }\n  },\n\n  makeColumnSortable: function ($header, sorted = false) {\n    $header.addClass('orderable');\n\n    const headerHtml = $header.html();\n    const $instructions = this.$tableCaption.find('[data-sort-instructions]');\n    const $headerButton = $('<button/>', {\n      id: `${this.elementIndex.idPrefix}-${$header.attr('data-attribute')}`,\n      type: 'button',\n      'aria-pressed': 'false',\n    }).html(headerHtml);\n\n    if ($instructions.length) {\n      $headerButton.attr('aria-describedby', $instructions.attr('id'));\n    }\n\n    if (sorted) {\n      $headerButton.attr('aria-pressed', 'true');\n      $headerButton.on('click', this._handleSelectedSortHeaderClick.bind(this));\n    } else {\n      $headerButton.on(\n        'click',\n        this._handleUnselectedSortHeaderClick.bind(this)\n      );\n    }\n\n    $header.empty().append($headerButton);\n  },\n\n  isVerticalList: function () {\n    return true;\n  },\n\n  getTotalVisible: function () {\n    if (this._isStructureTableDraggingLastElements()) {\n      return this._totalVisiblePostStructureTableDraggee;\n    } else {\n      return this._totalVisible;\n    }\n  },\n\n  setTotalVisible: function (totalVisible) {\n    if (this._isStructureTableDraggingLastElements()) {\n      this._totalVisiblePostStructureTableDraggee = totalVisible;\n    } else {\n      this._totalVisible = totalVisible;\n    }\n  },\n\n  getMorePending: function () {\n    if (this._isStructureTableDraggingLastElements()) {\n      return this._morePendingPostStructureTableDraggee;\n    } else {\n      return this._morePending;\n    }\n  },\n\n  setMorePending: function (morePending) {\n    if (this._isStructureTableDraggingLastElements()) {\n      this._morePendingPostStructureTableDraggee = morePending;\n    } else {\n      this._morePending = this._morePendingPostStructureTableDraggee =\n        morePending;\n    }\n  },\n\n  getLoadMoreParams: function () {\n    var params = this.base();\n\n    // If we are dragging the last elements on the page,\n    // tell the controller to only load elements positioned after the draggee.\n    if (this._isStructureTableDraggingLastElements()) {\n      params.criteria.positionedAfter =\n        this.structureTableSort.$targetItem.data('id');\n    }\n\n    return params;\n  },\n\n  appendElements: function ($newElements) {\n    this.base($newElements);\n\n    if (this.structureTableSort) {\n      this.structureTableSort.addItems($newElements);\n    }\n\n    Craft.cp.updateResponsiveTables();\n  },\n\n  _collapseElement: function ($toggle, force) {\n    if (!force && !$toggle.hasClass('expanded')) {\n      return false;\n    }\n\n    $toggle.removeClass('expanded');\n    $toggle.attr('aria-expanded', 'false');\n\n    // Find and remove the descendant rows\n    var $row = $toggle.parent().parent(),\n      id = $row.data('id'),\n      level = $row.data('level'),\n      $nextRow = $row.next();\n\n    while ($nextRow.length) {\n      if (!Garnish.hasAttr($nextRow, 'data-spinnerrow')) {\n        if ($nextRow.data('level') <= level) {\n          break;\n        }\n\n        if (this.elementSelect) {\n          this.elementSelect.removeItems($nextRow);\n        }\n\n        if (this.structureTableSort) {\n          this.structureTableSort.removeItems($nextRow);\n        }\n\n        this._totalVisible--;\n      }\n\n      var $nextNextRow = $nextRow.next();\n      $nextRow.remove();\n      $nextRow = $nextNextRow;\n    }\n\n    // Remember that this row should be collapsed\n    if (!this.elementIndex.instanceState.collapsedElementIds) {\n      this.elementIndex.instanceState.collapsedElementIds = [];\n    }\n\n    this.elementIndex.instanceState.collapsedElementIds.push(id);\n    this.elementIndex.setInstanceState(\n      'collapsedElementIds',\n      this.elementIndex.instanceState.collapsedElementIds\n    );\n\n    // Bottom of the index might be viewable now\n    this.maybeLoadMore();\n  },\n\n  _expandElement: function ($toggle, force) {\n    if (!force && $toggle.hasClass('expanded')) {\n      return false;\n    }\n\n    $toggle.addClass('expanded');\n    $toggle.attr('aria-expanded', 'true');\n\n    // Remove this element from our list of collapsed elements\n    if (this.elementIndex.instanceState.collapsedElementIds) {\n      var $row = $toggle.parent().parent(),\n        id = $row.data('id'),\n        index = $.inArray(\n          id,\n          this.elementIndex.instanceState.collapsedElementIds\n        );\n\n      if (index !== -1) {\n        this.elementIndex.instanceState.collapsedElementIds.splice(index, 1);\n        this.elementIndex.setInstanceState(\n          'collapsedElementIds',\n          this.elementIndex.instanceState.collapsedElementIds\n        );\n\n        // Add a temporary row\n        var $spinnerRow = this._createSpinnerRowAfter($row);\n\n        // Load the nested elements\n        let data = $.extend(true, {}, this.settings.params);\n        data.criteria.descendantOf = id;\n\n        Craft.sendActionRequest('POST', this.settings.loadMoreElementsAction, {\n          data,\n        })\n          .then((response) => {\n            // Do we even care about this anymore?\n            if (!$spinnerRow.parent().length) {\n              return;\n            }\n\n            let $newElements = $(response.data.html);\n\n            // Are there more descendants we didn't get in this batch?\n            let totalVisible = this._totalVisible + $newElements.length;\n            let morePending =\n              this.settings.batchSize &&\n              $newElements.length === this.settings.batchSize;\n\n            if (morePending) {\n              // Remove all the elements after it\n              let $nextRows = $spinnerRow.nextAll();\n\n              if (this.elementSelect) {\n                this.elementSelect.removeItems($nextRows);\n              }\n\n              if (this.structureTableSort) {\n                this.structureTableSort.removeItems($nextRows);\n              }\n\n              $nextRows.remove();\n              totalVisible -= $nextRows.length;\n            } else {\n              // Maintain the current 'more' status\n              morePending = this._morePending;\n            }\n\n            $spinnerRow.replaceWith($newElements);\n            this.thumbLoader.load($newElements);\n\n            if (this.elementIndex.actions || this.settings.selectable) {\n              this.elementSelect.addItems(\n                $newElements.filter(':not(.disabled)')\n              );\n              this.elementIndex.updateActionTriggers();\n            }\n\n            if (this.structureTableSort) {\n              this.structureTableSort.addItems($newElements);\n            }\n\n            Craft.appendHeadHtml(response.data.headHtml);\n            Craft.appendBodyHtml(response.data.bodyHtml);\n            Craft.cp.updateResponsiveTables();\n\n            this.setTotalVisible(totalVisible);\n            this.setMorePending(morePending);\n\n            // Is there room to load more right now?\n            this.maybeLoadMore();\n          })\n          .catch((e) => {\n            Craft.cp.displayError();\n            if (!$spinnerRow.parent().length) {\n              return;\n            }\n          });\n      }\n    }\n  },\n\n  _createSpinnerRowAfter: function ($row) {\n    return $(\n      '<tr data-spinnerrow>' +\n        '<td class=\"centeralign\" colspan=\"' +\n        $row.children().length +\n        '\">' +\n        '<div class=\"spinner\"/>' +\n        '</td>' +\n        '</tr>'\n    ).insertAfter($row);\n  },\n\n  _isStructureTableDraggingLastElements: function () {\n    return (\n      this.structureTableSort &&\n      this.structureTableSort.dragging &&\n      this.structureTableSort.draggingLastElements\n    );\n  },\n\n  _handleSelectedSortHeaderClick: function (ev) {\n    var $header = $(ev.currentTarget).closest('th');\n\n    if ($header.hasClass('loading')) {\n      return;\n    }\n\n    // Reverse the sort direction\n    var selectedSortDir = this.elementIndex.getSelectedSortDirection(),\n      newSortDir = selectedSortDir === 'asc' ? 'desc' : 'asc';\n\n    // In case it's actually the structure view\n    this.elementIndex.selectViewMode('table');\n\n    this.elementIndex.setSelectedSortDirection(newSortDir);\n    this._handleSortHeaderClick(ev, $header);\n  },\n\n  _handleUnselectedSortHeaderClick: function (ev) {\n    var $header = $(ev.currentTarget).closest('th');\n\n    if ($header.hasClass('loading')) {\n      return;\n    }\n\n    var attr = $header.attr('data-attribute');\n\n    // In case it's actually the structure view\n    this.elementIndex.selectViewMode('table');\n\n    this.elementIndex.setSelectedSortAttribute(attr);\n    this._handleSortHeaderClick(ev, $header);\n  },\n\n  _handleSortHeaderClick: function (ev, $header) {\n    if (this.$selectedSortHeader) {\n      this.$selectedSortHeader.removeClass('ordered asc desc');\n    }\n\n    $header.addClass('ordered loading');\n    this.elementIndex.updateElements();\n\n    // No need for two spinners\n    this.elementIndex.setIndexAvailable();\n  },\n\n  _updateScreenReaderStatus: function () {\n    let attr, dir;\n    if (this.elementIndex.viewMode === 'structure') {\n      attr = 'structure';\n      dir = 'asc';\n    } else {\n      [attr, dir] = this.elementIndex.getSortAttributeAndDirection();\n    }\n\n    const attrLabel = this.elementIndex.getSortLabel(attr);\n    if (!attrLabel) {\n      return;\n    }\n\n    const dirLabel =\n      dir === 'asc'\n        ? Craft.t('app', 'Ascending')\n        : Craft.t('app', 'Descending');\n\n    const message = Craft.t(\n      'app',\n      'Table {name} sorted by {attribute}, {direction}',\n      {\n        name: this.$table.attr('data-name'),\n        attribute: attrLabel,\n        direction: dirLabel,\n      }\n    );\n\n    this.$statusMessage.empty();\n    this.$statusMessage.text(message);\n  },\n\n  _updateTableAttributes: function ($element, tableAttributes) {\n    var $tr = $element.closest('tr');\n\n    for (var attr in tableAttributes) {\n      if (!tableAttributes.hasOwnProperty(attr)) {\n        continue;\n      }\n\n      $tr\n        .children('[data-attr=\"' + attr + '\"]:first')\n        .html(tableAttributes[attr]);\n    }\n  },\n\n  destroy: function () {\n    if (this._broadcastListener) {\n      Craft.messageReceiver.removeEventListener(\n        'message',\n        this._broadcastListener\n      );\n      delete this._broadcastListener;\n    }\n\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Tab manager\n */\nCraft.Tabs = Garnish.Base.extend({\n  $container: null,\n  $tablist: null,\n  $menuBtn: null,\n  $tabs: null,\n  $firstTab: null,\n  $lastTab: null,\n  $selectedTab: null,\n  $focusableTab: null,\n  menu: null,\n\n  init: function (container) {\n    this.$container = $(container);\n    this.$tablist = this.$container.find('> [role=\"tablist\"]:first');\n    this.$tabs = this.$tablist.find('> [role=\"tab\"]');\n    this.$firstTab = this.$tabs.first();\n    this.$lastTab = this.$tabs.last();\n    this.$selectedTab = this.$tabs.filter('.sel:first');\n    this.$focusableTab = this.$tabs.filter('[tabindex=0]:first');\n    this.$menuBtn = this.$container.find('> .menubtn:first').menubtn();\n    this.menu = this.$menuBtn.data('menubtn').menu;\n\n    // Is there already a tab manager?\n    if (this.$container.data('tabs')) {\n      console.warn('Double-instantiating a tab manager on an element');\n      this.$container.data('tabs').destroy();\n    }\n\n    this.$container.data('tabs', this);\n\n    for (let i = 0; i < this.$tabs.length; i++) {\n      const $a = this.$tabs.eq(i);\n\n      // Does it link to an anchor?\n      const href = $a.attr('href');\n      if (href && href.charAt(0) === '#') {\n        this.addListener($a, 'keydown', (ev) => {\n          if ([Garnish.SPACE_KEY, Garnish.RETURN_KEY].includes(ev.keyCode)) {\n            ev.preventDefault();\n            this.selectTab(ev.currentTarget);\n          }\n        });\n        this.addListener($a, 'click', (ev) => {\n          ev.preventDefault();\n          this.selectTab(ev.currentTarget);\n        });\n      }\n\n      this.addListener($a, 'keydown', (ev) => {\n        let $tab;\n        if (\n          [Garnish.LEFT_KEY, Garnish.RIGHT_KEY].includes(ev.keyCode) &&\n          $.contains(this.$tablist[0], ev.currentTarget)\n        ) {\n          if (\n            ev.keyCode ===\n            (Craft.orientation === 'ltr' ? Garnish.LEFT_KEY : Garnish.RIGHT_KEY)\n          ) {\n            $tab = $(ev.currentTarget).prevAll(\n              '[role=\"tab\"]:not(.hidden):first'\n            );\n            $tab = $tab.length ? $tab : this.$lastTab;\n          } else {\n            $tab = $(ev.currentTarget).nextAll(\n              '[role=\"tab\"]:not(.hidden):first'\n            );\n            $tab = $tab.length ? $tab : this.$firstTab;\n          }\n        } else if (\n          ev.keyCode === Garnish.HOME_KEY ||\n          ev.keyCode === Garnish.END_KEY\n        ) {\n          $tab =\n            ev.keyCode === Garnish.HOME_KEY ? this.$firstTab : this.$lastTab;\n        }\n\n        if ($tab) {\n          ev.preventDefault();\n          this.makeTabFocusable($tab);\n          $tab.focus();\n          this.scrollToTab($tab);\n        }\n      });\n    }\n\n    this.updateMenuBtn();\n\n    Garnish.$win.on('resize', () => {\n      this.updateMenuBtn();\n    });\n\n    // Prevent menu options from updating the URL\n    this.menu.$options.on('click', (ev) => {\n      const $option = $(ev.currentTarget);\n      const href = $option.attr('href');\n      if (href && href.charAt(0) === '#') {\n        ev.preventDefault();\n      }\n    });\n\n    this.menu.on('optionselect', (ev) => {\n      this.selectTab($(ev.selectedOption).data('id'));\n    });\n  },\n\n  selectTab: function (tab, focusTab = true) {\n    const $tab = this._getTab(tab);\n\n    if ($tab[0] === this.$selectedTab[0]) {\n      return;\n    }\n\n    this.deselectTab();\n    this.$selectedTab = $tab.addClass('sel').attr('aria-selected', 'true');\n    this.makeTabFocusable($tab);\n\n    if (focusTab) {\n      $tab.trigger('focus');\n    }\n\n    this.scrollToTab($tab);\n\n    this.menu.$options.removeClass('sel');\n    this.menu.$options.filter(`[data-id=\"${$tab.data('id')}\"]`).addClass('sel');\n\n    this.trigger('selectTab', {\n      $tab: $tab,\n    });\n\n    $('#content').trigger('scroll');\n\n    const $slideoutContainer = $tab.closest('.slideout-container');\n    if ($slideoutContainer.length) {\n      $slideoutContainer.find('.so-content').trigger('scroll');\n    }\n  },\n\n  deselectTab: function () {\n    const $tab = this.$selectedTab\n      .removeClass('sel')\n      .attr('aria-selected', 'false');\n    this.$selectedTab = null;\n\n    this.trigger('deselectTab', {\n      $tab: $tab,\n    });\n  },\n\n  makeTabFocusable: function (tab) {\n    const $tab = this._getTab(tab);\n\n    if ($tab[0] === this.$focusableTab[0]) {\n      return;\n    }\n\n    this.$focusableTab.attr('tabindex', '-1');\n    this.$focusableTab = $tab.attr('tabindex', '0');\n  },\n\n  scrollToTab: function (tab) {\n    const $tab = this._getTab(tab);\n    const scrollLeft = this.$tablist.scrollLeft();\n    const tabOffset = $tab.offset().left;\n    const elemScrollOffset = tabOffset - this.$tablist.offset().left;\n    let targetScrollLeft = false;\n\n    // Is the tab hidden on the left?\n    if (elemScrollOffset < 0) {\n      targetScrollLeft = scrollLeft + elemScrollOffset - 24;\n    } else {\n      const tabWidth = $tab.outerWidth();\n      const ulWidth = this.$tablist.prop('clientWidth');\n\n      // Is it hidden to the right?\n      if (elemScrollOffset + tabWidth > ulWidth) {\n        targetScrollLeft =\n          scrollLeft + (elemScrollOffset - (ulWidth - tabWidth)) + 24;\n      }\n    }\n\n    if (targetScrollLeft !== false) {\n      this.$tablist.scrollLeft(targetScrollLeft);\n    }\n  },\n\n  updateMenuBtn: function () {\n    if (\n      Math.floor(this.$tablist.prop('scrollWidth') - 48) >\n      this.$container.prop('clientWidth')\n    ) {\n      this.$tablist.addClass('scrollable');\n      this.$menuBtn.removeClass('hidden');\n    } else {\n      this.$tablist.removeClass('scrollable');\n      this.$menuBtn.addClass('hidden');\n    }\n  },\n\n  _getTab: function (tab) {\n    if (tab instanceof jQuery) {\n      return tab;\n    }\n\n    if (tab instanceof HTMLElement) {\n      return $(tab);\n    }\n\n    if (typeof tab !== 'string') {\n      throw 'Invalid tab ID';\n    }\n\n    const $tab = this.$tabs.filter(`[data-id=\"${tab}\"]`);\n\n    if (!$tab.length) {\n      throw `Invalid tab ID: ${tab}`;\n    }\n\n    return $tab;\n  },\n\n  destroy: function () {\n    this.$container.removeData('tabs');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Tag select input\n */\nCraft.TagSelectInput = Craft.BaseElementSelectInput.extend(\n  {\n    searchTimeout: null,\n    searchMenu: null,\n\n    $container: null,\n    $elementsContainer: null,\n    $elements: null,\n    $addTagInput: null,\n    $spinner: null,\n\n    _ignoreBlur: false,\n\n    init: function (settings) {\n      // Normalize the settings\n      // ---------------------------------------------------------------------\n\n      // Are they still passing in a bunch of arguments?\n      if (!$.isPlainObject(settings)) {\n        // Loop through all of the old arguments and apply them to the settings\n        var normalizedSettings = {},\n          args = ['id', 'name', 'tagGroupId', 'sourceElementId'];\n\n        for (var i = 0; i < args.length; i++) {\n          if (typeof arguments[i] !== 'undefined') {\n            normalizedSettings[args[i]] = arguments[i];\n          } else {\n            break;\n          }\n        }\n\n        settings = normalizedSettings;\n      }\n\n      this.base($.extend({}, Craft.TagSelectInput.defaults, settings));\n\n      this.$addTagInput = this.$container.children('.add').children('.text');\n      this.$spinner = this.$addTagInput.next();\n\n      this.addListener(this.$addTagInput, 'input', () => {\n        if (this.searchTimeout) {\n          clearTimeout(this.searchTimeout);\n        }\n\n        this.searchTimeout = setTimeout(this.searchForTags.bind(this), 500);\n      });\n\n      this.addListener(this.$addTagInput, 'keydown', function (ev) {\n        if (ev.keyCode === Garnish.RETURN_KEY) {\n          ev.preventDefault();\n        }\n\n        let $option;\n\n        switch (ev.keyCode) {\n          case Garnish.RETURN_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              this.selectTag(this.searchMenu.$options.filter('.hover'));\n            }\n            return;\n          }\n\n          case Garnish.DOWN_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              let $hoverOption = this.searchMenu.$options.filter('.hover');\n              if ($hoverOption.length) {\n                let $nextOption = $hoverOption\n                  .parent()\n                  .nextAll()\n                  .find('a:not(.disabled)')\n                  .first();\n                if ($nextOption.length) {\n                  this.focusOption($nextOption);\n                }\n              } else {\n                this.focusOption(this.searchMenu.$options.eq(0));\n              }\n            }\n            return;\n          }\n\n          case Garnish.UP_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              let $hoverOption = this.searchMenu.$options.filter('.hover');\n              if ($hoverOption.length) {\n                let $prevOption = $hoverOption\n                  .parent()\n                  .prevAll()\n                  .find('a:not(.disabled)')\n                  .last();\n                if ($prevOption.length) {\n                  this.focusOption($prevOption);\n                }\n              } else {\n                this.focusOption(\n                  this.searchMenu.$options.eq(\n                    this.searchMenu.$options.length - 1\n                  )\n                );\n              }\n            }\n            return;\n          }\n        }\n      });\n\n      this.addListener(this.$addTagInput, 'focus', function () {\n        if (this.searchMenu) {\n          this.searchMenu.show();\n        }\n      });\n\n      this.addListener(this.$addTagInput, 'blur', function () {\n        if (this._ignoreBlur) {\n          this._ignoreBlur = false;\n          return;\n        }\n\n        setTimeout(() => {\n          if (this.searchMenu) {\n            this.searchMenu.hide();\n          }\n        }, 1);\n      });\n    },\n\n    focusOption: function ($option) {\n      this.searchMenu.$options.removeClass('hover');\n      $option.addClass('hover');\n      this.searchMenu.$menuList.attr(\n        'aria-activedescendant',\n        $option.attr('id')\n      );\n    },\n\n    // No \"add\" button\n    getAddElementsBtn: $.noop,\n\n    getElementSortAxis: function () {\n      return null;\n    },\n\n    searchForTags: function () {\n      if (this.searchMenu) {\n        this.killSearchMenu();\n      }\n\n      var val = this.$addTagInput.val();\n\n      if (val) {\n        this.$spinner.removeClass('hidden');\n\n        var excludeIds = [];\n\n        for (var i = 0; i < this.$elements.length; i++) {\n          var id = $(this.$elements[i]).data('id');\n\n          if (id) {\n            excludeIds.push(id);\n          }\n        }\n\n        // take allowSelfRelations into consideration too\n        if (\n          this.settings.sourceElementId &&\n          !this.settings.allowSelfRelations\n        ) {\n          excludeIds.push(this.settings.sourceElementId);\n        }\n\n        var data = {\n          search: this.$addTagInput.val(),\n          tagGroupId: this.settings.tagGroupId,\n          excludeIds: excludeIds,\n        };\n\n        Craft.sendActionRequest('POST', 'tags/search-for-tags', {data})\n          .then((response) => {\n            if (this.searchMenu) {\n              this.killSearchMenu();\n            }\n            this.$spinner.addClass('hidden');\n            var $menu = $('<div class=\"menu tagmenu\"/>').appendTo(Garnish.$bod),\n              $ul = $('<ul/>').appendTo($menu);\n\n            var $li;\n\n            for (var i = 0; i < response.data.tags.length; i++) {\n              $li = $('<li/>').appendTo($ul);\n\n              $('<a data-icon=\"tag\"/>')\n                .appendTo($li)\n                .text(response.data.tags[i].title)\n                .data('id', response.data.tags[i].id)\n                .addClass(response.data.tags[i].exclude ? 'disabled' : '');\n            }\n\n            if (!response.data.exactMatch) {\n              $li = $('<li/>').appendTo($ul);\n              $('<a data-icon=\"plus\"/>').appendTo($li).text(data.search);\n            }\n\n            $ul.find('a:not(.disabled):first').addClass('hover');\n\n            this.searchMenu = new Garnish.Menu($menu, {\n              attachToElement: this.$addTagInput,\n              onOptionSelect: this.selectTag.bind(this),\n            });\n\n            this.addListener($menu, 'mousedown', () => {\n              this._ignoreBlur = true;\n            });\n\n            this.searchMenu.show();\n          })\n          .catch(({response}) => {\n            // Just in case\n            if (this.searchMenu) {\n              this.killSearchMenu();\n            }\n\n            this.$spinner.addClass('hidden');\n          });\n      } else {\n        this.$spinner.addClass('hidden');\n      }\n    },\n\n    selectTag: function (option) {\n      var $option = $(option);\n\n      if ($option.hasClass('disabled')) {\n        return;\n      }\n\n      var id = $option.data('id');\n      var title = $option.text();\n\n      var $element = $('<div/>', {\n        class: 'element small removable',\n        'data-id': id,\n        'data-site-id': this.settings.targetSiteId,\n        'data-label': title,\n        'data-editable': '1',\n      }).appendTo(this.$elementsContainer);\n\n      var $input = $('<input/>', {\n        type: 'hidden',\n        name: this.settings.name + '[]',\n        value: id,\n      }).appendTo($element);\n\n      $('<button/>', {\n        class: 'delete icon',\n        title: Craft.t('app', 'Remove'),\n        type: 'button',\n        'aria-label': Craft.t('app', 'Remove {label}', {\n          label: title,\n        }),\n      }).appendTo($element);\n\n      var $titleContainer = $('<div/>', {\n        class: 'label',\n      }).appendTo($element);\n\n      $('<span/>', {\n        class: 'title',\n        text: title,\n      }).appendTo($titleContainer);\n\n      this.$elements = this.$elements.add($element);\n\n      this.addElements($element);\n\n      this.killSearchMenu();\n      this.$addTagInput.val('');\n      this.$addTagInput.trigger('focus');\n\n      if (!id) {\n        // We need to create the tag first\n        $element.addClass('loading disabled');\n\n        var data = {\n          groupId: this.settings.tagGroupId,\n          title: title,\n        };\n\n        Craft.sendActionRequest('POST', 'tags/create-tag', {data})\n          .then((response) => {\n            $element.attr('data-id', response.data.id);\n            $input.val(response.data.id);\n\n            $element.removeClass('loading disabled');\n          })\n          .catch(({response}) => {\n            this.removeElement($element);\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n          });\n      }\n    },\n\n    killSearchMenu: function () {\n      this.searchMenu.hide();\n      this.searchMenu.destroy();\n      this.searchMenu = null;\n    },\n  },\n  {\n    defaults: {\n      tagGroupId: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Thumb Element Index View\n */\nCraft.ThumbsElementIndexView = Craft.BaseElementIndexView.extend({\n  getElementContainer: function () {\n    return this.$container.children('ul');\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.ui = {\n  createButton: function (config) {\n    const $btn = $('<button/>', {\n      type: config.type || 'button',\n      class: 'btn',\n    });\n    if (config.id) {\n      $btn.attr('id', config.id);\n    }\n    if (config.class) {\n      $btn.addClass(config.class);\n    }\n    if (config.ariaLabel) {\n      $btn.attr('aria-label', config.ariaLabel);\n    }\n    if (config.role) {\n      $btn.attr('role', config.role);\n    }\n    if (config.html) {\n      $btn.html(config.html);\n    } else if (config.label) {\n      $btn.append($('<div class=\"label\"/>').text(config.label));\n    } else {\n      $btn.addClass('btn-empty');\n    }\n    if (config.toggle) {\n      $btn.attr('aria-expanded', 'false');\n    }\n    if (config.controls) {\n      $btn.attr('aria-controls', config.controls);\n    }\n    if (config.spinner) {\n      $btn.append($('<div class=\"spinner spinner-absolute\"/>'));\n    }\n    return $btn;\n  },\n\n  createSubmitButton: function (config) {\n    const $btn = this.createButton(\n      Object.assign({}, config, {\n        type: 'submit',\n        label: config.label || Craft.t('app', 'Submit'),\n      })\n    );\n    $btn.addClass('submit');\n    return $btn;\n  },\n\n  createTextInput: function (config) {\n    config = $.extend(\n      {\n        autocomplete: false,\n      },\n      config\n    );\n    var $input = $('<input/>', {\n      attr: {\n        class: 'text',\n        type: config.type || 'text',\n        inputmode: config.inputmode,\n        id: config.id,\n        size: config.size,\n        name: config.name,\n        value: config.value,\n        maxlength: config.maxlength,\n        autofocus: this.getAutofocusValue(config.autofocus),\n        autocomplete:\n          typeof config.autocomplete === 'boolean'\n            ? config.autocomplete\n              ? 'on'\n              : 'off'\n            : config.autocomplete,\n        disabled: this.getDisabledValue(config.disabled),\n        readonly: config.readonly,\n        title: config.title,\n        placeholder: config.placeholder,\n        step: config.step,\n        min: config.min,\n        max: config.max,\n      },\n    });\n\n    if (config.class) {\n      $input.addClass(config.class);\n    }\n    if (config.placeholder) {\n      $input.addClass('nicetext');\n    }\n    if (config.type === 'password') {\n      $input.addClass('password');\n    }\n    if (config.disabled) {\n      $input.addClass('disabled');\n    }\n    if (!config.size) {\n      $input.addClass('fullwidth');\n    }\n\n    if (config.showCharsLeft && config.maxlength) {\n      $input\n        .attr('data-show-chars-left')\n        .css(\n          'padding-' + (Craft.orientation === 'ltr' ? 'right' : 'left'),\n          7.2 * config.maxlength.toString().length + 14 + 'px'\n        );\n    }\n\n    if (config.placeholder || config.showCharsLeft) {\n      new Garnish.NiceText($input);\n    }\n\n    if (config.type === 'password') {\n      return $('<div class=\"passwordwrapper\"/>').append($input);\n    } else {\n      return $input;\n    }\n  },\n\n  createTextField: function (config) {\n    if (!config.id) {\n      config.id = 'text' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTextInput(config), config);\n  },\n\n  createCopyTextInput: function (config) {\n    let id = config.id || 'copytext' + Math.floor(Math.random() * 1000000000);\n    let buttonId = config.buttonId || `${id}-btn`;\n\n    let $container = $('<div/>', {\n      class: 'copytext',\n    });\n\n    let $input = this.createTextInput(\n      $.extend({}, config, {\n        readonly: true,\n      })\n    ).appendTo($container);\n\n    let $btn = $('<button/>', {\n      type: 'button',\n      id: buttonId,\n      class: 'btn',\n      'data-icon': 'clipboard',\n      title: Craft.t('app', 'Copy to clipboard'),\n      'aria-label': Craft.t('app', 'Copy to clipboard'),\n    }).appendTo($container);\n\n    $btn.on('click', () => {\n      $input[0].select();\n      document.execCommand('copy');\n      Craft.cp.displayNotice(Craft.t('app', 'Copied to clipboard.'));\n      $container.trigger('copy');\n      $input[0].setSelectionRange(0, 0);\n    });\n\n    return $container;\n  },\n\n  createCopyTextBtn: function (config) {\n    let id = config.id || 'copytext' + Math.floor(Math.random() * 1000000000);\n    let value = config.value;\n\n    let $btn = $('<div/>', {\n      id,\n      class: 'copytextbtn',\n      role: 'button',\n      title: Craft.t('app', 'Copy to clipboard'),\n      'aria-label': Craft.t('app', 'Copy to clipboard'),\n      tabindex: '0',\n    });\n\n    if (config.class) {\n      $btn.addClass(config.class);\n    }\n\n    let $input = $('<input/>', {\n      value,\n      readonly: true,\n      size: value.length,\n      tabindex: '-1',\n    }).appendTo($btn);\n\n    let $icon = $('<span/>', {\n      'data-icon': 'clipboard',\n      'aria-hidden': 'true',\n    }).appendTo($btn);\n\n    const copyValue = function () {\n      $input[0].select();\n      document.execCommand('copy');\n      Craft.cp.displayNotice(Craft.t('app', 'Copied to clipboard.'));\n      $btn.trigger('copy');\n      $input[0].setSelectionRange(0, 0);\n      $btn.focus();\n    };\n\n    $btn.on('click', () => {\n      copyValue();\n    });\n\n    $btn.on('keydown', (ev) => {\n      if (ev.keyCode === Garnish.SPACE_KEY) {\n        copyValue();\n        ev.preventDefault();\n      }\n    });\n\n    return $btn;\n  },\n\n  createCopyTextField: function (config) {\n    if (!config.id) {\n      config.id = 'copytext' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createCopyTextInput(config), config);\n  },\n\n  createCopyTextPrompt: function (config) {\n    let $container = $('<div/>', {\n      class: 'modal fitted',\n    });\n    let $body = $('<div/>', {\n      class: 'body',\n    }).appendTo($container);\n    this.createCopyTextField(\n      $.extend(\n        {\n          size: Math.max(Math.min(config.value.length, 50), 25),\n        },\n        config\n      )\n    ).appendTo($body);\n\n    const $label = $body.find('label');\n\n    // Provide accessible name for modal dialog\n    if ($label.length > 0 && $label.attr('id')) {\n      $container.attr('aria-labelledby', $label.attr('id'));\n    }\n\n    let modal = new Garnish.Modal($container, {\n      closeOtherModals: false,\n    });\n    $container.on('copy', () => {\n      modal.hide();\n    });\n    return $container;\n  },\n\n  createTextarea: function (config) {\n    var $textarea = $('<textarea/>', {\n      class: 'text',\n      rows: config.rows || 2,\n      cols: config.cols || 50,\n      id: config.id,\n      name: config.name,\n      maxlength: config.maxlength,\n      autofocus: config.autofocus && !Garnish.isMobileBrowser(true),\n      disabled: !!config.disabled,\n      placeholder: config.placeholder,\n      html: config.value,\n    });\n\n    if (config.showCharsLeft) {\n      $textarea.attr('data-show-chars-left', '');\n    }\n\n    if (config.class) {\n      $textarea.addClass(config.class);\n    }\n\n    if (!config.size) {\n      $textarea.addClass('fullwidth');\n    }\n\n    return $textarea;\n  },\n\n  createTextareaField: function (config) {\n    if (!config.id) {\n      config.id = 'textarea' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTextarea(config), config);\n  },\n\n  createSelect: function (config) {\n    var $container = $('<div/>', {\n      class: 'select',\n    });\n\n    if (config.class) {\n      $container.addClass(config.class);\n    }\n\n    var $select = $('<select/>', {\n      id: config.id,\n      name: config.name,\n      autofocus: config.autofocus && Garnish.isMobileBrowser(true),\n      disabled: config.disabled,\n      'data-target-prefix': config.targetPrefix,\n      'aria-labelledby': config.labelledBy,\n    }).appendTo($container);\n\n    // Normalize the options into an array\n    if ($.isPlainObject(config.options)) {\n      let options = [];\n      for (var key in config.options) {\n        if (!config.options.hasOwnProperty(key)) {\n          continue;\n        }\n        let option = config.options[key];\n        if ($.isPlainObject(option)) {\n          if (typeof option.optgroup !== 'undefined') {\n            options.push(option);\n          } else {\n            options.push({\n              label: option.label,\n              value: typeof option.value !== 'undefined' ? option.value : key,\n              disabled:\n                typeof option.disabled !== 'undefined'\n                  ? option.disabled\n                  : false,\n            });\n          }\n        } else {\n          options.push({\n            label: option,\n            value: key,\n          });\n        }\n      }\n      config.options = options;\n    }\n\n    var $optgroup = null;\n\n    for (let i = 0; i < config.options.length; i++) {\n      let option = config.options[i];\n\n      // Starting a new <optgroup>?\n      if (typeof option.optgroup !== 'undefined') {\n        $optgroup = $('<optgroup/>', {\n          label: option.label,\n        }).appendTo($select);\n      } else {\n        $('<option/>', {\n          value: option.value,\n          selected: option.value == config.value,\n          disabled:\n            typeof option.disabled !== 'undefined' ? option.disabled : false,\n          html: option.label,\n        }).appendTo($optgroup || $select);\n      }\n    }\n\n    if (config.toggle) {\n      $select.addClass('fieldtoggle');\n      new Craft.FieldToggle($select);\n    }\n\n    return $container;\n  },\n\n  createSelectField: function (config) {\n    if (!config.id) {\n      config.id = 'select' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createSelect(config), config);\n  },\n\n  createCheckbox: function (config) {\n    var id = config.id || 'checkbox' + Math.floor(Math.random() * 1000000000);\n\n    var $input = $('<input/>', {\n      type: 'checkbox',\n      value: typeof config.value !== 'undefined' ? config.value : '1',\n      id: id,\n      class: 'checkbox',\n      name: config.name,\n      checked: config.checked ? 'checked' : null,\n      autofocus: this.getAutofocusValue(config.autofocus),\n      disabled: this.getDisabledValue(config.disabled),\n      'data-target': config.toggle,\n      'data-reverse-target': config.reverseToggle,\n    });\n\n    if (config.class) {\n      $input.addClass(config.class);\n    }\n\n    if (config.toggle || config.reverseToggle) {\n      $input.addClass('fieldtoggle');\n      new Craft.FieldToggle($input);\n    }\n\n    var $label = $('<label/>', {\n      for: id,\n      html: config.label,\n    });\n\n    // Should we include a hidden input first?\n    if (\n      config.name &&\n      (config.name.length < 3 || config.name.slice(-2) !== '[]')\n    ) {\n      return $([\n        $('<input/>', {\n          type: 'hidden',\n          name: config.name,\n          value: '',\n        })[0],\n        $input[0],\n        $label[0],\n      ]);\n    } else {\n      return $([$input[0], $label[0]]);\n    }\n  },\n\n  createCheckboxField: function (config) {\n    if (!config.id) {\n      config.id = 'checkbox' + Math.floor(Math.random() * 1000000000);\n    }\n\n    var $field = $('<div class=\"field checkboxfield\"/>', {\n      id: `${config.id}-field`,\n    });\n\n    if (config.first) {\n      $field.addClass('first');\n    }\n    if (config.instructions) {\n      $field.addClass('has-instructions');\n    }\n\n    this.createCheckbox(config).appendTo($field);\n\n    if (config.instructions) {\n      $('<div class=\"instructions\"/>')\n        .text(config.instructions)\n        .appendTo($field);\n    }\n\n    return $field;\n  },\n\n  createCheckboxSelect: function (config) {\n    var $container = $('<fieldset class=\"checkbox-select\"/>');\n\n    if (config.class) {\n      $container.addClass(config.class);\n    }\n\n    var allValue, allChecked;\n\n    if (config.showAllOption) {\n      allValue = config.allValue || '*';\n      allChecked = config.values == allValue;\n\n      // Create the \"All\" checkbox\n      $('<div/>')\n        .appendTo($container)\n        .append(\n          this.createCheckbox({\n            id: config.id,\n            class: 'all',\n            label: '<b>' + (config.allLabel || Craft.t('app', 'All')) + '</b>',\n            name: config.name,\n            value: allValue,\n            checked: allChecked,\n            autofocus: config.autofocus,\n          })\n        );\n    } else {\n      allChecked = false;\n    }\n\n    // Create the actual options\n    for (var i = 0; i < config.options.length; i++) {\n      var option = config.options[i];\n\n      if (option.value == allValue) {\n        continue;\n      }\n\n      $('<div/>')\n        .appendTo($container)\n        .append(\n          this.createCheckbox({\n            label: option.label,\n            name: config.name ? config.name + '[]' : null,\n            value: option.value,\n            checked: allChecked || (config.values || []).includes(option.value),\n            disabled: allChecked,\n          })\n        );\n    }\n\n    new Garnish.CheckboxSelect($container);\n\n    return $container;\n  },\n\n  createCheckboxSelectField: function (config) {\n    config.fieldset = true;\n    if (!config.id) {\n      config.id = 'checkboxselect' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createCheckboxSelect(config), config);\n  },\n\n  createLightswitch: function (config) {\n    var value = config.value || '1';\n    var indeterminateValue = config.indeterminateValue || '-';\n\n    var $container = $('<button/>', {\n      type: 'button',\n      class: 'lightswitch',\n      'data-value': value,\n      'data-indeterminate-value': indeterminateValue,\n      id: config.id,\n      role: 'switch',\n      'aria-checked': config.on\n        ? 'true'\n        : config.indeterminate\n        ? 'mixed'\n        : 'false',\n      'aria-labelledby': config.labelId,\n      'data-target': config.toggle,\n      'data-reverse-target': config.reverseToggle,\n    });\n\n    if (config.on) {\n      $container.addClass('on');\n    } else if (config.indeterminate) {\n      $container.addClass('indeterminate');\n    }\n\n    if (config.small) {\n      $container.addClass('small');\n    }\n\n    if (config.disabled) {\n      $container.addClass('disabled');\n    }\n\n    $(\n      '<div class=\"lightswitch-container\">' +\n        '<div class=\"handle\"></div>' +\n        '</div>'\n    ).appendTo($container);\n\n    if (config.name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: config.name,\n        value: config.on\n          ? value\n          : config.indeterminate\n          ? indeterminateValue\n          : '',\n        disabled: config.disabled,\n      }).appendTo($container);\n    }\n\n    if (config.toggle || config.reverseToggle) {\n      $container.addClass('fieldtoggle');\n      new Craft.FieldToggle($container);\n    }\n\n    new Craft.LightSwitch($container, {\n      onChange: config.onChange || $.noop,\n    });\n\n    return $container;\n  },\n\n  createLightswitchField: function (config) {\n    if (!config.id) {\n      config.id = 'lightswitch' + Math.floor(Math.random() * 1000000000);\n    }\n    if (!config.labelId) {\n      config.labelId = `${config.id}-label`;\n    }\n    return this.createField(this.createLightswitch(config), config).addClass(\n      'lightswitch-field'\n    );\n  },\n\n  createColorInput: function (config) {\n    const id = config.id || 'color' + Math.floor(Math.random() * 1000000000);\n    const containerId = config.containerId || id + '-container';\n    const name = config.name || null;\n    const value = config.value || null;\n    const small = config.small || false;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      id: containerId,\n      class: 'flex color-container',\n    });\n\n    const $colorPreviewContainer = $('<div/>', {\n      class: 'color static' + (small ? ' small' : ''),\n    }).appendTo($container);\n\n    const $colorPreview = $('<div/>', {\n      class: 'color-preview',\n      style: config.value ? {backgroundColor: config.value} : null,\n    }).appendTo($colorPreviewContainer);\n\n    const $inputContainer = $('<div/>', {\n      class: 'color-input-container',\n    })\n      .append(\n        $('<div/>', {\n          class: 'color-hex-indicator light code',\n          'aria-hidden': 'true',\n          text: '#',\n        })\n      )\n      .appendTo($container);\n\n    const $input = this.createTextInput({\n      id: id,\n      name: name,\n      value: Craft.ltrim(value, '#'),\n      size: 10,\n      class: 'color-input',\n      autofocus: autofocus,\n      disabled: disabled,\n      'aria-label': Craft.t('app', 'Color hex value'),\n    }).appendTo($inputContainer);\n\n    new Craft.ColorInput($container);\n    return $container;\n  },\n\n  createColorField: function (config) {\n    config.fieldset = true;\n    o;\n    if (!config.id) {\n      config.id = 'color' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createColorInput(config), config);\n  },\n\n  createDateInput: function (config) {\n    const isMobile = Garnish.isMobileBrowser();\n    const id =\n      (config.id || 'date' + Math.floor(Math.random() * 1000000000)) + '-date';\n    const name = config.name || null;\n    const inputName = name ? name + '[date]' : null;\n    const value =\n      config.value && typeof config.value.getMonth === 'function'\n        ? config.value\n        : null;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      class: 'datewrapper',\n    });\n\n    const $input = this.createTextInput({\n      id: id,\n      type: isMobile ? 'date' : 'text',\n      class: isMobile && !value ? 'empty-value' : false,\n      name: inputName,\n      value: value\n        ? isMobile\n          ? value.toISOString().split('T')[0]\n          : Craft.formatDate(value)\n        : '',\n      placeholder: ' ',\n      autocomplete: false,\n      autofocus: autofocus,\n      disabled: disabled,\n    }).appendTo($container);\n\n    $('<div data-icon=\"date\"></div>').appendTo($container);\n\n    if (name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: name + '[timezone]',\n        val: Craft.timezone,\n      }).appendTo($container);\n    }\n\n    if (isMobile) {\n      $input.datetimeinput();\n    } else {\n      $input.datepicker(\n        $.extend(\n          {\n            defaultDate: value || new Date(),\n          },\n          Craft.datepickerOptions\n        )\n      );\n    }\n\n    if (config.hasOuterContainer) {\n      return $container;\n    }\n\n    return $('<div class=\"datetimewrapper\"/>').append($container).datetime();\n  },\n\n  createDateField: function (config) {\n    if (!config.id) {\n      config.id = 'date' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createDateInput(config), config);\n  },\n\n  createDateRangePicker: function (config) {\n    var now = new Date();\n    var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n    config = $.extend(\n      {\n        class: '',\n        options: [\n          'today',\n          'thisWeek',\n          'thisMonth',\n          'thisYear',\n          'past7Days',\n          'past30Days',\n          'past90Days',\n          'pastYear',\n        ],\n        onChange: $.noop,\n        selected: null,\n        startDate: null,\n        endDate: null,\n      },\n      config\n    );\n\n    var $menu = $('<div/>', {class: 'menu'});\n    var $ul = $('<ul/>', {class: 'padded'}).appendTo($menu);\n    var $allOption = $('<a/>')\n      .addClass('sel')\n      .text(Craft.t('app', 'All'))\n      .data('handle', 'all');\n\n    $('<li/>').append($allOption).appendTo($ul);\n\n    var option;\n    var selectedOption;\n    for (var i = 0; i < config.options.length; i++) {\n      var handle = config.options[i];\n      switch (handle) {\n        case 'today':\n          option = {\n            label: Craft.t('app', 'Today'),\n            startDate: today,\n            endDate: today,\n          };\n          break;\n        case 'thisWeek':\n          var firstDayOffset = now.getDay() - Craft.datepickerOptions.firstDay;\n          if (firstDayOffset < 0) {\n            firstDayOffset += 7;\n          }\n          option = {\n            label: Craft.t('app', 'This week'),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - firstDayOffset\n            ),\n            endDate: today,\n          };\n          break;\n        case 'thisMonth':\n          option = {\n            label: Craft.t('app', 'This month'),\n            startDate: new Date(now.getFullYear(), now.getMonth()),\n            endDate: today,\n          };\n          break;\n        case 'thisYear':\n          option = {\n            label: Craft.t('app', 'This year'),\n            startDate: new Date(now.getFullYear(), 0),\n            endDate: today,\n          };\n          break;\n        case 'past7Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 7}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 7\n            ),\n            endDate: today,\n          };\n          break;\n        case 'past30Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 30}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 30\n            ),\n            endDate: today,\n          };\n          break;\n        case 'past90Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 90}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 90\n            ),\n            endDate: today,\n          };\n          break;\n        case 'pastYear':\n          option = {\n            label: Craft.t('app', 'Past year'),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 365\n            ),\n            endDate: today,\n          };\n          break;\n      }\n\n      var $li = $('<li/>');\n      var $a = $('<a/>', {text: option.label})\n        .data('handle', handle)\n        .data('startDate', option.startDate)\n        .data('endDate', option.endDate)\n        .data('startTime', option.startDate ? option.startDate.getTime() : null)\n        .data('endTime', option.endDate ? option.endDate.getTime() : null);\n\n      if (config.selected && handle == config.selected) {\n        selectedOption = $a[0];\n      }\n\n      $li.append($a);\n      $li.appendTo($ul);\n    }\n\n    $('<hr/>').appendTo($menu);\n\n    var $flex = $('<div/>', {class: 'flex flex-nowrap padded'}).appendTo($menu);\n    var $startDate = this.createDateField({label: Craft.t('app', 'From')})\n      .appendTo($flex)\n      .find('input');\n    var $endDate = this.createDateField({label: Craft.t('app', 'To')})\n      .appendTo($flex)\n      .find('input');\n\n    // prevent ESC keypresses in the date inputs from closing the menu\n    var $dateInputs = $startDate.add($endDate);\n    $dateInputs.on('keyup', function (ev) {\n      if (\n        ev.keyCode === Garnish.ESC_KEY &&\n        $(this).data('datepicker') &&\n        $(this).data('datepicker').dpDiv.is(':visible')\n      ) {\n        ev.stopPropagation();\n      }\n    });\n\n    // prevent clicks in the datepicker divs from closing the menu\n    if ($startDate.data('datepicker')) {\n      $startDate.data('datepicker').dpDiv.on('mousedown', function (ev) {\n        ev.stopPropagation();\n      });\n    }\n    if ($endDate.data('datepicker')) {\n      $endDate.data('datepicker').dpDiv.on('mousedown', function (ev) {\n        ev.stopPropagation();\n      });\n    }\n\n    var menu = new Garnish.Menu($menu, {\n      onOptionSelect: function (option) {\n        var $option = $(option);\n        $btn.text($option.text());\n        menu.setPositionRelativeToAnchor();\n        $menu.find('.sel').removeClass('sel');\n        $option.addClass('sel');\n\n        // Update the start/end dates\n        $startDate.datepicker('setDate', $option.data('startDate'));\n        $endDate.datepicker('setDate', $option.data('endDate'));\n\n        config.onChange(\n          $option.data('startDate') || null,\n          $option.data('endDate') || null,\n          $option.data('handle')\n        );\n      },\n    });\n\n    $dateInputs.on('change', function () {\n      // Do the start & end dates match one of our options?\n      let startDate = $startDate.datepicker('getDate');\n      let endDate = $endDate.datepicker('getDate');\n      let startTime = startDate ? startDate.getTime() : null;\n      let endTime = endDate ? endDate.getTime() : null;\n\n      let $options = $ul.find('a');\n      let $option;\n      let foundOption = false;\n\n      for (let i = 0; i < $options.length; i++) {\n        $option = $options.eq(i);\n        if (\n          startTime === ($option.data('startTime') || null) &&\n          endTime === ($option.data('endTime') || null)\n        ) {\n          menu.selectOption($option[0]);\n          foundOption = true;\n          config.onChange(null, null, $option.data('handle'));\n          break;\n        }\n      }\n\n      if (!foundOption) {\n        $menu.find('.sel').removeClass('sel');\n        $flex.addClass('sel');\n\n        if (!startTime && !endTime) {\n          $btn.text(Craft.t('app', 'All'));\n        } else if (startTime && endTime) {\n          $btn.text($startDate.val() + ' - ' + $endDate.val());\n        } else if (startTime) {\n          $btn.text(Craft.t('app', 'From {date}', {date: $startDate.val()}));\n        } else {\n          $btn.text(Craft.t('app', 'To {date}', {date: $endDate.val()}));\n        }\n        menu.setPositionRelativeToAnchor();\n\n        config.onChange(startDate, endDate, 'custom');\n      }\n    });\n\n    menu.on('hide', function () {\n      $startDate.datepicker('hide');\n      $endDate.datepicker('hide');\n    });\n\n    let btnClasses = 'btn menubtn';\n    if (config.class) {\n      btnClasses = btnClasses + ' ' + config.class;\n    }\n\n    let $btn = $('<button/>', {\n      type: 'button',\n      class: btnClasses,\n      'data-icon': 'date',\n      text: Craft.t('app', 'All'),\n    });\n\n    new Garnish.MenuBtn($btn, menu);\n\n    if (selectedOption) {\n      menu.selectOption(selectedOption);\n    }\n\n    if (config.startDate) {\n      $startDate.datepicker('setDate', config.startDate);\n    }\n\n    if (config.endDate) {\n      $endDate.datepicker('setDate', config.endDate);\n    }\n\n    if (config.startDate || config.endDate) {\n      $dateInputs.trigger('change');\n    }\n\n    return $btn;\n  },\n\n  createTimeInput: function (config) {\n    const isMobile = Garnish.isMobileBrowser();\n    const id =\n      (config.id || 'time' + Math.floor(Math.random() * 1000000000)) + '-time';\n    const name = config.name || null;\n    const inputName = name ? name + '[time]' : null;\n    const value =\n      config.value && typeof config.value.getMonth === 'function'\n        ? config.value\n        : null;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      class: 'timewrapper',\n    });\n\n    const $input = this.createTextInput({\n      id: id,\n      type: isMobile ? 'time' : 'text',\n      class: isMobile && !value ? 'empty-value' : false,\n      name: inputName,\n      placeholder: ' ',\n      autocomplete: false,\n      autofocus: autofocus,\n      disabled: disabled,\n    }).appendTo($container);\n\n    $('<div data-icon=\"time\"></div>').appendTo($container);\n\n    if (name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: name + '[timezone]',\n        val: Craft.timezone,\n      }).appendTo($container);\n    }\n\n    if (isMobile) {\n      if (value) {\n        $input.val(value.toISOString().split('T')[1]);\n      }\n      $input.datetimeinput();\n    } else {\n      $input.timepicker(Craft.timepickerOptions);\n      if (value) {\n        $input.timepicker(\n          'setTime',\n          value.getHours() * 3600 + value.getMinutes() * 60 + value.getSeconds()\n        );\n      }\n    }\n\n    if (config.hasOuterContainer) {\n      return $container;\n    }\n\n    return $('<div class=\"datetimewrapper\"/>').append($container).datetime();\n  },\n\n  createTimeField: function (config) {\n    if (!config.id) {\n      config.id = 'time' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTimeInput(config), config);\n  },\n\n  createField: function (input, config) {\n    const label =\n      config.label && config.label !== '__blank__' ? config.label : null;\n\n    const $field = $(config.fieldset ? '<fieldset/>' : '<div/>', {\n      class: 'field',\n      id: config.fieldId || (config.id ? config.id + '-field' : null),\n    });\n\n    if (config.first) {\n      $field.addClass('first');\n    }\n\n    if (config.fieldClass) {\n      $field.addClass(config.fieldClass);\n    }\n\n    if (label && config.fieldset) {\n      $('<legend/>', {\n        text: label,\n        class: 'visually-hidden',\n        'data-label': label,\n      }).appendTo($field);\n    }\n\n    if (label) {\n      const $heading = $('<div class=\"heading\"/>').appendTo($field);\n\n      $(config.fieldset ? '<legend/>' : '<label/>', {\n        id:\n          config.labelId ||\n          (config.id\n            ? `${config.id}-${config.fieldset ? 'legend' : 'label'}`\n            : null),\n        class: config.required ? 'required' : null,\n        for: (!config.fieldset && config.id) || null,\n        text: label,\n      }).appendTo($heading);\n    }\n\n    if (config.instructions) {\n      $('<div class=\"instructions\"/>')\n        .text(config.instructions)\n        .appendTo($field);\n    }\n\n    $('<div class=\"input\"/>').append(input).appendTo($field);\n\n    if (config.tip) {\n      const $tip = $('<p class=\"notice has-icon\"/>');\n      $('<span class=\"icon\" aria-hidden=\"true\"/>').appendTo($tip);\n      $('<span class=\"visually-hidden\"/>')\n        .text(Craft.t('app', 'Tip') + ': ')\n        .appendTo($tip);\n      $('<span/>').text(config.tip).appendTo($tip);\n      $tip.appendTo($field);\n    }\n\n    if (config.warning) {\n      const $warning = $('<p class=\"warning has-icon\"/>');\n      $('<span class=\"icon\" aria-hidden=\"true\"/>').appendTo($warning);\n      $('<span class=\"visually-hidden\"/>')\n        .text(Craft.t('app', 'Warning') + ': ')\n        .appendTo($warning);\n      $('<span/>').text(config.warning).appendTo($warning);\n      $warning.appendTo($field);\n    }\n\n    if (config.errors) {\n      this.addErrorsToField($field, config.errors);\n    }\n\n    return $field;\n  },\n\n  createErrorList: function (errors) {\n    var $list = $('<ul class=\"errors\"/>');\n\n    if (errors) {\n      this.addErrorsToList($list, errors);\n    }\n\n    return $list;\n  },\n\n  addErrorsToList: function ($list, errors) {\n    for (var i = 0; i < errors.length; i++) {\n      $('<li/>').text(errors[i]).appendTo($list);\n    }\n  },\n\n  addErrorsToField: function ($field, errors) {\n    if (!errors) {\n      return;\n    }\n\n    $field.addClass('has-errors');\n    $field.children('.input').addClass('errors');\n\n    var $errors = $field.children('ul.errors');\n\n    if (!$errors.length) {\n      $errors = this.createErrorList().appendTo($field);\n    }\n\n    this.addErrorsToList($errors, errors);\n  },\n\n  clearErrorsFromField: function ($field) {\n    $field.removeClass('has-errors');\n    $field.children('.input').removeClass('errors');\n    $field.children('ul.errors').remove();\n  },\n\n  getAutofocusValue: function (autofocus) {\n    return autofocus && !Garnish.isMobileBrowser(true) ? 'autofocus' : null;\n  },\n\n  getDisabledValue: function (disabled) {\n    return disabled ? 'disabled' : null;\n  },\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.Uploader = Garnish.Base.extend(\n  {\n    uploader: null,\n    allowedKinds: null,\n    $element: null,\n    settings: null,\n    _rejectedFiles: {},\n    _extensionList: null,\n    _totalFileCounter: 0,\n    _validFileCounter: 0,\n\n    init: function ($element, settings) {\n      this._rejectedFiles = {size: [], type: [], limit: []};\n      this.$element = $element;\n      this.allowedKinds = null;\n      this._extensionList = null;\n      this._totalFileCounter = 0;\n      this._validFileCounter = 0;\n\n      settings = $.extend({}, Craft.Uploader.defaults, settings);\n\n      var events = settings.events;\n      delete settings.events;\n\n      if (settings.allowedKinds && settings.allowedKinds.length) {\n        if (typeof settings.allowedKinds === 'string') {\n          settings.allowedKinds = [settings.allowedKinds];\n        }\n\n        this.allowedKinds = settings.allowedKinds;\n        delete settings.allowedKinds;\n      }\n\n      settings.autoUpload = false;\n\n      this.uploader = this.$element.fileupload(settings);\n      for (var event in events) {\n        if (!events.hasOwnProperty(event)) {\n          continue;\n        }\n\n        this.uploader.on(event, events[event]);\n      }\n\n      this.settings = settings;\n\n      this.uploader.on('fileuploadadd', this.onFileAdd.bind(this));\n    },\n\n    /**\n     * Set uploader parameters.\n     */\n    setParams: function (paramObject) {\n      // If CSRF protection isn't enabled, these won't be defined.\n      if (\n        typeof Craft.csrfTokenName !== 'undefined' &&\n        typeof Craft.csrfTokenValue !== 'undefined'\n      ) {\n        // Add the CSRF token\n        paramObject[Craft.csrfTokenName] = Craft.csrfTokenValue;\n      }\n\n      this.uploader.fileupload('option', {formData: paramObject});\n    },\n\n    /**\n     * Get the number of uploads in progress.\n     */\n    getInProgress: function () {\n      return this.uploader.fileupload('active');\n    },\n\n    /**\n     * Return true, if this is the last upload.\n     */\n    isLastUpload: function () {\n      // Processing the last file or not processing at all.\n      return this.getInProgress() < 2;\n    },\n\n    /**\n     * Called on file add.\n     */\n    onFileAdd: function (e, data) {\n      e.stopPropagation();\n\n      var validateExtension = false;\n\n      if (this.allowedKinds) {\n        if (!this._extensionList) {\n          this._createExtensionList();\n        }\n\n        validateExtension = true;\n      }\n\n      // Make sure that file API is there before relying on it\n      data.process().done(() => {\n        var file = data.files[0];\n        var pass = true;\n        if (validateExtension) {\n          var matches = file.name.match(/\\.([a-z0-4_]+)$/i);\n          var fileExtension = matches[1];\n          if (\n            $.inArray(fileExtension.toLowerCase(), this._extensionList) === -1\n          ) {\n            pass = false;\n            this._rejectedFiles.type.push('“' + file.name + '”');\n          }\n        }\n\n        if (file.size > this.settings.maxFileSize) {\n          this._rejectedFiles.size.push('“' + file.name + '”');\n          pass = false;\n        }\n\n        // If the validation has passed for this file up to now, check if we're not hitting any limits\n        if (\n          pass &&\n          typeof this.settings.canAddMoreFiles === 'function' &&\n          !this.settings.canAddMoreFiles(this._validFileCounter)\n        ) {\n          this._rejectedFiles.limit.push('“' + file.name + '”');\n          pass = false;\n        }\n\n        if (pass) {\n          this._validFileCounter++;\n          data.submit();\n        }\n\n        if (++this._totalFileCounter === data.originalFiles.length) {\n          this._totalFileCounter = 0;\n          this._validFileCounter = 0;\n          this.processErrorMessages();\n        }\n      });\n\n      return true;\n    },\n\n    /**\n     * Process error messages.\n     */\n    processErrorMessages: function () {\n      var str;\n\n      if (this._rejectedFiles.type.length) {\n        if (this._rejectedFiles.type.length === 1) {\n          str =\n            'The file {files} could not be uploaded. The allowed file kinds are: {kinds}.';\n        } else {\n          str =\n            'The files {files} could not be uploaded. The allowed file kinds are: {kinds}.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.type.join(', '),\n          kinds: this.allowedKinds.join(', '),\n        });\n        this._rejectedFiles.type = [];\n        Craft.cp.displayError(str);\n      }\n\n      if (this._rejectedFiles.size.length) {\n        if (this._rejectedFiles.size.length === 1) {\n          str =\n            'The file {files} could not be uploaded, because it exceeds the maximum upload size of {size}.';\n        } else {\n          str =\n            'The files {files} could not be uploaded, because they exceeded the maximum upload size of {size}.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.size.join(', '),\n          size: this.humanFileSize(Craft.maxUploadSize),\n        });\n        this._rejectedFiles.size = [];\n        Craft.cp.displayError(str);\n      }\n\n      if (this._rejectedFiles.limit.length) {\n        if (this._rejectedFiles.limit.length === 1) {\n          str =\n            'The file {files} could not be uploaded, because the field limit has been reached.';\n        } else {\n          str =\n            'The files {files} could not be uploaded, because the field limit has been reached.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.limit.join(', '),\n        });\n        this._rejectedFiles.limit = [];\n        Craft.cp.displayError(str);\n      }\n    },\n\n    humanFileSize: function (bytes) {\n      var threshold = 1024;\n\n      if (bytes < threshold) {\n        return bytes + ' B';\n      }\n\n      var units = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n\n      var u = -1;\n\n      do {\n        bytes = bytes / threshold;\n        ++u;\n      } while (bytes >= threshold);\n\n      return bytes.toFixed(1) + ' ' + units[u];\n    },\n\n    _createExtensionList: function () {\n      this._extensionList = [];\n\n      for (var i = 0; i < this.allowedKinds.length; i++) {\n        var allowedKind = this.allowedKinds[i];\n\n        if (typeof Craft.fileKinds[allowedKind] !== 'undefined') {\n          for (\n            var j = 0;\n            j < Craft.fileKinds[allowedKind].extensions.length;\n            j++\n          ) {\n            var ext = Craft.fileKinds[allowedKind].extensions[j];\n            this._extensionList.push(ext);\n          }\n        }\n      }\n    },\n\n    destroy: function () {\n      this.$element.fileupload('destroy');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      dropZone: null,\n      pasteZone: null,\n      fileInput: null,\n      sequentialUploads: true,\n      maxFileSize: Craft.maxUploadSize,\n      allowedKinds: null,\n      events: {},\n      canAddMoreFiles: null,\n      headers: {Accept: 'application/json;q=0.9,*/*;q=0.8'},\n      paramName: 'assets-upload',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.UriFormatGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    sourceVal = sourceVal.replace(/<(.*?)>/g, '');\n\n    // Make it lowercase\n    sourceVal = sourceVal.toLowerCase();\n\n    // Convert extended ASCII characters to basic ASCII\n    sourceVal = Craft.asciiString(sourceVal);\n\n    // Handle must start with a letter and end with a letter/number\n    sourceVal = sourceVal.replace(/^[^a-z]+/, '');\n    sourceVal = sourceVal.replace(/[^a-z0-9]+$/, '');\n\n    // Get the \"words\"\n    var words = Craft.filterArray(sourceVal.split(/[^a-z0-9]+/));\n\n    var uriFormat = words.join(Craft.slugWordSeparator);\n\n    if (uriFormat && this.settings.suffix) {\n      uriFormat += this.settings.suffix;\n    }\n\n    return uriFormat;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * User index class\n */\nCraft.UserIndex = Craft.BaseElementIndex.extend({\n  init: function (elementType, $container, settings) {\n    this.on('selectSource', this.updateUrl.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific group in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultSourceSlug !== 'undefined'\n    ) {\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = $(this.$sources[i]);\n        if ($source.data('slug') === defaultSourceSlug) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateUrl: function () {\n    if (this.settings.context === 'index') {\n      let uri = 'users';\n      const slug = this.$source.data('slug');\n      if (slug) {\n        uri += `/${slug}`;\n      }\n      Craft.setPath(uri);\n    }\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\User', Craft.UserIndex);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Volume folder selector modal class\n */\nCraft.VolumeFolderSelectorModal = Craft.BaseElementSelectorModal.extend(\n  {\n    init: function (settings) {\n      settings = Object.assign(\n        {},\n        Craft.VolumeFolderSelectorModal.defaults,\n        settings,\n        {\n          showSiteMenu: false,\n        }\n      );\n      settings.indexSettings.disabledFolderIds = settings.disabledFolderIds;\n      this.base('craft\\\\elements\\\\Asset', settings);\n    },\n\n    getElementIndexParams: function () {\n      return Object.assign({}, this.base(), {\n        foldersOnly: true,\n      });\n    },\n\n    hasSelection: function () {\n      return (\n        this.base() ||\n        (this.elementIndex &&\n          this.elementIndex.sourcePath.length &&\n          typeof this.elementIndex.sourcePath[\n            this.elementIndex.sourcePath.length - 1\n          ].folderId !== 'undefined' &&\n          !this.settings.disabledFolderIds.includes(\n            this.elementIndex.sourcePath[\n              this.elementIndex.sourcePath.length - 1\n            ].folderId\n          ))\n      );\n    },\n\n    getElementInfo: function ($selectedElements) {\n      return [\n        {\n          folderId: $selectedElements.length\n            ? parseInt(\n                $selectedElements.find('.element:first').data('folder-id')\n              )\n            : this.elementIndex.sourcePath[\n                this.elementIndex.sourcePath.length - 1\n              ].folderId,\n        },\n      ];\n    },\n\n    getIndexSettings: function () {\n      return Object.assign(this.base(), {\n        foldersOnly: true,\n        canSelectElement: ($element) => {\n          const folderId = $element.find('.element:first').data('folder-id');\n          return (\n            folderId && !this.settings.disabledFolderIds.includes(folderId)\n          );\n        },\n      });\n    },\n  },\n  {\n    defaults: {\n      disabledFolderIds: [],\n      indexSettings: {},\n    },\n  }\n);\n","// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = require(\"!!../../../../../../node_modules/mini-css-extract-plugin/dist/loader.js??ruleSet[1].rules[3].use[1]!../../../../../../node_modules/css-loader/dist/cjs.js!../../../../../../node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!../../../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./charts.scss\");\nif(content.__esModule) content = content.default;\nif(typeof content === 'string') content = [[module.id, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = require(\"!../../../../../../node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"3790022a\", content, true, {});","// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = require(\"!!../../../../../../node_modules/mini-css-extract-plugin/dist/loader.js??ruleSet[1].rules[3].use[1]!../../../../../../node_modules/css-loader/dist/cjs.js!../../../../../../node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!../../../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./craft.scss\");\nif(content.__esModule) content = content.default;\nif(typeof content === 'string') content = [[module.id, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = require(\"!../../../../../../node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"80058a3c\", content, true, {});","/**\n * Translates the list format produced by css-loader into something\n * easier to manipulate.\n */\nexport default function listToStyles (parentId, list) {\n  var styles = []\n  var newStyles = {}\n  for (var i = 0; i < list.length; i++) {\n    var item = list[i]\n    var id = item[0]\n    var css = item[1]\n    var media = item[2]\n    var sourceMap = item[3]\n    var part = {\n      id: parentId + ':' + i,\n      css: css,\n      media: media,\n      sourceMap: sourceMap\n    }\n    if (!newStyles[id]) {\n      styles.push(newStyles[id] = { id: id, parts: [part] })\n    } else {\n      newStyles[id].parts.push(part)\n    }\n  }\n  return styles\n}\n","/*\n  MIT License http://www.opensource.org/licenses/mit-license.php\n  Author Tobias Koppers @sokra\n  Modified by Evan You @yyx990803\n*/\n\nimport listToStyles from './listToStyles'\n\nvar hasDocument = typeof document !== 'undefined'\n\nif (typeof DEBUG !== 'undefined' && DEBUG) {\n  if (!hasDocument) {\n    throw new Error(\n    'vue-style-loader cannot be used in a non-browser environment. ' +\n    \"Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.\"\n  ) }\n}\n\n/*\ntype StyleObject = {\n  id: number;\n  parts: Array<StyleObjectPart>\n}\n\ntype StyleObjectPart = {\n  css: string;\n  media: string;\n  sourceMap: ?string\n}\n*/\n\nvar stylesInDom = {/*\n  [id: number]: {\n    id: number,\n    refs: number,\n    parts: Array<(obj?: StyleObjectPart) => void>\n  }\n*/}\n\nvar head = hasDocument && (document.head || document.getElementsByTagName('head')[0])\nvar singletonElement = null\nvar singletonCounter = 0\nvar isProduction = false\nvar noop = function () {}\nvar options = null\nvar ssrIdKey = 'data-vue-ssr-id'\n\n// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>\n// tags it will allow on a page\nvar isOldIE = typeof navigator !== 'undefined' && /msie [6-9]\\b/.test(navigator.userAgent.toLowerCase())\n\nexport default function addStylesClient (parentId, list, _isProduction, _options) {\n  isProduction = _isProduction\n\n  options = _options || {}\n\n  var styles = listToStyles(parentId, list)\n  addStylesToDom(styles)\n\n  return function update (newList) {\n    var mayRemove = []\n    for (var i = 0; i < styles.length; i++) {\n      var item = styles[i]\n      var domStyle = stylesInDom[item.id]\n      domStyle.refs--\n      mayRemove.push(domStyle)\n    }\n    if (newList) {\n      styles = listToStyles(parentId, newList)\n      addStylesToDom(styles)\n    } else {\n      styles = []\n    }\n    for (var i = 0; i < mayRemove.length; i++) {\n      var domStyle = mayRemove[i]\n      if (domStyle.refs === 0) {\n        for (var j = 0; j < domStyle.parts.length; j++) {\n          domStyle.parts[j]()\n        }\n        delete stylesInDom[domStyle.id]\n      }\n    }\n  }\n}\n\nfunction addStylesToDom (styles /* Array<StyleObject> */) {\n  for (var i = 0; i < styles.length; i++) {\n    var item = styles[i]\n    var domStyle = stylesInDom[item.id]\n    if (domStyle) {\n      domStyle.refs++\n      for (var j = 0; j < domStyle.parts.length; j++) {\n        domStyle.parts[j](item.parts[j])\n      }\n      for (; j < item.parts.length; j++) {\n        domStyle.parts.push(addStyle(item.parts[j]))\n      }\n      if (domStyle.parts.length > item.parts.length) {\n        domStyle.parts.length = item.parts.length\n      }\n    } else {\n      var parts = []\n      for (var j = 0; j < item.parts.length; j++) {\n        parts.push(addStyle(item.parts[j]))\n      }\n      stylesInDom[item.id] = { id: item.id, refs: 1, parts: parts }\n    }\n  }\n}\n\nfunction createStyleElement () {\n  var styleElement = document.createElement('style')\n  styleElement.type = 'text/css'\n  head.appendChild(styleElement)\n  return styleElement\n}\n\nfunction addStyle (obj /* StyleObjectPart */) {\n  var update, remove\n  var styleElement = document.querySelector('style[' + ssrIdKey + '~=\"' + obj.id + '\"]')\n\n  if (styleElement) {\n    if (isProduction) {\n      // has SSR styles and in production mode.\n      // simply do nothing.\n      return noop\n    } else {\n      // has SSR styles but in dev mode.\n      // for some reason Chrome can't handle source map in server-rendered\n      // style tags - source maps in <style> only works if the style tag is\n      // created and inserted dynamically. So we remove the server rendered\n      // styles and inject new ones.\n      styleElement.parentNode.removeChild(styleElement)\n    }\n  }\n\n  if (isOldIE) {\n    // use singleton mode for IE9.\n    var styleIndex = singletonCounter++\n    styleElement = singletonElement || (singletonElement = createStyleElement())\n    update = applyToSingletonTag.bind(null, styleElement, styleIndex, false)\n    remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true)\n  } else {\n    // use multi-style-tag mode in all other cases\n    styleElement = createStyleElement()\n    update = applyToTag.bind(null, styleElement)\n    remove = function () {\n      styleElement.parentNode.removeChild(styleElement)\n    }\n  }\n\n  update(obj)\n\n  return function updateStyle (newObj /* StyleObjectPart */) {\n    if (newObj) {\n      if (newObj.css === obj.css &&\n          newObj.media === obj.media &&\n          newObj.sourceMap === obj.sourceMap) {\n        return\n      }\n      update(obj = newObj)\n    } else {\n      remove()\n    }\n  }\n}\n\nvar replaceText = (function () {\n  var textStore = []\n\n  return function (index, replacement) {\n    textStore[index] = replacement\n    return textStore.filter(Boolean).join('\\n')\n  }\n})()\n\nfunction applyToSingletonTag (styleElement, index, remove, obj) {\n  var css = remove ? '' : obj.css\n\n  if (styleElement.styleSheet) {\n    styleElement.styleSheet.cssText = replaceText(index, css)\n  } else {\n    var cssNode = document.createTextNode(css)\n    var childNodes = styleElement.childNodes\n    if (childNodes[index]) styleElement.removeChild(childNodes[index])\n    if (childNodes.length) {\n      styleElement.insertBefore(cssNode, childNodes[index])\n    } else {\n      styleElement.appendChild(cssNode)\n    }\n  }\n}\n\nfunction applyToTag (styleElement, obj) {\n  var css = obj.css\n  var media = obj.media\n  var sourceMap = obj.sourceMap\n\n  if (media) {\n    styleElement.setAttribute('media', media)\n  }\n  if (options.ssrId) {\n    styleElement.setAttribute(ssrIdKey, obj.id)\n  }\n\n  if (sourceMap) {\n    // https://developer.chrome.com/devtools/docs/javascript-debugging\n    // this makes source maps inside style tags work properly in Chrome\n    css += '\\n/*# sourceURL=' + sourceMap.sources[0] + ' */'\n    // http://stackoverflow.com/a/26603875\n    css += '\\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */'\n  }\n\n  if (styleElement.styleSheet) {\n    styleElement.styleSheet.cssText = css\n  } else {\n    while (styleElement.firstChild) {\n      styleElement.removeChild(styleElement.firstChild)\n    }\n    styleElement.appendChild(document.createTextNode(css))\n  }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = function(module) {\n\tvar getter = module && module.__esModule ?\n\t\tfunction() { return module['default']; } :\n\t\tfunction() { return module; };\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }","var __WEBPACK_NAMESPACE_OBJECT__ = jQuery;","/** global: Craft */\n/** global: Garnish */\nimport $ from 'jquery';\n\n/**\n * CP class\n */\nCraft.CP = Garnish.Base.extend(\n  {\n    elementThumbLoader: null,\n    authManager: null,\n\n    $nav: null,\n    $navToggle: null,\n    $globalSidebar: null,\n    $globalContainer: null,\n    $mainContainer: null,\n    $alerts: null,\n    $crumbs: null,\n    $breadcrumbList: null,\n    $breadcrumbItems: null,\n    $notificationContainer: null,\n    $main: null,\n    $primaryForm: null,\n    $headerContainer: null,\n    $header: null,\n    $mainContent: null,\n    $details: null,\n    $sidebarContainer: null,\n    $sidebarToggle: null,\n    $sidebar: null,\n    $contentContainer: null,\n    $edition: null,\n\n    $confirmUnloadForms: null,\n    $deltaForms: null,\n    $collapsibleTables: null,\n\n    isMobile: null,\n    fixedHeader: false,\n\n    breadcrumbListWidth: 0,\n    breadcrumbDisclosureItem: `<li class=\"breadcrumb-toggle-wrapper\" data-disclosure-item><button data-disclosure-trigger aria-controls=\"breadcrumb-disclosure\" aria-haspopup=\"true\">${Craft.t(\n      'app',\n      'More…'\n    )}</button><div id=\"breadcrumb-disclosure\" class=\"menu menu--disclosure\" data-disclosure-menu><ul></ul></div></li>`,\n\n    tabManager: null,\n\n    enableQueue: true,\n    totalJobs: 0,\n    jobInfo: null,\n    displayedJobInfo: null,\n    displayedJobInfoUnchanged: 1,\n    trackJobProgressTimeout: null,\n    jobProgressIcon: null,\n\n    checkingForUpdates: false,\n    forcingRefreshOnUpdatesCheck: false,\n    includingDetailsOnUpdatesCheck: false,\n    checkForUpdatesCallbacks: null,\n\n    resizeTimeout: null,\n\n    init: function () {\n      this.elementThumbLoader = new Craft.ElementThumbLoader();\n\n      // Is this session going to expire?\n      if (Craft.remainingSessionTime !== 0) {\n        this.authManager = new Craft.AuthManager();\n      }\n\n      // Find all the key elements\n      this.$nav = $('#nav');\n      this.$navToggle = $('#primary-nav-toggle');\n      this.$globalSidebar = $('#global-sidebar');\n      this.$globalContainer = $('#global-container');\n      this.$mainContainer = $('#main-container');\n      this.$alerts = $('#alerts');\n      this.$crumbs = $('#crumbs');\n      this.$breadcrumbList = $('.breadcrumb-list');\n      this.$breadcrumbItems = $('.breadcrumb-list li');\n      this.$notificationContainer = $('#notifications');\n      this.$main = $('#main');\n      this.$primaryForm = $('#main-form');\n      this.$headerContainer = $('#header-container');\n      this.$header = $('#header');\n      this.$mainContent = $('#main-content');\n      this.$details = $('#details');\n      this.$sidebarContainer = $('#sidebar-container');\n      this.$sidebarToggle = $('#sidebar-toggle');\n      this.$sidebar = $('#sidebar');\n      this.$contentContainer = $('#content-container');\n      this.$collapsibleTables = $('table.collapsible');\n\n      this.isMobile = Garnish.isMobileBrowser();\n\n      this.updateContentHeading();\n\n      // Swap any instruction text with info icons\n      let $allInstructions = this.$details.find(\n        '.meta > .field > .instructions'\n      );\n\n      for (let i = 0; i < $allInstructions.length; i++) {\n        let $instructions = $allInstructions.eq(i);\n        let $label = $instructions.siblings('.heading').children('label');\n        $('<span/>', {\n          class: 'info',\n          html: $instructions.children().html(),\n        }).appendTo($label);\n        $instructions.remove();\n      }\n\n      if (!this.isMobile && this.$header.length) {\n        this.addListener(Garnish.$win, 'scroll', 'updateFixedHeader');\n        this.updateFixedHeader();\n      }\n\n      Garnish.$doc.ready(() => {\n        // Update responsive tables on window resize\n        this.addListener(Garnish.$win, 'resize', (ev) => {\n          // Ignore element resizes\n          if (ev.target === window) {\n            this.handleWindowResize();\n\n            clearTimeout(this.resizeTimeout);\n            var cp = this;\n            this.resizeTimeout = setTimeout(function () {\n              cp.setSidebarNavAttributes();\n            }, 100);\n          }\n        });\n        this.handleWindowResize();\n        this.setSidebarNavAttributes();\n\n        // Wait a frame before initializing any confirm-unload forms,\n        // so other JS that runs on ready() has a chance to initialize\n        Garnish.requestAnimationFrame(this.initSpecialForms.bind(this));\n      });\n\n      // Alerts\n      if (this.$alerts.length) {\n        this.initAlerts();\n      }\n\n      // Toggles\n      this.addListener(this.$navToggle, 'click', 'toggleNav');\n      this.addListener(this.$sidebarToggle, 'click', 'toggleSidebar');\n\n      // Does this page have a primary form?\n      if (!this.$primaryForm.length) {\n        this.$primaryForm = $('form[data-saveshortcut]:first');\n      }\n\n      // Does the primary form support the save shortcut?\n      if (\n        this.$primaryForm.length &&\n        Garnish.hasAttr(this.$primaryForm, 'data-saveshortcut')\n      ) {\n        let shortcuts = [];\n        let actions = this.$primaryForm.data('actions');\n        if (typeof actions === 'undefined') {\n          shortcuts.push([\n            {\n              keyCode: Garnish.S_KEY,\n              ctrl: true,\n            },\n            {\n              redirect: this.$primaryForm.data('saveshortcut-redirect'),\n              retainScroll: Garnish.hasAttr(\n                this.$primaryForm,\n                'saveshortcut-scroll'\n              ),\n            },\n          ]);\n        } else {\n          for (let i = 0; i < actions.length; i++) {\n            let action = actions[i];\n            if (!action.shortcut) {\n              continue;\n            }\n            shortcuts.push([\n              {\n                keyCode: Garnish.S_KEY,\n                ctrl: true,\n                shift: !!action.shift,\n              },\n              {\n                action: action.action,\n                redirect: action.redirect,\n                confirm: action.confirm,\n                params: action.params,\n                data: action.data,\n                retainScroll: action.retainScroll,\n              },\n            ]);\n          }\n        }\n        for (let i = 0; i < shortcuts.length; i++) {\n          Garnish.uiLayerManager.registerShortcut(shortcuts[i][0], () => {\n            this.submitPrimaryForm(shortcuts[i][1]);\n          });\n        }\n      }\n\n      this.initTabs();\n\n      if (this.tabManager) {\n        if (window.LOCATION_HASH) {\n          const $tab = this.tabManager.$tabs.filter(\n            `[href=\"#${window.LOCATION_HASH}\"]`\n          );\n          if ($tab.length) {\n            this.tabManager.selectTab($tab);\n          }\n        }\n      }\n\n      // Should we match the previous scroll position?\n      let scrollY = Craft.getLocalStorage('scrollY');\n      if (typeof scrollY !== 'undefined') {\n        Craft.removeLocalStorage('scrollY');\n        Garnish.$doc.ready(() => {\n          Garnish.requestAnimationFrame(() => {\n            window.scrollTo(0, scrollY);\n          });\n        });\n      }\n\n      if ($.isTouchCapable()) {\n        this.$mainContainer.on(\n          'focus',\n          'input, textarea, .focusable-input',\n          this._handleInputFocus.bind(this)\n        );\n        this.$mainContainer.on(\n          'blur',\n          'input, textarea, .focusable-input',\n          this._handleInputBlur.bind(this)\n        );\n      }\n\n      // Announcements HUD\n      if (Craft.announcements.length) {\n        let $btn = $('#announcements-btn').removeClass('hidden');\n        const hasUnreads = Craft.announcements.some((a) => a.unread);\n        let $unreadMessage;\n        if (hasUnreads) {\n          $unreadMessage = $('<span/>', {\n            class: 'visually-hidden',\n            html: Craft.t('app', 'Unread messages'),\n          });\n          $btn.addClass('unread').append($unreadMessage);\n        }\n        let hud;\n        this.addListener($btn, 'click', () => {\n          if (!hud) {\n            let contents = '';\n            Craft.announcements.forEach((a) => {\n              contents +=\n                `<div class=\"announcement ${\n                  a.unread ? 'unread' : ''\n                }\" role=\"listitem\">` +\n                '<div class=\"announcement__header\">' +\n                `<h3 class=\"announcement__heading h2\">${a.heading}</h3>` +\n                '<div class=\"announcement-label-container\">' +\n                `<div class=\"announcement-icon\" aria-hidden=\"true\">${a.icon}</div>` +\n                `<div class=\"announcement-label\">${a.label}</div>` +\n                '</div>' +\n                '</div>' +\n                `<p>${a.body}</p>` +\n                '</div>';\n            });\n            hud = new Garnish.HUD(\n              $btn,\n              `<h2 class=\"visually-hidden\">${Craft.t(\n                'app',\n                'Announcements'\n              )}</h2><div id=\"announcements\" role=\"list\">${contents}</div>`,\n              {\n                onShow: () => {\n                  $btn.addClass('active');\n                },\n                onHide: () => {\n                  $btn.removeClass('active');\n                },\n              }\n            );\n\n            // Open outbound links in new windows\n            $('a', hud.$main).each(function () {\n              if (\n                this.hostname.length &&\n                this.hostname !== location.hostname &&\n                typeof $(this).attr('target') === 'undefined'\n              ) {\n                $(this).attr('rel', 'noopener').attr('target', '_blank');\n              }\n            });\n\n            if (hasUnreads) {\n              $btn.removeClass('unread');\n              $unreadMessage.remove();\n              Craft.sendActionRequest(\n                'POST',\n                'users/mark-announcements-as-read',\n                {\n                  data: {\n                    ids: Craft.announcements.map((a) => a.id),\n                  },\n                }\n              );\n            }\n          } else {\n            hud.show();\n          }\n        });\n      }\n\n      // Add .stuck class to #footer when stuck\n      // h/t https://stackoverflow.com/a/61115077/1688568\n      const footer = document.getElementById('footer');\n      if (footer) {\n        const observer = new IntersectionObserver(\n          ([ev]) => {\n            ev.target.classList.toggle('stuck', ev.intersectionRatio < 1);\n          },\n          {\n            rootMargin: '0px 0px -1px 0px',\n            threshold: [1],\n          }\n        );\n        observer.observe(footer);\n      }\n\n      // Load any element thumbs\n      this.elementThumbLoader.load(this.$mainContent);\n    },\n\n    get $contentHeader() {\n      const $contentHeader = $('#content-header');\n      if ($contentHeader.length) {\n        return $contentHeader;\n      }\n      return $('<header/>', {\n        id: 'content-header',\n        class: 'pane-header',\n      }).prependTo($('#content'));\n    },\n\n    get $noticeContainer() {\n      const $noticeContainer = $('#content-notice');\n      if ($noticeContainer.length) {\n        return $noticeContainer;\n      }\n      return $('<div id=\"content-notice\"/>')\n        .attr('role', 'status')\n        .prependTo(this.$contentHeader);\n    },\n\n    initSpecialForms: function () {\n      // Look for forms that we should watch for changes on\n      this.$confirmUnloadForms = $('form[data-confirm-unload]');\n      this.$deltaForms = $('form[data-delta]');\n\n      if (!this.$confirmUnloadForms.length) {\n        return;\n      }\n\n      const $forms = this.$confirmUnloadForms.add(this.$deltaForms);\n\n      for (let i = 0; i < $forms.length; i++) {\n        const $form = $forms.eq(i);\n        let serialized;\n        if (!$form.data('initialSerializedValue')) {\n          if (typeof $form.data('serializer') === 'function') {\n            serialized = $form.data('serializer')();\n          } else {\n            serialized = $form.serialize();\n          }\n          $form.data('initialSerializedValue', serialized);\n        }\n        this.addListener($form, 'submit', function (ev) {\n          if (Garnish.hasAttr($form, 'data-confirm-unload')) {\n            this.removeListener(Garnish.$win, 'beforeunload');\n          }\n          if (Garnish.hasAttr($form, 'data-delta')) {\n            ev.preventDefault();\n            let serialized;\n            if (typeof $form.data('serializer') === 'function') {\n              serialized = $form.data('serializer')();\n            } else {\n              serialized = $form.serialize();\n            }\n            const data = Craft.findDeltaData(\n              $form.data('initialSerializedValue'),\n              serialized,\n              $form.data('delta-names'),\n              null,\n              $form.data('initial-delta-values'),\n              $form.data('modified-delta-names')\n            );\n            Craft.createForm(data).appendTo(Garnish.$bod).submit();\n          }\n        });\n      }\n\n      this.addListener(Garnish.$win, 'beforeunload', function (ev) {\n        let confirmUnload = false;\n        if (\n          typeof Craft.livePreview !== 'undefined' &&\n          Craft.livePreview.inPreviewMode\n        ) {\n          confirmUnload = true;\n        } else {\n          for (let i = 0; i < this.$confirmUnloadForms.length; i++) {\n            const $form = this.$confirmUnloadForms.eq(i);\n            let serialized;\n            if (typeof $form.data('serializer') === 'function') {\n              serialized = $form.data('serializer')();\n            } else {\n              serialized = $form.serialize();\n            }\n            if ($form.data('initialSerializedValue') !== serialized) {\n              confirmUnload = true;\n              break;\n            }\n          }\n        }\n\n        if (confirmUnload) {\n          var message = Craft.t(\n            'app',\n            'Any changes will be lost if you leave this page.'\n          );\n\n          if (ev) {\n            ev.originalEvent.returnValue = message;\n          } else {\n            window.event.returnValue = message;\n          }\n\n          return message;\n        }\n      });\n    },\n\n    _handleInputFocus: function () {\n      this.updateFixedHeader();\n    },\n\n    _handleInputBlur: function () {\n      this.updateFixedHeader();\n    },\n\n    /**\n     * Submits a form.\n     * @param {Object} [options]\n     * @param {string} [options.action] The `action` param value override\n     * @param {string} [options.redirect] The `redirect` param value override\n     * @param {string} [options.confirm] A confirmation message that should be shown to the user before submit\n     * @param {Object} [options.params] Additional params that should be added to the form, defined as name/value pairs\n     * @param {Object} [options.data] Additional data to be passed to the submit event\n     * @param {boolean} [options.retainScroll] Whether the scroll position should be stored and reapplied on the next page load\n     */\n    submitPrimaryForm: function (options) {\n      // Give other stuff on the page a chance to prepare\n      this.trigger('beforeSaveShortcut');\n\n      if (typeof options !== 'object' || !$.isPlainObject(options)) {\n        options = {};\n      }\n\n      if (!options.redirect) {\n        options.redirect = this.$primaryForm.data('saveshortcut-redirect');\n      }\n\n      if (!options.data) {\n        options.data = {};\n      }\n      options.data.saveShortcut = true;\n\n      Craft.submitForm(this.$primaryForm, options);\n    },\n\n    updateSidebarMenuLabel: function () {\n      this.updateContentHeading();\n    },\n\n    updateContentHeading: function () {\n      const $item = this.$sidebar.find('a.sel:first');\n      const $label = $item.children('.label');\n      $('#content-heading').text($label.length ? $label.text() : $item.text());\n      Garnish.$bod.removeClass('showing-sidebar');\n    },\n\n    toggleNav: function () {\n      const isExpanded = this.navIsExpanded();\n\n      if (isExpanded === null) return;\n\n      if (isExpanded) {\n        this.disableGlobalSidebarLinks();\n        this.$navToggle.focus();\n        this.$navToggle.attr('aria-expanded', 'false');\n        Garnish.$bod.removeClass('showing-nav');\n      } else {\n        this.enableGlobalSidebarLinks();\n        this.$globalSidebar.find(':focusable')[0].focus();\n        this.$navToggle.attr('aria-expanded', 'true');\n        Garnish.$bod.addClass('showing-nav');\n      }\n    },\n\n    enableGlobalSidebarLinks: function () {\n      const focusableItems = this.$globalSidebar.find(':focusable');\n\n      $(focusableItems).each(function () {\n        $(this).attr('tabindex', '0');\n      });\n    },\n\n    disableGlobalSidebarLinks: function () {\n      const focusableItems = this.$globalSidebar.find(':focusable');\n\n      $(focusableItems).each(function () {\n        $(this).attr('tabindex', '-1');\n      });\n    },\n\n    setSidebarNavAttributes: function () {\n      const isExpanded = this.navIsExpanded();\n\n      if (isExpanded === null) return;\n\n      if (!isExpanded) {\n        this.disableGlobalSidebarLinks();\n      } else {\n        this.enableGlobalSidebarLinks();\n      }\n    },\n\n    navIsExpanded: function () {\n      if (!this.$globalSidebar[0]) return null;\n\n      const isAlwaysVisible = getComputedStyle(this.$globalSidebar[0])\n        .getPropertyValue('--is-always-visible')\n        .trim();\n\n      return (\n        this.$navToggle.attr('aria-expanded') === 'true' ||\n        isAlwaysVisible === 'true'\n      );\n    },\n\n    toggleSidebar: function () {\n      const expanded = this.$sidebarToggle.attr('aria-expanded') === 'true';\n      const newState = expanded ? 'false' : 'true';\n      this.$sidebarToggle.attr('aria-expanded', newState);\n      Garnish.$bod.toggleClass('showing-sidebar');\n    },\n\n    initTabs: function () {\n      if (this.tabManager) {\n        this.tabManager.destroy();\n        this.tabManager = null;\n      }\n\n      const $tabs = $('#tabs');\n      if (!$tabs.length) {\n        return;\n      }\n\n      this.tabManager = new Craft.Tabs($tabs);\n\n      this.tabManager.on('selectTab', (ev) => {\n        const href = ev.$tab.attr('href');\n\n        // Show its content area\n        if (href && href.charAt(0) === '#') {\n          $(href).removeClass('hidden');\n        }\n\n        // Trigger a resize event to update any UI components that are listening for it\n        Garnish.$win.trigger('resize');\n\n        // Fixes Redactor fixed toolbars on previously hidden panes\n        Garnish.$doc.trigger('scroll');\n\n        // If there is a revision menu, set its links to this tab ID\n        if (href && href.charAt(0) === '#') {\n          const menuBtn = $('#context-btn').menubtn().data('menubtn');\n          if (menuBtn) {\n            for (let i = 0; i < menuBtn.menu.$options.length; i++) {\n              let a = menuBtn.menu.$options[i];\n              if (a.href) {\n                a.href = a.href.match(/^[^#]*/)[0] + href;\n              }\n            }\n          }\n        }\n\n        if (typeof history !== 'undefined') {\n          // Delay changing the hash so it doesn't cause the browser to jump on page load\n          Garnish.requestAnimationFrame(() => {\n            history.replaceState(undefined, undefined, href);\n          });\n        }\n      });\n\n      this.tabManager.on('deselectTab', (ev) => {\n        const href = ev.$tab.attr('href');\n        if (href && href.charAt(0) === '#') {\n          // Hide its content area\n          $(ev.$tab.attr('href')).addClass('hidden');\n        }\n      });\n    },\n\n    updateTabs: function (tabs) {\n      if (tabs) {\n        const $tabContainer = $(tabs).attr('id', 'tabs');\n        if (this.tabManager) {\n          this.tabManager.$container.replaceWith($tabContainer);\n        } else {\n          $tabContainer.appendTo(this.$contentHeader);\n        }\n        this.initTabs();\n      } else if (this.tabManager) {\n        if (this.tabManager.$container.siblings().length) {\n          this.tabManager.$container.remove();\n        } else {\n          this.tabManager.$container.parent().remove();\n        }\n        this.tabManager.destroy();\n        this.tabManager = null;\n      }\n    },\n\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabsContainer() {\n      return this.tabManager ? this.tabManager.$container : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabsList() {\n      return this.tabManager ? this.tabManager.$tablist : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabs() {\n      return this.tabManager ? this.tabManager.$tablist.find('> a') : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $selectedTab() {\n      return this.tabManager ? this.tabManager.$selectedTab : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get selectedTabIndex() {\n      return this.tabManager\n        ? this.tabManager.$tabs.index(this.tabManager.$selectedTab)\n        : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $focusableTab() {\n      return this.tabManager ? this.tabManager.$focusableTab : undefined;\n    },\n    /**\n     * @param {(jQuery|HTMLElement|string)} tab\n     * @deprecated in 3.7.0\n     */\n    selectTab: function (tab) {\n      if (this.tabManager) {\n        this.tabManager.selectTab(tab);\n      }\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    deselectTab: function () {\n      if (this.tabManager) {\n        this.tabManager.deselectTab();\n      }\n    },\n\n    handleWindowResize: function () {\n      this.updateResponsiveTables();\n      this.handleBreadcrumbVisibility();\n    },\n\n    breadcrumbItemsWrap: function () {\n      if (!this.$breadcrumbItems[0]) return;\n\n      this.$breadcrumbList.css(\n        Craft.orientation === 'ltr' ? 'margin-right' : 'margin-left',\n        ''\n      );\n      const listWidth = this.$breadcrumbList[0].getBoundingClientRect().width;\n      let totalItemWidth = 0;\n\n      // Iterate through all list items (inclusive of more button)\n      const $items = this.$breadcrumbList.find('li');\n      for (let i = 0; i < $items.length; i++) {\n        totalItemWidth += $items.get(i).getBoundingClientRect().width;\n      }\n\n      this.breadcrumbListWidth = listWidth;\n\n      if (totalItemWidth <= listWidth) {\n        return false;\n      }\n\n      // If it's less than a pixel off, it's probably just a rounding error.\n      // Give the container an extra pixel to be safe, though\n      if (totalItemWidth < listWidth + 1) {\n        this.$breadcrumbList.css(\n          Craft.orientation === 'ltr' ? 'margin-right' : 'margin-left',\n          '-1px'\n        );\n        return false;\n      }\n\n      return true;\n    },\n\n    handleBreadcrumbVisibility: function () {\n      if (!this.breadcrumbItemsWrap()) return;\n\n      if (this.$breadcrumbList.find('[data-disclosure-item]').length === 0) {\n        this.$breadcrumbList.append(this.breadcrumbDisclosureItem);\n      }\n\n      const triggerWidth = this.$breadcrumbList.find(\n        '[data-disclosure-item]'\n      )[0].offsetWidth;\n      let visibleItemWidth = triggerWidth;\n      let finalIndex;\n      let newWidth;\n      const listWidth = this.breadcrumbListWidth;\n\n      // Find breadcrumbs that should remain visible without overflowing\n      this.$breadcrumbItems.each(function (index) {\n        newWidth = visibleItemWidth + this.offsetWidth;\n\n        if (newWidth < listWidth) {\n          finalIndex = index;\n          visibleItemWidth += this.offsetWidth;\n        } else {\n          return false;\n        }\n      });\n\n      // Separate breadcrums that should remain visible vs. hidden\n      const shownItems = this.$breadcrumbItems.slice(0, finalIndex + 1);\n      const hiddenItems = this.$breadcrumbItems.slice(finalIndex + 1);\n\n      // Empty list DOM and add shown items and trigger item\n      this.$breadcrumbList.html('');\n      this.$breadcrumbList.append(shownItems);\n      this.$breadcrumbList.append(this.breadcrumbDisclosureItem);\n\n      // Add hidden items to disclosure menu and initialize\n      this.$breadcrumbList\n        .find('[data-disclosure-menu] ul')\n        .append(hiddenItems);\n      this.$breadcrumbList.find('[data-disclosure-trigger]').disclosureMenu();\n    },\n\n    updateResponsiveTables: function () {\n      for (\n        this.updateResponsiveTables._i = 0;\n        this.updateResponsiveTables._i < this.$collapsibleTables.length;\n        this.updateResponsiveTables._i++\n      ) {\n        this.updateResponsiveTables._$table = this.$collapsibleTables.eq(\n          this.updateResponsiveTables._i\n        );\n        this.updateResponsiveTables._containerWidth =\n          this.updateResponsiveTables._$table.parent().width();\n        this.updateResponsiveTables._check = false;\n\n        if (this.updateResponsiveTables._containerWidth > 0) {\n          // Is this the first time we've checked this table?\n          if (\n            typeof this.updateResponsiveTables._$table.data(\n              'lastContainerWidth'\n            ) === 'undefined'\n          ) {\n            this.updateResponsiveTables._check = true;\n          } else {\n            this.updateResponsiveTables._isCollapsed =\n              this.updateResponsiveTables._$table.hasClass('collapsed');\n\n            // Getting wider?\n            if (\n              this.updateResponsiveTables._containerWidth >\n              this.updateResponsiveTables._$table.data('lastContainerWidth')\n            ) {\n              if (this.updateResponsiveTables._isCollapsed) {\n                this.updateResponsiveTables._$table.removeClass('collapsed');\n                this.updateResponsiveTables._check = true;\n              }\n            } else if (!this.updateResponsiveTables._isCollapsed) {\n              this.updateResponsiveTables._check = true;\n            }\n          }\n\n          // Are we checking the table width?\n          if (this.updateResponsiveTables._check) {\n            if (\n              this.updateResponsiveTables._$table.width() - 30 >\n              this.updateResponsiveTables._containerWidth\n            ) {\n              this.updateResponsiveTables._$table.addClass('collapsed');\n            }\n          }\n\n          // Remember the container width for next time\n          this.updateResponsiveTables._$table.data(\n            'lastContainerWidth',\n            this.updateResponsiveTables._containerWidth\n          );\n        }\n      }\n    },\n\n    updateFixedHeader: function () {\n      if (this.isMobile) {\n        return;\n      }\n\n      // Have we scrolled passed the top of #main?\n      if (\n        this.$main.length &&\n        this.$headerContainer[0].getBoundingClientRect().top < 0\n      ) {\n        if (!this.fixedHeader) {\n          var headerHeight = this.$headerContainer.height();\n\n          // Hard-set the minimum content container height\n          this.$contentContainer.css(\n            'min-height',\n            'calc(100vh - ' + (headerHeight + 14 + 48 - 1) + 'px)'\n          );\n\n          // Hard-set the header container height\n          this.$headerContainer.height(headerHeight);\n          Garnish.$bod.addClass('fixed-header');\n\n          // Fix the sidebar and details pane positions if they are taller than #content-container\n          var contentHeight = this.$contentContainer.outerHeight();\n          var $detailsHeight = this.$details.outerHeight();\n          var css = {\n            top: headerHeight + 'px',\n            'max-height': 'calc(100vh - ' + headerHeight + 'px)',\n          };\n          this.$sidebar.addClass('fixed').css(css);\n          this.$details.addClass('fixed').css(css);\n          this.fixedHeader = true;\n        }\n      } else if (this.fixedHeader) {\n        this.$headerContainer.height('auto');\n        Garnish.$bod.removeClass('fixed-header');\n        this.$contentContainer.css('min-height', '');\n        this.$sidebar.removeClass('fixed').css({\n          top: '',\n          'max-height': '',\n        });\n        this.$details.removeClass('fixed').css({\n          top: '',\n          'max-height': '',\n        });\n        this.fixedHeader = false;\n      }\n    },\n\n    /**\n     * Dispays a notification.\n     *\n     * @param {string} type `notice`, `success`, or `error`\n     * @param {string} message\n     * @param {Object} [settings]\n     * @param {string} [settings.icon] The icon to show on the notification\n     * @param {string} [settings.iconLabel] The icon’s ARIA label\n     * @param {string} [settings.details] Any additional HTML that should be included below the message\n     * @returns {Object} The notification\n     */\n    displayNotification: function (type, message, settings) {\n      const notification = new Craft.CP.Notification(type, message, settings);\n\n      this.trigger('displayNotification', {\n        notificationType: type,\n        message,\n        notification,\n      });\n\n      return notification;\n    },\n\n    /**\n     * Displays a notice.\n     *\n     * @param {string} message\n     * @param {Object} [settings]\n     * @param {string} [settings.icon] The icon to show on the notification\n     * @param {string} [settings.iconLabel] The icon’s ARIA label\n     * @param {string} [settings.details] Any additional HTML that should be included below the message\n     * @returns {Object} The notification\n     */\n    displayNotice: function (message, settings) {\n      return this.displayNotification(\n        'notice',\n        message,\n        Object.assign(\n          {\n            icon: 'info',\n            iconLabel: Craft.t('app', 'Notice'),\n          },\n          settings\n        )\n      );\n    },\n\n    /**\n     * Displays a success notification.\n     *\n     * @param {string} message\n     * @param {Object} [settings]\n     * @param {string} [settings.icon] The icon to show on the notification\n     * @param {string} [settings.iconLabel] The icon’s ARIA label\n     * @param {string} [settings.details] Any additional HTML that should be included below the message\n     * @returns {Object} The notification\n     */\n    displaySuccess: function (message, settings) {\n      return this.displayNotification(\n        'success',\n        message,\n        Object.assign(\n          {\n            icon: 'check',\n            iconLabel: Craft.t('app', 'Success'),\n          },\n          settings\n        )\n      );\n    },\n\n    /**\n     * Displays an error.\n     *\n     * @param {string} message\n     * @param {Object} [settings]\n     * @param {string} [settings.icon] The icon to show on the notification\n     * @param {string} [settings.iconLabel] The icon’s ARIA label\n     * @param {string} [settings.details] Any additional HTML that should be included below the message\n     * @returns {Object} The notification\n     */\n    displayError: function (message, settings) {\n      if (!message || typeof message === 'object') {\n        settings = message;\n        message = Craft.t('app', 'A server error occurred.');\n      }\n\n      return this.displayNotification(\n        'error',\n        message,\n        Object.assign(\n          {\n            icon: 'alert',\n            iconLabel: Craft.t('app', 'Error'),\n          },\n          settings\n        )\n      );\n    },\n\n    fetchAlerts: function () {\n      return Craft.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            const data = {\n              path: Craft.path,\n            };\n            Craft.sendActionRequest('POST', 'app/get-cp-alerts', {data})\n              .then(({data}) => {\n                resolve(data.alerts);\n              })\n              .catch(reject);\n          })\n      );\n    },\n\n    displayAlerts: function (alerts) {\n      this.$alerts.remove();\n\n      if (Garnish.isArray(alerts) && alerts.length) {\n        this.$alerts = $('<ul id=\"alerts\"/>').prependTo($('#page-container'));\n\n        for (let alert of alerts) {\n          if (!$.isPlainObject(alert)) {\n            alert = {\n              content: alert,\n              showIcon: true,\n            };\n          }\n          let content = alert.content;\n          if (alert.showIcon) {\n            content = `<span data-icon=\"alert\" aria-label=\"${Craft.t(\n              'app',\n              'Error'\n            )}\"></span> ${content}`;\n          }\n          $(`<li>${content}</li>`).appendTo(this.$alerts);\n        }\n\n        var height = this.$alerts.outerHeight();\n        this.$alerts\n          .css('margin-top', -height)\n          .velocity({'margin-top': 0}, 'fast');\n\n        this.initAlerts();\n      }\n    },\n\n    initAlerts: function () {\n      // Are there any shunnable alerts?\n      var $shunnableAlerts = this.$alerts.find('a[class^=\"shun:\"]');\n\n      for (var i = 0; i < $shunnableAlerts.length; i++) {\n        this.addListener($shunnableAlerts[i], 'click', (ev) => {\n          ev.preventDefault();\n\n          Craft.queue.push(\n            () =>\n              new Promise((resolve, reject) => {\n                const $link = $(ev.currentTarget);\n                const data = {\n                  message: $link.prop('className').substring(5),\n                };\n                Craft.sendActionRequest('POST', 'app/shun-cp-alert', {data})\n                  .then(() => {\n                    $link.parent().remove();\n                    resolve();\n                  })\n                  .catch(({response}) => {\n                    this.displayError(response.data.message);\n                    reject();\n                  });\n              })\n          );\n        });\n      }\n    },\n\n    checkForUpdates: function (forceRefresh, includeDetails, callback) {\n      // Make 'includeDetails' optional\n      if (typeof includeDetails === 'function') {\n        callback = includeDetails;\n        includeDetails = false;\n      }\n\n      // If forceRefresh == true, we're currently checking for updates, and not currently forcing a refresh,\n      // then just set a new callback that re-checks for updates when the current one is done.\n      if (\n        this.checkingForUpdates &&\n        ((forceRefresh === true && !this.forcingRefreshOnUpdatesCheck) ||\n          (includeDetails === true && !this.includingDetailsOnUpdatesCheck))\n      ) {\n        var realCallback = callback;\n        callback = () => {\n          this.checkForUpdates(forceRefresh, includeDetails, realCallback);\n        };\n      }\n\n      // Callback function?\n      if (typeof callback === 'function') {\n        if (!Garnish.isArray(this.checkForUpdatesCallbacks)) {\n          this.checkForUpdatesCallbacks = [];\n        }\n\n        this.checkForUpdatesCallbacks.push(callback);\n      }\n\n      if (!this.checkingForUpdates) {\n        this.checkingForUpdates = true;\n        this.forcingRefreshOnUpdatesCheck = forceRefresh === true;\n        this.includingDetailsOnUpdatesCheck = includeDetails === true;\n\n        this._checkForUpdates(forceRefresh, includeDetails).then((info) => {\n          this.updateUtilitiesBadge();\n          this.checkingForUpdates = false;\n\n          if (Garnish.isArray(this.checkForUpdatesCallbacks)) {\n            var callbacks = this.checkForUpdatesCallbacks;\n            this.checkForUpdatesCallbacks = null;\n\n            for (var i = 0; i < callbacks.length; i++) {\n              callbacks[i](info);\n            }\n          }\n\n          this.trigger('checkForUpdates', {\n            updateInfo: info,\n          });\n        });\n      }\n    },\n\n    _checkForUpdates: function (forceRefresh, includeDetails) {\n      return new Promise((resolve, reject) => {\n        if (!forceRefresh) {\n          this._checkForCachedUpdates(includeDetails)\n            .then((info) => {\n              if (info.cached) {\n                resolve(info);\n                return;\n              }\n\n              this._getUpdates(includeDetails).then((info) => {\n                resolve(info);\n              });\n            })\n            .catch(reject);\n        } else {\n          this._getUpdates(includeDetails).then(resolve).catch(reject);\n        }\n      });\n    },\n\n    _checkForCachedUpdates: function (includeDetails) {\n      return new Promise(function (resolve, reject) {\n        var data = {\n          onlyIfCached: true,\n          includeDetails: includeDetails,\n        };\n\n        Craft.sendActionRequest('POST', 'app/check-for-updates', {data})\n          .then(({data}) => {\n            resolve(data);\n          })\n          .catch(() => {\n            resolve({cached: false});\n          });\n      });\n    },\n\n    _getUpdates: function (includeDetails) {\n      return new Promise((resolve, reject) => {\n        Craft.sendApiRequest('GET', 'updates')\n          .then((updates) => {\n            this._cacheUpdates(updates, includeDetails).then((data) => {\n              resolve(data);\n            });\n          })\n          .catch(reject);\n      });\n    },\n\n    _cacheUpdates: function (updates, includeDetails) {\n      return new Promise((resolve, reject) => {\n        const data = {\n          updates,\n          includeDetails,\n        };\n\n        Craft.sendActionRequest('POST', 'app/cache-updates', {data})\n          .then(({data}) => {\n            resolve(data);\n          })\n          .catch(reject);\n      });\n    },\n\n    updateUtilitiesBadge: function () {\n      var $utilitiesLink = $('#nav-utilities').find('> a:not(.sel)');\n\n      // Ignore if there is no (non-selected) Utilities nav item\n      if (!$utilitiesLink.length) {\n        return;\n      }\n\n      Craft.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            Craft.sendActionRequest('POST', 'app/get-utilities-badge-count')\n              .then(({data}) => {\n                // Get the existing utility nav badge and screen reader text, if any\n                let $badge = $utilitiesLink.children('.badge');\n                let $screenReaderText = $utilitiesLink.children(\n                  '[data-notification]'\n                );\n\n                if (data.badgeCount) {\n                  if (!$badge.length) {\n                    $badge = $(\n                      '<span class=\"badge\" aria-hidden=\"true\"/>'\n                    ).appendTo($utilitiesLink);\n                  }\n\n                  if (!$screenReaderText.length) {\n                    $screenReaderText = $(\n                      '<span class=\"visually-hidden\" data-notification/>'\n                    ).appendTo($utilitiesLink);\n                  }\n\n                  $badge.text(data.badgeCount);\n                  $screenReaderText.text(\n                    Craft.t(\n                      'app',\n                      '{num, number} {num, plural, =1{notification} other{notifications}}',\n                      {\n                        num: data.badgeCount,\n                      }\n                    )\n                  );\n                } else if ($badge.length && $screenReaderText.length) {\n                  $badge.remove();\n                  $screenReaderText.remove();\n                }\n                resolve();\n              })\n              .catch(reject);\n          })\n      );\n    },\n\n    runQueue: function () {\n      if (!this.enableQueue) {\n        return;\n      }\n\n      if (Craft.runQueueAutomatically) {\n        Craft.queue.push(\n          () =>\n            new Promise((resolve, reject) => {\n              Craft.sendActionRequest('POST', 'queue/run')\n                .then(() => {\n                  this.trackJobProgress(false, true);\n                  resolve();\n                })\n                .catch(reject);\n            })\n        );\n      } else {\n        this.trackJobProgress(false, true);\n      }\n    },\n\n    trackJobProgress: function (delay, force) {\n      if (force && this.trackJobProgressTimeout) {\n        clearTimeout(this.trackJobProgressTimeout);\n        this.trackJobProgressTimeout = null;\n      }\n\n      // Ignore if we're already tracking jobs, or the queue is disabled\n      if (this.trackJobProgressTimeout || !this.enableQueue) {\n        return;\n      }\n\n      if (delay === true) {\n        // Determine the delay based on how long the displayed job info has remained unchanged\n        var timeout = Math.min(60000, this.displayedJobInfoUnchanged * 500);\n        this.trackJobProgressTimeout = setTimeout(\n          this._trackJobProgressInternal.bind(this),\n          timeout\n        );\n      } else {\n        this._trackJobProgressInternal();\n      }\n    },\n\n    _trackJobProgressInternal: function () {\n      Craft.queue.push(\n        () =>\n          new Promise((resolve, reject) => {\n            Craft.sendActionRequest(\n              'POST',\n              'queue/get-job-info?limit=50&dontExtendSession=1'\n            )\n              .then(({data}) => {\n                this.trackJobProgressTimeout = null;\n                this.totalJobs = data.total;\n                this.setJobInfo(data.jobs);\n                if (this.jobInfo.length) {\n                  // Check again after a delay\n                  this.trackJobProgress(true);\n                }\n                resolve();\n              })\n              .catch(reject);\n          })\n      );\n    },\n\n    setJobInfo: function (jobInfo) {\n      if (!this.enableQueue) {\n        return;\n      }\n\n      this.jobInfo = jobInfo;\n\n      // Update the displayed job info\n      var oldInfo = this.displayedJobInfo;\n      this.displayedJobInfo = this.getDisplayedJobInfo();\n\n      // Same old same old?\n      if (\n        oldInfo &&\n        this.displayedJobInfo &&\n        oldInfo.id === this.displayedJobInfo.id &&\n        oldInfo.progress === this.displayedJobInfo.progress &&\n        oldInfo.progressLabel === this.displayedJobInfo.progressLabel &&\n        oldInfo.status === this.displayedJobInfo.status\n      ) {\n        this.displayedJobInfoUnchanged++;\n      } else {\n        // Reset the counter\n        this.displayedJobInfoUnchanged = 1;\n      }\n\n      this.updateJobIcon();\n\n      // Fire a setJobInfo event\n      this.trigger('setJobInfo');\n    },\n\n    /**\n     * Returns info for the job that should be displayed in the control panel sidebar\n     */\n    getDisplayedJobInfo: function () {\n      if (!this.enableQueue) {\n        return null;\n      }\n\n      // Set the status preference order\n      var statuses = [\n        Craft.CP.JOB_STATUS_RESERVED,\n        Craft.CP.JOB_STATUS_FAILED,\n        Craft.CP.JOB_STATUS_WAITING,\n      ];\n\n      for (var i = 0; i < statuses.length; i++) {\n        for (var j = 0; j < this.jobInfo.length; j++) {\n          if (\n            this.jobInfo[j].status === statuses[i] &&\n            (statuses[i] !== Craft.CP.JOB_STATUS_WAITING ||\n              !this.jobInfo[j].delay)\n          ) {\n            return this.jobInfo[j];\n          }\n        }\n      }\n\n      return null;\n    },\n\n    updateJobIcon: function () {\n      if (!this.enableQueue || !this.$nav.length) {\n        return;\n      }\n\n      if (this.displayedJobInfo) {\n        if (!this.jobProgressIcon) {\n          this.jobProgressIcon = new JobProgressIcon();\n        }\n\n        if (\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_RESERVED ||\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_WAITING\n        ) {\n          this.jobProgressIcon.hideFailMode();\n          this.jobProgressIcon.setDescription(\n            this.displayedJobInfo.description,\n            this.displayedJobInfo.progressLabel\n          );\n          this.jobProgressIcon.setProgress(this.displayedJobInfo.progress);\n        } else if (\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_FAILED\n        ) {\n          this.jobProgressIcon.showFailMode(Craft.t('app', 'Failed'));\n        }\n      } else {\n        if (this.jobProgressIcon) {\n          this.jobProgressIcon.hideFailMode();\n          this.jobProgressIcon.complete();\n          delete this.jobProgressIcon;\n        }\n      }\n    },\n\n    /**\n     * Returns the active site for the control panel\n     *\n     * @returns {number}\n     */\n    getSiteId: function () {\n      // If the old BaseElementIndex.siteId value is in localStorage, go aheand and remove & return that\n      let siteId = Craft.getLocalStorage('BaseElementIndex.siteId');\n      if (typeof siteId !== 'undefined') {\n        Craft.removeLocalStorage('BaseElementIndex.siteId');\n        try {\n          this.setSiteId(siteId);\n        } catch (e) {}\n      }\n      return Craft.siteId;\n    },\n\n    /**\n     * Sets the active site for the control panel\n     * @param {number} siteId\n     */\n    setSiteId: function (siteId) {\n      const site = Craft.sites.find((s) => s.id === siteId);\n\n      if (!site) {\n        throw `Invalid site ID: ${siteId}`;\n      }\n\n      Craft.siteId = siteId;\n\n      // update the base URLs used get Craft.getUrl(), etc.\n      Craft.actionUrl = Craft.getUrl(Craft.actionUrl, {site: site.handle});\n      Craft.baseCpUrl = Craft.getUrl(Craft.baseCpUrl, {site: site.handle});\n      Craft.baseUrl = Craft.getUrl(Craft.baseUrl, {site: site.handle});\n\n      // update the current URL\n      const url = Craft.getUrl(document.location.href, {site: site.handle});\n      history.replaceState({}, '', url);\n\n      // update the site--x body class\n      for (let className of document.body.classList) {\n        if (className.match(/^site--/)) {\n          document.body.classList.remove(className);\n        }\n      }\n      document.body.classList.add(`site--${site.handle}`);\n\n      // update other URLs on the page\n      $('a').each(function () {\n        if (\n          this.hostname.length &&\n          this.hostname === location.hostname &&\n          this.href.indexOf(Craft.cpTrigger) !== -1\n        ) {\n          this.href = Craft.getUrl(this.href, {site: site.handle});\n        }\n      });\n    },\n  },\n  {\n    //maxWidth: 1051, //1024,\n\n    /**\n     * @deprecated in 4.2.0. Use Craft.notificationDuration instead.\n     */\n    notificationDuration: 5000,\n\n    JOB_STATUS_WAITING: 1,\n    JOB_STATUS_RESERVED: 2,\n    JOB_STATUS_DONE: 3,\n    JOB_STATUS_FAILED: 4,\n  }\n);\n\nCraft.CP.Notification = Garnish.Base.extend({\n  type: null,\n  message: null,\n  settings: null,\n  closing: false,\n  closeTimeout: null,\n  _preventDelayedClose: false,\n  $container: null,\n  $closeBtn: null,\n  originalActiveElement: null,\n\n  init: function (type, message, settings) {\n    this.type = type;\n    this.message = message;\n    this.settings = settings || {};\n\n    this.$container = $('<div/>', {\n      class: 'notification',\n      'data-type': this.type,\n    }).appendTo(Craft.cp.$notificationContainer);\n\n    const $body = $('<div class=\"notification-body\"/>').appendTo(\n      this.$container\n    );\n\n    if (this.settings.icon) {\n      const $icon = $('<span/>', {\n        class: 'notification-icon',\n        'data-icon': this.settings.icon,\n      }).appendTo($body);\n      if (this.settings.iconLabel) {\n        $icon.attr({\n          'aria-label': this.settings.iconLabel,\n          role: 'img',\n        });\n      } else {\n        $icon.attr('aria-hidden', 'true');\n      }\n    }\n\n    const $main = $('<div class=\"notification-main\"/>').appendTo($body);\n\n    $('<div/>', {\n      class: 'notification-message',\n      text: this.message,\n    }).appendTo($main);\n\n    const $closeBtnContainer = $('<div/>').appendTo(this.$container);\n    this.$closeBtn = $('<button/>', {\n      type: 'button',\n      class: 'notification-close-btn',\n      'aria-label': Craft.t('app', 'Close'),\n      'data-icon': 'remove',\n    }).appendTo($closeBtnContainer);\n\n    if (this.settings.details) {\n      const $detailsContainer = $('<div class=\"notification-details\"/>')\n        .append(this.settings.details)\n        .appendTo($main);\n\n      const $focusableElement = $detailsContainer.find('button,input');\n      if ($focusableElement.length) {\n        Garnish.uiLayerManager.addLayer(this.$container);\n        Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n          this.close();\n        });\n        this.originalActiveElement = document.activeElement;\n        this.$container.attr('tabindex', '-1').focus();\n        this.$container.on('keydown', (ev) => {\n          if (ev.keyCode === Garnish.ESC_KEY) {\n            ev.stopPropagation();\n            this.close();\n          }\n        });\n      }\n    }\n\n    this.$container\n      .css({\n        opacity: 0,\n        'margin-bottom': this._negMargin(),\n      })\n      .velocity({opacity: 1, 'margin-bottom': 0}, {duration: 'fast'});\n\n    Craft.initUiElements(this.$container);\n\n    this.addListener(this.$closeBtn, 'click', 'close');\n\n    if (Craft.notificationDuration) {\n      this._initDelayedClose();\n    }\n  },\n\n  _initDelayedClose: function () {\n    if (this._preventDelayedClose) {\n      return;\n    }\n\n    if (!Craft.isVisible()) {\n      Garnish.$doc.one('visibilitychange', () => {\n        this._initDelayedClose();\n      });\n      return;\n    }\n\n    this.delayedClose();\n\n    this.$container.on(\n      'keypress keyup change focus blur click mousedown mouseup',\n      (ev) => {\n        if (ev.target != this.$closeBtn[0]) {\n          this.$container.off(\n            'keypress keyup change focus blur click mousedown mouseup'\n          );\n          this.preventDelayedClose();\n        }\n      }\n    );\n  },\n\n  _negMargin: function () {\n    return `-${this.$container.outerHeight() + 12}px`;\n  },\n\n  close: function () {\n    if (this.closing) {\n      return;\n    }\n\n    if (this.closeTimeout) {\n      clearTimeout(this.closeTimeout);\n      this.closeTimeout = null;\n    }\n\n    this.closing = true;\n\n    if (\n      this.originalActiveElement &&\n      document.activeElement &&\n      (document.activeElement === this.$container[0] ||\n        $.contains(this.$container[0], document.activeElement))\n    ) {\n      $(this.originalActiveElement).focus();\n    }\n\n    this.$container.velocity(\n      {opacity: 0, 'margin-bottom': this._negMargin()},\n      {\n        duration: 'fast',\n        complete: () => {\n          this.$container.remove();\n        },\n      }\n    );\n  },\n\n  delayedClose: function () {\n    this.closeTimeout = setTimeout(() => {\n      this.close();\n    }, Craft.notificationDuration);\n\n    // Hold off on closing automatically on hover\n    this.$container.one('mouseover', () => {\n      clearTimeout(this.closeTimeout);\n      this.closeTimeout = null;\n\n      this.$container.on('mouseout', (ev) => {\n        if (ev.target == this.$container[0]) {\n          this.$container.off('mouseout');\n          this.delayedClose();\n        }\n      });\n    });\n  },\n\n  preventDelayedClose: function () {\n    this._preventDelayedClose = true;\n\n    if (this.closeTimeout) {\n      clearTimeout(this.closeTimeout);\n      this.closeTimeout = null;\n    }\n\n    this.$container.off('mouseover mouseout');\n  },\n});\n\nGarnish.$scrollContainer = Garnish.$win;\nCraft.cp = new Craft.CP();\n\n/**\n * Job progress icon class\n */\nvar JobProgressIcon = Garnish.Base.extend({\n  $li: null,\n  $a: null,\n  $label: null,\n  $progressLabel: null,\n\n  progress: null,\n  failMode: false,\n\n  _$bgCanvas: null,\n  _$staticCanvas: null,\n  _$hoverCanvas: null,\n  _$failCanvas: null,\n\n  _staticCtx: null,\n  _hoverCtx: null,\n  _canvasSize: null,\n  _arcPos: null,\n  _arcRadius: null,\n  _lineWidth: null,\n\n  _arcStartPos: 0,\n  _arcEndPos: 0,\n  _arcStartStepSize: null,\n  _arcEndStepSize: null,\n  _arcStep: null,\n  _arcStepTimeout: null,\n  _arcAnimateCallback: null,\n\n  _progressBar: null,\n\n  init: function () {\n    this.$li = $('<li/>').appendTo(Craft.cp.$nav.children('ul'));\n    this.$a = $('<a/>', {\n      id: 'job-icon',\n      href: Craft.canAccessQueueManager\n        ? Craft.getUrl('utilities/queue-manager')\n        : null,\n    }).appendTo(this.$li);\n    this.$canvasContainer = $('<span class=\"icon\"/>').appendTo(this.$a);\n    var $labelContainer = $('<span class=\"label\"/>').appendTo(this.$a);\n    this.$label = $('<span/>').appendTo($labelContainer);\n    this.$progressLabel = $('<span class=\"progress-label\"/>')\n      .appendTo($labelContainer)\n      .hide();\n\n    let m = window.devicePixelRatio > 1 ? 2 : 1;\n    this._canvasSize = 18 * m;\n    this._arcPos = this._canvasSize / 2;\n    this._arcRadius = 7 * m;\n    this._lineWidth = 3 * m;\n\n    this._$bgCanvas = this._createCanvas('bg', '#61666b');\n    this._$staticCanvas = this._createCanvas('static', '#d7d9db');\n    this._$hoverCanvas = this._createCanvas('hover', '#fff');\n    this._$failCanvas = this._createCanvas('fail', '#da5a47').hide();\n\n    this._staticCtx = this._$staticCanvas[0].getContext('2d');\n    this._hoverCtx = this._$hoverCanvas[0].getContext('2d');\n\n    this._drawArc(this._$bgCanvas[0].getContext('2d'), 0, 1);\n    this._drawArc(this._$failCanvas[0].getContext('2d'), 0, 1);\n  },\n\n  setDescription: function (description, progressLabel) {\n    this.$a.attr('title', description);\n    this.$label.text(description);\n    if (progressLabel) {\n      this.$progressLabel.text(progressLabel).show();\n    } else {\n      this.$progressLabel.hide();\n    }\n  },\n\n  setProgress: function (progress) {\n    if (progress == 0) {\n      this._$staticCanvas.hide();\n      this._$hoverCanvas.hide();\n    } else {\n      this._$staticCanvas.show();\n      this._$hoverCanvas.show();\n      if (this.progress && progress > this.progress) {\n        this._animateArc(0, progress / 100);\n      } else {\n        this._setArc(0, progress / 100);\n      }\n    }\n\n    this.progress = progress;\n  },\n\n  complete: function () {\n    this._animateArc(0, 1, () => {\n      this._$bgCanvas.velocity('fadeOut');\n\n      this._animateArc(1, 1, () => {\n        this.$a.remove();\n        this.destroy();\n      });\n    });\n  },\n\n  showFailMode: function (message) {\n    if (this.failMode) {\n      return;\n    }\n\n    this.failMode = true;\n    this.progress = null;\n\n    this._$bgCanvas.hide();\n    this._$staticCanvas.hide();\n    this._$hoverCanvas.hide();\n    this._$failCanvas.show();\n\n    this.setDescription(message);\n  },\n\n  hideFailMode: function () {\n    if (!this.failMode) {\n      return;\n    }\n\n    this.failMode = false;\n\n    this._$bgCanvas.show();\n    this._$staticCanvas.show();\n    this._$hoverCanvas.show();\n    this._$failCanvas.hide();\n  },\n\n  _createCanvas: function (id, color) {\n    var $canvas = $(\n        '<canvas id=\"job-icon-' +\n          id +\n          '\" width=\"' +\n          this._canvasSize +\n          '\" height=\"' +\n          this._canvasSize +\n          '\"/>'\n      ).appendTo(this.$canvasContainer),\n      ctx = $canvas[0].getContext('2d');\n\n    ctx.strokeStyle = color;\n    ctx.lineWidth = this._lineWidth;\n    ctx.lineCap = 'round';\n    return $canvas;\n  },\n\n  _setArc: function (startPos, endPos) {\n    this._arcStartPos = startPos;\n    this._arcEndPos = endPos;\n\n    this._drawArc(this._staticCtx, startPos, endPos);\n    this._drawArc(this._hoverCtx, startPos, endPos);\n  },\n\n  _drawArc: function (ctx, startPos, endPos) {\n    ctx.clearRect(0, 0, this._canvasSize, this._canvasSize);\n    ctx.beginPath();\n    ctx.arc(\n      this._arcPos,\n      this._arcPos,\n      this._arcRadius,\n      (1.5 + startPos * 2) * Math.PI,\n      (1.5 + endPos * 2) * Math.PI\n    );\n    ctx.stroke();\n    ctx.closePath();\n  },\n\n  _animateArc: function (targetStartPos, targetEndPos, callback) {\n    if (this._arcStepTimeout) {\n      clearTimeout(this._arcStepTimeout);\n    }\n\n    this._arcStep = 0;\n    this._arcStartStepSize = (targetStartPos - this._arcStartPos) / 10;\n    this._arcEndStepSize = (targetEndPos - this._arcEndPos) / 10;\n    this._arcAnimateCallback = callback;\n    this._takeNextArcStep();\n  },\n\n  _takeNextArcStep: function () {\n    this._setArc(\n      this._arcStartPos + this._arcStartStepSize,\n      this._arcEndPos + this._arcEndStepSize\n    );\n\n    this._arcStep++;\n\n    if (this._arcStep < 10) {\n      this._arcStepTimeout = setTimeout(this._takeNextArcStep.bind(this), 50);\n    } else if (this._arcAnimateCallback) {\n      this._arcAnimateCallback();\n    }\n  },\n});\n"],"names":["Craft","Accordion","Garnish","Base","extend","$trigger","targetSelector","_$target","init","trigger","this","$","data","console","warn","destroy","attr","addListener","event","key","keyCode","SPACE_KEY","RETURN_KEY","preventDefault","onTriggerClick","hideTarget","showTarget","$target","length","_currentHeight","height","removeClass","addClass","i","$t","prop","_targetHeight","css","overflow","velocity","getUserPreferredAnimationDuration","eq","$win","hasClass","removeData","base","AddressesInput","$container","$addBtn","$addBtnItem","$cards","container","settings","setSettings","defaults","find","closest","initCard","updateAddButton","createAddress","$card","ev","target","editAddress","$actionBtn","disclosureMenu","menu","$menu","$editBtn","stopPropagation","$deleteBtn","confirm","t","addressId","draftId","sendActionRequest","elementId","then","remove","not","createElementEditor","on","id","response","$newCard","html","replaceWith","insertBefore","initUiElements","add","canCreateAddress","maxAddresses","elementType","ownerId","element","AdminTable","totalItems","sorter","$noItems","$table","$tbody","$deleteBtns","allowDeleteAll","minItems","noItemsSelector","tableSelector","children","sortable","DataTableSorter","onSortChange","reorderItems","bind","handleDeleteBtnClick","updateUI","addRow","row","maxItems","$row","appendTo","addItems","ids","$items","idAttribute","push","JSON","stringify","reorderAction","onReorderItems","cp","displaySuccess","reorderSuccessMessage","displayError","reorderFailMessage","confirmDeleteItem","deleteItem","confirmDeleteMessage","name","getItemName","getItemId","deleteAction","handleDeleteItemSuccess","handleDeleteItemFailure","deleteFailMessage","removeItems","onDeleteItem","deleteSuccessMessage","escapeHtml","nameAttribute","hide","show","$moveButtons","newItemBtnSelector","noop","AssetImageEditor","Modal","$body","$footer","$imageTools","$buttons","$cancelBtn","$replaceBtn","$saveBtn","$focalPointBtn","$editorContainer","$straighten","$croppingCanvas","$spinner","$constraintContainer","$constraintRadioInputs","$customConstraints","canvas","image","viewport","focalPoint","grid","croppingCanvas","clipper","croppingRectangle","cropperHandles","cropperGrid","croppingShade","imageStraightenAngle","viewportRotation","originalWidth","originalHeight","imageVerticeCoords","zoomRatio","animationInProgress","currentView","assetId","cacheBust","draggingCropper","scalingCropper","draggingFocal","previousMouseX","previousMouseY","shiftKeyHeld","editorHeight","editorWidth","cropperState","scaleFactor","flipData","focalPointState","maxImageSize","lastLoadedDimensions","imageIsLoading","mouseMoveEvent","croppingConstraint","constraintOrientation","showingCustomConstraint","saving","renderImage","renderCropper","_queue","Queue","Date","now","allowDegreeFractions","isImagick","prefersReducedMotion","animationDuration","x","y","$bod","type","class","text","allowSavingAsNew","ui","createButton","label","spinner","saveImage","createSubmitButton","removeListener","$shade","getMaxImageSize","loadEditor","browserViewportWidth","$doc","get","documentElement","clientWidth","browserViewportHeight","clientHeight","Math","max","window","devicePixelRatio","$tabs","$viewsContainer","$views","innerHeight","innerWidth","_showSpinner","updateSizeAndPosition","$customConstraintWrapper","filter","parent","append","size","value","val","test","fabric","StaticCanvas","width","enableRetinaScaling","requestAnimationFrame","renderAll","imageUrl","getActionUrl","Image","fromURL","imageObject","set","originX","originY","left","top","getHeight","getWidth","getScaledImageDimensions","_setFittedImageVerticeCoordinates","_repositionEditorElements","focalState","imageDimensions","offsetX","offsetY","focal","focalData","adjustedX","adjustedY","storeFocalPointState","_createFocalPoint","_createViewport","storeCropperState","_addControlListeners","_handleMouseMove","_handleMouseDown","_handleMouseUp","_handleMouseOut","_hideSpinner","first","_reloadImage","setSrc","outerHeight","previousEditorDimensions","setDimensions","currentScaledDimensions","getZoomToFitRatio","previouslyOccupiedArea","_getBoundingRectangle","_repositionCropper","getZoomToCoverRatio","_repositionImage","_repositionViewport","_repositionFocalPoint","_zoomImage","Rect","fill","globalCompositeOperation","sizeFactor","focalX","focalY","deltaX","deltaY","Group","Circle","radius","strokeWidth","stroke","toggleFocalPoint","dimensions","state","currentWidth","ratio","hasOrientationChanged","_","imageRatio","editorRatio","min","round","_getPrevTab","newTabIndex","activeTabIndex","_getActiveTabIndex","_getNextTab","_getActiveTab","$activeTab","index","_handleTabClick","LEFT_KEY","UP_KEY","$prevTab","activateTab","RIGHT_KEY","DOWN_KEY","$nextTab","rotateImage","flipImage","straighteningInput","SlideRuleInput","onStart","_showGrid","onChange","slider","straighten","onEnd","_hideGrid","_cleanupFocalPointAfterStraighten","SHIFT_KEY","_handleConstraintChange","_handleOrientationClick","_applyCustomConstraint","_handleConstraintClick","constraint","currentTarget","siblings","_showCustomConstraint","_hideCustomConstraint","setCroppingConstraint","enforceCroppingConstraint","$constraints","$constraint","labelSelector","$label","split","reverse","join","replace","_getCustomConstraint","w","h","parseFloat","isNaN","_setCustomConstraint","$tab","tab","view","tabindex","showView","enableSlider","disableSlider","Promise","resolve","reject","disableCropMode","enableCropMode","zoomFactor","degrees","parseInt","imageZoomRatio","newAngle","angle","scaledImageDimensions","viewportProperties","imageProperties","angleInRadians","PI","newDeltaX","cos","sin","newDeltaY","modifiedDeltaX","modifiedDeltaY","temp","animate","duration","onComplete","cleanAngle","_adjustFocalPointByAngle","_resetFocalPointPosition","axis","editorCenter","setValue","properties","scaleY","scaleX","previousAngle","_adjustEditorElementsOnStraighten","newCenterX","newCenterY","angleDelta","currentZoomRatio","adjustmentRatio","cropperCenterX","cropperCenterY","imageVertices","getImageVerticeCoords","rectangle","_getZoomRatioToFitRectangle","_isCenterInside","opacity","object","containingObject","newFocalX","newFocalY","adjustedFocalX","adjustedFocalY","containingVertices","vertex","rectangleVertices","_getRectangleVertices","verticeIndex","arePointsInsideRectangle","edge","_getEdgeCrossed","rectangleCenter","distanceFromVertexToEdge","abs","sqrt","pow","distanceFromCenterToEdge","$button","postData","imageRotation","cropData","zoom","onSave","broadcaster","postMessage","runQueue","Preview","refresh","message","scaledWidth","scaledHeight","boundingBox","_getImageBoundingBox","scale","vertScale","horiScale","getCombinedZoomRatio","strokeOptions","gridWidth","gridHeight","xStep","yStep","Line","onFadeOut","removeAllListeners","_editorModeTransition","cropperData","_showCropper","_hideCropper","targetZoom","inverseZoomFactor","imageOffsetX","imageOffsetY","callback","pause","resume","clipperData","_setupCropperLayer","_redrawCropperElements","backgroundColor","hoverCursor","selection","position","rectangleRatio","rectWidth","rectHeight","lineOptions","gridOptions","pathGroup","Path","cropTextTop","cropTextBackgroundColor","previousImageArea","currentOffset","areaFactor","coordinateSet","a","b","c","d","_isMouseOver","move","handle","_cropperHandleHitTest","pageX","pageY","_handleMouseMoveInternal","_handleFocalDrag","_handleCropperDrag","_handleCropperResize","_setMouseCursor","vertices","dxi","dyi","furthest","furthestDeltas","newX","newY","previousHeight","previousWidth","startingRectangle","_calculateNewCropperSizeByDeltas","cropperDirection","topDelta","leftDelta","change","match","isMobileBrowser","cursor","parentOffset","offset","mouseX","mouseY","lb","rb","tb","bb","topLeft","topRight","bottomRight","bottomLeft","zoomMode","topVerticalSegment","bottomVerticalSegment","rightHorizontalSegment","leftHorizontalSegment","verticalOffset","horizontalOffset","_debug","fabricObj","points","ab","_getVector","bc","scalarAbAb","_getScalarProduct","scalarBcBc","point","ap","bp","scalarAbAp","scalarBcBp","projectsOnAB","projectsOnBC","_getVectorMagnitude","vector","_getAngleBetweenVectors","acos","edgePoints","centerPoint","smallestDiff","edgeCrossed","edgeIndex","toCenter","edgeVector","toVertex","diff","box","proportion","AssetIndex","BaseElementIndex","$includeSubfoldersContainer","$includeSubfoldersCheckbox","showingIncludeSubfoldersCheckbox","$uploadButton","$uploadInput","$progressBar","uploader","promptHandler","progressBar","$listedFolders","itemDrag","_uploadTotalFiles","_uploadFileProgress","_currentUploaderSettings","Object","assign","context","DragDrop","activeDropTargetClass","minMouseDist","hideDraggee","moveHelperToCursor","item","$targetItem","elementSelect","selectItem","_findDraggableItems","getSelectedElements","$item","$dropTargets","$visibleSources","toArray","source","hasAttr","sourcePath","$source","step","folderId","$btn","$draggee","targetFolderId","_targetFolderId","$activeDropTarget","returnHelpersToDraggees","fadeOutHelpers","$folders","$assets","folderIds","map","assetIds","mover","AssetMover","moveFolders","totalFoldersMoved","moveAssets","totalAssetsMoved","totalItemsMoved","displayNotice","elementIndex","updateElements","$main","modal","_positionProgressBar","$dropTarget","is","afterInit","foldersOnly","initForFiles","style","addButton","PromptHandler","ProgressBar","options","url","fileInput","dropZone","events","fileuploadstart","_onUploadStart","fileuploadprogressall","_onUploadProgress","fileuploaddone","_onUploadSuccess","fileuploadalways","_onUploadAlways","fileuploadfail","_onUploadFailure","criteria","kind","allowedKinds","Uploader","isIndexBusy","onSelectSource","setParams","onSourcePathChange","currentFolder","canMoveSubItems","selectable","multiSelect","startSearching","hideSidebar","hasChildren","floor","random","insertAfter","$search","$subContainer","setSelecetedSourceState","checked","getSelectedSourceState","marginBottom","stopSearching","complete","getViewSettings","canSelectElement","getViewParams","showFolders","trashed","includeSubfolders","setIndexBusy","resetProgressBar","showProgressBar","resetPrompts","progress","loaded","total","setProgressPercentage","result","selectElementAfterUpdate","conflict","prompt","file","filename","choices","title","addPrompt","isLastUpload","hideProgressBar","setIndexAvailable","getPromptCount","showBatchPrompts","_uploadFollowup","_updateAfterUpload","jqXHR","responseJSON","clearSearch","setSelectedSortAttribute","returnData","setItemCount","doFollowup","parameterArray","parameterIndex","action","followupAlways","incrementProcessedItemCount","updateProgressBar","followupSuccess","choice","sourceAssetId","conflictingAssetId","targetFilename","followupFailure","onUpdateElements","_onUpdateElements","getAllElements","newElements","$newElements","$elements","_onKeyDown","_onElementFocus","$folder","$title","folderName","disabledFolderIds","includes","has","$a","href","getCpUrl","uri","role","empty","firstFocusableEl","focus","removeAllItems","shiftKey","PreviewFileModal","openInstance","selfDestruct","$element","$focusedItem","_loadPreview","startingWidth","startingHeight","getSourcePathLabel","getSourcePathActionLabel","getSourcePathActions","actions","canCreate","onSelect","_createSubfolder","canRename","_renameFolder","canMove","getMoveTargetSourceKeys","_moveFolder","canDelete","destructive","_deleteFolder","subfolderName","parentId","folder","slice","newName","peerFiles","$sources","volumeHandle","parentFolder","VolumeFolderSelectorModal","sources","showTitle","modalTitle","selectBtnLabel","indexSettings","defaultSource","sourceKey","defaultSourcePath","targetFolder","$sourcePathActionsBtn","scrollTop","windowHeight","registerElementIndexClass","requests","for","params","_batchMoveRequests","conflictChoices","handleConflictChoice","request","force","suggestedFilename","transferList","folderIdsToDelete","onSuccess","merge","totalMoved","_processTransferList","_deleteFolders","_batchRequests","responses","success","error","prompts","nextRequests","nextRequest","nextTotalMoved","activeRequests","failure","AssetSelectInput","BaseElementSelectInput","$uploadBtn","openPreviewTimeout","apply","arguments","canUpload","_attachUploader","updateAddElementsBtn","$elementsContainer","openPreview","onAddElements","clearOpenPreviewTimeout","setTimeout","clearTimeout","minGutter","formData","fieldId","sourceElementId","siteId","$addElementBtn","limit","describedBy","multiple","csrfTokenName","csrfTokenValue","canAddMoreFiles","_onUploadComplete","next","enableAddElementsBtn","disableAddElementsBtn","selectUploadedFile","canAddMoreElements","$newElement","prepend","margin","outerWidth","animateCss","addElements","parameters","thumbSize","viewMode","appendHeadHtml","headHtml","getElementInfo","slotsTaken","AssetSelectorModal","BaseElementSelectorModal","$selectTransformBtn","_selectedTransform","transforms","createSelectTransformButton","$btnGroup","$primaryButtons","$selectBtn","$menuList","MenuButton","MenuBtn","onOptionSelect","onSelectTransform","disable","onSelectionChange","$selectedElements","allowTransforms","enable","option","transform","selectImagesWithTransform","transformUrls","imageIdsWithMissingUrls","showFooterSpinner","fetchMissingTransformUrls","hideFooterSpinner","selectElements","pop","info","elementInfo","canSelectImageTransforms","registerElementSelectorModalClass","AssetsFieldSettings","$useSingleFolderInput","$sourceInputs","$defaultUploadLocationSelect","$defaultUploadLocationOptions","useSingleFolderToggleId","sourcesFieldId","defaultUploadLocationId","updateDefaultUploadLocationSelect","firstEnabledValue","defaultUploadLocationVal","$input","getOption","$selectedOption","AuthManager","remainingSessionTime","checkRemainingSessionTimer","showLoginModalTimer","decrementLogoutWarningInterval","showingLogoutWarningModal","showingLoginModal","logoutWarningModal","loginModal","$logoutWarningPara","$passwordInput","$loginBtn","$loginErrorPara","submitLoginIfLoggedOut","username","updateRemainingSessionTime","setCheckRemainingSessionTimer","seconds","checkRemainingSessionTime","extendSession","ajax","dataType","textStatus","timeout","minSafeSessionTime","showLogoutWarningModal","checkInterval","showLoginModal","submitLogin","hideLogoutWarningModal","hideLoginModal","quickShow","$form","$logoutBtn","$renewSessionBtn","prependTo","autoShow","closeOtherModals","hideOnEsc","hideOnShadeClick","shadeClass","onFadeIn","updateLogoutWarningMessage","setInterval","decrementLogoutWarning","time","secondsToHumanTimeDuration","clearInterval","quick","quickHide","$inputContainer","$inputsFlexContainer","$passwordContainer","$buttonContainer","$passwordWrapper","PasswordInput","onToggleInput","$newPasswordInput","logout","redirectTo","renewSession","validatePassword","removeAttr","login","clearLoginError","loginName","password","showLoginError","shake","initialized","idPrefix","instanceState","sourceStates","sourceStatesStorageKey","searchTimeout","sourceSelect","$sidebar","showingSidebar","rootSourceKey","sourceViewModes","$rootSource","sourcesByKey","$sourceActionsContainer","$sourceActionsBtn","$toolbar","toolbarOffset","$searchContainer","$filterBtn","searching","searchText","sortByScore","drafts","$clearSearchBtn","$statusMenuBtn","$statusMenuContainer","statusMenu","status","$siteMenuBtn","siteMenu","_sourcePath","$sourcePathOuterContainer","$sourcePathInnerContainer","$sourcePathOverflowBtnContainer","$updateSpinner","$viewModeBtnContainer","viewModeBtns","_viewMode","_autoSelectElements","$countSpinner","$countContainer","$actionsContainer","page","resultSet","totalResults","$exportBtn","actionsHeadHtml","actionsBodyHtml","$selectAllContainer","$selectAllCheckbox","showingActionTriggers","exporters","exportersByType","_$triggers","_cancelToken","viewMenus","activeViewMenu","filterHuds","_activeElement","canSortByStructure","randomString","getDefaultInstanceState","storageKey","getLocalStorage","toolbarSelector","initSources","menubtn","_handleStatusChange","$option","$options","_setSite","_handleSiteChange","defaultSiteId","getSiteId","$storedSiteOption","updateElementsIfSearchTextChanged","queryParams","getQueryParams","selector","selectOption","setQueryParam","selectDefaultSource","getDefaultSourcePath","handleResize","search","sort","lastDashPos","lastIndexOf","substring","dir","setPage","pageNum","onAfterInit","showSourcePath","_updateSourcePathVisibility","_createCancelToken","axios","CancelToken","token","_cancelRequests","cancel","getSourceContainer","getSite","sites","s","_getSourcesInList","Select","multi","allowEmpty","vertical","_handleSourceSelectionChange","initSource","getQueryParam","getDefaultSourceKey","getSourceByKey","selectSource","refreshSources","refreshSourcesAction","e","isCancel","initSourceToggle","expandedSources","indexOf","_expandSource","deinitSourceToggle","$toggle","_getSourceToggle","deinitSource","selectedSource","$lastSource","segment","testSourceKey","_collapseSource","undefined","canView","getDefaultExpandedSources","$overflowBtn","overflowMenuId","$overflowUl","$nav","$ol","$overflowMenu","$overflowLi","icon","selectSourcePathStep","isFirst","isLast","$li","$btnBody","actionBtnLabel","menuId","groupedActions","administrative","group","forEach","_buildSourcePathActionList","history","replaceState","firstStep","lastStep","overage","_checkSourcePathOverage","getBoundingClientRect","$ul","num","updateSortField","setInstanceState","storeInstanceState","setLocalStorage","getSourceState","defaultValue","viewState","k","hasOwnProperty","storeSortAttributeAndDirection","getPageUrl","_resetCount","updateSourceMenu","getSourceActions","_buildActionList","userIsAdmin","allowAdminChanges","createCustomizeSourcesModal","updateViewMenu","hideTrigger","ViewMenu","showTrigger","batchSize","canHaveDrafts","savedDraftsOnly","draftOf","currentStep","condition","referenceElementId","referenceElementSiteId","disabledElementIds","paginated","_isViewPaginated","mode","order","collapsedElementIds","getSortAttributeAndDirection","sortAttribute","sortDirection","serialized","filters","preservePagination","pageChanged","updateElementsAction","cancelToken","fixedHeader","headerContainerHeight","$headerContainer","maxScrollTop","$scrollContainer","_updateView","$elementContainer","getElementContainer","firstFocusableElement","showActionTriggers","_createTriggers","submitAction","actionParams","selectedElementIds","getSelectedElementIds","_findAction","viewParams","expandPostArray","elementAction","elementIds","download","downloadFromUrl","submitActionsAction","badgeCounts","_updateBadgeCounts","afterAction","actionClass","onAfterAction","hideActionTriggers","detach","updateActionTriggers","totalSelected","getEnabledElements","setStatus","getSelectedSortAttribute","getRootSource","attribute","getSortOption","getDefaultSort","getSelectedSortDirection","direction","setSortAttribute","sortOption","defaultDir","attributes","lastAttr","oldHistory","orderHistory","setSortDirection","setSelectedSortDirection","getSortLabel","getSelectedViewMode","getSourceLevel","parentsUntil","getParentSource","$parent","keys","updateContentHeading","$firstOption","getViewModesForSource","sourceViewMode","$viewModeBtn","className","selectViewMode","doesSourceHaveViewMode","updateFilterBtn","urlParams","setUrl","getUrl","path","selectSourceByKey","getSortOptions","sortOptions","o","defaultSort","getTableColumnOptions","getTableColumnOption","getDefaultTableColumns","getSelectedTableColumns","setSelectedTableColumns","tableColumns","updateTableColumnField","viewModes","orientation","createView","getViewClass","TableElementIndexView","ThumbsElementIndexView","rememberDisabledElementId","inArray","forgetDisabledElementId","splice","enableElements","parents","onEnableElements","disableElements","onDisableElements","getElementById","enableElementsById","makeArray","disableElementsById","getButtonContainer","isShowingSidebar","buttonContainer","document","activeElement","contains","blur","elementsHeight","scrollParent","positionTop","setProperty","body","CustomizeSourcesModal","onHide","onSelectSite","elements","$selectedItems","_handleActionTriggerSubmit","getPostData","_handleMenuActionTriggerSubmit","selectedOption","queryParam","firstSite","updateSourceVisibility","$heading","$headings","setSiteId","toString","_handleSelectionChange","_handleSourceDblClick","_toggleSource","_handleSourceToggleClick","prev","$list","topLevel","_getChildSources","$childSources","_countResults","itemLabel","elementTypeNames","elementTypeName","toLowerCase","itemsLabel","elementTypePluralName","last","countLabel","items","$paginationContainer","totalPages","ceil","$paginationNav","$prevBtn","disabled","$nextBtn","appendBodyHtml","bodyHtml","selectAllElements","deselectAllElements","checkboxMode","selectElementById","$badge","countElementsAction","count","triggers","safeMenuActions","destructiveMenuActions","formatInputId","$menuTrigger","$safeList","_createMenuTriggerList","$destructiveList","$div","_showExportHud","typeOptions","$typeField","createSelectField","$formatField","$typeSelect","formattable","$limitField","createTextField","placeholder","$submitBtn","$exportSubmit","MultiFunctionBtn","HUD","submitting","busyEvent","format","successEvent","showFilterHud","FilterHud","showing","hasRules","$sortField","$sortAttributeSelect","$sortDirectionPicker","sortDirectionListbox","$tableColumnsField","$tableColumnsContainer","$revertContainer","$revertBtn","$closeBtn","_buildMenu","DisclosureMenu","tidyTableColumnField","FX_DURATION","$scoreOption","select","$lastContainer","lastIndex","$checkbox","$checkboxes","_getTableColumnCheckboxes","defaultOrder","column","reduce","obj","checkboxA","checkboxB","revert","$metaContainer","_createSortField","_createTableColumnsField","$footerContainer","_createRevertBtn","$sortAttributeSelectContainer","createSelect","Listbox","$field","createField","fieldset","columns","createCheckbox","DragSort","_onTableColumnChange","$selectedCheckboxes","compare","loading","$clearBtn","cleared","$loadingContent","hudClass","$hud","$tip","hudHtml","$btnContainer","clear","setBusy","setReady","setFocus","elem","func","setFocusWithin","updateSizeAndPositionInternal","hudHeight","searchOffset","availableSpace","bottom","overflowY","onShow","serialize","BaseElementIndexView","$loadingMoreSpinner","$scroller","loadingMore","_totalVisible","_morePending","_handleEnableElements","_handleDisableElements","thumbLoader","elementThumbLoader","setTotalVisible","setMorePending","load","isVerticalList","_handleElementEditing","maybeLoadMore","selectElement","selectAll","deselectAll","getElementCheckbox","getTotalVisible","totalVisible","getMorePending","morePending","canLoadMore","loadMore","loadMoreElementsAction","getLoadMoreParams","appendElements","onAppendElements","each","isSelected","off","elementSort","elementEditor","_initialized","isPlainObject","normalizedSettings","args","modalStorageKey","maintainHierarchy","getContainer","getElementsContainer","getAddElementsBtn","getSpinner","initElementSelect","initElementSort","resetElements","getElements","getSelectedItems","ignoreHandleSelector","getElementSortAxis","collapseDraggees","magnetStrength","helperLagBase","resetItemOrder","updateButtonContainer","showSpinner","hideSpinner","focusNextLogicalElement","focusLastRemoveBtn","$removeBtns","removeElements","editable","_handleShowElementEditor","isTouchCapable","removeElement","BACKSPACE_KEY","DELETE_KEY","elementSelectInput","prevalidate","replaceElement","replacementId","$existing","$nextDeleteBtn","lastElementIndex","onRemoveElements","$allElements","_animateStructureElementAway","animateElementAway","right","REMOVE_FX_DURATION","showModal","createModal","createElementSelectorModal","getModalSettings","hideOnSelect","showSiteMenu","getDisabledElementIds","onModalSelect","onModalHide","triggerElement","modalSettings","allowSelfRelations","selectStructuredElements","slotsLeft","updateDisabledElementsInModal","createNewElement","appendElement","animateElementIntoPlace","onSelectElements","disableCancelBtn","disableSelectBtn","containerId","branchLimit","selectionLabel","onResponse","enableCancelBtn","enableSelectBtn","$newElementsContainer","filteredElements","clone","removeText","setElementSize","single","$modalElement","$inputElement","origOffset","destOffset","$helper","zIndex","ADD_FX_DURATION","editorSettings","supportSidebarToggleView","$content","$sourceToggles","$sidebarToggleBtn","$sidebarCloseBtn","$mainHeading","$secondaryButtons","headingId","$headingContainer","fullscreen","updateModalBottomPadding","footerHeight","updateSidebarView","sidebarShouldBeHidden","buildSidebarToggleView","resetView","$mainHeader","$sidebarHeader","getActiveSourceName","toggle","controls","closeSidebar","toggleSidebar","sidebarIsOpen","openSidebar","uiLayerManager","addLayer","registerShortcut","ESC_KEY","$focusedEl","getFocusedElement","removeLayer","_createElementIndex","updateSelectBtnState","updateHeading","hasSelection","clearMouseUpTimeout","disableElementsOnSelect","getElementIndexParams","bodyAction","createElementIndex","getIndexSettings","touchData","firstTap","secondTap","getItemIndex","resizable","onCancel","BaseInputGenerator","listening","startListening","setNewSource","stopListening","onSourceTextChange","updateTarget","onTargetTextChange","onFormSubmit","sourceVal","targetVal","generateTargetValue","dispatchEvent","InputEvent","inputType","Event","selectFullValue","CategoryIndex","editableGroups","$newCategoryBtnGroup","$newCategoryBtn","updateButton","editableCategoryGroups","g","uid","defaultGroupHandle","selectedSourceHandle","$menuBtn","selectedGroup","visibleLabel","ariaLabel","isCtrlKeyPressed","originalEvent","button","open","_createCategory","$menuContainer","anchorRole","setPath","groupId","location","cpEditUrl","fresh","groupSourceKey","CategorySelectInput","selectedCategoryIds","categoryIds","$allCategories","_animateCategoryAway","charts","DataTable","rows","cellIndex","parseTime","d3","timeParse","Tip","setContent","setPosition","BaseChart","$chart","chartBaseClass","dataTable","formatLocale","timeFormatLocale","svg","globalSettings","formats","d3Formats","formatLocaleDefinition","d3FormatLocaleDefinition","timeFormatLocaleDefinition","d3TimeFormatLocaleDefinition","resize","baseSettings","draw","chartClass","onAfterDrawTicks","tickKey","tick","$tickText","numberFormat","percentFormat","currencyFormat","shortDateFormats","day","month","year","colors","Area","tip","drawingArea","getChartMargin","translateX","translateY","drawTicks","drawAxes","drawChart","drawTipTriggers","getX","xAxis","axisBottom","tickFormat","getXFormatter","ticks","call","yAxis","getY","axisLeft","getYFormatter","tickValues","getYTickValues","axisRight","showAxis","tickSizeOuter","gridlines","xLineAxis","tickSize","yLineAxis","line","datum","area","y0","y1","plots","enter","tips","chartMargin","xAxisTickInterval","node","getTotalLength","tipTriggerWidth","$xValue","$yValue","content","values","yTicksMaxWidth","computedTickWidth","formatter","padded","xDomainMin","xDomainMax","xDomain","scaleTime","range","domain","yDomain","getYMaxValue","scaleLinear","utils","getTimeFormatter","getNumberFormatter","maxValue","getDuration","secondsNum","hours","minutes","chartSettings","dataScale","ColorInput","$colorContainer","$colorPreview","$colorInput","createColorInput","handleTextChange","input","createElement","setAttribute","updateColor","trim","repeat","_browserSupportsColorInputs","doesBrowserSupportColorInputs","CpScreenSlideout","Slideout","namespace","showingLoadSpinner","hasTabs","hasCpLink","hasSidebar","$header","$tabContainer","$loadSpinner","$editLink","$sidebarBtn","$noticeContainer","tabManager","ignoreFailedRequest","fieldsWithErrors","ltr","showSidebar","$contents","containerElement","containerAttributes","method","novalidate","closeOnEsc","closeOnShadeClick","S_KEY","ctrl","handleSubmit","closeMeMaybe","refreshInitialData","showLoadSpinner","getParams","headers","requestOptions","update","deltaNames","initialDeltaValues","hideLoadSpinner","updateHeaderVisibility","forceShow","showHeader","submitButtonLabel","updateTabs","tabs","formAttributes","setElementAttributes","editUrl","sidebar","hostname","notice","Tabs","_closedSidebarStyles","offsetWidth","_openedSidebarStyles","one","trapFocusWithin","showSubmitSpinner","hideSubmitSpinner","submit","findDeltaData","handleSubmitResponse","handleSubmitError","clearErrors","notificationSettings","modelName","closeOnSubmit","close","isAxiosError","errors","showErrors","entries","fieldErrors","addErrorsToField","clearErrorsFromField","isDirty","isOpen","rxhtmlTag","jQuery","htmlPrefilter","navHeight","arr","isArray","grouped","thisKey","category","translations","formatMessage","pattern","tokens","_tokenizePattern","_parseToken","start","pos","depth","chars","param","arg","number","formatNumber","plural","selectorChars","p","formatDate","date","datepicker","datepickerOptions","dateFormat","shortcutText","shift","alt","clientOs","str","escapeRegex","getText","encodeUriComponent","encodeURIComponent","differences","chr","re","RegExp","setSelectionRange","inputName","rtrim","baseUrl","anchor","anchorPos","fromEntries","URLSearchParams","qsPos","isEmptyObject","pathParam","pathMatch","omitScriptNameInUrls","usePathInfo","scriptName","baseCpUrl","getSiteUrl","baseSiteUrl","actionUrl","hash","origin","pathname","qs","pageTrigger","pageParam","getCsrfInput","postActionRequest","contentType","_actionHeaders","errorThrown","readyState","alert","send","registeredAssetBundles","registeredJsFiles","toUpperCase","actionName","namespaceInputName","v","getTime","sendApiRequest","_getApiHeaders","apiHeaders","baseURL","baseApiUrl","apiParams","_apiHeaders","processCraftHeaders","httpProxy","proxy","apiResponse","_processApiHeaders","_loadingApiHeaders","_apiHeaderWaitlist","_rejectApiRequests","clearCachedApiHeaders","XMLHttpRequest","setRequestHeader","responseType","onload","disposition","getResponseHeader","matches","exec","blob","Blob","link","URL","createObjectURL","appendChild","click","removeChild","stringToArray","oldData","newData","modifiedDeltaNames","groupedOldParams","_groupParamsByDeltaNames","groupedNewParams","__root__","n","concat","withRoot","initialValues","encodeURIComponentExceptEqualChar","decodeURIComponent","paramLoop","paramName","serializeParam","subName","expanded","m","unshift","parentElem","createForm","chunks","obj1","obj2","sortObjectKeys","Array","getObjectKeys","escapeChars","escaped","ltrim","startsWith","substr","filterArray","filtered","removeFromArray","getLast","uppercaseFirst","charAt","lowercaseFirst","parseUrl","scheme","host","port","query","Proxy","searchParams","isSameHost","requestUrlInfo","urlInfo","showSeconds","secondsInWeek","weeks","days","timeComponents","asciiString","charMap","normalize","char","asciiStr","asciiCharMap","uuid","crypto","randomUUID","getRandomValues","Uint8Array","namespaceId","createErrorList","$existingCss","existingCss","regexp","$existingJs","src","existingJs","appendFootHtml","infoicon","checkboxselect","fieldtoggle","lightswitch","nicetext","formsubmit","datetime","datetimeinput","_elementIndexClasses","_elementSelectorModalClasses","_elementEditorClasses","registerElementEditorClass","ElementEditorSlideout","systemUid","localStorage","parse","removeLocalStorage","removeItem","getCookie","cookie","setCookie","defaultCookieOptions","maxAge","expires","toUTCString","secure","removeCookie","hasThumb","otherSize","$oldImg","$newImg","sizes","srcset","picturefill","submitForm","redirect","retainScroll","scrollY","filterInputVal","regex","selectionStart","newVal","filterNumberInputVal","dataAttributes","subValue","isVisible","visibilityState","useMobileStyles","pageId","BroadcastChannel","channelName","appId","messageReceiver","addEventListener","instances","elementHtml","$replacement","$inputs","fn","animateLeft","easing","animateRight","$elem","itemSelector","cols","maxCols","minColWidth","fillMode","colClass","snapToGrid","Grid","InfoIcon","CheckboxSelect","FieldToggle","settingName","settingValue","thisSettings","indeterminateValue","LightSwitch","NiceText","$anchor","customTrigger","menuAnchor","$wrapper","checkValue","hasValue","charsLeftHtml","charsLeft","ready","$elementIndexSourcesContainer","$sourcesContainer","$sourcesHeader","$sourcesHeading","$sourceSettingsContainer","$sourceSettingsHeader","$addSourceMenu","addSourceMenu","$footerBtnContainer","$loadingSpinner","sourceSort","baseSortOptions","availableTableAttributes","customFieldAttributes","conditionBuilderHtml","conditionBuilderJs","userGroups","setContainer","buildModal","defaultSortOptions","addSource","$menuBtnContainer","sourceData","scrollContainerToElement","$newHeadingBtn","focusLabelInput","$newCustomSourceBtn","tableAttributes","$labelInput","getSourceName","focusIsInside","currentLayer","isNew","$itemLabel","$itemInput","Heading","updateItemLabel","heading","Source","CustomSource","save","disabledSourceKeys","reload","appendIndexSourceItem","$sourceItem","$lastSourceItem","isHeading","$lastTopLevelSource","BaseSource","$settingsContainer","handleActivatingKeypress","isNative","deselect","createSettings","getIndexSourceItem","$sortDirectionInput","createLightswitchField","createSortField","createTableAttributesField","handleSortAttributeChange","useDefaultDir","$columnCheckboxes","selectedAttributes","createTableColumnOption","instructions","$labelField","defaultId","swapPlaceholders","createCheckboxSelectField","showAllOption","handleLabelInputChange","table","$rows","helper","getHelper","caboose","Y_AXIS","$helperRow","helperClass","$cells","$helperCells","DeleteUserModal","userId","$deleteActionRadios","$deleteSubmitBtn","userSelect","_deleting","idParam","contentSummary","_submitBtnLabel","validateDeleteInputs","withContent","validates","onSubmit","DynamicGenerator","EditableTable","baseName","biggestId","$addRowBtn","$tableParent","$statusMessage","rowCount","hasMaxRows","hasMinRows","radioCheckboxes","copyDraggeeInputValuesToHelper","updateAllRows","initialize","initializeIfVisible","minRows","createRowObj","updateAddRowButton","canAddRow","staticRows","updateRow","canDeleteRow","updateDeleteRowButton","rowId","updateStatusMessage","allowDelete","deleteRow","$tr","onDeleteRow","allowAdd","maxRows","rowIdPrefix","createRow","defaultValues","onAddRow","allowReorder","Row","focusOnPrevRow","tdIndex","blurTd","prevRow","$prevTr","$tds","focusOnNextRow","nextRow","$nextTr","importData","lines","j","textualColTypes","colId","$cell","col","scope","code","small","createDateInput","createLightswitch","createTimeInput","createTextInput","niceTexts","tds","$textareas","tr","td","$textarea","textareasByColId","onHeightChange","onTextareaHeightChange","radioMode","applyToggleCheckbox","autopopulate","HandleGenerator","allowNonAlphaStart","onTextareaFocus","onRadioCheckboxChange","checkbox","checkboxColId","neg","checkboxCol","colum","ignoreNextTextareaFocus","handleKeypress","charCode","handlePaste","clipboardData","getData","validateValue","safeValue","tallestTextareaHeight","tdHeight","numericKeyCodes","ElementActionTrigger","maxLevels","newChildUrl","triggerEnabled","batch","bulk","defineProperty","activate","updateTrigger","validateSelection","enableTrigger","disableTrigger","requireId","handleTriggerActivation","ElementEditor","isFullPage","$contentContainer","$revisionBtn","$revisionLabel","$expandSiteStatusesBtn","$statusIcon","$previewBtn","$editMetaBtn","metaHud","$nameTextInput","$saveMetaBtn","$siteStatusPane","$globalLightswitch","$siteLightswitches","$additionalSiteField","siteIds","newSiteIds","enableAutosave","lastSerializedValue","listeningForChanges","pauseLevel","queue","submittingForm","duplicatedElements","failed","httpStatus","httpError","openingPreview","preview","activatedPreviewToken","previewTokenQueue","previewLinks","hiddenTipsStorageKey","tipDismissBtn","slideout","$primaryForm","_createQueue","autosaveDrafts","siteStatuses","$spinnerContainer","canEditMultipleSites","previewTargets","enablePreview","$previewBtnContainer","createPreviewLink","createShareMenu","revisionId","serializeForm","isProvisionalDraft","initForProvisionalDraft","isUnpublishedDraft","initForDraft","canSaveCanonical","saveShortcut","createDraft","listenForChanges","showStatusHud","handleDismissibleTips","canonicalId","canCreateDrafts","statusIcons","checkForm","stopListeningForChanges","$discardButton","initialHeight","$notice","heightDiff","hashedCpEditUrl","provisional","createEditMetaBtn","expandSiteStatuses","$enabledForSiteField","_getOtherSupportedSites","_createSiteStatusField","$globalField","_showField","siteStatusValues","hasEnabled","hasDisabled","originalEnabledValue","originalSerializedStatus","enabledForSite","_updateGlobalStatus","serializedStatuses","additionalSites","_createAddlSiteField","_updateSiteStatuses","_removeField","allEnabled","allDisabled","turnOn","turnOff","turnIndeterminate","enabled","site","fieldClass","$lightswitch","some","selectLabelId","$addlSiteSelectLabel","$addlSiteSelectContainer","labelledBy","$addlSiteSelect","addlSiteInfo","enabledByDefault","_saveFailMessage","_saveSuccessMessage","hud","$mainContainer","spinners","statusMessage","getTokenizedPreviewUrl","targetUrl","targetLabel","activatePreviewToken","updatePreviewLinks","updatePreviewLinkHref","isLive","getPreviewTokenParams","previewToken","getPreviewToken","randoParam","asPromise","siteToken","previewUrl","tokenParam","createTokenParams","getPreview","$statusIcons","scrollTo","ensureIsDraftOrRevision","onlyIfChanged","removeActionParams","isPreviewActive","$editor","redirectName","saveDraft","isActive","modifiedFieldNames","preparedData","prepareData","deltaName","extraData","visibleLayoutElements","selectedTabId","_saveHeaders","newSelectedTabId","_afterSaveDraft","createdProvisionalDraft","docTitle","draftName","revisionMenu","oldId","siteSettings","creator","timestamp","updatePreviewTargets","checkMetaValues","selectors","modifiedAttributes","$fields","noChanges","$allTabContainers","changedElements","missingElements","tabInfo","$oldElement","$placeholder","$unusedTabContainers","$newSelectedTab","selectTab","afterUpdate","_showFailStatus","setStatusMessage","deltaCallback","swapDuplicatedElementIds","idsRE","namespacedFields","pre","post","_filterFieldInputName","nestedNames","lastHandle","fieldsWithoutContent","newTarget","$previewLink","delay","showMetaHud","createMetaHud","onMetaHudShow","$hudBody","$nameField","$nameInputContainer","saveMeta","onMetaHudHide","onMetaHudEscape","shakeMetaHud","autosave","$confirmUnloadForms","hideTip","getHiddenTipsUids","setHiddenTipsUids","uids","targetElement","$targetParent","layoutElementUid","Storage","hiddenTips","editor","saveParams","onSaveElement","validators","ElementFieldSettings","allowMultipleSources","$maintainHierarchyField","$maintainHierarchyInput","$sourcesField","$sourceSelect","$branchLimitField","$maxRelationsField","$minRelationsField","maintainHierarchyFieldId","branchLimitFieldId","minRelationsFieldId","maxRelationsFieldId","updateLimitFields","updateMaintainHierarchyField","showField","$checkedInputs","ElementThumbLoader","workers","Worker","$thumbs","$thumb","$scrollParent","addToQueue","invisibleThumbs","thumb","active","loadNext","scrollParentOffset","scrollParentHeight","thumbOffset","retryAll","loader","$img","ElevatedSessionForm","inputs","form","getInputPostVal","handleFormSubmit","elevatedSessionManager","fetchingTimeout","stopImmediatePropagation","inputsChanged","$currentInput","requireElevatedSession","ElevatedSessionManager","passwordModal","$errorPara","minSafeElevatedSessionTimeout","showPasswordModal","$passwordModal","focusPasswordInput","submitPassword","currentPassword","showPasswordError","EntryIndex","publishableSections","$newEntryBtnGroup","$newEntryBtn","defaultSectionHandle","selectedSection","section","_createEntry","sectionId","entry","sectionSourceKey","FieldLayoutDesigner","$configInput","$newTabBtn","$libraryToggle","$selectedLibrary","$fieldLibrary","$uiLibrary","$uiLibraryElements","$fieldSearch","$clearFieldSearchBtn","$fieldGroups","tabGrid","elementDrag","_config","$workspace","$fieldSearchContainer","initTab","ElementDrag","customizableTabs","tabDrag","TabDrag","customizableUi","$libraryPicker","$matches","$group","Tab","removeFieldByHandle","addTab","updatePositionInConfig","config","updateConfig","createSlideout","contents","js","eval","designer","destroyed","settingsNamespace","createMenu","initElement","menuBtn","onTabOptionSelect","$prev","$next","settingsHtml","settingsJs","applySettings","$indicator","hasConditions","Element","findIndex","designerConfig","newIndex","tabConfig","oldIndex","isField","requirable","hasCustomWidth","hasSettings","isRequired","showSettings","initUi","SlidePicker","valueLabel","pct","$fieldsContainer","selectorHtml","updateRequiredClass","required","elementConfig","BaseDrag","Drag","$insertion","showingInsertion","$caboose","findItems","onDragStart","createInsertion","createCaboose","removeCaboose","swapDraggeeWithInsertion","swapInsertionWithDraggee","setMidpoints","getClosestItem","_closestItem","_closestItemMouseDiff","_i","_$item","_midpoint","_mouseDiff","getDist","checkForNewClosestItem","refreshCols","onDragStop","display","draggeeDisplay","visibility","helpers","_showDraggee","onDrag","draggingLibraryElement","draggingField","originalTab","isDraggeeMandatory","isHoveringOverTab","hitTest","$fieldContainers","$libraryElement","targetPrefix","reverseTargetSelector","_$reverseTarget","getType","normalizeTargetSelector","findTargets","onToggleChange","nodeName","getToggleVal","boolean","postVal","_show","totalCols","colGutterDrop","colPctWidth","possibleItemColspans","possibleItemPositionsByColspan","itemPositions","itemColspansByPosition","layouts","layout","itemHeights","leftPadding","_refreshingCols","_refreshColsAfterRefresh","_forceRefreshColsAfterRefresh","handleContainerHeightProxy","setItems","oldHeight","scrollHeight","gutter","itemIndex","tallestItemHeight","colIndex","itemHeight","remainder","itemHeightsByColspan","positionRight","positionLeft","minColspan","maxColspan","colspan","getItemWidthCss","minPosition","maxPosition","colHeights","createLayouts","layoutTotalCols","highestTotalCols","layoutHeights","shortestHeight","shortestLayouts","emptySpaces","emptySpace","colspans","getItemLeftPosCss","positions","isSimpleLayout","positionItems","completeRefreshCols","onRefreshCols","getItemWidth","getItemWidthInPx","getItemLeftPosInPx","prevPositions","prevColspans","prevColHeights","prevEmptySpace","LayoutGenerator","endingCol","affectedColHeights","onItemResize","newHeight","tallestColHeightsByPosition","colHeightsForPosition","tallestColHeight","words","handleCasing","ImageUpload","initImageUpload","containerSelector","uploadAction","postParameters","fileInputSelector","uploadParamName","initButtons","uploadButtonSelector","deleteButtonSelector","refreshImage","onAfterRefreshImage","$icon","$liveRegion","wrap","previousSibling","nodeType","Node","TEXT_NODE","nodeValue","showHud","closeOtherHUDs","$outerContainer","$innerContainer","indeterminate","dragger","dragStartMargin","outerContainer","X_AXIS","_onDragStart","_onDrag","_onDragStop","muteEvent","changed","_onSettle","_getOffMargin","_onMouseDown","_onMouseUp","dragging","_getMargin","mouseDistX","selectedOptionIndex","selectedClass","focusClass","LivePreview","$extraFields","$dragHandle","$previewContainer","$iframeContainer","$iframe","$fieldPlaceholder","basePostData","inPreviewMode","fields","lastPostData","updateIframeInterval","checkAgain","dragStartEditorWidth","_slideInOnIframeLoad","_scrollX","_scrollY","_editorWidth","_editorWidthInPx","protocol","previewParams","extraFields","defaultEditorWidth","moveFieldsBack","editorWidthInPx","inPx","minEditorWidthInPx","exit","$editorHeader","handleWindowResize","getIframeWidth","$clone","_getClone","updateIframe","slideIn","createToken","previewAction","submitPrimaryForm","updateWidths","$newClone","field","contentWindow","scrollLeft","xhrFields","withCredentials","crossDomain","handleSuccess","handleError","forceUpdateIframe","write","copyInputValues","livePreview","$textInput","$showPasswordToggle","showingPassword","passwordInput","initInputFocusEvents","hidePassword","setCurrentInput","updateToggleLabel","showPassword","autocapitalize","togglePassword","onInputChange","onClick","selectionEnd","$previewWrapper","$previewSkipLink","$bumperLink","$notifier","$previewHeader","$targetBtn","$targetMenu","$deviceTypeContainer","$orientationBtn","$refreshBtn","$deviceMask","$devicePreviewContainer","iframeLoaded","$tempInput","activeTarget","currentDeviceType","deviceOrientation","deviceWidth","deviceHeight","deviceMaskDimensions","phone","tablet","iframeHeight","_updateIframeProxy","previewSkipLinkText","$modalLabel","Pro","switchTarget","_buildDeviceTypeFieldset","_getDeviceTypeTranslation","translation","_getDeviceOrientationTranslation","deviceType","deviceBtnGroup","switchDeviceType","_activeTarget","_autoRefresh","previewTarget","hideModalBackgroundLayers","resetModalBackgroundLayerVisibility","_devicePreviewIsActive","updateDevicePreview","_useIframeResizer","previewIframeResizerOptions","resetScroll","sameHost","frameborder","iFrameResize","checkOrigin","scrolling","onInit","iframe","_updateNotifier","newDeviceType","switchOrientation","hZoom","wZoom","previewHeight","previewWidth","maskHeight","maskWidth","translate","rotationDeg","marginTop","marginLeft","$triggerElement","$bumperButtonStart","$bumperButtonEnd","requestId","defaultSettings","_onHide","instance","loadAsset","focusItem","_addBumperButtons","_addModalName","destruct","desiredHeight","desiredWidth","containerHeight","containerWidth","_resizeContainer","previewHtml","$innerProgressBar","$progressBarStatus","_itemCount","_processedItemCount","_displaySteps","displaySteps","setProcessedItemCount","incrementItemCount","percentage","$modalContainerDiv","$prompt","$promptApplyToRemainingContainer","$promptApplyToRemainingCheckbox","$promptApplyToRemainingLabel","$pomptChoices","_prompts","_promptBatchCallback","_promptBatchReturnData","_promptBatchNum","_showNextPromptInBatch","remainingInBatch","_showPrompt","_handleBatchPromptSelection","applyToRemaining","choiceData","itemsToGo","_promptCallback","$promptMessage","$promptChoices","$promptButtons","$radioButton","_selectPromptChoice","fadeOut","_cancelPrompt","running","paused","pausedForVisibility","jobs","isPaused","_resume","job","_add","qResolve","qReject","_exec","totalSteps","HOME_KEY","END_KEY","_min","_max","Number","isInteger","prevAll","triggerEvent","$activeButton","startPositionX","graduationsMin","graduationsMax","slideMin","slideMax","$overlay","$cursor","$graduations","$graduationsUl","_handleResize","_handleTapStart","_handleTapMove","_handleTapEnd","_handleKeypress","graduationsCalculatedWidth","valueToPosition","current","PAGE_UP_KEY","PAGE_DOWN_KEY","touch","startLeft","curX","positionToValue","scaleMin","scaleMax","addModalAttributes","autoOpen","setTriggerElement","_cancelTransitionListeners","addPanel","removePanel","openPanels","panel","updateStyles","totalPanels","SlugGenerator","allowUppercaseInSlug","limitAutoSlugsToAscii","XRegExp","matchChain","slugWordSeparator","Structure","structureDrag","$parents","initToggle","StructureDrag","initNewChildMenus","viewStateKey","$addBtns","onNewChildMenuClick","showMenu","getIndent","level","baseIndent","nestedIndent","addElement","$parentUl","_removeUl","structure","draggeeLevel","$helperLi","$targets","draggeeHeight","$level","cancelDrag","$lis","$closestTarget","closestTargetPos","closestTargetYDiff","closestTargetOffset","closestTargetHeight","targetOffset","targetHeight","targetYMidpoint","targetYDiff","$closestTargetLi","closestTargetLevel","$nextTargetLi","nextTargetLevel","hoveringBetweenRows","draggeeX","targetItemMouseDiffX","$parentLis","$closestParentLi","closestParentLiXDiff","closestParentLevel","$parentLi","parentLiX","parentLiXDiff","parentLevel","onMouseUp","$draggeeParent","moved","$closestSiblings","newLevel","setLevel","structureId","prevId","indent","$childLis","StructureTableSorter","tableView","_basePadding","_helperMargin","_$firstRowCells","_$titleHelperCell","_titleHelperCellOuterWidth","_ancestors","_updateAncestorsFrame","_draggeeLevel","_draggeeLevelDelta","draggingLastElements","_loadingDraggeeLevelDelta","_targetLevel","_targetLevelBounds","_positionChanged","singleHelper","helperSpacingY","findDraggee","$nextRow","nextRowLevel","nextRowLevelDelta","_getAjaxBaseData","delta","drag","$helperCell","$firstRowCell","canInsertBefore","_getLevelBounds","canInsertAfter","_getAncestors","_setTargetLevelBounds","_updateIndent","onInsertionPointChange","_updateAncestorsBeforeRepaint","levelDiff","padding","_getLevelIndent","$prevRow","prevRowLevel","$spinnerRow","_createSpinnerRowAfter","onPositionChange","_expandElement","onReturnHelpersToDraggees","newDraggeeIndexes","oldDraggeeIndexes","$postDraggeeItems","nextAll","_minLevel","_maxLevel","forcePositionChange","_mouseDist","realMouseX","mousedownX","_indentationDist","LEVEL_INDENT","_targetLevelMouseDiff","_magnetImpact","MAX_GIVE","_closestLevelMagnetIndent","targetLevel","_level","_$prevRow","cancelAnimationFrame","_updateAncestors","_$ancestor","_newAncestors","ancestorTitle","HELPER_MARGIN","$tableCaption","$selectedSortHeader","structureTableSort","_totalVisiblePostStructureTableDraggee","_morePendingPostStructureTableDraggee","_broadcastListener","initTableHeaders","_updateScreenReaderStatus","_collapseElement","attributeHtml","selectedSortAttr","selectedSortDir","$tableHeaders","sortValue","makeColumnSortable","sorted","headerHtml","$instructions","$headerButton","_handleSelectedSortHeaderClick","_handleUnselectedSortHeaderClick","_isStructureTableDraggingLastElements","positionedAfter","updateResponsiveTables","$nextNextRow","descendantOf","$nextRows","newSortDir","_handleSortHeaderClick","attrLabel","dirLabel","_updateTableAttributes","removeEventListener","$tablist","$firstTab","$lastTab","$selectedTab","$focusableTab","makeTabFocusable","scrollToTab","updateMenuBtn","focusTab","_getTab","deselectTab","$slideoutContainer","elemScrollOffset","targetScrollLeft","tabWidth","ulWidth","HTMLElement","TagSelectInput","searchMenu","$addTagInput","_ignoreBlur","searchForTags","selectTag","$hoverOption","$nextOption","focusOption","$prevOption","killSearchMenu","excludeIds","tagGroupId","tags","exclude","exactMatch","Menu","attachToElement","targetSiteId","$titleContainer","autocomplete","inputmode","maxlength","autofocus","getAutofocusValue","getDisabledValue","readonly","showCharsLeft","createCopyTextInput","buttonId","execCommand","createCopyTextBtn","copyValue","createCopyTextField","createCopyTextPrompt","createTextarea","createTextareaField","$select","optgroup","$optgroup","selected","reverseToggle","createCheckboxField","createCheckboxSelect","allValue","allChecked","allLabel","labelId","$colorPreviewContainer","createColorField","isMobile","getMonth","toISOString","timezone","defaultDate","hasOuterContainer","createDateField","createDateRangePicker","today","getFullYear","getDate","startDate","endDate","$allOption","firstDayOffset","getDay","firstDay","$flex","$startDate","$endDate","$dateInputs","dpDiv","setPositionRelativeToAnchor","startTime","endTime","foundOption","btnClasses","timepicker","timepickerOptions","getHours","getMinutes","getSeconds","createTimeField","warning","$warning","addErrorsToList","$errors","_rejectedFiles","_extensionList","_totalFileCounter","_validFileCounter","autoUpload","fileupload","onFileAdd","paramObject","getInProgress","validateExtension","_createExtensionList","process","done","files","pass","fileExtension","maxFileSize","originalFiles","processErrorMessages","kinds","humanFileSize","maxUploadSize","bytes","threshold","u","toFixed","allowedKind","fileKinds","extensions","ext","pasteZone","sequentialUploads","Accept","UriFormatGenerator","uriFormat","suffix","UserIndex","updateUrl","defaultSourceSlug","slug","__esModule","default","module","locals","exports","listToStyles","list","styles","newStyles","part","media","sourceMap","parts","hasDocument","DEBUG","Error","stylesInDom","head","getElementsByTagName","singletonElement","singletonCounter","isProduction","ssrIdKey","isOldIE","navigator","userAgent","addStylesClient","_isProduction","_options","addStylesToDom","newList","mayRemove","domStyle","refs","addStyle","createStyleElement","styleElement","querySelector","parentNode","styleIndex","applyToSingletonTag","applyToTag","newObj","textStore","replaceText","replacement","Boolean","styleSheet","cssText","cssNode","createTextNode","childNodes","ssrId","btoa","unescape","firstChild","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getter","definition","enumerable","prototype","CP","authManager","$navToggle","$globalSidebar","$globalContainer","$alerts","$crumbs","$breadcrumbList","$breadcrumbItems","$notificationContainer","$mainContent","$details","$sidebarContainer","$sidebarToggle","$edition","$deltaForms","$collapsibleTables","breadcrumbListWidth","breadcrumbDisclosureItem","enableQueue","totalJobs","jobInfo","displayedJobInfo","displayedJobInfoUnchanged","trackJobProgressTimeout","jobProgressIcon","checkingForUpdates","forcingRefreshOnUpdatesCheck","includingDetailsOnUpdatesCheck","checkForUpdatesCallbacks","resizeTimeout","$allInstructions","updateFixedHeader","setSidebarNavAttributes","initSpecialForms","initAlerts","shortcuts","shortcut","initTabs","LOCATION_HASH","_handleInputFocus","_handleInputBlur","announcements","$unreadMessage","hasUnreads","unread","footer","IntersectionObserver","classList","intersectionRatio","rootMargin","observe","$contentHeader","$forms","confirmUnload","returnValue","updateSidebarMenuLabel","toggleNav","isExpanded","navIsExpanded","disableGlobalSidebarLinks","enableGlobalSidebarLinks","focusableItems","isAlwaysVisible","getComputedStyle","getPropertyValue","newState","toggleClass","$tabsContainer","$tabsList","selectedTabIndex","handleBreadcrumbVisibility","breadcrumbItemsWrap","listWidth","totalItemWidth","finalIndex","visibleItemWidth","shownItems","hiddenItems","_$table","_containerWidth","_check","_isCollapsed","headerHeight","displayNotification","notification","Notification","notificationType","iconLabel","fetchAlerts","alerts","displayAlerts","showIcon","$shunnableAlerts","$link","checkForUpdates","forceRefresh","includeDetails","realCallback","_checkForUpdates","updateUtilitiesBadge","callbacks","updateInfo","_getUpdates","_checkForCachedUpdates","cached","onlyIfCached","updates","_cacheUpdates","$utilitiesLink","$screenReaderText","badgeCount","runQueueAutomatically","trackJobProgress","_trackJobProgressInternal","setJobInfo","oldInfo","getDisplayedJobInfo","progressLabel","updateJobIcon","statuses","JOB_STATUS_RESERVED","JOB_STATUS_FAILED","JOB_STATUS_WAITING","JobProgressIcon","hideFailMode","setDescription","description","setProgress","showFailMode","cpTrigger","notificationDuration","JOB_STATUS_DONE","closing","closeTimeout","_preventDelayedClose","originalActiveElement","$closeBtnContainer","details","_negMargin","_initDelayedClose","delayedClose","preventDelayedClose","$progressLabel","failMode","_$bgCanvas","_$staticCanvas","_$hoverCanvas","_$failCanvas","_staticCtx","_hoverCtx","_canvasSize","_arcPos","_arcRadius","_lineWidth","_arcStartPos","_arcEndPos","_arcStartStepSize","_arcEndStepSize","_arcStep","_arcStepTimeout","_arcAnimateCallback","_progressBar","canAccessQueueManager","$canvasContainer","$labelContainer","_createCanvas","getContext","_drawArc","_animateArc","_setArc","color","$canvas","ctx","strokeStyle","lineWidth","lineCap","startPos","endPos","clearRect","beginPath","arc","closePath","targetStartPos","targetEndPos","_takeNextArcStep"],"sourceRoot":""}
\ No newline at end of file

programming_language: Scala
filename: BaseElementIndex.js
change_type: ModificationType.MODIFY
diff: @@ -3457,7 +3457,7 @@ const ViewMenu = Garnish.Base.extend({
       .createSelect({
         options: this.elementIndex.getSortOptions(this.$source).map((o) => {
           return {
-            label: o.label,
+            label: Craft.escapeHtml(o.label),
             value: o.attr,
           };
         }),

programming_language: JavaScript
filename: CustomizeSourcesModal.js
change_type: ModificationType.MODIFY
diff: @@ -639,7 +639,7 @@ Craft.CustomizeSourcesModal.Source =
           name: `sources[${this.sourceData.key}][defaultSort][0]`,
           options: this.sourceData.sortOptions.map((o) => {
             return {
-              label: o.label,
+              label: Craft.escapeHtml(o.label),
               value: o.attr,
             };
           }),

programming_language: JavaScript