import { css, html } from 'lit'
import { property, query } from 'lit/decorators.js'
import type { PropertyValueMap } from 'lit'
import { UsBaseElement } from '../../base/UsBaseElement'
import { customElementIfNotExist } from '../../../utils/customElementIfNotExist'
import type { ISwitchProps } from './model/ISwitchProps'
import UsSwitch_css from './switch.pcss'
import vars_css from './vars.pcss'
declare global {
interface HTMLElementTagNameMap {
'us-switch': UsSwitch
}
}
@customElementIfNotExist('us-switch')
export class UsSwitch extends UsBaseElement implements ISwitchProps {
static styles = [
UsBaseElement.styles,
css([UsSwitch_css] as TemplateStringsArray | any),
css([vars_css] as TemplateStringsArray | any),
]
@property({ type: Boolean }) disabled!: boolean
@property({ type: Boolean }) checked!: boolean
@property({ type: String, attribute: 'data-testid', reflect: true }) dataTestId = 'switch'
@query('.switch') formElement!: HTMLInputElement
willUpdate(changedProperties: PropertyValueMap | Map): void {
if (changedProperties.has('checked') && changedProperties.get('checked') !== undefined)
this.formElement.checked = !changedProperties.get('checked')
}
render() {
return html`
`
}
handleKeyDown(event: KeyboardEvent) {
if (!this.disabled) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
this.checked = !this.checked
this.dispatchEvent(new Event('change', { bubbles: true, cancelable: true }))
}
}
}
handleChange(e: Event) {
e.stopPropagation()
if (!this.disabled) {
this.checked = this.formElement.checked
this.dispatchEvent(new Event('change', { bubbles: true, cancelable: true }))
}
}
handleInput(e: Event) {
e.stopPropagation()
}
handleClick(e: Event) {
e.stopPropagation()
}
}