Skip to content

Instantly share code, notes, and snippets.

@nexpr
Last active October 24, 2023 01:50
Show Gist options
  • Save nexpr/9db3fd84a653ef95947b6b241600aaff to your computer and use it in GitHub Desktop.
Save nexpr/9db3fd84a653ef95947b6b241600aaff to your computer and use it in GitHub Desktop.
LitElement で直接 CSS を書けるようにする
import { html } from "lit"
import { StylitElement } from "./StylitElement.js"
customElements.define("foo-bar", class extends StylitElement {
static properties = {
name: {},
}
constructor() {
super()
this.name = ""
}
render() {
return html`
<div class=${this.style`display: flex; flex-flow: column; gap: 10px;`}>
<div
class=${this.style`
border: 2px solid #aaa;
padding: 12px;
:is(input) {
padding: 4px;
}
`}
>
<label>name</label>
<input .value=${this.name} @input=${event => this.name = event.target.value}>
</div>
<div
class=${this.style`
border: 2px solid #f8d;
padding: 20px;
:is(input) {
padding: 4px;
}
`}
>
<label>name</label>
<input .value=${this.name} @input=${event => this.name = event.target.value}>
</div>
${["#f00", "#0f0", "#00f"].map(color => {
return html`
<div
class=${this.style`
border: 2px solid ${color};
padding: 12px;
:is(input) {
padding: 4px;
}
`}
>
<label>name</label>
<input .value=${this.name} @input=${event => this.name = event.target.value}>
</div>
`
})}
</div>
`
}
})
import { LitElement } from "lit"
export class StylitElement extends LitElement {
constructor() {
super()
this._cssss = new CSSStyleSheet()
this._style_num = 0
}
style(template, ...values) {
const class_name = "c" + (this._style_num++).toString(36)
this._cssss.insertRule(`.${class_name} {${String.raw(template, ...values)}}`)
return class_name
}
update() {
this._style_num = 0
const old = this._cssss
this._cssss = new CSSStyleSheet()
super.update()
const index = this.shadowRoot.adoptedStyleSheets.indexOf(old)
if (index < 0) {
this.shadowRoot.adoptedStyleSheets.push(this._cssss)
} else {
this.shadowRoot.adoptedStyleSheets.splice(index, 1, this._cssss)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment