Skip to content

Instantly share code, notes, and snippets.

@tangentstorm
Created March 7, 2024 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangentstorm/e02b46c3c2531374d1fabec89152c51d to your computer and use it in GitHub Desktop.
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
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