/*
 * 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 T from"@typo3/core/document-service.js";import D from"@typo3/backend/form-engine-validation.js";import p from"@typo3/backend/modal.js";import*as j from"@typo3/backend/utility/message-utility.js";import w from"@typo3/backend/severity.js";import*as P from"@typo3/backend/backend-exception.js";import I from"@typo3/backend/event/interaction-request-map.js";import N from"@typo3/backend/utility.js";import{selector as y}from"@typo3/core/literals.js";import"@typo3/backend/form-engine/element/extra/char-counter.js";import M,{ModifierKeys as O}from"@typo3/backend/hotkeys.js";import v from"@typo3/core/event/regular-event.js";import s from"~labels/backend.alt_doc";import _ from"~labels/core.core";var C;(function(E){E.save="_savedok",E.saveAndClose="_saveandclosedok",E.saveAndView="_savedokview",E.saveAndNew="_savedoknew",E.duplicate="_duplicatedoc"})(C||(C={}));var z=function(){function E(t,n){n?e.interactionRequestMap.resolveFor(t):e.interactionRequestMap.rejectFor(t)}const k=new Map;k.set("typo3-backend-form-update-value",t=>{const n=document.querySelector(y`[name="${t.elementName}"]`),a=document.querySelector(y`[data-formengine-input-name="${t.elementName}"]`);e.Validation.updateInputField(t.elementName),n!==null&&(e.markFieldAsChanged(n),e.Validation.validateField(n)),a!==null&&a!==n&&e.Validation.validateField(a)}),k.set("typo3-backend-form-reload",t=>{const n=()=>{e.Validation.suspend(),e.saveDocument(),e.Validation.resume()};if(!t.confirmation){n();return}const a=p.advanced({title:_.get("mess.refreshRequired.title"),content:_.get("mess.refreshRequired.content"),severity:w.warning,staticBackdrop:!0,buttons:[{text:_.get("mess.refreshRequired.cancel"),active:!0,btnClass:"btn-default",name:"cancel",trigger:()=>{a.hideModal()}},{text:_.get("mess.refreshRequired.confirm"),btnClass:"btn-"+w.getCssClass(w.warning),name:"ok",trigger:()=>{e.closeModalsRecursive(),n()}}]})}),k.set("typo3-backend-form-update-bitmask",(t,n)=>{const a=n.target,o=e.formElement[t.elementName],i=a.checked!==t.invert,l=Math.pow(2,t.position),u=Math.pow(2,t.total)-l-1;o.value=i?o.value|l:o.value&u,o.dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0}))});let A=!1,q=null;const e={consumeTypes:["typo3.setUrl","typo3.beforeSetUrl","typo3.refresh"],Validation:D,interactionRequestMap:I,formName:"editform",formElement:void 0,openedPopupWindow:null,browserUrl:""};Object.defineProperty(e,"formElement",{get:()=>document.forms.namedItem(e.formName),enumerable:!0,configurable:!1}),e.ready=async function(){return q??(q=async function(){A||await new Promise(n=>e.formElement.addEventListener("typo3:form-engine:ready",()=>n(),{once:!0}))}())},e.openPopupWindow=function(t,n,a,o,i,l,u){const c={mode:t};return n&&(c.fieldReference=n),a&&(c.allowedTypes=a),o&&(c.disallowedFileExtensions=o),i&&(c.irreObjectId=i),l&&(t==="db"?c.expandPage=l:c.expandFolder=l),c.useEvents=u?"1":"0",p.advanced({type:p.types.iframe,content:e.browserUrl+"&"+new URLSearchParams(c).toString(),size:p.sizes.large})},e.setSelectOptionFromExternalSource=function(t,n,a,o,i=[],l=void 0){let u=!1,c=!1,r=e.getFieldElement(t);const m=r;if(m===null||n==="--div--"||m instanceof HTMLOptGroupElement)return;const f=e.getFieldElement(t,"_list",!0);if(f!==null&&(r=f,u=r.multiple&&r.size!==1,c=!0),u||c){const h=e.getFieldElement(t,"_avail");if(h===null)return;if(!u){for(const d of r.querySelectorAll("option")){const b=h.querySelector(y`option[value="${d.value}"]`);b!==null&&(b.classList.remove("hidden"),b.disabled=!1,e.enableOptGroup(b))}r.replaceChildren()}if(i.length>0){let d=!1;const b=r.querySelectorAll("option");(i.includes(n)||b.length===1&&i.includes(b[0].value))&&(r.replaceChildren(),d=!0),d&&typeof l<"u"&&l.closest("select").querySelectorAll("[disabled]").forEach(function(x){x.classList.remove("hidden"),x.disabled=!1,e.enableOptGroup(x)})}let g=!0;const S=e.getFieldElement(t,"_mul",!0);if(S===null||Number(S.value)===0){for(const d of r.querySelectorAll("option"))if(d.value===n){g=!1;break}if(g&&typeof l<"u"){l.classList.add("hidden"),l.disabled=!0;const d=l.parentElement;d instanceof HTMLOptGroupElement&&d.querySelectorAll("option:not([disabled]):not([hidden]):not(.hidden)").length===0&&(d.disabled=!0,d.classList.add("hidden"))}}if(g){const d=document.createElement("option");d.value=n,d.title=o,d.text=a,r.append(d),e.updateHiddenFieldValueFromSelect(r,m),e.markFieldAsChanged(m),e.Validation.validateField(r),e.Validation.validateField(h)}}else{const h=/_(\d+)$/,g=n.toString().match(h);g!=null&&(n=g[1]),r.value=n,e.Validation.validateField(r)}},e.updateHiddenFieldValueFromSelect=function(t,n){const a=Array.from(t.options).map(o=>o.value);n.value=a.join(","),n.dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0}))},e.getFieldElement=function(t,n,a){if(n){let i;switch(n){case"_list":i=e.formElement.querySelector(y`:is(input, select, textarea)[data-formengine-input-name="${t}"]:not([type=hidden])`);break;case"_avail":i=e.formElement.querySelector(y`:is(input, select, textarea)[data-relatedfieldname="${t}"]`);break;case"_mul":i=e.formElement.querySelector(y`input[type=hidden][data-formengine-input-name="${t}"]`);break;default:i=null;break}if(i!==null||a===!0)return i}const o=e.formElement.elements.namedItem(t);return o instanceof HTMLElement?o:null},e.delegatesInitialized=!1,e.initializeDelegates=function(){e.delegatesInitialized||(new v("click",t=>{t.preventDefault(),e.preventExitIfNotSaved(e.preventExitIfNotSavedCallback)}).delegateTo(document,".t3js-editform-close"),new v("click",t=>{t.preventDefault(),e.previewAction(t,e.previewActionCallback)}).delegateTo(document,".t3js-editform-view"),new v("click",t=>{t.preventDefault(),e.newAction(t,e.newActionCallback)}).delegateTo(document,".t3js-editform-new"),new v("click",t=>{t.preventDefault(),e.duplicateAction(t,e.duplicateActionCallback)}).delegateTo(document,".t3js-editform-duplicate"),new v("click",t=>{t.preventDefault(),e.deleteAction(t,e.deleteActionCallback)}).delegateTo(document,".t3js-editform-delete-record"),new v("change",(t,n)=>{n.closest(".t3js-formengine-field-item").classList.toggle("disabled")}).delegateTo(document,'.t3-form-field-eval-null-checkbox input[type="checkbox"]'),new v("change",(t,n)=>{e.toggleCheckboxField(n),e.markFieldAsChanged(n)}).delegateTo(document,'.t3js-form-field-eval-null-placeholder-checkbox input[type="checkbox"]'),new v("click",(t,n)=>{t.preventDefault(),t.stopPropagation();const a=n.dataset.mode,o=n.dataset.fieldReference??"",i=n.dataset.allowedTypes??"",l=n.dataset.disallowedTypes??"",u=n.dataset.irreObjectId??"",c=n.dataset.entryPoint,r=n.dataset.useEvents==="true",m=e.openPopupWindow(a,o,i,l,u,c,r);r&&m.addEventListener("typo3:element-browser:message",f=>{const{actionName:h,close:g}=f.detail;if(h==="typo3:elementBrowser:elementAdded"){const{fieldName:S,value:d,label:b}=f.detail;e.setSelectOptionFromExternalSource(S,d,b||d,b||d)}g&&(m.hideModal(),n.focus())})}).delegateTo(document,".t3js-element-browser"),new v("click",(t,n)=>{const a=JSON.parse(n.dataset.formengineFieldChangeItems);e.processOnFieldChange(a,t)}).delegateTo(document,'[data-formengine-field-change-event="click"]'),new v("change",(t,n)=>{const a=JSON.parse(n.dataset.formengineFieldChangeItems);e.processOnFieldChange(a,t)}).delegateTo(document,'[data-formengine-field-change-event="change"]'),window.addEventListener("message",e.handlePostMessage),e.delegatesInitialized=!0)},e.initializeEvents=function(){top.TYPO3&&typeof top.TYPO3.Backend<"u"&&(top.TYPO3.Backend.consumerScope.attach(e),window.addEventListener("pagehide",()=>top.TYPO3.Backend.consumerScope.detach(e),{once:!0}))},e.consume=function(t){if(!t)throw new P.BackendException("No interaction request given",1496589980);let n;const a=new Promise((o,i)=>{n={resolve:o,reject:i}});if(t.concernsTypes(e.consumeTypes)){const o=t.outerMostRequest;e.interactionRequestMap.attachFor(o,n),o.isProcessed()?E(o,o.getProcessedData().response):e.hasChange()||e.isNew()?e.preventExitIfNotSaved(function(i){o.setProcessedData({response:i}),E(o,i)}):e.interactionRequestMap.resolveFor(o)}return a},e.handlePostMessage=function(t){if(!j.MessageUtility.verifyOrigin(t.origin))throw"Denied message sent by "+t.origin;if(t.data.actionName==="typo3:elementBrowser:elementAdded"){if(typeof t.data.fieldName>"u")throw"fieldName not defined in message";if(typeof t.data.value>"u")throw"value not defined in message";const n=t.data.label||t.data.value,a=t.data.title||n,o=N.trimExplode(",",t.data?.exclusiveValues??"");e.setSelectOptionFromExternalSource(t.data.fieldName,t.data.value,n,a,o)}},e.initializeRemainingCharacterViews=function(){document.querySelectorAll('[maxlength]:not([data-input-type="datetimepicker"]):not(.t3js-color-picker)').forEach(n=>{const a=n.closest(".t3js-formengine-field-item");if(a!==null&&a.querySelector("typo3-backend-formengine-char-counter")===null){const o=document.createElement("typo3-backend-formengine-char-counter");o.setAttribute("target",`[data-formengine-input-name="${y`${n.dataset.formengineInputName}`}"]`),a.append(o)}})},e.initializeMinimumCharactersLeftViews=function(){const t=(o,i)=>{const l=i.currentTarget.closest(".t3js-formengine-field-item"),u=l.querySelector(".t3js-charcounter-min"),c=_.get("labels.remainingCharacters",{0:o});if(u)u.querySelector("span").innerHTML=c;else{const r=document.createElement("div");r.classList.add("t3js-charcounter-min");const m=document.createElement("span");m.classList.add("badge","badge-danger"),m.innerHTML=c,r.append(m);let f=l.querySelector(".t3js-charcounter-wrapper");f||(f=document.createElement("div"),f.classList.add("t3js-charcounter-wrapper"),l.append(f)),f.prepend(r)}},n=o=>{const l=o.currentTarget.closest(".t3js-formengine-field-item").querySelector(".t3js-charcounter-min");l&&l.remove()};document.querySelectorAll('[minlength]:not([data-input-type="datetimepicker"]):not(.t3js-charcounter-min-initialized)').forEach(o=>{o.addEventListener("focus",i=>{const l=e.getMinCharacterLeftCount(o);l>0&&t(l,i)}),o.addEventListener("blur",n),o.addEventListener("keyup",i=>{const l=e.getMinCharacterLeftCount(o);l>0?t(l,i):n(i)})})},e.getMinCharacterLeftCount=function(t){const n=t.value,a=t.minLength,o=n.length;if(o===0)return 0;const i=(n.match(/\n/g)||[]).length;return a-o-i},e.initializeNullNoPlaceholderCheckboxes=function(){document.querySelectorAll(".t3-form-field-eval-null-checkbox").forEach(t=>{const n=t.querySelector('input[type="checkbox"]'),a=t.closest(".t3js-formengine-field-item");n.checked||a.classList.add("disabled")})},e.initializeNullWithPlaceholderCheckboxes=function(){document.querySelectorAll(".t3js-form-field-eval-null-placeholder-checkbox").forEach(t=>{e.toggleCheckboxField(t.querySelector('input[type="checkbox"]'),!1)})},e.toggleCheckboxField=function(t,n=!0){const a=t.closest(".t3js-formengine-field-item"),o=a.querySelector(".t3js-formengine-placeholder-placeholder"),i=a.querySelector(".t3js-formengine-placeholder-formfield");t.checked?(o.hidden=!0,i.hidden=!1,n&&i.querySelector("input,select,textarea")?.focus()):(o.hidden=!1,i.hidden=!0)},e.reinitialize=function(){const t=document.querySelectorAll(".t3js-clearable");t.length>0&&import("@typo3/backend/input/clearable.js").then(function(){t.forEach(n=>n.clearable())}),e.initializeNullNoPlaceholderCheckboxes(),e.initializeNullWithPlaceholderCheckboxes(),e.initializeLocalizationStateSelector(),e.initializeMinimumCharactersLeftViews(),e.initializeRemainingCharacterViews()},e.initializeLocalizationStateSelector=function(){document.querySelectorAll(".t3js-l10n-state-container").forEach(t=>{const n=t.closest(".t3js-formengine-field-item")?.querySelector("[data-formengine-input-name]");if(n==null)return;const a=t.querySelector('input[type="radio"]:checked')?.value;a===void 0&&console.warn("The localization state of the field "+n.dataset.formengineInputName+" cannot be determined. This smells like a DataHandler bug."),(a==="parent"||a==="source")&&(n.disabled=!0)})},e.hasChange=function(){const t=document.querySelector(y`form[name="${e.formName}"] .has-change`)!==null,n=document.querySelector('[name^="data["].has-change')!==null;return t||n},e.isNew=function(){return document.querySelector('form[name="'+e.formName+'"] .typo3-TCEforms.is-new')!==null},e.markFieldAsChanged=function(t){t.classList.add("has-change");const n=t.closest(".t3js-formengine-palette-field")?.querySelector(".t3js-formengine-label");n?.classList.add("has-change")},e.preventExitIfNotSavedCallback=()=>{e.closeDocument()},e.preventFollowLinkIfNotSaved=function(t){return e.preventExitIfNotSaved(function(){window.location.href=t}),!1},e.preventExitIfNotSaved=function(t){if(t=t||e.preventExitIfNotSavedCallback,e.hasChange()||e.isNew()){const n=s.get("label.confirm.close_without_save.title"),a=s.get("label.confirm.close_without_save.content"),o=[{text:s.get("buttons.confirm.close_without_save.no"),btnClass:"btn-default",name:"no"},{text:s.get("buttons.confirm.close_without_save.yes"),btnClass:"btn-default",name:"yes"}];document.querySelector(".has-error")===null&&o.push({text:s.get("buttons.confirm.save_and_close"),btnClass:"btn-primary",name:"save",active:!0});const i=p.confirm(n,a,w.warning,o);i.addEventListener("button.clicked",function(l){l.target.name==="no"?i.hideModal():l.target.name==="yes"?(i.hideModal(),t.call(null,!0)):l.target.name==="save"&&(i.hideModal(),e.saveAndCloseDocument())})}else t.call(null,!0)},e.preventSaveIfHasErrors=function(){if(document.querySelector(".has-error")!==null){const t=s.get("label.alert.save_with_error.title"),n=s.get("label.alert.save_with_error.content"),a=p.confirm(t,n,w.error,[{text:s.get("buttons.alert.save_with_error.ok"),btnClass:"btn-danger",name:"ok"}]);return a.addEventListener("button.clicked",function(o){o.target.name==="ok"&&a.hideModal()}),!1}return!0},e.processOnFieldChange=function(t,n){t.forEach(a=>{const o=k.get(a.name);o instanceof Function&&o.call(null,a.data||null,n)})},e.registerOnFieldChangeHandler=function(t,n){k.has(t)&&console.warn("Handler for onFieldChange name `"+t+"` has been overridden."),k.set(t,n)},e.closeModalsRecursive=function(){typeof p.currentModal<"u"&&p.currentModal!==null&&(p.currentModal.addEventListener("typo3-modal-hidden",function(){e.closeModalsRecursive()}),p.currentModal.hideModal())},e.enableDocHeaderButtons=function(){const t=document.querySelector(".t3js-module-docheader-buttons");t&&t.querySelectorAll('button, a, input[type="submit"]').forEach(n=>{n instanceof HTMLButtonElement||n instanceof HTMLInputElement?n.disabled=!1:n instanceof HTMLAnchorElement&&(n.classList.remove("disabled"),n.removeAttribute("aria-disabled"))})};const L=t=>{const n=document.createElement("input");return n.type="hidden",n.name=t,n.value="1",n};e.previewAction=function(t,n){n=n||e.previewActionCallback;const a=t.target.href,o="isNew"in t.target.dataset,i=L(C.saveAndView);e.hasChange()||e.isNew()?e.showPreviewModal(a,o,i,n):(e.formElement.append(i),window.open("","newTYPO3frontendWindow"),e.formElement.submit())},e.previewActionCallback=function(t,n,a){switch(p.dismiss(),t){case"discard":const o=window.open(n,"newTYPO3frontendWindow");o.focus(),N.urlsPointToSameServerSideResource(o.location.href,n)&&o.location.reload();break;case"save":e.formElement.append(a),window.open("","newTYPO3frontendWindow"),e.saveDocument();break;default:break}},e.showPreviewModal=function(t,n,a,o){const i=s.get("label.confirm.view_record_changed.title"),l={text:s.get("buttons.confirm.view_record_changed.cancel"),btnClass:"btn-default",name:"cancel"},u={text:s.get("buttons.confirm.view_record_changed.no-save"),btnClass:"btn-default",name:"discard"},c={text:s.get("buttons.confirm.view_record_changed.save"),btnClass:"btn-primary",name:"save",active:!0};let r=[],m=[];if(n){if(!e.Validation.isValid()){e.Validation.showErrorModal();return}r=[l,c],m=[s.get("label.confirm.view_record_changed.content.is-new-page")]}else r=[l,u],m=[s.get("label.confirm.view_record_changed.content")],e.Validation.isValid()?r.push(c):m.push(s.get("label.confirm.view_record_changed.invalid_form"));const f=document.createElement("p");m.forEach((g,S)=>{f.append(g),S!==m.length-1&&f.append(document.createElement("br"))});const h=p.confirm(i,f,w.info,r);h.addEventListener("button.clicked",function(g){o(g.target.name,t,a,h)})},e.newAction=function(t,n){n=n||e.newActionCallback;const a=L(C.saveAndNew),o="isNew"in t.target.dataset;e.hasChange()||e.isNew()?e.showNewModal(o,a,n):(e.formElement.append(a),e.formElement.submit())},e.newActionCallback=function(t,n){switch(p.dismiss(),t){case"no":e.formElement.append(n),e.formElement.submit();break;case"yes":e.formElement.append(n),e.saveDocument();break;default:break}},e.showNewModal=function(t,n,a){const o=s.get("label.confirm.new_record_changed.title"),i=s.get("label.confirm.new_record_changed.content");let l=[];const u={text:s.get("buttons.confirm.new_record_changed.cancel"),btnClass:"btn-default",name:"cancel"},c={text:s.get("buttons.confirm.new_record_changed.no"),btnClass:"btn-default",name:"no"},r={text:s.get("buttons.confirm.new_record_changed.yes"),btnClass:"btn-primary",name:"yes",active:!0};t?l=[u,r]:l=[u,c,r],p.confirm(o,i,w.info,l).addEventListener("button.clicked",function(f){a(f.target.name,n)})},e.duplicateAction=function(t,n){n=n||e.duplicateActionCallback;const a=L(C.duplicate),o="isNew"in t.target.dataset;e.hasChange()||e.isNew()?e.showDuplicateModal(o,a,n):(e.formElement.append(a),e.formElement.submit())},e.duplicateActionCallback=function(t,n){switch(p.dismiss(),t){case"no":e.formElement.append(n),e.formElement.submit();break;case"yes":e.formElement.append(n),e.saveDocument();break;default:break}},e.showDuplicateModal=function(t,n,a){const o=s.get("label.confirm.duplicate_record_changed.title"),i=s.get("label.confirm.duplicate_record_changed.content");let l=[];const u={text:s.get("buttons.confirm.duplicate_record_changed.cancel"),btnClass:"btn-default",name:"cancel"},c={text:s.get("button.confirm.duplicate_record_changed.no"),btnClass:"btn-default",name:"no"},r={text:s.get("buttons.confirm.duplicate_record_changed.yes"),btnClass:"btn-primary",name:"yes",active:!0};t?l=[u,r]:l=[u,c,r],p.confirm(o,i,w.info,l).addEventListener("button.clicked",function(f){a(f.target.name,n)})},e.deleteAction=function(t,n){n=n||e.deleteActionCallback;const a=t.target.closest(".t3js-editform-delete-record");e.showDeleteModal(a,n)},e.deleteActionCallback=function(t,n){p.dismiss(),t==="yes"&&e.invokeRecordDeletion(n)},e.showDeleteModal=function(t,n){const a=s.get("label.confirm.delete_record.title");let o=s.get("label.confirm.delete_record.content",[t.dataset.recordInfo]);t.dataset.referenceCountMessage&&(o+=`
`+t.dataset.referenceCountMessage),t.dataset.translationCountMessage&&(o+=`
`+t.dataset.translationCountMessage),p.confirm(a,o,w.warning,[{text:s.get("buttons.confirm.delete_record.no"),btnClass:"btn-default",name:"no"},{text:s.get("buttons.confirm.delete_record.yes"),btnClass:"btn-warning",name:"yes",active:!0}]).addEventListener("button.clicked",function(l){n(l.target.name,t)})},e.enableOptGroup=function(t){const n=t.parentElement;n instanceof HTMLOptGroupElement&&n.querySelectorAll("option:not([hidden]):not([disabled]):not(.hidden)").length&&(n.hidden=!1,n.disabled=!1,n.classList.remove("hidden"))},e.closeDocument=function(){e.formElement.closeDoc.value=1,e.formElement.submit()};const F=t=>{const n=document.activeElement;(n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement)&&n.blur();const a=document.querySelector(y`button[name="${t}"][form="${e.formElement.id}"]`);a!==null?e.formElement.requestSubmit(a):(e.formElement.append(L(t)),e.formElement.requestSubmit())};return e.saveDocument=function(){F(C.save)},e.saveAndCloseDocument=function(){F(C.saveAndClose)},e.initialize=function(t){e.browserUrl=t,e.initializeDelegates(),T.ready().then(()=>{e.initializeEvents(),e.Validation.initialize(this),e.reinitialize(),document.getElementById("t3js-ui-block")?.remove(),e.enableDocHeaderButtons(),e.formElement.dispatchEvent(new Event("typo3:form-engine:ready")),A=!0,M.setScope("backend/form-engine"),M.register([M.normalizedCtrlModifierKey,"s"],n=>{n.preventDefault(),e.saveDocument()},{scope:"backend/form-engine",allowOnEditables:!0}),M.register([M.normalizedCtrlModifierKey,O.SHIFT,"s"],n=>{n.preventDefault(),e.saveAndCloseDocument()},{scope:"backend/form-engine",allowOnEditables:!0})})},e.invokeRecordDeletion=function(t){window.location.href=t.href},TYPO3.FormEngine=e,e}();export{z as default};
