/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */
import $ from"jquery";import*as Helper from"@typo3/form/backend/form-editor/helper.js";import Icons from"@typo3/backend/icons.js";import Sortable from"sortablejs";const defaultConfiguration={domElementClassNames:{formElementIsComposit:"t3-form-element-composit",formElementIsTopLevel:"t3-form-element-toplevel",noNesting:"mjs-nestedSortable-no-nesting",selected:"selected",sortable:"sortable",previewViewPreviewElement:"t3-form-element-preview"},domElementDataAttributeNames:{abstractType:"data-element-abstract-type",noSorting:"data-no-sorting"},domElementDataAttributeValues:{abstractViewToolbar:"elementToolbar",abstractViewToolbarNewElement:"stageElementToolbarNewElement",abstractViewToolbarNewElementSplitButton:"stageElementToolbarNewElementSplitButton",abstractViewToolbarNewElementSplitButtonAfter:"stageElementToolbarNewElementSplitButtonAfter",abstractViewToolbarNewElementSplitButtonInside:"stageElementToolbarNewElementSplitButtonInside",abstractViewToolbarRemoveElement:"stageElementToolbarRemoveElement",buttonHeaderRedo:"redoButton",buttonHeaderUndo:"undoButton",buttonPaginationPrevious:"buttonPaginationPrevious",buttonPaginationNext:"buttonPaginationNext","FormElement-_ElementToolbar":"FormElement-_ElementToolbar","FormElement-_UnknownElement":"FormElement-_UnknownElement","FormElement-AdvancedPassword":"FormElement-AdvancedPassword","FormElement-Checkbox":"FormElement-Checkbox","FormElement-ContentElement":"FormElement-ContentElement","FormElement-CountrySelect":"FormElement-CountrySelect","FormElement-DatePicker":"FormElement-DatePicker","FormElement-Fieldset":"FormElement-Fieldset","FormElement-GridRow":"FormElement-GridRow","FormElement-FileUpload":"FormElement-FileUpload","FormElement-Hidden":"FormElement-Hidden","FormElement-ImageUpload":"FormElement-ImageUpload","FormElement-MultiCheckbox":"FormElement-MultiCheckbox","FormElement-MultiSelect":"FormElement-MultiSelect","FormElement-Page":"FormElement-Page","FormElement-Password":"FormElement-Password","FormElement-RadioButton":"FormElement-RadioButton","FormElement-SingleSelect":"FormElement-SingleSelect","FormElement-StaticText":"FormElement-StaticText","FormElement-SummaryPage":"FormElement-SummaryPage","FormElement-Text":"FormElement-Text","FormElement-Textarea":"FormElement-Textarea","FormElement-Email":"FormElement-Email","FormElement-Url":"FormElement-Url","FormElement-Telephone":"FormElement-Telephone","FormElement-Number":"FormElement-Number","FormElement-Date":"FormElement-Date",formElementIcon:"elementIcon",iconValidator:"form-validator",multiValueContainer:"multiValueContainer",paginationTitle:"paginationTitle",stageHeadline:"formDefinitionLabel",stagePanel:"stagePanel",validatorsContainer:"validatorsContainer",validatorIcon:"validatorIcon"},isSortable:!0};let configuration=null,formEditorApp=null,stageDomElement=null;function getFormEditorApp(){return formEditorApp}function getHelper(e){return getUtility().isUndefinedOrNull(e)?Helper.setConfiguration(configuration):Helper.setConfiguration(e)}function getUtility(){return getFormEditorApp().getUtility()}function getViewModel(){return getFormEditorApp().getViewModel()}function assert(e,t,n){return getFormEditorApp().assert(e,t,n)}function getRootFormElement(){return getFormEditorApp().getRootFormElement()}function getCurrentlySelectedFormElement(){return getFormEditorApp().getCurrentlySelectedFormElement()}function getPublisherSubscriber(){return getFormEditorApp().getPublisherSubscriber()}function getFormElementDefinition(e,t){return getFormEditorApp().getFormElementDefinition(e,t)}function setTemplateTextContent(e,t){getUtility().isNonEmptyString(t)&&$(e).text(t)}function renderTemplateDispatcher(e,t){switch(e.get("type")){case"Checkbox":renderCheckboxTemplate(e,t);break;case"FileUpload":case"ImageUpload":renderFileUploadTemplates(e,t);break;case"CountrySelect":case"SingleSelect":case"RadioButton":case"MultiSelect":case"MultiCheckbox":renderSelectTemplates(e,t);break;case"Textarea":case"AdvancedPassword":case"Password":case"Text":case"Email":case"Url":case"Telephone":case"Number":case"DatePicker":case"Date":renderSimpleTemplateWithValidators(e,t);break;case"Fieldset":case"GridRow":case"SummaryPage":case"Page":case"StaticText":case"Hidden":case"ContentElement":renderSimpleTemplate(e,t)}getPublisherSubscriber().publish("view/stage/abstract/render/template/perform",[e,t])}function renderNestedSortableListItem(e){let t,n;const r=$("<li></li>");getFormElementDefinition(e,"_isCompositeFormElement")||r.addClass(getHelper().getDomElementClassName("noNesting")),getFormElementDefinition(e,"_isTopLevelFormElement")&&r.addClass(getHelper().getDomElementClassName("formElementIsTopLevel")),getFormElementDefinition(e,"_isCompositeFormElement")&&r.addClass(getHelper().getDomElementClassName("formElementIsComposit"));try{n=getHelper().getTemplate("FormElement-"+e.get("type")).clone()}catch{n=getHelper().getTemplate("FormElement-_UnknownElement").clone(),assert(n.length>0,'No template found for element "'+e.get("__identifierPath")+'"',1478987818)}n=$("<div></div>").attr(getHelper().getDomElementDataAttribute("elementIdentifier"),e.get("__identifierPath")).append($(n.html())),getFormElementDefinition(e,"_isCompositeFormElement")&&n.attr(getHelper().getDomElementDataAttribute("abstractType"),"isCompositeFormElement"),getFormElementDefinition(e,"_isTopLevelFormElement")&&n.attr(getHelper().getDomElementDataAttribute("abstractType"),"isTopLevelFormElement"),r.append(n),renderTemplateDispatcher(e,n);const o=e.get("renderables");if(t=null,"array"===$.type(o)){t=$("<ol></ol>"),t.addClass(getHelper().getDomElementClassName("sortable"));for(let e=0,n=o.length;e<n;++e)t.append(renderNestedSortableListItem(o[e]))}return t&&r.append(t),r}function addSortableEvents(){const e=stageDomElement.get(0).querySelectorAll("ol."+getHelper().getDomElementClassName("sortable")),t="li:not("+getHelper().getDomElementDataAttribute("noSorting","bracesWithKey")+")",n="div"+getHelper().getDomElementDataAttribute("elementIdentifier","bracesWithKey");e.forEach((function(e){e.querySelectorAll(n).forEach((function(e){e.classList.add("form-sortable-handle")})),new Sortable(e,{group:"stage-nodes",handle:n,draggable:t,animation:200,swapThreshold:.6,dragClass:"form-sortable-drag",ghostClass:"form-sortable-ghost",onStart:function(e){getPublisherSubscriber().publish("view/stage/abstract/dnd/start",[$(e.item),$(e.item)])},onChange:function(e){let t;const n=getAbstractViewParentFormElementIdentifierPathWithinDomElement($(e.item));n&&(t=getFormEditorApp().findEnclosingCompositeFormElementWhichIsNotOnTopLevel(n)),getPublisherSubscriber().publish("view/stage/abstract/dnd/change",[$(e.item),n,t])},onEnd:function(e){const t=getAbstractViewFormElementIdentifierPathWithinDomElement($(e.item)),n=getAbstractViewSiblingFormElementIdentifierPathWithinDomElement($(e.item),"prev"),r=getAbstractViewSiblingFormElementIdentifierPathWithinDomElement($(e.item),"next");getPublisherSubscriber().publish("view/stage/abstract/dnd/update",[$(e.item),t,n,r]),getPublisherSubscriber().publish("view/stage/abstract/dnd/stop",[getAbstractViewFormElementIdentifierPathWithinDomElement($(e.item))])}})}))}export function getStageDomElement(){return stageDomElement}export function buildTitleByFormElement(e){getUtility().isUndefinedOrNull(e)&&(e=getRootFormElement()),assert("object"===$.type(e),'Invalid parameter "formElement"',1479037151);const t=document.createElement("span");return t.textContent=e.get("label")?e.get("label"):e.get("identifier"),t}export function setStageHeadline(e){getUtility().isUndefinedOrNull(e)&&(e=buildTitleByFormElement().textContent),$(getHelper().getDomElementDataIdentifierSelector("stageHeadline")).text(e)}export function getStagePanelDomElement(){return $(getHelper().getDomElementDataIdentifierSelector("stagePanel"))}export function renderPagination(){const e=getRootFormElement().get("renderables").length;getViewModel().enableButton($(getHelper().getDomElementDataIdentifierSelector("buttonPaginationPrevious"))),getViewModel().enableButton($(getHelper().getDomElementDataIdentifierSelector("buttonPaginationNext"))),0===getFormEditorApp().getCurrentlySelectedPageIndex()&&getViewModel().disableButton($(getHelper().getDomElementDataIdentifierSelector("buttonPaginationPrevious"))),1!==e&&getFormEditorApp().getCurrentlySelectedPageIndex()!==e-1||getViewModel().disableButton($(getHelper().getDomElementDataIdentifierSelector("buttonPaginationNext")));const t=getFormEditorApp().getCurrentlySelectedPageIndex()+1;$(getHelper().getDomElementDataIdentifierSelector("paginationTitle")).text(getFormElementDefinition(getRootFormElement(),"paginationTitle").replace("{0}",t.toString()).replace("{1}",e))}export function renderUndoRedo(){getViewModel().enableButton($(getHelper().getDomElementDataIdentifierSelector("buttonHeaderUndo"))),getViewModel().enableButton($(getHelper().getDomElementDataIdentifierSelector("buttonHeaderRedo"))),getFormEditorApp().getCurrentApplicationStatePosition()+1>=getFormEditorApp().getCurrentApplicationStates()&&getViewModel().disableButton($(getHelper().getDomElementDataIdentifierSelector("buttonHeaderUndo"))),0===getFormEditorApp().getCurrentApplicationStatePosition()&&getViewModel().disableButton($(getHelper().getDomElementDataIdentifierSelector("buttonHeaderRedo")))}export function getAllFormElementDomElements(){return $(getHelper().getDomElementDataAttribute("elementIdentifier","bracesWithKey"),stageDomElement)}export function renderFormDefinitionPageAsSortableList(e){return assert("number"===$.type(e),'Invalid parameter "pageIndex"',1478721208),$("<ol></ol>").append(renderNestedSortableListItem(getRootFormElement().get("renderables")[e]))}export function getAbstractViewParentFormElementWithinDomElement(e){return $(e).parent().closest("li").find(getHelper().getDomElementDataAttribute("elementIdentifier","bracesWithKey")).first()}export function getAbstractViewParentFormElementIdentifierPathWithinDomElement(e){return getAbstractViewParentFormElementWithinDomElement(e).attr(getHelper().getDomElementDataAttribute("elementIdentifier"))}export function getAbstractViewFormElementWithinDomElement(e){return $(e).find(getHelper().getDomElementDataAttribute("elementIdentifier","bracesWithKey")).first()}export function getAbstractViewFormElementIdentifierPathWithinDomElement(e){return getAbstractViewFormElementWithinDomElement($(e)).attr(getHelper().getDomElementDataAttribute("elementIdentifier"))}export function getAbstractViewSiblingFormElementIdentifierPathWithinDomElement(e,t){getUtility().isUndefinedOrNull(t)&&(t="prev");const n=getAbstractViewFormElementIdentifierPathWithinDomElement(e);return(e="prev"===t?$(e).prev("li"):$(e).next("li")).find(getHelper().getDomElementDataAttribute("elementIdentifier","bracesWithKey")).not(getHelper().getDomElementDataAttribute("elementIdentifier","bracesWithKeyValue",[n])).first().attr(getHelper().getDomElementDataAttribute("elementIdentifier"))}export function getAbstractViewFormElementDomElement(e){let t;return t="string"==typeof e?e:getUtility().isUndefinedOrNull(e)?getCurrentlySelectedFormElement().get("__identifierPath"):e.get("__identifierPath"),$(getHelper().getDomElementDataAttribute("elementIdentifier","bracesWithKeyValue",[t]),stageDomElement)}export function removeAllStageToolbars(){$(getHelper().getDomElementDataIdentifierSelector("abstractViewToolbar"),stageDomElement).off().empty().remove()}export function createAbstractViewFormElementToolbar(e){let t;assert("object"===$.type(e),'Invalid parameter "formElement"',1479035778);const n=getFormElementDefinition(e,void 0);return n._isTopLevelFormElement?$():(t=getHelper().getTemplate("FormElement-_ElementToolbar").clone(),t.length?(t=$($(t.html())),getHelper().getTemplatePropertyDomElement("_type",t).text(getFormElementDefinition(e,"label")),getHelper().getTemplatePropertyDomElement("_identifier",t).text(e.get("identifier")),n._isCompositeFormElement?(getViewModel().hideComponent($(getHelper().getDomElementDataIdentifierSelector("abstractViewToolbarNewElement"),t)),$(getHelper().getDomElementDataIdentifierSelector("abstractViewToolbarNewElementSplitButtonAfter"),t).on("click",(function(){getPublisherSubscriber().publish("view/stage/abstract/elementToolbar/button/newElement/clicked",["view/insertElements/perform/after",{disableElementTypes:[],onlyEnableElementTypes:[]}])})),$(getHelper().getDomElementDataIdentifierSelector("abstractViewToolbarNewElementSplitButtonInside"),t).on("click",(function(){getPublisherSubscriber().publish("view/stage/abstract/elementToolbar/button/newElement/clicked",["view/insertElements/perform/inside",{disableElementTypes:[],onlyEnableElementTypes:[]}])}))):(getViewModel().hideComponent($(getHelper().getDomElementDataIdentifierSelector("abstractViewToolbarNewElementSplitButton"),t)),$(getHelper().getDomElementDataIdentifierSelector("abstractViewToolbarNewElement"),t).on("click",(function(){getPublisherSubscriber().publish("view/stage/abstract/elementToolbar/button/newElement/clicked",["view/insertElements/perform/after",{disableElementTypes:[]}])}))),$(getHelper().getDomElementDataIdentifierSelector("abstractViewToolbarRemoveElement"),t).on("click",(function(){getViewModel().showRemoveFormElementModal()})),t):$())}export function createAndAddAbstractViewFormElementToolbar(e,t,n){getUtility().isUndefinedOrNull(t)&&(t=getCurrentlySelectedFormElement()),n?createAbstractViewFormElementToolbar(t).fadeOut(0,(function(){e.prepend($(this)),$(getHelper().getDomElementDataIdentifierSelector("abstractViewToolbar"),e).fadeIn("fast")})):e.prepend(createAbstractViewFormElementToolbar(t))}export function renderAbstractStageArea(e,t){getUtility().isUndefinedOrNull(e)&&(e=getFormEditorApp().getCurrentlySelectedPageIndex()),stageDomElement.off().empty().append(renderFormDefinitionPageAsSortableList(e)),stageDomElement.on("click",(function(e){const t=$(e.target).closest(getHelper().getDomElementDataAttribute("elementIdentifier","bracesWithKey")).attr(getHelper().getDomElementDataAttribute("elementIdentifier"));!getUtility().isUndefinedOrNull(t)&&getUtility().isNonEmptyString(t)&&getPublisherSubscriber().publish("view/stage/element/clicked",[t])})),configuration.isSortable&&addSortableEvents(),"function"===$.type(t)&&t()}export function renderPreviewStageArea(e){assert(getUtility().isNonEmptyString(e),'Invalid parameter "html"',1475424409),stageDomElement.off().empty().html(e),$(":input",stageDomElement).prop("disabled","disabled").on("click dblclick select focus keydown keypress keyup mousedown mouseup",(function(e){return e.preventDefault()})),$("form",stageDomElement).submit((function(e){return e.preventDefault()})),getAllFormElementDomElements().each((function(){const e=getFormEditorApp().getFormElementByIdentifierPath($(this).data("elementIdentifierPath"));getFormElementDefinition(e,"_isTopLevelFormElement")||$(this).attr("title","identifier: "+e.get("identifier")+" (type: "+e.get("type")+")"),getFormElementDefinition(e,"_isTopLevelFormElement")&&$(this).addClass(getHelper().getDomElementClassName("formElementIsTopLevel")),getFormElementDefinition(e,"_isCompositeFormElement")&&$(this).addClass(getHelper().getDomElementClassName("formElementIsComposit"))}))}export function eachTemplateProperty(e,t,n){$(getHelper().getDomElementDataAttribute("templateProperty","bracesWithKey"),t).each((function(t,r){const o=$(r).attr(getHelper().getDomElementDataAttribute("templateProperty")),l=e.get(o);"function"===$.type(n)&&n(o,l,r)}))}export function renderCheckboxTemplate(e,t){renderSimpleTemplateWithValidators(e,t),eachTemplateProperty(e,t,(function(e,t,n){("boolean"===$.type(t)&&t||"true"===t||1===t||"1"===t)&&$(n).addClass(getHelper().getDomElementClassName("noNesting"))}))}export function renderSimpleTemplate(e,t){assert("object"===$.type(e),'Invalid parameter "formElement"',1479035696),eachTemplateProperty(e,t,((e,t,n)=>{setTemplateTextContent(n,t)})),Icons.getIcon(getFormElementDefinition(e,"iconIdentifier"),Icons.sizes.small,null,Icons.states.default,Icons.markupIdentifiers.inline).then((function(e){$(getHelper().getDomElementDataIdentifierSelector("formElementIcon"),t).append($(e).addClass(getHelper().getDomElementClassName("icon")))})),getHelper().getTemplatePropertyDomElement("_type",t).append(document.createTextNode(getFormElementDefinition(e,"label"))),getHelper().getTemplatePropertyDomElement("_identifier",t).append(document.createTextNode(e.get("identifier")))}export function renderSimpleTemplateWithValidators(e,t){assert("object"===$.type(e),'Invalid parameter "formElement"',1479035674),renderSimpleTemplate(e,t);const n=$(getHelper().getDomElementDataIdentifierSelector("validatorsContainer"),$(t)).clone();$(getHelper().getDomElementDataIdentifierSelector("validatorsContainer"),$(t)).empty();const r=e.get("validators");if("array"===$.type(r)){let e=0;if(r.length>0){for(let o=0,l=r.length;o<l;++o){if("NotEmpty"===r[o].identifier){getHelper().getTemplatePropertyDomElement("_required",t).text("*");continue}e++;const l=getFormEditorApp().getFormEditorDefinition("validators",r[o].identifier),i=$($(n).clone());getHelper().getTemplatePropertyDomElement("_label",i).append(document.createTextNode(l.label)),$(getHelper().getDomElementDataIdentifierSelector("validatorsContainer"),$(t)).append(i.html())}e>0&&Icons.getIcon(getHelper().getDomElementDataAttributeValue("iconValidator"),Icons.sizes.small,null,Icons.states.default,Icons.markupIdentifiers.inline).then((function(e){$(getHelper().getDomElementDataIdentifierSelector("validatorIcon"),$(t)).append($(e).addClass(getHelper().getDomElementClassName("icon")))}))}}}export function renderSelectTemplates(e,t){const n=$(getHelper().getDomElementDataIdentifierSelector("multiValueContainer"),$(t)).clone();$(getHelper().getDomElementDataIdentifierSelector("multiValueContainer"),$(t)).empty(),renderSimpleTemplateWithValidators(e,t);const r=$(getHelper().getDomElementDataIdentifierSelector("multiValueContainer"),$(t)).attr(getHelper().getDomElementDataAttribute("templateProperty")),o=e.get(r),l=(e,r,o)=>{let l=!1;const i=$($(n).clone());for(const e of Object.keys(o))if(o[e]===r){l=!0;break}getHelper().getTemplatePropertyDomElement("_label",i).append(document.createTextNode(e)),l&&getHelper().getTemplatePropertyDomElement("_label",i).addClass(getHelper().getDomElementClassName("selected")),$(getHelper().getDomElementDataIdentifierSelector("multiValueContainer"),$(t)).append(i.html())};let i=e.get("defaultValue");if(getFormEditorApp().getUtility().isUndefinedOrNull(i)?i={}:"string"===$.type(i)&&(i={0:i}),"object"===$.type(o))for(const e of Object.keys(o))l(o[e],e,i);else if("array"===$.type(o))for(const e of Object.keys(o))getUtility().isUndefinedOrNull(o[e]._label)?l(o[e],e,i):l(o[e]._label,o[e]._value,i)}export function renderFileUploadTemplates(e,t){const n=$(getHelper().getDomElementDataIdentifierSelector("multiValueContainer"),$(t)).clone();$(getHelper().getDomElementDataIdentifierSelector("multiValueContainer"),$(t)).empty(),renderSimpleTemplateWithValidators(e,t);const r=$(getHelper().getDomElementDataIdentifierSelector("multiValueContainer"),$(t)).attr(getHelper().getDomElementDataAttribute("templateProperty")),o=e.get(r),l=function(e){const r=$($(n).clone());getHelper().getTemplatePropertyDomElement("_value",r).append(e),$(getHelper().getDomElementDataIdentifierSelector("multiValueContainer"),$(t)).append(r.html())};if("object"===$.type(o))for(const e of Object.keys(o))l(o[e]);else if("array"===$.type(o))for(let e=0,t=o.length;e<t;++e)l(o[e])}export function bootstrap(e,t,n){return formEditorApp=e,assert("object"===$.type(t),'Invalid parameter "appendToDomElement"',1478992119),stageDomElement=$(t),configuration=$.extend(!0,defaultConfiguration,n||{}),Helper.bootstrap(formEditorApp),this}