Skip to content

Commit

Permalink
feat: add naive list support
Browse files Browse the repository at this point in the history
  • Loading branch information
sebkolind committed Nov 15, 2023
1 parent 7441936 commit 8fd3b1d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 6 deletions.
13 changes: 11 additions & 2 deletions example/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ const Component = new O('[hello-world]', function () {
this.setState({
name: 'John Doe',
count: 0,
text: 'Click me'
text: 'Click me',
items: [
{ title: 'Item 1' },
{ title: 'Item 2' }
]
})
})

Expand All @@ -16,7 +20,12 @@ const Button = new O('button', function () {

this.setState({
count,
text: `Clicked ${count}`
text: `Clicked ${count}`,
items: [
{ title: 'Item 1' },
{ title: 'Item 2' },
{ title: 'Item 3' }
]
})
})
})
Expand Down
3 changes: 3 additions & 0 deletions example/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
<a href="./robots.txt" aria-label="robots.txt"></a>
<div hello-world>
<p>one.js 💛</p>
<ul o-for="items">
<li o-text="title"></li>
</ul>
<span o-text="name"></span>
<button o-text="text"></button>
<div>
Expand Down
29 changes: 25 additions & 4 deletions lib/one.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,36 @@ class O {
return this.#state
}

render (target) {
render (target, state = this.#state) {
const iterator = target.length ? target : [target]
for (const el of iterator) {
if (el.getAttribute(TEXT)) {
const key = el.getAttribute(TEXT)
el.textContent = this.#state[key] != null
? this.#state[key]
const text = el.getAttribute(TEXT)
const key = el.getAttribute('key')
const s = key ? state?.[key]?.[text] : state[text]
el.textContent = s != null
? s
: el.textContent
}
if (el.getAttribute('o-for')) {
const template = el.children[0].cloneNode(true)
const array = state[el.getAttribute('o-for')]
// TODO: Handle if the array length is less than,
// the current children length, which means we have to remove

// Only remove first child if it is the template
if (!template.getAttribute('key')) {
el.children[0].remove()
}
array.forEach((item, i) => {
// Don't append already existing children
if (!el.children[i]) {
template.setAttribute('key', i)
el.append(template.cloneNode(true))
}
})
this.render(el.children, array)
}

if (el.children.length) {
for (const c of el.children) {
Expand Down

0 comments on commit 8fd3b1d

Please sign in to comment.