UNPKG

hyperviews

Version:

View template language based targeting hyperscript

103 lines (89 loc) 2.6 kB
<script> const { h, Component } = window.preact export default class Todos extends Component { constructor (props) { super(props) this.render = view this.state = { todos: [{ id: 1, text: 'Buy milk' }] } this.onSubmit = e => { e.preventDefault() this.setState({ input: '', todos: this.state.todos.concat({ id: Date.now(), text: this.state.input }) }) } this.onChangeInput = e => { this.setState({ input: e.target.value.trim() }) } this.onChangeDoneAll = e => { const done = e.target.checked this.setState({ todos: this.state.todos.map(todo => { todo.done = done return todo }) }) } this.onChangeDone = (e, todo) => { this.setState({ todos: this.state.todos.map(item => { if (item.id === todo.id) { item.done = !item.done } return item }) }) } this.onChangeText = (e, todo) => { this.setState({ todos: this.state.todos.map(item => { if (item.id === todo.id) { item.text = e.target.value } return item }) }) } this.onClickClear = e => { this.setState({ todos: this.state.todos.filter(t => !t.done) }) } } } </script> <function> <section> <!-- Add new todo and toggle all --> <form onsubmit=this.onSubmit> <input type=text name=text class=form-control placeholder='Enter new todo' value={state.input} required=required autocomplete=off onchange=this.onChangeInput> <input type=checkbox onchange=this.onChangeDoneAll> </form> <!-- Todos list --> <ul> <li each='todo in state.todos' key={todo.id}> {$index + 1}. <input type=text value={todo.text} onchange='e => this.onChangeText(e, todo)' class=form-control style="{ borderColor: todo.text ? '': 'red', textDecoration: todo.done ? 'line-through': '' }"> <input type=checkbox checked={todo.done} onchange='e => this.onChangeDone(e, todo)'> </li> </ul> <!-- Summary --> <span>Total {state.todos.length}</span> <button if='state.todos.find(t => t.done)' onclick=this.onClickClear>Clear done</button> <!-- Debug --> <pre><code>{JSON.stringify(state, null, 2)}</code></pre> </section> </function>