import{LitElement as e,html as t,css as i}from"../../../lit/index.js";import{SimpleFieldsBaseStyles as s,SimpleFieldsLabelStyles as l,SimpleFieldsDescriptionStyles as r}from"./simple-fields-ui.js";const SimpleFieldsContainerBehaviors=function(e){return class extends e{static get tag(){return"simple-fields-container"}static get styles(){return[...s,...l,...r,i`
          :host {
            display: block;
          }
          :host([error]) {
            color: var(--simple-fields-error-color, #b40000);
            transition: color 0.3s ease-in-out;
          }
          :host([disabled]) {
            color: var(--simple-fields-disabled-color, #999999);
          }
          .field-main.inline,
          .field-main > div,
          #field-bottom {
            display: flex;
            align-items: stretch;
            justify-content: flex-start;
          }
          * {
            flex: 1 1 auto;
          }
          #fieldmeta {
            text-align: right;
          }
          .field,
          ::slotted([slot="field"]) {
            width: auto;
            border: none;
            color: var(--simple-fields-color, currentColor);
            background-color: var(
              --simple-fields-background-color,
              transparent
            );
            transition: opacity ease-in-out;
            flex: 1 0 auto;
          }
          ::slotted([slot="field"]:focus) {
            outline: none;
          }
          :host[inline] ::slotted([slot="field"]:focus),
          ::slotted([type="checkbox"][slot="radio"]:focus),
          ::slotted([type="checkbox"][slot="field"]:focus) {
            outline: unset;
          }
          .field-main.inline .field,
          .field-main.inline ::slotted([slot="field"]) {
            min-width: var(--simple-fields-detail-line-height, 22px);
            height: var(--simple-fields-detail-line-height, 22px);
            margin: 0 var(--simple-fields-margin-small, 8px) 0 0;
          }
          .field[disabled],
          :host([readonly]) ::slotted([slot="field"]) {
            opacity: var(--simple-fields-disabled-opacity, 0.7);
            transition: opacity ease-in-out;
          }
          .field[readonly],
          .field[disabled],
          :host([readonly]) ::slotted([slot="field"]),
          :host([disabled]) ::slotted([slot="field"]) {
            cursor: not-allowed;
            pointer-events: none;
          }
          .border-bottom {
            height: 0;
          }
          :host([disabled]) .border-bottom {
            border-bottom: var(
                --simple-fields-border-bottom-disabled-size,
                var(--simple-fields-border-bottom-size, 1px)
              )
              dashed var(--simple-fields-border-color, #999);
          }
          .border-bottom.blur {
            border-bottom: var(--simple-fields-border-bottom-size, 1px) solid
              var(--simple-fields-border-color, #999);
            width: 100%;
          }
          .border-bottom.focus {
            margin: -1px auto 0;
            width: 0;
            border-bottom: var(--simple-fields-border-bottom-focus-size, 2px)
              solid var(--simple-fields-accent-color, #3f51b5);
            transition: width 0.5s ease-in-out;
          }
          :host(:focus-within) .border-bottom.focus {
            width: 100%;
            transition: width 0.5s ease-in-out;
          }
          :host([type="checkbox"]) .border-bottom,
          :host([type="color"]) .border-bottom,
          :host([type="file"]) .border-bottom,
          :host([type="radio"]) .border-bottom,
          :host([type="range"]) .border-bottom {
            display: none;
          }
          ::slotted(label:hover),
          ::slotted(label:focus),
          ::slotted(label:focus-within) {
            color: var(--simple-fields-accent-color, #3f51b5);
            transition: background-color 0.3s ease-in-out;
          }
          ::slotted(input) {
            padding: 0px;
          }
          ::slotted(textarea[slot="field"]) {
            margin: 0;
            transition: height 0.5s ease-in-out;
            box-sizing: border-box;
            vertical-align: bottom;
          }
          ::slotted(fieldset[slot="field"]) {
            margin: 0;
            padding: 0;
            border: none;
            font-size: var(--simple-fields-font-size, 16px);
            font-family: var(--simple-fields-font-family, sans-serif);
            line-height: var(--simple-fields-line-height, 22px);
            display: var(--simple-fields-radio-option-display, block);
            flex-wrap: var(--simple-fields-radio-option-flex-wrap, wrap);
            transition: color 0.3s ease-in-out;
          }
          ::slotted(fieldset[slot="field"]:hover),
          ::slotted(fieldset[slot="field"]:focus),
          ::slotted(fieldset[slot="field"]:focus-within) {
            color: var(--simple-fields-accent-color, #3f51b5);
          }
        `]}render(){return t` ${this.fieldMainTemplate} ${this.fieldBottom} `}static get properties(){return{autovalidate:{type:Boolean},counter:{type:String},description:{type:String},disabled:{type:Boolean,reflect:!0},defaultErrorMessage:{type:String},defaultRequiredMessage:{type:String},error:{type:Boolean,reflect:!0},errorMessage:{type:String},hidden:{type:Boolean,reflect:!0},field:{type:Object},id:{type:String,reflect:!0},inline:{type:Boolean,reflect:!0},label:{type:String},minchecked:{type:Number},maxchecked:{type:Number},maxwords:{type:Number},name:{type:String,reflect:!0},numberMessage:{type:String},pattern:{type:String},patternMessage:{type:String},prefix:{type:String},readonly:{type:Boolean,reflect:!0},required:{type:Boolean,reflect:!0},requiredMessage:{type:String},suffix:{type:String},type:{type:String},validTypes:{type:Array},isSimpleFieldType:{type:Boolean,reflect:!0,attribute:"is-simple-field-type"},value:{type:Object},__delayedFocus:{type:Boolean}}}constructor(){super(),this.isSimpleFieldType=!0,this.counter="none",this.autovalidate=!1,this.disabled=!1,this.hidden=!1,this.error=!1,this.id=this._generateUUID(),this.inline=!1,this.blockList=!1,this.validTypes=["checkbox","color","date","datetime-local","email","file","fieldset","hidden","month","number","password","radio","range","search","select","tel","text","textarea","time","url","week"],this._observeAndListen(),this.addEventListener("click",this.focus)}disconnectedCallback(){this.removeEventListener("click",this.focus),super.disconnectedCallback()}autoGrow(e=this.field){this.field&&(this.field.style.height="auto",this.field.style.height=`${this.field.scrollHeight}px`,this.field.style.overflowY="hidden")}firstUpdated(e){super.firstUpdated&&super.firstUpdated(e),this._updateField()}updated(e){let t=!1;e.forEach(((e,i)=>{"error"===i&&this.error!==e&&(t=!0),"errorMessage"===i&&this.errorMessage!==e&&(t=!0),"error"===i&&this.field&&this.field.setAttribute("aria-invalid",this.error?"true":"false")})),t&&this._fireErrorChanged()}get descriptionTemplate(){return t`
        <div id="description" part="field-desc">
          <slot name="description"></slot>
          ${this.description}
        </div>
      `}get errorTemplate(){return t`
        <div
          id="error-message"
          ?hidden="${!this.error}"
          role="alert"
          part="error-msg"
        >
          ${this.errorMessage}
        </div>
      `}get fieldBottom(){return t`
        <div class="border-bottom blur"></div>
        <div class="border-bottom focus"></div>
        <div id="field-bottom" part="field-bottom">
          <div id="error-desc" part="field-bottom-inner">
            ${this.descriptionTemplate} ${this.errorTemplate}
          </div>
          ${this.fieldMeta}
        </div>
      `}get fieldId(){return`${this.id||"field"}.input`}get fieldMainTemplate(){return t`
        <div
          class="${this.inline||["checkbox","color","radio"].includes(this.type||"text")?"field-main inline":"field-main"}"
          part="field-main"
        >
          ${this.labelTemplate}
          <div part="field-inner">
            ${this.prefixTemplate}
            <slot name="field"></slot>
            ${this.suffixTemplate}
          </div>
        </div>
      `}get fieldMeta(){return t`
        <div id="fieldmeta" aria-live="polite" part="field-meta">
          <slot name="field-meta"></slot>
        </div>
      `}get hasFieldset(){return"fieldset"===this.type}get labelTemplate(){return t`
        <label
          id="${this.fieldId}-label"
          for="${this.fieldId}"
          class="label-main"
          ?hidden="${"fieldset"===this.type}"
          part="label"
        >
          <slot name="label-prefix"></slot>
          <slot name="label"></slot>
          ${this.label}${this.error||this.required?"*":""}
        </label>
      `}get multicheck(){return this.hasFieldset&&this.field.querySelector("input[type=checkbox]")}get numberError(){let e=!!this._getFieldValue()&&this._getFieldValue().length,t="select"===this.type?this.min:!!this.multicheck&&this.minchecked,i="select"===this.type?this.max:!!this.multicheck&&this.maxchecked;return i&&e&&i<e?i-e:!!(t&&e&&t>e)&&t-e}get numeric(){return["date","month","week","time","datetime-local","number","range"].includes(this.type)}get patternError(){return this.pattern&&""!==this.pattern&&this._getFieldValue()&&(this.field.multiple?this._getFieldValue().filter((e=>!e.match(this.pattern))):!this._getFieldValue().match(this.pattern))}get prefixTemplate(){return t`
        <slot name="prefix"></slot>
        ${this.prefix}
      `}get requiredError(){return!this._getFieldValue()&&this.required}get slottedFieldObserver(){return new MutationObserver(this._updateField)}get suffixTemplate(){return t` ${this.suffix?t`${this.suffix}`:t`<slot name="suffix"></slot>`}`}focus(){this.field?(this.field.focus(),this.__delayedFocus=!1):this.__delayedFocus=!0}cursorAtEnd(){this.field.selectionStart=this.field.selectionEnd=this.field.value.length}select(){!this.field||"text"!==this.type&&"textarea"!==this.type||this.field.select()}setRangeText(e,t,i,s){!this.field||"text"!==this.type&&"textarea"!==this.type||this.field.setRangeText(e,t,i,s)}setSelectionRange(e,t,i){!this.field||"text"!==this.type&&"textarea"!==this.type||this.field.setSelectionRange(e,t,i)}stepDown(e=1){this.field&&this.numeric&&this.field.stepDown()}stepUp(e=1){this.field&&this.numeric&&this.field.stepUp()}validate(){let e=this.field.querySelector("legend");return this.requiredError?(this.error=!0,this.errorMessage=this.requiredMessage||"required"):this.numberError?(this.error=!0,this.errorMessage=this.numberMessage||(this.numberError>0?`select ${this.numberError} more`:`select ${0-this.numberError} fewer`)):this.patternError&&(this.error=!0,this.errorMessage=this.patternMessage||"invalid format"),this.hasFieldset&&e&&(e.innerHTML=e.innerHTML.replace(/\**\s*$/,this.error?"*":""),e.style.color=this.error?"var(--simple-fields-error-color, #b40000)":""),!this.error}_fireErrorChanged(){this.dispatchEvent(new CustomEvent("error-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:this}))}_generateUUID(){return"ss-s-s-s-sss".replace(/s/g,Math.floor(65536*(1+Math.random())).toString(16).substring(1))}_getFieldsetValue(){let e,t;return this.field.querySelector("input[type=radio]")?(e=this.field.querySelector("input:checked"),t=e?e.value:void 0):this.field.querySelector("input[type=checkbox]")&&(t=[],e=this.field.querySelectorAll("input:checked"),e.forEach((e=>t.push(e.value)))),t}_getFieldValue(){let e;return this.field&&(e=this.hasFieldset?this._getFieldsetValue():"checkbox"===this.type||"radio"===this.type?!!this.field.checked:"select"===this.type?this.multiple?Object.keys(this.field.selectedOptions).map((e=>this.field.selectedOptions[e].value)):this.field.selectedOptions[0].value:this.field.value),e}_getValidType(e){return"datetime"===e&&this.validTypes.includes(e)?"datetime-local":this.validTypes.includes(e)?e:"text"}_handleFieldChange(){"text"!==this.type&&"textarea"!==this.type||this._updateCount(),this.autovalidate&&this.validate(),this.value=this._getFieldValue(),"textarea"===this.type&&this.autoGrow()}_observeAndListen(e=!0){e?(this.slottedFieldObserver.observe(this,{attributeFilter:["disabled","readonly","required","slot"],childlist:!0}),this._updateField(),this.addEventListener("click",this.focus),this.addEventListener("focusout",this._onFocusout),this.addEventListener("focusin",this._onFocusin)):(this.slottedFieldObserver.disconnect(),this.removeEventListener("click",this.focus),this.removeEventListener("focusout",this._onFocusout),this.removeEventListener("focusin",this._onFocusin))}_onFocusin(){this.error=!1}_onFocusout(){this.autovalidate&&this.validate()}_updateField(){let e=this.field;if(this.field=this.querySelector&&this.querySelector("[slot=field]")?this.querySelector("[slot=field]"):void 0,this.id=`${this.fieldId||""}-wrapper`,this.field){let e=this.field.tagName.toLowerCase(),t=this.field.getAttribute("type")||"text";if(this.type=this._getValidType("input"===e?t:e),this.required=this.field.required,this.disabled=this.field.disabled,this.readonly=this.field.readonly,this.field.setAttribute("aria-describedby","field-bottom"),this.addEventListener("change",this._handleFieldChange),this.addEventListener("input",this._handleFieldChange),"select"===this.type&&(this.multiple=this.field.multiple),"textarea"===this.type&&(this.field.getAttribute("rows")||this.field.setAttribute("rows",1),this.field.addEventListener("keydown",(e=>e.stopPropagation()))),"fieldset"===this.type){let e=this.querySelector("legend");e&&(e.style.fontSize="var(--simple-fields-detail-font-size, 12px)",e.style.fontFamily="var(--simple-fields-detail-font-family, sans-serif)",e.style.lineHeight="var(--simple-fields-detail-line-height, 22px)",e.style.paddingInlineStart=0,e.style.paddingInlineEnd=0),this.querySelectorAll("label, input").forEach((e=>e.style.marginRight="var(--simple-fields-margin, 16px)")),this.querySelectorAll("label input").forEach((e=>e.style.marginLeft="calc(0 - var(--simple-fields-margin, 16px))"))}}else this.disabled=!1,this.readonly=!1,this.required=!1,this.type=void 0,e&&("textarea"===e.tagName.toLowerCase()&&e.addEventListener("keydown",(e=>e.stopPropagation())),e.removeEventListener("change",this._handleFieldChange),e.removeEventListener("input",this._handleFieldChange));this.field&&this.__delayedFocus&&this.focus()}_updateCount(){let e="",t="[\\w\\-\\']+",i=new RegExp(t,"gim"),s=this.field.getAttribute("maxlength")||this.maxlength||!1,l=this.maxwords||!1,r="word"===this.counter?l:s,o=new RegExp(`.{0,${s||1}}`,"g"),d=new RegExp(`(${t}\\W*){0,${l||1}}`,"g"),matchval=e=>((this.field||{}).value||"").match(e),length=()=>this.field.value?this.field.value.length:0,wordlength=()=>this.field&&this.field.value&&matchval(i)?matchval(i).length:0,correctLength=(e,t,i)=>{e&&t&&t<e&&this.field.value.match(i)&&(this.field.value=matchval(i)[0].trim())};correctLength(length(),s,o),correctLength(wordlength(),l,d),e="word"===this.counter?wordlength():length(),"none"!==this.counter&&this.shadowRoot&&this.shadowRoot.querySelector("#fieldmeta")&&(this.shadowRoot.querySelector("#fieldmeta").innerHTML=r?`${e}/${r}`:e)}}};class SimpleFieldsContainer extends(SimpleFieldsContainerBehaviors(e)){}customElements.define(SimpleFieldsContainer.tag,SimpleFieldsContainer);export{SimpleFieldsContainer,SimpleFieldsContainerBehaviors};