/*
 * 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{MessageUtility as R}from"@typo3/backend/utility/message-utility.js";import{AjaxDispatcher as q}from"@typo3/backend/form-engine/inline-relation/ajax-dispatcher.js";import F from"nprogress";import j from"@typo3/backend/form-engine.js";import f from"@typo3/backend/form-engine-validation.js";import E from"@typo3/backend/modal.js";import w from"@typo3/backend/notification.js";import x from"@typo3/core/document-service.js";import h from"@typo3/core/event/regular-event.js";import O from"@typo3/backend/severity.js";import v from"@typo3/backend/utility.js";import{selector as b}from"@typo3/core/literals.js";var u;(function(c){c.toggleSelector='[data-bs-toggle="formengine-inline"]',c.controlSectionSelector=".t3js-formengine-irre-control",c.createNewRecordButtonSelector=".t3js-create-new-button",c.createNewRecordBySelectorSelector=".t3js-create-new-selector",c.deleteRecordButtonSelector=".t3js-editform-delete-inline-record",c.createNewRecordPresetSelector=".t3js-create-new-preset"})(u||(u={}));var p;(function(c){c.new="inlineIsNewRecord",c.visible="panel-visible",c.collapsed="panel-collapsed",c.notLoaded="t3js-not-loaded"})(p||(p={}));var g;(function(c){c.structureSeparator="-"})(g||(g={}));class s extends HTMLElement{constructor(){super(...arguments),this.container=null,this.ajaxDispatcher=null,this.requestQueue={},this.progressQueue={},this.handlePostMessage=e=>{if(!R.verifyOrigin(e.origin))throw"Denied message sent by "+e.origin;if(e.data.actionName==="typo3:foreignRelation:insert"){if(typeof e.data.objectGroup>"u")throw"No object group defined for message";if(e.data.objectGroup!==this.container.dataset.objectGroup)return;if(this.isUniqueElementUsed(parseInt(e.data.uid,10))){w.error("There is already a relation to the selected element");return}this.importRecord([e.data.objectGroup,e.data.uid]).then(()=>{if(e.source){const t={actionName:"typo3:foreignRelation:inserted",objectGroup:e.data.objectId,table:e.data.table,uid:e.data.uid};R.send(t,e.source)}})}if(e.data.actionName==="typo3:foreignRelation:delete"){if(e.data.objectGroup!==this.container.dataset.objectGroup)return;const t=e.data.directRemoval||!1,o=[e.data.objectGroup,e.data.uid].join("-");this.deleteRecord(o,t)}}}static getInlineRecordContainer(e){return document.querySelector(b`[data-object-id="${e}"]`)}static getValuesFromHashMap(e){return Object.keys(e).map(t=>e[t])}static selectOptionValueExists(e,t){return e.querySelector(b`option[value="${t}"]`)!==null}static removeSelectOptionByValue(e,t){const o=e.querySelector(b`option[value="${t}"]`);o!==null&&o.remove()}static reAddSelectOption(e,t,o){if(s.selectOptionValueExists(e,t))return;const r=e.querySelectorAll("option");let i=-1;for(const a of Object.keys(o.possible)){if(a===t)break;for(let l=0;l<r.length;++l)if(r[l].value===a){i=l;break}}i===-1?i=1:i<r.length&&i++;const n=document.createElement("option");n.text=o.possible[t],n.value=t,e.insertBefore(n,e.options[i])}static collapseExpandRecord(e){const t=s.getInlineRecordContainer(e),o=document.querySelector(b`[aria-controls="${e}_fields"]`);t.classList.contains(p.collapsed)?(t.classList.remove(p.collapsed),t.classList.add(p.visible),o.setAttribute("aria-expanded","true")):(t.classList.remove(p.visible),t.classList.add(p.collapsed),o.setAttribute("aria-expanded","false"))}async connectedCallback(){const e=this.getAttribute("identifier")||"";await x.ready(),this.container=this.querySelector(b`#${e}`),this.container!==null&&(this.ajaxDispatcher=new q(this.container.dataset.objectGroup),this.registerEvents())}registerEvents(){this.registerCreateRecordButton(),this.registerCreateRecordByPresetSelector(),this.registerCreateRecordBySelector(),this.registerRecordToggle(),this.registerDeleteButton(),new h("message",this.handlePostMessage).bindTo(window)}registerCreateRecordButton(){new h("click",(e,t)=>{e.preventDefault(),e.stopImmediatePropagation();let o=this.container.dataset.objectGroup;typeof t.dataset.recordUid<"u"&&(o+=g.structureSeparator+t.dataset.recordUid),this.importRecord([o],t.dataset.recordUid??null)}).delegateTo(this.container,u.createNewRecordButtonSelector)}registerCreateRecordByPresetSelector(){new h("change",(e,t)=>{e.preventDefault(),e.stopImmediatePropagation();const o=this.container.querySelector(u.createNewRecordPresetSelector),r=o?.value;if(r==="")return;let i=this.container.dataset.objectGroup;typeof t.dataset.recordUid<"u"&&(i+=g.structureSeparator+t.dataset.recordUid),o.value="",this.importRecord([i,"",r],t.dataset.recordUid??null)}).delegateTo(this.container,u.createNewRecordPresetSelector)}registerCreateRecordBySelector(){new h("change",(e,t)=>{e.preventDefault(),e.stopImmediatePropagation();const o=t,r=o.options[o.selectedIndex].getAttribute("value");r!==""&&this.importRecord([this.container.dataset.objectGroup,r])}).delegateTo(this.container,u.createNewRecordBySelectorSelector)}registerRecordToggle(){new h("click",(e,t)=>{e.preventDefault(),e.stopImmediatePropagation(),this.loadRecordDetails(t.closest(u.toggleSelector).parentElement.dataset.objectId)}).delegateTo(this.container,`${u.toggleSelector} .form-irre-header-cell:not(${u.controlSectionSelector}`)}registerDeleteButton(){new h("click",(e,t)=>{e.preventDefault(),e.stopImmediatePropagation();const o=TYPO3.lang["label.confirm.delete_record.title"]||"Delete this record?",r=(TYPO3.lang["label.confirm.delete_record.content"]||"Are you sure you want to delete the record '%s'?").replace("%s",t.dataset.recordInfo);E.confirm(o,r,O.warning,[{text:TYPO3.lang["buttons.confirm.delete_record.no"]||"Cancel",active:!0,btnClass:"btn-default",name:"no",trigger:(i,n)=>n.hideModal()},{text:TYPO3.lang["buttons.confirm.delete_record.yes"]||"Yes, delete this record",btnClass:"btn-warning",name:"yes",trigger:(i,n)=>{this.deleteRecord(t.closest("[data-object-id]").dataset.objectId),n.hideModal()}}])}).delegateTo(this.container,u.deleteRecordButtonSelector)}createRecord(e,t,o=null,r=null){let i=this.container.dataset.objectGroup;o!==null?(i+=g.structureSeparator+o,s.getInlineRecordContainer(i).insertAdjacentHTML("afterend",t),this.memorizeAddRecord(e,o,r)):(document.getElementById(this.container.getAttribute("id")+"_records").insertAdjacentHTML("beforeend",t),this.memorizeAddRecord(e,null,r))}async importRecord(e,t){return this.ajaxDispatcher.send(this.ajaxDispatcher.newRequest(this.ajaxDispatcher.getEndpoint("site_configuration_inline_create")),e).then(async o=>{this.createRecord(o.compilerInput.uid,o.data,typeof t<"u"?t:null,typeof o.compilerInput.childChildUid<"u"?o.compilerInput.childChildUid:null)})}loadRecordDetails(e){const t=document.getElementById(e+"_fields"),o=s.getInlineRecordContainer(e),r=typeof this.requestQueue[e]<"u";if(!(t!==null&&!o.classList.contains(p.notLoaded))){const n=this.getProgress(e,o.dataset.objectIdHash);if(r)this.requestQueue[e].abort(),delete this.requestQueue[e],delete this.progressQueue[e],n.done();else{const a=this.ajaxDispatcher.newRequest(this.ajaxDispatcher.getEndpoint("site_configuration_inline_details"));this.ajaxDispatcher.send(a,[e]).then(async m=>{delete this.requestQueue[e],delete this.progressQueue[e],o.classList.remove(p.notLoaded),t.innerHTML=m.data,s.collapseExpandRecord(e),n.done(),j.reinitialize(),f.initializeInputFields(),f.validate(this.container),this.removeUsed(s.getInlineRecordContainer(e))}),this.requestQueue[e]=a,n.start()}return}s.collapseExpandRecord(e)}memorizeAddRecord(e,t=null,o=null){const r=this.getFormFieldForElements();if(r===null)return;let i=v.trimExplode(",",r.value);if(t){const n=[];for(let a=0;a<i.length;a++)i[a].length&&n.push(i[a]),t===i[a]&&n.push(e);i=n}else i.push(e);r.value=i.join(","),f.markFieldAsChanged(r),document.dispatchEvent(new Event("change")),this.setUnique(e,o),j.reinitialize(),f.initializeInputFields(),f.validate(this.container)}memorizeRemoveRecord(e){const t=this.getFormFieldForElements();if(t===null)return[];const o=v.trimExplode(",",t.value),r=o.indexOf(e);return r>-1&&(o.splice(r,1),t.value=o.join(","),f.markFieldAsChanged(t),document.dispatchEvent(new Event("change"))),o}deleteRecord(e,t=!1){const o=s.getInlineRecordContainer(e),r=o.dataset.objectUid;if(o.classList.add("t3js-inline-record-deleted"),!o.classList.contains(p.new)&&!t){const i=this.container.querySelector(b`[name="cmd${o.dataset.fieldName}[delete]"]`);i.removeAttribute("disabled"),o.parentElement.insertAdjacentElement("afterbegin",i)}new h("transitionend",()=>{o.remove(),f.validate(this.container)}).bindTo(o),this.revertUnique(r),this.memorizeRemoveRecord(r),o.classList.add("form-irre-object--deleted")}getProgress(e,t){const o="#"+t+"_header";let r;return typeof this.progressQueue[e]<"u"?r=this.progressQueue[e]:(r=F,r.configure({parent:o,showSpinner:!1}),this.progressQueue[e]=r),r}getFormFieldForElements(){const e=document.getElementsByName(this.container.dataset.formField);return e.length>0?e[0]:null}isUniqueElementUsed(e){const t=TYPO3.settings.FormEngineInline.unique[this.container.dataset.objectGroup];return s.getValuesFromHashMap(t.used).indexOf(e)!==-1}removeUsed(e){const t=TYPO3.settings.FormEngineInline.unique[this.container.dataset.objectGroup],o=s.getValuesFromHashMap(t.used),r=e.querySelector('[name="data['+t.table+"]["+e.dataset.objectUid+"]["+t.field+']"]');if(r!==null){const i=r.options[r.selectedIndex].value;for(const n of o)n!==i&&s.removeSelectOptionByValue(r,n)}}setUnique(e,t){const o=TYPO3.settings.FormEngineInline.unique[this.container.dataset.objectGroup],r=document.getElementById(this.container.dataset.objectGroup+"_selector");if(o.max!==-1){const i=this.getFormFieldForElements(),n=this.container.dataset.objectGroup+g.structureSeparator+e;let l=s.getInlineRecordContainer(n).querySelector('[name="data['+o.table+"]["+e+"]["+o.field+']"]');const m=s.getValuesFromHashMap(o.used);if(r!==null){if(l!==null)for(const d of m)s.removeSelectOptionByValue(l,d);for(const d of m)s.removeSelectOptionByValue(l,d);typeof o.used.length<"u"&&(o.used={}),o.used[e]={table:o.elTable,uid:t}}if(i!==null&&s.selectOptionValueExists(r,t)){const d=v.trimExplode(",",i.value);for(const y of d)l=document.querySelector('[name="data['+o.table+"]["+y+"]["+o.field+']"]'),l!==null&&y!==e&&s.removeSelectOptionByValue(l,t)}}s.selectOptionValueExists(r,t)&&(s.removeSelectOptionByValue(r,t),o.used[e]={table:o.elTable,uid:t})}revertUnique(e){const t=TYPO3.settings.FormEngineInline.unique[this.container.dataset.objectGroup],o=this.container.dataset.objectGroup+g.structureSeparator+e,r=s.getInlineRecordContainer(o),i=r.querySelector('[name="data['+t.table+"]["+r.dataset.objectUid+"]["+t.field+']"]');let n;if(i!==null)n=i.value;else if(r.dataset.tableUniqueOriginalValue!=="")n=r.dataset.tableUniqueOriginalValue.replace(t.table+"_","");else return;if(n!=="9223372036854775807"){const d=document.getElementById(this.container.dataset.objectGroup+"_selector");s.reAddSelectOption(d,n,t)}if(t.max===-1)return;const a=this.getFormFieldForElements();if(a===null)return;const l=v.trimExplode(",",a.value);let m;for(let d=0;d<l.length;d++)m=document.querySelector('[name="data['+t.table+"]["+l[d]+"]["+t.field+']"]'),m!==null&&s.reAddSelectOption(m,n,t);delete t.used[e]}}window.customElements.define("typo3-formengine-container-sitelanguage",s);
