/*
 * 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 Icons from"@typo3/backend/icons.js";import PersistentStorage from"@typo3/backend/storage/persistent.js";import RegularEvent from"@typo3/core/event/regular-event.js";import DocumentService from"@typo3/core/document-service.js";import{default as Modal}from"@typo3/backend/modal.js";import{SeverityEnum}from"@typo3/backend/enum/severity.js";import Severity from"@typo3/backend/severity.js";import{MultiRecordSelectionSelectors}from"@typo3/backend/multi-record-selection.js";import{selector}from"@typo3/core/literals.js";class Recordlist{constructor(){this.identifier={entity:".t3js-entity",toggle:".t3js-toggle-recordlist",localize:".t3js-action-localize",editMultiple:".t3js-record-edit-multiple",icons:{collapse:"actions-view-list-collapse",expand:"actions-view-list-expand"}},this.toggleClick=(e,t)=>{e.preventDefault();const o=t.dataset.table,i=document.querySelector(t.dataset.bsTarget),n="expanded"===i.dataset.state,l=t.querySelector(".t3js-icon"),a=n?this.identifier.icons.expand:this.identifier.icons.collapse;Icons.getIcon(a,Icons.sizes.small).then((e=>{l.replaceWith(document.createRange().createContextualFragment(e))}));let r={};PersistentStorage.isset("moduleData.web_list.collapsedTables")&&(r=PersistentStorage.get("moduleData.web_list.collapsedTables"));const s={};s[o]=n?1:0,r=Object.assign(r,s),PersistentStorage.set("moduleData.web_list.collapsedTables",r).then((()=>{i.dataset.state=n?"collapsed":"expanded"}))},this.onEditMultiple=(e,t)=>{e.preventDefault();let o="",i="",n=[];const l=[];if("multiRecordSelection:action:edit"===e.type){const t=e.detail,a=t.configuration;if(i=a.returnUrl||"",n=a.columnsOnly||[],o=a.tableName||"",""===o)return;t.checkboxes.forEach((e=>{const t=e.closest(MultiRecordSelectionSelectors.elementSelector);null!==t&&t.dataset[a.idField]&&l.push(t.dataset[a.idField])}))}else{const e=t.closest("[data-table]");if(null===e)return;if(o=e.dataset.table||"",""===o)return;i=t.dataset.returnUrl||"",n=JSON.parse(t.dataset.columnsOnly||"{}");const a=e.querySelectorAll(this.identifier.entity+'[data-uid][data-table="'+o+'"] td.col-checkbox input[type="checkbox"]:checked');if(a.length)a.forEach((e=>{l.push(e.closest(this.identifier.entity+selector`[data-uid][data-table="${o}"]`).dataset.uid)}));else{const t=e.querySelectorAll(this.identifier.entity+selector`[data-uid][data-table="${o}"]`);if(!t.length)return;t.forEach((e=>{l.push(e.dataset.uid)}))}}if(!l.length)return;let a=top.TYPO3.settings.FormEngine.moduleUrl+"&edit["+o+"]["+l.join(",")+"]=edit&returnUrl="+Recordlist.getReturnUrl(i);n.length>0&&(a+=n.map(((e,t)=>"&columnsOnly["+o+"]["+t+"]="+e)).join("")),window.location.href=a},this.disableButton=(e,t)=>{t.setAttribute("disabled","disabled"),t.classList.add("disabled")},this.deleteRow=e=>{const t=document.querySelector(`table[data-table="${e.table}"]`),o=t.querySelector(`tr[data-uid="${e.uid}"]`),i=t.closest(".panel"),n=i.querySelector(".panel-heading");if([o,...t.querySelectorAll(`[data-l10nparent="${e.uid}"]`)].forEach((e=>{e?.remove()})),null===t.querySelector("tbody tr")&&i.remove(),"0"===o.dataset.l10nparent||""===o.dataset.l10nparent){const e=Number(n.querySelector(".t3js-table-total-items").textContent),t=n.querySelector(".t3js-table-total-items");null!==t&&(t.textContent=String(e-1))}"pages"===e.table&&top.document.dispatchEvent(new CustomEvent("typo3:pagetree:refresh"))},this.registerPaginationEvents=()=>{document.querySelectorAll(".t3js-recordlist-paging").forEach((e=>{e.addEventListener("keyup",(t=>{t.preventDefault();let o=Number(e.value);const i=Number(e.min),n=Number(e.max);if(i&&o<i&&(o=i),n&&o>n&&(o=n),e.value=o.toString(10),"Enter"===t.key&&o!==Number(e.dataset.currentpage)){const t=e.closest('form[name^="list-table-form-"]'),i=new URL(t.action,window.origin);i.searchParams.set("pointer",o.toString()),window.location.href=i.toString()}}))}))},new RegularEvent("click",this.toggleClick).delegateTo(document,this.identifier.toggle),new RegularEvent("click",this.onEditMultiple).delegateTo(document,this.identifier.editMultiple),new RegularEvent("click",this.disableButton).delegateTo(document,this.identifier.localize),DocumentService.ready().then((()=>{this.registerPaginationEvents()})),new RegularEvent("typo3:datahandler:process",this.handleDataHandlerResult.bind(this)).bindTo(document),new RegularEvent("multiRecordSelection:action:edit",this.onEditMultiple).bindTo(document),new RegularEvent("multiRecordSelection:action:delete",this.deleteMultiple).bindTo(document),new RegularEvent("multiRecordSelection:action:copyMarked",(e=>{Recordlist.submitClipboardFormWithCommand("copyMarked",e.target)})).bindTo(document),new RegularEvent("multiRecordSelection:action:removeMarked",(e=>{Recordlist.submitClipboardFormWithCommand("removeMarked",e.target)})).bindTo(document)}static submitClipboardFormWithCommand(e,t){const o=t.closest("form");if(!o)return;const i=o.querySelector('input[name="cmd"]');i&&(i.value=e,o.submit())}static getReturnUrl(e){return""===e&&(e=top.list_frame.document.location.pathname+top.list_frame.document.location.search),encodeURIComponent(e)}handleDataHandlerResult(e){const t=e.detail.payload;t.hasErrors||"datahandler"!==t.component&&"delete"===t.action&&this.deleteRow(t)}deleteMultiple(e){e.preventDefault();const t=e.detail.configuration;Modal.advanced({title:t.title||"Delete",content:t.content||"Are you sure you want to delete those records?",severity:SeverityEnum.warning,buttons:[{text:TYPO3.lang["button.close"]||"Close",active:!0,btnClass:"btn-default",trigger:(e,t)=>t.hideModal()},{text:t.ok||TYPO3.lang["button.ok"]||"OK",btnClass:"btn-"+Severity.getCssClass(SeverityEnum.warning),trigger:(t,o)=>{o.hideModal(),Recordlist.submitClipboardFormWithCommand("delete",e.target)}}]})}}export default new Recordlist;