/*
 * 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{LitElement as S,html as a,nothing as c}from"lit";import{property as m,state as v,customElement as T}from"lit/decorators.js";import{live as C}from"lit/directives/live.js";import"@typo3/backend/element/spinner-element.js";import"@typo3/backend/element/icon-element.js";import k from"@typo3/backend/notification.js";import f from"@typo3/backend/utility/dom-helper.js";import R from"@typo3/core/ajax/ajax-request.js";import{copyToClipboard as w}from"@typo3/backend/copy-to-clipboard.js";import{markdown as E}from"@typo3/core/directive/markdown.js";import"@typo3/backend/settings/editor/editable-setting.js";import{SettingsMode as g,sanitizeSettingsMode as _}from"@typo3/backend/settings/enum/settings-mode.enum.js";import p from"~labels/backend.settingseditor";import D from"~labels/backend.copytoclipboard";import"@typo3/backend/settings/type/bool.js";import"@typo3/backend/settings/type/int.js";import"@typo3/backend/settings/type/number.js";import"@typo3/backend/settings/type/string.js";import"@typo3/backend/settings/type/stringlist.js";var d=function(u,i,e,t){var s=arguments.length,n=s<3?i:t===null?t=Object.getOwnPropertyDescriptor(i,e):t,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(u,i,e,t);else for(var r=u.length-1;r>=0;r--)(o=u[r])&&(n=(s<3?o(n):s>3?o(i,e,n):o(i,e))||n);return s>3&&n&&Object.defineProperty(i,e,n),n};class b extends Event{static{this.eventName="typo3:settings-editor:submit"}constructor(i,e){super(b.eventName,{bubbles:!0,composed:!0,cancelable:!1}),this.originalEvent=i,this.formData=e}}let l=class extends S{constructor(){super(...arguments),this.formName="settings_form",this.customFormData={},this.mode=g.basic,this.searchTerm="",this.activeCategory="",this.visibleCategories={},this.observer=null}disconnectedCallback(){super.disconnectedCallback(),this.observer?.disconnect()}createRenderRoot(){return this}adjustNavigationSize(){const i=f.scrollableParent(this),e=this.querySelector(".settings-navigation-inner"),t=this.querySelector(".settings-search"),s=this.querySelector(".settings-navigation");if(s!==null&&e){const n=i.getBoundingClientRect(),o=s.getBoundingClientRect(),r=t?.getBoundingClientRect().bottom??Math.max(n.top,e.getBoundingClientRect().top),h=Math.min(n.bottom,window.innerHeight),y=Math.max(0,h-o.bottom),$=h-r-y;e.style.maxHeight=`${$}px`}}firstUpdated(){f.scrollEventTarget(this).addEventListener("scroll",()=>{this.adjustNavigationSize()})}updated(i){if(i.has("mode")&&this.mode===g.minimal)this.observer?.disconnect(),this.observer=null;else if(i.has("mode")&&this.mode!==g.minimal){const e=f.scrollableParent(this);this.observer=new IntersectionObserver(t=>{t.forEach(o=>{const r=o.target.dataset.key;this.visibleCategories[r]=o.isIntersecting});const s=o=>o.reduce((r,h)=>[...r,h.key,...s(h.categories)],[]),n=s(this.categories).filter(o=>this.visibleCategories[o])[0]||"";n&&(this.activeCategory=n)},{root:e===document.documentElement?null:e,threshold:.1})}if([...this.renderRoot.querySelectorAll(".settings-category")].map(e=>this.observer?.observe(e)),this.adjustNavigationSize(),i.has("activeCategory")){const e=this.querySelector(".settings-navigation-inner"),t=this.querySelector(".settings-navigation-item.active");if(e&&t){const s=e.scrollTop,n=e.getBoundingClientRect().height,o=t.getBoundingClientRect().height,r=t.offsetTop>=s,h=t.offsetTop+o<=s+n;r?h||this.querySelector(".settings-navigation-inner").scrollTo({top:Math.max(0,t.offsetTop+o),behavior:"auto"}):this.querySelector(".settings-navigation-inner").scrollTo({top:Math.max(0,t.offsetTop-o),behavior:"auto"})}}}renderCategoryTree(i,e){return a`<ul data-level=${e}>${i.map(t=>a`<li ?hidden=${t.__hidden}><button type=button @click=${s=>{s.preventDefault(),this.selectCategory(t)}} class="settings-navigation-item ${this.activeCategory===t.key?"active":""}"><span class=settings-navigation-item-icon> <typo3-backend-icon identifier=${t.icon?t.icon:"actions-chevron-end"} size=small></typo3-backend-icon> </span><span class=settings-navigation-item-label>${t.label}</span></button> ${t.categories.length===0?c:a`${this.renderCategoryTree(t.categories,e+1)}`}</li>`)}</ul>`}renderSettings(i,e){return i.map(t=>a`<div class=settings-category-list data-key=${t.key}><div class=settings-category data-key=${t.key} ?hidden=${t.__hidden}>${this.renderHeadline(Math.min(e+1,6),`category-headline-${t.key}`,t.icon,a`${t.label}`)}<div class=settings-category-description>${t.description?E(t.description,"minimal"):c}</div></div>${t.settings.map(s=>a`<typo3-backend-editable-setting ?hidden=${s.__hidden} .setting=${s} .dumpuri=${this.dumpUrl} .mode=${this.mode}></typo3-backend-editable-setting>`)}</div>${t.categories.length===0?c:a`${this.renderSettings(t.categories,e+1)}`}`)}renderHeadline(i,e,t,s){switch(i){case 1:return a`<h1 class=settings-category-headline id=${e}>${t?a`<typo3-backend-icon identifier=${t}></typo3-backend-icon>`:c}${s}</h1>`;case 2:return a`<h2 class=settings-category-headline id=${e}>${t?a`<typo3-backend-icon identifier=${t}></typo3-backend-icon>`:c}${s}</h2>`;case 3:return a`<h3 class=settings-category-headline id=${e}>${t?a`<typo3-backend-icon identifier=${t}></typo3-backend-icon>`:c}${s}</h3>`;case 4:return a`<h4 class=settings-category-headline id=${e}>${t?a`<typo3-backend-icon identifier=${t}></typo3-backend-icon>`:c}${s}</h4>`;case 5:return a`<h5 class=settings-category-headline id=${e}>${t?a`<typo3-backend-icon identifier=${t}></typo3-backend-icon>`:c}${s}</h5>`;case 6:return a`<h6 class=settings-category-headline id=${e}>${t?a`<typo3-backend-icon identifier=${t}></typo3-backend-icon>`:c}${s}</h6>`;default:throw new Error(`Invalid header level: ${i}`)}}selectCategory(i){const e=`#category-headline-${i.key}`,t=this.renderRoot.querySelector(e.replaceAll(".","\\.")),s=f.scrollableParent(this),n=this.renderRoot.querySelector(".settings-search").offsetHeight,o=parseInt(window.getComputedStyle(this.renderRoot.querySelector(".settings-body-inner")).paddingTop,10),r=t.offsetTop-n-o;s.scrollTo({top:r,behavior:"smooth"}),this.activeCategory=i.key}async onSubmit(i){const e=i.target,t=new FormData(e),s={settings:{}};if(t.forEach((n,o)=>{const r=o.match(/^settings\[(.+?)\]$/);r?s.settings[r[1]]=typeof n=="string"?n:n.name:s[o]=typeof n=="string"?n:n.name}),this.dispatchEvent(new b(i,s)),!i.defaultPrevented&&i.submitter?.value==="export"){i.preventDefault();const n=new FormData(e),r=await(await new R(this.dumpUrl).post(n)).resolve();typeof r.yaml=="string"?w(r.yaml):(console.warn("Value can not be copied to clipboard.",typeof r.yaml),k.error(D.get("copyToClipboard.error")))}}async onSearch(i){i.preventDefault(),this.searchTerm=i.currentTarget.value}render(){const i=this.filterCategories(),e=i.filter(t=>!t.__hidden).length>0;return a`<form class=settings-container id=${this.formName} name=${this.formName} action=${this.actionUrl} method=post @submit=${t=>this.onSubmit(t)}>${Object.entries(this.customFormData).map(([t,s])=>a`<input type=hidden name=${t} value=${s}>`)}<div class=settings>${this.mode!==g.minimal?a`<div class=settings-search><label for=settings-search class=visually-hidden>${p.get("settingseditor.search.searchTermVisuallyHiddenLabel")}</label> <input type=search autocomplete=off id=settings-search class=form-control placeholder=${p.get("settingseditor.search.searchTermPlaceholder")} .value=${C(this.searchTerm)} @change=${t=>this.onSearch(t)} @input=${t=>this.onSearch(t)}></div>`:c} ${this.mode!==g.minimal?a`<div class=settings-navigation ?hidden=${!e}><div class=settings-navigation-inner @transitionend=${()=>this.adjustNavigationSize()}>${this.renderCategoryTree(i??[],1)}</div></div>`:c}<div class=settings-body ?hidden=${!e}><div class=settings-body-inner>${this.renderSettings(i??[],1)}</div></div></div>${e?c:a`<div class="callout callout-info mt-3"><div class=callout-icon><span class=icon-emphasized> <typo3-backend-icon identifier=actions-info size=small></typo3-backend-icon> </span></div><div class=callout-content><div class=callout-title>${p.get("settingseditor.search.noResultsTitle")}</div><div class=callout-body><p>${p.get("settingseditor.search.noResultsMessage")}</p><button type=button class="btn btn-default" @click=${()=>this.searchTerm=""}>${p.get("settingseditor.search.noResultsResetButtonLabel")}</button></div></div></div>`}</form>`}filterCategories(i=null){return i??=this.categories,i.map(e=>{const t=this.filterSettings(e.settings),s=this.filterCategories(e.categories),n=t.filter(r=>!r.__hidden).length>0,o=s.filter(r=>!r.__hidden).length>0;return{...e,settings:t,categories:s,__hidden:!n&&!o}})}filterSettings(i){return i.map(e=>({...e,__hidden:!(this.matchesSearchTerm(e.definition.key)||this.matchesSearchTerm(e.definition.label)||this.matchesSearchTerm(e.definition.description??"")||this.valueMatchesSearchTerm(e.value)||e.definition.tags.filter(t=>this.matchesSearchTerm(t)).length>0)}))}matchesSearchTerm(i){return this.searchTerm===""?!0:this.matchesSubstring(i,this.searchTerm)}valueMatchesSearchTerm(i){return typeof i=="string"?this.matchesSearchTerm(i):Array.isArray(i)?i.filter(e=>typeof e=="string"&&this.matchesSearchTerm(e)).length>0:!1}matchesSubstring(i,e){return i.toLowerCase().includes(e.toLowerCase())}};d([m({type:Array})],l.prototype,"categories",void 0),d([m({type:String,attribute:"form-name"})],l.prototype,"formName",void 0),d([m({type:String,attribute:"action-url"})],l.prototype,"actionUrl",void 0),d([m({type:String,attribute:"dump-url"})],l.prototype,"dumpUrl",void 0),d([m({type:Object,attribute:"custom-form-data"})],l.prototype,"customFormData",void 0),d([m({type:String,converter:_})],l.prototype,"mode",void 0),d([v()],l.prototype,"searchTerm",void 0),d([v()],l.prototype,"activeCategory",void 0),l=d([T("typo3-backend-settings-editor")],l);export{l as SettingsEditorElement,b as SettingsEditorSubmitEvent};
