예제
실용적인 예제와 라이브 데모.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
반복되는 항목은 list()로 그리고, 데이터를 바꿀 때마다 update()를 호출합니다.
import 'nuclo' interface Todo { id: number text: string done: boolean } let todos: Todo[] = [] let filter: "all" | "active" | "done" = "all" let text = "" let nextId = 1 function visible() { if (filter === "active") return todos.filter((t) => !t.done) if (filter === "done") return todos.filter((t) => t.done) return todos } function addTodo() { if (!text.trim()) return todos.push({ id: nextId++, text, done: false }) text = "" update() } // A filter button: pressed while its filter is the active one function FilterButton(label: string, next: typeof filter) { return button(label, { "aria-pressed": () => String(filter === next), style: () => ({ fontWeight: filter === next ? "700" : "400" }), onClick: () => { filter = next; update() }, }) } export function TodoList() { return div( input( // value: () => text keeps the input in sync, so Add can clear it { placeholder: "Add a task...", value: () => text }, { onInput: (event) => { text = (event.target as HTMLInputElement).value }, onKeyDown: (event) => { if (event.key === "Enter") addTodo() }, }, ), button("Add", { onClick: addTodo }), div( FilterButton("All", "all"), FilterButton("Active", "active"), FilterButton("Done", "done"), ), ul( list( () => visible(), (todo) => li( input( { type: "checkbox", checked: () => todo.done }, { onChange: () => { todo.done = !todo.done; update() } }, ), span(todo.text, { style: () => ({ textDecoration: todo.done ? "line-through" : "none", opacity: todo.done ? "0.6" : "1", }), }), button("✕", { "aria-label": "Delete", onClick: () => { todos = todos.filter((item) => item.id !== todo.id) update() }, }), ), ), when(() => visible().length === 0, div("No tasks yet.")), ), p(() => { const left = todos.filter((t) => !t.done).length return `${left} of ${todos.length} remaining` }), ) }