Last active
February 24, 2022 19:47
-
-
Save rodydavis/e01658b23dde352ef12f00612c71db38 to your computer and use it in GitHub Desktop.
Color input with lit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { html, css, LitElement } from "lit"; | |
import { customElement, property } from "lit/decorators.js"; | |
/** Color Input */ | |
@customElement("color-input") | |
export class ColorInput extends LitElement { | |
static override styles = css` | |
main { | |
--input-size: 48px; | |
--padding: 4px; | |
display: flex; | |
flex-direction: row; | |
margin-top: calc(var(--padding) / 2); | |
margin-bottom: calc(var(--padding) / 2); | |
} | |
input[type="color"] { | |
width: var(--input-size); | |
height: var(--input-size); | |
outline: none; | |
border: none; | |
border-radius: 50%; | |
} | |
input[type="color"]::-webkit-color-swatch-wrapper { | |
padding: 0; | |
} | |
input[type="color"]::-webkit-color-swatch { | |
border: none; | |
border-radius: var(--input-size); | |
border: var(--md-sys-color-outline) solid 1px; | |
} | |
.details { | |
display: flex; | |
flex-direction: column; | |
margin-left: calc(var(--padding) / 2); | |
justify-content: center; | |
user-select: none; | |
} | |
.title { | |
font-style: normal; | |
font-weight: normal; | |
font-size: 16px; | |
line-height: 24px; | |
color: var(--md-sys-color-on-background); | |
} | |
.subtitle { | |
font-style: normal; | |
font-weight: normal; | |
font-size: 12px; | |
line-height: 16px; | |
letter-spacing: 0.1px; | |
color: var(--md-sys-color-on-surface); | |
opacity: 0.68; | |
} | |
`; | |
@property() value = "#000000"; | |
@property() label = "Color"; | |
@property() description = ""; | |
override render() { | |
return html`<main> | |
<input | |
id="color-input" | |
type="color" | |
.value=${this.value} | |
@change=${(e: Event) => { | |
const input = e.target as HTMLInputElement; | |
this.onColorChange(input.value); | |
}} | |
@contextmenu=${(e: Event) => { | |
e.preventDefault(); | |
let value = prompt("Enter a color", this.value); | |
if (value) { | |
if (value.startsWith("#")) value = value.slice(1); | |
this.onColorChange(`#${value}`); | |
} else { | |
this.onColorChange(this.value); | |
} | |
return false; | |
}} | |
/> | |
<div class="details"> | |
<span class="title">${this.label}</span> | |
${this.description | |
? html`<span class="subtitle">${this.description}</span>` | |
: html``} | |
</div> | |
</main>`; | |
} | |
onColorChange(color: string) { | |
this.dispatchEvent( | |
new CustomEvent("color", { | |
detail: color, | |
bubbles: true, | |
composed: true, | |
}) | |
); | |
} | |
} | |
declare global { | |
interface HTMLElementTagNameMap { | |
"color-input": ColorInput; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment