예제
실용적인 예제와 라이브 데모.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
청구서 항목 배열을 list()로 그립니다. 행마다 스스로 검증하고, 합계에는 유효한 행만 반영됩니다. 다른 행을 추가하거나 지워도 행에 입력한 값은 그대로 남습니다.
import 'nuclo' interface Line { id: number; item: string; qty: string; price: string } let nextId = 3 let lines: Line[] = [ { id: 1, item: 'Design', qty: '2', price: '120' }, { id: 2, item: '', qty: '1', price: '' }, ] const touched = new Set<number>() // line ids that were blurred let submitted: string | null = null // Validation per row, and for the whole form. const lineErrors = (l: Line) => ({ item: l.item.trim() ? null : 'Name the item', qty: Number.isInteger(+l.qty) && +l.qty > 0 ? null : 'Whole number above 0', price: l.price !== '' && +l.price >= 0 ? null : 'A price', }) const lineValid = (l: Line) => Object.values(lineErrors(l)).every((e) => e === null) const valid = () => lines.length > 0 && lines.every(lineValid) const total = () => lines.filter(lineValid).reduce((sum, l) => sum + +l.qty * +l.price, 0) const rowStyle = { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 64px 84px 36px', gap: '6px', } // One input per cell. The row object is the state, so an input writes // straight into it and update() refreshes the errors and the total. const cell = (l: Line, key: 'item' | 'qty' | 'price', placeholder: string, type = 'text') => input({ type, placeholder, value: () => l[key], style: () => ({ borderColor: touched.has(l.id) && lineErrors(l)[key] ? '#ef4444' : '' }), 'aria-label': `${key} of line ${l.id}`, onInput: (e) => { l[key] = e.currentTarget.value; update() }, onBlur: () => { touched.add(l.id); update() }, }) // list() keeps a row's inputs while the row is in the array: adding or // removing other rows does not touch them, and their focus survives. export const Invoice = () => form( div({ style: rowStyle }, small('Item'), small('Qty'), small('Price'), span()), list(() => lines, (l) => div( div( { style: rowStyle }, cell(l, 'item', 'Item'), cell(l, 'qty', '1', 'number'), cell(l, 'price', '0.00', 'number'), button('✕', { type: 'button', title: 'Remove', 'aria-label': 'Remove line', onClick: () => { lines = lines.filter((x) => x !== l); update() }, }), ), p({ role: 'alert' }, () => touched.has(l.id) ? Object.values(lineErrors(l)).find((e) => e) ?? '' : ''), ), ), div( { style: { display: 'flex', justifyContent: 'space-between', fontWeight: '600' } }, span('Total'), span(() => total().toFixed(2)), ), div( button('Add line', { type: 'button', onClick: () => { lines.push({ id: nextId++, item: '', qty: '1', price: '' }) update() }, }), button('Send invoice', { type: 'button', disabled: () => !valid(), onClick: () => { submitted = `${lines.length} lines, total ${total().toFixed(2)}` update() }, }), ), when(() => submitted !== null, p(() => submitted ?? '')), )