예제
실용적인 예제와 라이브 데모.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
list()는 항목이 배열에 남아 있는 동안 그 행을 그대로 지켜 줍니다. 순서를 바꾸고, 끼워 넣고, 이름을 고쳐도 입력값과 포커스는 그대로입니다. 스위치를 켜면 update()마다 객체를 복제하며 동일성이 깨졌을 때 치르는 대가를 보여 줍니다.
Type into a row, then reorder or insert: the row keeps its input and its focus, and the mount count only grows by what was inserted. Flip the switch and every change rebuilds every row.
import 'nuclo' interface Person { id: number; name: string } let people: Person[] = [ { id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }, { id: 3, name: 'Linus' }, ] let nextId = 4 let clone = false let mounts = 0 // Counts every row built, refreshing only the "stats" scope. const mounted = () => on('mount', () => { mounts++ queueMicrotask(() => update('stats')) }) const row = { style: { display: 'flex', flexWrap: 'wrap', gap: '6px' } } // list() matches rows to items by identity (===). A row whose item is // still in the array is kept: its DOM, its input's text, its focus. // Reordering moves the same nodes. Only new items build new rows. // With the switch on, every update() hands list() fresh copies of the // objects. They are not the same items any more, so every row is rebuilt. const items = () => (clone ? people.map((p) => ({ ...p })) : people) function Row(p: Person) { return div( mounted(), { style: { display: 'flex', alignItems: 'center', gap: '8px' } }, small(`#${p.id}`), input({ placeholder: `Type here: ${p.name}`, 'aria-label': `Note for ${p.name}` }), span(() => p.name), // dynamic: a rename shows without a rebuild button('✕', { 'aria-label': `Remove ${p.name}`, onClick: () => { people = people.filter((x) => x.id !== p.id); update() }, }), ) } export const App = () => div( div(scope('stats'), span('rows ', b(() => String(people.length))), span('mounts ', b(() => String(mounts)))), list(items, Row), div( row, button('Reverse', { onClick: () => { people = [...people].reverse(); update() }, }), button('Sort by name', { onClick: () => { people = [...people].sort((a, b) => a.name.localeCompare(b.name)); update() }, }), button('Insert at top', { onClick: () => { people = [{ id: nextId, name: `Person ${nextId++}` }, ...people] update() }, }), // Mutate the item in place: the row is kept and the text updates. button('Rename first', { onClick: () => { people[0].name += '!'; update() }, }), ), // The pitfall: new objects every update are new items to list(), // so every row is torn down and rebuilt, and typed text is lost. label( input({ type: 'checkbox' }, { checked: () => clone }, { onChange: () => { clone = !clone; update() } }), 'Clone the objects on every update (breaks identity)', ), p('Type into a row, then reorder or insert: the row keeps its input and its focus, and the mount count only grows by what was inserted. Flip the switch and every change rebuilds every row.'), )