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

편집 기록에서 골라 되돌리기Pick an entry from the edit history

고친 내용이 표 아래 목록에 번호 붙은 기록으로 쌓여요. 마지막 것이 아니어도 원하는 기록의 "되돌리기"를 눌러 그 편집만 원래 값으로 돌려요.Edits pile up as numbered entries in a list under the grid. Press "Undo" on any entry, not only the last, to restore just that edit.

활용Intermediate
직접 써 보기Live preview편집 기록에서 골라 되돌리기Pick an entry from the edit history

코드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="revertLast">마지막 기록 되돌리기</button>
  </div>
  <div id="grid" style="height: 270px"></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('revertLast').addEventListener('click', () => actions.revertLast(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 확정한 편집을 번호를 붙여 기록해요. 되돌리기(undo)는 항상 마지막 것부터지만,
// 여기서는 번호를 골라 그 편집만 되돌려요. 이후에 다른 칸을 고쳤어도 상관없어요.
let history = [];
let say = () => { };
export const options = {
  columns: [
    { id: 'campaign', title: '캠페인', width: 170, editable: true },
    {
      id: 'status',
      title: '상태',
      width: 120,
      editable: true,
      cellEditor: 'select',
      editorOptions: [{ value: '준비' }, { value: '진행' }, { value: '중지' }],
    },
  ],
  rows: [
    { id: 1, campaign: '봄맞이 할인', status: '준비' },
    { id: 2, campaign: '신규 가입 쿠폰', status: '진행' },
    { id: 3, campaign: '장바구니 알림', status: '중지' },
    { id: 4, campaign: '재구매 감사 메일', status: '진행' },
  ],
  rowKey: 'id',
  saveMode: 'batch',
};
const describe = (n, e) => L(`#${n} ${String(e.key)}번 줄 ${e.columnId === 'status' ? '상태' : '캠페인'}: ${String(e.before)} → ${String(e.after)}${e.reverted ? ' (되돌림)' : ''}${e.undone ? ' (Ctrl+Z로 되돌림)' : ''}`, `#${n} row ${String(e.key)} ${e.columnId === 'status' ? 'status' : 'campaign'}: ${String(e.before)} → ${String(e.after)}${e.reverted ? ' (undone)' : ''}${e.undone ? ' (undone with Ctrl+Z)' : ''}`);
let panel = null;
let grid = null;
// 표 아래에 편집 기록 목록을 직접 그려요. 줄마다 "되돌리기" 버튼이 있고, 되돌린 기록은 줄이 그어져요.
function paint() {
  if (!panel)
    return;
  panel.replaceChildren();
  if (!history.length) {
    panel.append(L('아직 고친 기록이 없어요. 칸을 고치면 여기에 쌓여요.', 'No edits yet. Edits pile up here.'));
    return;
  }
  history.forEach((entry, i) => {
    const line = document.createElement('div');
    line.style.cssText = 'display: flex; align-items: center; gap: 8px; padding: 2px 0;';
    const text = document.createElement('span');
    text.textContent = describe(i + 1, entry);
    if (entry.reverted || entry.undone)
      text.style.cssText = 'text-decoration: line-through; color: var(--muted);';
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = L('되돌리기', 'Undo');
    button.disabled = entry.reverted || entry.undone;
    button.style.cssText =
      'font: inherit; font-size: 12px; padding: 1px 8px; background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; cursor: pointer;';
    button.addEventListener('click', () => grid && revert(grid, i + 1));
    line.append(text, button);
    panel?.append(line);
  });
}
export function setup(api, log) {
  history = [];
  grid = api;
  say = log;
  panel = document.createElement('div');
  panel.style.cssText =
    'margin-top: 8px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; font-size: 13px; color: var(--fg); background: var(--bg);';
  document.getElementById('grid')?.after(panel);
  paint();
  log({
    ko: '칸을 고치면 번호 붙은 기록이 표 아래에 쌓여요.',
    en: 'Edit a cell and numbered history entries pile up under the table.',
  });
  const off = api.on('editCommitted', (e) => {
    // 새로 고치면 "다시 실행"할 수 있던 기록은 사라져요.
    history = history.filter((entry) => !entry.undone);
    history.push({
      key: e.rowKey,
      columnId: e.columnId,
      before: e.oldValue,
      after: e.newValue,
      reverted: false,
      undone: false,
    });
    log(describe(history.length, history[history.length - 1]));
    paint();
  });
  // 키(Ctrl+Z·Ctrl+Y), 버튼, 코드 어느 쪽으로 되돌려도 목록이 따라가게, 되돌리기 기록의 변화를 직접 받아요.
  const undoneStack = [];
  const offHistory = api.on('historyChanged', ({ action }) => {
    if (action === 'undo') {
      const target = [...history].reverse().find((entry) => !entry.reverted && !entry.undone);
      if (target) {
        target.undone = true;
        undoneStack.push(target);
      }
    }
    else if (action === 'redo') {
      const target = undoneStack.pop();
      if (target)
        target.undone = false;
    }
    else if (action === 'clear') {
      history = [];
      undoneStack.length = 0;
    }
    else {
      undoneStack.length = 0; // 새 기록이 들어오면 다시 실행 목록은 비워져요
    }
    paint();
  });
  return () => {
    off();
    offHistory();
    panel?.remove();
    panel = null;
    grid = null;
  };
}
function revert(api, n) {
  const entry = history[n - 1];
  if (entry === undefined)
    return say({ ko: `${n}번 기록은 없어요.`, en: `There is no entry ${n}.` });
  if (entry.reverted)
    return say({ ko: `${n}번은 이미 되돌렸어요.`, en: `Entry ${n} is already undone.` });
  if (entry.undone)
    return say({
      ko: `${n}번은 Ctrl+Z로 이미 되돌려져 있어요. Ctrl+Y로 다시 실행할 수 있어요.`,
      en: `Entry ${n} was already undone with Ctrl+Z. Redo it with Ctrl+Y.`,
    });
  const row = api.getRowByKey(entry.key);
  if (row === undefined)
    return say({ ko: `${n}번 기록의 줄이 없어요.`, en: `The row of entry ${n} is gone.` });
  if (row[entry.columnId] !== entry.after) {
    return say({
      ko: `${n}번 칸은 그 뒤에 또 바뀌어서 되돌릴 수 없어요. 더 나중 기록부터 되돌려 주세요.`,
      en: `The cell of entry ${n} changed again later, so it cannot be undone. Undo the later entries first.`,
    });
  }
  api.updateRows([{ ...row, [entry.columnId]: entry.before }]);
  entry.reverted = true;
  say(describe(n, entry));
  paint();
}
export const actions = {
  revertLast: (api) => {
    const n = history.map((e) => e.reverted || e.undone).lastIndexOf(false) + 1;
    if (n === 0)
      return say({ ko: '되돌릴 기록이 없어요.', en: 'No entry to undo.' });
    revert(api, n);
  },
};

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="revertLast">Revert latest entry</button>
  </div>
  <div id="grid" style="height: 270px"></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('revertLast').addEventListener('click', () => actions.revertLast(api));
example.js
// Committed edits are recorded with numbers. Undo always starts from the last one,
// but here you pick a number and undo only that edit, even if other cells were edited afterwards.
let history = [];
let say = () => { };
export const options = {
  columns: [
    { id: 'campaign', title: 'Campaign', width: 170, editable: true },
    {
      id: 'status',
      title: 'Status',
      width: 120,
      editable: true,
      cellEditor: 'select',
      editorOptions: [{ value: 'Ready' }, { value: 'Running' }, { value: 'Paused' }],
    },
  ],
  rows: [
    { id: 1, campaign: 'Spring sale', status: 'Ready' },
    { id: 2, campaign: 'New signup coupon', status: 'Running' },
    { id: 3, campaign: 'Cart reminder', status: 'Paused' },
    { id: 4, campaign: 'Repeat purchase thank-you mail', status: 'Running' },
  ],
  rowKey: 'id',
  saveMode: 'batch',
};
const describe = (n, e) => `#${n} row ${String(e.key)} ${e.columnId === 'status' ? 'status' : 'campaign'}: ${String(e.before)} → ${String(e.after)}${e.reverted ? ' (undone)' : ''}${e.undone ? ' (undone with Ctrl+Z)' : ''}`;
let panel = null;
let grid = null;
// Draw the edit history list under the grid by hand. Each line has an "Undo" button, and undone entries are struck through.
function paint() {
  if (!panel)
    return;
  panel.replaceChildren();
  if (!history.length) {
    panel.append('No edits yet. Edits pile up here.');
    return;
  }
  history.forEach((entry, i) => {
    const line = document.createElement('div');
    line.style.cssText = 'display: flex; align-items: center; gap: 8px; padding: 2px 0;';
    const text = document.createElement('span');
    text.textContent = describe(i + 1, entry);
    if (entry.reverted || entry.undone)
      text.style.cssText = 'text-decoration: line-through; color: var(--muted);';
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = 'Undo';
    button.disabled = entry.reverted || entry.undone;
    button.style.cssText =
      'font: inherit; font-size: 12px; padding: 1px 8px; background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; cursor: pointer;';
    button.addEventListener('click', () => grid && revert(grid, i + 1));
    line.append(text, button);
    panel?.append(line);
  });
}
export function setup(api, log) {
  history = [];
  grid = api;
  say = log;
  panel = document.createElement('div');
  panel.style.cssText =
    'margin-top: 8px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; font-size: 13px; color: var(--fg); background: var(--bg);';
  document.getElementById('grid')?.after(panel);
  paint();
  log('Edit a cell and numbered history entries pile up under the table.');
  const off = api.on('editCommitted', (e) => {
    // A new edit discards the entries that could have been redone.
    history = history.filter((entry) => !entry.undone);
    history.push({
      key: e.rowKey,
      columnId: e.columnId,
      before: e.oldValue,
      after: e.newValue,
      reverted: false,
      undone: false,
    });
    log(describe(history.length, history[history.length - 1]));
    paint();
  });
  // Listen to history changes directly so the list follows whether the undo comes from keys (Ctrl+Z, Ctrl+Y), a button or code.
  const undoneStack = [];
  const offHistory = api.on('historyChanged', ({ action }) => {
    if (action === 'undo') {
      const target = [...history].reverse().find((entry) => !entry.reverted && !entry.undone);
      if (target) {
        target.undone = true;
        undoneStack.push(target);
      }
    }
    else if (action === 'redo') {
      const target = undoneStack.pop();
      if (target)
        target.undone = false;
    }
    else if (action === 'clear') {
      history = [];
      undoneStack.length = 0;
    }
    else {
      undoneStack.length = 0; // a new record empties the redo list
    }
    paint();
  });
  return () => {
    off();
    offHistory();
    panel?.remove();
    panel = null;
    grid = null;
  };
}
function revert(api, n) {
  const entry = history[n - 1];
  if (entry === undefined)
    return say(`There is no entry ${n}.`);
  if (entry.reverted)
    return say(`Entry ${n} is already undone.`);
  if (entry.undone)
    return say(`Entry ${n} was already undone with Ctrl+Z. Redo it with Ctrl+Y.`);
  const row = api.getRowByKey(entry.key);
  if (row === undefined)
    return say(`The row of entry ${n} is gone.`);
  if (row[entry.columnId] !== entry.after) {
    return say(`The cell of entry ${n} changed again later, so it cannot be undone. Undo the later entries first.`);
  }
  api.updateRows([{ ...row, [entry.columnId]: entry.before }]);
  entry.reverted = true;
  say(describe(n, entry));
  paint();
}
export const actions = {
  revertLast: (api) => {
    const n = history.map((e) => e.reverted || e.undone).lastIndexOf(false) + 1;
    if (n === 0)
      return say('No entry to undo.');
    revert(api, n);
  },
};