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

되돌리기 개수 제한과 저장Undo limit and saving

되돌리기 기록은 최근 몇 번까지만 남길 수 있어요. 되돌린 값은 변경 추적에도 반영돼서, 전부 되돌리면 저장할 것이 없어져요.Keep only the latest few undo steps. Undone values also reach change tracking, so undoing everything leaves nothing to save.

활용Intermediate
직접 써 보기Live preview되돌리기 개수 제한과 저장Undo limit and saving

코드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="limit">
      <option value="3" selected>최근 3번</option>
      <option value="100">100번 (기본)</option>
      <option value="0">기록 끄기 (0)</option>
    </select>
    <button type="button" id="undo">되돌리기</button>
    <button type="button" id="redo">다시 실행</button>
    <button type="button" id="clear">기록 비우기</button>
    <button type="button" id="save">저장</button>
  </div>
  <div id="grid" style="height: 300px"></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('limit').addEventListener('change', (event) => actions.limit(api, event.target.value));
document.getElementById('undo').addEventListener('click', () => actions.undo(api));
document.getElementById('redo').addEventListener('click', () => actions.redo(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
example.js
// 저장 결과를 사람이 읽는 말로 바꿔요(status는 영어 코드라서 그대로 보여 주지 않아요).
const saveText = (r, en = false) => {
  const words = {
    saved: ['모두 저장했어요', 'All saved'],
    partial: ['일부만 저장했어요', 'Partly saved'],
    failed: ['저장하지 못했어요', 'Could not save'],
    empty: ['저장할 변경이 없어요', 'No changes to save'],
    invalid: ['값이 맞지 않아 저장하지 않았어요', 'Not saved because a value is not valid'],
    stale: [
      '서버에 더 새로운 값이 있어서 저장하지 못했어요',
      'Could not save because the server has a newer value',
    ],
  };
  const word = words[r.status] ?? ['저장을 마쳤어요', 'Save finished'];
  const counts = r.committed || r.failed
    ? en
      ? ` (${r.committed} succeeded, ${r.failed} failed)`
      : ` (성공 ${r.committed}줄, 실패 ${r.failed}줄)`
    : '';
  return `${word[en ? 1 : 0]}${counts}`;
};
// 되돌리기 기록은 undoLimit개까지만 남겨요(기본 100, 0이면 기록하지 않아요).
// 되돌린 값도 일반 편집처럼 변경 추적에 반영돼서, 전부 되돌리면 저장할 것이 없어져요.
export const options = {
  undoLimit: 3,
  columns: [
    { id: 'name', title: '상품', width: 150, editable: true },
    { id: 'price', title: '가격(원)', kind: 'number', width: 120, align: 'end', editable: true },
  ],
  rows: [
    { id: 1, name: '스탠드 조명', price: 32000 },
    { id: 2, name: '높이 조절 책상', price: 219000 },
    { id: 3, name: '메쉬 의자', price: 148000 },
    { id: 4, name: '모니터 받침대', price: 27000 },
    { id: 5, name: '무소음 키보드', price: 59000 },
  ],
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: async () => {
    await new Promise((resolve) => setTimeout(resolve, 200));
  },
};
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) => {
      syncButtons(api);
      log({
        ko: `${{ record: '기록', undo: '되돌림', redo: '다시 실행', clear: '비움' }[e.action]} · 되돌릴 수 있는 것 ${e.undoCount}개`,
        en: `${{ record: 'Recorded', undo: 'Undid', redo: 'Redid', clear: 'Cleared' }[e.action]} · ${e.undoCount} steps can be undone`,
      });
    }),
    api.on('changesCountChanged', (e) => log({ ko: `저장 안 한 변경 ${e.count}개`, en: `${e.count} unsaved changes` })),
  ];
  log({
    ko: '최근 3번의 편집만 되돌릴 수 있어요. 5개 칸을 차례로 고쳐 보세요.',
    en: 'Only the last 3 edits can be undone. Edit 5 cells one after another.',
  });
  syncButtons(api);
  return () => off.forEach((fn) => fn());
}
export const actions = {
  limit: (api, value) => {
    api.setOptions({ undoLimit: Number(value ?? '3') });
    syncButtons(api);
  },
  undo: (api) => {
    if (!api.undo())
      say({ ko: '되돌릴 편집이 없어요.', en: 'No edit to undo.' });
  },
  redo: (api) => {
    if (!api.redo())
      say({ ko: '다시 실행할 편집이 없어요.', en: 'No edit to redo.' });
  },
  clear: (api) => {
    api.clearHistory();
    say({ ko: '되돌리기 기록을 비웠어요.', en: 'Cleared the undo history.' });
  },
  save: async (api) => {
    if (!api.hasChanges())
      return say({ ko: '저장할 변경이 없어요.', en: 'No changes to save.' });
    const report = await api.save();
    say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
  },
};

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="History size" id="limit">
      <option value="3" selected>Latest 3</option>
      <option value="100">100 (default)</option>
      <option value="0">Off (0)</option>
    </select>
    <button type="button" id="undo">Undo</button>
    <button type="button" id="redo">Redo</button>
    <button type="button" id="clear">Clear history</button>
    <button type="button" id="save">Save</button>
  </div>
  <div id="grid" style="height: 300px"></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('limit').addEventListener('change', (event) => actions.limit(api, event.target.value));
document.getElementById('undo').addEventListener('click', () => actions.undo(api));
document.getElementById('redo').addEventListener('click', () => actions.redo(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
example.js
// Turn the save result into plain words (status is an English code, so it is not shown as is).
const saveText = (r) => {
  const words = {
    saved: 'All saved',
    partial: 'Partly saved',
    failed: 'Could not save',
    empty: 'No changes to save',
    invalid: 'Not saved because a value is not valid',
    stale: 'Could not save because the server has a newer value',
  };
  const word = words[r.status] ?? 'Save finished';
  const counts = r.committed || r.failed ? ` (${r.committed} succeeded, ${r.failed} failed)` : '';
  return `${word}${counts}`;
};
// The undo history keeps at most undoLimit steps (default 100; 0 means nothing is recorded).
// Undone values are reflected in change tracking like normal edits, so undoing everything leaves nothing to save.
export const options = {
  undoLimit: 3,
  columns: [
    { id: 'name', title: 'Product', width: 150, editable: true },
    { id: 'price', title: 'Price ($)', kind: 'number', width: 120, align: 'end', editable: true },
  ],
  rows: [
    { id: 1, name: 'Desk lamp', price: 32 },
    { id: 2, name: 'Height-adjustable desk', price: 219 },
    { id: 3, name: 'Mesh chair', price: 148 },
    { id: 4, name: 'Monitor stand', price: 27 },
    { id: 5, name: 'Silent keyboard', price: 59 },
  ],
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: async () => {
    await new Promise((resolve) => setTimeout(resolve, 200));
  },
};
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) => {
      syncButtons(api);
      log(`${{ record: 'Recorded', undo: 'Undid', redo: 'Redid', clear: 'Cleared' }[e.action]} · ${e.undoCount} steps can be undone`);
    }),
    api.on('changesCountChanged', (e) => log(`${e.count} unsaved changes`)),
  ];
  log('Only the last 3 edits can be undone. Edit 5 cells one after another.');
  syncButtons(api);
  return () => off.forEach((fn) => fn());
}
export const actions = {
  limit: (api, value) => {
    api.setOptions({ undoLimit: Number(value ?? '3') });
    syncButtons(api);
  },
  undo: (api) => {
    if (!api.undo())
      say('No edit to undo.');
  },
  redo: (api) => {
    if (!api.redo())
      say('No edit to redo.');
  },
  clear: (api) => {
    api.clearHistory();
    say('Cleared the undo history.');
  },
  save: async (api) => {
    if (!api.hasChanges())
      return say('No changes to save.');
    const report = await api.save();
    say(`Save result: ${saveText(report)}`);
  },
};