Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created November 19, 2023 12:13
Show Gist options
  • Save nexpr/92d403bb4935c40bf4abdd0636411592 to your computer and use it in GitHub Desktop.
Save nexpr/92d403bb4935c40bf4abdd0636411592 to your computer and use it in GitHub Desktop.
lit example: time input
import { LitElement, css, html } from "lit"
import { live } from "lit/directives/live.js"
export class TimeInput extends LitElement {
static styles = css`
.container {
display: flex;
gap: 10px;
}
input {
width: 30px;
}
`
static properties = {
_hour: {},
_minute: {},
}
get time() {
return this._buildTime()
}
set time(value) {
const [hour, minute] = String(value || "").split(":")
this._hour = this._fix(hour, "", 23)
this._minute = this._fix(minute, "", 59)
}
constructor() {
super()
this._hour = ""
this._minute = ""
}
render() {
return html`
<div class="container">
<input name="hour" .value=${live(this._hour)} @input=${this._onChange} maxlength="2">
:
<input name="minute" .value=${live(this._minute)} @input=${this._onChange} maxlength="2">
</div>
`
}
_buildTime() {
if (!this._hour || !this._minute) return null
return [this._hour, this._minute].map(x => x.padStart(2, "0")).join(":")
}
_fix(value, fallback_value, max) {
value = value.slice(0, 2).replace(/[^\d]/g, "")
if (max < +value) {
return fallback_value
} else {
return value
}
}
_onChange(event) {
const name = event.target.name
const key = "_" + name
const value = this._fix(event.target.value, this[key], name === "hour" ? 23 : 59)
const pre_time = this.time
this[key] = value
const time = this.time
this.requestUpdate()
if (pre_time !== time) {
this.dispatchEvent(new Event("change"))
}
}
}
window.customElements.define("time-input", TimeInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment