본문으로 건너뛰기Skip to content
예제 첫화면Examples home

바뀐 것 표시하고 되돌리기See what changed and take it back

저장하기 전까지 고친 값은 "변경"으로 쌓여요. 고친 칸에는 표시가 붙고, 추가·삭제한 줄도 구분돼요. 바뀐 내용은 원래 값과 지금 값을 나란히 한눈에 보고, 한 줄만 또는 전부 원래대로 돌릴 수 있어요.Until you save, edits pile up as changes. Changed cells are marked and added or removed rows are distinguished. See the change set as a code-style diff, and revert one row or everything.

입문Beginner
직접 써 보기Live preview바뀐 것 표시하고 되돌리기See what changed and take it back

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="add">직원 추가</button>
    <button type="button" id="removeSelected">고른 줄 삭제</button>
    <button type="button" id="revertSelected">고른 줄만 되돌리기</button>
    <button type="button" id="rollback">모두 되돌리기</button>
    <button type="button" id="commit">지금 값을 기준으로</button>
  </div>
  <div id="grid" style="height: 330px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('revertSelected').addEventListener('click', () => actions.revertSelected(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(api));
document.getElementById('commit').addEventListener('click', () => actions.commit(api));
example.js
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은'];
const departments = ['개발', '디자인', '기획', '영업', '개발'];
const rows = names.map((name, i) => ({
  id: i + 1,
  name,
  department: departments[i],
  salary: 3800 + i * 300,
}));
let nextId = 100;
// saveMode: 'batch'(기본)에서는 고친 값이 바로 저장되지 않고 "변경"으로 쌓여요.
// 고친 칸에는 표시가 붙고(원래 값으로 되돌리면 사라져요), 추가한 줄·삭제한 줄도 표시돼요.
// getChanges()는 줄마다 "무엇이 어떻게 바뀌었는지" 알려 주고, rollbackChanges()는 모두 원래대로 돌려요.
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 110, editable: true },
    { id: 'department', title: '부서', width: 100, editable: true },
    { id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
  ],
  rows,
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
  saveMode: 'batch',
};
const isEn = () => document.documentElement.dataset.lang === 'en';
const STATE_NAMES = {
  ko: { added: '추가', modified: '수정', removed: '삭제' },
  en: { added: 'added', modified: 'modified', removed: 'deleted' },
};
const stateName = (state, en) => STATE_NAMES[en ? 'en' : 'ko'][state] ?? state;
// 변경을 코드 diff처럼 보여 줘요: "-"는 원래 값, "+"는 지금 값이에요.
function diff(api, en = isEn()) {
  const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
  const lines = [];
  for (const change of api.getChanges()) {
    lines.push(en
      ? `Row ${change.key} (${stateName(change.state, en)})`
      : `${change.key}번 줄 (${stateName(change.state, en)})`);
    if (change.state === 'modified') {
      for (const cell of change.cells ?? []) {
        lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
        lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
      }
    }
    else {
      lines.push(`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`);
    }
  }
  return lines.length ? lines.join('\n') : en ? 'Nothing changed' : '(바뀐 것이 없어요)';
}
let say = () => { };
export function setup(api, log) {
  say = log;
  log({
    ko: '칸을 고쳐 보세요. 고친 칸에 표시가 붙고 아래에 바뀐 내용이 나와요.',
    en: 'Edit a cell. The edited cell gets a mark and the changes appear below.',
  });
  return api.on('changesCountChanged', ({ count, added, modified, removed }) => log({
    ko: `변경 ${count}줄 — 추가 ${added}, 수정 ${modified}, 삭제 ${removed}\n${diff(api, false)}`,
    en: `${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api, true)}`,
  }));
}
export const actions = {
  add: (api) => {
    nextId += 1;
    api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
  },
  removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
  // 고른 줄만 원래 값으로 돌려요: 바뀐 칸마다 oldValue를 되살려서 다시 넣어요.
  revertSelected: (api) => {
    const keys = new Set(api.getSelectedKeys().map(String));
    const back = api
      .getChanges()
      .filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
      .map((c) => {
      const original = { ...c.row };
      for (const cell of c.cells ?? [])
        Object.assign(original, { [cell.columnId]: cell.oldValue });
      return original;
    });
    if (back.length)
      api.updateRows(back);
    else
      say({
        ko: '돌릴 줄이 없어요. 고친 줄을 Space로 골라 두고 눌러 보세요',
        en: 'No selected edited row to revert. Select an edited row (Space) first',
      });
  },
  rollback: (api) => api.rollbackChanges(),
  // 지금 상태를 새 기준으로 삼아요(서버에 저장한 뒤에 하는 일이에요). 표시와 변경 기록이 모두 지워져요.
  commit: (api) => api.commitChanges(),
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="add">Add employee</button>
    <button type="button" id="removeSelected">Delete selected</button>
    <button type="button" id="revertSelected">Revert selected</button>
    <button type="button" id="rollback">Revert all</button>
    <button type="button" id="commit">Use current values as baseline</button>
  </div>
  <div id="grid" style="height: 330px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('revertSelected').addEventListener('click', () => actions.revertSelected(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(api));
document.getElementById('commit').addEventListener('click', () => actions.commit(api));
example.js
const names = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Reed', 'Ava Brooks'];
const departments = ['Dev', 'Design', 'Planning', 'Sales', 'Dev'];
const rows = names.map((name, i) => ({
  id: i + 1,
  name,
  department: departments[i],
  salary: 38000 + i * 3000,
}));
let nextId = 100;
// With saveMode: 'batch' (the default), edited values are not saved at once but pile up as "changes".
// An edited cell gets a mark (it disappears if you restore the original value); added and deleted rows are marked too.
// getChanges() tells, per row, what changed and how, and rollbackChanges() restores everything.
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 110, editable: true },
    { id: 'department', title: 'Department', width: 130, editable: true },
    { id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
  ],
  rows,
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
  saveMode: 'batch',
};
const STATE_NAMES = {
  added: 'added',
  modified: 'modified',
  removed: 'deleted',
};
// Show the changes like a code diff: "-" is the original value, "+" is the current one.
function diff(api) {
  const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
  const lines = [];
  for (const change of api.getChanges()) {
    lines.push(`Row ${change.key} (${STATE_NAMES[change.state] ?? change.state})`);
    if (change.state === 'modified') {
      for (const cell of change.cells ?? []) {
        lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
        lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
      }
    }
    else {
      lines.push(`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`);
    }
  }
  return lines.length ? lines.join('\n') : 'Nothing changed';
}
let say = () => { };
export function setup(api, log) {
  say = log;
  log('Edit a cell. The edited cell gets a mark and the changes appear below.');
  return api.on('changesCountChanged', ({ count, added, modified, removed }) => log(`${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api)}`));
}
export const actions = {
  add: (api) => {
    nextId += 1;
    api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
  },
  removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
  // Restore only the selected rows: bring back oldValue for each changed cell and put it in again.
  revertSelected: (api) => {
    const keys = new Set(api.getSelectedKeys().map(String));
    const back = api
      .getChanges()
      .filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
      .map((c) => {
      const original = { ...c.row };
      for (const cell of c.cells ?? [])
        Object.assign(original, { [cell.columnId]: cell.oldValue });
      return original;
    });
    if (back.length)
      api.updateRows(back);
    else
      say('No selected edited row to revert. Select an edited row (Space) first');
  },
  rollback: (api) => api.rollbackChanges(),
  // Take the current state as the new baseline (done after saving to the server). All marks and the change record are cleared.
  commit: (api) => api.commitChanges(),
};