/*
 * 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 U from"@typo3/core/document-service.js";import{SeverityEnum as Y}from"@typo3/backend/enum/severity.js";import"bootstrap";import j from"@typo3/backend/modal.js";import I from"@typo3/core/security-utility.js";import{property as C,customElement as B}from"lit/decorators.js";import{LitElement as q,html as s,nothing as u}from"lit";import{classMap as _}from"lit/directives/class-map.js";import{styleMap as A}from"lit/directives/style-map.js";import{createRef as H,ref as T}from"lit/directives/ref.js";import{CodeMirrorElement as P}from"@typo3/backend/code-editor/element/code-mirror-element.js";var h=function(l,e,t,n){var i=arguments.length,r=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(l,e,t,n);else for(var a=l.length-1;a>=0;a--)(o=l[a])&&(r=(i<3?o(r):i>3?o(e,t,r):o(e,t))||r);return i>3&&r&&Object.defineProperty(e,t,r),r},d,f;(function(l){l.none="",l.slide="slide",l.collect="collect",l.collectReverse="collectReverse"})(f||(f={}));let c=d=class extends q{constructor(){super(...arguments),this.colCount=1,this.rowCount=1,this.readOnly=!1,this.fieldName="",this.data=[],this.codeMirrorConfig={},this.previewAreaRef=H(),this.codeMirrorRef=H(),this.defaultCell={spanned:0,rowspan:1,colspan:1,name:"",colpos:"",column:void 0,identifier:"",slideMode:f.none},this.modalButtonClickHandler=e=>{const t=e.target,n=e.currentTarget;t.name==="cancel"?n.hideModal():t.name==="ok"&&(this.setName(n.querySelector(".t3js-grideditor-field-name").value,n.userData.col,n.userData.row),this.setColumn(parseInt(n.querySelector(".t3js-grideditor-field-colpos").value,10),n.userData.col,n.userData.row),this.setIdentifier(n.querySelector(".t3js-grideditor-field-identifier").value,n.userData.col,n.userData.row),this.setSlideMode(n.querySelector(".t3js-grideditor-field-slide-mode").value,n.userData.col,n.userData.row),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord()),n.hideModal())},this.addColumnHandler=e=>{e.preventDefault(),this.addColumn(),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())},this.removeColumnHandler=e=>{e.preventDefault(),this.removeColumn(),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())},this.addRowTopHandler=e=>{e.preventDefault(),this.addRowTop(),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())},this.addRowBottomHandler=e=>{e.preventDefault(),this.addRowBottom(),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())},this.removeRowTopHandler=e=>{e.preventDefault(),this.removeRowTop(),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())},this.removeRowBottomHandler=e=>{e.preventDefault(),this.removeRowBottom(),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())},this.linkEditorHandler=e=>{e.preventDefault();const t=e.currentTarget;this.showOptions(Number(t.dataset.col),Number(t.dataset.row))},this.linkExpandRightHandler=e=>{e.preventDefault();const t=e.currentTarget;this.addColspan(Number(t.dataset.col),Number(t.dataset.row)),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())},this.linkShrinkLeftHandler=e=>{e.preventDefault();const t=e.currentTarget;this.removeColspan(Number(t.dataset.col),Number(t.dataset.row)),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())},this.linkExpandDownHandler=e=>{e.preventDefault();const t=e.currentTarget;this.addRowspan(Number(t.dataset.col),Number(t.dataset.row)),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())},this.linkShrinkUpHandler=e=>{e.preventDefault();const t=e.currentTarget;this.removeRowspan(Number(t.dataset.col),Number(t.dataset.row)),this.requestUpdate(),this.writeConfig(this.export2LayoutRecord())}}static stripMarkup(e){return new I().stripHtml(e)}async connectedCallback(){await U.ready(),this.field=document.querySelector('input[name="'+this.fieldName+'"]'),this.addVisibilityObserver(this),super.connectedCallback()}firstUpdated(){this.writeConfig(this.export2LayoutRecord())}createRenderRoot(){return this}render(){return s`<div class=${_({grideditor:!0,"grideditor-readonly":this.readOnly})}>${this.readOnly?u:this.renderControls("top",!1)}<div class=grideditor-editor><div class=t3js-grideditor>${this.renderEditorGrid()}</div></div>${this.readOnly?u:this.renderControls("right",!0)} ${this.readOnly?u:this.renderControls("bottom",!1)}<div class=grideditor-preview>${this.renderPreview()}</div></div>`}renderControls(e,t){const n={top:this.addRowTopHandler,right:this.addColumnHandler,bottom:this.addRowBottomHandler},i={top:TYPO3.lang.grid_addRow,right:TYPO3.lang.grid_addColumn,bottom:TYPO3.lang.grid_addRow},r={top:this.removeRowTopHandler,right:this.removeColumnHandler,bottom:this.removeRowBottomHandler},o={top:TYPO3.lang.grid_removeRow,right:TYPO3.lang.grid_removeColumn,bottom:TYPO3.lang.grid_removeRow};return s`<div class="grideditor-control grideditor-control-${e}"><div class=${_({"btn-group":!t,"btn-group-vertical":t})}><button @click=${n[e]} class="btn btn-default btn-sm" title=${i[e]}><typo3-backend-icon identifier=actions-plus size=small></typo3-backend-icon></button> <button @click=${r[e]} class="btn btn-default btn-sm" title=${o[e]}><typo3-backend-icon identifier=actions-minus size=small></typo3-backend-icon></button></div></div>`}renderEditorGrid(){const e=[];for(let t=0;t<this.rowCount;t++)if(this.data[t].length!==0)for(let i=0;i<this.colCount;i++){const r=this.data[t][i];r.spanned!==1&&e.push(this.renderGridCell(t,i,r))}return s`<div class=grideditor-editor-grid>${e}</div>`}renderGridCell(e,t,n){const i={"--grideditor-cell-col":t+1,"--grideditor-cell-colspan":n.colspan,"--grideditor-cell-row":e+1,"--grideditor-cell-rowspan":n.rowspan};return s`<div class=grideditor-cell style=${A(i)}><div class=grideditor-cell-actions>${this.readOnly?u:s`<button @click=${this.linkEditorHandler} class="t3js-grideditor-link-editor grideditor-action grideditor-action-edit" data-row=${e} data-col=${t} title=${TYPO3.lang.grid_editCell}><typo3-backend-icon identifier=actions-open size=small></typo3-backend-icon></button> ${this.cellCanSpanRight(t,e)?s`<button @click=${this.linkExpandRightHandler} class="t3js-grideditor-link-expand-right grideditor-action grideditor-action-expand-right" data-row=${e} data-col=${t} title=${TYPO3.lang.grid_cell_merge_right}><typo3-backend-icon identifier=actions-caret-right size=small></typo3-backend-icon></button>`:u} ${this.cellCanShrinkLeft(t,e)?s`<button @click=${this.linkShrinkLeftHandler} class="t3js-grideditor-link-shrink-left grideditor-action grideditor-action-shrink-left" data-row=${e} data-col=${t} title=${TYPO3.lang.grid_cell_split_horizontal}><typo3-backend-icon identifier=actions-caret-left size=small></typo3-backend-icon></button>`:u} ${this.cellCanSpanDown(t,e)?s`<button @click=${this.linkExpandDownHandler} class="t3js-grideditor-link-expand-down grideditor-action grideditor-action-expand-down" data-row=${e} data-col=${t} title=${TYPO3.lang.grid_cell_merge_down}><typo3-backend-icon identifier=actions-caret-down size=small></typo3-backend-icon></button>`:u} ${this.cellCanShrinkUp(t,e)?s`<button @click=${this.linkShrinkUpHandler} class="t3js-grideditor-link-shrink-up grideditor-action grideditor-action-shrink-up" data-row=${e} data-col=${t} title=${TYPO3.lang.grid_cell_split_vertical}><typo3-backend-icon identifier=actions-caret-up size=small></typo3-backend-icon></button>`:u}`}</div><div class=grideditor-cell-info><strong>${TYPO3.lang.grid_name}:</strong> ${n.name?d.stripMarkup(n.name):TYPO3.lang.grid_notSet}<br><strong>${TYPO3.lang.grid_column}:</strong> ${typeof n.column>"u"||isNaN(n.column)?TYPO3.lang.grid_notSet:n.column} ${n.identifier?.length?s`<br><strong>${TYPO3.lang.grid_identifier}:</strong> ${n.identifier}`:""} ${(n.slideMode?.toString()||"")!==""?s`<br><strong>${TYPO3.lang.grid_slideMode}:</strong> ${n.slideMode.toString()}`:""}</div></div>`}renderPreview(){return Object.keys(this.codeMirrorConfig).length===0?s`<label>${TYPO3.lang["buttons.pageTsConfig"]}</label><div class="t3js-grideditor-preview-config grideditor-preview"><textarea class="t3js-tsconfig-preview-area form-control" rows=25 readonly ${T(this.previewAreaRef)}></textarea></div>`:s`<typo3-t3editor-codemirror class="t3js-grideditor-preview-config grideditor-preview" label=${this.codeMirrorConfig.label} panel=${this.codeMirrorConfig.panel} mode=${this.codeMirrorConfig.mode} nolazyload=true readonly ${T(this.codeMirrorRef)}><textarea class="t3js-tsconfig-preview-area form-control" ${T(this.previewAreaRef)}></textarea></typo3-t3editor-codemirror>`}getNewCell(){return structuredClone(this.defaultCell)}writeConfig(e){this.field.value=e;const t=e.split(`
`);let n="";for(const a of t)a&&(n+="			"+a+`
`);const i=`mod.web_layout.BackendLayouts {
  exampleKey {
    title = Example
    icon = content-container-columns-2
    config {
`+n.replace(new RegExp("\\t","g"),"  ")+`    }
  }
}
`,r=this.previewAreaRef.value;r instanceof HTMLTextAreaElement&&(r.value=i);const o=this.codeMirrorRef.value;o instanceof P&&o.setContent(i)}addRowTop(){const e=[];for(let t=0;t<this.colCount;t++){const n=this.getNewCell();n.name=t+"x"+this.data.length,e[t]=n}this.data.unshift(e),this.rowCount++}addRowBottom(){const e=[];for(let t=0;t<this.colCount;t++){const n=this.getNewCell();n.name=t+"x"+this.data.length,e[t]=n}this.data.push(e),this.rowCount++}removeRowTop(){if(this.rowCount<=1)return!1;const e=[];for(let t=1;t<this.rowCount;t++)e.push(this.data[t]);for(let t=0;t<this.colCount;t++)this.data[0][t].spanned===1&&this.findUpperCellWidthRowspanAndDecreaseByOne(t,0);return this.data=e,this.rowCount--,!0}removeRowBottom(){if(this.rowCount<=1)return!1;const e=[];for(let t=0;t<this.rowCount-1;t++)e.push(this.data[t]);for(let t=0;t<this.colCount;t++)this.data[this.rowCount-1][t].spanned===1&&this.findUpperCellWidthRowspanAndDecreaseByOne(t,this.rowCount-1);return this.data=e,this.rowCount--,!0}findUpperCellWidthRowspanAndDecreaseByOne(e,t){const n=this.getCell(e,t-1);return n?(n.spanned===1?this.findUpperCellWidthRowspanAndDecreaseByOne(e,t-1):n.rowspan>1&&this.removeRowspan(e,t-1),!0):!1}removeColumn(){if(this.colCount<=1)return!1;const e=[];for(let t=0;t<this.rowCount;t++){const n=[];for(let i=0;i<this.colCount-1;i++)n.push(this.data[t][i]);this.data[t][this.colCount-1].spanned===1&&this.findLeftCellWidthColspanAndDecreaseByOne(this.colCount-1,t),e.push(n)}return this.data=e,this.colCount--,!0}findLeftCellWidthColspanAndDecreaseByOne(e,t){const n=this.getCell(e-1,t);return n?(n.spanned===1?this.findLeftCellWidthColspanAndDecreaseByOne(e-1,t):n.colspan>1&&this.removeColspan(e-1,t),!0):!1}addColumn(){for(let e=0;e<this.rowCount;e++){const t=this.getNewCell();t.name=this.colCount+"x"+e,this.data[e].push(t)}this.colCount++}setName(e,t,n){const i=this.getCell(t,n);return i?(i.name=d.stripMarkup(e),!0):!1}setColumn(e,t,n){const i=this.getCell(t,n);return i?(i.column=parseInt(e.toString(),10),!0):!1}setIdentifier(e,t,n){const i=this.getCell(t,n);return i?(i.identifier=d.stripMarkup(e),!0):!1}setSlideMode(e,t,n){const i=this.getCell(t,n);return i?(i.slideMode=f[e],!0):!1}showOptions(e,t){const n=this.getCell(e,t);if(!n)return!1;let i;n.column===0?i=0:n.column?i=parseInt(n.column.toString(),10):i="";const r=document.createElement("div"),o=document.createElement("div");o.classList.add("form-group");const a=document.createElement("label");a.classList.add("form-label");const v=document.createElement("input");v.classList.add("form-control");const M=o.cloneNode(!0),y=a.cloneNode(!0);y.innerText=TYPO3.lang.grid_nameHelp,y.htmlFor="grideditor-field-name";const p=v.cloneNode(!0);p.id="grideditor-field-name",p.type="text",p.classList.add("t3js-grideditor-field-name"),p.name="name",p.value=d.stripMarkup(n.name)||"",M.append(y,p);const D=o.cloneNode(!0),k=a.cloneNode(!0);k.innerText=TYPO3.lang.grid_columnHelp,k.htmlFor="grideditor-field-colpos";const m=v.cloneNode(!0);m.type="text",m.classList.add("t3js-grideditor-field-colpos"),m.id="grideditor-field-colpos",m.name="column",m.value=i.toString(),D.append(k,m);const L=o.cloneNode(!0),R=a.cloneNode(!0);R.innerText=TYPO3.lang.grid_identifierHelp,R.htmlFor="grideditor-field-identifier";const w=v.cloneNode(!0);p.type="text",w.classList.add("t3js-grideditor-field-identifier"),w.id="grideditor-field-identifier",w.name="identifier",w.value=typeof n.identifier=="string"?d.stripMarkup(n.identifier):"",L.append(R,w);const S=o.cloneNode(!0),x=a.cloneNode(!0);x.innerText=TYPO3.lang.grid_slideModeHelp,x.htmlFor="grideditor-field-slide-mode";const g=document.createElement("select");g.classList.add("form-select","t3js-grideditor-field-slide-mode"),g.id="grideditor-field-slide-mode",g.name="slideMode",g.value=d.stripMarkup(n.slideMode?.toString())||"",Object.keys(f).map(O=>{const E=O!=="none"?O:"",N=f[O],b=document.createElement("option");b.value=N,b.text=E,b.selected=N===n.slideMode?.toString(),g.appendChild(b)}),S.append(x,g),r.append(M,D,L,S);const $=j.show(TYPO3.lang.grid_windowTitle,r,Y.notice,[{active:!0,btnClass:"btn-default",name:"cancel",text:TYPO3.lang["button.cancel"]||"Cancel"},{btnClass:"btn-primary",name:"ok",text:TYPO3.lang["button.ok"]||"OK"}]);return $.userData.col=e,$.userData.row=t,$.addEventListener("button.clicked",this.modalButtonClickHandler),!0}getCell(e,t){return e>this.colCount-1||t>this.rowCount-1?!1:this.data.length>t-1&&this.data[t].length>e-1?this.data[t][e]:null}cellCanSpanRight(e,t){if(e===this.colCount-1)return!1;const n=this.getCell(e,t);if(!n)return!1;let i;if(n.rowspan>1){for(let r=t;r<t+n.rowspan;r++)if(i=this.getCell(e+n.colspan,r),!i||i.spanned===1||i.colspan>1||i.rowspan>1)return!1}else if(i=this.getCell(e+n.colspan,t),!i||n.spanned===1||i.spanned===1||i.colspan>1||i.rowspan>1)return!1;return!0}cellCanSpanDown(e,t){if(t===this.rowCount-1)return!1;const n=this.getCell(e,t);if(!n)return!1;let i;if(n.colspan>1){for(let r=e;r<e+n.colspan;r++)if(i=this.getCell(r,t+n.rowspan),!i||i.spanned===1||i.colspan>1||i.rowspan>1)return!1}else if(i=this.getCell(e,t+n.rowspan),!i||n.spanned===1||i.spanned===1||i.colspan>1||i.rowspan>1)return!1;return!0}cellCanShrinkLeft(e,t){return this.data[t][e].colspan>1}cellCanShrinkUp(e,t){return this.data[t][e].rowspan>1}addColspan(e,t){const n=this.getCell(e,t);if(!n||!this.cellCanSpanRight(e,t))return!1;for(let i=t;i<t+n.rowspan;i++)this.data[i][e+n.colspan].spanned=1;return n.colspan+=1,!0}addRowspan(e,t){const n=this.getCell(e,t);if(!n||!this.cellCanSpanDown(e,t))return!1;for(let i=e;i<e+n.colspan;i++)this.data[t+n.rowspan][i].spanned=1;return n.rowspan+=1,!0}removeColspan(e,t){const n=this.getCell(e,t);if(!n||!this.cellCanShrinkLeft(e,t))return!1;n.colspan-=1;for(let i=t;i<t+n.rowspan;i++)this.data[i][e+n.colspan].spanned=0;return!0}removeRowspan(e,t){const n=this.getCell(e,t);if(!n||!this.cellCanShrinkUp(e,t))return!1;n.rowspan-=1;for(let i=e;i<e+n.colspan;i++)this.data[t+n.rowspan][i].spanned=0;return!0}export2LayoutRecord(){let e=`backend_layout {
	colCount = `+this.colCount+`
	rowCount = `+this.rowCount+`
	rows {
`;for(let t=0;t<this.rowCount;t++){e+="		"+(t+1)+` {
`,e+=`			columns {
`;let n=0;for(let i=0;i<this.colCount;i++){const r=this.getCell(i,t);if(r&&!r.spanned){const o=d.stripMarkup(r.name)||"";n++,e+="				"+n+` {
`,e+="					name = "+(o||i+"x"+t)+`
`,r.colspan>1&&(e+="					colspan = "+r.colspan+`
`),r.rowspan>1&&(e+="					rowspan = "+r.rowspan+`
`),typeof r.column=="number"&&(e+="					colPos = "+r.column+`
`),typeof r.identifier=="string"&&r.identifier.length&&(e+="					identifier = "+r.identifier+`
`),r.slideMode!==void 0&&r.slideMode!==f.none&&(e+="					slideMode = "+r.slideMode.toString()+`
`),e+=`				}
`}}e+=`			}
`,e+=`		}
`}return e+=`	}
}
`,e}addVisibilityObserver(e){e.offsetParent===null&&new IntersectionObserver(t=>{t.forEach(n=>{const i=this.codeMirrorRef.value;n.intersectionRatio>0&&i instanceof P&&i.requestUpdate()})}).observe(e)}};h([C({type:Number})],c.prototype,"colCount",void 0),h([C({type:Number})],c.prototype,"rowCount",void 0),h([C({type:Boolean})],c.prototype,"readOnly",void 0),h([C({type:String})],c.prototype,"fieldName",void 0),h([C({type:Array})],c.prototype,"data",void 0),h([C({type:Object})],c.prototype,"codeMirrorConfig",void 0),c=d=h([B("typo3-backend-grid-editor")],c);export{c as GridEditor};
