바뀐 것 표시하고 되돌리기See what changed and take it back
저장하기 전까지 고친 값은 "변경"으로 쌓여요. 고친 칸에는 표시가 붙고, 추가·삭제한 줄도 구분돼요. 바뀐 내용은 원래 값과 지금 값을 나란히 한눈에 보고, 한 줄만 또는 전부 원래대로 돌릴 수 있어요.Until you save, edits pile up as changes. Changed cells are marked and added or removed rows are distinguished. See the change set as a code-style diff, and revert one row or everything.
코드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="add">직원 추가</button>
<button type="button" id="removeSelected">고른 줄 삭제</button>
<button type="button" id="revertSelected">고른 줄만 되돌리기</button>
<button type="button" id="rollback">모두 되돌리기</button>
<button type="button" id="commit">지금 값을 기준으로</button>
</div>
<div id="grid" style="height: 330px"></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('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('revertSelected').addEventListener('click', () => actions.revertSelected(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(api));
document.getElementById('commit').addEventListener('click', () => actions.commit(api));const names = ['김서연', '이준호', '박민지', '최도윤', '정하은'];
const departments = ['개발', '디자인', '기획', '영업', '개발'];
const rows = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i],
salary: 3800 + i * 300,
}));
let nextId = 100;
// saveMode: 'batch'(기본)에서는 고친 값이 바로 저장되지 않고 "변경"으로 쌓여요.
// 고친 칸에는 표시가 붙고(원래 값으로 되돌리면 사라져요), 추가한 줄·삭제한 줄도 표시돼요.
// getChanges()는 줄마다 "무엇이 어떻게 바뀌었는지" 알려 주고, rollbackChanges()는 모두 원래대로 돌려요.
export const options = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = () => document.documentElement.dataset.lang === 'en';
const STATE_NAMES = {
ko: { added: '추가', modified: '수정', removed: '삭제' },
en: { added: 'added', modified: 'modified', removed: 'deleted' },
};
const stateName = (state, en) => STATE_NAMES[en ? 'en' : 'ko'][state] ?? state;
// 변경을 코드 diff처럼 보여 줘요: "-"는 원래 값, "+"는 지금 값이에요.
function diff(api, en = isEn()) {
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines = [];
for (const change of api.getChanges()) {
lines.push(en
? `Row ${change.key} (${stateName(change.state, en)})`
: `${change.key}번 줄 (${stateName(change.state, en)})`);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
}
else {
lines.push(`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`);
}
}
return lines.length ? lines.join('\n') : en ? 'Nothing changed' : '(바뀐 것이 없어요)';
}
let say = () => { };
export function setup(api, log) {
say = log;
log({
ko: '칸을 고쳐 보세요. 고친 칸에 표시가 붙고 아래에 바뀐 내용이 나와요.',
en: 'Edit a cell. The edited cell gets a mark and the changes appear below.',
});
return api.on('changesCountChanged', ({ count, added, modified, removed }) => log({
ko: `변경 ${count}줄 — 추가 ${added}, 수정 ${modified}, 삭제 ${removed}\n${diff(api, false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api, true)}`,
}));
}
export const actions = {
add: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
// 고른 줄만 원래 값으로 돌려요: 바뀐 칸마다 oldValue를 되살려서 다시 넣어요.
revertSelected: (api) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length)
api.updateRows(back);
else
say({
ko: '돌릴 줄이 없어요. 고친 줄을 Space로 골라 두고 눌러 보세요',
en: 'No selected edited row to revert. Select an edited row (Space) first',
});
},
rollback: (api) => api.rollbackChanges(),
// 지금 상태를 새 기준으로 삼아요(서버에 저장한 뒤에 하는 일이에요). 표시와 변경 기록이 모두 지워져요.
commit: (api) => api.commitChanges(),
};<!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="add">직원 추가</button>
<button type="button" id="removeSelected">고른 줄 삭제</button>
<button type="button" id="revertSelected">고른 줄만 되돌리기</button>
<button type="button" id="rollback">모두 되돌리기</button>
<button type="button" id="commit">지금 값을 기준으로</button>
</div>
<div id="grid" style="height: 330px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은'];
const departments = ['개발', '디자인', '기획', '영업', '개발'];
const rows = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i],
salary: 3800 + i * 300,
}));
let nextId = 100;
// saveMode: 'batch'(기본)에서는 고친 값이 바로 저장되지 않고 "변경"으로 쌓여요.
// 고친 칸에는 표시가 붙고(원래 값으로 되돌리면 사라져요), 추가한 줄·삭제한 줄도 표시돼요.
// getChanges()는 줄마다 "무엇이 어떻게 바뀌었는지" 알려 주고, rollbackChanges()는 모두 원래대로 돌려요.
const options = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = () => document.documentElement.dataset.lang === 'en';
const STATE_NAMES = {
ko: { added: '추가', modified: '수정', removed: '삭제' },
en: { added: 'added', modified: 'modified', removed: 'deleted' },
};
const stateName = (state, en) => STATE_NAMES[en ? 'en' : 'ko'][state] ?? state;
// 변경을 코드 diff처럼 보여 줘요: "-"는 원래 값, "+"는 지금 값이에요.
function diff(api, en = isEn()) {
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines = [];
for (const change of api.getChanges()) {
lines.push(en
? `Row ${change.key} (${stateName(change.state, en)})`
: `${change.key}번 줄 (${stateName(change.state, en)})`);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
}
else {
lines.push(`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`);
}
}
return lines.length ? lines.join('\n') : en ? 'Nothing changed' : '(바뀐 것이 없어요)';
}
let say = () => { };
function setup(api, log) {
say = log;
log({
ko: '칸을 고쳐 보세요. 고친 칸에 표시가 붙고 아래에 바뀐 내용이 나와요.',
en: 'Edit a cell. The edited cell gets a mark and the changes appear below.',
});
return api.on('changesCountChanged', ({ count, added, modified, removed }) => log({
ko: `변경 ${count}줄 — 추가 ${added}, 수정 ${modified}, 삭제 ${removed}\n${diff(api, false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api, true)}`,
}));
}
const actions = {
add: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
// 고른 줄만 원래 값으로 돌려요: 바뀐 칸마다 oldValue를 되살려서 다시 넣어요.
revertSelected: (api) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length)
api.updateRows(back);
else
say({
ko: '돌릴 줄이 없어요. 고친 줄을 Space로 골라 두고 눌러 보세요',
en: 'No selected edited row to revert. Select an edited row (Space) first',
});
},
rollback: (api) => api.rollbackChanges(),
// 지금 상태를 새 기준으로 삼아요(서버에 저장한 뒤에 하는 일이에요). 표시와 변경 기록이 모두 지워져요.
commit: (api) => api.commitChanges(),
};
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('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('revertSelected').addEventListener('click', () => actions.revertSelected(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(api));
document.getElementById('commit').addEventListener('click', () => actions.commit(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.add(api)}
>직원 추가</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSelected(api)}
>고른 줄 삭제</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.revertSelected(api)}
>고른 줄만 되돌리기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.rollback(api)}
>모두 되돌리기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.commit(api)}
>지금 값을 기준으로</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은'];
const departments = ['개발', '디자인', '기획', '영업', '개발'];
const rows: Row[] = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i] as string,
salary: 3800 + i * 300,
}));
let nextId = 100;
// saveMode: 'batch'(기본)에서는 고친 값이 바로 저장되지 않고 "변경"으로 쌓여요.
// 고친 칸에는 표시가 붙고(원래 값으로 되돌리면 사라져요), 추가한 줄·삭제한 줄도 표시돼요.
// getChanges()는 줄마다 "무엇이 어떻게 바뀌었는지" 알려 주고, rollbackChanges()는 모두 원래대로 돌려요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = (): boolean => document.documentElement.dataset.lang === 'en';
const STATE_NAMES = {
ko: { added: '추가', modified: '수정', removed: '삭제' },
en: { added: 'added', modified: 'modified', removed: 'deleted' },
} as const;
const stateName = (state: string, en: boolean): string =>
(STATE_NAMES[en ? 'en' : 'ko'] as Record<string, string>)[state] ?? state;
// 변경을 코드 diff처럼 보여 줘요: "-"는 원래 값, "+"는 지금 값이에요.
function diff(api: GridApi<Row>, en = isEn()): string {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [];
for (const change of api.getChanges()) {
lines.push(
en
? `Row ${change.key} (${stateName(change.state, en)})`
: `${change.key}번 줄 (${stateName(change.state, en)})`,
);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
} else {
lines.push(
`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`,
);
}
}
return lines.length ? lines.join('\n') : en ? 'Nothing changed' : '(바뀐 것이 없어요)';
}
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 고쳐 보세요. 고친 칸에 표시가 붙고 아래에 바뀐 내용이 나와요.',
en: 'Edit a cell. The edited cell gets a mark and the changes appear below.',
});
return api.on('changesCountChanged', ({ count, added, modified, removed }) =>
log({
ko: `변경 ${count}줄 — 추가 ${added}, 수정 ${modified}, 삭제 ${removed}\n${diff(api, false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api, true)}`,
}),
);
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// 고른 줄만 원래 값으로 돌려요: 바뀐 칸마다 oldValue를 되살려서 다시 넣어요.
revertSelected: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length) api.updateRows(back);
else
say({
ko: '돌릴 줄이 없어요. 고친 줄을 Space로 골라 두고 눌러 보세요',
en: 'No selected edited row to revert. Select an edited row (Space) first',
});
},
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
// 지금 상태를 새 기준으로 삼아요(서버에 저장한 뒤에 하는 일이에요). 표시와 변경 기록이 모두 지워져요.
commit: (api: GridApi<Row>) => api.commitChanges(),
};버튼을 누르면 이 예제의 코드가 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.add(api)">직원 추가</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSelected(api)"
>고른 줄 삭제</button>
<button
type="button"
:disabled="!api"
@click="api && actions.revertSelected(api)"
>고른 줄만 되돌리기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.rollback(api)"
>모두 되돌리기</button>
<button type="button" :disabled="!api" @click="api && actions.commit(api)">지금 값을 기준으로</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은'];
const departments = ['개발', '디자인', '기획', '영업', '개발'];
const rows: Row[] = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i] as string,
salary: 3800 + i * 300,
}));
let nextId = 100;
// saveMode: 'batch'(기본)에서는 고친 값이 바로 저장되지 않고 "변경"으로 쌓여요.
// 고친 칸에는 표시가 붙고(원래 값으로 되돌리면 사라져요), 추가한 줄·삭제한 줄도 표시돼요.
// getChanges()는 줄마다 "무엇이 어떻게 바뀌었는지" 알려 주고, rollbackChanges()는 모두 원래대로 돌려요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = (): boolean => document.documentElement.dataset.lang === 'en';
const STATE_NAMES = {
ko: { added: '추가', modified: '수정', removed: '삭제' },
en: { added: 'added', modified: 'modified', removed: 'deleted' },
} as const;
const stateName = (state: string, en: boolean): string =>
(STATE_NAMES[en ? 'en' : 'ko'] as Record<string, string>)[state] ?? state;
// 변경을 코드 diff처럼 보여 줘요: "-"는 원래 값, "+"는 지금 값이에요.
function diff(api: GridApi<Row>, en = isEn()): string {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [];
for (const change of api.getChanges()) {
lines.push(
en
? `Row ${change.key} (${stateName(change.state, en)})`
: `${change.key}번 줄 (${stateName(change.state, en)})`,
);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
} else {
lines.push(
`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`,
);
}
}
return lines.length ? lines.join('\n') : en ? 'Nothing changed' : '(바뀐 것이 없어요)';
}
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 고쳐 보세요. 고친 칸에 표시가 붙고 아래에 바뀐 내용이 나와요.',
en: 'Edit a cell. The edited cell gets a mark and the changes appear below.',
});
return api.on('changesCountChanged', ({ count, added, modified, removed }) =>
log({
ko: `변경 ${count}줄 — 추가 ${added}, 수정 ${modified}, 삭제 ${removed}\n${diff(api, false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api, true)}`,
}),
);
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// 고른 줄만 원래 값으로 돌려요: 바뀐 칸마다 oldValue를 되살려서 다시 넣어요.
revertSelected: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length) api.updateRows(back);
else
say({
ko: '돌릴 줄이 없어요. 고친 줄을 Space로 골라 두고 눌러 보세요',
en: 'No selected edited row to revert. Select an edited row (Space) first',
});
},
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
// 지금 상태를 새 기준으로 삼아요(서버에 저장한 뒤에 하는 일이에요). 표시와 변경 기록이 모두 지워져요.
commit: (api: GridApi<Row>) => api.commitChanges(),
};버튼을 누르면 이 예제의 코드가 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.add(api)"
>직원 추가</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSelected(api)"
>고른 줄 삭제</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.revertSelected(api)"
>고른 줄만 되돌리기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.rollback(api)"
>모두 되돌리기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.commit(api)"
>지금 값을 기준으로</button>
</div>
<mx-grid style="height: 330px" [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 } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은'];
const departments = ['개발', '디자인', '기획', '영업', '개발'];
const rows: Row[] = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i] as string,
salary: 3800 + i * 300,
}));
let nextId = 100;
// saveMode: 'batch'(기본)에서는 고친 값이 바로 저장되지 않고 "변경"으로 쌓여요.
// 고친 칸에는 표시가 붙고(원래 값으로 되돌리면 사라져요), 추가한 줄·삭제한 줄도 표시돼요.
// getChanges()는 줄마다 "무엇이 어떻게 바뀌었는지" 알려 주고, rollbackChanges()는 모두 원래대로 돌려요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const isEn = (): boolean => document.documentElement.dataset.lang === 'en';
const STATE_NAMES = {
ko: { added: '추가', modified: '수정', removed: '삭제' },
en: { added: 'added', modified: 'modified', removed: 'deleted' },
} as const;
const stateName = (state: string, en: boolean): string =>
(STATE_NAMES[en ? 'en' : 'ko'] as Record<string, string>)[state] ?? state;
// 변경을 코드 diff처럼 보여 줘요: "-"는 원래 값, "+"는 지금 값이에요.
function diff(api: GridApi<Row>, en = isEn()): string {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [];
for (const change of api.getChanges()) {
lines.push(
en
? `Row ${change.key} (${stateName(change.state, en)})`
: `${change.key}번 줄 (${stateName(change.state, en)})`,
);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
} else {
lines.push(
`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`,
);
}
}
return lines.length ? lines.join('\n') : en ? 'Nothing changed' : '(바뀐 것이 없어요)';
}
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 고쳐 보세요. 고친 칸에 표시가 붙고 아래에 바뀐 내용이 나와요.',
en: 'Edit a cell. The edited cell gets a mark and the changes appear below.',
});
return api.on('changesCountChanged', ({ count, added, modified, removed }) =>
log({
ko: `변경 ${count}줄 — 추가 ${added}, 수정 ${modified}, 삭제 ${removed}\n${diff(api, false)}`,
en: `${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api, true)}`,
}),
);
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '새 직원', department: '개발', salary: 3500 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// 고른 줄만 원래 값으로 돌려요: 바뀐 칸마다 oldValue를 되살려서 다시 넣어요.
revertSelected: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length) api.updateRows(back);
else
say({
ko: '돌릴 줄이 없어요. 고친 줄을 Space로 골라 두고 눌러 보세요',
en: 'No selected edited row to revert. Select an edited row (Space) first',
});
},
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
// 지금 상태를 새 기준으로 삼아요(서버에 저장한 뒤에 하는 일이에요). 표시와 변경 기록이 모두 지워져요.
commit: (api: GridApi<Row>) => api.commitChanges(),
};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="add">Add employee</button>
<button type="button" id="removeSelected">Delete selected</button>
<button type="button" id="revertSelected">Revert selected</button>
<button type="button" id="rollback">Revert all</button>
<button type="button" id="commit">Use current values as baseline</button>
</div>
<div id="grid" style="height: 330px"></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('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('revertSelected').addEventListener('click', () => actions.revertSelected(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(api));
document.getElementById('commit').addEventListener('click', () => actions.commit(api));const names = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Reed', 'Ava Brooks'];
const departments = ['Dev', 'Design', 'Planning', 'Sales', 'Dev'];
const rows = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i],
salary: 38000 + i * 3000,
}));
let nextId = 100;
// With saveMode: 'batch' (the default), edited values are not saved at once but pile up as "changes".
// An edited cell gets a mark (it disappears if you restore the original value); added and deleted rows are marked too.
// getChanges() tells, per row, what changed and how, and rollbackChanges() restores everything.
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 130, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const STATE_NAMES = {
added: 'added',
modified: 'modified',
removed: 'deleted',
};
// Show the changes like a code diff: "-" is the original value, "+" is the current one.
function diff(api) {
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines = [];
for (const change of api.getChanges()) {
lines.push(`Row ${change.key} (${STATE_NAMES[change.state] ?? change.state})`);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
}
else {
lines.push(`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`);
}
}
return lines.length ? lines.join('\n') : 'Nothing changed';
}
let say = () => { };
export function setup(api, log) {
say = log;
log('Edit a cell. The edited cell gets a mark and the changes appear below.');
return api.on('changesCountChanged', ({ count, added, modified, removed }) => log(`${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api)}`));
}
export const actions = {
add: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
// Restore only the selected rows: bring back oldValue for each changed cell and put it in again.
revertSelected: (api) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length)
api.updateRows(back);
else
say('No selected edited row to revert. Select an edited row (Space) first');
},
rollback: (api) => api.rollbackChanges(),
// Take the current state as the new baseline (done after saving to the server). All marks and the change record are cleared.
commit: (api) => api.commitChanges(),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>See what changed and take it back</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="add">Add employee</button>
<button type="button" id="removeSelected">Delete selected</button>
<button type="button" id="revertSelected">Revert selected</button>
<button type="button" id="rollback">Revert all</button>
<button type="button" id="commit">Use current values as baseline</button>
</div>
<div id="grid" style="height: 330px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Reed', 'Ava Brooks'];
const departments = ['Dev', 'Design', 'Planning', 'Sales', 'Dev'];
const rows = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i],
salary: 38000 + i * 3000,
}));
let nextId = 100;
// With saveMode: 'batch' (the default), edited values are not saved at once but pile up as "changes".
// An edited cell gets a mark (it disappears if you restore the original value); added and deleted rows are marked too.
// getChanges() tells, per row, what changed and how, and rollbackChanges() restores everything.
const options = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 130, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const STATE_NAMES = {
added: 'added',
modified: 'modified',
removed: 'deleted',
};
// Show the changes like a code diff: "-" is the original value, "+" is the current one.
function diff(api) {
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines = [];
for (const change of api.getChanges()) {
lines.push(`Row ${change.key} (${STATE_NAMES[change.state] ?? change.state})`);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
}
else {
lines.push(`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`);
}
}
return lines.length ? lines.join('\n') : 'Nothing changed';
}
let say = () => { };
function setup(api, log) {
say = log;
log('Edit a cell. The edited cell gets a mark and the changes appear below.');
return api.on('changesCountChanged', ({ count, added, modified, removed }) => log(`${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api)}`));
}
const actions = {
add: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api) => api.removeRows(api.getSelectedKeys()),
// Restore only the selected rows: bring back oldValue for each changed cell and put it in again.
revertSelected: (api) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length)
api.updateRows(back);
else
say('No selected edited row to revert. Select an edited row (Space) first');
},
rollback: (api) => api.rollbackChanges(),
// Take the current state as the new baseline (done after saving to the server). All marks and the change record are cleared.
commit: (api) => api.commitChanges(),
};
options.ariaLabel = "See what changed and take it back";
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('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('revertSelected').addEventListener('click', () => actions.revertSelected(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(api));
document.getElementById('commit').addEventListener('click', () => actions.commit(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.add(api)}
>Add employee</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSelected(api)}
>Delete selected</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.revertSelected(api)}
>Revert selected</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.rollback(api)}
>Revert all</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.commit(api)}
>Use current values as baseline</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const names = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Reed', 'Ava Brooks'];
const departments = ['Dev', 'Design', 'Planning', 'Sales', 'Dev'];
const rows: Row[] = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i] as string,
salary: 38000 + i * 3000,
}));
let nextId = 100;
// With saveMode: 'batch' (the default), edited values are not saved at once but pile up as "changes".
// An edited cell gets a mark (it disappears if you restore the original value); added and deleted rows are marked too.
// getChanges() tells, per row, what changed and how, and rollbackChanges() restores everything.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 130, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const STATE_NAMES: Record<string, string> = {
added: 'added',
modified: 'modified',
removed: 'deleted',
};
// Show the changes like a code diff: "-" is the original value, "+" is the current one.
function diff(api: GridApi<Row>): string {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [];
for (const change of api.getChanges()) {
lines.push(`Row ${change.key} (${STATE_NAMES[change.state] ?? change.state})`);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
} else {
lines.push(
`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`,
);
}
}
return lines.length ? lines.join('\n') : 'Nothing changed';
}
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Edit a cell. The edited cell gets a mark and the changes appear below.');
return api.on('changesCountChanged', ({ count, added, modified, removed }) =>
log(
`${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api)}`,
),
);
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// Restore only the selected rows: bring back oldValue for each changed cell and put it in again.
revertSelected: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length) api.updateRows(back);
else say('No selected edited row to revert. Select an edited row (Space) first');
},
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
// Take the current state as the new baseline (done after saving to the server). All marks and the change record are cleared.
commit: (api: GridApi<Row>) => api.commitChanges(),
};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.add(api)">Add employee</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSelected(api)"
>Delete selected</button>
<button
type="button"
:disabled="!api"
@click="api && actions.revertSelected(api)"
>Revert selected</button>
<button
type="button"
:disabled="!api"
@click="api && actions.rollback(api)"
>Revert all</button>
<button type="button" :disabled="!api" @click="api && actions.commit(api)">Use current values as baseline</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const names = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Reed', 'Ava Brooks'];
const departments = ['Dev', 'Design', 'Planning', 'Sales', 'Dev'];
const rows: Row[] = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i] as string,
salary: 38000 + i * 3000,
}));
let nextId = 100;
// With saveMode: 'batch' (the default), edited values are not saved at once but pile up as "changes".
// An edited cell gets a mark (it disappears if you restore the original value); added and deleted rows are marked too.
// getChanges() tells, per row, what changed and how, and rollbackChanges() restores everything.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 130, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const STATE_NAMES: Record<string, string> = {
added: 'added',
modified: 'modified',
removed: 'deleted',
};
// Show the changes like a code diff: "-" is the original value, "+" is the current one.
function diff(api: GridApi<Row>): string {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [];
for (const change of api.getChanges()) {
lines.push(`Row ${change.key} (${STATE_NAMES[change.state] ?? change.state})`);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
} else {
lines.push(
`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`,
);
}
}
return lines.length ? lines.join('\n') : 'Nothing changed';
}
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Edit a cell. The edited cell gets a mark and the changes appear below.');
return api.on('changesCountChanged', ({ count, added, modified, removed }) =>
log(
`${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api)}`,
),
);
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// Restore only the selected rows: bring back oldValue for each changed cell and put it in again.
revertSelected: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length) api.updateRows(back);
else say('No selected edited row to revert. Select an edited row (Space) first');
},
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
// Take the current state as the new baseline (done after saving to the server). All marks and the change record are cleared.
commit: (api: GridApi<Row>) => api.commitChanges(),
};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.add(api)"
>Add employee</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSelected(api)"
>Delete selected</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.revertSelected(api)"
>Revert selected</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.rollback(api)"
>Revert all</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.commit(api)"
>Use current values as baseline</button>
</div>
<mx-grid style="height: 330px" [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 } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
department: string;
salary: number;
}
const names = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Reed', 'Ava Brooks'];
const departments = ['Dev', 'Design', 'Planning', 'Sales', 'Dev'];
const rows: Row[] = names.map((name, i) => ({
id: i + 1,
name,
department: departments[i] as string,
salary: 38000 + i * 3000,
}));
let nextId = 100;
// With saveMode: 'batch' (the default), edited values are not saved at once but pile up as "changes".
// An edited cell gets a mark (it disappears if you restore the original value); added and deleted rows are marked too.
// getChanges() tells, per row, what changed and how, and rollbackChanges() restores everything.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 110, editable: true },
{ id: 'department', title: 'Department', width: 130, editable: true },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
const STATE_NAMES: Record<string, string> = {
added: 'added',
modified: 'modified',
removed: 'deleted',
};
// Show the changes like a code diff: "-" is the original value, "+" is the current one.
function diff(api: GridApi<Row>): string {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const lines: string[] = [];
for (const change of api.getChanges()) {
lines.push(`Row ${change.key} (${STATE_NAMES[change.state] ?? change.state})`);
if (change.state === 'modified') {
for (const cell of change.cells ?? []) {
lines.push(`- ${title(cell.columnId)}: ${String(cell.oldValue)}`);
lines.push(`+ ${title(cell.columnId)}: ${String(cell.newValue)}`);
}
} else {
lines.push(
`${change.state === 'added' ? '+' : '-'} ${change.row.name} / ${change.row.department} / ${change.row.salary}`,
);
}
}
return lines.length ? lines.join('\n') : 'Nothing changed';
}
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Edit a cell. The edited cell gets a mark and the changes appear below.');
return api.on('changesCountChanged', ({ count, added, modified, removed }) =>
log(
`${count} changed ${count === 1 ? 'row' : 'rows'} — ${added} added, ${modified} modified, ${removed} deleted\n${diff(api)}`,
),
);
}
export const actions = {
add: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: 'New hire', department: 'Dev', salary: 35000 }], 0);
},
removeSelected: (api: GridApi<Row>) => api.removeRows(api.getSelectedKeys()),
// Restore only the selected rows: bring back oldValue for each changed cell and put it in again.
revertSelected: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys().map(String));
const back = api
.getChanges()
.filter((c) => keys.has(String(c.key)) && c.state === 'modified' && c.cells)
.map((c) => {
const original = { ...c.row };
for (const cell of c.cells ?? [])
Object.assign(original, { [cell.columnId]: cell.oldValue });
return original;
});
if (back.length) api.updateRows(back);
else say('No selected edited row to revert. Select an edited row (Space) first');
},
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
// Take the current state as the new baseline (done after saving to the server). All marks and the change record are cleared.
commit: (api: GridApi<Row>) => api.commitChanges(),
};