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

실행 취소·다시 실행Undo and redo

실수로 고친 값을 Ctrl+Z로 되돌리고 Ctrl+Y로 다시 실행해요. 버튼으로도 할 수 있고, 줄 단위로 고치면 한 줄이 한 단계예요.Take back a mistaken edit with Ctrl+Z and redo it with Ctrl+Y, or use buttons. With row editing, one row is one step.

입문Beginner
직접 써 보기Live preview실행 취소·다시 실행Undo and redo

코드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">
    <select aria-label="고치는 방식" id="mode">
      <option value="cell" selected>칸마다</option>
      <option value="row">줄마다</option>
    </select>
    <button type="button" id="undo">되돌리기</button>
    <button type="button" id="redo">다시 실행</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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('undo').addEventListener('click', () => actions.undo(api));
document.getElementById('redo').addEventListener('click', () => actions.redo(api));
example.js
// 확정한 편집은 저절로 기록돼요. 편집 중이 아닐 때 Ctrl+Z(되돌리기), Ctrl+Y(다시 실행)가 먹고,
// 버튼용으로 undo(), redo(), canUndo(), canRedo()를 쓸 수 있어요.
// editMode: 'row'이면 한 줄에서 고친 칸들이 한 번에 되돌려져요.
export const options = {
  columns: [
    { id: 'item', title: '품목', width: 140, editable: true },
    { id: 'stock', title: '재고', kind: 'number', width: 90, align: 'end', editable: true },
    { id: 'place', title: '보관 위치', width: 140, editable: true },
  ],
  rows: [
    { id: 1, item: '프린터 용지', stock: 120, place: 'A-1 선반' },
    { id: 2, item: '토너 카트리지', stock: 14, place: 'B-3 선반' },
    { id: 3, item: '라벨 스티커', stock: 60, place: 'A-2 선반' },
    { id: 4, item: '무선 마우스', stock: 9, place: 'C-1 선반' },
  ],
  rowKey: 'id',
};
let say = () => { };
// 되돌릴 것이 없을 때는 버튼을 흐리게 해서 누를 수 없게 해요(버튼의 id는 컨트롤 id와 같아요).
function syncButtons(api) {
  for (const [id, can] of [
    ['undo', api.canUndo()],
    ['redo', api.canRedo()],
  ]) {
    const button = document.getElementById(id);
    if (button instanceof HTMLButtonElement)
      button.disabled = !can;
  }
}
export function setup(api, log) {
  say = log;
  const off = [
    api.on('historyChanged', (e) => {
      const what = {
        record: '기록했어요',
        undo: '되돌렸어요',
        redo: '다시 실행했어요',
        clear: '기록을 비웠어요',
      }[e.action];
      const whatEn = { record: 'Recorded', undo: 'Undid', redo: 'Redid', clear: 'Cleared history' }[e.action];
      log({
        ko: `${what} · 되돌릴 수 있는 것 ${e.undoCount}개, 다시 실행할 수 있는 것 ${e.redoCount}개`,
        en: `${whatEn} · ${e.undoCount} steps to undo, ${e.redoCount} steps to redo`,
      });
      syncButtons(api);
    }),
    api.on('rowEditCommitted', (e) => log({
      ko: `${String(e.rowKey)}번 줄: ${e.cells.length}칸을 한 단계로 묶었어요`,
      en: `Row ${String(e.rowKey)}: grouped ${e.cells.length} cells into one step`,
    })),
  ];
  log({
    ko: '칸을 고친 뒤 Ctrl+Z / Ctrl+Y를 눌러 보세요.',
    en: 'Edit cells, then press Ctrl+Z / Ctrl+Y.',
  });
  syncButtons(api);
  return () => off.forEach((fn) => fn());
}
export const actions = {
  undo: (api) => {
    if (!api.undo())
      say({ ko: '되돌릴 편집이 없어요.', en: 'No edit to undo.' });
  },
  redo: (api) => {
    if (!api.redo())
      say({ ko: '다시 실행할 편집이 없어요.', en: 'No edit to redo.' });
  },
  mode: (api, value) => {
    api.clearHistory();
    api.setOptions({ editMode: value === 'row' ? 'row' : 'cell' });
    syncButtons(api);
  },
};

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">
    <select aria-label="Edit unit" id="mode">
      <option value="cell" selected>Per cell</option>
      <option value="row">Per row</option>
    </select>
    <button type="button" id="undo">Undo</button>
    <button type="button" id="redo">Redo</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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('undo').addEventListener('click', () => actions.undo(api));
document.getElementById('redo').addEventListener('click', () => actions.redo(api));
example.js
// Committed edits are recorded automatically. When not editing, Ctrl+Z (undo) and Ctrl+Y (redo) work,
// and undo(), redo(), canUndo(), canRedo() are available for buttons.
// With editMode: 'row', the cells edited in one row are undone together.
export const options = {
  columns: [
    { id: 'item', title: 'Item', width: 140, editable: true },
    { id: 'stock', title: 'Stock', kind: 'number', width: 90, align: 'end', editable: true },
    { id: 'place', title: 'Location', width: 140, editable: true },
  ],
  rows: [
    { id: 1, item: 'Printer paper', stock: 120, place: 'Shelf A-1' },
    { id: 2, item: 'Toner cartridge', stock: 14, place: 'Shelf B-3' },
    { id: 3, item: 'Label stickers', stock: 60, place: 'Shelf A-2' },
    { id: 4, item: 'Wireless mouse', stock: 9, place: 'Shelf C-1' },
  ],
  rowKey: 'id',
};
let say = () => { };
// When there is nothing to undo, dim the button so it cannot be pressed (the button id equals the control id).
function syncButtons(api) {
  for (const [id, can] of [
    ['undo', api.canUndo()],
    ['redo', api.canRedo()],
  ]) {
    const button = document.getElementById(id);
    if (button instanceof HTMLButtonElement)
      button.disabled = !can;
  }
}
export function setup(api, log) {
  say = log;
  const off = [
    api.on('historyChanged', (e) => {
      const what = { record: 'Recorded', undo: 'Undid', redo: 'Redid', clear: 'Cleared history' }[e.action];
      log(`${what} · ${e.undoCount} steps to undo, ${e.redoCount} steps to redo`);
      syncButtons(api);
    }),
    api.on('rowEditCommitted', (e) => log(`Row ${String(e.rowKey)}: grouped ${e.cells.length} cells into one step`)),
  ];
  log('Edit cells, then press Ctrl+Z / Ctrl+Y.');
  syncButtons(api);
  return () => off.forEach((fn) => fn());
}
export const actions = {
  undo: (api) => {
    if (!api.undo())
      say('No edit to undo.');
  },
  redo: (api) => {
    if (!api.redo())
      say('No edit to redo.');
  },
  mode: (api, value) => {
    api.clearHistory();
    api.setOptions({ editMode: value === 'row' ? 'row' : 'cell' });
    syncButtons(api);
  },
};