FreeGridv1.15.1English

편집

달력·기간·콤보·여러 값 선택·라디오·스위치·숫자·전화번호 서식·모달 편집기로 셀을 바로 고치고, 셀별 편집 조건, 행 단위 편집, 취소할 수 있는 변경 이벤트를 씁니다.

실행 예제편집

셀을 바로 수정합니다. 텍스트·숫자·날짜·선택 편집기, 유효성 검사, 실행 취소, 변경 내역까지 지원합니다.

이 데모의 코드
import { createGrid, type ColumnDef, type Row } from '@freegridjs/core';
import { makeRows } from '../data';
import { button, separator, text, tr, type DemoContext } from '../ui';

const CITIES: Record<string, string[]> = {
  'South Korea': ['Seoul', 'Busan', 'Incheon'],
  Japan: ['Tokyo', 'Osaka', 'Kyoto'],
  Germany: ['Berlin', 'Munich', 'Hamburg'],
  France: ['Paris', 'Lyon', 'Marseille'],
  Spain: ['Madrid', 'Barcelona', 'Valencia'],
  China: ['Beijing', 'Shanghai', 'Shenzhen'],
  'United States': ['New York', 'Seattle', 'Austin'],
  'United Kingdom': ['London', 'Manchester', 'Leeds'],
};

export default function mount(ctx: DemoContext) {
  const { lang } = ctx;
  const h = (en: string, ko: string) => tr(lang, { en, ko });
  const TAGS = [h('VIP', 'VIP'), h('New', '신규'), h('Wholesale', '도매'), h('Overseas', '해외')];
  const pad = (n: number) => String(n).padStart(2, '0');
  const data = makeRows(300).map(r => {
    const m = 1 + (r.id % 12);
    return {
      ...r,
      city: CITIES[r.country][r.id % 3],
      period: `2026-${pad(m)}-01 ~ 2026-${pad(m)}-${pad(10 + (r.id % 18))}`,
      plan: ['Free', 'Pro', 'Team'][r.id % 3],
      tags: TAGS.filter((_, i) => (r.id >> i) & 1),
      phone: `010-${String(1000 + ((r.id * 37) % 9000))}-${String(1000 + ((r.id * 91) % 9000))}`,
      rating: (r.id % 11) / 2,
      newsletter: r.id % 4 ? 'Y' : 'N',
      memo: r.id % 5 ? '' : h('Call before delivery.\nLeave at the front desk.', '배송 전 전화 주세요.\n프런트에 맡겨 주세요.'),
    };
  });
  const columns: ColumnDef[] = [
    { field: 'id', header: 'ID', type: 'number', format: '0', width: 70, pinned: 'left' },
    // text editor + required
    { field: 'name', header: h('Name', '이름'), width: 170, editable: true, required: true },
    // combo: type to filter the list; free: false keeps out values that are not listed
    { field: 'country', header: h('Country', '국가'), width: 150, editable: true,
      editor: { type: 'combo', options: Object.keys(CITIES), free: false } },
    // dependent select: options come from the row's country
    // a city the new country does not have is cleared (dependsOn), blank cities show the placeholder
    { field: 'city', header: h('City', '도시'), width: 130, editable: true, dependsOn: ['country'],
      editor: { type: 'select', placeholder: h('Choose…', '선택…'), options: (row: Row) => CITIES[row.country] ?? [] } },
    // number editor + validation
    { field: 'q1', header: h('Q1 revenue', '1분기 매출'), type: 'number', format: '#,##0', width: 130, editable: true,
      validate: v => (v == null || (typeof v === 'number' && v >= 0) ? true : h('Must be 0 or more', '0 이상이어야 합니다')) },
    // date columns open a calendar; typing a date still works
    { field: 'joined', header: h('Joined', '가입일'), type: 'date', width: 130, editable: true },
    // two-month calendar with presets (last 7 days, this month …)
    { field: 'period', header: h('Contract period', '계약 기간'), width: 210, editable: true, editor: { type: 'dateRange' } },
    { field: 'plan', header: h('Plan', '요금제'), width: 90, editable: true, editor: { type: 'radio', options: ['Free', 'Pro', 'Team'] } },
    { field: 'tags', header: h('Tags', '태그'), width: 170, editable: true, editor: { type: 'multiSelect', options: TAGS } },
    // formatted as you type: 010-1234-5678, 02-123-4567
    { field: 'phone', header: h('Phone', '전화번호'), width: 140, editable: true, editor: { type: 'mask', mask: 'phone' } },
    { field: 'rating', header: h('Rating', '평점'), type: 'number', format: '0.0', width: 90, editable: true,
      editor: { type: 'number', min: 0, max: 5, step: 0.5 } },
    { field: 'newsletter', header: h('Newsletter', '뉴스레터'), width: 110, editable: true, headerCheckbox: true, editor: { type: 'toggle', on: 'Y', off: 'N' } },
    { field: 'active', header: h('Active', '활성'), type: 'boolean', width: 90, editable: true }, // Space or double-click toggles
    // one click opens a dialog for long text
    { field: 'memo', header: h('Memo', '메모'), width: 180, editable: true, singleClickEdit: true,
      editor: { type: 'modal', title: h('Delivery memo', '배송 메모'), maxLength: 500 } },
    { field: 'email', header: h('Email (read-only)', '이메일 (읽기 전용)'), width: 260 },
  ];
  const grid = createGrid(ctx.host, {
    columns, data, rowSelection: 'multiple', locale: lang,
    getRowId: r => String(r.id),
    // right-click a cell: Add note… (a red corner marks it; hover to read)
    cellNotes: true,
    notes: [{ rowId: '3', colId: 'name', note: h('VIP customer: call before shipping', 'VIP 고객: 출고 전 전화') }],
  });

  grid.on('cellValueChanged', e => ctx.log(`cellValueChanged → ${e.colId}: ${String(e.oldValue)} → ${String(e.newValue)}`));
  grid.on('validationFailed', e => ctx.log(`validationFailed → ${e.colId}: ${e.message}`));
  grid.on('rowsAdded', e => ctx.log(`rowsAdded → ${e.rows.length}`));
  grid.on('rowsRemoved', e => ctx.log(`rowsRemoved → ${e.rows.length}`));

  text(ctx, h('Double-click, press Enter or just type. Enter saves, Esc cancels, Tab moves on. Switches flip with one click; Memo opens a dialog.',
    '더블클릭하거나 Enter를 누르거나 바로 입력하세요. Enter로 저장, Esc로 취소, Tab으로 다음 칸. 스위치는 한 번 클릭으로, 메모는 클릭하면 창이 열립니다.'));
  separator(ctx);
  button(ctx, h('Add row', '행 추가'), () => {
    const [row] = grid.addRows([{ id: 1000 + grid.getData().length, name: '', country: 'South Korea', city: 'Seoul', q1: 0, active: true }], 0);
    grid.scrollToRow(0);
    grid.startEdit(0, 'name');
    return row;
  });
  button(ctx, h('Delete selected', '선택 행 삭제'), () => grid.removeSelectedRows());
  button(ctx, h('Undo', '실행 취소'), () => grid.undo());
  button(ctx, h('Redo', '다시 실행'), () => grid.redo());
  separator(ctx);
  button(ctx, h('Show changes', '변경 내역 보기'), () => {
    const m = grid.getModifiedRows();
    ctx.log(h(`created ${m.created.length}, updated ${m.updated.length}, deleted ${m.deleted.length}`,
      `추가 ${m.created.length}, 수정 ${m.updated.length}, 삭제 ${m.deleted.length}`));
    for (const c of grid.getChanges().slice(0, 10)) ctx.log(`  #${c.row.id} ${c.colId}: ${String(c.oldValue)} → ${String(c.newValue)}`);
  });
  button(ctx, h('Save (commit)', '저장 (commit)'), () => {
    grid.commitChanges();
    ctx.log(h('changes committed — this is where you would send them to your server', '변경 확정 — 실제로는 여기서 서버로 보냅니다'));
  });
  button(ctx, h('Revert all', '모두 되돌리기'), () => grid.revertChanges());
  return grid;
}

컬럼에 editable: true를 지정하면 사용자가 셀을 수정할 수 있습니다. 더블클릭하거나 Enter나 F2를 누르거나, 그냥 입력을 시작하면 됩니다. Enter는 저장하고 아래로, Tab은 저장하고 다음 편집 칸으로 이동하며, Esc는 취소합니다. 참/거짓 값은 Space나 더블클릭으로 바뀝니다. 한글(일본어·중국어) 입력기로 입력해도 똑같이 편집이 시작되고 조합이 편집 칸 안에서 이어집니다. 조합을 끝내는 Enter는 조합만 끝내고, 다음 Enter가 저장합니다.

편집기는 컬럼 타입을 따릅니다. 텍스트, 숫자(1,234도 입력 가능), 날짜(달력), 참/거짓입니다. 다른 편집기는 editor로 고릅니다. 정해진 목록이면 select, 긴 글이면 textarea, 시각이나 날짜·시각이면 'time', 'datetime'이고, 그 밖에 아래 편집기들이 있습니다. select의 options를 행을 받는 함수로 주면 국가에 따른 도시처럼 종속 선택이 되고, disabled: true인 옵션은 고를 수도, 붙여넣을 수도 없습니다. editable도 함수로 주면 마감된 주문을 잠그는 것처럼 셀마다 정할 수 있습니다.

const COUNTRIES = { KR: ['Seoul', 'Busan'], JP: ['Tokyo', 'Osaka'] };

const grid = createGrid(el, {
  columns: [
    { field: 'id', type: 'number' },                                   // read-only
    { field: 'name', editable: true },
    { field: 'qty', type: 'number', editable: ({ row }) => !row.locked }, // per cell
    { field: 'country', editable: true, editor: { type: 'select', options: Object.keys(COUNTRIES) } },
    { field: 'city', editable: true, editor: { type: 'select', options: row => COUNTRIES[row.country] } },
    { field: 'status', editable: true, editor: { type: 'select', options: [
      { value: 'open' }, { value: 'closed', label: 'Closed (admin only)', disabled: true } ] } },
    { field: 'memo', editable: true, editor: { type: 'textarea' } },
    { field: 'pickup', editable: true, editor: { type: 'time' } },
    { field: 'active', type: 'boolean', editable: true },             // Space / double-click toggles
  ],
  data,
  editType: 'cell',   // or 'row': Tab stays in the row, Enter saves it, Escape puts it back
});

grid.startEdit(0, 'name');   // open an editor from code
grid.stopEdit();             // save it (stopEdit(true) cancels)

// stop a change before it happens
grid.on('beforeEdit', e => { if (e.row.locked) e.cancel(); });
grid.on('beforeCellChange', e => { if (e.newValue < 0) e.cancel(); });
grid.on('cellValueChanged', e => console.log(e.colId, e.oldValue, '→', e.newValue));

코드에서는 startEdit(rowIndex, colId)와 stopEdit()로 편집기를 열고 닫습니다. 그때마다 editStart와 editStop이 오고, 값이 바뀌면 행에 새 값이 들어간 뒤 cellValueChanged가 옵니다. beforeEdit에서 cancel()을 부르면 편집기가 열리지 않고, beforeCellChange에서 부르면 편집·붙여넣기·Delete로 들어오는 값을 막습니다.

편집기 종류

편집기는 editor: { type }로 고릅니다. 붙여넣기·채우기·Delete도 같은 규칙을 따르고, 셀에는 옵션 이름과 서식이 적용된 값이 보입니다. singleClickEdit: true면 한 번 클릭으로 열립니다. 편집기마다 예제와 전체 옵션이 있는 페이지가 따로 있습니다.

연쇄 선택과 컬럼 체크박스

dependsOn은 상위 값이 바뀌어 목록에 없게 된 값을 비우고, headerCheckbox는 컬럼 전체를 한 번에 켜고 끕니다. 예제와 설명은 아래에 있습니다.

셀 메모

cellNotes: true를 켜면 우클릭으로 셀 메모를 추가·편집·삭제합니다. 자세한 내용:

행 단위 편집

editType: 'row'를 주면 행 단위로 편집합니다. Tab은 같은 행 안에서만 움직이고, Enter를 누르거나 다른 행으로 가면 그 행이 저장되며(rowEditStop에 바뀐 칸 목록이 담깁니다), Esc는 행 전체를 되돌립니다. 코드에서는 stopRowEdit()로 행 편집을 마칩니다.

잘못된 값을 막고 바뀐 것만 서버로 보내는 방법은 유효성 검사와 변경 추적을 보세요. =qty*price 같은 수식을 담는 셀은 수식에 있습니다.

밖에서 들어오는 변경

웹소켓처럼 밖에서 들어오는 변경은 applyTransaction으로 id 기준 추가·수정·삭제만 반영하세요. 바뀐 셀이 잠깐 깜빡이고, 실행 취소나 변경 내역에는 들어가지 않습니다. 자주 들어오면 applyTransactionAsync가 모아서 한 번에 그립니다. 자세한 내용은 실시간 업데이트에 있습니다.

// prices pushed from a websocket: changed cells flash
socket.onmessage = e => grid.applyTransactionAsync({ update: JSON.parse(e.data) });

// add, update and remove by id
grid.applyTransaction({ add: [newOrder], addIndex: 0, update: [{ id: 7, status: 'done' }], remove: [{ id: 3 }] });

이 페이지에 대한 질문

셀을 편집 가능하게 하려면?

컬럼에 editable: true(또는 셀마다 판단하는 함수)를 주세요. 텍스트·숫자·날짜·선택·시간·여러 줄 편집기와 유효성 검사, 실행 취소, 저장용 변경 내역이 들어 있습니다.