편집 기록에서 골라 되돌리기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.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));// 예제 틀이 알려 주는 페이지 언어(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);
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>편집 기록에서 골라 되돌리기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="revertLast">마지막 기록 되돌리기</button>
</div>
<div id="grid" style="height: 270px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 확정한 편집을 번호를 붙여 기록해요. 되돌리기(undo)는 항상 마지막 것부터지만,
// 여기서는 번호를 골라 그 편집만 되돌려요. 이후에 다른 칸을 고쳤어도 상관없어요.
let history = [];
let say = () => { };
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);
});
}
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();
}
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);
},
};
options.ariaLabel = "편집 기록에서 골라 되돌리기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('revertLast').addEventListener('click', () => actions.revertLast(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.revertLast(api)}
>마지막 기록 되돌리기</button>
</div>
<Grid style={{ height: 270 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, RowKey } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
campaign: string;
status: string;
}
interface Entry {
key: RowKey;
columnId: string;
before: unknown;
after: unknown;
reverted: boolean;
undone: boolean; // Ctrl+Z나 되돌리기 버튼(전체 되돌리기 기록)으로 되돌려진 상태
}
// 확정한 편집을 번호를 붙여 기록해요. 되돌리기(undo)는 항상 마지막 것부터지만,
// 여기서는 번호를 골라 그 편집만 되돌려요. 이후에 다른 칸을 고쳤어도 상관없어요.
let history: Entry[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
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: number, e: Entry): string =>
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: HTMLElement | null = null;
let grid: GridApi<Row> | null = null;
// 표 아래에 편집 기록 목록을 직접 그려요. 줄마다 "되돌리기" 버튼이 있고, 되돌린 기록은 줄이 그어져요.
function paint(): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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] as Entry));
paint();
});
// 키(Ctrl+Z·Ctrl+Y), 버튼, 코드 어느 쪽으로 되돌려도 목록이 따라가게, 되돌리기 기록의 변화를 직접 받아요.
const undoneStack: Entry[] = [];
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: GridApi<Row>, n: number): void {
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 as keyof Row] !== 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: GridApi<Row>) => {
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);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.revertLast(api)"
>마지막 기록 되돌리기</button>
</div>
<Grid style="height: 270px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, RowKey } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
campaign: string;
status: string;
}
interface Entry {
key: RowKey;
columnId: string;
before: unknown;
after: unknown;
reverted: boolean;
undone: boolean; // Ctrl+Z나 되돌리기 버튼(전체 되돌리기 기록)으로 되돌려진 상태
}
// 확정한 편집을 번호를 붙여 기록해요. 되돌리기(undo)는 항상 마지막 것부터지만,
// 여기서는 번호를 골라 그 편집만 되돌려요. 이후에 다른 칸을 고쳤어도 상관없어요.
let history: Entry[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
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: number, e: Entry): string =>
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: HTMLElement | null = null;
let grid: GridApi<Row> | null = null;
// 표 아래에 편집 기록 목록을 직접 그려요. 줄마다 "되돌리기" 버튼이 있고, 되돌린 기록은 줄이 그어져요.
function paint(): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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] as Entry));
paint();
});
// 키(Ctrl+Z·Ctrl+Y), 버튼, 코드 어느 쪽으로 되돌려도 목록이 따라가게, 되돌리기 기록의 변화를 직접 받아요.
const undoneStack: Entry[] = [];
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: GridApi<Row>, n: number): void {
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 as keyof Row] !== 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: GridApi<Row>) => {
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);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.revertLast(api)"
>마지막 기록 되돌리기</button>
</div>
<mx-grid style="height: 270px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, RowKey } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
campaign: string;
status: string;
}
interface Entry {
key: RowKey;
columnId: string;
before: unknown;
after: unknown;
reverted: boolean;
undone: boolean; // Ctrl+Z나 되돌리기 버튼(전체 되돌리기 기록)으로 되돌려진 상태
}
// 확정한 편집을 번호를 붙여 기록해요. 되돌리기(undo)는 항상 마지막 것부터지만,
// 여기서는 번호를 골라 그 편집만 되돌려요. 이후에 다른 칸을 고쳤어도 상관없어요.
let history: Entry[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
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: number, e: Entry): string =>
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: HTMLElement | null = null;
let grid: GridApi<Row> | null = null;
// 표 아래에 편집 기록 목록을 직접 그려요. 줄마다 "되돌리기" 버튼이 있고, 되돌린 기록은 줄이 그어져요.
function paint(): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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] as Entry));
paint();
});
// 키(Ctrl+Z·Ctrl+Y), 버튼, 코드 어느 쪽으로 되돌려도 목록이 따라가게, 되돌리기 기록의 변화를 직접 받아요.
const undoneStack: Entry[] = [];
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: GridApi<Row>, n: number): void {
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 as keyof Row] !== 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: GridApi<Row>) => {
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);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<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>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));// 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);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Pick an entry from the edit history</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="revertLast">Revert latest entry</button>
</div>
<div id="grid" style="height: 270px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 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 = () => { };
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);
});
}
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();
}
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);
},
};
options.ariaLabel = "Pick an entry from the edit history";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('revertLast').addEventListener('click', () => actions.revertLast(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.revertLast(api)}
>Revert latest entry</button>
</div>
<Grid style={{ height: 270 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, RowKey } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
campaign: string;
status: string;
}
interface Entry {
key: RowKey;
columnId: string;
before: unknown;
after: unknown;
reverted: boolean;
undone: boolean; // undone with Ctrl+Z or the undo button (the whole-history undo)
}
// 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: Entry[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
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: number, e: Entry): string =>
`#${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: HTMLElement | null = null;
let grid: GridApi<Row> | null = 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(): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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] as Entry));
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: Entry[] = [];
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: GridApi<Row>, n: number): void {
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 as keyof Row] !== 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: GridApi<Row>) => {
const n = history.map((e) => e.reverted || e.undone).lastIndexOf(false) + 1;
if (n === 0) return say('No entry to undo.');
revert(api, n);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.revertLast(api)"
>Revert latest entry</button>
</div>
<Grid style="height: 270px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, RowKey } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
campaign: string;
status: string;
}
interface Entry {
key: RowKey;
columnId: string;
before: unknown;
after: unknown;
reverted: boolean;
undone: boolean; // undone with Ctrl+Z or the undo button (the whole-history undo)
}
// 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: Entry[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
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: number, e: Entry): string =>
`#${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: HTMLElement | null = null;
let grid: GridApi<Row> | null = 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(): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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] as Entry));
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: Entry[] = [];
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: GridApi<Row>, n: number): void {
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 as keyof Row] !== 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: GridApi<Row>) => {
const n = history.map((e) => e.reverted || e.undone).lastIndexOf(false) + 1;
if (n === 0) return say('No entry to undo.');
revert(api, n);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.revertLast(api)"
>Revert latest entry</button>
</div>
<mx-grid style="height: 270px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, RowKey } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
campaign: string;
status: string;
}
interface Entry {
key: RowKey;
columnId: string;
before: unknown;
after: unknown;
reverted: boolean;
undone: boolean; // undone with Ctrl+Z or the undo button (the whole-history undo)
}
// 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: Entry[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
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: number, e: Entry): string =>
`#${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: HTMLElement | null = null;
let grid: GridApi<Row> | null = 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(): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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] as Entry));
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: Entry[] = [];
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: GridApi<Row>, n: number): void {
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 as keyof Row] !== 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: GridApi<Row>) => {
const n = history.map((e) => e.reverted || e.undone).lastIndexOf(false) + 1;
if (n === 0) return say('No entry to undo.');
revert(api, n);
},
};