
/* /web_editor/static/src/js/core/owl_utils.js */
odoo.define('@web_editor/js/core/owl_utils',['@odoo/owl','@web/core/templates','@web/core/l10n/translation'],function(require){'use strict';let __exports={};const{App,Component,useState,xml}=require("@odoo/owl");const{getTemplate}=require("@web/core/templates");const{_t}=require("@web/core/l10n/translation");const rootTemplate=xml`<SubComp t-props="state"/>`;__exports.attachComponent=attachComponent;async function attachComponent(parent,element,componentClass,props={}){class Root extends Component{static template=rootTemplate;static components={SubComp:componentClass};static props=["*"];state=useState(props);}
const env=Component.env;const app=new App(Root,{env,getTemplate,dev:env.debug,translatableAttributes:["data-tooltip"],translateFn:_t,});if(parent.__parentedMixin){parent.__parentedChildren.push({get $el(){return $(app.root.el);},destroy(){app.destroy();},});}
const originalValidateTarget=App.validateTarget;App.validateTarget=()=>{};const mountPromise=app.mount(element);App.validateTarget=originalValidateTarget;const component=await mountPromise;const subComp=Object.values(component.__owl__.children)[0].component;return{component:subComp,destroy(){app.destroy();},update(props){Object.assign(component.state,props);},};}
return __exports;});;

/* /web_editor/static/src/js/editor/snippets.editor.js */
odoo.define('@web_editor/js/editor/snippets.editor',['@web/core/utils/numbers','@web/core/confirmation_dialog/confirmation_dialog','@web/core/utils/hooks','@web/legacy/js/public/public_widget','@web_editor/js/editor/drag_and_drop','@web_editor/js/editor/snippets.options','@web_editor/js/common/utils','@web_editor/js/common/grid_layout_utils','@web/core/utils/strings','@web_editor/js/editor/odoo-editor/src/utils/utils','@web/core/utils/timing','@web/core/utils/functions','@web/core/utils/arrays','@web/core/browser/browser','@web_editor/js/editor/toolbar','@odoo/owl','@web_editor/js/wysiwyg/widgets/link_tools','@web/core/utils/ui','@web/core/l10n/translation','@web/core/utils/render','@web/core/network/rpc','@web_editor/js/common/column_layout_mixin','@web/core/tooltip/tooltip','@web_editor/js/editor/add_snippet_dialog','@web_editor/js/common/scrolling'],function(require){'use strict';let __exports={};const{clamp}=require("@web/core/utils/numbers");const{ConfirmationDialog}=require("@web/core/confirmation_dialog/confirmation_dialog");const{useService,useBus}=require("@web/core/utils/hooks");const publicWidget=require("@web/legacy/js/public/public_widget")[Symbol.for("default")];const{useDragAndDrop}=require("@web_editor/js/editor/drag_and_drop");const options=require("@web_editor/js/editor/snippets.options")[Symbol.for("default")];const weUtils=require("@web_editor/js/common/utils")[Symbol.for("default")];const gridUtils=require("@web_editor/js/common/grid_layout_utils");const{escape}=require("@web/core/utils/strings");const{closestElement,isUnremovable}=require("@web_editor/js/editor/odoo-editor/src/utils/utils");const{debounce,throttleForAnimation}=require("@web/core/utils/timing");const{uniqueId}=require("@web/core/utils/functions");const{sortBy,unique}=require("@web/core/utils/arrays");const{browser}=require("@web/core/browser/browser");const{Toolbar}=require("@web_editor/js/editor/toolbar");const{Component,EventBus,markup,onMounted,onWillStart,onWillUnmount,useEffect,useRef,useState,}=require("@odoo/owl");const{LinkTools}=require('@web_editor/js/wysiwyg/widgets/link_tools');const{touching,closest,addLoadingEffect:addButtonLoadingEffect,isVisible,}=require("@web/core/utils/ui");const{_t}=require("@web/core/l10n/translation");const{renderToElement}=require("@web/core/utils/render");const{RPCError}=require("@web/core/network/rpc");const{ColumnLayoutMixin}=require("@web_editor/js/common/column_layout_mixin");const{Tooltip:OdooTooltip}=require("@web/core/tooltip/tooltip");const{AddSnippetDialog}=require("@web_editor/js/editor/add_snippet_dialog");const{scrollTo}=require("@web_editor/js/common/scrolling");let cacheSnippetTemplate={};var globalSelector={closest:()=>$(),all:()=>$(),is:()=>false,};var SnippetEditor=publicWidget.Widget.extend({template:'web_editor.snippet_overlay',events:{'click .oe_snippet_remove':'_onRemoveClick','wheel':'_onMouseWheel','click .o_send_back':'_onSendBackClick','click .o_bring_front':'_onBringFrontClick','click .o_snippet_replace':'_onReplaceClick',},custom_events:{'option_update':'_onOptionUpdate','user_value_widget_request':'_onUserValueWidgetRequest','snippet_option_visibility_update':'_onSnippetOptionVisibilityUpdate',},layoutElementsSelector:['.o_we_shape','.o_we_bg_filter',].join(','),init:function(parent,target,templateOptions,$editable,options){this._super.apply(this,arguments);this.options=options;this.$editable=$editable&&$editable.length?$editable:$(document.body);this.ownerDocument=this.$editable[0].ownerDocument;this.$body=$(this.ownerDocument.body);this.$target=$(target);this.$target.data('snippet-editor',this);this.templateOptions=templateOptions;this.isTargetParentEditable=false;this.isTargetMovable=false;this.$scrollingElement=$().getScrollingElement(this.$editable[0].ownerDocument);if(!this.$scrollingElement[0]){this.$scrollingElement=$(this.ownerDocument).find('.o_editable');}
this.displayOverlayOptions=false;this._$toolbarContainer=$();this.isRtl=this.options.direction==="rtl";this.__isStarted=new Promise(resolve=>{this.__isStartedResolveFunc=resolve;});},start:function(){var defs=[this._super.apply(this,arguments)];defs.push(this._initializeOptions());var $customize=this._customize$Elements[this._customize$Elements.length-1];this.isTargetParentEditable=this.$target.parent().is(':o_editable');this.isTargetMovable=this.isTargetParentEditable&&this.isTargetMovable&&!this.$target.hasClass('oe_unmovable');this.isTargetRemovable=this.isTargetParentEditable&&!this.$target.parent().is('[data-oe-type="image"]')&&!isUnremovable(this.$target[0]);this.displayOverlayOptions=this.displayOverlayOptions||this.isTargetMovable||!this.isTargetParentEditable;if(this.isTargetMovable){this.dropped=false;this.draggableComponent=this._initDragAndDrop(".o_move_handle",".oe_overlay",this.el);if(!this.$target[0].matches("section")){this.$target[0].classList.add("o_draggable");this.draggableComponentImgs=this._initDragAndDrop("img",".o_draggable",this.$target[0]);}}else{this.$('.o_overlay_move_options').addClass('d-none');const cloneButtonEl=$customize[0].querySelector(".oe_snippet_clone");cloneButtonEl.classList.toggle("d-none",!this.forceDuplicateButton);}
if(!this.isTargetRemovable){this.$el.add($customize).find('.oe_snippet_remove').addClass('d-none');}
if(this.$target[0].matches("[data-snippet]:not([data-snippet] *), .oe_structure > *")&&!this.$target[0].matches(".oe_structure_solo *")){this.trigger_up('find_snippet_template',{snippet:this.$target[0],callback:(snippet)=>{if(snippet.group){this.$el.add($customize).find('.o_snippet_replace').removeClass('d-none');}},});}
var _animationsCount=0;this.postAnimationCover=throttleForAnimation(()=>{this.trigger_up('cover_update',{overlayVisible:true,});});this.$target.on('transitionstart.snippet_editor, animationstart.snippet_editor',()=>{_animationsCount++;setTimeout(()=>{if(!--_animationsCount){this.postAnimationCover();}},500);});this.$target.on('transitionend.snippet_editor, animationend.snippet_editor',this.postAnimationCover);return Promise.all(defs).then(()=>{this.__isStartedResolveFunc(this);});},destroy:function(){this.trigger_up('snippet_editor_destroyed');this.draggableComponent&&this.draggableComponent.destroy();this.draggableComponentImgs?.destroy();if(this.$optionsSection){this.$optionsSection.remove();}
if(this.postAnimationCover){this.postAnimationCover.cancel();}
this._super(...arguments);this.$target.removeData('snippet-editor');this.$target.off('.snippet_editor');},areOptionsShown:function(){const lastIndex=this._customize$Elements.length-1;return!!this._customize$Elements[lastIndex].parent().length;},async buildSnippet(targetEl){for(var i in this.styles){await this.styles[i].onBuilt({isCurrent:targetEl===this.$target[0],});}
await this.toggleTargetVisibility(true,true);},cleanForSave:async function(){if(this.isDestroyed()){return;}
await this.toggleTargetVisibility(!this.$target.hasClass('o_snippet_invisible')&&!this.$target.hasClass('o_snippet_mobile_invisible')&&!this.$target.hasClass('o_snippet_desktop_invisible'));const proms=Object.values(this.styles).map((option)=>{return option.cleanForSave();});await Promise.all(proms);await this.cleanUI();},async cleanUI(){const proms=Object.values(this.styles).map((option)=>{return option.cleanUI();});await Promise.all(proms);},closeWidgets:function(){if(!this.styles||!this.areOptionsShown()){return;}
Object.keys(this.styles).forEach(key=>{this.styles[key].closeWidgets();});},cover:function(){if(!this.isShown()||!this.$target.length){return;}
const $modal=this.$target.find('.modal:visible');const $target=$modal.length?$modal:this.$target;const targetEl=$target[0];const rect=targetEl.getBoundingClientRect();const vpWidth=targetEl.ownerDocument.defaultView?.innerWidth||document.documentElement.clientWidth;const vpHeight=targetEl.ownerDocument.defaultView?.innerHeight||document.documentElement.clientHeight;const isInViewport=(rect.bottom>-0.1&&rect.right>-0.1&&(vpHeight-rect.top)>-0.1&&(vpWidth-rect.left)>-0.1);const hasSize=(Math.abs(rect.bottom-rect.top)>0.01&&Math.abs(rect.right-rect.left)>0.01);if(!isInViewport||!hasSize||!this.$target.is(`:visible`)){this.toggleOverlayVisibility(false);return;}
const transform=window.getComputedStyle(targetEl).getPropertyValue('transform');const transformOrigin=window.getComputedStyle(targetEl).getPropertyValue('transform-origin');targetEl.classList.add('o_transform_removal');const offset=$target.offset();const manipulatorOffset=this.$el.parent().offset();offset.top-=manipulatorOffset.top;offset.left-=manipulatorOffset.left;this.$el.css({width:$target.outerWidth(),height:$target.outerHeight(),left:offset.left,top:offset.top,transform,'transform-origin':transformOrigin,});this.$('.o_handles').css('height',$target.outerHeight());targetEl.classList.remove('o_transform_removal');const editableOffsetTop=this.$editable.offset().top-manipulatorOffset.top;this.$el.toggleClass('o_top_cover',offset.top-editableOffsetTop<25);const handleEReadonlyEl=this.$el[0].querySelector('.o_handle.e.readonly');if(handleEReadonlyEl){handleEReadonlyEl.style.width=$(targetEl).hasScrollableContent()?0:'';}},getName:function(){if(this.$target.data('translated-name')!==undefined){return this.$target.data('translated-name');}
if(this.$target.data('name')!==undefined){return this.$target.data('name');}
if(this.$target.is('img')){return _t("Image");}
if(this.$target.is('.fa')){return _t("Icon");}
if(this.$target.is('.media_iframe_video')){return _t("Video");}
if(this.$target.parent('.row').length){return _t("Column");}
if(this.$target.is('#wrapwrap > main')){return _t("Page Options");}
if(this.$target[0].matches(".btn")){return _t("Button");}
return _t("Block");},isShown:function(){return this.$el&&this.$el.parent().length&&this.$el.hasClass('oe_active');},isSticky:function(){return this.$el&&this.$el.hasClass('o_we_overlay_sticky');},isTargetVisible:function(){return(this.$target[0].dataset.invisible!=='1');},removeSnippet:async function(shouldRecordUndo=true){this.options.wysiwyg.odooEditor.unbreakableStepUnactive();this.toggleOverlay(false);await this.toggleOptions(false);await this.toggleTargetVisibility(!this.$target.hasClass('o_snippet_invisible'));this.trigger_up('will_remove_snippet',{$target:this.$target});await new Promise(resolve=>{this.trigger_up('call_for_each_child_snippet',{$snippet:this.$target,callback:async function(editor,$snippet){for(var i in editor.styles){await editor.styles[i].onRemove();}},onSuccess:resolve,});});let parent=this.$target[0].parentElement;let nextSibling=this.$target[0].nextElementSibling;while(nextSibling&&!isVisible(nextSibling)){nextSibling=nextSibling.nextElementSibling;}
let previousSibling=this.$target[0].previousElementSibling;while(previousSibling&&!isVisible(previousSibling)){previousSibling=previousSibling.previousElementSibling;}
if($(parent).is('.o_editable:not(body)')){parent=$(parent).closest('body');}
const activateSnippetProm=new Promise(resolve=>{this.trigger_up('activate_snippet',{$snippet:$(previousSibling||nextSibling||parent),onSuccess:resolve,});});var $parent=this.$target.parent();this.$target.find('*').addBack().each((index,el)=>{const tooltip=Tooltip.getInstance(el);if(tooltip){tooltip.dispose();}});this.$target.remove();this.$el.remove();if(this.$target[0].classList.contains('o_grid_item')){gridUtils._resizeGrid($parent[0]);}
var node=$parent[0];if(node&&node.firstChild){if(!node.firstChild.tagName&&node.firstChild.textContent===' '){node.removeChild(node.firstChild);}}
if($parent.closest(':data("snippet-editor")').length){const isEmptyAndRemovable=($el,editor)=>{editor=editor||$el.data('snippet-editor');const isEmptyFigureEl=$el[0].matches("figure")&&$el[0].children.length===1&&$el[0].children[0].matches("figcaption");const isEmpty=isEmptyFigureEl||($el.text().trim()===''&&$el.children().toArray().every(el=>{return el.matches(this.layoutElementsSelector);}));const notRemovableSelector=`.oe_structure,
                    .carousel-item,
                    .carousel-item > .container,
                    .carousel-item > .container-fluid,
                    .carousel-item > .o_container_small`;return isEmpty&&!$el[0].matches(notRemovableSelector)&&(!editor||editor.isTargetParentEditable)&&!isUnremovable($el[0]);};var editor=$parent.data('snippet-editor');while(!editor){var $nextParent=$parent.parent();if(isEmptyAndRemovable($parent)){$parent.remove();}
$parent=$nextParent;editor=$parent.data('snippet-editor');}
if(isEmptyAndRemovable($parent,editor)){setTimeout(()=>editor.removeSnippet());}}
this.$body.find('.note-control-selection').hide();this.$body.find('.o_table_handler').remove();this.trigger_up('snippet_removed');activateSnippetProm.then(()=>this.destroy());$parent.trigger('content_changed');$(window).trigger('resize');if(shouldRecordUndo){this.options.wysiwyg.odooEditor.historyStep();}},toggleOverlay:function(show,previewMode){if(!this.$el){return;}
if(previewMode){this.$el.toggleClass('o_we_overlay_preview',show);}else{this.$el.removeClass('o_we_overlay_preview');this.$el.toggleClass('o_we_overlay_sticky',show);if(!this.displayOverlayOptions){this.$el.find('.o_overlay_options_wrap').addClass('o_we_hidden_overlay_options');}}
this.$el.toggleClass('oe_active',show);this.cover();this.toggleOverlayVisibility(show);},async toggleOptions(show){if(!this.$el){return[];}
if(this.areOptionsShown()===show){return null;}
const editorUIsToUpdate=[];const focusOrBlur=show?async(editor,options)=>{for(const opt of options){await opt.onFocus();}
editorUIsToUpdate.push(editor);}:async(editor,options)=>{for(const opt of options){await opt.onBlur();}};for(const $el of this._customize$Elements){const editor=$el.data('editor');const styles=sortBy(Object.values(editor.styles||{}),"__order");await focusOrBlur(editor,styles);}
await Promise.all(editorUIsToUpdate.map(editor=>editor.updateOptionsUI()));const optionsSectionVisible=await Promise.all(editorUIsToUpdate.map(editor=>editor.updateOptionsUIVisibility())).then(editorVisibilityValues=>{return editorVisibilityValues.some(editorVisibilityValue=>editorVisibilityValue);});if(editorUIsToUpdate.length>0&&!optionsSectionVisible){return null;}
return this._customize$Elements;},toggleTargetVisibility:async function(show,ignoreDeviceVisibility){show=this._toggleVisibilityStatus(show,ignoreDeviceVisibility);var styles=Object.values(this.styles);const proms=sortBy(styles,"__order").map((style)=>{return show?style.onTargetShow():style.onTargetHide();});await Promise.all(proms);return show;},toggleOverlayVisibility:function(show){if(this.$el&&!this.scrollingTimeout){this.$el.toggleClass('o_overlay_hidden',(!show||this.$target[0].matches('.o_animating:not(.o_animate_on_scroll)'))&&this.isShown());}},async updateOptionsUI(assetsChanged){const proms=Object.values(this.styles).map(opt=>{return opt.updateUI({noVisibility:true,assetsChanged:assetsChanged});});return Promise.all(proms);},async updateOptionsUIVisibility(){const proms=Object.values(this.styles).map(opt=>{return opt.updateUIVisibility();});const someOptionsVisible=await Promise.all(proms).then(optionsVisibilityValues=>{return optionsVisibilityValues.some(optionsVisibilityValue=>optionsVisibilityValue);});const visibleOptionsInSection=this.$optionsSection.find('we-top-button-group, we-customizeblock-option').children(':not(.d-none)').length;const optionsSectionEmpty=!this.$optionsSection[0].querySelector(":scope > we-customizeblock-option");const optionsSectionVisible=visibleOptionsInSection&&!optionsSectionEmpty;this.$optionsSection.toggleClass("d-none",!optionsSectionVisible);return optionsSectionVisible||someOptionsVisible;},clone:async function(recordUndo){this.trigger_up('snippet_will_be_cloned',{$target:this.$target});await new Promise(resolve=>{this.trigger_up("clean_ui_request",{targetEl:this.$target[0],onSuccess:resolve,});});var $clone=this.$target.clone(false);this.$target.after($clone);if(recordUndo){this.options.wysiwyg.odooEditor.historyStep(true);}
await new Promise(resolve=>{this.trigger_up('call_for_each_child_snippet',{$snippet:$clone,callback:function(editor,$snippet){for(var i in editor.styles){editor.styles[i].onClone({isCurrent:($snippet.is($clone)),});}},onSuccess:resolve,});});this.trigger_up('snippet_cloned',{$target:$clone,$origin:this.$target});$clone.trigger('content_changed');},_initializeOptions:function(){this._customize$Elements=[];this.styles={};this.selectorSiblings=[];this.selectorChildren=[];this.selectorLockWithin=new Set();const selectorExcludeAncestor=new Set();if(this.options.allowParentsEditors){var $element=this.$target.parent();while($element.length){var parentEditor=$element.data('snippet-editor');if(parentEditor){this._customize$Elements=this._customize$Elements.concat(parentEditor._customize$Elements);break;}
$element=$element.parent();}}
var $optionsSection=$(renderToElement('web_editor.customize_block_options_section',{name:this.getName(),})).data('editor',this);const $optionsSectionBtnGroup=$optionsSection.find('we-top-button-group');$optionsSectionBtnGroup.contents().each((i,node)=>{if(node.nodeType===Node.TEXT_NODE){node.parentNode.removeChild(node);}});this.$optionsSection=$optionsSection;$optionsSection.on('mouseenter',this._onOptionsSectionMouseEnter.bind(this));$optionsSection.on('mouseleave',this._onOptionsSectionMouseLeave.bind(this));$optionsSection.on('click','we-title > span',this._onOptionsSectionClick.bind(this));$optionsSection.on('click','.oe_snippet_clone',this._onCloneClick.bind(this));$optionsSection.on('click','.oe_snippet_remove',this._onRemoveClick.bind(this));this._customize$Elements.push($optionsSection);this.$el.data('$optionsSection',$optionsSection);var i=0;var defs=this.templateOptions.map((val)=>{if(!val.selector.is(this.$target)){return;}
if(val.data.string){$optionsSection[0].querySelector('we-title > span').textContent=val.data.string;}
if(val['drop-near']){this.selectorSiblings.push(val['drop-near']);}
if(val['drop-in']){this.selectorChildren.push(val['drop-in']);}
if(val['drop-lock-within']){this.selectorLockWithin.add(val['drop-lock-within']);}
if(val['drop-exclude-ancestor']){selectorExcludeAncestor.add(val['drop-exclude-ancestor']);}
var optionName=val.option;var option=new(options.registry[optionName]||options.Class)(this,val.$el.children(),val.base_target?this.$target.find(val.base_target).eq(0):this.$target,this.$el,Object.assign({optionName:optionName,snippetName:this.getName(),},val.data),this.options);var key=optionName||uniqueId("option");if(this.styles[key]){key=uniqueId(key);}
this.styles[key]=option;option.__order=i++;if(option.forceNoDeleteButton){this.$el.add($optionsSection).find('.oe_snippet_remove').addClass('d-none');this.$el.add($optionsSection).find('.oe_snippet_clone').addClass('d-none');}
if(option.displayOverlayOptions){this.displayOverlayOptions=true;}
if(option.forceDuplicateButton){this.forceDuplicateButton=true;}
return option.appendTo(document.createDocumentFragment());});if(selectorExcludeAncestor.size){const excludedAncestorSelector=[...selectorExcludeAncestor].join(", ");this.excludeAncestors=(i,el)=>!el.closest(excludedAncestorSelector);}
this.isTargetMovable=(this.selectorSiblings.length>0||this.selectorChildren.length>0);this.$el.find('[data-bs-toggle="dropdown"]').dropdown();return Promise.all(defs).then(async()=>{const options=sortBy(Object.values(this.styles),"__order");const firstOptions=[];options.forEach(option=>{if(option.isTopOption){if(option.isTopFirstOption){firstOptions.push(option);}else{$optionsSectionBtnGroup.prepend(option.$el);}}else{$optionsSection.append(option.$el);}});firstOptions.forEach(option=>{$optionsSectionBtnGroup.prepend(option.$el);});$optionsSection.toggleClass('d-none',options.length===0);});},_initDragAndDrop(handle,elementsSelector,element){const modalAncestorEl=this.$target[0].closest('.modal');const $scrollable=modalAncestorEl&&$(modalAncestorEl)||(this.options.$scrollable)||(this.$scrollingElement.length&&this.$scrollingElement)||$().getScrollingElement(this.ownerDocument);const dragAndDropOptions={ref:{el:element},elements:elementsSelector,handle:handle,scrollingElement:$scrollable[0],enable:()=>!!this.$el.find('.o_move_handle:visible').length||this.dragStarted,helper:()=>{const cloneEl=this.$el[0].cloneNode(true);cloneEl.style.width="24px";cloneEl.style.height="24px";cloneEl.style.border="0";this.$el[0].ownerDocument.body.appendChild(cloneEl);cloneEl.classList.remove("d-none");cloneEl.classList.remove("o_dragged");return cloneEl;},onDragStart:(args)=>{this.dragStarted=true;const targetRect=this.$target[0].getBoundingClientRect();const gridRowSize=gridUtils.rowSize;const boundedYMousePosition=Math.min(args.y,targetRect.bottom-gridRowSize);this.mousePositionYOnElement=boundedYMousePosition-targetRect.y;this.mousePositionXOnElement=(args.x-targetRect.x)*(this.isRtl?-1:1);this._onDragAndDropStart(args);},onDragEnd:(...args)=>{if(!this.dragStarted){return false;}
this.dragStarted=false;setTimeout(()=>{this._onDragAndDropStop(...args);},0);},onDrag:this._onDragMove.bind(this),dropzoneOver:this.dropzoneOver.bind(this),dropzoneOut:this.dropzoneOut.bind(this),dropzones:()=>this.$dropZones?.toArray()||[],};const finalOptions=this.options.getDragAndDropOptions(dragAndDropOptions);return useDragAndDrop(finalOptions);},_toggleVisibilityStatus:function(show,ignoreDeviceVisibility){if(ignoreDeviceVisibility){if(this.$target[0].matches(".o_snippet_mobile_invisible, .o_snippet_desktop_invisible")){const isMobilePreview=weUtils.isMobileView(this.$target[0]);const isMobileHidden=this.$target[0].classList.contains("o_snippet_mobile_invisible");if(isMobilePreview===isMobileHidden){show=false;}}}
if(show===undefined){show=!this.isTargetVisible();}
if(show){delete this.$target[0].dataset.invisible;}else{this.$target[0].dataset.invisible='1';}
return show;},_canBeSanitizedUnless(el){let result=true;for(const snippetEl of[el,...el.querySelectorAll('[data-snippet]')]){this.trigger_up('find_snippet_template',{snippet:snippetEl,callback:function(snippet){const forbidSanitize=snippet.data.oeForbidSanitize;if(forbidSanitize){result=forbidSanitize==='form'?'form':false;}},});if(!result){break;}}
return result;},_outPreviousDropzone(self,currentDropzoneEl){const previousDropzoneEl=this;const rowEl=previousDropzoneEl.parentNode;if(rowEl.classList.contains('o_grid_mode')){self.dragState.gridMode=false;const fromGridToGrid=currentDropzoneEl.classList.contains('oe_grid_zone');if(fromGridToGrid){rowEl.style.removeProperty('position');}else{gridUtils._gridCleanUp(rowEl,self.$target[0]);self.$target[0].style.removeProperty('z-index');}
self.dragState.dragHelperEl.remove();self.dragState.backgroundGridEl.remove();self.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');gridUtils._resizeGrid(rowEl);self.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');const rowCount=parseInt(rowEl.dataset.rowCount);previousDropzoneEl.style.gridRowEnd=Math.max(rowCount+1,1);}
previousDropzoneEl.classList.remove('invisible');},_prepareDrag(){return()=>{};},_onCloneClick:function(ev){ev.preventDefault();this.clone(true);},_onDragAndDropStart({helper,addStyle}){this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');this.trigger_up('drag_and_drop_start');this.options.wysiwyg.odooEditor.automaticStepUnactive();var self=this;this.dragState={};const rowEl=this.$target[0].parentNode;this.dragState.overFirstDropzone=true;this.dragState.restore=this._prepareDrag();let hasGridLayoutOption=false;this.trigger_up('user_value_widget_request',{name:'grid_mode',allowParentOption:true,onSuccess:(widget)=>{if(widget.$target[0]===rowEl.parentElement){hasGridLayoutOption=true;}},});const allowGridMode=hasGridLayoutOption||rowEl.classList.contains('o_grid_mode');if(rowEl.classList.contains('row')&&this.options.isWebsite){if(allowGridMode){if(!rowEl.classList.contains('o_grid_mode')){this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');const containerEl=rowEl.parentNode;gridUtils._toggleGridMode(containerEl);this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');}
const columnStart=self.$target[0].style.gridColumnStart;const columnEnd=self.$target[0].style.gridColumnEnd;const rowStart=self.$target[0].style.gridRowStart;const rowEnd=self.$target[0].style.gridRowEnd;this.dragState.columnColCount=columnEnd-columnStart;this.dragState.columnRowCount=rowEnd-rowStart;this.dragState.startingGrid=rowEl;this.dragState.prevGridArea=self.$target[0].style.gridArea;this.dragState.startingZIndex=self.$target[0].style.zIndex;gridUtils._reloadLazyImages(this.$target[0]);}else{const isImageColumn=gridUtils._checkIfImageColumn(this.$target[0]);if(isImageColumn){const imageEl=this.$target[0].querySelector('img');this.dragState.columnWidth=parseFloat(imageEl.scrollWidth);this.dragState.columnHeight=parseFloat(imageEl.scrollHeight);}else{this.dragState.columnWidth=parseFloat(this.$target[0].scrollWidth);this.dragState.columnHeight=parseFloat(this.$target[0].scrollHeight);}
const style=window.getComputedStyle(this.$target[0]);this.dragState.columnWidth+=parseFloat(style.borderLeft)+parseFloat(style.borderRight);this.dragState.columnHeight+=parseFloat(style.borderTop)+parseFloat(style.borderBottom);}
this.dragState.columnTop=this.$target[0].getBoundingClientRect().top;this.dragState.isColumn=true;this.trigger_up('deactivate_snippet',{$snippet:self.$target});}
const targetMobileOrder=this.$target[0].style.order;if(targetMobileOrder){this.dragState.startingParent=this.$target[0].parentNode;this.dragState.mobileOrder=parseInt(targetMobileOrder);}
const toInsertInline=window.getComputedStyle(this.$target[0]).display.includes('inline');this.dropped=false;this._dropSiblings={prev:self.$target.prev()[0],next:self.$target.next()[0],};self.size={width:self.$target.width(),height:self.$target.height()};const dropCloneEl=document.createElement("div");dropCloneEl.classList.add("oe_drop_clone");dropCloneEl.style.setProperty("display","none");self.$target[0].after(dropCloneEl);self.$target.detach();self.$el.addClass('d-none');var $selectorSiblings=$();for(var i=0;i<self.selectorSiblings.length;i++){let $siblings=self.selectorSiblings[i].all();if(this.excludeAncestors){$siblings=$siblings.filter(this.excludeAncestors);}
$selectorSiblings=$selectorSiblings?$selectorSiblings.add($siblings):$siblings;}
var $selectorChildren;for(i=0;i<self.selectorChildren.length;i++){let $children=self.selectorChildren[i].all();if(this.excludeAncestors){$children=$children.filter(this.excludeAncestors);}
$selectorChildren=$selectorChildren?$selectorChildren.add($children):$children;}
for(const lockedParentSelector of this.selectorLockWithin){const closestLockedParentEl=dropCloneEl.closest(lockedParentSelector);const filterFunc=(i,el)=>el.closest(lockedParentSelector)===closestLockedParentEl;if($selectorSiblings){$selectorSiblings=$selectorSiblings.filter(filterFunc);}
if($selectorChildren){$selectorChildren=$selectorChildren.filter(filterFunc);}}
const canBeSanitizedUnless=this._canBeSanitizedUnless(this.$target[0]);const selectorGrids=new Set();const filterOutSelectorGrids=($selectorItems,getDropzoneParent)=>{if(!$selectorItems){return;}
for(let i=$selectorItems.length-1;i>=0;i--){const el=getDropzoneParent($selectorItems[i]);if(el.classList.contains('o_grid_mode')){$selectorItems.splice(i,1);selectorGrids.add(el);}}};filterOutSelectorGrids($selectorSiblings,el=>el.parentElement);filterOutSelectorGrids($selectorChildren,el=>el);this.trigger_up('activate_snippet',{$snippet:this.$target.parent()});this.trigger_up('activate_insertion_zones',{$selectorSiblings:$selectorSiblings,$selectorChildren:$selectorChildren,canBeSanitizedUnless:canBeSanitizedUnless,toInsertInline:toInsertInline,selectorGrids:selectorGrids,fromIframe:true,});this.$body.addClass('move-important');this.$dropZones=this.$editable.find('.oe_drop_zone');if(!canBeSanitizedUnless){this.$dropZones=this.$dropZones.not('[data-oe-sanitize] .oe_drop_zone');}else if(canBeSanitizedUnless==='form'){this.$dropZones=this.$dropZones.not('[data-oe-sanitize][data-oe-sanitize!="allow_form"] .oe_drop_zone');}},dropzoneOver({dropzone}){if(this.dropped){this.$target.detach();}
if(this.dragState.isColumn&&this.dragState.overFirstDropzone){this.dragState.overFirstDropzone=false;const columnTop=this.dragState.columnTop;const dropzoneBottom=dropzone.el.getBoundingClientRect().bottom;const areDropzonesGlued=(columnTop>=dropzoneBottom)&&(columnTop-dropzoneBottom<25);if(areDropzonesGlued&&dropzone.el.classList.contains('oe_grid_zone')){return;}}
this.dropped=true;const $dropzone=$(dropzone.el).first().after(this.$target);$dropzone.addClass('invisible');if(this.dragState.currentDropzoneEl){this._outPreviousDropzone.apply(this.dragState.currentDropzoneEl,[this,$dropzone[0]]);}
this.dragState.currentDropzoneEl=$dropzone[0];if($dropzone[0].classList.contains('oe_grid_zone')){const rowEl=$dropzone[0].parentNode;if(!this.$target[0].classList.contains('o_grid_item')){this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');const spans=gridUtils._convertColumnToGrid(rowEl,this.$target[0],this.dragState.columnWidth,this.dragState.columnHeight);this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');this.dragState.columnColCount=spans.columnColCount;this.dragState.columnRowCount=spans.columnRowCount;}
const columnColCount=this.dragState.columnColCount;const columnRowCount=this.dragState.columnRowCount;const dragHelperEl=document.createElement('div');dragHelperEl.classList.add('o_we_drag_helper');dragHelperEl.style.gridArea=`1 / 1 / ${1 + columnRowCount} / ${1 + columnColCount}`;rowEl.append(dragHelperEl);const backgroundGridEl=gridUtils._addBackgroundGrid(rowEl,columnRowCount);const rowCount=Math.max(rowEl.dataset.rowCount,columnRowCount);$dropzone[0].style.gridRowEnd=rowCount+1;this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');if(rowEl===this.dragState.startingGrid){this.$target[0].style.zIndex=this.dragState.startingZIndex;}else{gridUtils._setElementToMaxZindex(this.$target[0],rowEl);}
gridUtils._setElementToMaxZindex(backgroundGridEl,rowEl);gridUtils._setElementToMaxZindex(dragHelperEl,rowEl);const gridProp=gridUtils._getGridProperties(rowEl);const columnHeight=columnRowCount*(gridProp.rowSize+gridProp.rowGap)-gridProp.rowGap;const columnWidth=columnColCount*(gridProp.columnSize+gridProp.columnGap)-gridProp.columnGap;this.$target[0].style.height=columnHeight+'px';this.$target[0].style.width=columnWidth+'px';this.$target[0].style.position='absolute';this.$target[0].style.removeProperty('grid-area');rowEl.style.position='relative';this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');this.dragState.startingHeight=rowEl.clientHeight;this.dragState.currentHeight=rowEl.clientHeight;this.dragState.dragHelperEl=dragHelperEl;this.dragState.backgroundGridEl=backgroundGridEl;this.dragState.gridMode=true;}},dropzoneOut({dropzone}){const rowEl=dropzone.el.parentNode;const sameDropzoneAsCurrent=this.dragState.currentDropzoneEl===dropzone.el;if(sameDropzoneAsCurrent){if(rowEl.classList.contains('o_grid_mode')){this.dragState.gridMode=false;gridUtils._gridCleanUp(rowEl,this.$target[0]);this.$target[0].style.removeProperty('z-index');this.dragState.dragHelperEl.remove();this.dragState.backgroundGridEl.remove();this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');gridUtils._resizeGrid(rowEl);this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');const rowCount=parseInt(rowEl.dataset.rowCount);dropzone.el.style.gridRowEnd=Math.max(rowCount+1,1);}
var prev=this.$target.prev();if(dropzone.el===prev[0]){this.dropped=false;this.$target.detach();$(dropzone.el).removeClass('invisible');}
delete this.dragState.currentDropzoneEl;}},_onDragAndDropStop({x,y}){this.options.wysiwyg.odooEditor.automaticStepActive();this.options.wysiwyg.odooEditor.automaticStepSkipStack();this.options.wysiwyg.odooEditor.unbreakableStepUnactive();const rowEl=this.$target[0].parentNode;if(rowEl&&rowEl.classList.contains('o_grid_mode')){this.dragState.gridMode=false;const gridProp=gridUtils._getGridProperties(rowEl);const style=window.getComputedStyle(this.$target[0]);const top=parseFloat(style.top);const left=parseFloat(this.isRtl?style.right:style.left);const rowStart=Math.round(top/(gridProp.rowSize+gridProp.rowGap))+1;const columnStart=Math.round(left/(gridProp.columnSize+gridProp.columnGap))+1;const rowEnd=rowStart+this.dragState.columnRowCount;const columnEnd=columnStart+this.dragState.columnColCount;this.$target[0].style.gridArea=`${rowStart} / ${columnStart} / ${rowEnd} / ${columnEnd}`;gridUtils._gridCleanUp(rowEl,this.$target[0]);this.dragState.dragHelperEl.remove();this.dragState.backgroundGridEl.remove();this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');gridUtils._resizeGrid(rowEl);this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');}else if(this.$target[0].classList.contains('o_grid_item')&&this.dropped){this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');gridUtils._convertToNormalColumn(this.$target[0]);this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');}
if(!this.dropped){let $el=$(closest(this.$body[0].querySelectorAll('.oe_drop_zone'),{x,y}));$el=$el.filter(this.$dropZones);if($el.length){$el.after(this.$target);if($el[0].classList.contains('oe_grid_zone')){const rowEl=$el[0].parentNode;if(!this.$target[0].classList.contains('o_grid_item')){this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');const spans=gridUtils._convertColumnToGrid(rowEl,this.$target[0],this.dragState.columnWidth,this.dragState.columnHeight);this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');this.dragState.columnColCount=spans.columnColCount;this.dragState.columnRowCount=spans.columnRowCount;}
this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');this.$target[0].style.gridArea=`1 / 1 / ${1 + this.dragState.columnRowCount} / ${1 + this.dragState.columnColCount}`;const rowCount=Math.max(rowEl.dataset.rowCount,this.dragState.columnRowCount);rowEl.dataset.rowCount=rowCount;this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');if(rowEl===this.dragState.startingGrid){this.$target[0].style.zIndex=this.dragState.startingZIndex;}else{gridUtils._setElementToMaxZindex(this.$target[0],rowEl);}}else{if(this.$target[0].classList.contains('o_grid_item')){this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');gridUtils._convertToNormalColumn(this.$target[0]);this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');}}
this.dropped=true;}}
if(this.dragState.startingGrid){this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');gridUtils._resizeGrid(this.dragState.startingGrid);this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');}
this.$editable.find('.oe_drop_zone').remove();var prev=this.$target.first()[0].previousSibling;var next=this.$target.last()[0].nextSibling;var $parent=this.$target.parent();var $clone=this.$editable.find('.oe_drop_clone');if(prev===$clone[0]){prev=$clone[0].previousSibling;}else if(next===$clone[0]){next=$clone[0].nextSibling;}
$clone.after(this.$target);var $from=$clone.parent();this.$el.removeClass('d-none');this.$body.removeClass('move-important');$clone.remove();this.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');if(this.dropped){if(prev){this.$target.insertAfter(prev);}else if(next){this.$target.insertBefore(next);}else{$parent.prepend(this.$target);}
for(var i in this.styles){this.styles[i].onMove();}
if(this.dragState.mobileOrder!==undefined&&this.$target[0].parentNode!==this.dragState.startingParent){ColumnLayoutMixin._fillRemovedItemGap(this.dragState.startingParent,this.dragState.mobileOrder);}
this.$target.trigger('content_changed');$from.trigger('content_changed');}
this.trigger_up('drag_and_drop_stop',{$snippet:this.$target,});const samePositionAsStart=this.$target[0].classList.contains('o_grid_item')?(this.$target[0].parentNode===this.dragState.startingGrid&&this.$target[0].style.gridArea===this.dragState.prevGridArea):this._dropSiblings.prev===this.$target.prev()[0]&&this._dropSiblings.next===this.$target.next()[0];if(!samePositionAsStart){this.options.wysiwyg.odooEditor.historyStep();}
this.dragState.restore();delete this.$dropZones;delete this.dragState;},_onOptionsSectionMouseEnter:function(ev){if(!this.$target.is(':visible')){return;}
this.trigger_up('activate_snippet',{$snippet:this.$target,previewMode:true,});},_onOptionsSectionMouseLeave:function(ev){this.trigger_up('activate_snippet',{$snippet:false,previewMode:true,});},_onOptionsSectionClick:function(ev){this.trigger_up('activate_snippet',{$snippet:this.$target,previewMode:false,});},_onOptionUpdate:function(ev){var self=this;if(ev.data.optionNames){ev.stopPropagation();ev.data.optionNames.forEach((name)=>{notifyForEachMatchedOption(name);});}
if(ev.data.optionName){if(notifyForEachMatchedOption(ev.data.optionName)){ev.stopPropagation();}}
function notifyForEachMatchedOption(name){var regex=new RegExp('^'+name+'\\d+$');var hasOption=false;for(var key in self.styles){if(key===name||regex.test(key)){self.styles[key].notify(ev.data.name,ev.data.data);hasOption=true;}}
return hasOption;}},_onRemoveClick:function(ev){ev.preventDefault();ev.stopPropagation();this.trigger_up('snippet_edition_request',{exec:this.removeSnippet.bind(this)});},_onSnippetOptionVisibilityUpdate:function(ev){if(this.options.wysiwyg.isSaving()){return;}
ev.data.show=this._toggleVisibilityStatus(ev.data.show);if(this.$target[0]===ev.target.$target[0]&&!ev.data.show){this.trigger_up("activate_snippet",{$snippet:false});ev.data.show=true;}},_onUserValueWidgetRequest:function(ev){for(const key of Object.keys(this.styles)){const widget=this.styles[key].findWidget(ev.data.name);if(widget){ev.stopPropagation();ev.data.onSuccess(widget);return;}}
if(!ev.data.allowParentOption){ev.stopPropagation();}},_onMouseWheel:function(ev){ev.stopPropagation();this.$el.css('pointer-events','none');clearTimeout(this.wheelTimeout);this.wheelTimeout=setTimeout(()=>{this.$el.css('pointer-events','');},250);},_onSendBackClick(ev){ev.stopPropagation();const rowEl=this.$target[0].parentNode;const columnEls=[...rowEl.children].filter(el=>el!==this.$target[0]);const minZindex=Math.min(...columnEls.map(el=>el.style.zIndex));if(minZindex>0){this.$target[0].style.zIndex=minZindex-1;}else{for(const columnEl of columnEls){columnEl.style.zIndex++;}
this.$target[0].style.zIndex=0;}},_onBringFrontClick(ev){ev.stopPropagation();const rowEl=this.$target[0].parentNode;gridUtils._setElementToMaxZindex(this.$target[0],rowEl);},_onDragMove({x,y}){if(!this.dragState.gridMode||!this.dragState.currentDropzoneEl){return;}
const columnEl=this.$target[0];const rowEl=columnEl.parentNode;const rowElRect=rowEl.getBoundingClientRect();const rowElTop=rowElRect.top;const rowElLeft=rowElRect.left;const borderWidth=parseFloat(window.getComputedStyle(columnEl).borderWidth);const columnHeight=columnEl.clientHeight+2*borderWidth;const columnWidth=columnEl.clientWidth+2*borderWidth;let top=y-rowElTop-this.mousePositionYOnElement;const bottom=top+columnHeight;let left;if(this.isRtl){const rowElRight=rowElRect.right;left=rowElRight-x-this.mousePositionXOnElement-columnWidth;}else{left=x-rowElLeft-this.mousePositionXOnElement;}
left=clamp(left,0,rowEl.clientWidth-columnWidth);top=top<0?0:top;columnEl.style.top=top+'px';if(this.isRtl){columnEl.style.right=left+'px';}else{columnEl.style.left=left+'px';}
const gridProp=gridUtils._getGridProperties(rowEl);const rowStart=Math.round(top/(gridProp.rowSize+gridProp.rowGap))+1;const columnStart=Math.round(left/(gridProp.columnSize+gridProp.columnGap))+1;const rowEnd=rowStart+this.dragState.columnRowCount;const columnEnd=columnStart+this.dragState.columnColCount;const dragHelperEl=this.dragState.dragHelperEl;if(parseInt(dragHelperEl.style.gridRowStart)!==rowStart){dragHelperEl.style.gridRowStart=rowStart;dragHelperEl.style.gridRowEnd=rowEnd;}
if(parseInt(dragHelperEl.style.gridColumnStart)!==columnStart){dragHelperEl.style.gridColumnStart=columnStart;dragHelperEl.style.gridColumnEnd=columnEnd;}
const startingHeight=this.dragState.startingHeight;const currentHeight=this.dragState.currentHeight;const backgroundGridEl=this.dragState.backgroundGridEl;const dropzoneEl=this.dragState.currentDropzoneEl;const rowOverflow=Math.round((bottom-currentHeight)/(gridProp.rowSize+gridProp.rowGap));const updateRows=bottom>currentHeight||bottom<=currentHeight&&bottom>startingHeight;const rowCount=Math.max(rowEl.dataset.rowCount,this.dragState.columnRowCount);const maxRowEnd=rowCount+gridUtils.additionalRowLimit+1;if(Math.abs(rowOverflow)>=1&&updateRows){if(rowEnd<=maxRowEnd){const dropzoneEnd=parseInt(dropzoneEl.style.gridRowEnd);dropzoneEl.style.gridRowEnd=dropzoneEnd+rowOverflow;backgroundGridEl.style.gridRowEnd=dropzoneEnd+rowOverflow;this.dragState.currentHeight+=rowOverflow*(gridProp.rowSize+gridProp.rowGap);}else{dropzoneEl.style.gridRowEnd=maxRowEnd;backgroundGridEl.style.gridRowEnd=maxRowEnd;this.dragState.currentHeight=(maxRowEnd-1)*(gridProp.rowSize+gridProp.rowGap)-gridProp.rowGap;}}},_onReplaceClick(ev){ev.stopPropagation();this.trigger_up('open_add_snippet_dialog',{initialSnippetEl:this.$target[0],});},});class SnippetsMenu extends Component{static cacheSnippetTemplate={};static custom_events={'activate_insertion_zones':'_onActivateInsertionZones','activate_snippet':'_onActivateSnippet','call_for_each_child_snippet':'_onCallForEachChildSnippet','clone_snippet':'_onCloneSnippet',"clean_ui_request":"_onCleanUIRequest",'cover_update':'_onOverlaysCoverUpdate','deactivate_snippet':'_onDeactivateSnippet','drag_and_drop_stop':'_onSnippetDragAndDropStop','drag_and_drop_start':'_onSnippetDragAndDropStart','get_snippet_versions':'_onGetSnippetVersions','find_snippet_template':'_onFindSnippetTemplate','is_element_selected':'_onIsElementSelected','remove_snippet':'_onRemoveSnippet','snippet_edition_request':'_onSnippetEditionRequest','snippet_editor_destroyed':'_onSnippetEditorDestroyed','snippet_removed':'_onSnippetRemoved','snippet_cloned':'_onSnippetCloned','snippet_option_update':'_onSnippetOptionUpdate','snippet_option_visibility_update':'_onSnippetOptionVisibilityUpdate','snippet_thumbnail_url_request':'_onSnippetThumbnailURLRequest','request_save':'_onSaveRequest','hide_overlay':'_onHideOverlay','block_preview_overlays':'_onBlockPreviewOverlays','unblock_preview_overlays':'_onUnblockPreviewOverlays','user_value_widget_opening':'_onUserValueWidgetOpening','user_value_widget_closing':'_onUserValueWidgetClosing','reload_snippet_template':'_onReloadSnippetTemplate','request_editable':'_onRequestEditable','disable_loading_effect':'_onDisableLoadingEffect','enable_loading_effect':'_onEnableLoadingEffect',"update_invisible_dom":"_onUpdateInvisibleDom","open_add_snippet_dialog":"_onOpenAddSnippetDialog",};static tabs={BLOCKS:'blocks',OPTIONS:'options',CUSTOM:'custom',};static props={bus:{type:EventBus},mountedProm:{type:Promise},options:{type:Object},trigger_up:{type:Function},folded:{type:Boolean,optional:true},onSnippetDropped:{type:Function,optional:true},readyToCleanForSave:{type:Function,optional:true},setCSSVariables:{type:Function,optional:true},};static defaultProps={folded:false,onSnippetDropped:()=>{},readyToCleanForSave:()=>{},setCSSVariables:()=>{},};static template="web_editor.SnippetsMenu";static components={Toolbar,LinkTools};setup(){super.setup(...arguments);this.options=Object.assign({},this.props.options);this.$body=$((this.options.document||document).body);this.customEvents=SnippetsMenu.custom_events;this.tabs=SnippetsMenu.tabs;this.state=useState({showCustomizePanel:false,invisibleElements:[],currentTab:SnippetsMenu.tabs.BLOCKS,toolbarTitle:"",showToolbar:false,search:"",canUndo:false,canRedo:false,});this.snippets=useState(new Map());this.snippetsMenuRef=useRef("snippets-menu");this.toolbarWrapperRef=useRef("toolbar-wrapper");this.customizePanelRef=useRef("customize-panel");this.snippetsAreaRef=useRef("snippets-area");this.snippetEditors=[];this._enabledEditorHierarchy=[];this._mutex=this.options.mutex;this._notActivableElementsSelector=['#web_editor-top-edit','.o_we_website_top_actions','#oe_snippets','#oe_manipulators','.o_technical_modal','.oe_drop_zone','.o_notification_manager','.o_we_no_overlay','.ui-autocomplete','.modal .btn-close','.o_we_crop_widget','.transfo-container','.o_datetime_picker',].join(', ');this.loadingTimers={};this.loadingElements={};this._loadingEffectDisabled=false;this._onClick=this._onClick.bind(this);this.options.reloadSnippetDropzones=this.reloadSnippetDropzones.bind(this);this.orm=useService("orm");this.notification=useService("notification");this.dialog=useService("dialog");this.popover=useService("popover");onWillStart(()=>{this.options.wysiwyg.getColorpickerTemplate();this.options.wysiwyg.toolbarEl.classList.add("d-none");});onMounted(async()=>{await this.start();this.props.setCSSVariables(this.snippetsMenuRef.el);const titleButtons=this.customizePanel.querySelector("#o_we_editor_toolbar_container > we-title");this.options.wysiwyg.odooEditor.bindExecCommand(titleButtons);const customizeTableBlock=this.customizePanel.querySelector('#o-we-editor-table-container');this.options.wysiwyg.odooEditor.bindExecCommand(customizeTableBlock);this.props.mountedProm.resolve();this.el.classList.add("o_loaded");this.el.ownerDocument.body.classList.toggle('editor_has_snippets',!this.folded);});onWillUnmount(()=>{this.onWillUnmount();});useEffect((folded)=>{this.setFolded(folded);},()=>[this.props.folded]);useBus(this.props.bus,"ACTIVATE_SNIPPET",({detail})=>{const{$snippet,previewMode,onSuccess}=detail;this._activateSnippet($snippet,previewMode).then(onSuccess);});useBus(this.props.bus,"CALL_POST_SNIPPET_DROP",({detail})=>{this.callPostSnippetDrop(detail.$snippet).then(detail.onSuccess);});useBus(this.props.bus,"INSERT_SNIPPET",({detail})=>{const{snippetSelector}=detail;this._execWithLoadingEffect(()=>{const snippet=[...this.snippets.values()].find((snippet)=>{return snippet.baseBody.matches(snippetSelector);});if(snippet){const clonedBody=snippet.baseBody.cloneNode(true);clonedBody.classList.remove(".oe_snippet_body");this.options.wysiwyg.odooEditor.execCommand("insert",clonedBody);this.callPostSnippetDrop($(clonedBody));}});});useBus(this.props.bus,"CLEAN_FOR_SAVE",({detail})=>{detail.proms.push(this.cleanForSave());});useBus(this.props.bus,"UPDATE_SCROLLING_ELEMENT",({detail})=>{this.draggableComponent?.update({scrollingElement:detail.scrollingElement});});}
get invalidateSnippetCache(){return!!this._invalidateSnippetCache;}
set invalidateSnippetCache(invalidate){this._invalidateSnippetCache=invalidate;}
get hasSnippetGroups(){return Array.from(this.snippets.values()).some(snippet=>snippet.snippetGroup);}
_createTooltip($el,title,selector=false){return new Tooltip($el,{title:title,selector:selector,placement:"bottom",delay:100,container:this.el,boundary:this.el.ownerDocument.body,});}
async start(){this.el=this.snippetsMenuRef.el;this.$el=$(this.el);this.$=this.$el.find.bind(this.$el);this.customizePanel=this.customizePanelRef.el;const defs=[];this.ownerDocument=this.$el[0].ownerDocument;this.$document=$(this.ownerDocument);this.window=this.ownerDocument.defaultView;this.$window=$(this.window);this.$el=this.window.$(this.$el);this.$el.data('snippetMenu',this);this.__onTouchEvent=this._onTouchEvent.bind(this);document.addEventListener("touchstart",this.__onTouchEvent,true);document.addEventListener("touchmove",this.__onTouchEvent,true);document.addEventListener("touchend",this.__onTouchEvent,true);this._toolbarWrapperEl=this.toolbarWrapperRef.el;this._toolbarWrapperEl.style.display='contents';const toolbarEl=this._toolbarWrapperEl.firstChild;toolbarEl.classList.remove('oe-floating');this.options.wysiwyg.setupToolbar(toolbarEl);this._addToolbar();this._checkEditorToolbarVisibilityCallback=this._checkEditorToolbarVisibility.bind(this);$(this.options.wysiwyg.odooEditor.document.body).on('click',this._checkEditorToolbarVisibilityCallback);this.$snippetEditorArea=$('<div/>',{id:'oe_manipulators',});this.$body.prepend(this.$snippetEditorArea);this.options.getDragAndDropOptions=this._getDragAndDropOptions.bind(this);this.tooltips=this._createTooltip(this.el,function(){const el=this===undefined?arguments[0]:this.el;el.style.setProperty('overflow','scroll','important');const tipContent=el.scrollWidth>el.clientWidth?el.innerHTML:'';el.style.removeProperty('overflow');return tipContent;},"we-title");this.buttonTooltips=[];document.querySelectorAll("[title]:not(.oe_snippet)").forEach(el=>{this.buttonTooltips.push(this._createTooltip(el,function(){const el=this===undefined?arguments[0]:this.el;return el.title;}));});this.$document.on('click.snippets_menu','*',this._onClick);this.$document.on('mouseup.snippets_menu','.dropdown-toggle',this._onClick);if(this.$body[0].ownerDocument!==this.ownerDocument){this.$body.on('click.snippets_menu','*',this._onClick);}
this.debouncedCoverUpdate=throttleForAnimation(()=>{this.updateCurrentSnippetEditorOverlay();});this.$window.on("resize.snippets_menu",this.debouncedCoverUpdate);this.$body.on("content_changed.snippets_menu",this.debouncedCoverUpdate);$(this.$body[0].ownerDocument.defaultView).on("resize.snippets_menu",this.debouncedCoverUpdate);this.$body.on('keydown.snippets_menu',()=>{this.__overlayKeyWasDown=true;this.snippetEditors.forEach(editor=>{editor.toggleOverlayVisibility(false);});});this.$body.on('mousemove.snippets_menu, mousedown.snippets_menu',throttleForAnimation(()=>{if(!this.__overlayKeyWasDown){return;}
this.__overlayKeyWasDown=false;this.snippetEditors.forEach(editor=>{editor.toggleOverlayVisibility(true);editor.cover();});}));this.$scrollingElement=$().getScrollingElement(this.$body[0].ownerDocument);if(!this.$scrollingElement[0]){this.$scrollingElement=$(this.ownerDocument).find('.o_editable');}
this.$scrollingTarget=$().getScrollingTarget(this.$scrollingElement);this._onScrollingElementScroll=throttleForAnimation(()=>{for(const editor of this.snippetEditors){editor.toggleOverlayVisibility(false);}
clearTimeout(this.scrollingTimeout);this.scrollingTimeout=setTimeout(()=>{this._scrollingTimeout=null;for(const editor of this.snippetEditors){editor.toggleOverlayVisibility(true);editor.cover();}},250);});this.$scrollingTarget[0].addEventListener('scroll',this._onScrollingElementScroll,{capture:true});if(this.options.enableTranslation){await this._loadSnippetsTemplates();defs.push(this._updateInvisibleDOM());this.state.currentTab=SnippetsMenu.tabs.OPTIONS;this.$el.find('.o_we_website_top_actions').removeClass('d-none');this.$('#snippets_menu button').removeClass('active').prop('disabled',true);this.$('.o_we_customize_snippet_btn').addClass('active').prop('disabled',false);this.$('o_we_ui_loading').addClass('d-none');this.state.showToolbar=false;this.$('#o-we-editor-table-container').addClass('d-none');return Promise.all(defs);}
this.emptyOptionsTabContent=document.createElement('div');this.emptyOptionsTabContent.classList.add('text-center','pt-5');this.emptyOptionsTabContent.append(_t("Select a block on your page to style it."));defs.push((async()=>{await this._loadSnippetsTemplates();await this._updateInvisibleDOM();})());const alreadySelectedElements=new Set();this.$body.on('click.snippets_menu','.o_default_snippet_text',ev=>{const el=ev.currentTarget;if(alreadySelectedElements.has(el)){return;}
alreadySelectedElements.add(el);$(el).selectContent();});this.$body.on('keyup.snippets_menu',()=>{const selection=this.$body[0].ownerDocument.getSelection();if(!selection.rangeCount){return;}
const range=selection.getRangeAt(0);const $defaultTextEl=$(range.startContainer).closest('.o_default_snippet_text');$defaultTextEl.removeClass('o_default_snippet_text');alreadySelectedElements.delete($defaultTextEl[0]);});const refreshSnippetEditors=debounce(()=>{for(const snippetEditor of this.snippetEditors){this._mutex.exec(()=>snippetEditor.destroy());}
const selection=this.$body[0].ownerDocument.getSelection();if(selection.rangeCount){const target=selection.getRangeAt(0).startContainer.parentElement;this._activateSnippet($(target));}
this._updateInvisibleDOM();},500);this.options.wysiwyg.odooEditor.addEventListener('historyUndo',refreshSnippetEditors);this.options.wysiwyg.odooEditor.addEventListener('historyRedo',refreshSnippetEditors);const $autoFocusEls=$('.o_we_snippet_autofocus');this._activateSnippet($autoFocusEls.length?$autoFocusEls.first():false);return Promise.all(defs).then(()=>{const updateHistoryButtons=()=>{this.state.canRedo=this.options.wysiwyg.odooEditor.historyCanRedo();this.state.canUndo=this.options.wysiwyg.odooEditor.historyCanUndo();};this.options.wysiwyg.odooEditor.addEventListener('historyStep',updateHistoryButtons);this.options.wysiwyg.odooEditor.addEventListener('observerApply',()=>{$(this.options.wysiwyg.odooEditor.editable).trigger('content_changed');});setTimeout(()=>{this.$window[0].dispatchEvent(new Event("resize"));},1000);});}
onWillUnmount(){document.removeEventListener("touchstart",this.__onTouchEvent,true);document.removeEventListener("touchmove",this.__onTouchEvent,true);document.removeEventListener("touchend",this.__onTouchEvent,true);this.draggableComponent&&this.draggableComponent.destroy();if(this.$window){if(this.$snippetEditorArea){this.$snippetEditorArea.remove();}
this.$window.off('.snippets_menu');this.$document.off('.snippets_menu');if(this.$scrollingTarget){this.$scrollingTarget[0].removeEventListener('scroll',this._onScrollingElementScroll,{capture:true});}}
if(this.debouncedCoverUpdate){this.debouncedCoverUpdate.cancel();}
$(document.body).off('click',this._checkEditorToolbarVisibilityCallback);this.el.ownerDocument.body.classList.remove('editor_has_snippets');this.tooltips.dispose();this.buttonTooltips.forEach(tooltip=>tooltip.dispose());options.clearServiceCache();options.clearControlledSnippets();if(this.$body[0].ownerDocument!==this.ownerDocument){this.$body.off('.snippets_menu');}}
async cleanForSave(){await this.postSnippetDropPromise;await this._activateSnippet(false);await this._mutex.getUnlockedDef();this.props.readyToCleanForSave();await this._mutex.getUnlockedDef();await this._destroyEditors();this.getEditableArea().find('[contentEditable]').removeAttr('contentEditable').removeProp('contentEditable');this.getEditableArea().find('.o_we_selected_image').removeClass('o_we_selected_image');[...this.getEditableArea()].forEach(editableAreaEl=>{editableAreaEl.querySelectorAll("[data-visibility='conditional']").forEach(invisibleEl=>delete invisibleEl.dataset.invisible);});}
loadSnippets(){if(!this.invalidateSnippetCache&&cacheSnippetTemplate[this.options.snippets]){this._defLoadSnippets=cacheSnippetTemplate[this.options.snippets];return this._defLoadSnippets;}
const context=Object.assign({},this.options.context,{rendering_bundle:true});if(context.user_lang){context.lang=this.options.context.user_lang;context.snippet_lang=this.options.context.lang;}
this._defLoadSnippets=this.orm.silent.call("ir.ui.view","render_public_asset",[this.options.snippets,{}],{context});cacheSnippetTemplate[this.options.snippets]=this._defLoadSnippets;if(this.invalidateSnippetCache){this.invalidateSnippetCache=false;}
return this._defLoadSnippets;}
setFolded(foldState=true){this.el.classList.toggle('d-none',foldState);this.el.ownerDocument.body.classList.toggle('editor_has_snippets',!foldState);this.folded=!!foldState;}
getEditableArea(){return this.options.wysiwyg.$editable.find(this.options.selectorEditableArea).add(this.options.wysiwyg.$editable.filter(this.options.selectorEditableArea));}
getSnippetsByCategories(){const categories=new Map();let snippets=Array.from(this.snippets.values());let strMatches=null;let hasCustomStructureSnippet=false;if(this.hasSnippetGroups){hasCustomStructureSnippet=snippets.some(snippet=>snippet.isCustom&&["structure","hybrid"].includes(snippet.fromCategory));snippets=snippets.filter(snippet=>{return snippet.category.id!=="snippet_structure"&&snippet.category.id!=="snippet_custom"||snippet.category.id==="snippet_custom"&&["content","hybrid"].includes(snippet.fromCategory);});}else{const search=this.state.search.toLowerCase();strMatches=str=>!search||str.toLowerCase().includes(search);}
for(const snippet of snippets){let categorySnippets=categories.get(snippet.category);if(!categorySnippets){categorySnippets=[];categories.set(snippet.category,categorySnippets);}
let matches=false;if(!this.hasSnippetGroups){matches=strMatches(snippet.category.text)||strMatches(snippet.displayName)||strMatches(snippet.data.oeKeywords||'');}else if(snippet.snippetGroup==="custom"){if(!hasCustomStructureSnippet){continue;}}
if(this.hasSnippetGroups||matches){categorySnippets.push(snippet);}}
return categories;}
updateCurrentSnippetEditorOverlay(){if(this.snippetEditorDragging){return;}
for(const snippetEditor of this.snippetEditors){if(snippetEditor.$target.closest('body').length){snippetEditor.cover();continue;}
this._mutex.exec(()=>this._destroyEditor(snippetEditor));}
this._mutex.exec(()=>{if(this.state.currentTab===this.tabs.OPTIONS&&!this.snippetEditors.length){const selection=this.$body[0].ownerDocument.getSelection();const range=selection?.rangeCount&&selection.getRangeAt(0);const currentlySelectedNode=range?.commonAncestorContainer;const isEditableTextElementSelected=currentlySelectedNode?.nodeType===Node.TEXT_NODE&&!!currentlySelectedNode?.parentNode?.isContentEditable;if(!isEditableTextElementSelected){this._activateEmptyOptionsTab();}}});}
activateSnippet($snippet){return this._activateSnippet($snippet);}
async callPostSnippetDrop($target,postSnippetDropExtraActions){this.postSnippetDropPromise=new Promise(resolve=>{this._postSnippetDropResolver=resolve;});await this._callForEachChildSnippet($target,function(editor,$snippet){return editor.buildSnippet($target[0]);});$target.trigger('content_changed');await this._mutex.exec(()=>{const proms=[];this.props.onSnippetDropped({$target:$target,addPostDropAsync:prom=>proms.push(prom),});return Promise.all(proms);});await this._updateInvisibleDOM();if(postSnippetDropExtraActions){postSnippetDropExtraActions();}
this._postSnippetDropResolver();}
execWithLoadingEffect(action,contentLoading=true,delay=500){return this._execWithLoadingEffect(...arguments);}
reloadSnippetDropzones(){this._disableUndroppableSnippets();}
_activateInsertionZones($selectorSiblings,$selectorChildren,canBeSanitizedUnless,toInsertInline,selectorGrids=[],fromIframe=false){var self=this;const $editableArea=self.getEditableArea();let $open=$editableArea.find('.modal:visible');if(!$open.length){$open=$editableArea.find('.dropdown-menu.show').addBack('.dropdown-menu.show').parent();}
if($open.length){$selectorSiblings=$open.find($selectorSiblings);$selectorChildren=$open.find($selectorChildren);selectorGrids=new Set([...selectorGrids].filter(rowEl=>$open[0].contains(rowEl)));}
function setDropZoneDirection($elem,$parent,toInsertInline,$sibling){let vertical=false;let style={};$sibling=$sibling||$elem;const css=window.getComputedStyle($elem[0]);const parentCss=window.getComputedStyle($parent[0]);const float=css.float||css.cssFloat;const display=parentCss.display;const flex=parentCss.flexDirection;if(toInsertInline||float==='left'||float==='right'||(display==='flex'&&flex==='row')){if(!toInsertInline){style['float']=float;}
if((parseInt($sibling.parent().width())!==parseInt($sibling.outerWidth(true)))){vertical=true;style['height']=Math.max($sibling.outerHeight(),30)+'px';if(toInsertInline){style["display"]="inline-block";style["verticalAlign"]="middle";style["float"]="none";}}}
return{vertical:vertical,style:style,};}
function testPreviousSibling(node,$zone){if(!node||((node.tagName||!node.textContent.match(/\S/))&&node.tagName!=='BR')){return false;}
return{vertical:true,style:{'float':'none','display':'inline-block','height':parseInt(self.window.getComputedStyle($zone[0]).lineHeight)+'px',},};}
var $clone=this.$body.find('.oe_drop_clone');if($clone.length&&!$clone[0].parentElement.classList.contains("o_grid_mode")){var $neighbor=$clone.prev();if(!$neighbor.length){$neighbor=$clone.next();}
var data;if($neighbor.length){data=setDropZoneDirection($neighbor,$neighbor.parent(),toInsertInline);}else{data={vertical:false,style:{},};}
self._insertDropzone($('<we-hook/>').insertAfter($clone),data.vertical,data.style,canBeSanitizedUnless);}
if($clone.length&&$open.length&&$clone[0].parentElement.classList.contains("o_grid_mode")){selectorGrids.add($clone[0].parentElement);}
if($selectorChildren){$selectorChildren.each(function(){var data;var $zone=$(this);var $children=$zone.find('> :not(.oe_drop_zone, .oe_drop_clone)');if(!$zone.children().last().is('.oe_drop_zone')){data=testPreviousSibling($zone[0].lastChild,$zone)||setDropZoneDirection($zone,$zone,toInsertInline,$children.last());self._insertDropzone($('<we-hook/>').appendTo($zone),data.vertical,data.style,canBeSanitizedUnless);}
if(!$zone.children().first().is('.oe_drop_clone')){data=testPreviousSibling($zone[0].firstChild,$zone)||setDropZoneDirection($zone,$zone,toInsertInline,$children.first());self._insertDropzone($('<we-hook/>').prependTo($zone),data.vertical,data.style,canBeSanitizedUnless);}});$selectorSiblings=$(unique(($selectorSiblings||$()).add($selectorChildren.children()).get()));}
const noDropZonesSelector='.o_we_no_overlay, :not(:visible)';if($selectorSiblings){$selectorSiblings.not(`.oe_drop_zone, .oe_drop_clone, ${noDropZonesSelector}`).each(function(){var data;var $zone=$(this);var $zoneToCheck=$zone;while($zoneToCheck.prev(noDropZonesSelector).length){$zoneToCheck=$zoneToCheck.prev();}
if(!$zoneToCheck.prev('.oe_drop_zone:visible, .oe_drop_clone').length){data=setDropZoneDirection($zone,$zone.parent(),toInsertInline);self._insertDropzone($('<we-hook/>').insertBefore($zone),data.vertical,data.style,canBeSanitizedUnless);}
$zoneToCheck=$zone;while($zoneToCheck.next(noDropZonesSelector).length){$zoneToCheck=$zoneToCheck.next();}
if(!$zoneToCheck.next('.oe_drop_zone:visible, .oe_drop_clone').length){data=setDropZoneDirection($zone,$zone.parent(),toInsertInline);self._insertDropzone($('<we-hook/>').insertAfter($zone),data.vertical,data.style,canBeSanitizedUnless);}});}
var count;var $zones;do{count=0;$zones=this.getEditableArea().find('.oe_drop_zone > .oe_drop_zone').remove();count+=$zones.length;$zones.remove();}while(count>0);$zones=this.getEditableArea().find('.oe_drop_zone:not(.oe_vertical)');let iframeOffset;const bodyWindow=this.$body[0].ownerDocument.defaultView;if(bodyWindow.frameElement&&bodyWindow!==this.ownerDocument.defaultView&&!fromIframe){iframeOffset=bodyWindow.frameElement.getBoundingClientRect();}
$zones.each(function(){var zone=$(this);var prev=zone.prev();var next=zone.next();if(prev.is('.oe_drop_zone')||next.is('.oe_drop_zone')){zone.remove();return;}
var floatPrev=prev.css('float')||'none';var floatNext=next.css('float')||'none';var dispPrev=prev.css('display')||null;var dispNext=next.css('display')||null;if((floatPrev==='left'||floatPrev==='right')&&(floatNext==='left'||floatNext==='right')){zone.remove();}else if(dispPrev!==null&&dispNext!==null&&dispPrev.indexOf('inline')>=0&&dispNext.indexOf('inline')>=0){zone.remove();}
if(iframeOffset){this.oldGetBoundingClientRect=this.getBoundingClientRect;this.getBoundingClientRect=()=>{const rect=this.oldGetBoundingClientRect();const{x,y}=iframeOffset;rect.x+=x;rect.y+=y;return rect;};}});for(const rowEl of selectorGrids){self._insertGridDropzone(rowEl);}}
_updateInvisibleDOM(){return this._execWithLoadingEffect(async()=>{this.options.wysiwyg.odooEditor.automaticStepSkipStack();this.invisibleDOMMap=new Map();const isMobile=this._isMobile();const invisibleSelector=`.o_snippet_invisible, ${isMobile ? '.o_snippet_mobile_invisible' : '.o_snippet_desktop_invisible'}`;const $selector=this.options.enableTranslation?this.$body:globalSelector.all();let $invisibleSnippets=$selector.find(invisibleSelector).addBack(invisibleSelector);if(this.options.enableTranslation){$invisibleSnippets=$invisibleSnippets.not("header, footer");}
const descendantPerSnippet=new Map();const rootInvisibleSnippetEls=[...$invisibleSnippets].filter(invisibleSnippetEl=>{const ancestorInvisibleEl=invisibleSnippetEl.parentElement.closest(invisibleSelector);if(!ancestorInvisibleEl){return true;}
const descendantSnippets=descendantPerSnippet.get(ancestorInvisibleEl)||[];descendantPerSnippet.set(ancestorInvisibleEl,[...descendantSnippets,invisibleSnippetEl]);return false;});const createInvisibleElement=async(invisibleSnippetEl,isRootParent,isDescendant,parents)=>{const editor=await this._createSnippetEditor($(invisibleSnippetEl),true);return{editor,snippetEl:invisibleSnippetEl,name:editor.getName(),isRootParent,isDescendant,invisibleSnippetEl,isVisible:editor.isTargetVisible(),children:[],parents:isDescendant?parents:null,};};const createInvisibleElements=(snippetEls,isDescendant,parents)=>{return Promise.all((snippetEls).map(async(snippetEl)=>{const descendantSnippetEls=descendantPerSnippet.get(snippetEl);const invisibleElement=await createInvisibleElement(snippetEl,!isDescendant&&!!descendantSnippetEls,isDescendant,parents);if(descendantSnippetEls){invisibleElement.children=await createInvisibleElements(descendantSnippetEls,true,invisibleElement);}
return invisibleElement;}));};this.state.invisibleElements=await createInvisibleElements(rootInvisibleSnippetEls,false,this.state.invisibleElements);},false);}
async _activateSnippet($snippet,previewMode,ifInactiveOptions){if(this._blockPreviewOverlays&&previewMode){return;}
if($snippet&&!$snippet.is(':visible')){return;}
if($snippet&&$snippet.length){const $globalSnippet=globalSelector.closest($snippet);if(!$globalSnippet.length){$snippet=$snippet.closest('[data-oe-model="ir.ui.view"]:not([data-oe-type]):not(.oe_structure), [data-oe-type="html"]:not(.oe_structure)');}else{$snippet=$globalSnippet;}}
if(this.options.enableTranslation&&$snippet&&!this._allowInTranslationMode($snippet)){const translationEditors=this.snippetEditors.filter(editor=>{return this._allowInTranslationMode(editor.$target);});for(const editor of translationEditors){await editor.cleanForSave();editor.destroy();}
return;}
const exec=previewMode?action=>this._mutex.exec(action):action=>this._execWithLoadingEffect(action,false);return exec(()=>{return new Promise(resolve=>{if($snippet&&$snippet.length){return this._createSnippetEditor($snippet).then(resolve);}
resolve(null);}).then(async editorToEnable=>{if(editorToEnable&&editorToEnable.$target[0]&&!editorToEnable.$target[0].closest("body")){return null;}
if(!previewMode&&this._enabledEditorHierarchy[0]===editorToEnable||ifInactiveOptions&&this._enabledEditorHierarchy.includes(editorToEnable)){return editorToEnable;}
if(!previewMode){this._enabledEditorHierarchy=[];let current=editorToEnable;while(current&&current.$target){this._enabledEditorHierarchy.push(current);current=current.getParent();}}
for(let i=this.snippetEditors.length;i--;){const editor=this.snippetEditors[i];editor.toggleOverlay(false,previewMode);if(!previewMode){const wasShown=!!await editor.toggleOptions(false);if(wasShown){this._updateRightPanelContent({content:[],tab:SnippetsMenu.tabs.BLOCKS,});}}}
let customize$Elements;if(editorToEnable){editorToEnable.toggleOverlay(true,previewMode);if(!previewMode&&!editorToEnable.displayOverlayOptions){const parentEditor=this._enabledEditorHierarchy.find(ed=>ed.displayOverlayOptions);if(parentEditor){parentEditor.toggleOverlay(true,previewMode);}}
customize$Elements=await editorToEnable.toggleOptions(true);}else{for(const editor of this.snippetEditors){if(editor.isSticky()){editor.toggleOverlay(true,false);customize$Elements=await editor.toggleOptions(true);}}}
if(!previewMode){if(editorToEnable&&!customize$Elements){editorToEnable.toggleOverlay(false);}
this._updateRightPanelContent({content:customize$Elements||[],tab:customize$Elements?this.tabs.OPTIONS:this.tabs.BLOCKS,});}
return editorToEnable;});});}
async _loadSnippetsTemplates(withMutex=true){const loadSnippetsTemplates=async()=>{await this._destroyEditors();const html=await this.loadSnippets();const snippetsDocument=new DOMParser().parseFromString(html,"text/html");const snippetsBody=snippetsDocument.body;await this._computeSnippetTemplates(snippetsBody);};if(withMutex){return this._execWithLoadingEffect(async()=>{await loadSnippetsTemplates();},false);}else{return loadSnippetsTemplates();}}
_destroyEditor(editor){editor.destroy();const index=this.snippetEditors.indexOf(editor);if(index>=0){this.snippetEditors.splice(index,1);}}
async _destroyEditors($el){const aliveEditors=this.snippetEditors.filter((snippetEditor)=>{return!$el||$el.has(snippetEditor.$target).length;});const cleanForSavePromises=aliveEditors.map((snippetEditor)=>snippetEditor.cleanForSave());await Promise.all(cleanForSavePromises);for(const snippetEditor of aliveEditors){snippetEditor.destroy();}}
_callForEachChildSnippet($snippet,callback){var self=this;var defs=Array.from($snippet.add(globalSelector.all($snippet))).map((el)=>{var $snippet=$(el);return self._createSnippetEditor($snippet).then(function(editor){if(editor){return callback.call(self,editor,$snippet);}});});return Promise.all(defs);}
_closeWidgets(){this.snippetEditors.forEach(editor=>editor.closeWidgets());}
_computeSelectorFunctions({selector,exclude,target,noCheck,isChildren,excludeParent,forDrop,textSelector}){var self=this;exclude+=`${exclude && ', '}.o_snippet_not_selectable`;let filterFunc=function(){if(forDrop){const selfOrParentEl=isChildren?this.parentNode:this;if(selfOrParentEl.closest("[data-oe-type=image]")){return false;}}
if($(this).is(exclude)){return false;}
if(noCheck){return true;}
if(!forDrop&&this.classList.contains('o_editable_media')){return weUtils.shouldEditableMediaBeEditable(this);}
if(forDrop&&!isChildren){return!$(this).is('.o_not_editable :not([contenteditable="true"]), .o_not_editable');}
if(isChildren){return!$(this).is('.o_not_editable *');}
return!$(this).is('.o_not_editable:not(.s_social_media) :not([contenteditable="true"])');};if(target){const oldFilter=filterFunc;filterFunc=function(){return oldFilter.apply(this)&&$(this).find(target).length!==0;};}
if(excludeParent){const oldFilter=filterFunc;filterFunc=function(){return oldFilter.apply(this)&&!$(this).parent().is(excludeParent);};}
const functions={};if(noCheck||this.options.enableTranslation){functions.is=function($from,options={}){return $from.is(options.onlyTextOptions?textSelector:selector)&&$from.filter(filterFunc).length!==0;};functions.closest=function($from,parentNode){return $from.closest(selector,parentNode).filter(filterFunc);};functions.all=function($from){return($from?self.cssFind($from,selector):self.$body.find(selector)).filter(filterFunc);};}else{functions.is=function($from){return $from.is(selector)&&self.getEditableArea().find($from).addBack($from).length!==0&&$from.filter(filterFunc).length!==0;};functions.closest=function($from,parentNode){var parents=self.getEditableArea().get();return $from.closest(selector,parentNode).filter(function(){var node=this;while(node.parentNode){if(parents.indexOf(node)!==-1){return true;}
node=node.parentNode;}
return false;}).filter(filterFunc);};functions.all=isChildren?function($from){return self.cssFind($from||self.getEditableArea(),selector).filter(filterFunc);}:function($from){$from=$from||self.getEditableArea();return $from.filter(selector).add(self.cssFind($from,selector)).filter(filterFunc);};}
return functions;}
_computeSnippetTemplates(html){var self=this;var $html=$(html);const websiteFormEditorOptionsEl=$html.find('[data-js="WebsiteFormEditor"]')[0];if(websiteFormEditorOptionsEl){websiteFormEditorOptionsEl.dataset.dropExcludeAncestor="form";}
const filterSelectEl=$html.find("we-select").has("we-button[data-gl-filter]")[0];if(filterSelectEl){filterSelectEl.dataset.name="glfilter_select_opt";}
this.templateOptions=[];var selectors=[];var $styles=$html.find('[data-selector]');const snippetAdditionDropIn=$styles.filter('#so_snippet_addition').data('drop-in');$styles.each(function(){var $style=$(this);var selector=$style.data('selector');var exclude=$style.data('exclude')||'';const excludeParent=$style.attr('id')==="so_content_addition"?snippetAdditionDropIn:'';var target=$style.data('target');var noCheck=$style.data('no-check');const optionID=$style.data('js');const textSelector=$style.data("text-selector");var option={'option':optionID,'base_selector':selector,'base_exclude':exclude,'base_target':target,'selector':self._computeSelectorFunctions({selector,exclude,target,noCheck,textSelector}),'$el':$style,'drop-near':$style.data('drop-near')&&self._computeSelectorFunctions({selector:$style.data('drop-near'),noCheck,isChildren:true,excludeParent,forDrop:true}),'drop-in':$style.data('drop-in')&&self._computeSelectorFunctions({selector:$style.data('drop-in'),noCheck,forDrop:true,}),'drop-exclude-ancestor':this.dataset.dropExcludeAncestor,'drop-lock-within':this.dataset.dropLockWithin,'data':Object.assign({string:$style.attr('string')},$style.data()),};self.templateOptions.push(option);selectors.push(option.selector);});$styles.addClass('d-none');globalSelector.closest=function($from){var $temp;var $target;for(var i=0,len=selectors.length;i<len;i++){$temp=selectors[i].closest($from,$target&&$target[0]);if($temp.length){$target=$temp;}}
return $target||$();};globalSelector.all=function($from){var $target=$();for(var i=0,len=selectors.length;i<len;i++){$target=$target.add(selectors[i].all($from));}
return $target;};globalSelector.is=function($from,options={}){for(var i=0,len=selectors.length;i<len;i++){if(selectors[i].is($from,options)){return true;}}
return false;};this.snippets.clear();let index=0;for(const snippetsEl of html.querySelectorAll("snippets")){const category={id:snippetsEl.id,text:snippetsEl.getAttribute("string"),classes:[...snippetsEl.classList]};for(const snippetEl of snippetsEl.children){const isCustom=!!snippetEl.closest('#snippet_custom');const snippet={id:parseInt(snippetEl.dataset.oeSnippetId)||uniqueId(snippetEl.dataset.moduleId),name:snippetEl.children[0].dataset.snippet,displayName:snippetEl.getAttribute("name"),category:category,content:snippetEl.children,thumbnailSrc:escape(snippetEl.dataset.oeThumbnail),imagePreview:escape(snippetEl.dataset.oImagePreview),visible:true,baseBody:snippetEl.children[0],data:{...snippetEl.dataset,...snippetEl.children[0].dataset},isCustom:isCustom,snippetGroup:snippetEl.dataset.oSnippetGroup,group:isCustom?"custom":snippetEl.dataset.oGroup,key:index++,};if(snippetEl.dataset.oSnippetGroup){snippet.content[0].dataset.snippetGroup=snippetEl.dataset.oSnippetGroup;}
[...snippet.content].forEach(el=>{el.classList.add("oe_snippet_body");let snippetClasses=el.getAttribute('class').match(/s_[^ ]+/g);if(snippetClasses&&snippetClasses.length){snippetClasses='.'+snippetClasses.join('.');}
const $els=self.$body.find(snippetClasses).not('[data-name]').add($(snippetClasses)).add(el);$els.attr('data-name',snippet.displayName).data('name',snippet.displayName);});if(snippetEl.dataset.moduleId){snippet.moduleId=snippetEl.dataset.moduleId;snippet.moduleDisplayName=snippetEl.dataset.moduleDisplayName;snippet.installable=true;}
if(snippet.isCustom){snippet.renameTitle=_t("Rename %s",snippet.displayName);snippet.deleteTitle=_t("Delete %s",snippet.displayName);snippet.isRenaming=false;}
this.snippets.set(snippet.key,snippet);}
const snippets=Array.from(this.snippets.values());const customSnippets=snippets.filter(snippet=>{return snippet.category.id==="snippet_custom";});for(const customSnippet of customSnippets){const customSnippetName=customSnippet.name.startsWith("s_button_")?"s_button":customSnippet.name;const categoryIds=snippets.filter(snippet=>snippet.name===customSnippetName).map(snippet=>snippet.category.id);customSnippet.fromCategory=categoryIds.includes("snippet_structure")&&categoryIds.includes("snippet_content")?"hybrid":categoryIds.includes("snippet_structure")?"structure":categoryIds.includes("snippet_content")?"content":"";if(customSnippet.fromCategory==="content"){customSnippet.group="";}}}
this._registerDefaultTexts();this._makeSnippetDraggable();this._disableUndroppableSnippets();}
_createSnippetEditor($snippet,forceCreate=false){var self=this;var snippetEditor=$snippet.data('snippet-editor');if(snippetEditor){return snippetEditor.__isStarted;}
if(!forceCreate&&this.options.enableTranslation&&!this._allowInTranslationMode($snippet)){return Promise.resolve(null);}
var def;const allowParentsEditors=this._allowParentsEditors($snippet);if(allowParentsEditors){var $parent=globalSelector.closest($snippet.parent());if($parent.length){def=this._createSnippetEditor($parent);}}
return Promise.resolve(def).then(function(parentEditor){snippetEditor=$snippet.data('snippet-editor');if(snippetEditor){return snippetEditor.__isStarted;}
let editableArea=self.getEditableArea();snippetEditor=new SnippetEditor(parentEditor||self,$snippet,self.templateOptions,$snippet.closest('[data-oe-type="html"], .oe_structure').add(editableArea),Object.assign({},self.options,{allowParentsEditors:allowParentsEditors}));self.snippetEditors.push(snippetEditor);return snippetEditor.prependTo(self.$snippetEditorArea);}).then(function(){return snippetEditor;});}
cssFind($from,selector){if(selector.indexOf(' ')>=0){return $from.closest('body').find(selector).filter((i,$el)=>$from.has($el).length);}
return $from.find(selector);}
_disableUndroppableSnippets(){var self=this;var cache={};[...this.snippets.values()].filter(snippet=>!snippet.snippetGroup).forEach((snippet)=>{const $snippetBody=$(snippet.baseBody);const isSnippetStructure=snippet.category.id==="snippet_structure";const isSanitizeForbidden=snippet.data.oeForbidSanitize;const checkSanitize=isSanitizeForbidden==="form"?(el)=>!el.closest('[data-oe-sanitize]:not([data-oe-sanitize="allow_form"])'):isSanitizeForbidden?(el)=>!el.closest('[data-oe-sanitize]'):()=>true;const isVisible=(el)=>el.closest(".o_snippet_invisible")?!el.closest("[data-invisible]"):true;const canDrop=($els)=>[...$els].some((el)=>checkSanitize(el)&&isVisible(el));var check=false;self.templateOptions.forEach((option,k)=>{if(check||!($snippetBody.is(option.base_selector)&&!$snippetBody.is(option.base_exclude))){return;}
k=isSanitizeForbidden?'forbidden/'+k:k;cache[k]=cache[k]||{'drop-near':option['drop-near']?canDrop(option['drop-near'].all()):false,'drop-in':option['drop-in']?canDrop(option['drop-in'].all()):false,};const hasDropNear=cache[k]['drop-near'];const hasDropIn=cache[k]['drop-in'];check=isSnippetStructure?hasDropIn:hasDropNear||hasDropIn;});snippet.disabled=!check;});[...this.snippets.values()].filter(snippetGroup=>snippetGroup.snippetGroup).forEach((snippetGroup)=>{snippetGroup.disabled=![...self.snippets.values()].some(snippet=>!snippet.disabled&&(snippet.group===snippetGroup.snippetGroup))});}
_getDragAndDropOptions(options={}){let iframeWindow=false;if(this.$body[0].ownerDocument.defaultView!==window){iframeWindow=this.$body[0].ownerDocument.defaultView;}
return Object.assign({},options,{iframeWindow,cursor:"move",});}
_insertDropzone($hook,vertical,style,canBeSanitizedUnless){const skip=$hook.closest('[data-oe-sanitize="no_block"]').length;let forbidSanitize;if(canBeSanitizedUnless==='form'){forbidSanitize=$hook.closest('[data-oe-sanitize]:not([data-oe-sanitize="allow_form"]):not([data-oe-sanitize="no_block"])').length;}else{forbidSanitize=!canBeSanitizedUnless&&$hook.closest('[data-oe-sanitize]:not([data-oe-sanitize="no_block"])').length;}
var $dropzone=$('<div/>',{'class':skip?'d-none':'oe_drop_zone oe_insert'+(vertical?' oe_vertical':'')+
(forbidSanitize?' text-center oe_drop_zone_danger':''),});if(style){$dropzone.css(style);}
if(forbidSanitize){$dropzone[0].appendChild(document.createTextNode(_t("For technical reasons, this block cannot be dropped here")));}
$hook.replaceWith($dropzone);return $dropzone;}
_insertGridDropzone(rowEl){const columnCount=12;const rowCount=parseInt(rowEl.dataset.rowCount);let $dropzone=$('<div/>',{'class':'oe_drop_zone oe_insert oe_grid_zone','style':'grid-area: '+1+'/'+1+'/'+(rowCount+1)+'/'+(columnCount+1),});$dropzone[0].style.minHeight=window.getComputedStyle(rowEl).height;$dropzone[0].style.width=window.getComputedStyle(rowEl).width;rowEl.append($dropzone[0]);}
_makeSnippetDraggable(){if(this.draggableComponent){this.draggableComponent.destroy();}
var $toInsert,dropped,$snippet;let $dropZones;let isSnippetGroup;let dragAndDropResolve;let $scrollingElement=$().getScrollingElement(this.$body[0].ownerDocument);if(!$scrollingElement[0]){$scrollingElement=$(this.ownerDocument).find('.o_editable');}
const oNotebook=this.ownerDocument.querySelector(".o_notebook");if(oNotebook){$scrollingElement=$(oNotebook);}
const dragAndDropOptions=this.options.getDragAndDropOptions({el:this.snippetsAreaRef.el,elements:".oe_snippet.o_we_draggable",scrollingElement:$scrollingElement[0],handle:'.oe_snippet_thumbnail:not(.o_we_ongoing_insertion)',cancel:'.oe_snippet.o_disabled',dropzones:()=>{return $dropZones.toArray();},helper:({element,elementRect,helperOffset,x,y})=>{const dragSnip=element.cloneNode(true);dragSnip.querySelectorAll('.o_delete_btn, .o_rename_btn').forEach(el=>el.remove());dragSnip.style.position="fixed";this.$el[0].ownerDocument.body.append(dragSnip);const thumbnailImgEl=element.querySelector(".oe_snippet_thumbnail_img");helperOffset.x=thumbnailImgEl.offsetWidth/2;helperOffset.y=thumbnailImgEl.offsetHeight/2;return dragSnip;},onDragStart:({element})=>{this._hideSnippetTooltips();const prom=new Promise(resolve=>dragAndDropResolve=()=>resolve());this._mutex.exec(()=>prom);const doc=this.options.wysiwyg.odooEditor.document;$(doc.body).addClass('oe_dropzone_active');this.options.wysiwyg.odooEditor.automaticStepUnactive();this.$el.find('.oe_snippet_thumbnail').addClass('o_we_ongoing_insertion');this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropCreateSnippet');dropped=false;const snippetKey=element.closest('.oe_snippet').dataset.snippetKey;const snippet=this.snippets.get(parseInt(snippetKey));$snippet=$(element).closest('.oe_snippet');const $baseBody=$(snippet.baseBody);const{$selectorSiblings,$selectorChildren}=this._getSelectors($baseBody);$toInsert=$baseBody.clone();isSnippetGroup=$toInsert[0].matches(".s_snippet_group");[...$toInsert.find('img[src^="/html_editor/shape/"], img[src^="/web_editor/shape/"]')].forEach(dynamicSvg=>{const colorCustomizedURL=new URL(dynamicSvg.getAttribute('src'),window.location.origin);colorCustomizedURL.searchParams.forEach((value,key)=>{const match=key.match(/^c([1-5])$/);if(match){colorCustomizedURL.searchParams.set(key,weUtils.getCSSVariableValue(`o-color-${match[1]}`));}});dynamicSvg.src=colorCustomizedURL.pathname+colorCustomizedURL.search;});if(!$selectorSiblings.length&&!$selectorChildren.length){console.warn($snippet.find('.oe_snippet_thumbnail_title').text()+" have not insert action: data-drop-near or data-drop-in");return;}
const forbidSanitize=snippet.data.oeForbidSanitize;const canBeSanitizedUnless=forbidSanitize==='form'?'form':!forbidSanitize;this.$body[0].appendChild($toInsert[0]);$toInsert[0].classList.remove("oe_snippet_body");const toInsertInline=window.getComputedStyle($toInsert[0]).display.includes('inline');if(!isSnippetGroup){$toInsert[0].classList.add("oe_snippet_body");}
$toInsert[0].remove();this._activateInsertionZones($selectorSiblings,$selectorChildren,canBeSanitizedUnless,toInsertInline);$dropZones=this.getEditableArea().find('.oe_drop_zone');if(forbidSanitize==='form'){$dropZones=$dropZones.filter((i,el)=>!el.closest('[data-oe-sanitize]:not([data-oe-sanitize="allow_form"]) .oe_drop_zone'));}else if(forbidSanitize){$dropZones=$dropZones.filter((i,el)=>!el.closest('[data-oe-sanitize] .oe_drop_zone'));}
const $openModal=this.getEditableArea().find('.modal:visible');if($openModal.length){this.draggableComponent.update({scrollingElement:$openModal[0]});$scrollingElement=$openModal;}
this._onDropZoneStart();},dropzoneOver:({dropzone})=>{if(isSnippetGroup){dropzone.el.classList.add("o_dropzone_highlighted");return;}
if(dropped){$toInsert.detach();$toInsert.addClass('oe_snippet_body');[...$dropZones].forEach(dropzoneEl=>dropzoneEl.classList.remove("invisible"));}
dropped=true;$(dropzone.el).first().after($toInsert).addClass('invisible');$toInsert.removeClass('oe_snippet_body');this._onDropZoneOver();},dropzoneOut:({dropzone})=>{if(isSnippetGroup){dropzone.el.classList.remove("o_dropzone_highlighted");return;}
var prev=$toInsert.prev();if(dropzone.el===prev[0]){dropped=false;$toInsert.detach();$(dropzone.el).removeClass('invisible');$toInsert.addClass('oe_snippet_body');}
this._onDropZoneOut();},onDragEnd:async({x,y,helper})=>{const doc=this.options.wysiwyg.odooEditor.document;$(doc.body).removeClass('oe_dropzone_active');this.options.wysiwyg.odooEditor.automaticStepUnactive();this.options.wysiwyg.odooEditor.automaticStepSkipStack();$toInsert.removeClass('oe_snippet_body');$scrollingElement.off('scroll.scrolling_element');if(isSnippetGroup){const highlightedDropzoneEl=doc.body.querySelector(".o_dropzone_highlighted");if(highlightedDropzoneEl){highlightedDropzoneEl.insertAdjacentElement('afterend',$toInsert[0]);dropped=true;}}
const sidebarRect=this.el.getBoundingClientRect();const isRTL=document.body.classList.contains("o_rtl");const isOutOfSidebar=isRTL?sidebarRect.left+sidebarRect.width<x-helper.getBoundingClientRect().width/2:x+helper.getBoundingClientRect().width/2<sidebarRect.left;if(!dropped&&y>3&&isOutOfSidebar){const point={x,y};let droppedOnNotNearest=touching(doc.body.querySelectorAll('.oe_structure_not_nearest'),point);const selector=droppedOnNotNearest?'.oe_drop_zone':':not(.oe_structure_not_nearest) > .oe_drop_zone';let $el=$(closest(doc.body.querySelectorAll(selector),point));$el=$el.filter($dropZones);if($el.length){$el.after($toInsert);dropped=true;}}
this.getEditableArea().find('.oe_drop_zone').remove();let $toInsertParent;let prev;let next;if(dropped){prev=$toInsert.first()[0].previousSibling;next=$toInsert.last()[0].nextSibling;$toInsertParent=$toInsert.parent();$toInsert.detach();}
this.options.wysiwyg.odooEditor.observerActive('dragAndDropCreateSnippet');if(dropped){if(prev){$toInsert.insertAfter(prev);}else if(next){$toInsert.insertBefore(next);}else{$toInsertParent.prepend($toInsert);}
var $target=$toInsert;this._updateDroppedSnippet($target);const isSnippetGroup=$target[0].matches(".s_snippet_group");if(!isSnippetGroup){this.options.wysiwyg.odooEditor.observerUnactive('dragAndDropCreateSnippet');await this._scrollToSnippet($target,this.$scrollable);this.options.wysiwyg.odooEditor.observerActive('dragAndDropCreateSnippet');browser.setTimeout(async()=>{dragAndDropResolve();await this.callPostSnippetDrop($target,()=>{this._disableUndroppableSnippets();this.options.wysiwyg.odooEditor.unbreakableStepUnactive();this.options.wysiwyg.odooEditor.historyStep();this.$el.find('.oe_snippet_thumbnail').removeClass('o_we_ongoing_insertion');});});}else{dragAndDropResolve();this._openAddSnippetDialog($target[0].dataset.snippetGroup,$target[0]);}}else{$toInsert.remove();if(dragAndDropResolve){dragAndDropResolve();}
this.$el.find('.oe_snippet_thumbnail').removeClass('o_we_ongoing_insertion');}
this._onDropZoneStop();},});this.draggableComponent=useDragAndDrop({ref:{el:this.el},...dragAndDropOptions});}
_getSelectors($baseBody){let $selectorSiblings=$();let $selectorChildren=$();const selectorExcludeAncestor=[];var temp=this.templateOptions;for(const k in temp){if($baseBody.is(temp[k].base_selector)&&!$baseBody.is(temp[k].base_exclude)){if(temp[k]['drop-near']){$selectorSiblings=$selectorSiblings.add(temp[k]['drop-near'].all());}
if(temp[k]['drop-in']){$selectorChildren=$selectorChildren.add(temp[k]['drop-in'].all());}
if(temp[k]['drop-exclude-ancestor']){selectorExcludeAncestor.push(temp[k]['drop-exclude-ancestor']);}}}
for(const excludedAncestorSelector of selectorExcludeAncestor){$selectorSiblings=$selectorSiblings.filter((i,el)=>!el.closest(excludedAncestorSelector));$selectorChildren=$selectorChildren.filter((i,el)=>!el.closest(excludedAncestorSelector));}
return{$selectorSiblings:$selectorSiblings,$selectorChildren:$selectorChildren,};}
_registerDefaultTexts($in){if($in===undefined){const snippets=[...this.snippets.values()].filter((snippet)=>!snippet.isCustom).map((snippet)=>snippet.baseBody);$in=$(snippets);}
$in.find('*').addBack().contents().filter(function(){return this.nodeType===3&&this.textContent.match(/\S/);}).parent().addClass('o_default_snippet_text');}
_updateRightPanelContent({content,tab,...options}){this._hideTooltips();this._closeWidgets();if(this.options.enableTranslation){tab=SnippetsMenu.tabs.OPTIONS;}
this.state.currentTab=tab||SnippetsMenu.tabs.BLOCKS;if(this._$toolbarContainer){this._$toolbarContainer[0].remove();}
this.state.showToolbar=false;this._$toolbarContainer=null;if(content){while(this.customizePanel.firstChild?.id!=="o_we_editor_toolbar_container"){this.customizePanel.removeChild(this.customizePanel.firstChild);}
$(this.customizePanel).prepend(content);if(this.state.currentTab===this.tabs.OPTIONS&&!options.forceEmptyTab){this._addToolbar();}}
if(options.forceEmptyTab){this.state.showToolbar=false;}}
async _scrollToSnippet($el,$scrollable){const modalEl=$el[0].closest('.modal');if(modalEl&&!$(modalEl).hasScrollableContent()){return;}
const scrollable=$scrollable?.get(0);return scrollTo($el[0],{extraOffset:50,scrollable:scrollable});}
_createLoadingElement(){const loaderContainer=document.createElement('div');const loader=document.createElement('img');const loaderContainerClassList=['o_we_ui_loading','d-flex','justify-content-center','align-items-center',];loaderContainer.classList.add(...loaderContainerClassList);loader.setAttribute('src','/web/static/img/spin.svg');loaderContainer.appendChild(loader);return loaderContainer;}
async _execWithLoadingEffect(action,contentLoading=true,delay=500){if(contentLoading==="both"){contentLoading=false;const actualAction=action;action=()=>{this._execWithLoadingEffect(actualAction,true,delay);};}
const mutexExecResult=this._mutex.exec(action);if(!this.loadingTimers[contentLoading]){const addLoader=()=>{if(this._loadingEffectDisabled||this.loadingElements[contentLoading]){return;}
this.loadingElements[contentLoading]=this._createLoadingElement();if(contentLoading){this.$snippetEditorArea.append(this.loadingElements[contentLoading]);}else{this.el.appendChild(this.loadingElements[contentLoading]);}};if(delay){this.loadingTimers[contentLoading]=setTimeout(addLoader,delay);}else{addLoader();}
this._mutex.getUnlockedDef().then(()=>{if(delay){clearTimeout(this.loadingTimers[contentLoading]);this.loadingTimers[contentLoading]=undefined;}
if(this.loadingElements[contentLoading]){this.loadingElements[contentLoading].remove();this.loadingElements[contentLoading]=null;}});}
return mutexExecResult;}
_activateEmptyOptionsTab(){this._updateRightPanelContent({content:this.emptyOptionsTabContent,tab:this.tabs.OPTIONS,forceEmptyTab:true,});}
_hideTooltips(){const tooltipTargetEls=this.el.querySelectorAll('[aria-describedby^="tooltip"]');for(const el of tooltipTargetEls){Tooltip.getInstance(el)?.hide();}}
_isMobile(){return weUtils.isMobileView(this.$body[0]);}
_allowParentsEditors($snippet){return!this.options.enableTranslation;}
async _snippetOptionUpdate(){const editors=this._enabledEditorHierarchy.filter(editor=>!!editor.$target[0].closest('body'));await Promise.all(editors.map(editor=>editor.updateOptionsUI()));await Promise.all(editors.map(editor=>editor.updateOptionsUIVisibility()));if(editors[0]!==this._enabledEditorHierarchy[0]){this._activateSnippet(editors[0].$target);}}
_allowInTranslationMode($snippet){return globalSelector.is($snippet,{onlyTextOptions:true});}
_updateDroppedSnippet($target){if($target[0].classList.contains("o_snippet_drop_in_only")){$target[0].classList.remove("o_snippet_drop_in_only");delete $target[0].dataset.snippet;delete $target[0].dataset.name;}}
_onClick(ev){if(this.options.wysiwyg.isSaving()){return;}
var srcElement=ev.target||(ev.originalEvent&&(ev.originalEvent.target||ev.originalEvent.originalTarget))||ev.srcElement;if(!srcElement||this.lastElement===srcElement){return;}
var $target=$(srcElement);if($target.parents('.o_edit_menu_popover').length&&!$target.parent('a').addBack('a').length){return;}
this.lastElement=srcElement;browser.setTimeout(()=>{this.lastElement=false;});if(!$target.closest('we-button, we-toggler, we-select, .o_we_color_preview').length&&!this._isColorpickerClick){this._closeWidgets();}
delete this._isColorpickerClick;if(!$target.closest('body > *').length||$target.is('#iframe_target')){return;}
if($target.closest(this._notActivableElementsSelector).length){return;}
const $oeStructure=$target.closest('.oe_structure');if($oeStructure.length&&!$oeStructure.children().length&&this.snippets.size>0){this._activateSnippet(false).then(()=>{this.$el.find('.oe_snippet').odooBounce();});return;}
this._activateSnippet($target);}
_onActivateInsertionZones(ev){this._activateInsertionZones(ev.data.$selectorSiblings,ev.data.$selectorChildren,ev.data.canBeSanitizedUnless,ev.data.toInsertInline,ev.data.selectorGrids,ev.data.fromIframe);}
_onActivateSnippet(ev){const prom=this._activateSnippet(ev.data.$snippet,ev.data.previewMode,ev.data.ifInactiveOptions);if(ev.data.onSuccess){prom.then(()=>ev.data.onSuccess());}}
_onCallForEachChildSnippet(ev){this._callForEachChildSnippet(ev.data.$snippet,ev.data.callback).then(()=>ev.data.onSuccess());}
_onOverlaysCoverUpdate(ev){this.snippetEditors.forEach(editor=>{if(ev.data.overlayVisible){editor.toggleOverlayVisibility(true);}
editor.cover();});}
async _onCloneSnippet(ev){ev.stopPropagation();const editor=await this._createSnippetEditor(ev.data.$snippet);await editor.clone();if(ev.data.onSuccess){ev.data.onSuccess();}}
_onCleanUIRequest(ev){const targetEditors=this.snippetEditors.filter(editor=>{return ev.data.targetEl.contains(editor.$target[0]);});Promise.all(targetEditors.map(editor=>editor.cleanUI())).then(()=>{ev.data.onSuccess();});}
_onDeactivateSnippet(){this._activateSnippet(false);}
_onSnippetDragAndDropStart(){this.snippetEditorDragging=true;}
async _onSnippetDragAndDropStop(ev){this.snippetEditorDragging=false;const visibleConditionalEls=[];for(const snippetEditor of this.snippetEditors){const targetEl=snippetEditor.$target[0];if(targetEl.dataset["visibility"]==="conditional"&&!targetEl.classList.contains("o_conditional_hidden")){visibleConditionalEls.push(targetEl);}}
const modalEl=ev.data.$snippet[0].closest('.modal');const carouselItemEl=ev.data.$snippet[0].closest('.carousel-item');await this._destroyEditors(carouselItemEl?$(carouselItemEl):modalEl?$(modalEl):null);await this._activateSnippet(ev.data.$snippet);for(const visibleConditionalEl of visibleConditionalEls){visibleConditionalEl.classList.remove("o_conditional_hidden");delete visibleConditionalEl.dataset["invisible"];}
await this._updateInvisibleDOM();}
_onTouchEvent(ev){if(ev.touches.length>1||ev.changedTouches.length<1){return;}
const touch=ev.changedTouches[0];const touchToMouse={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup"};const simulatedEvent=new MouseEvent(touchToMouse[ev.type],{screenX:touch.screenX,screenY:touch.screenY,clientX:touch.clientX,clientY:touch.clientY,button:0,bubbles:true,cancelable:true,});touch.target.dispatchEvent(simulatedEvent);}
_onFindSnippetTemplate(ev){const snippet=[...this.snippets.values()].find((snippet)=>{return snippet.name===ev.data.snippet.dataset.snippet;});if(snippet){ev.data.callback(snippet);}}
_onHideOverlay(){for(const editor of this.snippetEditors){editor.toggleOverlay(false);}}
_onIsElementSelected(ev){for(const editor of this.snippetEditors){if(editor.isShown()&&editor.$target[0]===ev.data.el){ev.data.callback();}}}
_onInstallBtnClick(ev){const snippetEl=ev.currentTarget.closest('[data-module-id]');const moduleID=parseInt(snippetEl.dataset.moduleId);const moduleDisplayName=snippetEl.dataset.moduleDisplayName;this._installModule(moduleID,moduleDisplayName);}
async onInvisibleEntryClick(invisibleEntry){const toggleVisibility=async(snippetEl)=>{const isVisible=await this._execWithLoadingEffect(async()=>{const editor=await this._createSnippetEditor($(snippetEl));const show=editor.toggleTargetVisibility();this._disableUndroppableSnippets();return show;},true);invisibleEntry.isVisible=isVisible;this._activateSnippet(isVisible?$(snippetEl):false);};if(invisibleEntry.isVisible){invisibleEntry.children.forEach((child)=>{if(child.isVisible){this.onInvisibleEntryClick(child);}});}else if(invisibleEntry.parents&&!invisibleEntry.parents.isVisible){this.onInvisibleEntryClick(invisibleEntry.parents);}
await toggleVisibility(invisibleEntry.snippetEl);}
_onBlocksTabClick(ev){this._activateSnippet(false);}
_onOptionsTabClick(ev){if(!ev.currentTarget.classList.contains('active')){this._activateSnippet(false);this._mutex.exec(()=>{this._activateEmptyOptionsTab();});}}
_onDeleteBtnClick(ev){ev.stopPropagation();const snippetKey=parseInt(ev.currentTarget.dataset.snippetKey);this._deleteCustomSnippet(snippetKey);}
_onRenameBtnClick(ev){const snippetKey=parseInt(ev.currentTarget.dataset.snippetKey);const snippet=this.snippets.get(snippetKey);snippet.renaming=true;}
async _onConfirmRename(ev){const input=ev.target.parentElement.querySelector("input");const snippetKey=parseInt(ev.target.closest(".oe_snippet").dataset.snippetKey);const newName=input.value;this._renameCustomSnippet(snippetKey,newName);}
_onMouseDown(ev){const $blockedArea=$('#wrapwrap');this.options.wysiwyg.odooEditor.automaticStepSkipStack();$blockedArea.addClass('o_we_no_pointer_events');const reenable=()=>{this.options.wysiwyg.odooEditor.automaticStepSkipStack();$blockedArea.removeClass('o_we_no_pointer_events');};const enableTimeoutID=setTimeout(()=>reenable(),5000);$(document).one('mouseup',()=>{clearTimeout(enableTimeoutID);reenable();});if(ev.target.closest(".o_colorpicker_widget")){this._isColorpickerClick=true;}}
_onMouseUp(ev){const snippetEl=ev.target.closest('.oe_snippet');if(snippetEl&&snippetEl.classList.contains("o_we_draggable")){this._showSnippetTooltip(snippetEl);}}
_showSnippetTooltip(snippetEl,delay=1500){if(snippetEl.dataset.snippetGroup||snippetEl.classList.contains("o_snippet_install")){return;}
if(this.hideShownTooltip){this.hideShownTooltip();}
this.hideShownTooltip=this.popover.add(snippetEl,OdooTooltip,{tooltip:_t("Drag and drop the building block."),});this._hideSnippetTooltips(1500);}
_hideSnippetTooltips(delay=0){clearTimeout(this.__hideSnippetTooltipTimeout);this.__hideSnippetTooltipTimeout=setTimeout(()=>{this.hideShownTooltip?.();},delay);}
_onGetSnippetVersions(ev){const snippet=[...this.snippets.values()].find((snippet)=>snippet.name===ev.data.snippetName);ev.data.onSuccess(snippet&&{vcss:snippet.data.vcss,vjs:snippet.data.vjs,vxml:snippet.data.vxml,});}
async _onReloadSnippetTemplate(ev){await this._activateSnippet(false);this.invalidateSnippetCache=true;await this._loadSnippetsTemplates();}
_onBlockPreviewOverlays(ev){this._blockPreviewOverlays=true;}
_onUnblockPreviewOverlays(ev){this._blockPreviewOverlays=false;}
async _onRemoveSnippet(ev){ev.stopPropagation();const editor=await this._createSnippetEditor(ev.data.$snippet);await editor.removeSnippet(ev.data.shouldRecordUndo);if(ev.data.onSuccess){ev.data.onSuccess();}}
_onSaveRequest(ev){const data=ev.data||{};if(data.invalidateSnippetCache){this.invalidateSnippetCache=true;}
ev.stopped=true;this._buttonClick(async(after)=>{await this.postSnippetDropPromise;return this._execWithLoadingEffect(()=>{const oldOnFailure=data.onFailure;data.onFailure=()=>{if(oldOnFailure){oldOnFailure();}
after();};this.props.trigger_up({name:'request_save',data});},true);},this.$el[0].querySelector('button[data-action=save]'));}
_onSnippetClick(ev){if(!ev.currentTarget.matches(".o_disabled")&&ev.currentTarget.dataset.snippetGroup){this._openAddSnippetDialog(ev.currentTarget.dataset.snippetGroup,ev.currentTarget);}else{const $els=this.getEditableArea().find('.oe_structure.oe_empty').addBack('.oe_structure.oe_empty');for(const el of $els){if(!el.children.length){$(el).odooBounce('o_we_snippet_area_animation');}}}}
_onSnippetEditionRequest(ev){this._execWithLoadingEffect(ev.data.exec,ev.data.optionsLoader?"both":true);}
_onSnippetEditorDestroyed(ev){ev.stopPropagation();const index=this.snippetEditors.indexOf(ev.target);this.snippetEditors.splice(index,1);}
_onSnippetCloned(ev){this._updateInvisibleDOM();}
_onSnippetRemoved(){this._disableUndroppableSnippets();this._updateInvisibleDOM();}
_onSnippetOptionUpdate(ev){ev.stopPropagation();(async()=>{await this._snippetOptionUpdate();ev.data.onSuccess();})();}
async _onSnippetOptionVisibilityUpdate(ev){if(this.options.wysiwyg.isSaving()){return;}
if(!ev.data.show){await this._activateSnippet(false);}
await this._updateInvisibleDOM();}
_onSnippetThumbnailURLRequest(ev){if(!ev.data.key){ev.data.onSuccess("");}
const snippet=[...this.snippets.values()].find((snippet)=>!snippet.isCustom&&snippet.name===ev.data.key);ev.data.onSuccess(snippet?snippet.thumbnailSrc:'');}
_onUserValueWidgetOpening(){this._closeWidgets();this.el.classList.add('o_we_backdrop');}
_onUserValueWidgetClosing(){this.el.classList.remove('o_we_backdrop');}
async _onUpdateInvisibleDom(){await this._updateInvisibleDOM();}
_addToolbar(toolbarMode="text"){if(this.folded){return;}
let titleText=_t("Inline Text");switch(toolbarMode){case"image":titleText=_t("Image Formatting");break;case"video":titleText=_t("Video Formatting");break;case"picto":titleText=_t("Icon Formatting");break;}
this.state.toolbarTitle=titleText;for(const dropdown of this._toolbarWrapperEl.querySelectorAll('.colorpicker-group')){const $=dropdown.ownerDocument.defaultView.$;const $dropdown=$(dropdown);$dropdown.off('show.bs.dropdown');$dropdown.on('show.bs.dropdown',()=>{this.options.wysiwyg.onColorpaletteDropdownShow(dropdown.dataset.colorType);});$dropdown.off('hide.bs.dropdown');$dropdown.on('hide.bs.dropdown',(ev)=>this.options.wysiwyg.onColorpaletteDropdownHide(ev));}
this._checkEditorToolbarVisibility();}
_checkEditorToolbarVisibility(e){const $toolbarTableContainer=this.$('#o-we-editor-table-container');const selection=this.options.wysiwyg.odooEditor.document.getSelection();const range=selection&&selection.rangeCount&&selection.getRangeAt(0);const $currentSelectionTarget=$(range&&range.commonAncestorContainer);if($currentSelectionTarget.closest('#o_we_editor_toolbar_container').length||(e&&$(e.target).closest('#o_we_editor_toolbar_container').length)){return;}
this.state.showToolbar=!(!range||!$currentSelectionTarget.parents('#wrapwrap, .iframe-editor-wrapper').length||closestElement(selection.anchorNode,'[data-oe-model]:not([data-oe-type="html"]):not([data-oe-field="arch"]):not([data-oe-translation-source-sha])')||closestElement(selection.focusNode,'[data-oe-model]:not([data-oe-type="html"]):not([data-oe-field="arch"]):not([data-oe-translation-source-sha])')||(e&&$(e.target).closest('.fa, img').length||this.options.wysiwyg.lastMediaClicked&&$(this.options.wysiwyg.lastMediaClicked).is('.fa, img'))||(this.options.wysiwyg.lastElement&&!this.options.wysiwyg.lastElement.isContentEditable));const isInsideTD=!!(range&&$(range.startContainer).closest('.o_editable td').length&&$(range.endContainer).closest('.o_editable td').length);$toolbarTableContainer.toggleClass('d-none',!isInsideTD);}
_onDiscardClick(){this._buttonClick(after=>{this.snippetEditors.forEach(editor=>{editor.toggleOverlay(false);});this.props.trigger_up({name:'request_cancel',data:{onReject:after}});},this.$el[0].querySelector('button[data-action=cancel]'),false);}
_onMobilePreviewClick(){this._execWithLoadingEffect(async()=>{const initialBodySize=this.$body[0].clientWidth;this._toggleMobilePreview();let count=0;do{await new Promise(resolve=>setTimeout(resolve,1));}while(count++<1000&&Math.abs(this.$body[0].clientWidth-initialBodySize)<1);const $gridItemEls=this.getEditableArea().find('div.o_grid_item');for(const gridItemEl of $gridItemEls){gridUtils._reloadLazyImages(gridItemEl);}
const isMobilePreview=weUtils.isMobileView(this.$body[0]);for(const invisibleOverrideEl of this.getEditableArea().find('.o_snippet_mobile_invisible, .o_snippet_desktop_invisible')){const isMobileHidden=invisibleOverrideEl.classList.contains("o_snippet_mobile_invisible");invisibleOverrideEl.classList.remove('o_snippet_override_invisible');if(isMobilePreview===isMobileHidden){invisibleOverrideEl.dataset.invisible='1';}else{delete invisibleOverrideEl.dataset.invisible;}}
this._updateInvisibleDOM();const enabledInvisibleOverrideEl=this.options.wysiwyg.lastElement&&this.options.wysiwyg.lastElement.closest(".o_snippet_mobile_invisible, .o_snippet_desktop_invisible");const needDeactivate=enabledInvisibleOverrideEl&&enabledInvisibleOverrideEl.dataset.invisible==="1";if(needDeactivate){return new Promise((resolve)=>{this._activateSnippet(false);resolve();});}
return this._snippetOptionUpdate();},false);}
_toggleMobilePreview(){return false;}
async _onUndo(){this.options.wysiwyg.undo();}
async _onRedo(){this.options.wysiwyg.redo();}
_onRequestEditable(ev){ev.data.callback($(this.options.wysiwyg.odooEditor.editable));}
_onEnableLoadingEffect(){this._loadingEffectDisabled=false;}
_onDisableLoadingEffect(){this._loadingEffectDisabled=true;Object.keys(this.loadingElements).forEach(key=>{if(this.loadingElements[key]){this.loadingElements[key].remove();this.loadingElements[key]=null;}});}
async _buttonClick(action,button,addLoadingEffect=true){if(this._buttonAction){return;}
this._buttonAction=true;let removeLoadingEffect;this._hideTooltips();if(addLoadingEffect){removeLoadingEffect=addButtonLoadingEffect(button);}
const actionButtons=this.$el[0].querySelectorAll('[data-action]');for(const actionButton of actionButtons){actionButton.disabled=true;}
const after=()=>{if(removeLoadingEffect){removeLoadingEffect();}
for(const actionButton of actionButtons){actionButton.disabled=false;}};await action(after);this._buttonAction=false;}
async _enableFakeOptionsTab(tab){let releaseLoader;try{const promise=new Promise(resolve=>releaseLoader=resolve);this._execWithLoadingEffect(()=>promise,false,0);await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));if(!this.topFakeOptionEl){let el;for(const[elementName,title]of this.constructor.optionsTabStructure){const newEl=document.createElement(elementName);newEl.dataset.name=title;if(el){el.appendChild(newEl);}else{this.topFakeOptionEl=newEl;}
el=newEl;}
this.bottomFakeOptionEl=el;this.$body[0].appendChild(this.topFakeOptionEl);}
this.topFakeOptionEl.classList.remove('d-none');const editorPromise=this._activateSnippet($(this.bottomFakeOptionEl));releaseLoader();releaseLoader=undefined;const editor=await editorPromise;this.topFakeOptionEl.classList.add('d-none');editor.toggleOverlay(false);this._updateRightPanelContent({tab,});}catch(e){if(releaseLoader){releaseLoader();}
throw e;}}
_onDropZoneStart(){}
_onDropZoneOver(){}
_onDropZoneOut(){}
_onDropZoneStop(){}
_trigger_up(ev){if(ev.name in this.constructor.custom_events){this[this.constructor.custom_events[ev.name]](ev);}
if(!ev.stopped){return this.props.trigger_up(ev);}}
_onOpenAddSnippetDialog(ev){this._openAddSnippetDialog(ev.data.snippetGroup,ev.data.initialSnippetEl);}
async _openAddSnippetDialog(snippetGroup=null,initialSnippetEl){this._mutex.exec(async()=>{let hookEl=null;let dropZoneEls=null;let isSnippetChosen=false;const snippetThumbnails=this.el.querySelectorAll(".oe_snippet_thumbnail");const isSnippetGroupClicked=initialSnippetEl.matches(".oe_snippet[data-snippet-group]");const groupSelected=snippetGroup||[...this.snippets.values()].find(snippet=>snippet.name===initialSnippetEl.dataset.snippet).group;this.options.wysiwyg.odooEditor.historyPauseSteps();if(isSnippetGroupClicked){const thumbnailEl=initialSnippetEl.querySelector(".oe_snippet_thumbnail");thumbnailEl.classList.add("o_we_ongoing_insertion");const selectors=this._getSelectors($("<section></section>"));this._activateInsertionZones(selectors.$selectorSiblings,selectors.$selectorChildren,false,false);dropZoneEls=this.$body[0].querySelectorAll(".oe_drop_zone");dropZoneEls.forEach(dropZoneEl=>dropZoneEl.classList.add("invisible"));dropZoneEls=[...dropZoneEls].filter(dropzoneEl=>{return!dropzoneEl.closest("[data-snippet]:not(.s_popup), #website_cookies_bar");});if(dropZoneEls?.length){hookEl=this._getClosestDropzone(dropZoneEls)||dropZoneEls[dropZoneEls.length-1];hookEl.classList.add("o_hook_drop_zone");}}else{hookEl=initialSnippetEl;}
if(hookEl){const hookParentEl=hookEl.parentNode;[...this.snippets.values()].forEach((snippet)=>{if(snippet.disabled){snippet.excluded=true;}else{const $snippetSelectorChildren=this._getSelectors($(snippet.baseBody)).$selectorChildren;const hasSelectorChild=[...$snippetSelectorChildren].some(snippetSelectorChild=>{return snippetSelectorChild===hookParentEl;});const forbidSanitize=snippet.data.oeForbidSanitize;let isForbidden=false;if(forbidSanitize==="form"){isForbidden=hookEl.closest('[data-oe-sanitize]:not([data-oe-sanitize="allow_form"])');}else if(forbidSanitize){isForbidden=hookEl.closest("[data-oe-sanitize]");}
snippet.excluded=!hasSelectorChild||isForbidden;}});}
const hasIncludedSnippet=[...this.snippets.values()].some(snippet=>snippet.excluded===false);if(!hasIncludedSnippet||!hookEl){if(dropZoneEls?.length){dropZoneEls.forEach(dropZoneEl=>dropZoneEl.remove());}
this.options.wysiwyg.odooEditor.historyUnpauseSteps();for(const snippetThumbnail of snippetThumbnails){snippetThumbnail.classList.remove('o_we_ongoing_insertion');}
return;}
await new Promise(resolve=>{this.dialog.add(AddSnippetDialog,{snippets:this.snippets,groupSelected:groupSelected,optionsSnippets:this.options.snippets,frontendDirection:this.options.direction,installModule:(moduleID,moduleDisplayName)=>{resolve();this._installModule(moduleID,moduleDisplayName);},addSnippet:async(snippetEl)=>{isSnippetChosen=true;hookEl.parentNode.insertBefore(snippetEl,hookEl);hookEl.parentNode.removeChild(hookEl);this.options.wysiwyg.odooEditor.automaticStepSkipStack();await this._scrollToSnippet($(snippetEl),this.$scrollable);this.options.wysiwyg.odooEditor.historyUnpauseSteps();browser.setTimeout(async()=>{resolve();await this.callPostSnippetDrop($(snippetEl),()=>{this._disableUndroppableSnippets();this.options.wysiwyg.odooEditor.historyStep();for(const snippetThumbnail of snippetThumbnails){snippetThumbnail.classList.remove('o_we_ongoing_insertion');}});});},deleteCustomSnippet:(snippetKey)=>{return this._deleteCustomSnippet(snippetKey,false);},renameCustomSnippet:(snippetKey,newName)=>{this._renameCustomSnippet(snippetKey,newName,false);},},{onClose:()=>{if(isSnippetGroupClicked){dropZoneEls=this.$body[0].querySelectorAll(".oe_drop_zone")
if(dropZoneEls){dropZoneEls.forEach(dropZoneEl=>dropZoneEl.remove());}}else if(!isSnippetChosen&&snippetGroup){initialSnippetEl.remove();}
if(!isSnippetChosen){this.options.wysiwyg.odooEditor.automaticStepSkipStack();this.options.wysiwyg.odooEditor.historyUnpauseSteps();for(const snippetThumbnail of snippetThumbnails){snippetThumbnail.classList.remove('o_we_ongoing_insertion');}
resolve();}}});});});}
_getClosestDropzone(dropZoneEls){let closestDropZoneEl=null;let closestDistance=Infinity;const iframeWindow=this.$body[0].ownerDocument.defaultView;const iframeWindowMidY=iframeWindow.innerHeight/2;for(const dropZoneEl of dropZoneEls){const rect=dropZoneEl.getBoundingClientRect();if(0>(rect.top-(iframeWindowMidY/2))){continue;}
const dropZoneElMidY=rect.top+(rect.height/2);const distance=Math.abs(iframeWindowMidY-dropZoneElMidY);if(distance<closestDistance){closestDistance=distance;closestDropZoneEl=dropZoneEl;}};return closestDropZoneEl;}
_installModule(moduleID,moduleDisplayName){moduleDisplayName=`"${moduleDisplayName}"`;const bodyText=_t("Do you want to install %s App?",moduleDisplayName);const linkText=_t("More info about this app.");const linkUrl='/odoo/action-base.open_module_tree/'+encodeURIComponent(moduleID);this.dialog.add(ConfirmationDialog,{title:_t("Install %s",moduleDisplayName),body:markup(`${escape(bodyText)}\n<a href="${escape(linkUrl)}" target="_blank"><i class="oi oi-arrow-right me-1"></i>${escape(linkText)}</a>`),confirm:async()=>{try{await this.orm.call("ir.module.module","button_immediate_install",[[moduleID]]);this.invalidateSnippetCache=true;this._onSaveRequest({data:{reloadWebClient:true,}});}catch(e){if(e instanceof RPCError){const message=escape(_t("Could not install module %s",moduleDisplayName));this.notification.add(message,{type:"danger",sticky:true,});}else{throw e;}}},confirmLabel:_t("Save and Install"),cancel:()=>{},});}
async _deleteCustomSnippet(snippetKey,withMutex=true){const snippet=this.snippets.get(snippetKey);const message=_t("Are you sure you want to delete the block %s?",snippet.displayName);return new Promise(resolve=>{this.dialog.add(ConfirmationDialog,{body:message,confirm:async()=>{await this.orm.call("ir.ui.view","delete_snippet",[],{'view_id':snippet.id,'template_key':this.options.snippets,});this.invalidateSnippetCache=true;this.snippets.delete(snippetKey);await this._loadSnippetsTemplates(withMutex);resolve();},cancel:()=>{resolve();return null;},confirmLabel:_t("Yes"),cancelLabel:_t("No"),});});}
async _renameCustomSnippet(snippetKey,newName,withMutex=true){const snippet=this.snippets.get(snippetKey);if(newName!==snippet.displayName){await this.orm.call("ir.ui.view","rename_snippet",[],{'name':newName,'view_id':snippet.id,'template_key':this.options.snippets,});this.invalidateSnippetCache=newName!==snippet.displayName;snippet.displayName=newName;await this._loadSnippetsTemplates(withMutex);}
snippet.renaming=false;}}
__exports[Symbol.for("default")]={SnippetsMenu:SnippetsMenu,SnippetEditor:SnippetEditor,globalSelector:globalSelector,};return __exports;});;

/* /web_editor/static/src/js/editor/snippets.options.js */
odoo.define('@web_editor/js/editor/snippets.options',['@web_editor/js/core/owl_utils','@web_editor/components/media_dialog/media_dialog','@web/core/confirmation_dialog/confirmation_dialog','@web/core/utils/timing','@web/core/utils/numbers','@web_editor/js/common/scrolling','@web/legacy/js/public/public_widget','@web_editor/js/wysiwyg/widgets/color_palette','@web_editor/js/common/utils','@web_editor/js/common/grid_layout_utils','@web_editor/js/common/column_layout_mixin','@web_editor/js/wysiwyg/widgets/image_crop','@web_editor/js/editor/image_processing','@web_editor/js/editor/odoo-editor/src/OdooEditor','@web/core/utils/objects','@web/core/l10n/translation','@web/core/utils/colors','@web/core/utils/render','@web/core/network/rpc'],function(require){'use strict';let __exports={};const{attachComponent}=require("@web_editor/js/core/owl_utils");const{MediaDialog}=require("@web_editor/components/media_dialog/media_dialog");const{ConfirmationDialog}=require("@web/core/confirmation_dialog/confirmation_dialog");const{throttleForAnimation,debounce}=require("@web/core/utils/timing");const{clamp}=require("@web/core/utils/numbers");const{scrollTo}=require("@web_editor/js/common/scrolling");const publicWidget=require("@web/legacy/js/public/public_widget")[Symbol.for("default")];const{ColorPalette}=require("@web_editor/js/wysiwyg/widgets/color_palette");const weUtils=require("@web_editor/js/common/utils")[Symbol.for("default")];const gridUtils=require("@web_editor/js/common/grid_layout_utils");const{ColumnLayoutMixin}=require("@web_editor/js/common/column_layout_mixin");const{normalizeColor,getBgImageURL,backgroundImageCssToParts,backgroundImagePartsToCss,DEFAULT_PALETTE,isBackgroundImageAttribute,}=weUtils;const{ImageCrop}=require('@web_editor/js/wysiwyg/widgets/image_crop');const{loadImage,loadImageInfo,applyModifications,removeOnImageChangeAttrs,isImageSupportedForProcessing,isImageSupportedForStyle,createDataURL,isGif,getDataURLBinarySize,isWebGLEnabled,}=require("@web_editor/js/editor/image_processing");const OdooEditorLib=require("@web_editor/js/editor/odoo-editor/src/OdooEditor");const{pick}=require("@web/core/utils/objects");const{_t}=require("@web/core/l10n/translation");const{isCSSColor,convertCSSColorToRgba,normalizeCSSColor,}=require('@web/core/utils/colors');const{renderToElement}=require("@web/core/utils/render");const{rpc}=require("@web/core/network/rpc");const preserveCursor=OdooEditorLib.preserveCursor;const{DateTime}=luxon;const resetOuids=OdooEditorLib.resetOuids;let _serviceCache={orm:{},rpc:{},};const clearServiceCache=()=>{_serviceCache={orm:{},rpc:{},};};const CSS_ANIMATION_RULE_REGEX=/(?<declaration>animation(?:-duration)?:\s*.*?)(?<value>(?:\d+(?:\.\d+)?)|(?:\.\d+))(?<unit>ms|s)(?<separator>\s|;|"|$)/gm;const SVG_DUR_TIMECOUNT_VAL_REGEX=/(?<attribute_name>\sdur="\s*)(?<value>(?:\d+(?:\.\d+)?)|(?:\.\d+))(?<unit>h|min|ms|s)?\s*"/gm;const CSS_ANIMATION_RATIO_REGEX=/(--animation_ratio: (?<ratio>\d*(\.\d+)?));/m;function serviceCached(service){const cache=_serviceCache;return Object.assign(Object.create(service),{call(){const serviceName=Object.prototype.hasOwnProperty.call(service,"call")?"orm":"rpc";const cacheId=JSON.stringify(arguments);if(!cache[serviceName][cacheId]){cache[serviceName][cacheId]=serviceName=="rpc"?service(...arguments):service.call(...arguments);}
return cache[serviceName][cacheId];},});}
const controlledSnippets=new Set();const clearControlledSnippets=()=>controlledSnippets.clear();function _addTitleAndAllowedAttributes(el,title,options){let tooltipEl=el;if(title){const titleEl=_buildTitleElement(title);tooltipEl=titleEl;el.appendChild(titleEl);if(options&&options.dataAttributes&&options.dataAttributes.fontFamily){titleEl.style.fontFamily=options.dataAttributes.fontFamily;}}
if(options&&options.classes){el.classList.add(...options.classes);}
if(options&&options.tooltip){tooltipEl.title=options.tooltip;}
if(options&&options.placeholder){el.setAttribute('placeholder',options.placeholder);}
if(options&&options.dataAttributes){for(const key in options.dataAttributes){el.dataset[key]=options.dataAttributes[key];}}
return el;}
function _buildElement(tagName,title,options){const el=document.createElement(tagName);return _addTitleAndAllowedAttributes(el,title,options);}
function _buildTitleElement(title){const titleEl=document.createElement('we-title');titleEl.textContent=title;return titleEl;}
const _buildImgElementCache={};async function _buildImgElement(src){if(!(src in _buildImgElementCache)){_buildImgElementCache[src]=(async()=>{let text;if(src.split('.').pop()==='svg'){try{const response=await window.fetch(src);text=await response.text();}catch{text="<svg></svg>";}
const parser=new window.DOMParser();const xmlDoc=parser.parseFromString(text,'text/xml');return xmlDoc.getElementsByTagName('svg')[0];}else{const imgEl=document.createElement('img');imgEl.src=src;return imgEl;}})();}
const node=await _buildImgElementCache[src];return node.cloneNode(true);}
function _buildRowElement(title,options){const groupEl=_buildElement('we-row',title,options);const rowEl=document.createElement('div');groupEl.appendChild(rowEl);if(options&&options.childNodes){options.childNodes.forEach(node=>rowEl.appendChild(node));}
return groupEl;}
function _buildCollapseElement(title,options){const groupEl=_buildElement('we-collapse',title,options);const titleEl=groupEl.querySelector('we-title');const children=options&&options.childNodes||[];if(titleEl){titleEl.remove();titleEl.classList.add('o_we_collapse_toggler');children.unshift(titleEl);}
let i=0;for(i=0;i<children.length;i++){groupEl.appendChild(children[i]);if(children[i].nodeType===Node.ELEMENT_NODE){break;}}
const togglerEl=document.createElement('we-toggler');togglerEl.classList.add('o_we_collapse_toggler');groupEl.appendChild(togglerEl);const containerEl=document.createElement('div');children.slice(i+1).forEach(node=>containerEl.appendChild(node));groupEl.appendChild(containerEl);return groupEl;}
function createPropertyProxy(obj,propertyName,value){return new Proxy(obj,{get:function(obj,prop){if(prop===propertyName){return value;}
return obj[prop];},set:function(obj,prop,val){if(prop===propertyName){return(value=val);}
return Reflect.set(...arguments);},});}
function registerUserValueWidget(widgetName,parent,title,options,$target){const widget=new userValueWidgetsRegistry[widgetName](parent,title,options,$target);parent.registerSubWidget(widget);return widget;}
const NULL_ID='__NULL__';const UserValueWidget=publicWidget.Widget.extend({className:'o_we_user_value_widget',custom_events:{'user_value_update':'_onUserValueNotification',},init:function(parent,title,options,$target){this._super(...arguments);this.title=title;this.options=options;this._userValueWidgets=[];this._value='';this.$target=$target;},async willStart(){await this._super(...arguments);if(this.options.dataAttributes.img){this.illustrationEl=await _buildImgElement(this.options.dataAttributes.img);}else if(this.options.dataAttributes.icon){this.illustrationEl=document.createElement('i');this.illustrationEl.classList.add('fa',this.options.dataAttributes.icon);}
if(this.options.dataAttributes.reload){this.options.dataAttributes.noPreview="true";}},_makeDescriptive:function(){const $el=this._super(...arguments);const el=$el[0];_addTitleAndAllowedAttributes(el,this.title,this.options);this.containerEl=document.createElement('div');if(this.illustrationEl){this.containerEl.appendChild(this.illustrationEl);}
el.appendChild(this.containerEl);return $el;},async start(){await this._super(...arguments);if(this.el.classList.contains('o_we_img_animate')){const buildImgExtensionSwitcher=(from,to)=>{const regex=new RegExp(`${from}$`,'i');return ev=>{const img=ev.currentTarget.getElementsByTagName("img")[0];img.src=img.src.replace(regex,to);};};this.$el.on('mouseenter.img_animate',buildImgExtensionSwitcher('png','gif'));this.$el.on('mouseleave.img_animate',buildImgExtensionSwitcher('gif','png'));}},destroy(){if(this.$el){this.$el.off('.img_animate');}
this._super(...arguments);},close:function(){if(!this.el){return;}
if(!this.el.classList.contains('o_we_widget_opened')){return;}
this.trigger_up('user_value_widget_closing');this.el.classList.remove('o_we_widget_opened');this._userValueWidgets.forEach(widget=>widget.close());},enable(){this.$el.click();},findWidget:function(name){for(const widget of this._userValueWidgets){if(widget.getName()===name){return widget;}
const depWidget=widget.findWidget(name);if(depWidget){return depWidget;}}
return null;},focus(){const el=this._getFocusableElement();if(el){el.focus();}},getActiveValue:function(methodName){return this._value;},getDefaultValue:function(methodName){const possibleValues=this._methodsParams.optionsPossibleValues[methodName];return possibleValues&&possibleValues[0]||'';},getDependencies:function(){return this._dependencies;},getMethodsNames:function(){return this._methodsNames;},getMethodsParams:function(methodName){const params=Object.assign({},this._methodsParams);if(methodName){params.possibleValues=params.optionsPossibleValues[methodName]||[];params.activeValue=this.getActiveValue(methodName);params.defaultValue=this.getDefaultValue(methodName);}
return params;},getName:function(){return this._methodsParams.name||'';},getValue:function(methodName){const isActive=this.isActive();if(!methodName||!this._methodsNames.includes(methodName)){return isActive?'true':'';}
if(isActive){return this.getActiveValue(methodName);}
return this.getDefaultValue(methodName);},isActive:function(){return this._value&&this._value!==NULL_ID;},isContainer:function(){return false;},isPreviewed:function(){const focusEl=document.activeElement;if(focusEl&&focusEl.tagName==='INPUT'&&(this.el===focusEl||this.el.contains(focusEl))){return true;}
return this.el.classList.contains('o_we_preview');},loadMethodsData:function(validMethodNames,extraParams){this._methodsNames=[];this._methodsParams=Object.assign({},extraParams);this._methodsParams.optionsPossibleValues={};this._dependencies=[];this._triggerWidgetsNames=[];this._triggerWidgetsValues=[];for(const key in this.el.dataset){const dataValue=this.el.dataset[key].trim();if(key==='dependencies'){this._dependencies.push(...dataValue.split(/\s*,\s*/g));}else if(key==='trigger'){this._triggerWidgetsNames.push(...dataValue.split(/\s*,\s*/g));}else if(key==='triggerValue'){this._triggerWidgetsValues.push(...dataValue.split(/\s*,\s*/g));}else if(validMethodNames.includes(key)){this._methodsNames.push(key);if(this._methodsParams.noSplit){this._methodsParams.optionsPossibleValues[key]=[dataValue];}else{this._methodsParams.optionsPossibleValues[key]=dataValue.split(/\s*\|\s*/g);}}else{this._methodsParams[key]=dataValue;}}
this._userValueWidgets.forEach(widget=>{const inheritedParams=Object.assign({},this._methodsParams);inheritedParams.optionsPossibleValues=null;widget.loadMethodsData(validMethodNames,inheritedParams);const subMethodsNames=widget.getMethodsNames();const subMethodsParams=widget.getMethodsParams();for(const methodName of subMethodsNames){if(!this._methodsNames.includes(methodName)){this._methodsNames.push(methodName);this._methodsParams.optionsPossibleValues[methodName]=[];}
for(const subPossibleValue of subMethodsParams.optionsPossibleValues[methodName]){this._methodsParams.optionsPossibleValues[methodName].push(subPossibleValue);}}});for(const methodName of this._methodsNames){const arr=this._methodsParams.optionsPossibleValues[methodName];const uniqArr=arr.filter((v,i,arr)=>i===arr.indexOf(v));this._methodsParams.optionsPossibleValues[methodName]=uniqArr;}
this._methodsNames.sort();},notifyValueChange:function(previewMode,isSimulatedEvent){const isPreviewed=this.isPreviewed();if(!previewMode&&!isPreviewed){this.notifyValueChange(true);}
const data={previewMode:previewMode||false,isSimulatedEvent:!!isSimulatedEvent,};if(previewMode===true||previewMode===false){data.prepare=()=>this.el.classList.add('o_we_preview');}else if(previewMode==='reset'){data.prepare=()=>this.el.classList.remove('o_we_preview');}
this.trigger_up('user_value_update',data);},open(){this.trigger_up('user_value_widget_opening');this.el.classList.add('o_we_widget_opened');},registerSubWidget:function(widget){this._userValueWidgets.push(widget);},async setValue(value,methodName){this._value=value;this.el.classList.remove('o_we_preview');},toggleVisibility:function(show){let doFocus=false;if(show){const wasInvisible=this.el.classList.contains('d-none');doFocus=wasInvisible&&this.el.dataset.requestFocus==="true";}
this.el.classList.toggle('d-none',!show);if(doFocus){this.focus();}},_getFocusableElement:function(){return null;},_handleNotifierEvent:function(ev){if(!ev){return true;}
if(ev._seen){return false;}
ev._seen=true;if(ev.preventDefault){ev.preventDefault();}
return true;},_onUserValueChange:function(ev){if(this._handleNotifierEvent(ev)){this.notifyValueChange(false);}},_onUserValueNotification:function(ev){ev.data.widget=this;if(!ev.data.triggerWidgetsNames){ev.data.triggerWidgetsNames=[];}
ev.data.triggerWidgetsNames.push(...this._triggerWidgetsNames);if(!ev.data.triggerWidgetsValues){ev.data.triggerWidgetsValues=[];}
ev.data.triggerWidgetsValues.push(...this._triggerWidgetsValues);},_onUserValuePreview:function(ev){if(this._handleNotifierEvent(ev)){this.notifyValueChange(true);}},_onUserValueReset:function(ev){if(this._handleNotifierEvent(ev)){this.notifyValueChange('reset');}},});const ButtonUserValueWidget=UserValueWidget.extend({tagName:'we-button',events:{'click':'_onButtonClick','click [role="button"]':'_onInnerButtonClick','mouseenter':'_onUserValuePreview','mouseleave':'_onUserValueReset',},async willStart(){await this._super(...arguments);if(this.options.dataAttributes.activeImg){this.activeImgEl=await _buildImgElement(this.options.dataAttributes.activeImg);}},_makeDescriptive(){const $el=this._super(...arguments);if(this.illustrationEl){$el[0].classList.add('o_we_icon_button');}
if(this.activeImgEl){this.containerEl.appendChild(this.activeImgEl);}
return $el;},start:function(parent,title,options){if(this.options&&this.options.childNodes){this.options.childNodes.forEach(node=>this.containerEl.appendChild(node));}
return this._super(...arguments);},getActiveValue:function(methodName){const possibleValues=this._methodsParams.optionsPossibleValues[methodName];return possibleValues&&possibleValues[possibleValues.length-1]||'';},isActive:function(){return(this.isPreviewed()!==this.el.classList.contains('active'));},loadMethodsData:function(validMethodNames){this._super.apply(this,arguments);for(const methodName of this._methodsNames){const possibleValues=this._methodsParams.optionsPossibleValues[methodName];if(possibleValues.length<=1){possibleValues.unshift('');}}},async setValue(value,methodName){await this._super(...arguments);let active=!!value;if(methodName){if(!this._methodsNames.includes(methodName)){return;}
active=(this.getActiveValue(methodName)===value);}
if(this.illustrationEl&&this.activeImgEl){this.illustrationEl.classList.toggle('d-none',active);this.activeImgEl.classList.toggle('d-none',!active);}
this.el.classList.toggle('active',active);},_onButtonClick:function(ev){if(!ev._innerButtonClicked){this._onUserValueChange(ev);}},_onInnerButtonClick:function(ev){ev._innerButtonClicked=true;},});const CheckboxUserValueWidget=ButtonUserValueWidget.extend({className:(ButtonUserValueWidget.prototype.className||'')+' o_we_checkbox_wrapper',start:function(){const checkboxEl=document.createElement('we-checkbox');this.containerEl.appendChild(checkboxEl);return this._super(...arguments);},enable(){this.$('we-checkbox').click();},_onButtonClick(ev){if(!ev.target.closest('we-title, we-checkbox')){return;}
return this._super(...arguments);},});const BaseSelectionUserValueWidget=UserValueWidget.extend({async start(){await this._super(...arguments);this.menuEl=document.createElement('we-selection-items');if(this.options&&this.options.childNodes){this.options.childNodes.forEach(node=>{if(node.nodeType===Node.ELEMENT_NODE){this.menuEl.appendChild(node);}});}
this.containerEl.appendChild(this.menuEl);},getMethodsParams(methodName){const params=this._super(...arguments);const activeWidget=this._getActiveSubWidget();if(!activeWidget){return params;}
return Object.assign(activeWidget.getMethodsParams(...arguments),params);},getValue(methodName){const activeWidget=this._getActiveSubWidget();if(activeWidget){return activeWidget.getActiveValue(methodName);}
return this._super(...arguments);},isContainer(){return true;},async setValue(value,methodName){const _super=this._super.bind(this);for(const widget of this._userValueWidgets){await widget.setValue(NULL_ID,methodName);}
for(const widget of[...this._userValueWidgets].reverse()){await widget.setValue(value,methodName);if(widget.isActive()){break;}}
await _super(...arguments);},_getActiveSubWidget(){const previewedWidget=this._userValueWidgets.find(widget=>widget.isPreviewed());if(previewedWidget){return previewedWidget;}
return this._userValueWidgets.find(widget=>widget.isActive());},});const SelectUserValueWidget=BaseSelectionUserValueWidget.extend({tagName:'we-select',events:{'click':'_onClick',},PLACEHOLDER_TEXT:_t("None"),async start(){await this._super(...arguments);if(this.options&&this.options.valueEl){this.containerEl.insertBefore(this.options.valueEl,this.menuEl);}
this.menuEl.dataset.placeholderText=this.PLACEHOLDER_TEXT;this.menuTogglerEl=document.createElement('we-toggler');this.menuTogglerEl.dataset.placeholderText=this.PLACEHOLDER_TEXT;this.iconEl=this.illustrationEl||null;const icon=this.el.dataset.icon;if(icon){this.iconEl=document.createElement('i');this.iconEl.classList.add('fa','fa-fw',icon);}
if(this.iconEl){this.el.classList.add('o_we_icon_select');this.menuTogglerEl.appendChild(this.iconEl);}
this.containerEl.insertBefore(this.menuTogglerEl,this.menuEl);const dropdownCaretEl=document.createElement('span');dropdownCaretEl.classList.add('o_we_dropdown_caret');this.containerEl.appendChild(dropdownCaretEl);},close:function(){this._super(...arguments);this.el.classList.remove("o_we_select_dropdown_up");if(this.menuTogglerEl){this.menuTogglerEl.classList.remove('active');}},isPreviewed:function(){return this._super(...arguments)||this.menuTogglerEl.classList.contains('active');},open(){this._super(...arguments);this.menuTogglerEl.classList.add('active');this._adjustDropdownPosition();},async setValue(){await this._super(...arguments);if(this.iconEl){return;}
if(this.menuTogglerItemEl){this.menuTogglerItemEl.remove();this.menuTogglerItemEl=null;}
let textContent='';const activeWidget=this._userValueWidgets.find(widget=>!widget.isPreviewed()&&widget.isActive());if(activeWidget){const svgTag=activeWidget.el.querySelector('svg');const value=(activeWidget.el.dataset.selectLabel||(!svgTag&&activeWidget.el.textContent.trim()));const imgSrc=activeWidget.el.dataset.img;const icon=activeWidget.el.dataset.icon;if(value){textContent=value;}else if(icon){this.menuTogglerItemEl=document.createElement('i');this.menuTogglerItemEl.classList.add('fa',icon);}else if(imgSrc){this.menuTogglerItemEl=document.createElement('img');this.menuTogglerItemEl.src=imgSrc;}else{const fakeImgEl=activeWidget.el.querySelector('.o_we_fake_img_item');if(fakeImgEl){this.menuTogglerItemEl=fakeImgEl.cloneNode(true);}}}else{textContent=this.PLACEHOLDER_TEXT;}
this.menuTogglerEl.textContent=textContent;if(this.menuTogglerItemEl){this.menuTogglerEl.appendChild(this.menuTogglerItemEl);}},enable(){if(!this.menuTogglerEl.classList.contains('active')){this.menuTogglerEl.click();}},_shouldIgnoreClick(ev){if(this.el.dataset.disabled==="true"){ev.preventDefault();return true;}
return!!ev.target.closest('[role="button"]');},_adjustDropdownPosition(){const customizePanelEl=this.menuEl.closest(".o_we_customize_panel");if(!customizePanelEl){return;}
this.el.classList.remove("o_we_select_dropdown_up");const customizePanelElCoords=customizePanelEl.getBoundingClientRect();let dropdownMenuElCoords=this.menuEl.getBoundingClientRect();const dropdownMenuMargin=5;if((dropdownMenuElCoords.bottom+dropdownMenuMargin)>customizePanelElCoords.bottom){this.el.classList.add("o_we_select_dropdown_up");dropdownMenuElCoords=this.menuEl.getBoundingClientRect();if(dropdownMenuElCoords.top<customizePanelElCoords.top){this.el.classList.remove("o_we_select_dropdown_up");}}},_onClick:function(ev){if(this._shouldIgnoreClick(ev)){return;}
if(!this.menuTogglerEl.classList.contains('active')){this.open();}else{this.close();}
const activeButton=this._userValueWidgets.find(widget=>widget.isActive());if(activeButton){this.menuEl.scrollTop=activeButton.el.offsetTop-(this.menuEl.offsetHeight/2);}},});const ButtonGroupUserValueWidget=BaseSelectionUserValueWidget.extend({tagName:'we-button-group',});const UnitUserValueWidget=UserValueWidget.extend({start:async function(){const unit=this.el.dataset.unit||'';this.el.dataset.unit=unit;if(this.el.dataset.saveUnit===undefined){this.el.dataset.saveUnit=unit;}
return this._super(...arguments);},getActiveValue:function(methodName){const activeValue=this._super(...arguments);const params=this._methodsParams;if(!this._isNumeric()){return activeValue;}
const defaultValue=this.getDefaultValue(methodName,false);return activeValue.split(/\s+/g).map(v=>{const numValue=parseFloat(v);if(isNaN(numValue)){return defaultValue;}else{const value=weUtils.convertNumericToUnit(numValue,params.unit,params.saveUnit,params.cssProperty,this.$target);return`${this._floatToStr(value)}${params.saveUnit}`;}}).join(' ');},getDefaultValue:function(methodName,useInputUnit){const defaultValue=this._super(...arguments);const params=this._methodsParams;if(!this._isNumeric()){return defaultValue;}
const unit=useInputUnit?params.unit:params.saveUnit;const numValue=weUtils.convertValueToUnit(defaultValue||'0',unit,params.cssProperty,this.$target);if(isNaN(numValue)){return defaultValue;}
return`${this._floatToStr(numValue)}${unit}`;},isActive:function(){const isSuperActive=this._super(...arguments);if(!this._isNumeric()){return isSuperActive;}
return isSuperActive&&(this._floatToStr(parseFloat(this._value))!=='0'||!!this._value.match(/\d+\s+\d+/));},async setValue(value,methodName){const params=this._methodsParams;if(this._isNumeric()){value=value.split(' ').map(v=>{const numValue=weUtils.convertValueToUnit(v,params.unit,params.cssProperty,this.$target);if(isNaN(numValue)){return'';}
return this._floatToStr(numValue);}).join(' ');}
return this._super(value,methodName);},_floatToStr:function(value){return`${parseFloat(value.toFixed(5))}`;},_isNumeric(){const params=this._methodsParams||this.el.dataset;return!!params.unit;},});const InputUserValueWidget=UnitUserValueWidget.extend({tagName:'we-input',events:{'input input':'_onInputInput','blur input':'_onInputBlur','change input':'_onUserValueChange','keydown input':'_onInputKeydown',},start:async function(){await this._super(...arguments);const unit=this.el.dataset.unit;this.inputEl=document.createElement('input');this.inputEl.setAttribute('type','text');this.inputEl.setAttribute('autocomplete','chrome-off');this.inputEl.setAttribute('placeholder',this.el.getAttribute('placeholder')||'');const useNumberAlignment=this._isNumeric()||!!this.el.dataset.hideUnit;this.inputEl.classList.toggle('text-start',!useNumberAlignment);this.inputEl.classList.toggle('text-end',useNumberAlignment);this.containerEl.appendChild(this.inputEl);const showUnit=(!!unit||!!this.el.dataset.fakeUnit)&&!this.el.dataset.hideUnit;if(showUnit){var unitEl=document.createElement('span');const unitText=this.el.dataset.fakeUnit||unit;unitEl.textContent=unitText;this.containerEl.appendChild(unitEl);if(unitText.length>3){this.el.classList.add('o_we_large');}}},async setValue(){await this._super(...arguments);this.inputEl.value=this._value;this._oldValue=this._value;},_getFocusableElement(){return this.inputEl;},_isNumeric(){const isNumeric=this._super(...arguments);const params=this._methodsParams||this.el.dataset;return isNumeric||!!params.fakeUnit||!!params.step;},_onInputInput:function(ev){this._value=this.inputEl.value;const params=this._methodsParams;const hasMin=('min'in params);const hasMax=('max'in params);if(hasMin||hasMax){const boundedValue=this._value.split(/\s+/g).map(v=>{let numValue=parseFloat(v);if(isNaN(numValue)){return hasMin?params.min:v;}else{numValue=hasMin?Math.max(params.min,numValue):numValue;numValue=hasMax?Math.min(numValue,params.max):numValue;return numValue;}}).join(" ");this._oldValue=undefined;this._value=boundedValue;}
if(!ev.detail||!ev.detail.keyUpOrDown){this.changeEventWillBeTriggered=true;}
this._onUserValuePreview(ev);},_onInputBlur:function(ev){if(this.notifyValueChangeOnBlur&&!this.changeEventWillBeTriggered){this._onUserValueChange(ev);this.notifyValueChangeOnBlur=false;}
this.changeEventWillBeTriggered=false;},_onInputKeydown:function(ev){const params=this._methodsParams;if(!this._isNumeric()){return;}
switch(ev.key){case"Enter":this._onUserValueChange(ev);break;case"ArrowUp":case"ArrowDown":{const input=ev.currentTarget;let parts=(input.value||input.placeholder).match(/-?\d+\.\d+|-?\d+/g);if(!parts){parts=[input.value||input.placeholder];}
if(parts.length>1&&!('min'in params)){params['min']=0;}
const newValue=parts.map(part=>{let value=parseFloat(part);if(isNaN(value)){value=0.0;}
let step=parseFloat(params.step);if(isNaN(step)){step=1.0;}
const increasing=ev.key==="ArrowUp";const hasMin=('min'in params);const hasMax=('max'in params);if(!increasing&&hasMin&&Math.abs(value-params.min)<0.001){return value;}
if(increasing&&hasMax&&Math.abs(value-params.max)<0.001){return value;}
value+=(increasing?step:-step);value=hasMin?Math.max(params.min,value):value;value=hasMax?Math.min(value,params.max):value;return this._floatToStr(value);}).join(" ");if(newValue===(input.value||input.placeholder)){return;}
input.value=newValue;input.dispatchEvent(new CustomEvent('input',{bubbles:true,cancelable:true,detail:{keyUpOrDown:true}}));this.notifyValueChangeOnBlur=true;break;}}},_onUserValueChange(){if(this._oldValue!==this._value){this._super(...arguments);}}});const MultiUserValueWidget=UserValueWidget.extend({tagName:'we-multi',start:function(){if(this.options&&this.options.childNodes){this.options.childNodes.forEach(node=>this.containerEl.appendChild(node));}
return this._super(...arguments);},getValue:function(methodName){const value=this._userValueWidgets.map(widget=>{return widget.getValue(methodName);}).join(' ').trim();return value||this._super(...arguments);},isContainer:function(){return true;},async setValue(value,methodName){let values=value.split(/\s*\|\s*/g);if(values.length===1){values=value.split(/\s+/g);}
for(let i=0;i<this._userValueWidgets.length-1;i++){await this._userValueWidgets[i].setValue(values.shift()||'',methodName);}
await this._userValueWidgets[this._userValueWidgets.length-1].setValue(values.join(' '),methodName);},});const ColorpickerUserValueWidget=SelectUserValueWidget.extend({className:(SelectUserValueWidget.prototype.className||'')+' o_we_so_color_palette',start:async function(){const _super=this._super.bind(this);const args=arguments;this.resetTabCount=0;this.colorPreviewEl=document.createElement('span');this.colorPreviewEl.classList.add('o_we_color_preview');this.colorPaletteEl=document.createElement('div');this.colorPaletteEl.classList.add('o_we_color_palette_wrapper');this.colorPaletteEl.style.display='contents';this.colorPaletteColorNames=[];this.options.childNodes=[this.colorPaletteEl];this.options.valueEl=this.colorPreviewEl;const wysiwyg=this.getParent().options.wysiwyg;if(wysiwyg){const colorpickerTemplate=await wysiwyg.getColorpickerTemplate.call(wysiwyg);this.colorPaletteColorNames=this._getColorNames(colorpickerTemplate);}
return _super(...args);},open:function(){if(this.colorPaletteWrapper){this.colorPaletteWrapper?.update({selectedCC:this._ccValue,selectedColor:this._value,resetTabCount:++this.resetTabCount,});this._super(...arguments);}else{this._colorPaletteRenderPromise=this._renderColorPalette();this._super(...arguments);this._colorPaletteRenderPromise.then(()=>{this._adjustDropdownPosition();});}},close:function(){this._super(...arguments);if(this._customColorValue&&this._customColorValue!==this._value){this._value=this._customColorValue;this._customColorValue=false;this._onUserValueChange();}},getMethodsParams:function(){return Object.assign(this._super(...arguments),{colorNames:this.colorPaletteColorNames,});},getValue:function(methodName){const isCCMethod=(this._methodsParams.withCombinations===methodName);let value=this._super(...arguments);if(isCCMethod){value=this._ccValue;}else if(typeof this._customColorValue==='string'){value=this._customColorValue;}
if(typeof this._previewColor==='string'){return isCCMethod?this._previewCC:this._previewColor;}
if(value){const useCssColor=this.options.dataAttributes.hasOwnProperty('useCssColor');const cssCompatible=this.options.dataAttributes.hasOwnProperty('cssCompatible');if((useCssColor||cssCompatible)&&!isCSSColor(value)){if(useCssColor){value=weUtils.getCSSVariableValue(value);}else{value=`var(--${value})`;}}}
return value;},isContainer:function(){return false;},isActive:function(){return!!this._ccValue||!weUtils.areCssValuesEqual(this._value,'rgba(0, 0, 0, 0)');},async setValue(color,methodName,...rest){const isCCMethod=(this._methodsParams.withCombinations===methodName);await this._super(isCCMethod?this._value:color,methodName,...rest);if(isCCMethod){this._ccValue=color;}
await this._colorPaletteRenderPromise;const classes=weUtils.computeColorClasses(this.colorPaletteColorNames);this.colorPreviewEl.classList.remove(...classes);this.colorPreviewEl.style.removeProperty('background-color');this.colorPreviewEl.style.removeProperty('background-image');const prefix=this.options.dataAttributes.colorPrefix||'bg';if(this._ccValue){this.colorPreviewEl.style.backgroundColor=`var(--we-cp-o-cc${this._ccValue}-${prefix.replace(/-/, '')})`;this.colorPreviewEl.style.backgroundImage=`var(--we-cp-o-cc${this._ccValue}-${prefix.replace(/-/, '')}-gradient)`;}
if(this._value){this.colorPreviewEl.style.backgroundImage='none';if(isCSSColor(this._value)){this.colorPreviewEl.style.backgroundColor=this._value;}else if(weUtils.isColorGradient(this._value)){this.colorPreviewEl.style.backgroundImage=this._value;}else if(weUtils.EDITOR_COLOR_CSS_VARIABLES.includes(this._value)){this.colorPreviewEl.style.backgroundColor=`var(--we-cp-${this._value}`;}else{const className=`bg-${this._value}`;if(classes.includes(className)){this.colorPreviewEl.classList.add(className);}}}
this.colorPaletteWrapper?.update({selectedCC:this._ccValue,selectedColor:this._value,});},_renderColorPalette:async function(){this.resetTabCount=0;const options={resetTabCount:this.resetTabCount,selectedCC:this._ccValue,selectedColor:this._value,getCustomColors:()=>{let result=[];this.trigger_up('get_custom_colors',{onSuccess:(colors)=>result=colors,});return result;},onCustomColorPicked:this._onCustomColorPicked.bind(this),onColorPicked:this._onColorPicked.bind(this),onColorHover:this._onColorHovered.bind(this),onColorLeave:this._onColorLeft.bind(this),onInputEnter:this._onEnterKey.bind(this),};if(this.options.dataAttributes.excluded){options.excluded=this.options.dataAttributes.excluded.replace(/ /g,'').split(',');}
if(this.options.dataAttributes.opacity){options.opacity=parseFloat(this.options.dataAttributes.opacity);}
if(this.options.dataAttributes.withCombinations){options.withCombinations=!!this.options.dataAttributes.withCombinations;}
if(this.options.dataAttributes.withGradients){options.withGradients=!!this.options.dataAttributes.withGradients;}
if(this.options.dataAttributes.noTransparency){options.noTransparency=!!this.options.dataAttributes.noTransparency;options.excluded=[...(options.excluded||[]),'transparent_grayscale'];}
if(this.options.dataAttributes.selectedTab){options.selectedTab=this.options.dataAttributes.selectedTab;}
const wysiwyg=this.getParent().options.wysiwyg;if(wysiwyg){options.document=this.$target[0].ownerDocument;options.getTemplate=wysiwyg.getColorpickerTemplate.bind(wysiwyg);options.getEditableCustomColors=wysiwyg.colorPalettesProps?.background?.getEditableCustomColors;}
this.colorPaletteWrapper?.destroy();const sidebarDocument=this.colorPaletteEl.ownerDocument;if(!(this.colorPaletteEl instanceof sidebarDocument.defaultView.HTMLElement)){const newEl=sidebarDocument.importNode(this.colorPaletteEl,true);this.colorPaletteEl.before(newEl);this.colorPaletteEl.remove();this.colorPaletteEl=newEl;}
this.colorPaletteWrapper=await attachComponent(this,this.colorPaletteEl,ColorPalette,options);},_shouldIgnoreClick(ev){return ev.originalEvent.__isColorpickerClick||this._super(...arguments);},_getColorNames(colorpickerTemplate){const colorNames=["1","2","3","4","5"];const template=new DOMParser().parseFromString(colorpickerTemplate,"text/html");template.querySelectorAll("button[data-color]:not(.o_custom_gradient_btn)").forEach(el=>{const colorName=el.dataset.color;if(!weUtils.isColorGradient(colorName)){colorNames.push(colorName);}});return colorNames;},_onCustomColorPicked:function(params){this._customColorValue=params.color;},_onColorPicked:function(params){this._previewCC=false;this._previewColor=false;this._customColorValue=false;this._ccValue=params.ccValue;this._value=params.color;this._onUserValueChange();},_onColorHovered:function(params){this._previewCC=params.ccValue;this._previewColor=params.color;this._onUserValuePreview();},_onColorLeft:function(){this._previewCC=false;this._previewColor=false;this._onUserValueReset();},_onEnterKey:function(){this.close();},});const MediapickerUserValueWidget=UserValueWidget.extend({tagName:'we-button',events:{'click':'_onEditMedia',},async start(){await this._super(...arguments);if(this.options.dataAttributes.buttonStyle){const iconEl=document.createElement('i');iconEl.classList.add('fa','fa-fw','fa-camera');$(this.containerEl).prepend(iconEl);}else{this.el.classList.add('o_we_no_toggle','o_we_bg_success');this.containerEl.textContent=_t("Replace");}},_openDialog(el,{images=false,videos=false,save}){el.src=this._value;const $editable=this.$target.closest('.o_editable');this.call("dialog","add",MediaDialog,{noImages:!images,noVideos:!videos,noIcons:true,noDocuments:true,isForBgVideo:true,vimeoPreviewIds:['528686125','430330731','509869821','397142251','763851966','486931161','499761556','1092009120','728584384','865314310','511727912','466830211'],'res_model':$editable.data('oe-model'),'res_id':$editable.data('oe-id'),save,media:el,});},async setValue(){await this._super(...arguments);this.el.classList.toggle('active',this.isActive());},_onEditMedia:function(ev){},});const ImagepickerUserValueWidget=MediapickerUserValueWidget.extend({_onEditMedia(ev){const dummyEl=document.createElement('img');this._openDialog(dummyEl,{images:true,save:(media)=>{this._value=media.getAttribute('src');this._onUserValueChange();}});},});const VideopickerUserValueWidget=MediapickerUserValueWidget.extend({_onEditMedia(ev){const dummyEl=document.createElement('iframe');this._openDialog(dummyEl,{videos:true,save:(media)=>{this._value=media.querySelector('iframe').src;this._onUserValueChange();}});},});const DatetimePickerUserValueWidget=InputUserValueWidget.extend({events:{'blur input':'_onInputBlur','input input':'_onDateInputInput',},pickerType:'datetime',init:function(){this._super(...arguments);this._value=DateTime.now().toUnixInteger().toString();},start:async function(){await this._super(...arguments);this.el.classList.add('o_we_large');this.inputEl.classList.add('datetimepicker-input','mx-0','text-start');this.picker=this.call("datetime_picker","create",{target:this.inputEl,onChange:this._onDateTimePickerChange.bind(this),pickerProps:{type:this.pickerType,minDate:DateTime.fromObject({year:1000}),maxDate:DateTime.now().plus({year:200}),value:DateTime.fromSeconds(parseInt(this._value)),rounding:0,},});this.picker.enable();},getMethodsParams:function(){return Object.assign(this._super(...arguments),{format:this.defaultFormat,});},isPreviewed:function(){return this._super(...arguments)||this.picker.isOpen;},async setValue(){await this._super(...arguments);let dateTime=null;if(this._value){dateTime=DateTime.fromSeconds(parseInt(this._value))
if(!dateTime.isValid){dateTime=DateTime.now();}}
this.picker.state.value=dateTime;},_onDateTimePickerChange:function(newDateTime){if(!newDateTime||!newDateTime.isValid){this._value='';}else{this._value=newDateTime.toUnixInteger().toString();}
this._onUserValuePreview();},_onDateInputInput(ev){if(!this.inputEl.value){this._value='';this._onUserValuePreview(ev);}},});const DatePickerUserValueWidget=DatetimePickerUserValueWidget.extend({pickerType:'date',});const ListUserValueWidget=UserValueWidget.extend({tagName:'we-list',events:{'click we-button.o_we_select_remove_option':'_onRemoveItemClick','click we-button.o_we_list_add_optional':'_onAddCustomItemClick','click we-button.o_we_list_add_existing':'_onAddExistingItemClick','click we-select.o_we_user_value_widget.o_we_add_list_item':'_onAddItemSelectClick','click we-button.o_we_checkbox_wrapper':'_onAddItemCheckboxClick','input table input':'_onListItemBlurInput','blur table input':'_onListItemBlurInput','mousedown':'_onWeListMousedown',},willStart(){if(this.options.createWidget){this.createWidget=this.options.createWidget;this.createWidget.setParent(this);this.registerSubWidget(this.createWidget);}
return this._super(...arguments);},start(){this.addItemTitle=this.el.dataset.addItemTitle||_t("Add");if(this.el.dataset.availableRecords){this.records=JSON.parse(this.el.dataset.availableRecords);}else{this.isCustom=!this.el.dataset.notEditable;}
if(this.el.dataset.defaults||this.el.dataset.hasDefault){this.hasDefault=this.el.dataset.hasDefault||'unique';this.selected=this.el.dataset.defaults?JSON.parse(this.el.dataset.defaults):[];}
this.listTable=document.createElement('table');const tableWrapper=document.createElement('div');tableWrapper.classList.add('o_we_table_wrapper');tableWrapper.appendChild(this.listTable);this.containerEl.appendChild(tableWrapper);this.el.classList.add('o_we_fw');this._makeListItemsSortable();if(this.createWidget){return this.createWidget.appendTo(this.containerEl);}},destroy(){this.bindedSortable?.cleanup();this._super(...arguments);},getMethodsParams(){return Object.assign(this._super(...arguments),{records:this.records,});},setValue(){this._super(...arguments);const currentValues=this._value?JSON.parse(this._value):[];this.listTable.innerHTML='';if(this.addItemButton){this.addItemButton.remove();}
if(this.createWidget){const selectedIds=currentValues.map(({id})=>id).filter(id=>typeof id==='number');this.createWidget.options.domainComponents.selected=selectedIds.length?['id','not in',selectedIds]:null;this.createWidget.setValue('');this.createWidget.inputEl.value='';$(this.createWidget.inputEl).trigger('input');}else{if(this.isCustom){this.addItemButton=document.createElement('we-button');this.addItemButton.textContent=this.addItemTitle;this.addItemButton.classList.add('o_we_list_add_optional');}else{this.addItemButton=document.createElement('we-select');this.addItemButton.classList.add('o_we_user_value_widget','o_we_add_list_item');const divEl=document.createElement('div');this.addItemButton.appendChild(divEl);const togglerEl=document.createElement('we-toggler');togglerEl.textContent=this.addItemTitle;divEl.appendChild(togglerEl);this.selectMenuEl=document.createElement('we-selection-items');divEl.appendChild(this.selectMenuEl);}
this.containerEl.appendChild(this.addItemButton);}
currentValues.forEach(value=>{if(typeof value==='object'){const recordData=value;const{id,display_name}=recordData;delete recordData.id;delete recordData.display_name;this._addItemToTable(id,display_name,recordData);}else{this._addItemToTable(value,value);}});if(!this.createWidget&&!this.isCustom){this._reloadSelectDropdown(currentValues);}
this._makeListItemsSortable();},getValue(methodName){if(this.createWidget&&this.createWidget.getMethodsNames().includes(methodName)){return this.createWidget.getValue(methodName);}
return this._value;},_addItemToTable(id,value=this.el.dataset.defaultValue||_t("Item"),recordData){const trEl=document.createElement('tr');if(!this.el.dataset.unsortable){const draggableEl=document.createElement('we-button');draggableEl.classList.add('o_we_drag_handle','o_we_link','fa','fa-fw','fa-arrows');draggableEl.dataset.noPreview='true';const draggableTdEl=document.createElement('td');draggableTdEl.appendChild(draggableEl);trEl.appendChild(draggableTdEl);}
let recordDataSelected=false;const inputEl=document.createElement('input');inputEl.type=this.el.dataset.inputType||'text';if(value){inputEl.value=value;}
if(id){inputEl.name=id;}
if(recordData){recordDataSelected=recordData.selected;if(recordData.placeholder){inputEl.placeholder=recordData.placeholder;}
for(const key of Object.keys(recordData)){inputEl.dataset[key]=recordData[key];}}
inputEl.disabled=!this.isCustom;const inputTdEl=document.createElement('td');inputTdEl.classList.add('o_we_list_record_name');inputTdEl.appendChild(inputEl);trEl.appendChild(inputTdEl);if(this.hasDefault){const checkboxEl=document.createElement('we-button');checkboxEl.classList.add('o_we_user_value_widget','o_we_checkbox_wrapper');if(this.selected.includes(id)||recordDataSelected){checkboxEl.classList.add('active');}
if(!recordData||!recordData.notToggleable){const div=document.createElement('div');const checkbox=document.createElement('we-checkbox');div.appendChild(checkbox);checkboxEl.appendChild(div);checkboxEl.appendChild(checkbox);const checkboxTdEl=document.createElement('td');checkboxTdEl.appendChild(checkboxEl);trEl.appendChild(checkboxTdEl);}}
if(!recordData||!recordData.undeletable){const buttonTdEl=document.createElement('td');const buttonEl=document.createElement('we-button');buttonEl.classList.add('o_we_select_remove_option','o_we_link','o_we_text_danger','fa','fa-fw','fa-minus');buttonEl.dataset.removeOption=id;buttonTdEl.appendChild(buttonEl);trEl.appendChild(buttonTdEl);}
this.listTable.appendChild(trEl);},_getFocusableElement(){return this.listTable.querySelector('input');},_makeListItemsSortable(){if(this.el.dataset.unsortable){return;}
this.bindedSortable=this.call("sortable","create",{ref:{el:this.listTable},elements:"tr",followingElementClasses:["opacity-50"],handle:".o_we_drag_handle",onDrop:()=>this._notifyCurrentState(),applyChangeOnDrop:true,},).enable();},_notifyCurrentState(preview=false){const isIdModeName=this.el.dataset.idMode==="name"||!this.isCustom;const trimmed=(str)=>str.trim().replace(/\s+/g," ");const values=[...this.listTable.querySelectorAll('.o_we_list_record_name input')].map(el=>{const id=trimmed(isIdModeName?el.name:el.value);return Object.assign({id:/^-?[0-9]{1,15}$/.test(id)?parseInt(id):id,name:trimmed(el.value),display_name:trimmed(el.value),},el.dataset);});if(this.hasDefault){const checkboxes=[...this.listTable.querySelectorAll('we-button.o_we_checkbox_wrapper.active')];this.selected=checkboxes.map(el=>{const input=el.parentElement.previousSibling.firstChild;const id=trimmed(isIdModeName?input.name:input.value);return/^-?[0-9]{1,15}$/.test(id)?parseInt(id):id;});values.forEach(v=>{v.selected=this.selected.includes(v.id)||v.notToggleable==='true';});}
this._value=JSON.stringify(values);if(preview){this._onUserValuePreview();}else{this._onUserValueChange();}
if(!this.createWidget&&!this.isCustom){this._reloadSelectDropdown(values);}},_reloadSelectDropdown(currentValues){this.selectMenuEl.innerHTML='';this.records.forEach(el=>{if(!currentValues.find(v=>v.id===el.id)){const option=document.createElement('we-button');option.classList.add('o_we_list_add_existing');option.dataset.addOption=el.id;option.dataset.noPreview='true';const divEl=document.createElement('div');divEl.textContent=el.display_name;option.appendChild(divEl);this.selectMenuEl.appendChild(option);}});if(!this.selectMenuEl.children.length){const title=document.createElement('we-title');title.textContent=_t("No more records");this.selectMenuEl.appendChild(title);}},_onAddCustomItemClick(){const recordData={};if(this.el.dataset.newElementsNotToggleable){recordData.notToggleable=true;}
this._addItemToTable(undefined,this.el.dataset.defaultValue,recordData);this._notifyCurrentState();this.el.querySelector('tr:last-child').scrollIntoView({behavior:'smooth',block:'nearest'});},_onAddExistingItemClick(ev){const value=ev.currentTarget.dataset.addOption;this._addItemToTable(value,ev.currentTarget.textContent);this._notifyCurrentState();},_onAddItemSelectClick(ev){ev.currentTarget.querySelector('we-toggler').classList.toggle('active');},_onAddItemCheckboxClick:function(ev){const isActive=ev.currentTarget.classList.contains('active');if(this.hasDefault==='unique'){this.listTable.querySelectorAll('we-button.o_we_checkbox_wrapper.active').forEach(el=>el.classList.remove('active'));}
ev.currentTarget.classList.toggle('active',!isActive);this._notifyCurrentState();},_onListItemBlurInput(ev){const preview=ev.type==='input';if(preview||!this.el.contains(ev.relatedTarget)||this.el.dataset.renderOnInputBlur){const timeSinceMousedown=ev.timeStamp-this.mousedownTime;if(timeSinceMousedown<500){setTimeout(()=>{this._notifyCurrentState(preview);},500);}else{this._notifyCurrentState(preview);}}},_onWeListMousedown(ev){this.mousedownTime=ev.timeStamp;},_onRemoveItemClick(ev){const minElements=this.el.dataset.allowEmpty?0:1;if(ev.target.closest('table').querySelectorAll('tr').length>minElements){ev.target.closest('tr').remove();this._notifyCurrentState();}},_onUserValueNotification(ev){const{widget,previewMode,prepare}=ev.data;if(widget&&widget===this.createWidget){if(widget.options.createMethod&&widget.getValue(widget.options.createMethod)){return this._super(ev);}
ev.stopPropagation();if(previewMode){return;}
prepare();const recordData=JSON.parse(widget.getMethodsParams('addRecord').recordData);const{id,display_name}=recordData;delete recordData.id;delete recordData.display_name;this._addItemToTable(id,display_name,recordData);this._notifyCurrentState();}
return this._super(ev);},});const RangeUserValueWidget=UnitUserValueWidget.extend({tagName:'we-range',events:{'change input':'_onInputChange','input input':'_onInputInput',},async start(){await this._super(...arguments);this.input=document.createElement('input');this.input.type="range";let min=this.el.dataset.min&&parseFloat(this.el.dataset.min)||0;let max=this.el.dataset.max&&parseFloat(this.el.dataset.max)||100;const step=this.el.dataset.step&&parseFloat(this.el.dataset.step)||1;this.displayValue=this.el.dataset.displayRangeValue;if(min>max){[min,max]=[max,min];this.input.classList.add('o_we_inverted_range');}
this._setInputAttributes(min,max,step);this.containerEl.appendChild(this.input);if(this.displayValue){this.outputEl=document.createElement('output');this.outputEl.classList.add('ms-2');this.containerEl.appendChild(this.outputEl);}
this._onInputChange=debounce(this._onInputChange,100);},loadMethodsData(validMethodNames){this._super(...arguments);for(const methodName of this._methodsNames){const possibleValues=this._methodsParams.optionsPossibleValues[methodName];if(possibleValues.length>1){this._setInputAttributes(0,possibleValues.length-1,1);break;}}},async setValue(value,methodName){await this._super(...arguments);const possibleValues=this._methodsParams.optionsPossibleValues[methodName];const inputValue=possibleValues.length>1?possibleValues.indexOf(value):this._value;this.input.value=inputValue;if(this.displayValue){this._computeDisplayValue(inputValue);}},getValue(methodName){const value=this._super(...arguments);const possibleValues=this._methodsParams.optionsPossibleValues[methodName];return possibleValues.length>1?possibleValues[+value]:value;},_onInputChange(ev){this._value=ev.target.value;this._onUserValueChange(ev);},_computeDisplayValue(inputValue){if(this.el.dataset.toRatio){const inputValueAsNumber=Number(inputValue);const ratio=inputValueAsNumber>=0?1+inputValueAsNumber:1/(1-inputValueAsNumber);this.outputEl.value=`${ratio.toFixed(2)}x`;}else if(this.el.dataset.displayRangeValueUnit){this.outputEl.value=inputValue+this.el.dataset.displayRangeValueUnit;}else{this.outputEl.value=inputValue;}},_onInputInput(ev){this._value=ev.target.value;if(this.displayValue){this._computeDisplayValue(this._value);}
this._onUserValuePreview(ev);},_setInputAttributes(min,max,step){this.input.setAttribute('min',min);this.input.setAttribute('max',max);this.input.setAttribute('step',step);},});const SelectPagerUserValueWidget=SelectUserValueWidget.extend({className:(SelectUserValueWidget.prototype.className||'')+' o_we_select_pager',events:Object.assign({},SelectUserValueWidget.prototype.events,{'click .o_pager_nav_btn':'_onClickScrollPage','click .o_pager_nav_angle':'_onClickCloseMenu',}),async start(){const _super=this._super.bind(this);await _super(...arguments);this.menuEl.classList.add('o_we_has_pager','position-fixed','top-0','end-0','z-1','rounded-0');this.menuTogglerEl.classList.add('o_we_toggler_pager');this.pagerContainerEl=this.el.querySelector('.o_pager_container');this.__onScroll=throttleForAnimation(this._onScroll.bind(this));this.pagerContainerEl.addEventListener('scroll',this.__onScroll);},destroy(){this._super(...arguments);this.pagerContainerEl.removeEventListener('scroll',this.__onScroll);},_adjustDropdownPosition(){return;},_shouldIgnoreClick(ev){return!!ev.target.closest('.o_pager_nav')||this._super(...arguments);},_onClickScrollPage(ev){const navButtonEl=ev.currentTarget;const attribute=navButtonEl.dataset.scrollTo;const destinationOffset=this.menuEl.querySelector('.'+attribute).offsetTop;const pagerNavEl=this.menuEl.querySelector('.o_pager_nav');this.pagerContainerEl.scrollTop=destinationOffset-pagerNavEl.offsetHeight;},_onClickCloseMenu(ev){this.close();},_onScroll(ev){const pagerContainerHeight=this.pagerContainerEl.getBoundingClientRect().height;const threshold=this.pagerContainerEl.scrollTop+(pagerContainerHeight/2);const anchorElements=this.menuEl.querySelectorAll('[data-scroll-to]');for(const anchorEl of anchorElements){const destination=anchorEl.getAttribute('data-scroll-to');const sectionEl=this.menuEl.querySelector(`.${destination}`);const nextSectionEl=sectionEl.nextElementSibling;anchorEl.classList.toggle('active',sectionEl.offsetTop<threshold&&(!nextSectionEl||nextSectionEl.offsetTop>threshold));}}});const Many2oneUserValueWidget=SelectUserValueWidget.extend({className:(SelectUserValueWidget.prototype.className||'')+' o_we_many2one',events:Object.assign({},SelectUserValueWidget.prototype.events,{'input .o_we_m2o_search input':'_onSearchInput','keydown .o_we_m2o_search input':'_onSearchKeydown','click .o_we_m2o_search_more':'_onSearchMoreClick',}),configAttributes:["model","fields","limit","domain","callWith","createMethod","filterInModel","filterInField","nullText","defaultMessage",],init(parent,title,options,$target){this.afterSearch=[];this.displayNameCache={};const{dataAttributes}=options;Object.assign(options,{limit:'5',fields:'[]',domain:'[]',callWith:'id',});this.configAttributes.forEach(attr=>{if(dataAttributes.hasOwnProperty(attr)){options[attr]=dataAttributes[attr];delete dataAttributes[attr];}});options.limit=parseInt(options.limit);options.fields=JSON.parse(options.fields);if(!options.fields.includes('display_name')){options.fields.push('display_name');}
options.domain=JSON.parse(options.domain);options.domainComponents={};options.nullText=$target[0].dataset.nullText||JSON.parse($target[0].dataset.oeContactOptions||'{}')['null_text'];this.orm=serviceCached(this.bindService("orm"));return this._super(...arguments);},async start(){await this._super(...arguments);this.inputEl=document.createElement('input');this.inputEl.setAttribute('placeholder',_t("Search for records..."));const searchEl=document.createElement('div');searchEl.classList.add('o_we_m2o_search');searchEl.appendChild(this.inputEl);this.menuEl.appendChild(searchEl);this.searchMore=document.createElement('div');this.searchMore.classList.add('o_we_m2o_search_more');this.searchMore.textContent=_t("Search more...");this.searchMore.title=_t("Search to show more records");if(this.options.createMethod){this.createInput=new InputUserValueWidget(this,undefined,{classes:['o_we_large'],dataAttributes:{noPreview:'true'},},this.$target);this.createButton=new ButtonUserValueWidget(this,undefined,{classes:['flex-grow-0'],dataAttributes:{noPreview:'true',[this.options.createMethod]:'',},childNodes:[document.createTextNode(_t("Create"))],},this.$target);this.createButton.isActive=()=>false;await Promise.all([this.createInput.appendTo(document.createDocumentFragment()),this.createButton.appendTo(document.createDocumentFragment()),]);this.registerSubWidget(this.createInput);this.registerSubWidget(this.createButton);this.createWidget=_buildRowElement('',{classes:['o_we_full_row','o_we_m2o_create','p-1'],childNodes:[this.createInput.el,this.createButton.el],});}
return this._search('');},async setValue(value,methodName){await this._super(...arguments);if(this.menuTogglerEl.textContent===this.PLACEHOLDER_TEXT.toString()){if(value!==''){this.menuTogglerEl.textContent=await this._getDisplayName(parseInt(value));}else{this.menuTogglerEl.textContent=this.options.defaultMessage||_t("Choose a record...");}}},getValue(methodName){if(methodName===this.options.createMethod&&this.createInput){return this.createInput._value;}
return this._super(...arguments);},isContainer(){return false;},open(){if(this.createInput){this.createInput.setValue('');}
return this._super(...arguments);},async setFilterInDomainIds(linkedRecordsIds){const allowedIds=new Set();if(linkedRecordsIds){const parentRecordsData=await this.orm.searchRead(this.options.filterInModel,[['id','in',linkedRecordsIds]],[this.options.filterInField]);parentRecordsData.forEach(record=>{record[this.options.filterInField].forEach(item=>allowedIds.add(item));});}
if(allowedIds.size){this.options.domainComponents.filterInModel=['id','in',[...allowedIds]];}},async _search(needle){const recTuples=await this.orm.call(this.options.model,"name_search",[],{name:needle,args:(await this._getSearchDomain()).concat(Object.values(this.options.domainComponents).filter(item=>item!==null)),operator:"ilike",limit:this.options.limit+1,});const records=await this.orm.read(this.options.model,recTuples.map(([id,_name])=>id),this.options.fields);this._userValueWidgets.filter(widget=>{return widget instanceof ButtonUserValueWidget&&!widget.isDestroyed()&&widget.el.parentElement.matches('we-selection-items');}).forEach(button=>{if(button.isPreviewed()){button.notifyValueChange('reset');}
button.destroy();});this._userValueWidgets=this._userValueWidgets.filter(widget=>!widget.isDestroyed());if(this.options.nullText&&this.options.nullText.toLowerCase().includes(needle.toLowerCase())){if(!records.length||records[0].id){records.unshift({id:0,name:this.options.nullText,display_name:this.options.nullText});}}
records.forEach(record=>{this.displayNameCache[record.id]=record.display_name;});await Promise.all(records.slice(0,this.options.limit).map(async record=>{const buttonDataAttributes=Object.assign({},this.options.dataAttributes);Object.keys(buttonDataAttributes).forEach(key=>{buttonDataAttributes[key]=buttonDataAttributes[key]||record[this.options.callWith];});const buttonWidget=new ButtonUserValueWidget(this,undefined,{dataAttributes:Object.assign({recordData:JSON.stringify(record)},buttonDataAttributes),childNodes:[document.createTextNode(record.display_name)],},this.$target);this.registerSubWidget(buttonWidget);await buttonWidget.appendTo(this.menuEl);if(this._methodsNames){buttonWidget.loadMethodsData(this._methodsNames);}}));if(this._methodsNames){this._methodsNames.forEach(methodName=>{this.setValue(this._value,methodName);});}
const hasMore=records.length>this.options.limit;if(hasMore){this.menuEl.appendChild(this.searchMore);this.searchMore.classList.remove('d-none');}else{this.searchMore.classList.add('d-none');}
if(this.createWidget){this.menuEl.appendChild(this.createWidget);}
this.waitingForSearch=false;this.afterSearch.forEach(cb=>cb());this.afterSearch=[];if(this.options.nullText&&!this.getValue()){this.setValue(0);}},async _getSearchDomain(){return this.options.domain;},async _getDisplayName(recordId){if(!this.displayNameCache.hasOwnProperty(recordId)){this.displayNameCache[recordId]=(await this.orm.read(this.options.model,[recordId],['display_name']))[0].display_name;}
return this.displayNameCache[recordId];},_onClick(ev){if(ev.target.closest('.o_we_m2o_search_more, .o_we_m2o_search, .o_we_m2o_create')&&!ev.target.closest('we-button')){ev.stopPropagation();return;}
return this._super(...arguments);},_onSearchInput(ev){clearTimeout(this.searchIntent);this.waitingForSearch=true;this.searchIntent=setTimeout(()=>{this._search(ev.target.value);},500);},_onSearchKeydown(ev){if(ev.key!=="Enter"){return;}
const action=()=>{const firstButton=this.menuEl.querySelector(':scope > we-button');if(firstButton){firstButton.click();}};if(this.waitingForSearch){this.afterSearch.push(action);}else{action();}},_onSearchMoreClick(ev){this.inputEl.focus();},_onUserValueNotification(ev){const{widget}=ev.data;if(widget&&widget===this.createInput){ev.stopPropagation();return;}
if(widget&&widget===this.createButton){this.createInput._value=this.createInput.el.querySelector('input').value;if(!this.createInput._value){ev.stopPropagation();}
return;}
if(widget!==this.createButton&&this.createInput){this.createInput._value='';}
return this._super(ev);},});const Many2manyUserValueWidget=UserValueWidget.extend({configAttributes:['model','recordId','m2oField','createMethod','fakem2m','filterIn'],init(parent,title,options,$target){const{dataAttributes}=options;this.configAttributes.forEach(attr=>{if(dataAttributes.hasOwnProperty(attr)){options[attr]=dataAttributes[attr];delete dataAttributes[attr];}});this.filterIn=options.filterIn!==undefined;if(this.filterIn){dataAttributes.filterInModel=options.model;dataAttributes.filterInField=options.m2oField;}
this.orm=this.bindService("orm");this.fields=this.bindService("field");return this._super(...arguments);},async willStart(){await this._super(...arguments);if(this.options.fakem2m){this.m2oModel=this.options.model;return;}
const{model,recordId,m2oField}=this.options;const[record]=await this.orm.read(model,[parseInt(recordId)],[m2oField]);const selectedRecordIds=record[m2oField];const modelData=await this.fields.loadFields(model,{fieldNames:[m2oField]});this.m2oModel=modelData[m2oField].relation;this.m2oName=modelData[m2oField].field_description;const selectedRecords=await this.orm.read(this.m2oModel,selectedRecordIds,['display_name']);this._value=JSON.stringify(selectedRecords);},async start(){this.el.classList.add('o_we_m2m');const m2oDataAttributes=Object.entries(this.options.dataAttributes).filter(([attrName])=>{return Many2oneUserValueWidget.prototype.configAttributes.includes(attrName);});m2oDataAttributes.push(['model',this.m2oModel],['addRecord',''],['createMethod',this.options.createMethod],);this.createWidget=new Many2oneUserValueWidget(null,undefined,{dataAttributes:Object.fromEntries(m2oDataAttributes),},this.$target);this.listWidget=registerUserValueWidget('we-list',this,undefined,{dataAttributes:{unsortable:'true',notEditable:'true',allowEmpty:'true'},createWidget:this.createWidget,},this.$target);await this.listWidget.appendTo(this.containerEl);this.listWidget.el.querySelector('we-select').style.position='static';this.el.style.position='relative';},async setFilterInDomainIds(linkedRecordsIds){if(this.filterIn){return this.listWidget.createWidget.setFilterInDomainIds(linkedRecordsIds);}},loadMethodsData(validMethodNames,...rest){this._super(['addRecord',...validMethodNames],...rest);this._methodsNames=this._methodsNames.filter(name=>name!=='addRecord');},setValue(value,methodName){if(methodName===this.options.createMethod){return this.createWidget.setValue(value,methodName);}
if(!value){value=this._value;}
this._super(value,methodName);this.listWidget.setValue(this._value);},getValue(methodName){return this.listWidget.getValue(methodName);},_onUserValueNotification(ev){const{widget,previewMode}=ev.data;if(!widget){return this._super(ev);}
if(widget===this.listWidget){ev.stopPropagation();this._value=widget._value;this.notifyValueChange(previewMode);}},});const userValueWidgetsRegistry={'we-button':ButtonUserValueWidget,'we-checkbox':CheckboxUserValueWidget,'we-select':SelectUserValueWidget,'we-button-group':ButtonGroupUserValueWidget,'we-input':InputUserValueWidget,'we-multi':MultiUserValueWidget,'we-colorpicker':ColorpickerUserValueWidget,'we-datetimepicker':DatetimePickerUserValueWidget,'we-datepicker':DatePickerUserValueWidget,'we-list':ListUserValueWidget,'we-imagepicker':ImagepickerUserValueWidget,'we-videopicker':VideopickerUserValueWidget,'we-range':RangeUserValueWidget,'we-select-pager':SelectPagerUserValueWidget,'we-many2one':Many2oneUserValueWidget,'we-many2many':Many2manyUserValueWidget,};const SnippetOptionWidget=publicWidget.Widget.extend({tagName:'we-customizeblock-option',events:{'click .o_we_collapse_toggler':'_onCollapseTogglerClick',},custom_events:{'user_value_update':'_onUserValueUpdate','user_value_widget_critical':'_onUserValueWidgetCritical',},isTopOption:false,isTopFirstOption:false,forceNoDeleteButton:false,displayOverlayOptions:false,forceDuplicateButton:false,init:function(parent,$uiElements,$target,$overlay,data,options){this._super.apply(this,arguments);this.$originalUIElements=$uiElements;this.$target=$target;this.$overlay=$overlay;this.data=data;this.options=options;this.className='snippet-option-'+this.data.optionName;this.ownerDocument=this.$target[0].ownerDocument;this._userValueWidgets=[];this._actionQueues=new Map();this.dialog=this.bindService("dialog");},willStart:async function(){await this._super(...arguments);return this._renderOriginalXML().then(uiFragment=>{this.uiFragment=uiFragment;});},renderElement:function(){this._super(...arguments);this.el.appendChild(this.uiFragment);this.uiFragment=null;},async onFocus(){},async onBuilt(options){},async onBlur(){},onClone:function(options){},onMove:function(){},onRemove:async function(){},onTargetShow:async function(){},onTargetHide:async function(){},cleanForSave:async function(){},cleanUI:async function(){},registerSubWidget(widget){this._userValueWidgets.push(widget);},selectClass:function(previewMode,widgetValue,params){for(const classNames of params.possibleValues){if(classNames){this.$target[0].classList.remove(...classNames.trim().split(/\s+/g));}}
if(widgetValue){this.$target[0].classList.add(...widgetValue.trim().split(/\s+/g));}},selectDataAttribute:function(previewMode,widgetValue,params){const value=this._selectAttributeHelper(widgetValue,params);this.$target[0].dataset[params.attributeName]=value;},selectAttribute:function(previewMode,widgetValue,params){const value=this._selectAttributeHelper(widgetValue,params);if(value){this.$target[0].setAttribute(params.attributeName,value);}else{this.$target[0].removeAttribute(params.attributeName);}},selectProperty:function(previewMode,widgetValue,params){if(!params.propertyName){throw new Error('Property name missing');}
const value=this._selectValueHelper(widgetValue,params);this.$target[0][params.propertyName]=value;},selectStyle:async function(previewMode,widgetValue,params){this.$target[0].classList.add('o_we_force_no_transition');const _restoreTransitions=()=>this.$target[0].classList.remove('o_we_force_no_transition');if(params.cssProperty==='background-color'){this.$target.trigger('background-color-event',previewMode);}
let cssProps=weUtils.CSS_SHORTHANDS[params.cssProperty]||[params.cssProperty];for(const cssProp of cssProps){this.$target[0].style.setProperty(cssProp,'');}
if(params.extraClass){this.$target.removeClass(params.extraClass);}
let bgImageParts=undefined;if(params.withGradients&&params.cssProperty==='background-color'){const styles=getComputedStyle(this.$target[0]);bgImageParts=backgroundImageCssToParts(styles['background-image']);delete bgImageParts.gradient;this.$target[0].style.setProperty('background-image','');if(!widgetValue||widgetValue==='false'){const styleBgImageParts=backgroundImageCssToParts(styles['background-image']);bgImageParts.gradient=styleBgImageParts.gradient;}
const combined=backgroundImagePartsToCss(bgImageParts);applyCSS.call(this,'background-image',combined,styles);}
if(params.colorNames&&params.colorPrefix){const colorNames=params.colorNames.filter(name=>!weUtils.isColorCombinationName(name));const classes=weUtils.computeColorClasses(colorNames,params.colorPrefix);this.$target[0].classList.remove(...classes);if(colorNames.includes(widgetValue)){const originalCSSValue=window.getComputedStyle(this.$target[0])[cssProps[0]];const className=params.colorPrefix+widgetValue;this.$target[0].classList.add(className);if(originalCSSValue!==window.getComputedStyle(this.$target[0])[cssProps[0]]){this.$target.addClass(params.extraClass);_restoreTransitions();return;}
this.$target[0].classList.remove(className);}}
const styles=window.getComputedStyle(this.$target[0]);const htmlPropValue=weUtils.getCSSVariableValue(widgetValue);if(htmlPropValue){widgetValue=`var(--${widgetValue})`;}
if(params.withGradients&&params.cssProperty==='background-color'&&weUtils.isColorGradient(widgetValue)){cssProps=['background-image'];bgImageParts.gradient=widgetValue;widgetValue=backgroundImagePartsToCss(bgImageParts);applyCSS.call(this,'background-color','rgba(0, 0, 0, 0)',styles);}
const values=widgetValue.replace(/,\s/g,',').split(/\s+/g);while(values.length<cssProps.length){switch(values.length){case 1:case 2:{values.push(values[0]);break;}
case 3:{values.push(values[1]);break;}
default:{values.push(values[values.length-1]);}}}
let hasUserValue=false;const applyAllCSS=(values)=>{for(let i=cssProps.length-1;i>0;i--){hasUserValue=applyCSS.call(this,cssProps[i],values.pop(),styles)||hasUserValue;}
hasUserValue=applyCSS.call(this,cssProps[0],values.join(' '),styles)||hasUserValue;}
applyAllCSS([...values]);function applyCSS(cssProp,cssValue,styles){if(typeof params.forceStyle!=='undefined'){this.$target[0].style.setProperty(cssProp,cssValue,params.forceStyle);return true;}
if(!weUtils.areCssValuesEqual(styles.getPropertyValue(cssProp),cssValue,cssProp,this.$target[0])){this.$target[0].style.setProperty(cssProp,cssValue);if(!params.preventImportant&&!weUtils.areCssValuesEqual(styles.getPropertyValue(cssProp),cssValue,cssProp,this.$target[0])){this.$target[0].style.setProperty(cssProp,cssValue,'important');}
return true;}
return false;}
if(params.extraClass){this.$target.toggleClass(params.extraClass,hasUserValue);if(hasUserValue){for(const cssProp of cssProps){this.$target[0].style.removeProperty(cssProp);}
applyAllCSS(values);}}
_restoreTransitions();},async selectColorCombination(previewMode,widgetValue,params){if(params.colorNames){const names=params.colorNames.filter(weUtils.isColorCombinationName);const classes=weUtils.computeColorClasses(names);this.$target[0].classList.remove(...classes);if(widgetValue){this.$target[0].classList.add('o_cc',`o_cc${widgetValue}`);}}},$:function(){return this.$target.find.apply(this.$target,arguments);},closeWidgets:function(){this._userValueWidgets.forEach(widget=>widget.close());},findWidget:function(name){for(const widget of this._userValueWidgets){if(widget.getName()===name){return widget;}
const depWidget=widget.findWidget(name);if(depWidget){return depWidget;}}
return null;},notify:function(name,data){if(name==='target'){this.setTarget(data);}},setTarget:function($target){this.$target=$target;},async updateUI({noVisibility,assetsChanged}={}){const proms=this._userValueWidgets.map(async widget=>{const methodsNames=widget.getMethodsNames();for(const methodName of methodsNames){const params=widget.getMethodsParams(methodName);let obj=this;if(params.applyTo){const $firstSubTarget=this.$(params.applyTo).eq(0);if(!$firstSubTarget.length){continue;}
obj=createPropertyProxy(this,'$target',$firstSubTarget);}
const value=await this._computeWidgetState.call(obj,methodName,params);if(value===undefined){continue;}
const normalizedValue=this._normalizeWidgetValue(value);await widget.setValue(normalizedValue,methodName);}});await Promise.all(proms);if(!noVisibility){await this.updateUIVisibility();}},updateUIVisibility:async function(){const proms=this._userValueWidgets.map(async widget=>{const params=widget.getMethodsParams();let obj=this;if(params.applyTo){const $firstSubTarget=this.$(params.applyTo).eq(0);if(!$firstSubTarget.length){widget.toggleVisibility(false);return;}
obj=createPropertyProxy(this,'$target',$firstSubTarget);}
const allSubWidgets=[widget];let i=0;while(i<allSubWidgets.length){allSubWidgets.push(...allSubWidgets[i]._userValueWidgets);i++;}
const proms=allSubWidgets.map(async widget=>{const show=await this._computeWidgetVisibility.call(obj,widget.getName(),params);if(!show){widget.toggleVisibility(false);return;}
const dependencies=widget.getDependencies();if(dependencies.length===1&&dependencies[0]==='fake'){widget.toggleVisibility(false);return;}
const dependenciesData=[];dependencies.forEach(depName=>{const toBeActive=(depName[0]!=='!');if(!toBeActive){depName=depName.substr(1);}
const widget=this._requestUserValueWidgets(depName,true)[0];if(widget){dependenciesData.push({widget:widget,toBeActive:toBeActive,});}});const dependenciesOK=!dependenciesData.length||dependenciesData.some(depData=>{return(depData.widget.isActive()===depData.toBeActive);});widget.toggleVisibility(dependenciesOK);});return Promise.all(proms);});const showUI=await this._computeVisibility();this.el.classList.toggle('d-none',!showUI);await Promise.all(proms);for(const el of this.$el.find('we-row')){const $userValueWidget=$(el).find('> div > .o_we_user_value_widget');el.classList.toggle('d-none',$userValueWidget.length&&!$userValueWidget.not('.d-none').length);}
for(const el of this.$el.find('we-collapse')){const $el=$(el);el.classList.toggle('d-none',$el.children().first().hasClass('d-none'));const hasNoVisibleElInCollapseMenu=!$el.children().last().children().not('.d-none').length;if(hasNoVisibleElInCollapseMenu){this._toggleCollapseEl(el,false);}
el.querySelector('.o_we_collapse_toggler').classList.toggle('d-none',hasNoVisibleElInCollapseMenu);}
return!this.displayOverlayOptions&&showUI;},async _checkIfWidgetsUpdateNeedWarning(widgets){const messages=[];for(const widget of widgets){const message=widget.getMethodsParams().warnMessage;if(message){messages.push(message);}}
return messages.join(' ');},async _checkIfWidgetsUpdateNeedReload(widgets){return false;},_computeVisibility:async function(){return true;},_computeWidgetState:async function(methodName,params){switch(methodName){case'selectClass':{let maxNbClasses=0;let activeClassNames='';for(const classNames of params.possibleValues){if(!classNames){continue;}
const classes=classNames.split(/\s+/g);if(params.stateToFirstClass){if(this.$target[0].classList.contains(classes[0])){return classNames;}else{continue;}}
if(classes.length>=maxNbClasses&&classes.every(className=>this.$target[0].classList.contains(className))){maxNbClasses=classes.length;activeClassNames=classNames;}}
return activeClassNames;}
case'selectAttribute':case'selectDataAttribute':{const attrName=params.attributeName;let attrValue;if(methodName==='selectAttribute'){attrValue=this.$target[0].getAttribute(attrName);}else if(methodName==='selectDataAttribute'){attrValue=this.$target[0].dataset[attrName];}
attrValue=(attrValue||'').trim();if(params.saveUnit&&!params.withUnit){attrValue=attrValue.split(/\s+/g).map(v=>v+params.saveUnit).join(' ');}
return attrValue||params.attributeDefaultValue||'';}
case'selectStyle':{let usedCC=undefined;if(params.colorPrefix&&params.colorNames){for(const c of params.colorNames){const className=weUtils.computeColorClasses([c],params.colorPrefix)[0];if(this.$target[0].classList.contains(className)){if(weUtils.isColorCombinationName(c)){usedCC=c;continue;}
return c;}}}
this.$target[0].classList.add('o_we_force_no_transition');const styles=window.getComputedStyle(this.$target[0]);const cssProps=weUtils.CSS_SHORTHANDS[params.cssProperty]||[params.cssProperty];const borderWidthCssProps=weUtils.CSS_SHORTHANDS['border-width'];const cssValues=cssProps.map(cssProp=>{let value=styles.getPropertyValue(cssProp).trim();if(cssProp==='box-shadow'){const inset=value.includes('inset');let values=value.replace(/,\s/g,',').replace('inset','').trim().split(/\s+/g);const color=values.find(s=>!s.match(/^\d/));values=values.join(' ').replace(color,'').trim();value=`${color} ${values}${inset ? ' inset' : ''}`;}
if(borderWidthCssProps.includes(cssProp)&&value.endsWith('px')){value=`${Math.ceil(parseFloat(value))}px`;}
return value;});if(cssValues.length===4&&weUtils.areCssValuesEqual(cssValues[3],cssValues[1],params.cssProperty,this.$target)){cssValues.pop();}
if(cssValues.length===3&&weUtils.areCssValuesEqual(cssValues[2],cssValues[0],params.cssProperty,this.$target)){cssValues.pop();}
if(cssValues.length===2&&weUtils.areCssValuesEqual(cssValues[1],cssValues[0],params.cssProperty,this.$target)){cssValues.pop();}
let value=cssValues.join(' ');if(params.withGradients&&params.cssProperty==='background-color'){const parts=backgroundImageCssToParts(styles['background-image']);if(parts.gradient){value=parts.gradient;}}
this.$target[0].classList.remove('o_we_force_no_transition');if(params.cssProperty==='background-color'&&params.withCombinations){if(usedCC){const ccValue=weUtils.getCSSVariableValue(`o-cc${usedCC}-bg-gradient`).trim().replaceAll("'",'')||weUtils.getCSSVariableValue(`o-cc${usedCC}-bg`).trim();if(weUtils.areCssValuesEqual(value,ccValue)){return'';}}else{const rgba=convertCSSColorToRgba(value);if(rgba&&rgba.opacity<0.001){return'';}}}
if(value==="currentColor"){return styles.color;}
return value;}
case'selectColorCombination':{if(params.colorNames){for(const c of params.colorNames){if(!weUtils.isColorCombinationName(c)){continue;}
const className=weUtils.computeColorClasses([c])[0];if(this.$target[0].classList.contains(className)){return c;}}}
return'';}}},_computeWidgetVisibility:async function(widgetName,params){return true;},_extraInfoFromDescriptionElement:function(el){return{title:el.getAttribute('string'),options:{classes:el.classList,dataAttributes:el.dataset,tooltip:el.title,placeholder:el.getAttribute('placeholder'),childNodes:[...el.childNodes],},};},_normalizeWidgetValue:function(value){value=`${value}`.trim();value=normalizeCSSColor(value);return value;},_renderCustomWidgets:function(uiFragment){return Promise.resolve();},_renderCustomXML:function(uiFragment){return Promise.resolve();},_renderOriginalXML:async function($xml){const uiFragment=document.createDocumentFragment();($xml||this.$originalUIElements).clone(true).appendTo(uiFragment);await this._renderCustomXML(uiFragment);for(const[itemName,build]of[['we-row',_buildRowElement],['we-collapse',_buildCollapseElement]]){uiFragment.querySelectorAll(itemName).forEach(el=>{const infos=this._extraInfoFromDescriptionElement(el);const groupEl=build(infos.title,infos.options);el.parentNode.insertBefore(groupEl,el);el.parentNode.removeChild(el);});}
await this._renderXMLWidgets(uiFragment);await this._renderCustomWidgets(uiFragment);if(this.isDestroyed()){return uiFragment;}
const validMethodNames=[];for(const key in this){validMethodNames.push(key);}
this._userValueWidgets.forEach(widget=>{widget.loadMethodsData(validMethodNames);});return uiFragment;},_renderXMLWidgets:function(parentEl,parentWidget){const proms=[...parentEl.children].map(el=>{const widgetName=el.tagName.toLowerCase();if(!userValueWidgetsRegistry.hasOwnProperty(widgetName)){return this._renderXMLWidgets(el,parentWidget);}
const infos=this._extraInfoFromDescriptionElement(el);const widget=registerUserValueWidget(widgetName,parentWidget||this,infos.title,infos.options,this.$target);return widget.insertAfter(el).then(()=>{parentEl.removeChild(el);if(widget.isContainer()&&!widget.isDestroyed()){return this._renderXMLWidgets(widget.el,widget);}});});return Promise.all(proms);},_requestUserValueWidgets:function(...args){const widgetNames=args;let allowParentOption=false;const lastArg=args[args.length-1];if(typeof lastArg==='boolean'){widgetNames.pop();allowParentOption=lastArg;}
const widgets=[];for(const widgetName of widgetNames){let widget=null;this.trigger_up('user_value_widget_request',{name:widgetName,onSuccess:_widget=>widget=_widget,allowParentOption:allowParentOption,});if(widget){widgets.push(widget);}}
return widgets;},_rerenderXML:async function(callback){this._userValueWidgets.forEach(widget=>widget.destroy());this._userValueWidgets=[];this.$el.empty();let $xml=undefined;if(callback){$xml=await callback.call(this);}
return this._renderOriginalXML($xml).then(uiFragment=>{this.$el.append(uiFragment);return this.updateUI();});},_select:async function(previewMode,widget){let $applyTo=null;if(previewMode===true){this.options.wysiwyg.odooEditor.automaticStepUnactive('preview_option');}
for(const methodName of widget.getMethodsNames()){const widgetValue=widget.getValue(methodName);const params=widget.getMethodsParams(methodName);if(params.applyTo){if(!$applyTo){$applyTo=this.$(params.applyTo);}
const proms=Array.from($applyTo).map((subTargetEl)=>{const proxy=createPropertyProxy(this,'$target',$(subTargetEl));return this[methodName].call(proxy,previewMode,widgetValue,params);});await Promise.all(proms);}else{await this[methodName](previewMode,widgetValue,params);}}
if(previewMode==='reset'||previewMode===false){this.options.wysiwyg.odooEditor.automaticStepActive('preview_option');}
($applyTo||this.$target).trigger('content_changed');},_selectAttributeHelper(value,params){if(!params.attributeName){throw new Error('Attribute name missing');}
return this._selectValueHelper(value,params);},_selectValueHelper(value,params){if(params.saveUnit&&!params.withUnit){value=value.split(params.saveUnit).join('');}
if(params.extraClass){this.$target.toggleClass(params.extraClass,params.defaultValue!==value);}
return value;},_toggleCollapseEl(collapseEl,show){collapseEl.classList.toggle('active',show);collapseEl.querySelector('we-toggler.o_we_collapse_toggler').classList.toggle('active',show);},_onCollapseTogglerClick(ev){const currentCollapseEl=ev.currentTarget.closest('we-collapse');this._toggleCollapseEl(currentCollapseEl);for(const collapseEl of currentCollapseEl.querySelectorAll('we-collapse')){this._toggleCollapseEl(collapseEl,false);}},_onUserValueUpdate:async function(ev){ev.stopPropagation();const widget=ev.data.widget;const previewMode=ev.data.previewMode;let requiresReload=false;if(!ev.data.previewMode&&!ev.data.isSimulatedEvent){const linkedWidgets=this._requestUserValueWidgets(...ev.data.triggerWidgetsNames);const widgets=[ev.data.widget].concat(linkedWidgets);const warnMessage=await this._checkIfWidgetsUpdateNeedWarning(widgets);if(warnMessage){const okWarning=await new Promise(resolve=>{this.dialog.add(ConfirmationDialog,{body:warnMessage,confirm:()=>resolve(true),cancel:()=>resolve(false),});});if(!okWarning){return;}}
requiresReload=!!await this._checkIfWidgetsUpdateNeedReload(widgets);}
if(!this._actionQueues.get(widget)){this._actionQueues.set(widget,[]);}
const currentAction={previewMode};this._actionQueues.get(widget).push(currentAction);const shouldRecordUndo=(!previewMode&&!ev.data.isSimulatedEvent);if(shouldRecordUndo){this.options.wysiwyg.odooEditor.unbreakableStepUnactive();}
const useLoaderOnOptionPanel=ev.target.el.dataset.loaderOnOptionPanel;this.trigger_up('snippet_edition_request',{exec:async()=>{if(this.isDestroyed()){return;}
const actionQueue=this._actionQueues.get(widget).filter(({previewMode},i,actions)=>{const prev=actions[i-1];const next=actions[i+1];if(previewMode===true&&next&&next.previewMode){return false;}else if(previewMode==='reset'&&prev&&prev.previewMode){return false;}
return true;});if(!actionQueue.includes(currentAction)){this._actionQueues.set(widget,actionQueue);return;}
this._actionQueues.set(widget,actionQueue.filter(action=>action!==currentAction));if(ev.data.prepare){ev.data.prepare();}
if(previewMode&&(widget.$el.closest('[data-no-preview="true"]').length)){return;}
await this._select(previewMode,widget);if(shouldRecordUndo){this.options.wysiwyg.odooEditor.historyStep();}
if(previewMode||requiresReload){return;}
await new Promise(resolve=>setTimeout(()=>{this.trigger_up('snippet_option_update',{onSuccess:()=>resolve(),});}));},optionsLoader:useLoaderOnOptionPanel});if(ev.data.isSimulatedEvent){return;}
const linkedWidgets=this._requestUserValueWidgets(...ev.data.triggerWidgetsNames);let i=0;const triggerWidgetsValues=ev.data.triggerWidgetsValues;for(const linkedWidget of linkedWidgets){const widgetValue=triggerWidgetsValues[i];if(widgetValue!==undefined){const normValue=this._normalizeWidgetValue(widgetValue);if(previewMode===true){linkedWidget._previewColor=normValue;}else if(previewMode===false){linkedWidget._previewColor=false;linkedWidget._value=normValue;}else{linkedWidget._previewColor=false;}}
linkedWidget.notifyValueChange(previewMode,true);i++;}
if(requiresReload){this.trigger_up('request_save',{reloadEditor:true,optionSelector:this.data.selector,url:this.data.reload,});}},_onUserValueWidgetCritical(){this.trigger_up('remove_snippet',{$snippet:this.$target,});},});const registry={};registry.sizing=SnippetOptionWidget.extend({displayOverlayOptions:true,start:function(){const self=this;const def=this._super.apply(this,arguments);let isMobile=weUtils.isMobileView(this.$target[0]);const isRtl=this.options.direction==="rtl";this.$handles=this.$overlay.find('.o_handle');let resizeValues=this._getSize();this.$handles.on('mousedown',function(ev){const mousedownTime=ev.timeStamp;ev.preventDefault();isMobile=weUtils.isMobileView(self.$target[0]);resizeValues=self._getSize();const $handle=$(ev.currentTarget);let compass=false;let XY=false;if($handle.hasClass('n')){compass='n';XY='Y';}else if($handle.hasClass('s')){compass='s';XY='Y';}else if($handle.hasClass('e')){compass='e';XY='X';}else if($handle.hasClass('w')){compass='w';XY='X';}else if($handle.hasClass('nw')){compass='nw';XY='YX';}else if($handle.hasClass('ne')){compass='ne';XY='YX';}else if($handle.hasClass('sw')){compass='sw';XY='YX';}else if($handle.hasClass('se')){compass='se';XY='YX';}
if(isRtl){if(compass.includes("e")){compass=compass.replace("e","w");}else if(compass.includes("w")){compass=compass.replace("w","e");}}
const isGrid=Object.keys(resizeValues).length===4;const isGridHandle=$handle[0].classList.contains('o_grid_handle');if(isGrid&&!isGridHandle||!isGrid&&isGridHandle){return;}
let resizeVal;if(compass.length>1){resizeVal=[resizeValues[compass[0]],resizeValues[compass[1]]];}else{resizeVal=[resizeValues[compass]];}
if(resizeVal.some(rV=>!rV)){return;}
let resizeResolve;const prom=new Promise(resolve=>resizeResolve=()=>resolve());self.trigger_up("snippet_edition_request",{exec:()=>{self.trigger_up("disable_loading_effect");return prom;}});const rowEl=self.$target[0].parentNode;let backgroundGridEl;if(rowEl.classList.contains("o_grid_mode")&&!isMobile){self.options.wysiwyg.odooEditor.observerUnactive('displayBackgroundGrid');backgroundGridEl=gridUtils._addBackgroundGrid(rowEl,0);gridUtils._setElementToMaxZindex(backgroundGridEl,rowEl);self.options.wysiwyg.odooEditor.observerActive('displayBackgroundGrid');}
const directions=[];for(const[i,resize]of resizeVal.entries()){const props={};let current=0;const cssProperty=resize[2];const cssPropertyValue=parseInt(self.$target.css(cssProperty));resize[0].forEach((val,key)=>{if(self.$target.hasClass(val)){current=key;}else if(parseInt(resize[1][key])===cssPropertyValue){current=key;}});props.resize=resize;props.current=current;props.begin=current;props.beginClass=self.$target.attr('class');props.regClass=new RegExp('\\s*'+resize[0][current].replace(/[-]*[0-9]+/,'[-]*[0-9]+'),'g');props.xy=ev['page'+XY[i]];props.XY=XY[i];props.compass=compass[i];directions.push(props);}
self.options.wysiwyg.odooEditor.automaticStepUnactive('resizing');const cursor=$handle.css('cursor')+'-important';const $iframeWindow=$(this.ownerDocument.defaultView);$iframeWindow[0].document.body.classList.add(cursor);self.$overlay.removeClass('o_handlers_idle');const iframeWindowMouseMove=function(ev){ev.preventDefault();let changeTotal=false;for(const dir of directions){let ddRaw=ev["page"+dir.XY]-dir.xy;if(dir.XY==="X"&&isRtl){ddRaw=-ddRaw;}
const dd=ddRaw+dir.resize[1][dir.begin];const next=dir.current+(dir.current+1===dir.resize[1].length?0:1);const prev=dir.current?(dir.current-1):0;let change=false;if(dd>(2*dir.resize[1][next]+dir.resize[1][dir.current])/3){self.$target.attr('class',(self.$target.attr('class')||'').replace(dir.regClass,''));self.$target.addClass(dir.resize[0][next]);dir.current=next;change=true;}
if(prev!==dir.current&&dd<(2*dir.resize[1][prev]+dir.resize[1][dir.current])/3){self.$target.attr('class',(self.$target.attr('class')||'').replace(dir.regClass,''));self.$target.addClass(dir.resize[0][prev]);dir.current=prev;change=true;}
if(change){self._onResize(dir.compass,dir.beginClass,dir.current);}
changeTotal=changeTotal||change;}
if(changeTotal){self.trigger_up('cover_update');$handle.addClass('o_active');}};const iframeWindowMouseUp=function(ev){$iframeWindow.off("mousemove",iframeWindowMouseMove);$iframeWindow.off("mouseup",iframeWindowMouseUp);$iframeWindow[0].document.body.classList.remove(cursor);self.$overlay.addClass('o_handlers_idle');$handle.removeClass('o_active');if(rowEl.classList.contains("o_grid_mode")&&!isMobile){self.options.wysiwyg.odooEditor.observerUnactive('displayBackgroundGrid');backgroundGridEl.remove();self.options.wysiwyg.odooEditor.observerActive('displayBackgroundGrid');gridUtils._resizeGrid(rowEl);const colClass=[...self.$target[0].classList].find(c=>/^col-/.test(c));const gColClass=[...self.$target[0].classList].find(c=>/^g-col-/.test(c));self.$target[0].classList.remove(colClass);self.$target[0].classList.add(gColClass.substring(2));}
self.options.wysiwyg.odooEditor.automaticStepActive('resizing');resizeResolve();self.trigger_up("enable_loading_effect");if(directions.every(dir=>dir.begin===dir.current)){const mouseupTime=ev.timeStamp;const mouseHeldDuration=mouseupTime-mousedownTime;if(mouseHeldDuration<500){const sameCoordinatesEls=self.ownerDocument.elementsFromPoint(ev.pageX,ev.pageY);const toBeClickedEl=sameCoordinatesEls.find(el=>!el.closest("#oe_manipulators")&&typeof el.click==="function");if(toBeClickedEl){toBeClickedEl.click();}}
return;}
setTimeout(function(){self.options.wysiwyg.odooEditor.historyStep();self.trigger_up("snippet_edition_request",{exec:async()=>{await new Promise(resolve=>{self.trigger_up("snippet_option_update",{onSuccess:()=>resolve()});});}});},0);};$iframeWindow.on("mousemove",iframeWindowMouseMove);$iframeWindow.on("mouseup",iframeWindowMouseUp);});for(const[key,value]of Object.entries(resizeValues)){this.$handles.filter('.'+key).toggleClass('readonly',!value);}
if(!isMobile&&this.$target[0].classList.contains("o_grid_item")){this.$handles.filter('.o_grid_handle').toggleClass('readonly',false);}
return def;},async updateUI(){this._updateSizingHandles();return this._super(...arguments);},setTarget:function(){this._super(...arguments);this._onResize();},async updateUIVisibility(){await this._super(...arguments);const isMobileView=weUtils.isMobileView(this.$target[0]);const isGridOn=this.$target[0].classList.contains("o_grid_item");const isGrid=!isMobileView&&isGridOn;if(this.$target[0].parentNode&&this.$target[0].parentNode.classList.contains('row')){for(const handleEl of this.$handles){const isGridHandle=handleEl.classList.contains('o_grid_handle');handleEl.classList.toggle('d-none',isGrid^isGridHandle);const isVerticalSizing=handleEl.matches('.n, .s');handleEl.classList.toggle("readonly",isMobileView&&isVerticalSizing&&isGridOn);}
const moveHandleEl=this.$overlay[0].querySelector('.o_move_handle');moveHandleEl.classList.toggle('d-none',isMobileView);const bringFrontBackEls=this.$overlay[0].querySelectorAll('.o_front_back');bringFrontBackEls.forEach(button=>button.classList.toggle("d-none",!isGrid));}},_getSize:function(){},_onResize:function(compass,beginClass,current){this._updateSizingHandles();this._notifyResizeChange();},_updateSizingHandles:function(){var self=this;var resizeValues=this._getSize();var $handles=this.$overlay.find('.o_handle');for(const[direction,resizeValue]of Object.entries(resizeValues)){var classes=resizeValue[0];var values=resizeValue[1];var cssProperty=resizeValue[2];var $handle=$handles.filter('.'+direction);var current=0;var cssPropertyValue=parseInt(self.$target.css(cssProperty));classes.forEach((className,key)=>{if(self.$target.hasClass(className)){current=key;}else if(values[key]===cssPropertyValue){current=key;}});$handle.toggleClass('o_handle_start',current===0);$handle.toggleClass('o_handle_end',current===classes.length-1);}
this.$overlay.find('.o_handle:not(.o_grid_handle)').filter(".n, .s").toArray().forEach(handle=>{var $handle=$(handle);var direction=$handle.hasClass('n')?'top':'bottom';$handle.outerHeight(self.$target.css('padding-'+direction));});},async _notifyResizeChange(){this.$target.trigger('content_changed');},});registry['sizing_y']=registry.sizing.extend({_getSize:function(){var nClass='pt';var nProp='padding-top';var sClass='pb';var sProp='padding-bottom';if(this.$target.is('hr')){nClass='mt';nProp='margin-top';sClass='mb';sProp='margin-bottom';}
var grid=[];for(var i=0;i<=(256/8);i++){grid.push(i*8);}
grid.splice(1,0,4);this.grid={n:[grid.map(v=>nClass+v),grid,nProp],s:[grid.map(v=>sClass+v),grid,sProp],};return this.grid;},});registry['sizing_x']=registry.sizing.extend({onClone:function(options){this._super.apply(this,arguments);if(options.isCurrent){const targetClassList=this.$target[0].classList;const offsetClasses=[...targetClassList].filter(cls=>cls.match(/^offset-(lg-)?([0-9]{1,2})$/));targetClassList.remove(...offsetClasses);}},_getSize:function(){const isMobileView=weUtils.isMobileView(this.$target[0]);const resolutionModifier=isMobileView?"":"lg-";var width=this.$target.closest('.row').width();var gridE=[1,2,3,4,5,6,7,8,9,10,11,12];var gridW=[0,1,2,3,4,5,6,7,8,9,10,11];this.grid={e:[gridE.map(v=>(`col-${resolutionModifier}${v}`)),gridE.map(v=>width/12*v),"width",],w:[gridW.map(v=>(`offset-${resolutionModifier}${v}`)),gridW.map(v=>width/12*v),"margin-left",],};return this.grid;},_onResize:function(compass,beginClass,current){const targetEl=this.$target[0];const isMobileView=weUtils.isMobileView(targetEl);const resolutionModifier=isMobileView?"":"lg-";if(compass==='w'||compass==='e'){const offsetRegex=new RegExp(`(?:^|\\s+)offset-${resolutionModifier}(\\d{1,2})(?!\\S)`);const colRegex=new RegExp(`(?:^|\\s+)col-${resolutionModifier}(\\d{1,2})(?!\\S)`);const beginOffset=Number(beginClass.match(offsetRegex)?.[1]||0);if(compass==='w'){const beginCol=Number(beginClass.match(colRegex)?.[1]||12);let offset=Number(this.grid.w[0][current].match(offsetRegex)?.[1]||0);if(offset<0){offset=0;}
let colSize=beginCol-(offset-beginOffset);if(colSize<=0){colSize=1;offset=beginOffset+beginCol-1;}
const offsetColRegex=new RegExp(`${offsetRegex.source}|${colRegex.source}`,"g");targetEl.className=targetEl.className.replace(offsetColRegex,"");targetEl.classList.add(`col-${resolutionModifier}${colSize > 12 ? 12 : colSize}`);if(offset>0){targetEl.classList.add(`offset-${resolutionModifier}${offset}`);}
if(isMobileView&&offset===0){targetEl.classList.remove("offset-lg-0");}else if((isMobileView&&offset>0&&!targetEl.className.match(/(^|\s+)offset-lg-\d{1,2}(?!\S)/))||(!isMobileView&&offset===0&&targetEl.className.match(/(^|\s+)offset-\d{1,2}(?!\S)/))){targetEl.classList.add("offset-lg-0");}}else if(beginOffset>0){const endCol=Number(this.grid.e[0][current].match(colRegex)?.[1]||0);if((endCol+beginOffset)>12){targetEl.className=targetEl.className.replace(colRegex,"");targetEl.classList.add(`col-${resolutionModifier}${12 - beginOffset}`);}}}
this._super.apply(this,arguments);},async _notifyResizeChange(){this.trigger_up('option_update',{optionName:'StepsConnector',name:'change_column_size',});this._super.apply(this,arguments);},});registry['sizing_grid']=registry.sizing.extend({_getSize(){const rowEl=this.$target.closest('.row')[0];const gridProp=gridUtils._getGridProperties(rowEl);const rowStart=this.$target[0].style.gridRowStart;const rowEnd=parseInt(this.$target[0].style.gridRowEnd);const columnStart=this.$target[0].style.gridColumnStart;const columnEnd=this.$target[0].style.gridColumnEnd;const gridN=[];const gridS=[];for(let i=1;i<rowEnd+12;i++){gridN.push(i);gridS.push(i+1);}
const gridW=[1,2,3,4,5,6,7,8,9,10,11,12];const gridE=[2,3,4,5,6,7,8,9,10,11,12,13];this.grid={n:[gridN.map(v=>('g-height-'+(rowEnd-v))),gridN.map(v=>((gridProp.rowSize+gridProp.rowGap)*(v-1))),'grid-row-start'],s:[gridS.map(v=>('g-height-'+(v-rowStart))),gridS.map(v=>((gridProp.rowSize+gridProp.rowGap)*(v-1))),'grid-row-end'],w:[gridW.map(v=>('g-col-lg-'+(columnEnd-v))),gridW.map(v=>((gridProp.columnSize+gridProp.columnGap)*(v-1))),'grid-column-start'],e:[gridE.map(v=>('g-col-lg-'+(v-columnStart))),gridE.map(v=>((gridProp.columnSize+gridProp.columnGap)*(v-1))),'grid-column-end'],};return this.grid;},_onResize(compass,beginClass,current){if(compass==='n'){const rowEnd=parseInt(this.$target[0].style.gridRowEnd);if(current<0){this.$target[0].style.gridRowStart=1;}else if(current+1>=rowEnd){this.$target[0].style.gridRowStart=rowEnd-1;}else{this.$target[0].style.gridRowStart=current+1;}}else if(compass==='s'){const rowStart=parseInt(this.$target[0].style.gridRowStart);const rowEnd=parseInt(this.$target[0].style.gridRowEnd);if(current+2<=rowStart){this.$target[0].style.gridRowEnd=rowStart+1;}else{this.$target[0].style.gridRowEnd=current+2;}
const rowEl=this.$target[0].parentNode;const rowCount=parseInt(rowEl.dataset.rowCount);const backgroundGridEl=rowEl.querySelector('.o_we_background_grid');const backgroundGridRowEnd=parseInt(backgroundGridEl.style.gridRowEnd);let rowMove=0;if(this.$target[0].style.gridRowEnd>rowEnd&&this.$target[0].style.gridRowEnd>rowCount+1){rowMove=this.$target[0].style.gridRowEnd-rowEnd;}else if(this.$target[0].style.gridRowEnd<rowEnd&&this.$target[0].style.gridRowEnd>=rowCount+1){rowMove=this.$target[0].style.gridRowEnd-rowEnd;}
backgroundGridEl.style.gridRowEnd=backgroundGridRowEnd+rowMove;}else if(compass==='w'){const columnEnd=parseInt(this.$target[0].style.gridColumnEnd);if(current<0){this.$target[0].style.gridColumnStart=1;}else if(current+1>=columnEnd){this.$target[0].style.gridColumnStart=columnEnd-1;}else{this.$target[0].style.gridColumnStart=current+1;}}else if(compass==='e'){const columnStart=parseInt(this.$target[0].style.gridColumnStart);if(current+2>13){this.$target[0].style.gridColumnEnd=13;}else if(current+2<=columnStart){this.$target[0].style.gridColumnEnd=columnStart+1;}else{this.$target[0].style.gridColumnEnd=current+2;}}
if(compass==='n'||compass==='s'){const numberRows=this.$target[0].style.gridRowEnd-this.$target[0].style.gridRowStart;this.$target.attr('class',this.$target.attr('class').replace(/\s*(g-height-)([0-9-]+)/g,''));this.$target.addClass('g-height-'+numberRows);}
if(compass==='w'||compass==='e'){const numberColumns=this.$target[0].style.gridColumnEnd-this.$target[0].style.gridColumnStart;this.$target.attr('class',this.$target.attr('class').replace(/\s*(g-col-lg-)([0-9-]+)/g,''));this.$target.addClass('g-col-lg-'+numberColumns);}},});registry.Box=SnippetOptionWidget.extend({async setShadow(previewMode,widgetValue,params){const styles=window.getComputedStyle(this.$target[0]);const currentBoxShadow=styles['box-shadow']||'none';const currentMode=currentBoxShadow==='none'?'':currentBoxShadow.includes('inset')?'inset':'outset';if(currentMode===widgetValue){return;}
if(previewMode===true){this._prevBoxShadow=currentBoxShadow;}
this.$target.toggleClass(params.shadowClass,!!widgetValue);let shadow='none';if(previewMode==='reset'){shadow=this._prevBoxShadow;}else{if(currentBoxShadow==='none'){shadow=this._getDefaultShadow(widgetValue,params.shadowClass);}else{if(widgetValue==='outset'){shadow=currentBoxShadow.replace('inset','').trim();}else if(widgetValue==='inset'){shadow=currentBoxShadow+' inset';}}}
await this.selectStyle(previewMode,shadow,Object.assign({cssProperty:'box-shadow'},params));},_computeWidgetState(methodName,params){if(methodName==='setShadow'){const shadowValue=this.$target.css('box-shadow');if(!shadowValue||shadowValue==='none'){return'';}
return this.$target.css('box-shadow').includes('inset')?'inset':'outset';}
return this._super(...arguments);},async _computeWidgetVisibility(widgetName,params){if(widgetName==='fake_inset_shadow_opt'){return false;}
return this._super(...arguments);},_getDefaultShadow(type,shadowClass){if(!type){return'none';}
const el=document.createElement('div');el.classList.add(shadowClass);document.body.appendChild(el);const shadow=`${$(el).css('box-shadow')}${type === 'inset' ? ' inset' : ''}`;el.remove();return shadow;},});registry.layout_column=SnippetOptionWidget.extend(ColumnLayoutMixin,{cleanUI(){this._removeGridPreview();},selectCount:async function(previewMode,widgetValue,params){if(widgetValue==="custom"){return;}
const previousNbColumns=this.$('> .row').children().length;let $row=this.$('> .row');if(!$row.length){const restoreCursor=preserveCursor(this.$target[0].ownerDocument);resetOuids(this.$target[0]);$row=this.$target.contents().wrapAll($('<div class="row"><div class="col-lg-12"/></div>')).parent().parent();restoreCursor();}
const nbColumns=parseInt(widgetValue);await this._updateColumnCount($row[0],(nbColumns||1));await new Promise(resolve=>setTimeout(resolve));if(nbColumns===0){const restoreCursor=preserveCursor(this.$target[0].ownerDocument);resetOuids($row[0]);$row.contents().unwrap().contents().unwrap();restoreCursor();this.trigger_up('activate_snippet',{$snippet:this.$target});}else if(previousNbColumns===0){this.trigger_up('activate_snippet',{$snippet:this.$('> .row').children().first()});}
this.trigger_up('option_update',{optionName:'StepsConnector',name:'change_columns',});},async selectLayout(previewMode,widgetValue,params){if(widgetValue==="grid"){const rowEl=this.$target[0].querySelector('.row');if(!rowEl||!rowEl.classList.contains('o_grid_mode')){gridUtils._toggleGridMode(this.$target[0]);this.trigger_up('activate_snippet',{$snippet:this.$target});}}else{const rowEl=this.$target[0].querySelector('.row');if(rowEl&&rowEl.classList.contains('o_grid_mode')){this._toggleNormalMode(rowEl);this.trigger_up('activate_snippet',{$snippet:this.$target});}}
this.trigger_up('option_update',{optionName:'StepsConnector',name:'change_columns',});},async addElement(previewMode,widgetValue,params){const rowEl=this.$target[0].querySelector('.row');const elementType=widgetValue;const currentTime=new Date().getTime();if(this.lastAddTime&&(currentTime-this.lastAddTime)/1000<15){this.lastStartPosition=[this.lastStartPosition[0]+1,this.lastStartPosition[1]+1];}else{this.lastStartPosition=[1,1];}
this.lastAddTime=currentTime;const newColumnEl=document.createElement('div');newColumnEl.classList.add('o_grid_item');let numberColumns,numberRows;let imageLoadedPromise;if(elementType==='image'){newColumnEl.classList.add('col-lg-6','g-col-lg-6','g-height-6','o_grid_item_image');numberColumns=6;numberRows=6;let isImageSaved=false;await new Promise(resolve=>{this.call("dialog","add",MediaDialog,{onlyImages:true,save:imageEl=>{isImageSaved=true;imageLoadedPromise=new Promise(resolve=>{imageEl.addEventListener("load",()=>resolve(),{once:true});});newColumnEl.appendChild(imageEl);},},{onClose:()=>resolve()});});if(!isImageSaved){this.options.wysiwyg.odooEditor.historyRevertCurrentStep();return;}}else if(elementType==='text'){newColumnEl.classList.add('col-lg-4','g-col-lg-4','g-height-2');numberColumns=4;numberRows=2;const pEl=document.createElement('p');pEl.classList.add('o_default_snippet_text');pEl.textContent=_t("Write something...");newColumnEl.appendChild(pEl);}else if(elementType==='button'){newColumnEl.classList.add('col-lg-2','g-col-lg-2','g-height-1');numberColumns=2;numberRows=1;const aEl=document.createElement('a');aEl.href='#';aEl.classList.add('mb-2','btn','btn-primary');aEl.textContent="Button";newColumnEl.appendChild(aEl);}
const rowStart=this.lastStartPosition[0];let columnStart=this.lastStartPosition[1];if(columnStart+numberColumns>13){columnStart=1;this.lastStartPosition[1]=columnStart;}
newColumnEl.style.gridArea=`${rowStart} / ${columnStart} / ${rowStart + numberRows} / ${columnStart + numberColumns}`;gridUtils._setElementToMaxZindex(newColumnEl,rowEl);rowEl.appendChild(newColumnEl);gridUtils._resizeGrid(rowEl);if(elementType==="image"){await imageLoadedPromise;}
const newColumnPosition=newColumnEl.getBoundingClientRect();const middleX=(newColumnPosition.left+newColumnPosition.right)/2;const middleY=(newColumnPosition.top+newColumnPosition.bottom)/2;const sameCoordinatesEl=this.ownerDocument.elementFromPoint(middleX,middleY);if(!sameCoordinatesEl||!newColumnEl.contains(sameCoordinatesEl)){newColumnEl.scrollIntoView({behavior:"smooth",block:"center"});}
this.trigger_up('activate_snippet',{$snippet:$(newColumnEl)});},async selectStyle(previewMode,widgetValue,params){await this._super(previewMode,widgetValue,params);const rowEl=this.$target[0];const isMobileView=weUtils.isMobileView(rowEl);if(["row-gap","column-gap"].includes(params.cssProperty)&&!isMobileView){this._removeGridPreview();void rowEl.offsetWidth;this.options.wysiwyg.odooEditor.observerUnactive("addGridPreview");this.gridPreviewEl=gridUtils._addBackgroundGrid(rowEl,0);this.gridPreviewEl.classList.add("o_we_grid_preview");gridUtils._setElementToMaxZindex(this.gridPreviewEl,rowEl);this.options.wysiwyg.odooEditor.observerActive("addGridPreview");this.removeGridPreview=this._removeGridPreview.bind(this);rowEl.addEventListener("animationend",this.removeGridPreview);}},_computeWidgetState:function(methodName,params){if(methodName==='selectCount'){const isMobile=this._isMobile();const columnEls=this.$target[0].querySelector(":scope > .row")?.children;return this._getNbColumns(columnEls,isMobile);}else if(methodName==='selectLayout'){const rowEl=this.$target[0].querySelector('.row');if(rowEl&&rowEl.classList.contains('o_grid_mode')){return"grid";}else{return'normal';}}
return this._super(...arguments);},_computeWidgetVisibility(widgetName,params){if(widgetName==='zero_cols_opt'){return this.$target.is('.s_allow_columns');}else if(widgetName==="column_count_opt"){return!this.$target[0].querySelector(":scope > .row.s_nb_column_fixed");}else if(widgetName==="custom_cols_opt"){const isMobile=this._isMobile();return this.$target[0].querySelector(":scope > .row")&&this._areColsCustomized(this.$target[0].querySelector(":scope > .row").children,isMobile);}
return this._super(...arguments);},async _updateColumnCount(rowEl,nbColumns){const isMobile=this._isMobile();const prevNbColumns=this._getNbColumns(rowEl.children,isMobile);if(nbColumns===prevNbColumns){return;}
this._resizeColumns(rowEl.children,nbColumns);const itemsDelta=nbColumns-rowEl.children.length;if(itemsDelta>0){const newItems=[];for(let i=0;i<itemsDelta;i++){const lastEl=rowEl.lastElementChild;newItems.push(new Promise(resolve=>{this.trigger_up("clone_snippet",{$snippet:$(lastEl),onSuccess:resolve});}));}
await Promise.all(newItems);}
this.trigger_up('cover_update');},_resizeColumns(columnEls,nbColumns){const isMobile=this._isMobile();const itemSize=Math.floor(12/nbColumns)||1;const firstItem=this._getFirstItem(columnEls,isMobile);const firstItemOffset=Math.floor((12-itemSize*nbColumns)/2);const resolutionModifier=isMobile?"":"-lg";const replacingRegex=new RegExp(`(?:^|\\s+)(col|offset)${resolutionModifier}(-\\d{1,2})?(?!\\S)`,"g");for(const columnEl of columnEls){columnEl.className=columnEl.className.replace(replacingRegex,"");columnEl.classList.add(`col${resolutionModifier}-${itemSize}`);if(firstItemOffset&&columnEl===firstItem){columnEl.classList.add(`offset${resolutionModifier}-${firstItemOffset}`);}
const hasMobileOffset=columnEl.className.match(/(^|\s+)offset-\d{1,2}(?!\S)/);const hasDesktopOffset=columnEl.className.match(/(^|\s+)offset-lg-[1-9][0-1]?(?!\S)/);columnEl.classList.toggle("offset-lg-0",hasMobileOffset&&!hasDesktopOffset);}},async _toggleNormalMode(rowEl){rowEl.classList.remove('o_grid_mode');const columnEls=rowEl.children;await new Promise(resolve=>{this.trigger_up("clean_ui_request",{targetEl:this.$target[0].closest("section"),onSuccess:resolve,});});for(const columnEl of columnEls){gridUtils._reloadLazyImages(columnEl);gridUtils._convertToNormalColumn(columnEl);}
delete rowEl.dataset.rowCount;rowEl.style.removeProperty('--grid-item-padding-x');rowEl.style.removeProperty('--grid-item-padding-y');rowEl.style.removeProperty("gap");},_removeGridPreview(){this.options.wysiwyg.odooEditor.observerUnactive("removeGridPreview");this.$target[0].removeEventListener("animationend",this.removeGridPreview);if(this.gridPreviewEl){this.gridPreviewEl.remove();delete this.gridPreviewEl;}
delete this.removeGridPreview;this.options.wysiwyg.odooEditor.observerActive("removeGridPreview");},_isMobile(){return weUtils.isMobileView(this.$target[0]);},});registry.GridColumns=SnippetOptionWidget.extend({cleanUI(){this._removePaddingPreview();},async selectStyle(previewMode,widgetValue,params){await this._super(...arguments);if(["--grid-item-padding-y","--grid-item-padding-x"].includes(params.cssProperty)){this._removePaddingPreview();void this.$target[0].offsetWidth;this.options.wysiwyg.odooEditor.observerUnactive("addPaddingPreview");this.$target[0].classList.add("o_we_padding_highlight");this.options.wysiwyg.odooEditor.observerActive("addPaddingPreview");this.removePaddingPreview=this._removePaddingPreview.bind(this);this.$target[0].addEventListener("animationend",this.removePaddingPreview);}},_computeWidgetVisibility(widgetName,params){if(["grid_padding_y_opt","grid_padding_x_opt"].includes(widgetName)){return this.$target[0].parentElement.classList.contains("o_grid_mode");}
return this._super(...arguments);},_removePaddingPreview(){this.options.wysiwyg.odooEditor.observerUnactive("removePaddingPreview");this.$target[0].removeEventListener("animationend",this.removePaddingPreview);this.$target[0].classList.remove("o_we_padding_highlight");delete this.removePaddingPreview;this.options.wysiwyg.odooEditor.observerActive("removePaddingPreview");},});registry.vAlignment=SnippetOptionWidget.extend({async _computeWidgetState(methodName,params){const value=await this._super(...arguments);if(methodName==='selectClass'&&!value){return'align-items-stretch';}
return value;},});registry.SnippetMove=SnippetOptionWidget.extend(ColumnLayoutMixin,{displayOverlayOptions:true,start:function(){var $buttons=this.$el.find('we-button');var $overlayArea=this.$overlay.find('.o_overlay_move_options');$overlayArea.prepend($buttons[1]);$overlayArea.prepend($buttons[0]);const parentEl=this.$target[0].parentElement;if(parentEl.classList.contains("row")){const columnEls=[...parentEl.children];const orderedColumnEls=columnEls.filter(el=>el.style.order);if(orderedColumnEls.length&&orderedColumnEls.length!==columnEls.length){this._removeMobileOrders(orderedColumnEls);}}
return this._super(...arguments);},onClone(options){this._super.apply(this,arguments);const mobileOrder=this.$target[0].style.order;if(options.isCurrent&&mobileOrder){const siblingEls=this.$target[0].parentElement.children;const cloneEls=[...siblingEls].filter(el=>el.style.order===mobileOrder);cloneEls.forEach((el,i)=>{if(i>0){el.style.order=siblingEls.length-cloneEls.length+i;}});}},onMove(){this._super.apply(this,arguments);this._removeMobileOrders(this.$target[0].parentElement.children);},onRemove(){this._super.apply(this,arguments);const targetMobileOrder=this.$target[0].style.order;if(targetMobileOrder){const targetOrder=parseInt(targetMobileOrder);this._fillRemovedItemGap(this.$target[0].parentElement,targetOrder);}},moveSnippet:function(previewMode,widgetValue,params){const isMobile=this._isMobile();const isNavItem=this.$target[0].classList.contains('nav-item');const $tabPane=isNavItem?$(this.$target.find('.nav-link')[0].hash):null;const moveLeftOrRight=["move_left_opt","move_right_opt"].includes(params.name);let siblingEls,mobileOrder;if(moveLeftOrRight){siblingEls=this.$target[0].parentElement.children;mobileOrder=!!this.$target[0].style.order;}
if(moveLeftOrRight&&isMobile&&!isNavItem){if(!mobileOrder){this._addMobileOrders(siblingEls);}
this._swapMobileOrders(widgetValue,siblingEls);}else{switch(widgetValue){case"prev":{let prevEl=this.$target[0].previousElementSibling;while(prevEl&&window.getComputedStyle(prevEl).display==="none"){prevEl=prevEl.previousElementSibling;}
prevEl?.insertAdjacentElement("beforebegin",this.$target[0]);if(isNavItem){$tabPane.prev().before($tabPane);}
break;}
case"next":{let nextEl=this.$target[0].nextElementSibling;while(nextEl&&window.getComputedStyle(nextEl).display==="none"){nextEl=nextEl.nextElementSibling;}
nextEl?.insertAdjacentElement("afterend",this.$target[0]);if(isNavItem){$tabPane.next().after($tabPane);}
break;}}
if(mobileOrder){this._removeMobileOrders(siblingEls);}}
if(!this.$target.is(this.data.noScroll)&&(params.name==='move_up_opt'||params.name==='move_down_opt')){const mainScrollingEl=$().getScrollingElement()[0];const elTop=this.$target[0].getBoundingClientRect().top;const heightDiff=mainScrollingEl.offsetHeight-this.$target[0].offsetHeight;const bottomHidden=heightDiff<elTop;const hidden=elTop<0||bottomHidden;if(hidden){scrollTo(this.$target[0],{extraOffset:50,forcedOffset:bottomHidden?heightDiff-50:undefined,duration:500,});}}
this.trigger_up('option_update',{optionName:'StepsConnector',name:'move_snippet',});this.trigger_up("update_invisible_dom");},async _computeWidgetVisibility(widgetName,params){const moveUpOrLeft=widgetName==="move_up_opt"||widgetName==="move_left_opt";const moveDownOrRight=widgetName==="move_down_opt"||widgetName==="move_right_opt";const moveLeftOrRight=widgetName==="move_left_opt"||widgetName==="move_right_opt";if(moveUpOrLeft||moveDownOrRight){const isMobileView=weUtils.isMobileView(this.$target[0]);if(!isMobileView&&this.$target[0].classList.contains("o_grid_item")){return false;}
if(moveLeftOrRight&&isMobileView){const targetMobileOrder=this.$target[0].style.order;if(targetMobileOrder){const siblingEls=this.$target[0].parentElement.children;const orderModifier=widgetName==="move_left_opt"?-1:1;let delta=0;while(true){delta+=orderModifier;const nextOrder=parseInt(targetMobileOrder)+delta;const siblingEl=[...siblingEls].find(el=>el.style.order===nextOrder.toString());if(!siblingEl){break;}
if(window.getComputedStyle(siblingEl).display==="none"){continue;}
return true;}
return false;}}
const direction=moveUpOrLeft?"previousElementSibling":"nextElementSibling";let siblingEl=this.$target[0][direction];while(siblingEl&&window.getComputedStyle(siblingEl).display==="none"){siblingEl=siblingEl[direction];}
return!!siblingEl;}
return this._super(...arguments);},_swapMobileOrders(widgetValue,siblingEls){const targetMobileOrder=this.$target[0].style.order;const orderModifier=widgetValue==="prev"?-1:1;let delta=0;while(true){delta+=orderModifier;const newOrder=parseInt(targetMobileOrder)+delta;const comparedEl=[...siblingEls].find(el=>el.style.order===newOrder.toString());if(window.getComputedStyle(comparedEl).display==="none"){continue;}
this.$target[0].style.order=newOrder;comparedEl.style.order=targetMobileOrder;break;}},_isMobile(){return false;},});registry.ReplaceMedia=SnippetOptionWidget.extend({init:function(){this._super(...arguments);this._activateLinkTool=this._activateLinkTool.bind(this);this._deactivateLinkTool=this._deactivateLinkTool.bind(this);},destroy:function(){this._clearListeners();return this._super(...arguments);},onFocus(){this.options.wysiwyg.odooEditor.addEventListener('activate_image_link_tool',this._activateLinkTool);this.options.wysiwyg.odooEditor.addEventListener('deactivate_image_link_tool',this._deactivateLinkTool);this.rerender=true;},onBlur(){this._clearListeners();},async replaceMedia(){const sel=this.ownerDocument.getSelection();if(!sel.rangeCount){const range=this.ownerDocument.createRange();range.selectNodeContents(this.$target[0]);sel.addRange(range);}
await this.options.wysiwyg.openMediaDialog({node:this.$target[0]});},setLink(previewMode,widgetValue,params){const parentEl=this._searchSupportedParentLinkEl();if(parentEl.tagName!=='A'){const wrapperEl=document.createElement('a');this.$target[0].after(wrapperEl);wrapperEl.appendChild(this.$target[0]);if(this.$target[0].getBoundingClientRect().width===0){const src=this.$target[0].src;this.$target[0].src='';this.$target[0].src=src;}}else{const fragment=document.createDocumentFragment();fragment.append(...parentEl.childNodes);parentEl.replaceWith(fragment);}},setNewWindow(previewMode,widgetValue,params){const linkEl=this._searchSupportedParentLinkEl();if(widgetValue){linkEl.setAttribute('target','_blank');}else{linkEl.removeAttribute('target');}},setUrl(previewMode,widgetValue,params){const linkEl=this._searchSupportedParentLinkEl();let url=widgetValue;if(!url){linkEl.removeAttribute('href');this.$target.trigger('href_changed');return;}
if(!url.startsWith('/')&&!url.startsWith('#')&&!/^([a-zA-Z]*.):.+$/gm.test(url)){url='http://'+url;}
linkEl.setAttribute('href',url);this.rerender=true;this.$target.trigger('href_changed');},async updateUI(){if(this.rerender){this.rerender=false;await this._rerenderXML();return;}
return this._super.apply(this,arguments);},_activateLinkTool(){const parentEl=this._searchSupportedParentLinkEl();if(parentEl.tagName==='A'){this._requestUserValueWidgets('media_url_opt')[0].focus();}else{this._requestUserValueWidgets('media_link_opt')[0].enable();}},_clearListeners(){this.options.wysiwyg.odooEditor.removeEventListener('activate_image_link_tool',this._activateLinkTool);this.options.wysiwyg.odooEditor.removeEventListener('deactivate_image_link_tool',this._deactivateLinkTool);},_deactivateLinkTool(){const parentEl=this._searchSupportedParentLinkEl();if(parentEl.tagName==='A'){this._requestUserValueWidgets('media_link_opt')[0].enable();}},_computeWidgetState(methodName,params){const parentEl=this._searchSupportedParentLinkEl();const linkEl=parentEl.tagName==='A'?parentEl:null;switch(methodName){case'setLink':{return linkEl?'true':'';}
case'setUrl':{let href=linkEl?linkEl.getAttribute('href'):'';return href||'';}
case'setNewWindow':{const target=linkEl?linkEl.getAttribute('target'):'';return target&&target==='_blank'?'true':'';}}
return this._super(...arguments);},async _computeWidgetVisibility(widgetName,params){if(widgetName==='media_link_opt'){if(this.$target[0].matches('img')){return isImageSupportedForStyle(this.$target[0])&&!this._searchSupportedParentLinkEl().matches("a[data-oe-xpath]");}
return!this.$target[0].classList.contains('media_iframe_video');}
return this._super(...arguments);},_searchSupportedParentLinkEl(){const parentEl=this.$target[0].parentElement;return parentEl.matches("figure")?parentEl.parentElement:parentEl;},});const ImageHandlerOption=SnippetOptionWidget.extend({async willStart(){const _super=this._super.bind(this);await this._initializeImage();return _super(...arguments);},async start(){await this._super(...arguments);const weightEl=document.createElement('span');weightEl.classList.add('o_we_image_weight','o_we_tag','d-none');weightEl.title=_t("Size");this.$weight=$(weightEl);await this._applyOptions(false);this._updateFilterAvailability();},async updateUI(){await this._super(...arguments);if(this._filesize===undefined){this.$weight.addClass('d-none');await this._applyOptions(false);}
if(this._filesize!==undefined){this.$weight.text(`${this._filesize.toFixed(1)} kb`);this.$weight.removeClass('d-none');this._relocateWeightEl();}
this._updateFilterAvailability();},selectFormat(previewMode,widgetValue,params){const values=widgetValue.split(' ');const image=this._getImg();image.dataset.resizeWidth=values[0];if(image.dataset.shape){image.dataset.originalMimetype=values[1];}else{image.dataset.mimetype=values[1];}
return this._applyOptions();},async setQuality(previewMode,widgetValue,params){if(previewMode){return;}
this._getImg().dataset.quality=widgetValue;return this._applyOptions();},glFilter(previewMode,widgetValue,params){const dataset=this._getImg().dataset;if(widgetValue){dataset.glFilter=widgetValue;}else{delete dataset.glFilter;}
return this._applyOptions();},customFilter(previewMode,widgetValue,params){const img=this._getImg();const{filterOptions}=img.dataset;const{filterProperty}=params;if(filterProperty==='filterColor'){widgetValue=normalizeColor(widgetValue);}
const newOptions=Object.assign(JSON.parse(filterOptions||"{}"),{[filterProperty]:widgetValue});img.dataset.filterOptions=JSON.stringify(newOptions);return this._applyOptions();},_computeVisibility(){const src=this._getImg().getAttribute('src');return src&&src!=='/';},async _computeWidgetState(methodName,params){const img=this._getImg();const _super=this._super.bind(this);await new Promise((resolve,reject)=>{if(img.complete){resolve();return;}
img.addEventListener('load',resolve,{once:true});img.addEventListener('error',resolve,{once:true});});switch(methodName){case'selectFormat':return img.naturalWidth+' '+this._getImageMimetype(img);case'setFilter':return img.dataset.filter;case'glFilter':return img.dataset.glFilter||"";case'setQuality':return img.dataset.quality||75;case'customFilter':{const{filterProperty}=params;const options=JSON.parse(img.dataset.filterOptions||"{}");const defaultValue=filterProperty==='blend'?'normal':0;return options[filterProperty]||defaultValue;}}
return _super(...arguments);},_relocateWeightEl(){},async _renderCustomXML(uiFragment){const img=this._getImg();if(!this.originalSrc||!this._isImageSupportedForProcessing(img)){return;}
const $select=$(uiFragment).find('we-select[data-name=format_select_opt]');(await this._computeAvailableFormats()).forEach(([value,[label,targetFormat]])=>{$select.append(`<we-button data-select-format="${Math.round(value)} ${targetFormat}" class="o_we_badge_at_end">${label} <span class="badge rounded-pill text-bg-dark">${targetFormat.split('/')[1]}</span></we-button>`);});const optQuality=uiFragment.querySelector('we-range[data-set-quality]');optQuality.setAttribute('data-name','quality_range_opt');},_updateFilterAvailability(){if(!this.el){return;}
let filterWidgetEl=this.el.querySelector('we-select[data-name="glfilter_select_opt"]');if(!filterWidgetEl){return;}
const tooltipTargetEl=filterWidgetEl.querySelector("we-toggler");if(!isWebGLEnabled()){filterWidgetEl.dataset.disabled="true";filterWidgetEl.setAttribute("aria-disabled","true");tooltipTargetEl.setAttribute("title",_t("WebGL is not enabled on your browser."));}else{delete filterWidgetEl.dataset.disabled;filterWidgetEl.removeAttribute("aria-disabled");tooltipTargetEl.removeAttribute("title");}},async _computeAvailableFormats(){if(!this.mimetypeBeforeConversion){return[];}
const img=this._getImg();const original=await loadImage(this.originalSrc);const maxWidth=img.dataset.width?img.naturalWidth:original.naturalWidth;const optimizedWidth=Math.min(maxWidth,this._computeMaxDisplayWidth());this.optimizedWidth=optimizedWidth;const widths={128:['128px','image/webp'],256:['256px','image/webp'],512:['512px','image/webp'],1024:['1024px','image/webp'],1920:['1920px','image/webp'],};widths[img.naturalWidth]=[_t("%spx",img.naturalWidth),'image/webp'];widths[optimizedWidth]=[_t("%spx (Suggested)",optimizedWidth),'image/webp'];const mimetypeBeforeConversion=img.dataset.mimetypeBeforeConversion;widths[maxWidth]=[_t("%spx (Original)",maxWidth),mimetypeBeforeConversion];if(mimetypeBeforeConversion!=="image/webp"){widths[maxWidth-0.1]=[_t("%spx",maxWidth),'image/webp'];}
return Object.entries(widths).filter(([width])=>width<=maxWidth).sort(([v1],[v2])=>v1-v2);},async _applyOptions(update=true){const img=this._getImg();if(!update&&!(img&&img.complete)){return;}
if(!this._isImageSupportedForProcessing(img)){this.originalId=null;this._filesize=undefined;return;}
if(!img.dataset.originalSrc){delete img.dataset.mimetype;return;}
const dataURL=await applyModifications(img,{mimetype:this._getImageMimetype(img)});this._filesize=getDataURLBinarySize(dataURL)/1024;if(update){img.classList.add('o_modified_image_to_save');const loadedImg=await loadImage(dataURL,img);this._applyImage(loadedImg);weUtils.forwardToThumbnail(img);return loadedImg;}
return img;},async _loadImageInfo(attachmentSrc=''){const img=this._getImg();await loadImageInfo(img,attachmentSrc);if(!img.dataset.originalId){this.originalId=null;this.originalSrc=null;return;}
this.originalId=img.dataset.originalId;this.originalSrc=img.dataset.originalSrc;this.mimetypeBeforeConversion=img.dataset.mimetypeBeforeConversion;},async _autoOptimizeImage(){await this._loadImageInfo();await this._rerenderXML();const img=this._getImg();if(!['image/gif','image/svg+xml'].includes(img.dataset.mimetype)){img.dataset.mimetype='image/webp';img.dataset.resizeWidth=this.optimizedWidth;}else if(img.dataset.shape&&img.dataset.originalMimetype!=="image/gif"){img.dataset.originalMimetype="image/webp";img.dataset.resizeWidth=this.optimizedWidth;}
await this._applyOptions();await this.updateUI();},_getImg(){},_computeMaxDisplayWidth(){},_applyImage(img){},_getImageMimetype(img){return img.dataset.mimetype;},async _initializeImage(){return this._loadImageInfo();},_isImageSupportedForProcessing(img,strict=false){return isImageSupportedForProcessing(this._getImageMimetype(img),strict);},_computeWidgetVisibility(widgetName,params){if(widgetName==="format_select_opt"&&!this.mimetypeBeforeConversion){return false;}
if(this._isImageProcessingWidget(widgetName,params)){const img=this._getImg();return this._isImageSupportedForProcessing(img,true);}
return isImageSupportedForStyle(this._getImg());},_isImageProcessingWidget(widgetName,params){return params.optionsPossibleValues.glFilter||'customFilter'in params.optionsPossibleValues||params.optionsPossibleValues.setQuality||widgetName==='format_select_opt';},});const _addAnimatedShapeLabel=function addAnimatedShapeLabel(containerEl,labelIsDimension=false){const labelEl=document.createElement('span');labelEl.classList.add('o_we_shape_animated_label');let labelStr=_t("Animated");const spanEl=document.createElement('span');if(labelIsDimension){const dimensionIcon=document.createElement('i');labelStr=containerEl.dataset.imgSize;dimensionIcon.classList.add('fa','fa-expand');labelEl.append(dimensionIcon);spanEl.textContent=labelStr;}else{labelEl.textContent=labelStr[0];spanEl.textContent=labelStr.substr(1);}
labelEl.appendChild(spanEl);containerEl.classList.add('position-relative');containerEl.appendChild(labelEl);return labelEl;};registry.ImageTools=ImageHandlerOption.extend({MAX_SUGGESTED_WIDTH:1920,init(){this.shapeCache={};return this._super(...arguments);},start(){this.$target.on('image_changed.ImageOptimization',this._onImageChanged.bind(this));this.$target.on('image_cropped.ImageOptimization',this._onImageCropped.bind(this));return this._super(...arguments);},destroy(){this.$target.off('.ImageOptimization');return this._super(...arguments);},async removeStretch(previewMode,widgetValue,params){this.options.wysiwyg.odooEditor.historyPauseSteps();this.trigger_up("disable_loading_effect");const restoreCursor=preserveCursor(this.$target[0].ownerDocument);const img=this._getImg();const document=this.el.ownerDocument;const imageCropWrapperElement=document.createElement("div");imageCropWrapperElement.classList.add("d-none");document.body.append(imageCropWrapperElement);const imageCropWrapper=await attachComponent(this,imageCropWrapperElement,ImageCrop,{activeOnStart:true,media:img,mimetype:this._getImageMimetype(img),});await imageCropWrapper.component.mountedPromise;if(widgetValue){await imageCropWrapper.component.reset();}else{await imageCropWrapper.component.cropSquare(false);if(isGif(this._getImageMimetype(img))){img.dataset[img.dataset.shape?"originalMimetype":"mimetype"]="image/png";}}
await this._reapplyCurrentShape();imageCropWrapper.destroy();imageCropWrapperElement.remove();restoreCursor();this.trigger_up("enable_loading_effect");if(!widgetValue){await this._onImageCropped();}
this.options.wysiwyg.odooEditor.historyUnpauseSteps();},async crop(){this.trigger_up('disable_loading_effect');const img=this._getImg();const document=this.$el[0].ownerDocument;const imageCropWrapperElement=document.createElement('div');document.body.append(imageCropWrapperElement);const cropperPromise=new Promise(resolve=>{this.$target.one("image_cropper_destroyed",async()=>{if(isGif(this._getImageMimetype(img))){img.dataset[img.dataset.shape?"originalMimetype":"mimetype"]="image/png";}
await this._reapplyCurrentShape();resolve();});});const imageCropWrapper=await attachComponent(this,imageCropWrapperElement,ImageCrop,{activeOnStart:true,media:img,mimetype:this._getImageMimetype(img),});await cropperPromise;imageCropWrapperElement.remove();imageCropWrapper.destroy();this.trigger_up('enable_loading_effect');},async transform(){this.trigger_up('hide_overlay');this.trigger_up('disable_loading_effect');const document=this.$target[0].ownerDocument;const playState=this.$target[0].style.animationPlayState;const transition=this.$target[0].style.transition;this.$target.transfo({document});const destroyTransfo=()=>{this.$target.transfo('destroy');$(document).off('mousedown',mousedown);window.document.removeEventListener('keydown',keydown);}
const mousedown=mousedownEvent=>{if(!$(mousedownEvent.target).closest('.transfo-container').length){destroyTransfo();this.$target[0].style.animationPlayState=playState;this.$target[0].style.transition=transition;}};$(document).on('mousedown',mousedown);const keydown=keydownEvent=>{if(keydownEvent.key==='Escape'){keydownEvent.stopImmediatePropagation();destroyTransfo();}};window.document.addEventListener('keydown',keydown);await new Promise(resolve=>{document.addEventListener('mouseup',resolve,{once:true});});this.trigger_up('enable_loading_effect');},async resetCrop(){const img=this._getImg();const imageCropWrapperElement=document.createElement('div');imageCropWrapperElement.classList.add("d-none");document.body.append(imageCropWrapperElement);const imageCropWrapper=await attachComponent(this,imageCropWrapperElement,ImageCrop,{activeOnStart:true,media:img,mimetype:this._getImageMimetype(img),});await imageCropWrapper.component.mountedPromise;await imageCropWrapper.component.reset();imageCropWrapper.destroy();imageCropWrapperElement.remove();await this._reapplyCurrentShape();},async resetTransform(){this.$target.attr('style',(this.$target.attr('style')||'').replace(/[^;]*transform[\w:]*;?/g,''));},async setImgShape(previewMode,widgetValue,params){this.trigger_up("disable_loading_effect");const img=this._getImg();let clonedImgEl;const isCropRequired=params.unstretch;if((isCropRequired&&img.dataset.isManualCrop!=="true"&&img.dataset.aspectRatio!=="1/1"&&previewMode!=="reset")||this.hasCroppedPreview){const restoreCursor=preserveCursor(this.$target[0].ownerDocument);clonedImgEl=img.cloneNode(true);img.insertAdjacentElement("afterend",clonedImgEl);img.classList.add("d-none");const document=this.el.ownerDocument;const imageCropWrapperElement=document.createElement("div");imageCropWrapperElement.classList.add("d-none");document.body.append(imageCropWrapperElement);const imageCropWrapper=await attachComponent(this,imageCropWrapperElement,ImageCrop,{activeOnStart:true,media:img,mimetype:this._getImageMimetype(img),});await imageCropWrapper.component.mountedPromise;await imageCropWrapper.component.cropSquare(previewMode);if(previewMode===false){if(isGif(this._getImageMimetype(img))){img.dataset[img.dataset.shape?"originalMimetype":"mimetype"]="image/png";}
this.isImageCropped=true;}
await this._reapplyCurrentShape();imageCropWrapper.destroy();imageCropWrapperElement.remove();restoreCursor();if(previewMode===true){this.hasCroppedPreview=true;}else{delete this.hasCroppedPreview;}}
if(this.isImageCropped&&previewMode==="reset"){delete this.isImageCropped;await this._onImageCropped();}
const saveData=previewMode===false;if(img.dataset.hoverEffect&&!widgetValue){const shapeImgSquareWidget=this._requestUserValueWidgets("shape_img_square_opt")[0];widgetValue=shapeImgSquareWidget.getActiveValue("setImgShape");}
if(widgetValue){await this._loadShape(widgetValue);if(previewMode==='reset'&&img.dataset.shapeColors){await this._applyShapeAndColors(false,img.dataset.shapeColors.split(';'));}else{await this._applyShapeAndColors(saveData);if(saveData&&img.dataset.mimetype!=='image/svg+xml'){img.dataset.originalMimetype=img.dataset.mimetype;img.dataset.mimetype='image/svg+xml';}
if(saveData){if(!this._isTransformableShape()){delete img.dataset.shapeFlip;delete img.dataset.shapeRotate;}
if(!this._canHaveHoverEffect()){delete img.dataset.hoverEffect;delete img.dataset.hoverEffectColor;delete img.dataset.hoverEffectStrokeWidth;delete img.dataset.hoverEffectIntensity;img.classList.remove("o_animate_on_hover");}
if(!this._isAnimatedShape()){delete img.dataset.shapeAnimationSpeed;}}}}else{img.src=await applyModifications(img,{mimetype:this._getImageMimetype(img)});delete img.dataset.shape;delete img.dataset.shapeColors;delete img.dataset.fileName;delete img.dataset.shapeFlip;delete img.dataset.shapeRotate;delete img.dataset.shapeAnimationSpeed;if(saveData){img.dataset.mimetype=img.dataset.originalMimetype;delete img.dataset.originalMimetype;}
weUtils.forwardToThumbnail(img);}
img.classList.add('o_modified_image_to_save');if(clonedImgEl){clonedImgEl.remove();img.classList.remove("d-none");}
this.trigger_up("enable_loading_effect");},async setImgShapeColor(previewMode,widgetValue,params){const img=this._getImg();const newColorId=parseInt(params.colorId);const oldColors=img.dataset.shapeColors.split(';');const newColors=oldColors.slice(0);newColors[newColorId]=this._getCSSColorValue(widgetValue===''?`o-color-${(newColorId + 1)}`:widgetValue);await this._applyShapeAndColors(true,newColors);img.classList.add('o_modified_image_to_save');},async setImgShapeFlipX(previewMode,widgetValue,params){await this._setImgShapeFlip("x");},async setImgShapeFlipY(previewMode,widgetValue,params){await this._setImgShapeFlip("y");},async setImgShapeRotateLeft(previewMode,widgetValue,params){await this._setImgShapeRotate(-90);},async setImgShapeRotateRight(previewMode,widgetValue,params){await this._setImgShapeRotate(90);},async setImgShapeHoverEffect(previewMode,widgetValue,params){const imgEl=this._getImg();if(previewMode!=="reset"){this.prevHoverEffectColor=imgEl.dataset.hoverEffectColor;this.prevHoverEffectIntensity=imgEl.dataset.hoverEffectIntensity;this.prevHoverEffectStrokeWidth=imgEl.dataset.hoverEffectStrokeWidth;}
delete imgEl.dataset.hoverEffectColor;delete imgEl.dataset.hoverEffectIntensity;delete imgEl.dataset.hoverEffectStrokeWidth;if(previewMode===true){if(params.name==="hover_effect_overlay_opt"){imgEl.dataset.hoverEffectColor=this._getCSSColorValue("black-25");}else if(params.name==="hover_effect_outline_opt"){imgEl.dataset.hoverEffectColor=this._getCSSColorValue("primary");imgEl.dataset.hoverEffectStrokeWidth=10;}else{imgEl.dataset.hoverEffectIntensity=20;if(params.name!=="hover_effect_mirror_blur_opt"){imgEl.dataset.hoverEffectColor="rgba(0, 0, 0, 0)";}}}else{if(this.prevHoverEffectColor){imgEl.dataset.hoverEffectColor=this.prevHoverEffectColor;}
if(this.prevHoverEffectIntensity){imgEl.dataset.hoverEffectIntensity=this.prevHoverEffectIntensity;}
if(this.prevHoverEffectStrokeWidth){imgEl.dataset.hoverEffectStrokeWidth=this.prevHoverEffectStrokeWidth;}}
await this._reapplyCurrentShape();if(this.firstHoverEffect){this.options.wysiwyg.odooEditor.historyUnpauseSteps();delete this.firstHoverEffect;}},async selectDataAttribute(previewMode,widgetValue,params){await this._super(...arguments);if(["shapeAnimationSpeed","hoverEffectIntensity","hoverEffectStrokeWidth"].includes(params.attributeName)){await this._reapplyCurrentShape();}},async setHoverEffectColor(previewMode,widgetValue,params){const img=this._getImg();let defaultColor="rgba(0, 0, 0, 0)";if(img.dataset.hoverEffect==="overlay"){defaultColor="black-25";}else if(img.dataset.hoverEffect==="outline"){defaultColor="primary";}
img.dataset.hoverEffectColor=this._getCSSColorValue(widgetValue||defaultColor);await this._reapplyCurrentShape();},notify(name){if(name==="enable_hover_effect"){this.trigger_up("snippet_edition_request",{exec:()=>{const imgEl=this._getImg();const shapeName=imgEl.dataset.shape?.split("/")[2];if(!shapeName){const shapeImgSquareWidget=this._requestUserValueWidgets("shape_img_square_opt")[0];shapeImgSquareWidget.enable();shapeImgSquareWidget.getParent().close();}
this.firstHoverEffect=true;const hoverEffectOverlayWidget=this._requestUserValueWidgets("hover_effect_overlay_opt")[0];hoverEffectOverlayWidget.enable();hoverEffectOverlayWidget.getParent().close();}});}else if(name==="disable_hover_effect"){this._disableHoverEffect();}else{this._super(...arguments);}},async updateUI(){await this._super(...arguments);const hoverEffectName=this.$target[0].dataset.hoverEffect;if(hoverEffectName){const hoverEffectColorWidget=this.findWidget("hover_effect_color_opt");const needToAdaptLabel=["image_zoom_in","image_zoom_out","dolly_zoom"].includes(hoverEffectName);const labelEl=hoverEffectColorWidget.el.querySelector("we-title");if(!this._originalHoverEffectColorLabel){this._originalHoverEffectColorLabel=labelEl.textContent;}
labelEl.textContent=needToAdaptLabel?_t("Overlay"):this._originalHoverEffectColorLabel;}
const hoverEffectsOptionsEl=this.$el[0].querySelector("#o_hover_effects_options");const animationEffectWidget=this._requestUserValueWidgets("animation_effect_opt")[0];if(hoverEffectsOptionsEl&&animationEffectWidget){animationEffectWidget.getParent().$el[0].append(hoverEffectsOptionsEl);}
const unsupportedQuality=this._unsupportedQualityOption();const inputQuality=this.el.querySelector('we-range[data-set-quality] input');if(inputQuality){if(!unsupportedQuality){inputQuality.disabled=false;inputQuality.removeAttribute('title');}else if(unsupportedQuality!==true){inputQuality.disabled=true;inputQuality.setAttribute('title',unsupportedQuality);}}},_isTransformed(){return this.$target.is('[style*="transform"]');},_isCropped(){return this.$target.hasClass('o_we_image_cropped');},_unsupportedQualityOption(){const img=this._getImg();const mimetype=this._getImageMimetype(img);if(!['image/jpeg','image/webp'].includes(mimetype)){return true;}
if('image/webp'===mimetype){if(this.canvasSupportWebp===undefined){const canvas=document.createElement('canvas');canvas.width=canvas.height=1;this.canvasSupportWebp=canvas.toDataURL('image/webp').slice(0,16)==='data:image/webp;';}
if(this.canvasSupportWebp===false){return _t('WebP compression not supported on this browser');}}
return false;},async _applyOptions(){const img=await this._super(...arguments);if(img&&img.dataset.shape){await this._loadShape(img.dataset.shape);if(/^data:/.test(img.src)){await this._applyShapeAndColors(true,(img.dataset.shapeColors&&img.dataset.shapeColors.split(';')));}}
return img;},async _loadShape(shapeName){const[module,directory,fileName]=shapeName.split('/');let shape=this.shapeCache[fileName];if(!shape){const shapeURL=`/${encodeURIComponent(module)}/static/image_shapes/${encodeURIComponent(directory)}/${encodeURIComponent(fileName)}.svg`;shape=await(await fetch(shapeURL)).text();this.shapeCache[fileName]=shape;}
this._getImg().dataset.shape=shapeName;},async _applyShapeAndColors(save,newColors){const img=this._getImg();let shape=this.shapeCache[img.dataset.shape.split('/')[2]];const oldColors=Object.values(DEFAULT_PALETTE).map(color=>shape.includes(color)?color:null);if(!newColors){newColors=oldColors.map((color,i)=>color!==null?this._getCSSColorValue(`o-color-${(i + 1)}`):null);}
newColors.forEach((color,i)=>shape=shape.replace(new RegExp(oldColors[i],'g'),this._getCSSColorValue(color)));await this._writeShape(shape);if(save){img.dataset.shapeColors=newColors.join(';');}
weUtils.forwardToThumbnail(img);},_replaceAnimationDuration(speed,svg){const ratio=(speed>=0.0?1.0+speed:1.0/(1.0-speed)).toFixed(3);function callbackCssAnimationRule(match,declaration,value,unit,separator){value=parseFloat(value)/(ratio?ratio:1);return`${declaration}${value}${unit}${separator}`;}
function callbackSvgDurTimecountVal(match,attribute_name,value,unit){value=parseFloat(value)/(ratio?ratio:1);return`${attribute_name}${value}${unit ? unit : 's'}"`}
svg=svg.replace(CSS_ANIMATION_RULE_REGEX,callbackCssAnimationRule);svg=svg.replace(SVG_DUR_TIMECOUNT_VAL_REGEX,callbackSvgDurTimecountVal);if(CSS_ANIMATION_RATIO_REGEX.test(svg)){svg=svg.replace(CSS_ANIMATION_RATIO_REGEX,`--animation_ratio: ${ratio};`);}else{const regex=/<svg .*>/m;const subst=`$&\n\t<style>\n\t\t:root { \n\t\t\t--animation_ratio: ${ratio};\n\t\t}\n\t</style>`;svg=svg.replace(regex,subst);}
return svg;},async _writeShape(svgText){const img=this._getImg();let needToRefreshPublicWidgets=false;let hasHoverEffect=false;if(img.dataset.hoverEffect&&this._canHaveHoverEffect()){needToRefreshPublicWidgets=true;hasHoverEffect=true;}
const dataURL=await this.computeShape(svgText,img);let clonedImgEl=null;if(hasHoverEffect){clonedImgEl=img.cloneNode(true);this.options.wysiwyg.odooEditor.observerUnactive("addClonedImgForHoverEffectPreview");img.classList.add("d-none");img.insertAdjacentElement("afterend",clonedImgEl);this.options.wysiwyg.odooEditor.observerActive("addClonedImgForHoverEffectPreview");}
const loadedImg=await loadImage(dataURL,img);if(hasHoverEffect){this.options.wysiwyg.odooEditor.observerUnactive("removeClonedImgForHoverEffectPreview");clonedImgEl.remove();img.classList.remove("d-none");this.options.wysiwyg.odooEditor.observerActive("removeClonedImgForHoverEffectPreview");}
if(needToRefreshPublicWidgets){await this._refreshPublicWidgets();}
return loadedImg;},async computeShape(svgText,img){const initialImageWidth=img.naturalWidth;const shapeAnimationSpeed=Number(img.dataset.shapeAnimationSpeed)||0;if(shapeAnimationSpeed){svgText=this._replaceAnimationDuration(shapeAnimationSpeed,svgText);}
const svg=new DOMParser().parseFromString(svgText,'image/svg+xml').documentElement;const shapeFlip=img.dataset.shapeFlip||"";const shapeRotate=img.dataset.shapeRotate||0;if((shapeFlip||shapeRotate)&&this._isTransformableShape()){let shapeTransformValues=[];if(shapeFlip){shapeTransformValues.push(`scale${shapeFlip === "x" ? "X" : shapeFlip === "y" ? "Y" : ""}(-1)`);}
if(shapeRotate){shapeTransformValues.push(`rotate(${shapeRotate}deg)`);}
const transformOrigin="transform-origin: 0.5px 0.5px;";svg.querySelector("#filterPath").setAttribute("style",`transform: ${shapeTransformValues.join(" ")}; ${transformOrigin}`);}
if(img.dataset.hoverEffect&&this._canHaveHoverEffect()){this._addImageShapeHoverEffect(svg,img);}
const svgAspectRatio=parseInt(svg.getAttribute('width'))/parseInt(svg.getAttribute('height'));const options={mimetype:this._getImageMimetype(img),perspective:svg.dataset.imgPerspective||null,imgAspectRatio:svg.dataset.imgAspectRatio||null,svgAspectRatio:svgAspectRatio,};const imgDataURL=await applyModifications(img,options);svg.removeChild(svg.querySelector('#preview'));svg.querySelectorAll("image").forEach(image=>{image.setAttribute("xlink:href",imgDataURL);});const originalImage=await loadImage(imgDataURL);if(!svg.dataset.forcedSize){svg.setAttribute('width',originalImage.naturalWidth);svg.setAttribute('height',originalImage.naturalHeight);}else{const imageWidth=Math.trunc(img.dataset.resizeWidth||img.dataset.width||initialImageWidth);const newHeight=imageWidth/svgAspectRatio;svg.setAttribute('width',imageWidth);svg.setAttribute('height',newHeight);}
const blob=new Blob([svg.outerHTML],{type:'image/svg+xml',});const dataURL=await createDataURL(blob);const imgFilename=(img.dataset.originalSrc.split('/').pop()).split('.')[0];img.dataset.fileName=`${imgFilename}.svg`;return dataURL;},_computeMaxDisplayWidth(){const img=this._getImg();const computedStyles=window.getComputedStyle(img);const displayWidth=parseFloat(computedStyles.getPropertyValue('width'));const gutterWidth=parseFloat(computedStyles.getPropertyValue('--o-grid-gutter-width'))||30;if(this.$target[0].closest('nav')){return Math.round(Math.min(displayWidth*3,this.MAX_SUGGESTED_WIDTH));}else if(img.closest('.container, .o_container_small')){const mdContainerMaxWidth=parseFloat(computedStyles.getPropertyValue('--o-md-container-max-width'))||720;const mdContainerInnerWidth=mdContainerMaxWidth-gutterWidth;return Math.round(clamp(displayWidth,mdContainerInnerWidth,this.MAX_SUGGESTED_WIDTH));}else if(img.closest('.container-fluid')){const lgBp=parseFloat(computedStyles.getPropertyValue('--breakpoint-lg'))||992;const mdContainerFluidMaxInnerWidth=lgBp-gutterWidth;return Math.round(clamp(displayWidth,mdContainerFluidMaxInnerWidth,this.MAX_SUGGESTED_WIDTH));}
return Math.round(Math.min(displayWidth*1.5,this.MAX_SUGGESTED_WIDTH));},_getImg(){return this.$target[0];},_relocateWeightEl(){const leftPanelEl=this.$overlay.data('$optionsSection')[0];const titleTextEl=leftPanelEl.querySelector('we-title > span');this.$weight.appendTo(titleTextEl);},async _computeWidgetVisibility(widgetName,params){if(widgetName.startsWith('img-shape-color')){const img=this._getImg();const shapeName=img.dataset.shape;const shapeColors=img.dataset.shapeColors;if(!shapeName||!shapeColors){return false;}
const colors=img.dataset.shapeColors.split(';');return colors[parseInt(params.colorId)];}
if(widgetName=='quality_range_opt'&&this._unsupportedQualityOption()===true){return false;}
if(widgetName==="shape_anim_speed_opt"){return this._isAnimatedShape();}
if(params.optionsPossibleValues.resetTransform){return this._isTransformed();}
if(params.optionsPossibleValues.resetCrop){return this._isCropped();}
if(params.optionsPossibleValues.crop){const img=this._getImg();return isImageSupportedForStyle(img)||this._isImageSupportedForProcessing(img);}
if(["img_shape_transform_flip_x_opt","img_shape_transform_flip_y_opt","img_shape_transform_rotate_x_opt","img_shape_transform_rotate_y_opt"].includes(params.name)){return this._isTransformableShape();}
if(widgetName==="hover_effect_none_opt"){return false;}
if(params.optionsPossibleValues.setImgShapeHoverEffect){const imgEl=this._getImg();return imgEl.classList.contains("o_animate_on_hover")&&this._canHaveHoverEffect();}
if(["alt","title"].includes(params.attributeName)){return isImageSupportedForStyle(this._getImg());}
if(widgetName==="shape_img_square_opt"){return false;}
if(widgetName==="remove_img_shape_opt"){const shapeImgSquareWidget=this._requestUserValueWidgets("shape_img_square_opt")[0];return!shapeImgSquareWidget.isActive();}
if(widgetName==="toggle_stretch_opt"){return this._isCropRequired();}
return this._super(...arguments);},_computeWidgetState(methodName,params){switch(methodName){case'selectStyle':{if(params.cssProperty==='width'){const width=this.$target[0].style.width.trim();if(width[width.length-1]==='%'){return`${parseInt(width)}%`;}
return'';}
break;}
case'transform':{return this._isTransformed()?'true':'';}
case'crop':{return this._isCropped()?'true':'';}
case'setImgShape':{return this._getImg().dataset.shape||'';}
case'setImgShapeColor':{const img=this._getImg();return(img.dataset.shapeColors&&img.dataset.shapeColors.split(';')[parseInt(params.colorId)])||'';}
case'setImgShapeFlipX':{const imgEl=this._getImg();return imgEl.dataset.shapeFlip?.includes("x")||"";}
case'setImgShapeFlipY':{const imgEl=this._getImg();return imgEl.dataset.shapeFlip?.includes("y")||"";}
case'setHoverEffectColor':{const imgEl=this._getImg();return imgEl.dataset.hoverEffectColor||"";}
case"removeStretch":{const imgEl=this._getImg();return imgEl.dataset.aspectRatio!=="1/1";}}
return this._super(...arguments);},async _renderCustomXML(uiFragment){await this._super(...arguments);uiFragment.querySelectorAll('we-select-page we-button[data-set-img-shape]').forEach(btn=>{const image=document.createElement('img');const[moduleName,directory,shapeName]=btn.dataset.setImgShape.split('/');image.src=`/${encodeURIComponent(moduleName)}/static/image_shapes/${encodeURIComponent(directory)}/${encodeURIComponent(shapeName)}.svg`;$(btn).prepend(image);if(btn.dataset.animated){_addAnimatedShapeLabel(btn);}else if(btn.dataset.imgSize){_addAnimatedShapeLabel(btn,true);}});},_getImageMimetype(img){if(img.dataset.shape&&img.dataset.originalMimetype){return img.dataset.originalMimetype;}
return this._super(...arguments);},_getCSSColorValue(color){if(!color||isCSSColor(color)){return color;}
return weUtils.getCSSVariableValue(color);},async _initializeImage(){const _super=this._super.bind(this);let img=this._getImg();let checkedAttribute='src';try{await loadImage(img.src);if(img.dataset.originalSrc){checkedAttribute='originalSrc';await loadImage(img.dataset.originalSrc);}}catch{if(checkedAttribute==='src'){Object.keys(img.dataset).forEach(key=>delete img.dataset[key]);img.dataset.mimetype='image/png';const newSrc='/web/image/web.image_placeholder';img=await loadImage(newSrc,img);return this._loadImageInfo(newSrc);}else{delete img.dataset.originalId;delete img.dataset.originalSrc;delete img.dataset.originalMimetype;}}
let match=img.src.match(/\/web_editor\/image_shape\/(\w+\.\w+)/);if(img.dataset.shape&&match){match=match[1];if(match.endsWith("_perspective")){match=match.slice(0,-12);}
return this._loadImageInfo(`/web/image/${encodeURIComponent(match)}`);}
return _super(...arguments);},async _loadImageInfo(){await this._super(...arguments);const img=this._getImg();if(img.dataset.shape){if(img.dataset.mimetype!=="image/svg+xml"){img.dataset.originalMimetype=img.dataset.mimetype;}
if(!this._isImageSupportedForProcessing(img)){delete img.dataset.shape;delete img.dataset.shapeColors;delete img.dataset.fileName;delete img.dataset.originalMimetype;delete img.dataset.shapeFlip;delete img.dataset.shapeRotate;delete img.dataset.hoverEffect;delete img.dataset.hoverEffectColor;delete img.dataset.hoverEffectStrokeWidth;delete img.dataset.hoverEffectIntensity;img.classList.remove("o_animate_on_hover");delete img.dataset.shapeAnimationSpeed;return;}
if(img.dataset.mimetype!=="image/svg+xml"){img.dataset.mimetype="image/svg+xml";}}},async _reapplyCurrentShape(){const img=this._getImg();if(img.dataset.shape){await this._loadShape(img.dataset.shape);await this._applyShapeAndColors(true,(img.dataset.shapeColors&&img.dataset.shapeColors.split(';')));img.classList.add("o_modified_image_to_save");}},_isImageProcessingWidget(widgetName,params){if(widgetName==='shape_img_opt'){return!isGif(this._getImageMimetype(this._getImg()));}
return this._super(...arguments);},async _setImgShapeFlip(flipValue){const imgEl=this._getImg();const currentFlipValue=imgEl.dataset.shapeFlip||"";const newFlipValue=currentFlipValue.includes(flipValue)?currentFlipValue.replace(flipValue,""):currentFlipValue+flipValue;if(newFlipValue){imgEl.dataset.shapeFlip=newFlipValue==="yx"?"xy":newFlipValue;}else{delete imgEl.dataset.shapeFlip;}
await this._applyShapeAndColors(true,imgEl.dataset.shapeColors?.split(";"));imgEl.classList.add("o_modified_image_to_save");},async _setImgShapeRotate(rotation){const imgEl=this._getImg();const currentRotateValue=parseInt(imgEl.dataset.shapeRotate)||0;const newRotateValue=(currentRotateValue+rotation+360)%360;if(newRotateValue){imgEl.dataset.shapeRotate=newRotateValue;}else{delete imgEl.dataset.shapeRotate;}
await this._applyShapeAndColors(true,imgEl.dataset.shapeColors?.split(";"));imgEl.classList.add("o_modified_image_to_save");},_isDeviceShape(){const imgEl=this._getImg();const shapeName=imgEl.dataset.shape;if(!shapeName){return false;}
const shapeCategory=imgEl.dataset.shape.split("/")[1];return shapeCategory==="devices";},_isTransformableShape(){const shapeImgWidget=this._requestUserValueWidgets("shape_img_opt")[0];return(shapeImgWidget&&!shapeImgWidget.getMethodsParams().noTransform)&&!this._isDeviceShape();},_isAnimatedShape(){const shapeImgWidget=this._requestUserValueWidgets("shape_img_opt")[0];return shapeImgWidget?.getMethodsParams().animated;},_isCropRequired(){const shapeImgWidget=this._requestUserValueWidgets("shape_img_opt")[0];return shapeImgWidget?.getMethodsParams().unstretch;},_canHaveHoverEffect(){return!this._isDeviceShape()&&!this._isAnimatedShape()&&this._isImageSupportedForShapes();},async _addImageShapeHoverEffect(svgEl,img){let rgba=null;let rbg=null;let opacity=null;const hoverEffectName=img.dataset.hoverEffect;if(!this.hoverEffectsSvg){this.hoverEffectsSvg=await this._getHoverEffects();}
const hoverEffectEls=this.hoverEffectsSvg.querySelectorAll(`#${hoverEffectName} > *`);hoverEffectEls.forEach(hoverEffectEl=>{svgEl.appendChild(hoverEffectEl.cloneNode(true));});const animateEl=svgEl.querySelector("animate");const animateTransformEls=svgEl.querySelectorAll("animateTransform");const animateElValues=animateEl?.getAttribute("values");let animateTransformElValues=animateTransformEls[0]?.getAttribute("values");if(img.dataset.hoverEffectColor){rgba=convertCSSColorToRgba(img.dataset.hoverEffectColor);rbg=`rgb(${rgba.red},${rgba.green},${rgba.blue})`;opacity=rgba.opacity/100;if(!["outline","image_mirror_blur"].includes(hoverEffectName)){svgEl.querySelector('[fill="hover_effect_color"]').setAttribute("fill",rbg);animateEl.setAttribute("values",animateElValues.replace("hover_effect_opacity",opacity));}}
switch(hoverEffectName){case"outline":{svgEl.querySelector('[stroke="hover_effect_color"]').setAttribute("stroke",rbg);svgEl.querySelector('[stroke-opacity="hover_effect_opacity"]').setAttribute("stroke-opacity",opacity);const strokeWidth=parseInt(img.dataset.hoverEffectStrokeWidth)*2;animateEl.setAttribute("values",animateElValues.replace("hover_effect_stroke_width",strokeWidth));break;}
case"image_zoom_in":case"image_zoom_out":case"dolly_zoom":{const imageEl=svgEl.querySelector("image");const clipPathEl=svgEl.querySelector("#clip-path");imageEl.setAttribute("id","shapeImage");imageEl.setAttribute("style","transform-origin: center; width: 100%; height: 100%");imageEl.setAttribute("preserveAspectRatio","none");svgEl.setAttribute("viewBox","0 0 1 1");svgEl.setAttribute("preserveAspectRatio","none");clipPathEl.setAttribute("clipPathUnits","userSpaceOnUse");const clipPathValue=imageEl.getAttribute("clip-path");imageEl.removeAttribute("clip-path");const gEl=document.createElementNS("http://www.w3.org/2000/svg","g");gEl.setAttribute("clip-path",clipPathValue);imageEl.parentNode.replaceChild(gEl,imageEl);gEl.appendChild(imageEl);let zoomValue=1.01+parseInt(img.dataset.hoverEffectIntensity)/200;animateTransformEls[0].setAttribute("values",animateTransformElValues.replace("hover_effect_zoom",zoomValue));if(hoverEffectName==="image_zoom_out"){const styleAttr=svgEl.querySelector("style");styleAttr.textContent=styleAttr.textContent.replace("hover_effect_zoom",zoomValue);}
if(hoverEffectName==="dolly_zoom"){clipPathEl.setAttribute("style","transform-origin: center;");zoomValue=0.99-parseInt(img.dataset.hoverEffectIntensity)/2000;animateTransformEls.forEach((animateTransformEl,index)=>{if(index>0){animateTransformElValues=animateTransformEl.getAttribute("values");animateTransformEl.setAttribute("values",animateTransformElValues.replace("hover_effect_zoom",zoomValue));}});}
break;}
case"image_mirror_blur":{const imageEl=svgEl.querySelector("image");imageEl.setAttribute('id','shapeImage');imageEl.setAttribute('style','transform-origin: center;');const imageMirrorEl=imageEl.cloneNode();imageMirrorEl.setAttribute("id",'shapeImageMirror');imageMirrorEl.setAttribute("filter","url(#blurFilter)");imageEl.insertAdjacentElement("beforebegin",imageMirrorEl);const zoomValue=0.99-parseInt(img.dataset.hoverEffectIntensity)/200;animateTransformEls[0].setAttribute("values",animateTransformElValues.replace("hover_effect_zoom",zoomValue));break;}}},_getHoverEffects(){const hoverEffectsURL="/website/static/src/svg/hover_effects.svg";return fetch(hoverEffectsURL).then(response=>response.text()).then(text=>{const parser=new DOMParser();const xmlDoc=parser.parseFromString(text,"text/xml");return xmlDoc.getElementsByTagName("svg")[0];});},async _disableHoverEffect(){const imgEl=this._getImg();const shapeName=imgEl.dataset.shape?.split("/")[2];delete imgEl.dataset.hoverEffect;delete imgEl.dataset.hoverEffectColor;delete imgEl.dataset.hoverEffectStrokeWidth;delete imgEl.dataset.hoverEffectIntensity;await this._applyOptions();if(shapeName==="geo_square"){this._requestUserValueWidgets("remove_img_shape_opt")[0].enable();}},async _select(previewMode,widget){await this._super(...arguments);if(widget.$el[0].closest("#o_hover_effects_options")){const hasSetImgShapeHoverEffectMethod=widget.getMethodsNames().includes("setImgShapeHoverEffect");if(previewMode===hasSetImgShapeHoverEffectMethod){this.$target[0].dispatchEvent(new Event("mouseover"));this.hoverTimeoutId=setTimeout(()=>{this.$target[0].dispatchEvent(new Event("mouseout"));},700);}else if(previewMode==="reset"){clearTimeout(this.hoverTimeoutId);}}},_isImageSupportedForShapes(){const imgEl=this._getImg();return imgEl.dataset.originalId&&this._isImageSupportedForProcessing(imgEl);},async _onImageChanged(ev){this.trigger_up('snippet_edition_request',{exec:async()=>{await this._autoOptimizeImage();this.trigger_up('cover_update');if(ev._complete){ev._complete();}}});},async _onImageCropped(ev){await this._rerenderXML();},});registry.BackgroundOptimize=ImageHandlerOption.extend({start(){this.$target.on('background_changed.BackgroundOptimize',this._onBackgroundChanged.bind(this));return this._super(...arguments);},destroy(){this.$target.off('.BackgroundOptimize');return this._super(...arguments);},_getImg(){return this.img;},_computeMaxDisplayWidth(){return 1920;},async _loadImageInfo(){this.img=new Image();const targetEl=this.$target[0].classList.contains("oe_img_bg")?this.$target[0]:this.$target[0].querySelector(":scope > .s_parallax_bg.oe_img_bg");if(targetEl){Object.entries(targetEl.dataset).filter(([key])=>isBackgroundImageAttribute(key)).forEach(([key,value])=>{this.img.dataset[key]=value;});const src=getBgImageURL(targetEl);this.img.src=src.startsWith("/")?src:"";}
return await this._super(...arguments);},_relocateWeightEl(){this.trigger_up('option_update',{optionNames:['BackgroundImage'],name:'add_size_indicator',data:this.$weight,});},_applyImage(img){const parts=backgroundImageCssToParts(this.$target.css('background-image'));parts.url=`url('${img.getAttribute('src')}')`;const combined=backgroundImagePartsToCss(parts);this.$target.css('background-image',combined);this.$target[0].classList.add("o_modified_image_to_save");for(const attribute in this.$target[0].dataset){if(isBackgroundImageAttribute(attribute)){delete this.$target[0].dataset[attribute];}}
Object.entries(img.dataset).forEach(([key,value])=>{this.$target[0].dataset[key]=value;});this.$target[0].dataset.bgSrc=img.getAttribute("src");},async _onBackgroundChanged(ev,previewMode){ev.stopPropagation();if(!previewMode){this.trigger_up('snippet_edition_request',{exec:async()=>{await this._autoOptimizeImage();}});}},});registry.BackgroundToggler=SnippetOptionWidget.extend({toggleBgImage(previewMode,widgetValue,params){if(!widgetValue){const targetEl=this.$target[0];targetEl.style.removeProperty("background-size");targetEl.classList.remove("o_bg_img_opt_repeat");this.$target.find('> .o_we_bg_filter').remove();const[bgImageWidget]=this._requestUserValueWidgets('bg_image_opt');const bgImageOpt=bgImageWidget.getParent();return bgImageOpt.background(false,'',bgImageWidget.getMethodsParams('background'));}else{this._requestUserValueWidgets('bg_image_opt')[0].el.click();}},toggleBgShape(previewMode,widgetValue,params){const[shapeWidget]=this._requestUserValueWidgets('bg_shape_opt');const shapeOption=shapeWidget.getParent();return shapeOption._toggleShape();},async selectFilterColor(previewMode,widgetValue,params){let filterEl=this.$target[0].querySelector(':scope > .o_we_bg_filter');const rgba=widgetValue&&convertCSSColorToRgba(widgetValue);if(!widgetValue||rgba&&rgba.opacity<0.001){if(filterEl){filterEl.remove();}
return;}
if(!filterEl){filterEl=document.createElement('div');filterEl.classList.add('o_we_bg_filter');const lastBackgroundEl=this._getLastPreFilterLayerElement();if(lastBackgroundEl){$(lastBackgroundEl).after(filterEl);}else{this.$target.prepend(filterEl);}}
const obj=createPropertyProxy(this,'$target',$(filterEl));params.cssProperty='background-color';return this.selectStyle.call(obj,previewMode,widgetValue,params);},_computeWidgetState(methodName,params){switch(methodName){case'toggleBgImage':{const[bgImageWidget]=this._requestUserValueWidgets('bg_image_opt');const bgImageOpt=bgImageWidget.getParent();return!!bgImageOpt._computeWidgetState('background',bgImageWidget.getMethodsParams('background'));}
case'toggleBgShape':{const[shapeWidget]=this._requestUserValueWidgets('bg_shape_opt');const shapeOption=shapeWidget.getParent();return!!shapeOption._computeWidgetState('shape',shapeWidget.getMethodsParams('shape'));}
case'selectFilterColor':{const filterEl=this.$target[0].querySelector(':scope > .o_we_bg_filter');if(!filterEl){return'';}
const obj=createPropertyProxy(this,'$target',$(filterEl));params.cssProperty='background-color';return this._computeWidgetState.call(obj,'selectStyle',params);}}
return this._super(...arguments);},_getLastPreFilterLayerElement(){return null;},});registry.BackgroundImage=SnippetOptionWidget.extend({start:function(){this.__customImageSrc=getBgImageURL(this.$target[0]);return this._super(...arguments);},background:async function(previewMode,widgetValue,params){if(previewMode===true){this.__customImageSrc=getBgImageURL(this.$target[0]);}else if(previewMode==='reset'){widgetValue=this.__customImageSrc;}else{this.__customImageSrc=widgetValue;}
this._setBackground(widgetValue);if(previewMode!=='reset'){removeOnImageChangeAttrs.forEach(attr=>delete this.$target[0].dataset[attr]);this.$target.trigger('background_changed',[previewMode]);}},async dynamicColor(previewMode,widgetValue,params){const currentSrc=getBgImageURL(this.$target[0]);switch(previewMode){case true:this.previousSrc=currentSrc;break;case'reset':this._setBackground(this.previousSrc);return;}
const newURL=new URL(currentSrc,window.location.origin);newURL.searchParams.set(params.colorName,normalizeColor(widgetValue));const src=newURL.pathname+newURL.search;await loadImage(src);this._setBackground(src);if(!previewMode){this.previousSrc=src;}},notify(name,data){if(name==='add_size_indicator'){this._requestUserValueWidgets('bg_image_opt')[0].$el.after(data);}else{this._super(...arguments);}},setTarget:function(){const oldBgURL=getBgImageURL(this.$target);const isModifiedImage=this.$target[0].classList.contains("o_modified_image_to_save");const filteredOldDataset=Object.entries(this.$target[0].dataset).filter(([key])=>{return isBackgroundImageAttribute(key);});filteredOldDataset.forEach(([key])=>{delete this.$target[0].dataset[key];});this.$target[0].classList.remove("o_modified_image_to_save");this._setBackground('');this._super(...arguments);if(oldBgURL){this._setBackground(oldBgURL);filteredOldDataset.forEach(([key,value])=>{this.$target[0].dataset[key]=value;});this.$target[0].classList.toggle("o_modified_image_to_save",isModifiedImage);}
this.__customImageSrc=getBgImageURL(this.$target[0]);},_computeWidgetState:function(methodName,params){switch(methodName){case'background':return getBgImageURL(this.$target[0]);case'dynamicColor':return new URL(getBgImageURL(this.$target[0]),window.location.origin).searchParams.get(params.colorName);}
return this._super(...arguments);},_computeWidgetVisibility(widgetName,params){if('colorName'in params){const src=new URL(getBgImageURL(this.$target[0]),window.location.origin);return src.searchParams.has(params.colorName);}else if(widgetName==='main_color_opt'){const src=new URL(getBgImageURL(this.$target[0]),window.location.origin);return src.origin===window.location.origin&&(src.pathname.startsWith('/html_editor/shape/')||src.pathname.startsWith('/web_editor/shape/'));}
return this._super(...arguments);},_setBackground(backgroundURL){const parts=backgroundImageCssToParts(this.$target.css('background-image'));if(backgroundURL){parts.url=`url('${backgroundURL}')`;this.$target.addClass('oe_img_bg o_bg_img_center o_bg_img_origin_border_box');}else{delete parts.url;this.$target[0].classList.remove("oe_img_bg","o_bg_img_center","o_bg_img_origin_border_box","o_modified_image_to_save",);}
const combined=backgroundImagePartsToCss(parts);this.selectStyle(false,combined,{cssProperty:'background-image',});this.options.wysiwyg.odooEditor.editable.focus();},});registry.BackgroundShape=SnippetOptionWidget.extend({updateUI({assetsChanged}={}){if(this.rerender||assetsChanged){this.rerender=false;return this._rerenderXML();}
return this._super.apply(this,arguments);},onBuilt(){if(this.$target[0].querySelector('.o_we_flip_x, .o_we_flip_y')){this._handlePreviewState(false,()=>{return{flip:this._getShapeData().flip};});}},shape(previewMode,widgetValue,params){this._handlePreviewState(previewMode,()=>{return{shape:widgetValue,colors:this._getImplicitColors(widgetValue,this._getShapeData().colors),flip:[],animated:params.animated,shapeAnimationSpeed:this._getShapeData().shapeAnimationSpeed,};});},color(previewMode,widgetValue,params){this._handlePreviewState(previewMode,()=>{const{colorName}=params;const{colors:previousColors}=this._getShapeData();const newColor=normalizeColor(widgetValue)||this._getDefaultColors()[colorName];const newColors=Object.assign(previousColors,{[colorName]:newColor});return{colors:newColors};});},flipX(previewMode,widgetValue,params){this._flipShape(previewMode,'x');},flipY(previewMode,widgetValue,params){this._flipShape(previewMode,'y');},showOnMobile(previewMode,widgetValue,params){this._handlePreviewState(previewMode,()=>{return{showOnMobile:!this._getShapeData().showOnMobile};});},setBgShapeAnimationSpeed(previewMode,widgetValue,params){this._handlePreviewState(previewMode,()=>{return{shapeAnimationSpeed:widgetValue};});},_computeWidgetState(methodName,params){switch(methodName){case'shape':{return this._getShapeData().shape;}
case'color':{const{shape,colors:customColors}=this._getShapeData();const colors=Object.assign(this._getDefaultColors(),customColors);const color=shape&&colors[params.colorName];return color||'';}
case'flipX':{const hasFlipClass=this.$target.find('> .o_we_shape.o_we_flip_x').length!==0;return hasFlipClass||this._getShapeData().flip.includes('x');}
case'flipY':{const hasFlipClass=this.$target.find('> .o_we_shape.o_we_flip_y').length!==0;return hasFlipClass||this._getShapeData().flip.includes('y');}
case'showOnMobile':{return this._getShapeData().showOnMobile;}
case"setBgShapeAnimationSpeed":{return this._getShapeData().shapeAnimationSpeed;}}
return this._super(...arguments);},async _computeWidgetVisibility(widgetName,params){if(widgetName==="bg_shape_anim_speed_opt"){const bgShapeWidget=this._requestUserValueWidgets("bg_shape_opt")[0];return bgShapeWidget.getMethodsParams().animated==="true";}
return this._super(...arguments);},_renderCustomXML(uiFragment){Object.keys(this._getDefaultColors()).map(colorName=>{uiFragment.querySelector('[data-name="colors"]').prepend($(`<we-colorpicker data-color="true" data-color-name="${colorName}"></we-colorpicker>`)[0]);});const style=window.getComputedStyle(this.$target[0]);const palette=[1,2,3,4,5].map(n=>style.getPropertyValue(`--o-cc${n}-bg`)).join();if(palette!==this._lastShapePalette){this._lastShapePalette=palette;this._shapeBackgroundImagePerClass={};for(const styleSheet of this.$target[0].ownerDocument.styleSheets){if(styleSheet.href&&new URL(styleSheet.href).host!==location.host){continue;}
for(const rule of[...styleSheet.cssRules]){if(rule.selectorText&&rule.selectorText.startsWith(".o_we_shape.")){this._shapeBackgroundImagePerClass[rule.selectorText]=rule.style.backgroundImage;}}}}
uiFragment.querySelectorAll('we-select-pager we-button[data-shape]').forEach(btn=>{const btnContent=document.createElement('div');btnContent.classList.add('o_we_shape_btn_content','position-relative','border-dark');const btnContentInnerDiv=document.createElement('div');btnContentInnerDiv.classList.add('o_we_shape');btnContent.appendChild(btnContentInnerDiv);if(btn.dataset.animated){_addAnimatedShapeLabel(btnContent);}
const{shape}=btn.dataset;const shapeEl=btnContent.querySelector('.o_we_shape');const shapeClassName=`o_${shape.replace(/\//g, '_')}`;shapeEl.classList.add(shapeClassName);const shapeBackgroundImage=this._shapeBackgroundImagePerClass[`.o_we_shape.${shapeClassName}`];shapeEl.style.setProperty("background-image",shapeBackgroundImage);btn.append(btnContent);});return uiFragment;},_flipShape(previewMode,axis){this._handlePreviewState(previewMode,()=>{const flip=new Set(this._getShapeData().flip);if(flip.has(axis)){flip.delete(axis);}else{flip.add(axis);}
return{flip:[...flip]};});},_insertShapeContainer(newContainer){const target=this.$target[0];const shapeContainer=target.querySelector(':scope > .o_we_shape');if(shapeContainer){this._removeShapeEl(shapeContainer);}
if(newContainer){const preShapeLayerElement=this._getLastPreShapeLayerElement();if(preShapeLayerElement){$(preShapeLayerElement).after(newContainer);}else{this.$target.prepend(newContainer);}}
return newContainer;},_createShapeContainer(shape){const shapeContainer=this._insertShapeContainer(document.createElement('div'));this.$target[0].style.position='relative';shapeContainer.className=`o_we_shape o_${shape.replace(/\//g, '_')}`;return shapeContainer;},_handlePreviewState(previewMode,computeShapeData){const target=this.$target[0];let changedShape=false;if(previewMode==='reset'){this._insertShapeContainer(this.prevShapeContainer);if(this.prevShape){target.dataset.oeShapeData=this.prevShape;}else{delete target.dataset.oeShapeData;}
return;}else{if(previewMode===true){const shapeContainer=target.querySelector(':scope > .o_we_shape');this.prevShapeContainer=shapeContainer&&shapeContainer.cloneNode(true);this.prevShape=target.dataset.oeShapeData;}
const curShapeData=target.dataset.oeShapeData||{};const newShapeData=computeShapeData();const{shape:curShape}=curShapeData;changedShape=newShapeData.shape!==curShape;this._markShape(newShapeData);if(previewMode===false&&changedShape){this.rerender=true;}}
const json=target.dataset.oeShapeData;const{shape,colors,flip=[],animated='false',showOnMobile,shapeAnimationSpeed}=json?JSON.parse(json):{};let shapeContainer=target.querySelector(':scope > .o_we_shape');if(!shape){return this._insertShapeContainer(null);}
if(changedShape){shapeContainer=this._createShapeContainer(shape);}
shapeContainer.classList.remove('o_we_flip_x','o_we_flip_y');shapeContainer.classList.toggle('o_we_animated',animated==='true');if(colors||flip.length||parseFloat(shapeAnimationSpeed)!==0){$(shapeContainer).css('background-image',`url("${this._getShapeSrc()}")`);shapeContainer.style.backgroundPosition='';if(flip.length){let[xPos,yPos]=$(shapeContainer).css('background-position').split(' ').map(p=>parseFloat(p));xPos=flip.includes('x')?-xPos+100:xPos;yPos=flip.includes('y')?-yPos+100:yPos;shapeContainer.style.backgroundPosition=`${xPos}% ${yPos}%`;}}else{$(shapeContainer).css('background-image','');$(shapeContainer).css('background-position','');}
shapeContainer.classList.toggle('o_shape_show_mobile',!!showOnMobile);if(previewMode===false){this.prevShapeContainer=shapeContainer.cloneNode(true);this.prevShape=target.dataset.oeShapeData;}},_removeShapeEl(shapeEl){shapeEl.remove();},_markShape(newData){const defaultColors=this._getDefaultColors();const shapeData=Object.assign(this._getShapeData(),newData);const areColorsDefault=Object.entries(shapeData.colors).every(([colorName,colorValue])=>{return defaultColors[colorName]&&colorValue.toLowerCase()===defaultColors[colorName].toLowerCase();});if(areColorsDefault){delete shapeData.colors;}
if(!shapeData.shape){delete this.$target[0].dataset.oeShapeData;}else{this.$target[0].dataset.oeShapeData=JSON.stringify(shapeData);}},_getLastPreShapeLayerElement(){const $filterEl=this.$target.find('> .o_we_bg_filter');if($filterEl.length){return $filterEl[0];}
return null;},_getShapeSrc(){const{shape,colors,flip,shapeAnimationSpeed}=this._getShapeData();if(!shape){return'';}
const searchParams=Object.entries(colors).map(([colorName,colorValue])=>{const encodedCol=encodeURIComponent(colorValue);return`${colorName}=${encodedCol}`;});if(flip.length){searchParams.push(`flip=${encodeURIComponent(flip.sort().join(''))}`);}
if(Number(shapeAnimationSpeed)){searchParams.push(`shapeAnimationSpeed=${encodeURIComponent(shapeAnimationSpeed)}`);}
return`/web_editor/shape/${encodeURIComponent(shape)}.svg?${searchParams.join('&')}`;},_getShapeData(target=this.$target[0]){const defaultData={shape:'',colors:this._getDefaultColors($(target)),flip:[],showOnMobile:false,shapeAnimationSpeed:"0",};const json=target.dataset.oeShapeData;return json?Object.assign(defaultData,JSON.parse(json.replace(/'/g,'"'))):defaultData;},_getDefaultColors($target=this.$target){const $shapeContainer=$target.find('> .o_we_shape').clone().addClass('d-none').appendTo(this.$target[0].ownerDocument.body);const shapeContainer=$shapeContainer[0];$shapeContainer.css('background-image','');const shapeSrc=shapeContainer&&getBgImageURL(shapeContainer);$shapeContainer.remove();if(!shapeSrc){return{};}
const url=new URL(shapeSrc,window.location.origin);return Object.fromEntries(url.searchParams.entries());},_getShapeDefaultColors(shapeId){const $shapeContainer=this.$el.find(".o_we_bg_shape_menu we-button[data-shape='"+shapeId+"'] div.o_we_shape");const shapeContainer=$shapeContainer[0];const shapeSrc=shapeContainer&&getBgImageURL(shapeContainer);const url=new URL(shapeSrc,window.location.origin);return Object.fromEntries(url.searchParams.entries());},_getImplicitColors(shape,previousColors){const defaultColors=this._getShapeDefaultColors(shape);let colors=previousColors||{};let sibling=this.$target[0].previousElementSibling;while(sibling){colors=Object.assign(this._getShapeData(sibling).colors||{},colors);sibling=sibling.previousElementSibling;}
const defaultKeys=Object.keys(defaultColors);colors=Object.assign(defaultColors,colors);return pick(colors,...defaultKeys);},_toggleShape(){if(this._getShapeData().shape){return this._handlePreviewState(false,()=>({shape:''}));}else{const target=this.$target[0];const previousSibling=target.previousElementSibling;const[shapeWidget]=this._requestUserValueWidgets('bg_shape_opt');const possibleShapes=shapeWidget.getMethodsParams('shape').possibleValues;let shapeToSelect;if(previousSibling){const previousShape=this._getShapeData(previousSibling).shape;shapeToSelect=possibleShapes.find((shape,i)=>{return possibleShapes[i-1]===previousShape;});}
if(!shapeToSelect){shapeToSelect=possibleShapes[1];}
const showOnMobile=weUtils.isMobileView(this.$target[0]);this.trigger_up('snippet_edition_request',{exec:()=>{this._requestUserValueWidgets('bg_shape_opt')[0].enable();}});this._createShapeContainer(shapeToSelect);return this._handlePreviewState(false,()=>({shape:shapeToSelect,colors:this._getImplicitColors(shapeToSelect),showOnMobile,}));}},});registry.BackgroundPosition=SnippetOptionWidget.extend({start:function(){this._super.apply(this,arguments);this._initOverlay();$(window).on('resize.bgposition',()=>this._dimensionOverlay());},destroy:function(){this._toggleBgOverlay(false);$(window).off('.bgposition');this._super.apply(this,arguments);},backgroundType:function(previewMode,widgetValue,params){this.$target.toggleClass('o_bg_img_opt_repeat',widgetValue==='repeat-pattern');this.$target.css('background-position','');this.$target[0].style.backgroundSize=widgetValue!=="repeat-pattern"?"":"100px, cover";},backgroundPositionOverlay:async function(previewMode,widgetValue,params){await new Promise(resolve=>{this.img=document.createElement('img');this.img.addEventListener('load',()=>resolve());this.img.src=getBgImageURL(this.$target[0]);});const position=this.$target.css('background-position').split(' ').map(v=>parseInt(v));const delta=this._getBackgroundDelta();this.originalPosition={left:position[0],top:position[1],};this.currentPosition={left:position[0]/100*delta.x||0,top:position[1]/100*delta.y||0,};const rect=this.$target[0].getBoundingClientRect();const viewportTop=$(window).scrollTop();const viewportBottom=viewportTop+$(window).height();const visibleHeight=rect.top<viewportTop?Math.max(0,Math.min(viewportBottom,rect.bottom)-viewportTop):rect.top<viewportBottom?Math.min(viewportBottom,rect.bottom)-rect.top:0;if(visibleHeight<200){await scrollTo(this.$target[0],{extraOffset:50});}
this._toggleBgOverlay(true);},selectStyle:function(previewMode,widgetValue,params){if(params.cssProperty==="background-size"){const targetEl=this.$target[0];if(!targetEl.classList.contains("o_bg_img_opt_repeat")){return;}
const sizeLayers=getComputedStyle(targetEl).getPropertyValue("background-size").split(",").map((bgSize)=>bgSize.trim());sizeLayers[0]=widgetValue;targetEl.style.setProperty("background-size",sizeLayers.join(", "));return;}
this._super(...arguments);},_computeVisibility:function(){return this._super(...arguments)&&!!getBgImageURL(this.$target[0]);},_computeWidgetState:function(methodName,params){const computedStyle=getComputedStyle(this.$target[0]);if(methodName==="backgroundType"){return computedStyle.backgroundRepeat.includes("no-repeat")?"cover":"repeat-pattern";}
if(methodName==="selectStyle"&&params.cssProperty==="background-size"){const bgSize=computedStyle.getPropertyValue("background-size").trim();return bgSize.split(",")[0].trim();}
return this._super(...arguments);},_initOverlay:function(){this.$backgroundOverlay=$(renderToElement('web_editor.background_position_overlay'));this.$overlayContent=this.$backgroundOverlay.find('.o_we_overlay_content');this.$overlayBackground=this.$overlayContent.find('.o_overlay_background');this.$backgroundOverlay.on('click','.o_btn_apply',()=>{this.$target.css('background-position',this.$bgDragger.css('background-position'));this._toggleBgOverlay(false);});this.$backgroundOverlay.on('click','.o_btn_discard',()=>{this._toggleBgOverlay(false);});this.$backgroundOverlay.insertAfter(this.$overlay);},_dimensionOverlay:function(){if(!this.$backgroundOverlay.is('.oe_active')){return;}
const $wrapwrap=$(this.ownerDocument.body).find("#wrapwrap");const targetOffset=this.$target.offset();this.$backgroundOverlay.css({width:$wrapwrap.innerWidth(),height:$wrapwrap.innerHeight(),});this.$overlayContent.offset(targetOffset);this.$bgDragger[0].style.setProperty("width",`${this.$target.innerWidth()}px`,"important");this.$bgDragger[0].style.setProperty("height",`${this.$target.innerHeight()}px`,"important");const topPos=Math.max(0,$(window).scrollTop()-this.$target.offset().top);this.$overlayContent.find('.o_we_overlay_buttons').css('top',`${topPos}px`);},_toggleBgOverlay:function(activate){if(!this.$backgroundOverlay||this.$backgroundOverlay.is('.oe_active')===activate){return;}
if(!activate){this.$backgroundOverlay.removeClass('oe_active');this.trigger_up('unblock_preview_overlays');this.trigger_up('activate_snippet',{$snippet:this.$target});$(document).off('click.bgposition');if(this.$bgDragger){this.$bgDragger.tooltip('dispose');}
return;}
this.trigger_up('hide_overlay');this.trigger_up('activate_snippet',{$snippet:this.$target,previewMode:true,});this.trigger_up('block_preview_overlays');this.$bgDragger=this.$target.clone().empty();this.$bgDragger.removeClass('o_editable');this.$bgDragger.css('background-attachment',this.$target.css('background-attachment'));this.$bgDragger.on('mousedown',this._onDragBackgroundStart.bind(this));this.$bgDragger.tooltip({title:'Click and drag the background to adjust its position!',trigger:'manual',container:this.$backgroundOverlay});this.$overlayBackground.empty().append(this.$bgDragger);this.$backgroundOverlay.addClass('oe_active');this._dimensionOverlay();this.$bgDragger.tooltip('show');window.setTimeout(()=>$(document).on('click.bgposition',this._onDocumentClicked.bind(this)),0);},_getBackgroundDelta:function(){const bgSize=this.$target.css('background-size');if(bgSize!=='cover'){let[width,height]=bgSize.split(' ');if(width==='auto'&&(height==='auto'||!height)){return{x:this.$target.outerWidth()-this.img.naturalWidth,y:this.$target.outerHeight()-this.img.naturalHeight,};}
[width,height]=[parseInt(width),parseInt(height)];return{x:this.$target.outerWidth()-(width||(height*this.img.naturalWidth/this.img.naturalHeight)),y:this.$target.outerHeight()-(height||(width*this.img.naturalHeight/this.img.naturalWidth)),};}
const renderRatio=Math.max(this.$target.outerWidth()/this.img.naturalWidth,this.$target.outerHeight()/this.img.naturalHeight);return{x:this.$target.outerWidth()-Math.round(renderRatio*this.img.naturalWidth),y:this.$target.outerHeight()-Math.round(renderRatio*this.img.naturalHeight),};},_onDragBackgroundStart:function(ev){ev.preventDefault();this.$bgDragger.addClass('o_we_grabbing');const $document=$(this.$target[0].ownerDocument);$document.on('mousemove.bgposition',this._onDragBackgroundMove.bind(this));$document.one('mouseup',()=>{this.$bgDragger.removeClass('o_we_grabbing');$document.off('mousemove.bgposition');});},_onDragBackgroundMove:function(ev){ev.preventDefault();const delta=this._getBackgroundDelta();this.currentPosition.left=clamp(this.currentPosition.left+ev.originalEvent.movementX,[0,delta.x]);this.currentPosition.top=clamp(this.currentPosition.top+ev.originalEvent.movementY,[0,delta.y]);const percentPosition={left:this.currentPosition.left/delta.x*100,top:this.currentPosition.top/delta.y*100,};percentPosition.left=isFinite(percentPosition.left)?percentPosition.left:this.originalPosition.left;percentPosition.top=isFinite(percentPosition.top)?percentPosition.top:this.originalPosition.top;this.$bgDragger.css('background-position',`${percentPosition.left}% ${percentPosition.top}%`);function clamp(val,bounds){bounds=bounds.sort();return Math.max(bounds[0],Math.min(val,bounds[1]));}},_onDocumentClicked:function(ev){if(!$(ev.target).closest('.o_we_background_position_overlay').length){this._toggleBgOverlay(false);}},});registry.ColoredLevelBackground=registry.BackgroundToggler.extend({start:function(){this._markColorLevel();return this._super(...arguments);},onBuilt:function(){this._markColorLevel();},_markColorLevel:function(){this.options.wysiwyg.odooEditor.observerUnactive('_markColorLevel');this.$target.addClass('o_colored_level');this.options.wysiwyg.odooEditor.observerActive('_markColorLevel');},});registry.ContainerWidth=SnippetOptionWidget.extend({cleanForSave:function(){this.$target.removeClass('o_container_preview');},selectClass:async function(previewMode,widgetValue,params){await this._super(...arguments);if(previewMode==='reset'){this.$target.removeClass('o_container_preview');}else if(previewMode){this.$target.addClass('o_container_preview');}
this.trigger_up('option_update',{optionName:'StepsConnector',name:'change_container_width',});},});registry.many2one=SnippetOptionWidget.extend({init(){this._super(...arguments);this.orm=this.bindService("orm");},async willStart(){const{oeMany2oneModel,oeMany2oneId}=this.$target[0].dataset;this.fields=['name','display_name'];return Promise.all([this._super(...arguments),this.orm.read(oeMany2oneModel,[parseInt(oeMany2oneId)],this.fields).then(([initialRecord])=>{this.initialRecord=initialRecord;}),]);},async changeRecord(previewMode,widgetValue,params){const target=this.$target[0];if(previewMode==='reset'){this.$target.data('oeMany2oneId',this.prevId);target.dataset.oeMany2oneId=this.prevId;this.$target.empty().append(this.$prevContents);return this._rerenderContacts(this.prevId,this.prevRecordName);}
const record=JSON.parse(params.recordData);if(previewMode===true){this.prevId=parseInt(target.dataset.oeMany2oneId);this.$prevContents=this.$target.contents();this.prevRecordName=this.prevRecordName||this.initialRecord.name;}
this.$target.data('oeMany2oneId',record.id);target.dataset.oeMany2oneId=record.id;if(target.dataset.oeType!=='contact'){target.textContent=record.name;}
await this._rerenderContacts(record.id,record.name);if(previewMode===false){this.prevId=record.id;this.$prevContents=this.$target.contents();this.prevRecordName=record.name;}},_computeWidgetState(methodName,params){if(methodName==='changeRecord'){return this.$target[0].dataset.oeMany2oneId;}
return this._super(...arguments);},async _renderCustomXML(uiFragment){const many2oneWidget=document.createElement('we-many2one');many2oneWidget.dataset.changeRecord='';const model=this.$target[0].dataset.oeMany2oneModel;const[{name:modelName}]=await this.orm.searchRead("ir.model",[['model','=',model]],['name']);many2oneWidget.setAttribute('String',modelName);many2oneWidget.dataset.model=model;many2oneWidget.dataset.fields=JSON.stringify(this.fields);uiFragment.appendChild(many2oneWidget);},async _rerenderContacts(contactId,defaultText){const selector=[`[data-oe-model="${this.$target.data('oe-model')}"]`,`[data-oe-id="${this.$target.data('oe-id')}"]`,`[data-oe-field="${this.$target.data('oe-field')}"]`,`[data-oe-contact-options!='${this.$target[0].dataset.oeContactOptions}']`,].join('');let $toRerender=$(selector);if(this.$target[0].dataset.oeType==='contact'){$toRerender=$toRerender.add(this.$target);}
await Promise.all($toRerender.attr('data-oe-many2one-id',contactId).data('oe-many2one-id',contactId).map(async(i,node)=>{if(node.dataset.oeType==='contact'){const html=await this.orm.call("ir.qweb.field.contact","get_record_to_html",[[contactId]],{options:JSON.parse(node.dataset.oeContactOptions)});$(node).html(html);}else{node.textContent=defaultText;}}));},});registry.VersionControl=SnippetOptionWidget.extend({async replaceSnippet(){let newBlockEl;this.trigger_up("find_snippet_template",{snippet:this.$target[0],callback:(snippet)=>{newBlockEl=snippet.baseBody.cloneNode(true);},});newBlockEl.querySelectorAll(".s_dialog_preview").forEach(previewEl=>previewEl.remove());this.options.wysiwyg.odooEditor.historyPauseSteps();this.$target[0].classList.add("d-none");this.$target[0].insertAdjacentElement("beforebegin",newBlockEl);this.options.wysiwyg.waitForEmptyMutexAction().then(async()=>{await new Promise((resolve)=>{this.options.wysiwyg.snippetsMenuBus.trigger("CALL_POST_SNIPPET_DROP",{$snippet:$(newBlockEl),onSuccess:resolve,});});await new Promise(resolve=>{this.trigger_up("remove_snippet",{$snippet:this.$target,onSuccess:resolve,shouldRecordUndo:false});});this.options.wysiwyg.odooEditor.historyUnpauseSteps();newBlockEl.classList.remove("oe_snippet_body");this.options.wysiwyg.odooEditor.historyStep();});},discardAlert(){const alertEl=this.$el[0].querySelector("we-alert");const optionsSectionEl=this.$overlay.data("$optionsSection")[0];alertEl.remove();optionsSectionEl.classList.remove("o_we_outdated_block_options");controlledSnippets.add(this.$target[0].dataset.snippet);},_renderCustomXML(uiFragment){const snippetName=this.$target[0].dataset.snippet;if(controlledSnippets.has(snippetName)){return;}
this.trigger_up("get_snippet_versions",{snippetName:snippetName,onSuccess:snippetVersions=>{const isUpToDate=snippetVersions&&["vjs","vcss","vxml"].every(key=>this.$target[0].dataset[key]===snippetVersions[key]);if(!isUpToDate){uiFragment.prepend(renderToElement("web_editor.outdated_block_message"));const optionsSectionEl=this.$overlay.data("$optionsSection")[0];optionsSectionEl.classList.add("o_we_outdated_block_options");}},});},});registry.SnippetSave=SnippetOptionWidget.extend({isTopOption:true,saveSnippet:function(previewMode,widgetValue,params){return new Promise(resolve=>{this.dialog.add(ConfirmationDialog,{body:_t("To save a snippet, we need to save all your previous modifications and reload the page."),cancel:()=>resolve(false),confirmLabel:_t("Save and Reload"),confirm:()=>{let targetCopyEl=null;const isButton=this.$target[0].matches("a.btn");const snippetKey=!isButton?this.$target[0].dataset.snippet:"s_button";let thumbnailURL;this.trigger_up('snippet_thumbnail_url_request',{key:snippetKey,onSuccess:url=>thumbnailURL=url,});let context;this.trigger_up('context_get',{callback:ctx=>context=ctx,});if(this.$target[0].matches(".s_popup")){targetCopyEl=this.$target[0].cloneNode(true);}
this.trigger_up('request_save',{reloadEditor:true,invalidateSnippetCache:true,onSuccess:async()=>{const defaultSnippetName=!isButton?_t("Custom %s",this.data.snippetName):_t("Custom Button");targetCopyEl=targetCopyEl||this.$target[0].cloneNode(true);targetCopyEl.classList.add('s_custom_snippet');delete targetCopyEl.dataset.name;if(isButton){targetCopyEl.classList.remove("mb-2");targetCopyEl.classList.add("o_snippet_drop_in_only","s_custom_button");}
let editableParentEl;for(const parentEl of this.options.getContentEditableAreas()){if(parentEl.contains(this.$target[0])){editableParentEl=parentEl;break;}}
context['model']=editableParentEl.dataset.oeModel;context['field']=editableParentEl.dataset.oeField;context['resId']=editableParentEl.dataset.oeId;await rpc(`/web/dataset/call_kw/ir.ui.view/save_snippet`,{model:"ir.ui.view",method:"save_snippet",args:[],kwargs:{'name':defaultSnippetName,'arch':targetCopyEl.outerHTML,'template_key':this.options.snippets,'snippet_key':snippetKey,'thumbnail_url':thumbnailURL,'context':context,},});},});resolve(true);},});});},});registry.DynamicSvg=SnippetOptionWidget.extend({start(){this.$target.on('image_changed.DynamicSvg',this._onImageChanged.bind(this));return this._super(...arguments);},destroy(){this.$target.off('.DynamicSvg');return this._super(...arguments);},async color(previewMode,widgetValue,params){const target=this.$target[0];switch(previewMode){case true:this.previousSrc=target.getAttribute('src');break;case'reset':target.src=this.previousSrc;return;}
const newURL=new URL(target.src,window.location.origin);let color=widgetValue?normalizeColor(widgetValue):'';if(!color){const colorId=params.colorName.slice(1);color=weUtils.getCSSVariableValue(`o-color-${colorId}`)||weUtils.DEFAULT_PALETTE[colorId];}
newURL.searchParams.set(params.colorName,color);const src=newURL.pathname+newURL.search;await loadImage(src);target.src=src;if(!previewMode){this.previousSrc=src;}},_computeWidgetState(methodName,params){switch(methodName){case'color':return new URL(this.$target[0].src,window.location.origin).searchParams.get(params.colorName);}
return this._super(...arguments);},_computeWidgetVisibility(widgetName,params){if('colorName'in params){return new URL(this.$target[0].src,window.location.origin).searchParams.get(params.colorName);}
return this._super(...arguments);},_computeVisibility(methodName,params){return this.$target.is("img[src^='/html_editor/shape/'], img[src^='/web_editor/shape/']");},_onImageChanged(methodName,params){return this.updateUI();},});registry.MultipleItems=SnippetOptionWidget.extend({async addItem(previewMode,widgetValue,params){const $target=this.$(params.item);const addBeforeItem=params.addBefore==='true';if($target.length){await new Promise(resolve=>{this.trigger_up('clone_snippet',{$snippet:$target,onSuccess:resolve,});});if(addBeforeItem){$target.before($target.next());}
if(params.selectItem!=='false'){this.trigger_up('activate_snippet',{$snippet:addBeforeItem?$target.prev():$target.next(),});}
this._addItemCallback($target);}},async removeItem(previewMode,widgetValue,params){const $target=this.$(params.item);if($target.length){await new Promise(resolve=>{this.trigger_up('remove_snippet',{$snippet:$target,onSuccess:resolve,});});this._removeItemCallback($target);}},_addItemCallback($target){},_removeItemCallback($target){},});registry.SelectTemplate=SnippetOptionWidget.extend({custom_events:Object.assign({},SnippetOptionWidget.prototype.custom_events,{'user_value_widget_opening':'_onWidgetOpening',}),init(){this._super(...arguments);this.containerSelector='';this.selectTemplateWidgetName='';this.orm=this.bindService("orm");},async start(){this.containerEl=this.containerSelector?this.$target.find(this.containerSelector)[0]:this.$target[0];this._templates={};return this._super(...arguments);},async selectTemplate(previewMode,widgetValue,params){await this._templatesLoading;if(previewMode==='reset'){if(!this.beforePreviewNodes){return;}
while(this.containerEl.lastChild){this.containerEl.removeChild(this.containerEl.lastChild);}
for(const node of this.beforePreviewNodes){this.containerEl.appendChild(node);}
this.beforePreviewNodes=null;return;}
if(!this.beforePreviewNodes){this.beforePreviewNodes=[...this.containerEl.childNodes];}
while(this.containerEl.lastChild){this.containerEl.removeChild(this.containerEl.lastChild);}
this.containerEl.insertAdjacentHTML('beforeend',this._templates[widgetValue]);if(!previewMode){this.beforePreviewNodes=null;}},async _getTemplate(xmlid){if(!this._templates[xmlid]){this._templates[xmlid]=await this.orm.call("ir.ui.view","render_public_asset",[`${xmlid}`,{}],{context:this.options.context});}
return this._templates[xmlid];},_onWidgetOpening(ev){if(this._templatesLoading||ev.target.getName()!==this.selectTemplateWidgetName){return;}
const templateParams=ev.target.getMethodsParams('selectTemplate');const proms=templateParams.possibleValues.map(async xmlid=>{if(!xmlid){return;}
await this._getTemplate(xmlid);});this._templatesLoading=Promise.all(proms);},});registry.GalleryHandler=SnippetOptionWidget.extend({notify(name,data){this._super(...arguments);if(name==="reorder_items"){const itemsEls=this._getItemsGallery();const oldPosition=itemsEls.indexOf(data.itemEl);if(oldPosition===0&&data.position==="prev"){data.position="last";}else if(oldPosition===itemsEls.length-1&&data.position==="next"){data.position="first";}
itemsEls.splice(oldPosition,1);switch(data.position){case"first":itemsEls.unshift(data.itemEl);break;case"prev":itemsEls.splice(Math.max(oldPosition-1,0),0,data.itemEl);break;case"next":itemsEls.splice(oldPosition+1,0,data.itemEl);break;case"last":itemsEls.push(data.itemEl);break;}
this._reorderItems(itemsEls,itemsEls.indexOf(data.itemEl));}},_getItemsGallery(){},_reorderItems(itemsEls,newItemPosition){},});registry.CarouselHandler=registry.GalleryHandler.extend({_updateIndicatorAndActivateSnippet(position){const carouselEl=this.$target[0].classList.contains("carousel")?this.$target[0]:this.$target[0].querySelector(".carousel");carouselEl.classList.remove("slide");$(carouselEl).carousel(position);const indicatorEls=this.$target[0].querySelectorAll(".carousel-indicators > *");indicatorEls.forEach((indicatorEl,i)=>{indicatorEl.classList.toggle("active",i===position);});this.trigger_up("activate_snippet",{$snippet:$(this.$target[0].querySelector(".carousel-item.active img")),ifInactiveOptions:true,});carouselEl.classList.add("slide");$(carouselEl).carousel("pause");},});__exports[Symbol.for("default")]={SnippetOptionWidget:SnippetOptionWidget,snippetOptionRegistry:registry,NULL_ID:NULL_ID,UserValueWidget:UserValueWidget,userValueWidgetsRegistry:userValueWidgetsRegistry,UnitUserValueWidget:UnitUserValueWidget,addTitleAndAllowedAttributes:_addTitleAndAllowedAttributes,buildElement:_buildElement,buildTitleElement:_buildTitleElement,buildRowElement:_buildRowElement,buildCollapseElement:_buildCollapseElement,addAnimatedShapeLabel:_addAnimatedShapeLabel,Class:SnippetOptionWidget,registry:registry,serviceCached,clearServiceCache,clearControlledSnippets,};return __exports;});