-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathexample.js
99 lines (90 loc) · 2.29 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var microcomponent = require('.')
var morph = require('nanomorph')
var css = require('yo-css')
var html = require('bel')
var shallowEqual = require('juliangruber-shallow-equal/objects')
var move = require('array-move').mut
function createComponent () {
var component = microcomponent({
name: 'example',
state: {
first: null,
last: null
}
})
component.on('render', render)
component.on('update', update)
return component
function render () {
this.state.first = this.props.first()
this.state.last = this.props.last()
return html`
<article>
<h1 style=${css({
fontFamily: 'monospace'
})}>
${this.props.title} (+${this.props.likes})
<button onclick=${this.props.like}>Like</button>
<button onclick=${this.props.delete}>x</button>
<button onclick=${this.props.up} disabled=${this.state.first}>^</button>
<button onclick=${this.props.down} disabled=${this.state.last}>v</button>
</h1>
</article>
`
}
function update (props) {
return !shallowEqual(props, this.props) ||
props.first() !== this.state.first ||
props.last() !== this.state.last
}
}
var state = {
posts: []
}
var el = render()
document.body.appendChild(el)
for (var i = 0; i < 10; i++) addPost()
function addPost () {
var post = {
title: Math.random().toString(16).slice(2),
likes: 0,
component: createComponent(),
like: function () {
post.likes++
update()
},
delete: function () {
state.posts.splice(state.posts.indexOf(post), 1)
update()
},
up: function () {
var idx = state.posts.indexOf(post)
move(state.posts, idx, idx - 1)
update()
},
down: function () {
var idx = state.posts.indexOf(post)
move(state.posts, idx, idx + 1)
update()
},
first: function () {
return state.posts.indexOf(post) === 0
},
last: function () {
return state.posts.indexOf(post) === state.posts.length - 1
}
}
state.posts.push(post)
update()
}
function render () {
return html`
<div>
<button onclick=${addPost}>New Post</button>
${state.posts.map(post => post.component.render(Object.assign({}, post)))}
</div>
`
}
function update () {
el = morph(el, render())
}