/*
 * 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{lll as d}from"@typo3/core/lit-helper.js";import C from"@typo3/core/document-service.js";import c from"@typo3/backend/notification.js";import L from"@typo3/backend/info-window.js";import{FileListActionSelector as M,FileListActionUtility as P,FileListActionEvent as p}from"@typo3/filelist/file-list-actions.js";import h from"nprogress";import S from"@typo3/backend/icons.js";import v from"@typo3/core/ajax/ajax-request.js";import s from"@typo3/core/event/regular-event.js";import{ModuleStateStorage as U}from"@typo3/backend/storage/module-state-storage.js";import y from"@typo3/backend/modal.js";import{SeverityEnum as F}from"@typo3/backend/enum/severity.js";import E from"@typo3/backend/severity.js";import{MultiRecordSelectionSelectors as R}from"@typo3/backend/multi-record-selection.js";import k from"@typo3/backend/context-menu.js";var m;(function(w){w.fileListFormSelector='form[name="fileListForm"]',w.commandSelector='input[name="cmd"]',w.searchFieldSelector='input[name="searchTerm"]',w.pointerFieldSelector='input[name="pointer"]'})(m||(m={}));const b="typo3:filelist:openElementBrowser";class l{constructor(){this.downloadFilesAndFolders=t=>{t.preventDefault();const e=t.target,i=t.detail,r=i.configuration,n=[];i.checkboxes.forEach(a=>{if(a.checked){const u=a.closest(M.elementSelector),f=P.getResourceForElement(u);n.unshift(f)}}),n.length?this.triggerDownload(n,r.downloadUrl,e):c.warning(d("file_download.invalidSelection"))},new s(b,t=>{const e=new URL(t.detail.actionUrl,window.location.origin);e.searchParams.set("expandFolder",t.detail.identifier),e.searchParams.set("mode",t.detail.mode),y.advanced({type:y.types.iframe,content:e.toString(),size:y.sizes.large}).addEventListener("typo3-modal-hidden",()=>{top.list_frame.document.location.reload()})}).bindTo(document),new s(p.primary,t=>{const e=t.detail,i=e.resources[0],r=e.trigger.closest("[data-default-language-access]");if(i.type==="file"&&r!==null){const n=new URL(top.TYPO3.settings.FormEngine.moduleUrl,window.location.origin);i.metaUid>0?n.searchParams.set("edit[sys_file_metadata]["+i.metaUid+"]","edit"):(n.searchParams.set("edit[sys_file_metadata][0]","new"),n.searchParams.set("defVals[sys_file_metadata][file]",i.uid.toString(10))),n.searchParams.set("returnUrl",l.getReturnUrl("")),window.location.href=n.toString()}if(i.type==="folder"){const n=l.parseQueryParameters(document.location);n.id=i.identifier;const a=new URL(window.location.pathname,window.location.origin);for(const[u,f]of Object.entries(n))a.searchParams.set(u,f);window.location.href=a.toString()}}).bindTo(document),new s(p.primaryContextmenu,t=>{const e=t.detail,i=e.resources[0];k.show("sys_file",i.identifier,"","","",e.trigger,e.event)}).bindTo(document),new s(p.show,t=>{const i=t.detail.resources[0];l.openInfoPopup("_"+i.type.toUpperCase(),i.identifier)}).bindTo(document),new s(p.download,t=>{const e=t.detail,i=e.resources[0];this.triggerDownload([i],e.url,e.trigger)}).bindTo(document),new s(p.updateOnlineMedia,t=>{const e=t.detail,i=e.resources[0];this.updateOnlineMedia(i,e.url)}).bindTo(document),C.ready().then(()=>{l.processTriggers(),new s("click",(t,e)=>{t.preventDefault(),document.dispatchEvent(new CustomEvent(b,{detail:{actionUrl:e.href,identifier:e.dataset.identifier,mode:e.dataset.mode}}))}).delegateTo(document,".t3js-element-browser")}),new s("multiRecordSelection:action:edit",this.editFileMetadata).bindTo(document),new s("multiRecordSelection:action:delete",this.deleteMultiple).bindTo(document),new s("multiRecordSelection:action:download",this.downloadFilesAndFolders).bindTo(document),new s("multiRecordSelection:action:copyMarked",t=>{l.submitClipboardFormWithCommand("copyMarked",t.target)}).bindTo(document),new s("multiRecordSelection:action:removeMarked",t=>{l.submitClipboardFormWithCommand("removeMarked",t.target)}).bindTo(document);const o=document.querySelector([m.fileListFormSelector,m.searchFieldSelector].join(" "))?.value!=="";new s("search",t=>{const e=t.target;e.value===""&&o&&e.closest(m.fileListFormSelector)?.submit()}).delegateTo(document,m.searchFieldSelector)}static submitClipboardFormWithCommand(o,t){const e=t.closest(m.fileListFormSelector);if(!e)return;const i=e.querySelector(m.commandSelector);if(i){if(i.value=o,o==="copyMarked"||o==="removeMarked"){const r=e.querySelector(m.pointerFieldSelector),n=l.parseQueryParameters(document.location).pointer;r&&n&&(r.value=n)}e.submit()}}static openInfoPopup(o,t){L.showItem(o,t)}static processTriggers(){const o=document.querySelector(".filelist-main");o!==null&&U.update("media",o.dataset.filelistCurrentIdentifier)}static parseQueryParameters(o){const t=new URLSearchParams(o.search);return Object.fromEntries(t.entries())}static getReturnUrl(o){if(o===""){const t=top.list_frame.document.forms.namedItem("fileListForm");t!==null?o=t.action:o=top.list_frame.document.location.pathname+top.list_frame.document.location.search}return o}deleteMultiple(o){o.preventDefault();const e=o.detail.configuration;y.advanced({title:e.title||"Delete",content:e.content||"Are you sure you want to delete those files and folders?",severity:F.warning,buttons:[{text:TYPO3.lang["button.close"]||"Close",active:!0,btnClass:"btn-default",trigger:(i,r)=>r.hideModal()},{text:e.ok||TYPO3.lang["button.ok"]||"OK",btnClass:"btn-"+E.getCssClass(F.warning),trigger:(i,r)=>{l.submitClipboardFormWithCommand("delete",o.target),r.hideModal()}}]})}editFileMetadata(o){o.preventDefault();const t=o.detail,e=t.configuration;if(!e||!e.idField||!e.table)return;const i=[];if(t.checkboxes.forEach(r=>{const n=r.closest(R.elementSelector);n!==null&&n.dataset[e.idField]&&i.push(n.dataset[e.idField])}),i.length){const r=new URL(top.TYPO3.settings.FormEngine.moduleUrl,window.location.origin);r.searchParams.set("edit["+e.table+"]["+i.join(",")+"]","edit"),r.searchParams.set("returnUrl",l.getReturnUrl(e.returnUrl||"")),(e.columnsOnly||[]).forEach((a,u)=>{r.searchParams.set("columnsOnly["+e.table+"]["+u+"]",a)}),window.location.href=r.toString()}else c.warning("The selected elements can not be edited.")}triggerDownload(o,t,e){if(o.length===1){const n=o.at(0);if(n.type==="file"){this.invokeDownload(n.url,n.name);return}}c.info(d("file_download.prepare"),"",2);const i=e?.innerHTML;e&&(e.setAttribute("disabled","disabled"),S.getIcon("spinner-circle",S.sizes.small).then(n=>{e.innerHTML=n})),h.configure({parent:"#typo3-filelist",showSpinner:!1}).start();const r=o.map(n=>n.identifier);new v(t).post({items:r}).then(async n=>{let a=n.response.headers.get("Content-Disposition");if(!a){const g=await n.resolve();g.success===!1&&g.status?c.warning(d("file_download."+g.status),d("file_download."+g.status+".message"),10):c.error(d("file_download.error"));return}a=a.substring(a.indexOf(" filename=")+10);const u=await n.raw().arrayBuffer(),f=new Blob([u],{type:n.raw().headers.get("Content-Type")}),T=URL.createObjectURL(f);this.invokeDownload(T,a),c.success(d("file_download.success"),"",2)}).catch(()=>{c.error(d("file_download.error"))}).finally(()=>{h.done(),e&&(e.removeAttribute("disabled"),e.innerHTML=i)})}updateOnlineMedia(o,t){!t||!o.uid||o.type!=="file"||(h.configure({parent:"#typo3-filelist",showSpinner:!1}).start(),new v(t).post({resource:o}).then(()=>{c.success(d("online_media.update.success"))}).catch(()=>{c.error(d("online_media.update.error"))}).finally(()=>{h.done(),window.location.reload()}))}invokeDownload(o,t){const e=document.createElement("a");e.href=o,e.download=t,document.body.appendChild(e),e.click(),URL.revokeObjectURL(o),document.body.removeChild(e)}}export{l as default,b as fileListOpenElementBrowser};
