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

저장 시점 만들고 돌아가기Create and restore save points

createSavePoint()는 지금 행의 깊은 복사본을 메모리에 보관하고, restoreSavePoint(id)는 그 모습으로 돌아가요. 최대 20개이고 되살리면 변경 추적과 되돌리기 기록이 비워져요.createSavePoint() keeps a deep copy of the current rows in memory and restoreSavePoint(id) goes back to it. At most 20 are kept, and a restore clears change tracking and the undo history.

입문Beginner
직접 써 보기Live preview저장 시점 만들고 돌아가기Create and restore save points

코드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="create">시점 만들기</button>
    <button type="button" id="mess">고치고 지우기</button>
    <button type="button" id="restore">최근 시점 되살리기</button>
    <button type="button" id="clear">시점 모두 지우기</button>
  </div>
  <div id="grid" style="height: 380px"></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('create').addEventListener('click', () => actions.create(api));
document.getElementById('mess').addEventListener('click', () => actions.mess(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const en = document.documentElement.dataset.lang === 'en';
const names = en
  ? ['Alex', 'Blair', 'Casey', 'Drew', 'Emery', 'Finn']
  : ['김서연', '이준호', '박민지', '최도윤', '정하은', '한지우'];
export const options = {
  columns: [
    { id: 'name', title: en ? 'Name' : '이름', flex: 2, minWidth: 120, editable: true },
    {
      id: 'score',
      title: en ? 'Score' : '점수',
      kind: 'number',
      flex: 1,
      minWidth: 90,
      editable: true,
    },
    { id: 'note', title: en ? 'Note' : '메모', flex: 2, minWidth: 120, editable: true },
  ],
  rows: names.map((name, i) => ({
    id: i + 1,
    name,
    score: 60 + i * 5,
    note: en ? 'Edit me' : '고쳐 보세요',
  })),
  rowKey: 'id',
  saveMode: 'batch',
};
let say = () => { };
const MAX = 20;
const time = (at) => new Date(at).toLocaleTimeString(en ? 'en-US' : 'ko-KR', { hour12: false });
/** 저장 시점 목록(이름·행 수·만든 시각)과 상한을 그리드 위쪽 안내 띠에 계속 보여 줘요. */
function show(api) {
  const points = api.listSavePoints();
  const items = points
    .map((p) => `${p.name} (${p.rowCount}${en ? ' rows' : '행'}, ${time(p.createdAt)})`)
    .join(' · ');
  const head = en
    ? `${points.length} of ${MAX} save points`
    : `저장 시점 ${points.length}/${MAX}개`;
  api.showNotice(items === '' ? `${head}: ${en ? 'none yet' : '아직 없어요'}` : `${head}: ${items}`);
}
export function setup(api, log) {
  say = log;
  show(api);
  const off = api.on('savePointRestored', (e) => say({ ko: `되살렸어요: ${e.name}`, en: `Restored: ${e.name}` }));
  return () => {
    off();
    api.clearNotice();
  };
}
const count = (n) => ({
  ko: `저장 시점 ${n}개`,
  en: `${n} save ${n === 1 ? 'point' : 'points'}`,
});
export const actions = {
  // 지금 모습을 보관해요. 이름을 생략하면 "저장 시점 N"이에요.
  create: (api) => {
    const made = api.createSavePoint();
    show(api);
    const n = api.listSavePoints().length;
    const c = count(n);
    say({ ko: `${c.ko}: ${made.name}`, en: `${c.en}: ${made.name}` });
  },
  // 값을 고치고 줄을 지워 봐요.
  mess: (api) => {
    api.setCellValue(1, 'score', 100);
    api.removeRows([2]);
    say({ ko: '1번 점수를 고치고 2번 행을 지웠어요', en: 'Edited score 1 and removed row 2' });
  },
  // 가장 최근 시점으로 되살려요. 변경 추적과 되돌리기 기록도 비워져요.
  restore: (api) => {
    const last = api.listSavePoints().at(-1);
    if (!last)
      return say({ ko: '먼저 저장 시점을 만드세요', en: 'Create a save point first' });
    api.restoreSavePoint(last.id);
  },
  clear: (api) => {
    api.clearSavePoints();
    show(api);
    say({ ko: '저장 시점을 모두 지웠어요', en: 'Cleared all save points' });
  },
};

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="create">Create point</button>
    <button type="button" id="mess">Mess up</button>
    <button type="button" id="restore">Restore latest</button>
    <button type="button" id="clear">Clear points</button>
  </div>
  <div id="grid" style="height: 380px"></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('create').addEventListener('click', () => actions.create(api));
document.getElementById('mess').addEventListener('click', () => actions.mess(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const names = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Reed', 'Ava Brooks', 'Mason Lee'];
export const options = {
  columns: [
    { id: 'name', title: 'Name', flex: 2, minWidth: 120, editable: true },
    {
      id: 'score',
      title: 'Score',
      kind: 'number',
      flex: 1,
      minWidth: 90,
      editable: true,
    },
    { id: 'note', title: 'Note', flex: 2, minWidth: 120, editable: true },
  ],
  rows: names.map((name, i) => ({
    id: i + 1,
    name,
    score: 60 + i * 5,
    note: 'Edit me',
  })),
  rowKey: 'id',
  saveMode: 'batch',
};
let say = () => { };
const MAX = 20;
const time = (at) => new Date(at).toLocaleTimeString('en-US', { hour12: false });
/** Keeps the list of save points (name, row count, creation time) and the limit visible in the notice strip above the grid. */
function show(api) {
  const points = api.listSavePoints();
  const items = points
    .map((p) => `${p.name} (${p.rowCount} rows, ${time(p.createdAt)})`)
    .join(' · ');
  const head = `${points.length} of ${MAX} save points`;
  api.showNotice(items === '' ? `${head}: none yet` : `${head}: ${items}`);
}
export function setup(api, log) {
  say = log;
  show(api);
  const off = api.on('savePointRestored', (e) => say(`Restored: ${e.name}`));
  return () => {
    off();
    api.clearNotice();
  };
}
const count = (n) => `${n} save ${n === 1 ? 'point' : 'points'}`;
export const actions = {
  // Keeps the current look. Without a name it is "Save point N".
  create: (api) => {
    const made = api.createSavePoint();
    show(api);
    const n = api.listSavePoints().length;
    say(`${count(n)}: ${made.name}`);
  },
  // Edit a value and delete a row.
  mess: (api) => {
    api.setCellValue(1, 'score', 100);
    api.removeRows([2]);
    say('Edited score 1 and removed row 2');
  },
  // Restore the most recent save point. Change tracking and the undo history are cleared too.
  restore: (api) => {
    const last = api.listSavePoints().at(-1);
    if (!last)
      return say('Create a save point first');
    api.restoreSavePoint(last.id);
  },
  clear: (api) => {
    api.clearSavePoints();
    show(api);
    say('Cleared all save points');
  },
};