Created
March 7, 2024 06:55
-
-
Save tangentstorm/e02b46c3c2531374d1fabec89152c51d to your computer and use it in GitHub Desktop.
a list component i made in the chrome developer tools by running developer tool snippets against about:blank
This file contains hidden or 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
customElements.define('ts-list', class extends HTMLElement { | |
static observedAttributes = ['ix'] | |
constructor() { super(); this.ix=0 } | |
connectedCallback() { | |
let sh = this.attachShadow({mode: 'open'}) | |
sh.innerHTML=` | |
<slot></slot> | |
<button id="up">^</button> | |
<button id="add">+</button> | |
<button id="dn">v</button>` | |
Array.from(this.children).map(x=>this.decorateChild(x)) | |
sh.getElementById('up').onclick = e=> this.mv(-1) | |
sh.getElementById('dn').onclick = e=> this.mv(+1) | |
sh.getElementById('add').onclick = e=>{ | |
let el = document.createElement('p') | |
this.insertBefore(el, this.children[this.ix].nextSibling) | |
this.decorateChild(el) | |
this.update()}} | |
decorateChild(el){ | |
el.contentEditable = true | |
el.onclick = e=>this.setAttribute('ix', [].indexOf.call(this.children, e.target))} | |
attributeChangedCallback(key,old,val) { | |
switch (key) { | |
case 'ix': { this.ix = parseInt(val); this.update() }}} | |
get value() { return this.children[this.ix].innerText } | |
get values() { return Array.from(this.children).map(x=>x.innerText) } | |
go(ix){ this.setAttribute('ix', this.ix=ix);this.update() } | |
mv(di){ this.go(Math.min(this.children.length-1, Math.max(0,this.ix + di))) } | |
update() { let cs = Array.from(this.children) | |
cs.forEach(c=>{c.classList.remove('active') }) | |
if (this.ix<cs.length) cs[this.ix].classList.add('active') }}) | |
document.head.innerHTML=` | |
<style> | |
ts-list { display:block; width: 200px; border: solid #333 2px; } | |
p { padding: 2px; border: solid silver 1px; } | |
p.active { background: silver } | |
</style> | |
` | |
document.body.innerHTML=` | |
<ts-list id="the-list" ix="0"> | |
<p>hello?</p> | |
<p>do the dishes</p> | |
</ts-list> | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment