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

행 삭제와 수정도 되돌리기Undo row removal and row updates

removeRows와 updateRows로 바꾼 것도 셀 편집과 같은 되돌리기 기록에 쌓여요. 한 번 부른 것이 한 단계예요.Changes made with removeRows and updateRows go into the same undo history as cell edits. One call is one step.

입문Beginner
직접 써 보기Live preview행 삭제와 수정도 되돌리기Undo row removal and row updates

코드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="remove">2행 삭제</button>
    <button type="button" id="refill">채우기</button>
    <button type="button" id="undo">되돌리기</button>
    <button type="button" id="redo">다시 실행</button>
  </div>
  <div id="grid" style="height: 172px"></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('remove').addEventListener('click', () => actions.remove(api));
document.getElementById('refill').addEventListener('click', () => actions.refill(api));
document.getElementById('undo').addEventListener('click', () => actions.undo(api));
document.getElementById('redo').addEventListener('click', () => actions.redo(api));
example.js
export const options = {
  columns: [
    { id: 'item', title: '품목', width: 160 },
    { id: 'stock', title: '재고', kind: 'number', width: 90, align: 'end' },
  ],
  rows: [
    { id: 1, item: '프린터 용지', stock: 120 },
    { id: 2, item: '토너 카트리지', stock: 14 },
    { id: 3, item: '라벨 스티커', stock: 60 },
    { id: 4, item: '무선 마우스', stock: 9 },
  ],
  rowKey: 'id',
};
let say = () => { };
// 방금 한 일을 기록 줄에 쉬운 말로 적으려고 기억해 둬요.
let lastWork = { ko: '', en: '' };
// 할 일이 없는 버튼은 흐리게(비활성) 해서, 눌러도 아무 일 없는 상태를 미리 보여 줘요.
function refreshButtons(api) {
  const set = (id, disabled) => {
    const el = document.getElementById(id);
    if (el instanceof HTMLButtonElement)
      el.disabled = disabled;
  };
  const empty = api.getRowCount() === 0;
  set('remove', empty);
  set('refill', empty);
  set('undo', !api.canUndo());
  set('redo', !api.canRedo());
}
const WORDS = {
  record: () => lastWork,
  undo: () => ({ ko: '한 단계 되돌렸어요', en: 'Undid one step' }),
  redo: () => ({ ko: '한 단계 다시 실행했어요', en: 'Redid one step' }),
  clear: () => ({ ko: '기록을 모두 비웠어요', en: 'Cleared the whole history' }),
};
export function setup(api, log) {
  say = log;
  refreshButtons(api);
  const offs = [
    api.on('historyChanged', (e) => {
      const word = WORDS[e.action]();
      log({
        ko: `${word.ko} · 되돌릴 수 있는 단계 ${e.undoCount}개, 다시 할 수 있는 단계 ${e.redoCount}개`,
        en: `${word.en} · ${e.undoCount} steps to undo, ${e.redoCount} steps to redo`,
      });
      refreshButtons(api);
    }),
    api.on('rowsChanged', () => refreshButtons(api)),
  ];
  return () => offs.forEach((off) => off());
}
// removeRows와 updateRows는 한 번 부르면 되돌리기 한 단계가 돼요. 다시 실행은 Ctrl+Y예요.
export const actions = {
  remove: (api) => {
    const keys = api
      .getRows()
      .slice(0, 2)
      .map((row) => row.id);
    if (keys.length === 0)
      return say({
        ko: '지울 행이 없어요. 되돌리기로 되살려 보세요',
        en: 'No row to delete. Use undo to bring them back',
      });
    lastWork = {
      ko: `앞의 ${keys.length}행을 지웠어요`,
      en: `Deleted the first ${keys.length} rows`,
    };
    api.removeRows(keys);
  },
  refill: (api) => {
    if (api.getRowCount() === 0)
      return say({
        ko: '채울 행이 없어요. 되돌리기로 되살려 보세요',
        en: 'No row to fill. Use undo to bring them back',
      });
    lastWork = { ko: '재고를 모두 100으로 채웠어요', en: 'Filled every stock with 100' };
    api.updateRows(api.getRows().map((row) => ({ ...row, stock: 100 })));
  },
  undo: (api) => {
    if (!api.undo())
      say({ ko: '되돌릴 것이 없어요', en: 'Nothing to undo' });
  },
  redo: (api) => {
    if (!api.redo())
      say({ ko: '다시 실행할 것이 없어요', en: 'Nothing to redo' });
  },
};

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="remove">Delete 2</button>
    <button type="button" id="refill">Refill</button>
    <button type="button" id="undo">Undo</button>
    <button type="button" id="redo">Redo</button>
  </div>
  <div id="grid" style="height: 172px"></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('remove').addEventListener('click', () => actions.remove(api));
document.getElementById('refill').addEventListener('click', () => actions.refill(api));
document.getElementById('undo').addEventListener('click', () => actions.undo(api));
document.getElementById('redo').addEventListener('click', () => actions.redo(api));
example.js
export const options = {
  columns: [
    { id: 'item', title: 'Item', width: 160 },
    { id: 'stock', title: 'Stock', kind: 'number', width: 90, align: 'end' },
  ],
  rows: [
    { id: 1, item: 'Printer paper', stock: 120 },
    { id: 2, item: 'Toner cartridge', stock: 14 },
    { id: 3, item: 'Label stickers', stock: 60 },
    { id: 4, item: 'Wireless mouse', stock: 9 },
  ],
  rowKey: 'id',
};
let say = () => { };
// Remember what was just done so the log line can describe it in plain words.
let lastWork = '';
// Dim buttons that have nothing to do, so a press that would do nothing is visible beforehand.
function refreshButtons(api) {
  const set = (id, disabled) => {
    const el = document.getElementById(id);
    if (el instanceof HTMLButtonElement)
      el.disabled = disabled;
  };
  const empty = api.getRowCount() === 0;
  set('remove', empty);
  set('refill', empty);
  set('undo', !api.canUndo());
  set('redo', !api.canRedo());
}
const WORDS = {
  record: () => lastWork,
  undo: () => 'Undid one step',
  redo: () => 'Redid one step',
  clear: () => 'Cleared the whole history',
};
export function setup(api, log) {
  say = log;
  refreshButtons(api);
  const offs = [
    api.on('historyChanged', (e) => {
      const word = WORDS[e.action]();
      log(`${word} · ${e.undoCount} steps to undo, ${e.redoCount} steps to redo`);
      refreshButtons(api);
    }),
    api.on('rowsChanged', () => refreshButtons(api)),
  ];
  return () => offs.forEach((off) => off());
}
// One call to removeRows or updateRows is one undo step. Redo is Ctrl+Y.
export const actions = {
  remove: (api) => {
    const keys = api
      .getRows()
      .slice(0, 2)
      .map((row) => row.id);
    if (keys.length === 0)
      return say('No row to delete. Use undo to bring them back');
    lastWork = `Deleted the first ${keys.length} rows`;
    api.removeRows(keys);
  },
  refill: (api) => {
    if (api.getRowCount() === 0)
      return say('No row to fill. Use undo to bring them back');
    lastWork = 'Filled every stock with 100';
    api.updateRows(api.getRows().map((row) => ({ ...row, stock: 100 })));
  },
  undo: (api) => {
    if (!api.undo())
      say('Nothing to undo');
  },
  redo: (api) => {
    if (!api.redo())
      say('Nothing to redo');
  },
};