/*
 * 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 R from"@typo3/core/document-service.js";import{html as f}from"lit";import"@typo3/backend/element/icon-element.js";import{SeverityEnum as m}from"@typo3/backend/enum/severity.js";import"@typo3/backend/input/clearable.js";import"@typo3/workspaces/renderable/record-table.js";import"@typo3/backend/element/pagination.js";import A from"@typo3/workspaces/workspaces.js";import u from"@typo3/backend/modal.js";import v from"@typo3/backend/storage/persistent.js";import b from"@typo3/backend/utility.js";import T from"@typo3/backend/window-manager.js";import l from"@typo3/core/event/regular-event.js";import{topLevelModuleImport as S}from"@typo3/backend/utility/top-level-module-import.js";import{selector as P}from"@typo3/core/literals.js";import x from"@typo3/workspaces/utility/icon-helper.js";import k from"@typo3/backend/action-button/deferred-action.js";var s;(function(r){r.searchForm="#workspace-settings-form",r.searchTextField='#workspace-settings-form input[name="search-text"]',r.searchSubmitBtn='#workspace-settings-form button[type="submit"]',r.depthSelector='#workspace-settings-form [name="depth"]',r.languageSelector='#workspace-settings-form select[name="languages"]',r.stagesSelector='#workspace-settings-form select[name="stages"]',r.workspaceActions=".workspace-actions",r.chooseStageAction='.workspace-actions [name="stage-action"]',r.chooseSelectionAction='.workspace-actions [name="selection-action"]',r.chooseMassAction='.workspace-actions [name="mass-action"]',r.publishAction='[data-action="publish"]',r.prevStageAction='[data-action="prevstage"]',r.nextStageAction='[data-action="nextstage"]',r.changesAction='[data-action="changes"]',r.previewAction='[data-action="preview"]',r.openAction='[data-action="open"]',r.versionAction='[data-action="version"]',r.removeAction='[data-action="remove"]',r.expandAction='[data-action="expand"]',r.workspaceRecipientsSelectAll=".t3js-workspace-recipients-selectall",r.workspaceRecipientsDeselectAll=".t3js-workspace-recipients-deselectall",r.container="#workspace-panel",r.contentsContainer="#workspace-contents",r.noContentsContainer="#workspace-contents-empty",r.previewLinksButton=".t3js-preview-link",r.pagination="#workspace-pagination"})(s||(s={}));class h extends A{constructor(){super(),this.settings={id:TYPO3.settings.Workspaces.id,depth:1,language:"all",limit:30,query:"",start:0,filterTxt:""},this.paging={currentPage:1,totalPages:1,totalItems:0},this.markedRecordsForMassAction=[],this.handleCheckboxStateChanged=a=>{const n=a.target,e=n.closest("tr"),t=n.checked,o=e.dataset.table,i=e.dataset.uid,c=e.dataset.t3ver_oid,g=o+":"+i+":"+c;if(t)this.markedRecordsForMassAction.push(g);else{const p=this.markedRecordsForMassAction.indexOf(g);p>-1&&this.markedRecordsForMassAction.splice(p,1)}e.dataset.collectionCurrent?h.changeCollectionChildrenState(e.dataset.collectionCurrent,t):e.dataset.collection&&(h.changeCollectionChildrenState(e.dataset.collection,t),h.changeCollectionParentState(e.dataset.collection,t));const d=document.querySelector(s.chooseMassAction);d!==null&&(d.disabled=this.markedRecordsForMassAction.length>0)},this.openIntegrityWarningModal=()=>{const a=u.confirm(TYPO3.lang["window.integrity_warning.title"],f`<p>${TYPO3.lang["integrity.hasIssuesDescription"]}<br>${TYPO3.lang["integrity.hasIssuesQuestion"]}</p>`,m.warning);return a.addEventListener("button.clicked",()=>a.hideModal()),a},S("@typo3/workspaces/renderable/send-to-stage-form.js"),S("@typo3/workspaces/renderable/record-information.js"),R.ready().then(()=>{this.registerEvents(),this.settings.depth=document.querySelector(s.depthSelector)?.value,this.settings.language=document.querySelector(s.languageSelector)?.value,this.settings.stage=document.querySelector(s.stagesSelector)?.value,document.querySelector(s.container)!==null&&this.getWorkspaceInfos()})}static refreshPageTree(){top.document.dispatchEvent(new CustomEvent("typo3:pagetree:refresh"))}static changeCollectionParentState(a,n){const e=document.querySelector('tr[data-collection-current="'+a+'"] input[type=checkbox]');e!==null&&e.checked!==n&&(e.checked=n,e.dataset.manuallyChanged="true",e.dispatchEvent(new CustomEvent("multiRecordSelection:checkbox:state:changed",{bubbles:!0,cancelable:!1})))}static changeCollectionChildrenState(a,n){const e=document.querySelectorAll(P`tr[data-collection="${a}"] input[type=checkbox]`);e.length&&e.forEach(t=>{t.checked!==n&&(t.checked=n,t.dataset.manuallyChanged="true",t.dispatchEvent(new CustomEvent("multiRecordSelection:checkbox:state:changed",{bubbles:!0,cancelable:!1})))})}checkIntegrity(a){return this.sendRemoteRequest(this.generateRemotePayload("checkIntegrity",a))}registerEvents(){new l("click",(n,e)=>{const t=e.closest("tr");this.checkIntegrity({selection:[{liveId:t.dataset.uid,versionId:t.dataset.t3ver_oid,table:t.dataset.table}],type:"selection"}).then(async o=>{(await o.resolve())[0].result.result==="warning"?this.openIntegrityWarningModal().addEventListener("confirm.button.ok",()=>{this.renderPublishModal(t)}):this.renderPublishModal(t)})}).delegateTo(document,s.publishAction),new l("click",(n,e)=>{this.sendToStage(e.closest("tr"),"prev")}).delegateTo(document,s.prevStageAction),new l("click",(n,e)=>{this.sendToStage(e.closest("tr"),"next")}).delegateTo(document,s.nextStageAction),new l("click",this.viewChanges.bind(this)).delegateTo(document,s.changesAction),new l("click",this.openPreview.bind(this)).delegateTo(document,s.previewAction),new l("click",(n,e)=>{const t=e.closest("tr"),o=TYPO3.settings.FormEngine.moduleUrl+"&returnUrl="+encodeURIComponent(document.location.href)+"&id="+TYPO3.settings.Workspaces.id+"&edit["+t.dataset.table+"]["+t.dataset.uid+"]=edit";window.location.href=o}).delegateTo(document,s.openAction),new l("click",(n,e)=>{const t=e.closest("tr"),o=t.dataset.table==="pages"?t.dataset.t3ver_oid:t.dataset.pid;window.location.href=TYPO3.settings.WebLayout.moduleUrl+"&id="+o}).delegateTo(document,s.versionAction),new l("click",this.confirmDeleteRecordFromWorkspace.bind(this)).delegateTo(document,s.removeAction),new l("click",(n,e)=>{let t;e.ariaExpanded==="true"?t="actions-caret-down":t="actions-caret-right",e.replaceChildren(document.createRange().createContextualFragment(x.getIcon(t)))}).delegateTo(document,s.expandAction),new l("click",()=>{window.top.document.querySelectorAll(".t3js-workspace-recipient").forEach(e=>{e.disabled||(e.checked=!0)})}).delegateTo(window.top.document,s.workspaceRecipientsSelectAll),new l("click",()=>{window.top.document.querySelectorAll(".t3js-workspace-recipient").forEach(e=>{e.disabled||(e.checked=!1)})}).delegateTo(window.top.document,s.workspaceRecipientsDeselectAll),new l("submit",n=>{n.preventDefault();const e=document.querySelector(s.searchTextField);this.settings.filterTxt=e.value,this.getWorkspaceInfos()}).delegateTo(document,s.searchForm),new l("input",(n,e)=>{const t=document.querySelector(s.searchSubmitBtn);e.value!==""?t.classList.remove("disabled"):(t.classList.add("disabled"),this.getWorkspaceInfos())}).delegateTo(document,s.searchTextField);const a=document.querySelector(s.searchTextField);a!==null&&a.clearable({onClear:()=>{document.querySelector(s.searchSubmitBtn).classList.add("disabled"),this.settings.filterTxt="",this.getWorkspaceInfos()}}),new l("multiRecordSelection:checkbox:state:changed",this.handleCheckboxStateChanged).bindTo(document),new l("change",(n,e)=>{const t=e.value;v.set("moduleData.workspaces_admin.depth",t),this.settings.depth=t,this.getWorkspaceInfos()}).delegateTo(document,s.depthSelector),new l("click",this.generatePreviewLinks.bind(this)).delegateTo(document,s.previewLinksButton),new l("change",(n,e)=>{v.set("moduleData.workspaces_admin.language",e.value),this.settings.language=e.value,this.sendRemoteRequest(this.generateRemotePayload("getWorkspaceInfos",this.settings)).then(async t=>{const o=await t.resolve();e.previousElementSibling.innerHTML=e.querySelector("option:checked").dataset.icon,this.renderWorkspaceInfos(o[0].result)})}).delegateTo(document,s.languageSelector),new l("change",(n,e)=>{const t=e.value;v.set("moduleData.workspaces_admin.stage",t),this.settings.stage=t,this.getWorkspaceInfos()}).delegateTo(document,s.stagesSelector),new l("change",this.sendToSpecificStageAction.bind(this)).delegateTo(document,s.chooseStageAction),new l("change",this.runSelectionAction.bind(this)).delegateTo(document,s.chooseSelectionAction),new l("change",this.runMassAction.bind(this)).delegateTo(document,s.chooseMassAction),new l("click",n=>{n.preventDefault();const e=n.target.closest("button");let t=!1;switch(e.dataset.action){case"previous":this.paging.currentPage>1&&(this.paging.currentPage--,t=!0);break;case"next":this.paging.currentPage<this.paging.totalPages&&(this.paging.currentPage++,t=!0);break;case"page":this.paging.currentPage=parseInt(e.dataset.page,10),t=!0;break;default:throw'Unknown action "'+e.dataset.action+'"'}t&&(this.settings.start=parseInt(this.settings.limit.toString(),10)*(this.paging.currentPage-1),this.getWorkspaceInfos())}).delegateTo(document,s.pagination)}sendToStage(a,n){let e,t,o;if(n==="next")e=a.dataset.nextStage,t="sendToNextStageWindow",o="sendToNextStageExecute";else if(n==="prev")e=a.dataset.prevStage,t="sendToPrevStageWindow",o="sendToPrevStageExecute";else throw"Invalid direction given.";this.sendRemoteRequest(this.generateRemoteActionsPayload(t,[a.dataset.uid,a.dataset.table,a.dataset.t3ver_oid])).then(async i=>{const c=this.renderSendToStageWindow(await i.resolve());c.addEventListener("button.clicked",g=>{if(g.target.name==="ok"){const p=b.convertFormToObject(c.querySelector("form"));p.affects={table:a.dataset.table,nextStage:e,t3ver_oid:a.dataset.t3ver_oid,uid:a.dataset.uid,elements:[]},this.sendRemoteRequest([this.generateRemoteActionsPayload(o,[p]),this.generateRemotePayload("getWorkspaceInfos",this.settings)]).then(async w=>{const y=await w.resolve();c.hideModal(),this.renderWorkspaceInfos(y[1].result),h.refreshPageTree()})}})})}getWorkspaceInfos(){this.sendRemoteRequest(this.generateRemotePayload("getWorkspaceInfos",this.settings)).then(async a=>{this.renderWorkspaceInfos((await a.resolve())[0].result)})}renderWorkspaceInfos(a){const n=document.querySelector(s.contentsContainer),e=document.querySelector(s.noContentsContainer);this.resetMassActionState(a.data.length),this.buildPagination(a.total),a.total===0?(n.style.display="none",e.style.display="block"):(n.style.display="block",e.style.display="none");const t=document.querySelector("typo3-workspaces-record-table");t.results=a.data}buildPagination(a){const n=document.querySelector(s.pagination);if(a===0){n.replaceChildren();return}if(this.paging.totalItems=a,this.paging.totalPages=Math.ceil(a/parseInt(this.settings.limit.toString(),10)),this.paging.totalPages===1){n.replaceChildren();return}let e=n.querySelector("typo3-backend-pagination");e===null&&(e=document.createElement("typo3-backend-pagination"),n.append(e)),e.paging={...this.paging}}viewChanges(a,n){a.preventDefault();const e=n.closest("tr");this.sendRemoteRequest(this.generateRemotePayload("getRowDetails",{stage:parseInt(e.dataset.stage,10),t3ver_oid:parseInt(e.dataset.t3ver_oid,10),table:e.dataset.table,uid:parseInt(e.dataset.uid,10),filterFields:!0})).then(async t=>{const o=(await t.resolve())[0].result.data[0],i=[],c=document.createElement("typo3-workspaces-record-information");c.record=o,c.TYPO3lang=TYPO3.lang,o.label_PrevStage!==!1&&e.dataset.stage!==e.dataset.prevStage&&i.push({text:o.label_PrevStage.title,active:!0,btnClass:"btn-default",name:"prevstage",trigger:(g,d)=>{d.hideModal(),this.sendToStage(e,"prev")}}),o.label_NextStage!==!1&&i.push({text:o.label_NextStage.title,active:!0,btnClass:"btn-default",name:"nextstage",trigger:(g,d)=>{d.hideModal(),this.sendToStage(e,"next")}}),i.push({text:TYPO3.lang.close,active:!0,btnClass:"btn-info",name:"cancel",trigger:(g,d)=>d.hideModal()}),u.advanced({type:u.types.default,title:TYPO3.lang["window.recordInformation"].replace("{0}",e.querySelector(".t3js-title-workspace").innerText.trim()),content:c,severity:m.info,buttons:i,size:u.sizes.medium})})}openPreview(a,n){const e=n.closest("tr");this.sendRemoteRequest(this.generateRemoteActionsPayload("viewSingleRecord",[e.dataset.table,e.dataset.uid])).then(async t=>{const o=(await t.resolve())[0].result;T.localOpen(o)})}confirmDeleteRecordFromWorkspace(a,n){const e=n.closest("tr"),t=u.confirm(TYPO3.lang["window.discard.title"],TYPO3.lang["window.discard.message"],m.warning,[{text:TYPO3.lang.cancel,active:!0,btnClass:"btn-default",name:"cancel",trigger:()=>{t.hideModal()}},{text:TYPO3.lang.ok,btnClass:"btn-warning",name:"ok"}]);t.addEventListener("button.clicked",o=>{o.target.name==="ok"&&this.sendRemoteRequest([this.generateRemoteActionsPayload("deleteSingleRecord",[e.dataset.table,e.dataset.uid])]).then(()=>{t.hideModal(),this.getWorkspaceInfos(),h.refreshPageTree()})})}runSelectionAction(a,n){const e=n.value,t=e!=="discard";if(e.length===0)return;const o=[];for(let i=0;i<this.markedRecordsForMassAction.length;++i){const c=this.markedRecordsForMassAction[i].split(":");o.push({table:c[0],liveId:c[2],versionId:c[1]})}t?this.checkIntegrity({selection:o,type:"selection"}).then(async i=>{(await i.resolve())[0].result.result==="warning"?this.openIntegrityWarningModal().addEventListener("confirm.button.ok",()=>{this.renderSelectionActionModal(e,o)}):this.renderSelectionActionModal(e,o)}):this.renderSelectionActionModal(e,o)}renderPublishModal(a){const n=u.advanced({title:TYPO3.lang["window.publish.title"],content:TYPO3.lang["window.publish.message"],severity:m.info,staticBackdrop:!0,buttons:[{text:TYPO3.lang.cancel,btnClass:"btn-default",trigger:function(){n.hideModal()}},{text:TYPO3.lang.label_doaction_publish,btnClass:"btn-info",action:new k(async()=>{await this.sendRemoteRequest(this.generateRemoteActionsPayload("publishSingleRecord",[a.dataset.table,a.dataset.t3ver_oid,a.dataset.uid])),this.getWorkspaceInfos(),h.refreshPageTree()})}]})}renderSelectionActionModal(a,n){const e=u.advanced({title:TYPO3.lang["window.selectionAction.title"],content:f`<p>${TYPO3.lang["tooltip."+a+"Selected"]}</p>`,severity:m.warning,staticBackdrop:!0,buttons:[{text:TYPO3.lang.cancel,btnClass:"btn-default",trigger:function(){e.hideModal()}},{text:TYPO3.lang["label_doaction_"+a],btnClass:"btn-warning",action:new k(async()=>{await this.sendRemoteRequest(this.generateRemoteActionsPayload("executeSelectionAction",{action:a,selection:n})),this.markedRecordsForMassAction=[],this.getWorkspaceInfos(),h.refreshPageTree()})}]});e.addEventListener("typo3-modal-hidden",()=>{const t=document.querySelector(s.chooseSelectionAction);t!==null&&(t.value="")})}runMassAction(a,n){const e=n.value,t=e!=="discard";e.length!==0&&(t?this.checkIntegrity({language:this.settings.language,type:e}).then(async o=>{(await o.resolve())[0].result.result==="warning"?this.openIntegrityWarningModal().addEventListener("confirm.button.ok",()=>{this.renderMassActionModal(e)}):this.renderMassActionModal(e)}):this.renderMassActionModal(e))}renderMassActionModal(a){let n,e;switch(a){case"publish":n="publishWorkspace",e=TYPO3.lang.label_doaction_publish;break;case"discard":n="flushWorkspace",e=TYPO3.lang.label_doaction_discard;break;default:throw"Invalid mass action "+a+" called."}const t=async i=>{const c=(await i.resolve())[0].result;c.processed<c.total?this.sendRemoteRequest(this.generateRemoteMassActionsPayload(n,c)).then(t):(this.getWorkspaceInfos(),u.dismiss())},o=u.advanced({title:TYPO3.lang["window.massAction.title"],content:f`<p>${TYPO3.lang["tooltip."+a+"All"]}</p><p>${TYPO3.lang["tooltip.affectWholeWorkspace"]}</p>`,severity:m.warning,staticBackdrop:!0,buttons:[{text:TYPO3.lang.cancel,btnClass:"btn-default",trigger:function(){o.hideModal()}},{text:e,btnClass:"btn-warning",action:new k(async()=>{const i=await this.sendRemoteRequest(this.generateRemoteMassActionsPayload(n,{init:!0,total:0,processed:0,language:this.settings.language}));await t(i)})}]});o.addEventListener("typo3-modal-hidden",()=>{const i=document.querySelector(s.chooseMassAction);i!==null&&(i.value="")})}sendToSpecificStageAction(a,n){const e=[],t=n.value;for(let o=0;o<this.markedRecordsForMassAction.length;++o){const i=this.markedRecordsForMassAction[o].split(":");e.push({table:i[0],uid:i[1],t3ver_oid:i[2]})}this.sendRemoteRequest(this.generateRemoteActionsPayload("sendToSpecificStageWindow",[t])).then(async o=>{const i=this.renderSendToStageWindow(await o.resolve());i.addEventListener("button.clicked",c=>{if(c.target.name==="ok"){const d=b.convertFormToObject(i.querySelector("form"));d.affects={elements:e,nextStage:t},this.sendRemoteRequest([this.generateRemoteActionsPayload("sendToSpecificStageExecute",[d]),this.generateRemotePayload("getWorkspaceInfos",this.settings)]).then(async p=>{const w=await p.resolve();i.hideModal(),this.renderWorkspaceInfos(w[1].result),h.refreshPageTree()})}}),i.addEventListener("typo3-modal-hide",()=>{const c=document.querySelector(s.chooseStageAction);c!==null&&(c.value="")})})}generatePreviewLinks(){this.sendRemoteRequest(this.generateRemoteActionsPayload("generateWorkspacePreviewLinksForAllLanguages",[this.settings.id])).then(async a=>{const n=(await a.resolve())[0].result,e=document.createElement("dl");for(const[t,o]of Object.entries(n)){const i=document.createElement("dt");i.textContent=t;const c=document.createElement("a");c.href=o,c.target="_blank",c.textContent=o;const g=document.createElement("dd");g.appendChild(c),e.append(i,g)}u.show(TYPO3.lang.previewLink,e,m.info,[{text:TYPO3.lang.ok,active:!0,btnClass:"btn-info",name:"ok",trigger:(t,o)=>o.hideModal()}],["modal-inner-scroll"])})}resetMassActionState(a){if(this.markedRecordsForMassAction=[],a){const n=document.querySelector(s.workspaceActions);n!==null&&n.classList.remove("hidden");const e=document.querySelector(s.chooseMassAction);e!==null&&(e.disabled=!1)}document.dispatchEvent(new CustomEvent("multiRecordSelection:actions:hide")),document.dispatchEvent(new CustomEvent("multiRecordSelection:checkboxes:uncheck"))}}var M=new h;export{M as default};
