줄 추가·복제·삭제와 새 줄 기본값Add, duplicate and delete rows with defaults
새 줄은 기본값 틀(오늘 날짜 등)로 맨 위에 넣고 바로 입력할 수 있어요. 선택한 줄을 복제하거나 삭제하고, 줄 안의 버튼으로 수정·삭제도 해요. 저장하기 전에는 모두 "변경"으로 쌓여서 한 번에 되돌릴 수 있어요.New rows start from a template (today's date, defaults) on top, ready for typing. Duplicate or delete selected rows, or use the buttons inside a row. Until saved, everything piles up as changes you can discard at once.
코드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="duplicate">선택 복제</button>
<button type="button" id="removeSelected">선택 삭제</button>
<button type="button" id="save">저장</button>
<button type="button" id="discard">변경 버리기</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('duplicate').addEventListener('click', () => actions.duplicate(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));// 저장 결과를 사람이 읽는 말로 바꿔요(status는 영어 코드라서 그대로 보여 주지 않아요).
const saveText = (r, en = false) => {
const words = {
saved: ['모두 저장했어요', 'All saved'],
partial: ['일부만 저장했어요', 'Partly saved'],
failed: ['저장하지 못했어요', 'Could not save'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
invalid: ['값이 맞지 않아 저장하지 않았어요', 'Not saved because a value is not valid'],
stale: [
'서버에 더 새로운 값이 있어서 저장하지 못했어요',
'Could not save because the server has a newer value',
],
};
const word = words[r.status] ?? ['저장을 마쳤어요', 'Save finished'];
const counts = r.committed || r.failed
? en
? ` (${r.committed} succeeded, ${r.failed} failed)`
: ` (성공 ${r.committed}줄, 실패 ${r.failed}줄)`
: '';
return `${word[en ? 1 : 0]}${counts}`;
};
const today = () => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows = [
{
id: 1,
title: '로그인 이동 오류 수정',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: '푸터 링크 정리',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: '검색 속도 개선',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel = { open: '진행 중', blocked: '막힘', done: '완료' };
const priorityLabel = {
1: '매우 낮음',
2: '낮음',
3: '보통',
4: '높음',
5: '매우 높음',
};
let nextId = 100;
// 저장한 상태의 줄 순서(줄 번호)예요. 저장하면 지금 순서로 새로 정해요.
let baseline = rows.map((row) => row.id);
let grid = null;
let say = () => { };
// 새 줄의 "기본값 틀"이에요. 제목은 비워 두고(필수), 상태·우선순위는 기본값, 등록일은 오늘이에요.
const blank = () => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// 줄 안의 버튼. 셀 렌더러는 칸만 받으니 setup에서 받은 api를 보관해 두고 버튼에서 써요.
const rowButtons = () => {
let key;
let badge;
// 저장하기 전에 새로 넣은 줄이면 "새 줄" 표시를 보여요.
const showBadge = () => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// 다른 예제의 줄 안 버튼(renderer-action-buttons)과 같은 모양이에요: 줄 높이 안에 들어가는 작은 버튼.
const style = 'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = '수정';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = '삭제';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// .mxg-cell-center 상자에 넣으면 버튼이 세로 가운데에 와요(칸 안의 내용은 기본으로 가운데가 아니에요).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = '새 줄';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey; // 스크롤하면 같은 칸이 다른 줄에 재사용돼요.
showBadge();
},
destroy() { },
};
};
export const options = {
columns: [
{ id: 'title', title: '제목', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: '작업', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: '상태',
kind: 'select',
width: 90,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: '우선순위',
kind: 'select',
width: 100,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: '등록일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// 지운 줄은 표에서 바로 사라져서, 저장하기 전까지는 어떤 줄이 지워진 상태인지 알 수 없어요.
// 그래서 표 아래에 "삭제됨" 안내를 두고, 지운 줄의 제목에 줄을 그어서 보여 줘요.
let ghosts = null;
function paintGhosts(api) {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // 두 줄 자리를 미리 잡아 두어요
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length)
return;
ghosts.append('삭제됨(저장 전): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(제목 없음)';
if (i)
ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "변경 버리기"로 원래 자리에 되돌려요.');
}
export function setup(api, log) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // 안내 자리를 미리 만들어 둬요(지울 때 화면이 밀리지 않게)
say = log;
log({
ko: '새로 넣은 줄에는 "새 줄" 표시가 붙고, 저장하기 전에는 삭제도 되돌릴 수 있어요.',
en: 'A new row gets a "새 줄" (new row) mark, and a deletion can be undone until you save.',
});
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// 변경 건수는 기록에 적지 않아요: 새 줄 표시와 "삭제됨" 안내가 이미 보여 주고, 기록이 길어지면 틀 높이를 넘어요.
void [count, added, modified, removed];
api.refresh(); // "새 줄" 표시를 다시 그려요
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
export const actions = {
add: (api) => {
// 앞 새 줄을 아직 입력 중이면(제목이 비어 검증에 실패) 그 입력을 접고 새 줄을 더해요.
if (api.isEditing())
api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // 첫 칸을 바로 입력할 수 있게 열어요.
},
// 복제: 선택한 줄을 새 줄로 만들어 원본 바로 아래에 넣어요. 새 줄은 새 키가 필요해요.
duplicate: (api) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id))
continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (복사)` }], i + 1);
}
},
removeSelected: (api) => {
const keys = api.getSelectedKeys();
if (!keys.length)
return say({ ko: '먼저 지울 줄을 골라 주세요.', en: 'Select the rows to delete first.' });
api.removeRows(keys);
},
// 제목이 빈 새 줄은 save()가 거부해서 그대로 새어 나가지 못해요.
save: async (api) => {
const report = await api.save();
say({
ko: report.status === 'invalid'
? `저장하지 않았어요: ${(report.errors ?? []).map((e) => `${e.rowKey}번 줄(${e.message})`).join(', ')}`
: `저장 결과: ${saveText(report)}`,
en: report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report, true)}`,
});
},
// 지운 줄은 변경 버리기로 되돌아오는데, 기본으로는 맨 끝에 붙어요. 저장해 둔 순서대로 다시 세워서 원래 자리에 돌려놓아요.
discard: (api) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id)] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `${baseline.indexOf(id) + 1}번째`).join(', ');
// 기록이 길어지면 틀 높이를 넘으니, 같은 말을 미리 잡아 둔 안내 자리에 보여 줘요.
paintGhosts(api);
if (ghosts)
ghosts.textContent = `지웠던 줄이 원래 자리(${where})로 돌아왔어요.`;
}
},
};<!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="duplicate">선택 복제</button>
<button type="button" id="removeSelected">선택 삭제</button>
<button type="button" id="save">저장</button>
<button type="button" id="discard">변경 버리기</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>
// 저장 결과를 사람이 읽는 말로 바꿔요(status는 영어 코드라서 그대로 보여 주지 않아요).
const saveText = (r, en = false) => {
const words = {
saved: ['모두 저장했어요', 'All saved'],
partial: ['일부만 저장했어요', 'Partly saved'],
failed: ['저장하지 못했어요', 'Could not save'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
invalid: ['값이 맞지 않아 저장하지 않았어요', 'Not saved because a value is not valid'],
stale: [
'서버에 더 새로운 값이 있어서 저장하지 못했어요',
'Could not save because the server has a newer value',
],
};
const word = words[r.status] ?? ['저장을 마쳤어요', 'Save finished'];
const counts = r.committed || r.failed
? en
? ` (${r.committed} succeeded, ${r.failed} failed)`
: ` (성공 ${r.committed}줄, 실패 ${r.failed}줄)`
: '';
return `${word[en ? 1 : 0]}${counts}`;
};
const today = () => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows = [
{
id: 1,
title: '로그인 이동 오류 수정',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: '푸터 링크 정리',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: '검색 속도 개선',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel = { open: '진행 중', blocked: '막힘', done: '완료' };
const priorityLabel = {
1: '매우 낮음',
2: '낮음',
3: '보통',
4: '높음',
5: '매우 높음',
};
let nextId = 100;
// 저장한 상태의 줄 순서(줄 번호)예요. 저장하면 지금 순서로 새로 정해요.
let baseline = rows.map((row) => row.id);
let grid = null;
let say = () => { };
// 새 줄의 "기본값 틀"이에요. 제목은 비워 두고(필수), 상태·우선순위는 기본값, 등록일은 오늘이에요.
const blank = () => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// 줄 안의 버튼. 셀 렌더러는 칸만 받으니 setup에서 받은 api를 보관해 두고 버튼에서 써요.
const rowButtons = () => {
let key;
let badge;
// 저장하기 전에 새로 넣은 줄이면 "새 줄" 표시를 보여요.
const showBadge = () => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// 다른 예제의 줄 안 버튼(renderer-action-buttons)과 같은 모양이에요: 줄 높이 안에 들어가는 작은 버튼.
const style = 'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = '수정';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = '삭제';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// .mxg-cell-center 상자에 넣으면 버튼이 세로 가운데에 와요(칸 안의 내용은 기본으로 가운데가 아니에요).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = '새 줄';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey; // 스크롤하면 같은 칸이 다른 줄에 재사용돼요.
showBadge();
},
destroy() { },
};
};
const options = {
columns: [
{ id: 'title', title: '제목', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: '작업', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: '상태',
kind: 'select',
width: 90,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: '우선순위',
kind: 'select',
width: 100,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: '등록일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// 지운 줄은 표에서 바로 사라져서, 저장하기 전까지는 어떤 줄이 지워진 상태인지 알 수 없어요.
// 그래서 표 아래에 "삭제됨" 안내를 두고, 지운 줄의 제목에 줄을 그어서 보여 줘요.
let ghosts = null;
function paintGhosts(api) {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // 두 줄 자리를 미리 잡아 두어요
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length)
return;
ghosts.append('삭제됨(저장 전): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(제목 없음)';
if (i)
ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "변경 버리기"로 원래 자리에 되돌려요.');
}
function setup(api, log) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // 안내 자리를 미리 만들어 둬요(지울 때 화면이 밀리지 않게)
say = log;
log({
ko: '새로 넣은 줄에는 "새 줄" 표시가 붙고, 저장하기 전에는 삭제도 되돌릴 수 있어요.',
en: 'A new row gets a "새 줄" (new row) mark, and a deletion can be undone until you save.',
});
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// 변경 건수는 기록에 적지 않아요: 새 줄 표시와 "삭제됨" 안내가 이미 보여 주고, 기록이 길어지면 틀 높이를 넘어요.
void [count, added, modified, removed];
api.refresh(); // "새 줄" 표시를 다시 그려요
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
const actions = {
add: (api) => {
// 앞 새 줄을 아직 입력 중이면(제목이 비어 검증에 실패) 그 입력을 접고 새 줄을 더해요.
if (api.isEditing())
api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // 첫 칸을 바로 입력할 수 있게 열어요.
},
// 복제: 선택한 줄을 새 줄로 만들어 원본 바로 아래에 넣어요. 새 줄은 새 키가 필요해요.
duplicate: (api) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id))
continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (복사)` }], i + 1);
}
},
removeSelected: (api) => {
const keys = api.getSelectedKeys();
if (!keys.length)
return say({ ko: '먼저 지울 줄을 골라 주세요.', en: 'Select the rows to delete first.' });
api.removeRows(keys);
},
// 제목이 빈 새 줄은 save()가 거부해서 그대로 새어 나가지 못해요.
save: async (api) => {
const report = await api.save();
say({
ko: report.status === 'invalid'
? `저장하지 않았어요: ${(report.errors ?? []).map((e) => `${e.rowKey}번 줄(${e.message})`).join(', ')}`
: `저장 결과: ${saveText(report)}`,
en: report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report, true)}`,
});
},
// 지운 줄은 변경 버리기로 되돌아오는데, 기본으로는 맨 끝에 붙어요. 저장해 둔 순서대로 다시 세워서 원래 자리에 돌려놓아요.
discard: (api) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id)] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `${baseline.indexOf(id) + 1}번째`).join(', ');
// 기록이 길어지면 틀 높이를 넘으니, 같은 말을 미리 잡아 둔 안내 자리에 보여 줘요.
paintGhosts(api);
if (ghosts)
ghosts.textContent = `지웠던 줄이 원래 자리(${where})로 돌아왔어요.`;
}
},
};
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('duplicate').addEventListener('click', () => actions.duplicate(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(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.duplicate(api)}
>선택 복제</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSelected(api)}
>선택 삭제</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>저장</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>변경 버리기</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
// 저장 결과를 사람이 읽는 말로 바꿔요(status는 영어 코드라서 그대로 보여 주지 않아요).
const saveText = (r: { status: string; committed: number; failed: number }, en = false): string => {
const words: Record<string, [string, string]> = {
saved: ['모두 저장했어요', 'All saved'],
partial: ['일부만 저장했어요', 'Partly saved'],
failed: ['저장하지 못했어요', 'Could not save'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
invalid: ['값이 맞지 않아 저장하지 않았어요', 'Not saved because a value is not valid'],
stale: [
'서버에 더 새로운 값이 있어서 저장하지 못했어요',
'Could not save because the server has a newer value',
],
};
const word = words[r.status] ?? ['저장을 마쳤어요', 'Save finished'];
const counts =
r.committed || r.failed
? en
? ` (${r.committed} succeeded, ${r.failed} failed)`
: ` (성공 ${r.committed}줄, 실패 ${r.failed}줄)`
: '';
return `${word[en ? 1 : 0]}${counts}`;
};
export interface Row {
id: number;
title: string;
status: string;
priority: number;
created: Date;
actions: string;
}
const today = (): Date => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows: Row[] = [
{
id: 1,
title: '로그인 이동 오류 수정',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: '푸터 링크 정리',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: '검색 속도 개선',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel: Record<string, string> = { open: '진행 중', blocked: '막힘', done: '완료' };
const priorityLabel: Record<string, string> = {
1: '매우 낮음',
2: '낮음',
3: '보통',
4: '높음',
5: '매우 높음',
};
let nextId = 100;
// 저장한 상태의 줄 순서(줄 번호)예요. 저장하면 지금 순서로 새로 정해요.
let baseline: number[] = rows.map((row) => row.id);
let grid: GridApi<Row> | null = null;
let say: (message: LogText) => void = () => {};
// 새 줄의 "기본값 틀"이에요. 제목은 비워 두고(필수), 상태·우선순위는 기본값, 등록일은 오늘이에요.
const blank = (): Row => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// 줄 안의 버튼. 셀 렌더러는 칸만 받으니 setup에서 받은 api를 보관해 두고 버튼에서 써요.
const rowButtons = (): CellRendererAdapter<Row> => {
let key: number;
let badge: HTMLSpanElement;
// 저장하기 전에 새로 넣은 줄이면 "새 줄" 표시를 보여요.
const showBadge = (): void => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// 다른 예제의 줄 안 버튼(renderer-action-buttons)과 같은 모양이에요: 줄 높이 안에 들어가는 작은 버튼.
const style =
'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey as number;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = '수정';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = '삭제';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// .mxg-cell-center 상자에 넣으면 버튼이 세로 가운데에 와요(칸 안의 내용은 기본으로 가운데가 아니에요).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = '새 줄';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey as number; // 스크롤하면 같은 칸이 다른 줄에 재사용돼요.
showBadge();
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: '제목', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: '작업', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: '상태',
kind: 'select',
width: 90,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: '우선순위',
kind: 'select',
width: 100,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: '등록일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// 지운 줄은 표에서 바로 사라져서, 저장하기 전까지는 어떤 줄이 지워진 상태인지 알 수 없어요.
// 그래서 표 아래에 "삭제됨" 안내를 두고, 지운 줄의 제목에 줄을 그어서 보여 줘요.
let ghosts: HTMLElement | null = null;
function paintGhosts(api: GridApi<Row>): void {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // 두 줄 자리를 미리 잡아 두어요
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length) return;
ghosts.append('삭제됨(저장 전): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(제목 없음)';
if (i) ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "변경 버리기"로 원래 자리에 되돌려요.');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // 안내 자리를 미리 만들어 둬요(지울 때 화면이 밀리지 않게)
say = log;
log({
ko: '새로 넣은 줄에는 "새 줄" 표시가 붙고, 저장하기 전에는 삭제도 되돌릴 수 있어요.',
en: 'A new row gets a "새 줄" (new row) mark, and a deletion can be undone until you save.',
});
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// 변경 건수는 기록에 적지 않아요: 새 줄 표시와 "삭제됨" 안내가 이미 보여 주고, 기록이 길어지면 틀 높이를 넘어요.
void [count, added, modified, removed];
api.refresh(); // "새 줄" 표시를 다시 그려요
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
export const actions = {
add: (api: GridApi<Row>) => {
// 앞 새 줄을 아직 입력 중이면(제목이 비어 검증에 실패) 그 입력을 접고 새 줄을 더해요.
if (api.isEditing()) api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // 첫 칸을 바로 입력할 수 있게 열어요.
},
// 복제: 선택한 줄을 새 줄로 만들어 원본 바로 아래에 넣어요. 새 줄은 새 키가 필요해요.
duplicate: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id)) continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (복사)` }], i + 1);
}
},
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (!keys.length)
return say({ ko: '먼저 지울 줄을 골라 주세요.', en: 'Select the rows to delete first.' });
api.removeRows(keys);
},
// 제목이 빈 새 줄은 save()가 거부해서 그대로 새어 나가지 못해요.
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({
ko:
report.status === 'invalid'
? `저장하지 않았어요: ${(report.errors ?? []).map((e) => `${e.rowKey}번 줄(${e.message})`).join(', ')}`
: `저장 결과: ${saveText(report)}`,
en:
report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report, true)}`,
});
},
// 지운 줄은 변경 버리기로 되돌아오는데, 기본으로는 맨 끝에 붙어요. 저장해 둔 순서대로 다시 세워서 원래 자리에 돌려놓아요.
discard: (api: GridApi<Row>) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id) as Row] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `${baseline.indexOf(id) + 1}번째`).join(', ');
// 기록이 길어지면 틀 높이를 넘으니, 같은 말을 미리 잡아 둔 안내 자리에 보여 줘요.
paintGhosts(api);
if (ghosts) ghosts.textContent = `지웠던 줄이 원래 자리(${where})로 돌아왔어요.`;
}
},
};버튼을 누르면 이 예제의 코드가 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.duplicate(api)"
>선택 복제</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSelected(api)"
>선택 삭제</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">저장</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">변경 버리기</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
// 저장 결과를 사람이 읽는 말로 바꿔요(status는 영어 코드라서 그대로 보여 주지 않아요).
const saveText = (r: { status: string; committed: number; failed: number }, en = false): string => {
const words: Record<string, [string, string]> = {
saved: ['모두 저장했어요', 'All saved'],
partial: ['일부만 저장했어요', 'Partly saved'],
failed: ['저장하지 못했어요', 'Could not save'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
invalid: ['값이 맞지 않아 저장하지 않았어요', 'Not saved because a value is not valid'],
stale: [
'서버에 더 새로운 값이 있어서 저장하지 못했어요',
'Could not save because the server has a newer value',
],
};
const word = words[r.status] ?? ['저장을 마쳤어요', 'Save finished'];
const counts =
r.committed || r.failed
? en
? ` (${r.committed} succeeded, ${r.failed} failed)`
: ` (성공 ${r.committed}줄, 실패 ${r.failed}줄)`
: '';
return `${word[en ? 1 : 0]}${counts}`;
};
export interface Row {
id: number;
title: string;
status: string;
priority: number;
created: Date;
actions: string;
}
const today = (): Date => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows: Row[] = [
{
id: 1,
title: '로그인 이동 오류 수정',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: '푸터 링크 정리',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: '검색 속도 개선',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel: Record<string, string> = { open: '진행 중', blocked: '막힘', done: '완료' };
const priorityLabel: Record<string, string> = {
1: '매우 낮음',
2: '낮음',
3: '보통',
4: '높음',
5: '매우 높음',
};
let nextId = 100;
// 저장한 상태의 줄 순서(줄 번호)예요. 저장하면 지금 순서로 새로 정해요.
let baseline: number[] = rows.map((row) => row.id);
let grid: GridApi<Row> | null = null;
let say: (message: LogText) => void = () => {};
// 새 줄의 "기본값 틀"이에요. 제목은 비워 두고(필수), 상태·우선순위는 기본값, 등록일은 오늘이에요.
const blank = (): Row => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// 줄 안의 버튼. 셀 렌더러는 칸만 받으니 setup에서 받은 api를 보관해 두고 버튼에서 써요.
const rowButtons = (): CellRendererAdapter<Row> => {
let key: number;
let badge: HTMLSpanElement;
// 저장하기 전에 새로 넣은 줄이면 "새 줄" 표시를 보여요.
const showBadge = (): void => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// 다른 예제의 줄 안 버튼(renderer-action-buttons)과 같은 모양이에요: 줄 높이 안에 들어가는 작은 버튼.
const style =
'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey as number;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = '수정';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = '삭제';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// .mxg-cell-center 상자에 넣으면 버튼이 세로 가운데에 와요(칸 안의 내용은 기본으로 가운데가 아니에요).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = '새 줄';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey as number; // 스크롤하면 같은 칸이 다른 줄에 재사용돼요.
showBadge();
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: '제목', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: '작업', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: '상태',
kind: 'select',
width: 90,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: '우선순위',
kind: 'select',
width: 100,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: '등록일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// 지운 줄은 표에서 바로 사라져서, 저장하기 전까지는 어떤 줄이 지워진 상태인지 알 수 없어요.
// 그래서 표 아래에 "삭제됨" 안내를 두고, 지운 줄의 제목에 줄을 그어서 보여 줘요.
let ghosts: HTMLElement | null = null;
function paintGhosts(api: GridApi<Row>): void {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // 두 줄 자리를 미리 잡아 두어요
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length) return;
ghosts.append('삭제됨(저장 전): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(제목 없음)';
if (i) ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "변경 버리기"로 원래 자리에 되돌려요.');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // 안내 자리를 미리 만들어 둬요(지울 때 화면이 밀리지 않게)
say = log;
log({
ko: '새로 넣은 줄에는 "새 줄" 표시가 붙고, 저장하기 전에는 삭제도 되돌릴 수 있어요.',
en: 'A new row gets a "새 줄" (new row) mark, and a deletion can be undone until you save.',
});
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// 변경 건수는 기록에 적지 않아요: 새 줄 표시와 "삭제됨" 안내가 이미 보여 주고, 기록이 길어지면 틀 높이를 넘어요.
void [count, added, modified, removed];
api.refresh(); // "새 줄" 표시를 다시 그려요
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
export const actions = {
add: (api: GridApi<Row>) => {
// 앞 새 줄을 아직 입력 중이면(제목이 비어 검증에 실패) 그 입력을 접고 새 줄을 더해요.
if (api.isEditing()) api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // 첫 칸을 바로 입력할 수 있게 열어요.
},
// 복제: 선택한 줄을 새 줄로 만들어 원본 바로 아래에 넣어요. 새 줄은 새 키가 필요해요.
duplicate: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id)) continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (복사)` }], i + 1);
}
},
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (!keys.length)
return say({ ko: '먼저 지울 줄을 골라 주세요.', en: 'Select the rows to delete first.' });
api.removeRows(keys);
},
// 제목이 빈 새 줄은 save()가 거부해서 그대로 새어 나가지 못해요.
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({
ko:
report.status === 'invalid'
? `저장하지 않았어요: ${(report.errors ?? []).map((e) => `${e.rowKey}번 줄(${e.message})`).join(', ')}`
: `저장 결과: ${saveText(report)}`,
en:
report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report, true)}`,
});
},
// 지운 줄은 변경 버리기로 되돌아오는데, 기본으로는 맨 끝에 붙어요. 저장해 둔 순서대로 다시 세워서 원래 자리에 돌려놓아요.
discard: (api: GridApi<Row>) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id) as Row] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `${baseline.indexOf(id) + 1}번째`).join(', ');
// 기록이 길어지면 틀 높이를 넘으니, 같은 말을 미리 잡아 둔 안내 자리에 보여 줘요.
paintGhosts(api);
if (ghosts) ghosts.textContent = `지웠던 줄이 원래 자리(${where})로 돌아왔어요.`;
}
},
};버튼을 누르면 이 예제의 코드가 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.duplicate(api)"
>선택 복제</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSelected(api)"
>선택 삭제</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>저장</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(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 { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
// 저장 결과를 사람이 읽는 말로 바꿔요(status는 영어 코드라서 그대로 보여 주지 않아요).
const saveText = (r: { status: string; committed: number; failed: number }, en = false): string => {
const words: Record<string, [string, string]> = {
saved: ['모두 저장했어요', 'All saved'],
partial: ['일부만 저장했어요', 'Partly saved'],
failed: ['저장하지 못했어요', 'Could not save'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
invalid: ['값이 맞지 않아 저장하지 않았어요', 'Not saved because a value is not valid'],
stale: [
'서버에 더 새로운 값이 있어서 저장하지 못했어요',
'Could not save because the server has a newer value',
],
};
const word = words[r.status] ?? ['저장을 마쳤어요', 'Save finished'];
const counts =
r.committed || r.failed
? en
? ` (${r.committed} succeeded, ${r.failed} failed)`
: ` (성공 ${r.committed}줄, 실패 ${r.failed}줄)`
: '';
return `${word[en ? 1 : 0]}${counts}`;
};
export interface Row {
id: number;
title: string;
status: string;
priority: number;
created: Date;
actions: string;
}
const today = (): Date => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows: Row[] = [
{
id: 1,
title: '로그인 이동 오류 수정',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: '푸터 링크 정리',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: '검색 속도 개선',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel: Record<string, string> = { open: '진행 중', blocked: '막힘', done: '완료' };
const priorityLabel: Record<string, string> = {
1: '매우 낮음',
2: '낮음',
3: '보통',
4: '높음',
5: '매우 높음',
};
let nextId = 100;
// 저장한 상태의 줄 순서(줄 번호)예요. 저장하면 지금 순서로 새로 정해요.
let baseline: number[] = rows.map((row) => row.id);
let grid: GridApi<Row> | null = null;
let say: (message: LogText) => void = () => {};
// 새 줄의 "기본값 틀"이에요. 제목은 비워 두고(필수), 상태·우선순위는 기본값, 등록일은 오늘이에요.
const blank = (): Row => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// 줄 안의 버튼. 셀 렌더러는 칸만 받으니 setup에서 받은 api를 보관해 두고 버튼에서 써요.
const rowButtons = (): CellRendererAdapter<Row> => {
let key: number;
let badge: HTMLSpanElement;
// 저장하기 전에 새로 넣은 줄이면 "새 줄" 표시를 보여요.
const showBadge = (): void => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// 다른 예제의 줄 안 버튼(renderer-action-buttons)과 같은 모양이에요: 줄 높이 안에 들어가는 작은 버튼.
const style =
'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey as number;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = '수정';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = '삭제';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// .mxg-cell-center 상자에 넣으면 버튼이 세로 가운데에 와요(칸 안의 내용은 기본으로 가운데가 아니에요).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = '새 줄';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey as number; // 스크롤하면 같은 칸이 다른 줄에 재사용돼요.
showBadge();
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: '제목', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: '작업', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: '상태',
kind: 'select',
width: 90,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: '우선순위',
kind: 'select',
width: 100,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: '등록일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// 지운 줄은 표에서 바로 사라져서, 저장하기 전까지는 어떤 줄이 지워진 상태인지 알 수 없어요.
// 그래서 표 아래에 "삭제됨" 안내를 두고, 지운 줄의 제목에 줄을 그어서 보여 줘요.
let ghosts: HTMLElement | null = null;
function paintGhosts(api: GridApi<Row>): void {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // 두 줄 자리를 미리 잡아 두어요
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length) return;
ghosts.append('삭제됨(저장 전): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(제목 없음)';
if (i) ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "변경 버리기"로 원래 자리에 되돌려요.');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // 안내 자리를 미리 만들어 둬요(지울 때 화면이 밀리지 않게)
say = log;
log({
ko: '새로 넣은 줄에는 "새 줄" 표시가 붙고, 저장하기 전에는 삭제도 되돌릴 수 있어요.',
en: 'A new row gets a "새 줄" (new row) mark, and a deletion can be undone until you save.',
});
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// 변경 건수는 기록에 적지 않아요: 새 줄 표시와 "삭제됨" 안내가 이미 보여 주고, 기록이 길어지면 틀 높이를 넘어요.
void [count, added, modified, removed];
api.refresh(); // "새 줄" 표시를 다시 그려요
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
export const actions = {
add: (api: GridApi<Row>) => {
// 앞 새 줄을 아직 입력 중이면(제목이 비어 검증에 실패) 그 입력을 접고 새 줄을 더해요.
if (api.isEditing()) api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // 첫 칸을 바로 입력할 수 있게 열어요.
},
// 복제: 선택한 줄을 새 줄로 만들어 원본 바로 아래에 넣어요. 새 줄은 새 키가 필요해요.
duplicate: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id)) continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (복사)` }], i + 1);
}
},
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (!keys.length)
return say({ ko: '먼저 지울 줄을 골라 주세요.', en: 'Select the rows to delete first.' });
api.removeRows(keys);
},
// 제목이 빈 새 줄은 save()가 거부해서 그대로 새어 나가지 못해요.
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({
ko:
report.status === 'invalid'
? `저장하지 않았어요: ${(report.errors ?? []).map((e) => `${e.rowKey}번 줄(${e.message})`).join(', ')}`
: `저장 결과: ${saveText(report)}`,
en:
report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report, true)}`,
});
},
// 지운 줄은 변경 버리기로 되돌아오는데, 기본으로는 맨 끝에 붙어요. 저장해 둔 순서대로 다시 세워서 원래 자리에 돌려놓아요.
discard: (api: GridApi<Row>) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id) as Row] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `${baseline.indexOf(id) + 1}번째`).join(', ');
// 기록이 길어지면 틀 높이를 넘으니, 같은 말을 미리 잡아 둔 안내 자리에 보여 줘요.
paintGhosts(api);
if (ghosts) ghosts.textContent = `지웠던 줄이 원래 자리(${where})로 돌아왔어요.`;
}
},
};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">New task</button>
<button type="button" id="duplicate">Duplicate selected</button>
<button type="button" id="removeSelected">Delete selected</button>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard changes</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('duplicate').addEventListener('click', () => actions.duplicate(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));// Turns the save result into human-readable text (status is an English code, so it is not shown as is).
const saveText = (r) => {
const words = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
empty: 'No changes to save',
invalid: 'Not saved because a value is not valid',
stale: 'Could not save because the server has a newer value',
};
const word = words[r.status] ?? 'Save finished';
const counts = r.committed || r.failed ? ` (${r.committed} succeeded, ${r.failed} failed)` : '';
return `${word}${counts}`;
};
const today = () => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows = [
{
id: 1,
title: 'Fix login redirect bug',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: 'Clean up footer links',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: 'Speed up search',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel = {
open: 'In progress',
blocked: 'Blocked',
done: 'Done',
};
const priorityLabel = {
1: 'Very low',
2: 'Low',
3: 'Medium',
4: 'High',
5: 'Very high',
};
let nextId = 100;
// Row order (row keys) as last saved. Saving resets it to the current order.
let baseline = rows.map((row) => row.id);
let grid = null;
let say = () => { };
// The "defaults template" for a new row. The title is left empty (required), status and priority use defaults, and the created date is today.
const blank = () => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// Buttons inside a row. A cell renderer only receives the cell, so keep the api received in setup and use it from the buttons.
const rowButtons = () => {
let key;
let badge;
// Show the "New" badge if the row was added before saving.
const showBadge = () => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// Same look as the in-row buttons of another example (renderer-action-buttons): small buttons that fit the row height.
const style = 'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = 'Edit';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = 'Delete';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// Putting the buttons in a .mxg-cell-center box centers them vertically (cell content is not centered by default).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = 'New';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey; // When scrolling, the same cell is reused for another row.
showBadge();
},
destroy() { },
};
};
export const options = {
columns: [
{ id: 'title', title: 'Title', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: 'Actions', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: 'Priority',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: 'Created', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// A deleted row vanishes from the grid at once, so until saving you could not tell which rows are deleted.
// So a "Deleted" note under the grid shows the deleted rows' titles with a strike-through.
let ghosts = null;
function paintGhosts(api) {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // reserve room for two lines in advance
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length)
return;
ghosts.append('Deleted (not saved yet): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(no title)';
if (i)
ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "Discard changes" puts them back in their place.');
}
export function setup(api, log) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // create the note area in advance (so the layout does not shift on delete)
say = log;
log('A new row gets a "New" mark, and a deletion can be undone until you save.');
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// The change count is not logged: the New badge and the "Deleted" note already show it, and a long log would overflow the frame height.
void [count, added, modified, removed];
api.refresh(); // redraw the "New" badge
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
export const actions = {
add: (api) => {
// If the previous new row is still being edited (empty title fails validation), cancel that edit and add a new row.
if (api.isEditing())
api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // open the first cell so you can type right away.
},
// Duplicate: make the selected rows into new rows right below the originals. A new row needs a new key.
duplicate: (api) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id))
continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (copy)` }], i + 1);
}
},
removeSelected: (api) => {
const keys = api.getSelectedKeys();
if (!keys.length)
return say('Select the rows to delete first.');
api.removeRows(keys);
},
// A new row with an empty title is rejected by save(), so it cannot slip through.
save: async (api) => {
const report = await api.save();
say(report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report)}`);
},
// Deleted rows come back with discard, but by default they are appended at the end. Re-sort by the saved order to put them back in place.
discard: (api) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id)] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `#${baseline.indexOf(id) + 1}`).join(', ');
// A long log would overflow the frame height, so show this in the reserved note area instead.
paintGhosts(api);
if (ghosts)
ghosts.textContent = `The deleted rows are back in their original places (${where}).`;
}
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Add, duplicate and delete rows with defaults</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="add">New task</button>
<button type="button" id="duplicate">Duplicate selected</button>
<button type="button" id="removeSelected">Delete selected</button>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard changes</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>
// Turns the save result into human-readable text (status is an English code, so it is not shown as is).
const saveText = (r) => {
const words = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
empty: 'No changes to save',
invalid: 'Not saved because a value is not valid',
stale: 'Could not save because the server has a newer value',
};
const word = words[r.status] ?? 'Save finished';
const counts = r.committed || r.failed ? ` (${r.committed} succeeded, ${r.failed} failed)` : '';
return `${word}${counts}`;
};
const today = () => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows = [
{
id: 1,
title: 'Fix login redirect bug',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: 'Clean up footer links',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: 'Speed up search',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel = {
open: 'In progress',
blocked: 'Blocked',
done: 'Done',
};
const priorityLabel = {
1: 'Very low',
2: 'Low',
3: 'Medium',
4: 'High',
5: 'Very high',
};
let nextId = 100;
// Row order (row keys) as last saved. Saving resets it to the current order.
let baseline = rows.map((row) => row.id);
let grid = null;
let say = () => { };
// The "defaults template" for a new row. The title is left empty (required), status and priority use defaults, and the created date is today.
const blank = () => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// Buttons inside a row. A cell renderer only receives the cell, so keep the api received in setup and use it from the buttons.
const rowButtons = () => {
let key;
let badge;
// Show the "New" badge if the row was added before saving.
const showBadge = () => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// Same look as the in-row buttons of another example (renderer-action-buttons): small buttons that fit the row height.
const style = 'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = 'Edit';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = 'Delete';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// Putting the buttons in a .mxg-cell-center box centers them vertically (cell content is not centered by default).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = 'New';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey; // When scrolling, the same cell is reused for another row.
showBadge();
},
destroy() { },
};
};
const options = {
columns: [
{ id: 'title', title: 'Title', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: 'Actions', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: 'Priority',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: 'Created', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// A deleted row vanishes from the grid at once, so until saving you could not tell which rows are deleted.
// So a "Deleted" note under the grid shows the deleted rows' titles with a strike-through.
let ghosts = null;
function paintGhosts(api) {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // reserve room for two lines in advance
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length)
return;
ghosts.append('Deleted (not saved yet): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(no title)';
if (i)
ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "Discard changes" puts them back in their place.');
}
function setup(api, log) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // create the note area in advance (so the layout does not shift on delete)
say = log;
log('A new row gets a "New" mark, and a deletion can be undone until you save.');
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// The change count is not logged: the New badge and the "Deleted" note already show it, and a long log would overflow the frame height.
void [count, added, modified, removed];
api.refresh(); // redraw the "New" badge
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
const actions = {
add: (api) => {
// If the previous new row is still being edited (empty title fails validation), cancel that edit and add a new row.
if (api.isEditing())
api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // open the first cell so you can type right away.
},
// Duplicate: make the selected rows into new rows right below the originals. A new row needs a new key.
duplicate: (api) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id))
continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (copy)` }], i + 1);
}
},
removeSelected: (api) => {
const keys = api.getSelectedKeys();
if (!keys.length)
return say('Select the rows to delete first.');
api.removeRows(keys);
},
// A new row with an empty title is rejected by save(), so it cannot slip through.
save: async (api) => {
const report = await api.save();
say(report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report)}`);
},
// Deleted rows come back with discard, but by default they are appended at the end. Re-sort by the saved order to put them back in place.
discard: (api) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id)] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `#${baseline.indexOf(id) + 1}`).join(', ');
// A long log would overflow the frame height, so show this in the reserved note area instead.
paintGhosts(api);
if (ghosts)
ghosts.textContent = `The deleted rows are back in their original places (${where}).`;
}
},
};
options.ariaLabel = "Add, duplicate and delete rows with defaults";
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('duplicate').addEventListener('click', () => actions.duplicate(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(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)}
>New task</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.duplicate(api)}
>Duplicate selected</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSelected(api)}
>Delete selected</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>Save</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>Discard changes</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
// Turns the save result into human-readable text (status is an English code, so it is not shown as is).
const saveText = (r: { status: string; committed: number; failed: number }): string => {
const words: Record<string, string> = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
empty: 'No changes to save',
invalid: 'Not saved because a value is not valid',
stale: 'Could not save because the server has a newer value',
};
const word = words[r.status] ?? 'Save finished';
const counts = r.committed || r.failed ? ` (${r.committed} succeeded, ${r.failed} failed)` : '';
return `${word}${counts}`;
};
export interface Row {
id: number;
title: string;
status: string;
priority: number;
created: Date;
actions: string;
}
const today = (): Date => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows: Row[] = [
{
id: 1,
title: 'Fix login redirect bug',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: 'Clean up footer links',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: 'Speed up search',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel: Record<string, string> = {
open: 'In progress',
blocked: 'Blocked',
done: 'Done',
};
const priorityLabel: Record<string, string> = {
1: 'Very low',
2: 'Low',
3: 'Medium',
4: 'High',
5: 'Very high',
};
let nextId = 100;
// Row order (row keys) as last saved. Saving resets it to the current order.
let baseline: number[] = rows.map((row) => row.id);
let grid: GridApi<Row> | null = null;
let say: (message: LogText) => void = () => {};
// The "defaults template" for a new row. The title is left empty (required), status and priority use defaults, and the created date is today.
const blank = (): Row => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// Buttons inside a row. A cell renderer only receives the cell, so keep the api received in setup and use it from the buttons.
const rowButtons = (): CellRendererAdapter<Row> => {
let key: number;
let badge: HTMLSpanElement;
// Show the "New" badge if the row was added before saving.
const showBadge = (): void => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// Same look as the in-row buttons of another example (renderer-action-buttons): small buttons that fit the row height.
const style =
'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey as number;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = 'Edit';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = 'Delete';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// Putting the buttons in a .mxg-cell-center box centers them vertically (cell content is not centered by default).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = 'New';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey as number; // When scrolling, the same cell is reused for another row.
showBadge();
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: 'Title', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: 'Actions', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: 'Priority',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: 'Created', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// A deleted row vanishes from the grid at once, so until saving you could not tell which rows are deleted.
// So a "Deleted" note under the grid shows the deleted rows' titles with a strike-through.
let ghosts: HTMLElement | null = null;
function paintGhosts(api: GridApi<Row>): void {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // reserve room for two lines in advance
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length) return;
ghosts.append('Deleted (not saved yet): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(no title)';
if (i) ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "Discard changes" puts them back in their place.');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // create the note area in advance (so the layout does not shift on delete)
say = log;
log('A new row gets a "New" mark, and a deletion can be undone until you save.');
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// The change count is not logged: the New badge and the "Deleted" note already show it, and a long log would overflow the frame height.
void [count, added, modified, removed];
api.refresh(); // redraw the "New" badge
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
export const actions = {
add: (api: GridApi<Row>) => {
// If the previous new row is still being edited (empty title fails validation), cancel that edit and add a new row.
if (api.isEditing()) api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // open the first cell so you can type right away.
},
// Duplicate: make the selected rows into new rows right below the originals. A new row needs a new key.
duplicate: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id)) continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (copy)` }], i + 1);
}
},
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (!keys.length) return say('Select the rows to delete first.');
api.removeRows(keys);
},
// A new row with an empty title is rejected by save(), so it cannot slip through.
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(
report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report)}`,
);
},
// Deleted rows come back with discard, but by default they are appended at the end. Re-sort by the saved order to put them back in place.
discard: (api: GridApi<Row>) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id) as Row] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `#${baseline.indexOf(id) + 1}`).join(', ');
// A long log would overflow the frame height, so show this in the reserved note area instead.
paintGhosts(api);
if (ghosts)
ghosts.textContent = `The deleted rows are back in their original places (${where}).`;
}
},
};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)">New task</button>
<button
type="button"
:disabled="!api"
@click="api && actions.duplicate(api)"
>Duplicate selected</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSelected(api)"
>Delete selected</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">Save</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">Discard changes</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
// Turns the save result into human-readable text (status is an English code, so it is not shown as is).
const saveText = (r: { status: string; committed: number; failed: number }): string => {
const words: Record<string, string> = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
empty: 'No changes to save',
invalid: 'Not saved because a value is not valid',
stale: 'Could not save because the server has a newer value',
};
const word = words[r.status] ?? 'Save finished';
const counts = r.committed || r.failed ? ` (${r.committed} succeeded, ${r.failed} failed)` : '';
return `${word}${counts}`;
};
export interface Row {
id: number;
title: string;
status: string;
priority: number;
created: Date;
actions: string;
}
const today = (): Date => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows: Row[] = [
{
id: 1,
title: 'Fix login redirect bug',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: 'Clean up footer links',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: 'Speed up search',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel: Record<string, string> = {
open: 'In progress',
blocked: 'Blocked',
done: 'Done',
};
const priorityLabel: Record<string, string> = {
1: 'Very low',
2: 'Low',
3: 'Medium',
4: 'High',
5: 'Very high',
};
let nextId = 100;
// Row order (row keys) as last saved. Saving resets it to the current order.
let baseline: number[] = rows.map((row) => row.id);
let grid: GridApi<Row> | null = null;
let say: (message: LogText) => void = () => {};
// The "defaults template" for a new row. The title is left empty (required), status and priority use defaults, and the created date is today.
const blank = (): Row => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// Buttons inside a row. A cell renderer only receives the cell, so keep the api received in setup and use it from the buttons.
const rowButtons = (): CellRendererAdapter<Row> => {
let key: number;
let badge: HTMLSpanElement;
// Show the "New" badge if the row was added before saving.
const showBadge = (): void => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// Same look as the in-row buttons of another example (renderer-action-buttons): small buttons that fit the row height.
const style =
'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey as number;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = 'Edit';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = 'Delete';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// Putting the buttons in a .mxg-cell-center box centers them vertically (cell content is not centered by default).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = 'New';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey as number; // When scrolling, the same cell is reused for another row.
showBadge();
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: 'Title', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: 'Actions', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: 'Priority',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: 'Created', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// A deleted row vanishes from the grid at once, so until saving you could not tell which rows are deleted.
// So a "Deleted" note under the grid shows the deleted rows' titles with a strike-through.
let ghosts: HTMLElement | null = null;
function paintGhosts(api: GridApi<Row>): void {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // reserve room for two lines in advance
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length) return;
ghosts.append('Deleted (not saved yet): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(no title)';
if (i) ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "Discard changes" puts them back in their place.');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // create the note area in advance (so the layout does not shift on delete)
say = log;
log('A new row gets a "New" mark, and a deletion can be undone until you save.');
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// The change count is not logged: the New badge and the "Deleted" note already show it, and a long log would overflow the frame height.
void [count, added, modified, removed];
api.refresh(); // redraw the "New" badge
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
export const actions = {
add: (api: GridApi<Row>) => {
// If the previous new row is still being edited (empty title fails validation), cancel that edit and add a new row.
if (api.isEditing()) api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // open the first cell so you can type right away.
},
// Duplicate: make the selected rows into new rows right below the originals. A new row needs a new key.
duplicate: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id)) continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (copy)` }], i + 1);
}
},
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (!keys.length) return say('Select the rows to delete first.');
api.removeRows(keys);
},
// A new row with an empty title is rejected by save(), so it cannot slip through.
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(
report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report)}`,
);
},
// Deleted rows come back with discard, but by default they are appended at the end. Re-sort by the saved order to put them back in place.
discard: (api: GridApi<Row>) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id) as Row] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `#${baseline.indexOf(id) + 1}`).join(', ');
// A long log would overflow the frame height, so show this in the reserved note area instead.
paintGhosts(api);
if (ghosts)
ghosts.textContent = `The deleted rows are back in their original places (${where}).`;
}
},
};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)"
>New task</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.duplicate(api)"
>Duplicate selected</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSelected(api)"
>Delete selected</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>Save</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>Discard changes</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 { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
// Turns the save result into human-readable text (status is an English code, so it is not shown as is).
const saveText = (r: { status: string; committed: number; failed: number }): string => {
const words: Record<string, string> = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
empty: 'No changes to save',
invalid: 'Not saved because a value is not valid',
stale: 'Could not save because the server has a newer value',
};
const word = words[r.status] ?? 'Save finished';
const counts = r.committed || r.failed ? ` (${r.committed} succeeded, ${r.failed} failed)` : '';
return `${word}${counts}`;
};
export interface Row {
id: number;
title: string;
status: string;
priority: number;
created: Date;
actions: string;
}
const today = (): Date => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
};
const rows: Row[] = [
{
id: 1,
title: 'Fix login redirect bug',
status: 'open',
priority: 2,
created: new Date(2026, 9, 12),
actions: '',
},
{
id: 2,
title: 'Clean up footer links',
status: 'done',
priority: 4,
created: new Date(2026, 9, 20),
actions: '',
},
{
id: 3,
title: 'Speed up search',
status: 'blocked',
priority: 1,
created: new Date(2026, 10, 2),
actions: '',
},
];
const statusLabel: Record<string, string> = {
open: 'In progress',
blocked: 'Blocked',
done: 'Done',
};
const priorityLabel: Record<string, string> = {
1: 'Very low',
2: 'Low',
3: 'Medium',
4: 'High',
5: 'Very high',
};
let nextId = 100;
// Row order (row keys) as last saved. Saving resets it to the current order.
let baseline: number[] = rows.map((row) => row.id);
let grid: GridApi<Row> | null = null;
let say: (message: LogText) => void = () => {};
// The "defaults template" for a new row. The title is left empty (required), status and priority use defaults, and the created date is today.
const blank = (): Row => {
nextId += 1;
return { id: nextId, title: '', status: 'open', priority: 3, created: today(), actions: '' };
};
// Buttons inside a row. A cell renderer only receives the cell, so keep the api received in setup and use it from the buttons.
const rowButtons = (): CellRendererAdapter<Row> => {
let key: number;
let badge: HTMLSpanElement;
// Show the "New" badge if the row was added before saving.
const showBadge = (): void => {
const added = grid?.getChanges().some((c) => c.key === key && c.state === 'added');
badge.style.display = added ? '' : 'none';
};
// Same look as the in-row buttons of another example (renderer-action-buttons): small buttons that fit the row height.
const style =
'padding: 0 10px; height: 22px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;';
return {
mount(el, ctx) {
key = ctx.rowKey as number;
const edit = document.createElement('button');
edit.type = 'button';
edit.textContent = 'Edit';
edit.style.cssText = style;
edit.addEventListener('click', () => grid?.startEdit(key, 'title'));
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = 'Delete';
remove.style.cssText = style;
remove.addEventListener('click', () => grid?.removeRows([key]));
// Putting the buttons in a .mxg-cell-center box centers them vertically (cell content is not centered by default).
const box = document.createElement('div');
box.className = 'mxg-cell-center';
box.style.gap = '6px';
el.append(box);
badge = document.createElement('span');
badge.textContent = 'New';
badge.style.cssText =
'font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--mxg-accent); color: var(--mxg-accent-fg);';
box.append(edit, remove, badge);
showBadge();
},
update(ctx) {
key = ctx.rowKey as number; // When scrolling, the same cell is reused for another row.
showBadge();
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: 'Title', width: 150, editable: true, validation: { required: true } },
{ id: 'actions', title: 'Actions', width: 170, sortable: false, cellRenderer: rowButtons },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value),
},
{
id: 'priority',
title: 'Priority',
kind: 'select',
width: 110,
editable: true,
editorOptions: Object.entries(priorityLabel).map(([value, label]) => ({
value: Number(value),
label,
})),
formatValue: (value) => priorityLabel[String(value)] ?? String(value),
},
{ id: 'created', title: 'Created', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
},
};
// A deleted row vanishes from the grid at once, so until saving you could not tell which rows are deleted.
// So a "Deleted" note under the grid shows the deleted rows' titles with a strike-through.
let ghosts: HTMLElement | null = null;
function paintGhosts(api: GridApi<Row>): void {
const gone = api.getChanges().filter((c) => c.state === 'removed');
if (!ghosts) {
ghosts = document.createElement('div');
ghosts.setAttribute('role', 'status');
ghosts.style.cssText =
'margin-top: 6px; font-size: 13px; color: var(--muted); min-height: 2.8em;'; // reserve room for two lines in advance
document.getElementById('grid')?.after(ghosts);
}
ghosts.replaceChildren();
if (!gone.length) return;
ghosts.append('Deleted (not saved yet): ');
gone.forEach((change, i) => {
const title = document.createElement('s');
title.textContent = change.row.title || '(no title)';
if (i) ghosts?.append(', ');
ghosts?.append(title);
});
ghosts.append(' — "Discard changes" puts them back in their place.');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
baseline = rows.map((row) => row.id);
grid = api;
paintGhosts(api); // create the note area in advance (so the layout does not shift on delete)
say = log;
log('A new row gets a "New" mark, and a deletion can be undone until you save.');
const offSaved = api.on('changesCommitted', () => {
baseline = api.getRows().map((row) => row.id);
});
const off = api.on('changesCountChanged', ({ count, added, modified, removed }) => {
// The change count is not logged: the New badge and the "Deleted" note already show it, and a long log would overflow the frame height.
void [count, added, modified, removed];
api.refresh(); // redraw the "New" badge
paintGhosts(api);
});
return () => {
off();
offSaved();
ghosts?.remove();
ghosts = null;
grid = null;
};
}
export const actions = {
add: (api: GridApi<Row>) => {
// If the previous new row is still being edited (empty title fails validation), cancel that edit and add a new row.
if (api.isEditing()) api.stopEdit({ cancel: true });
const row = blank();
api.addRows([row], 0);
api.startEdit(row.id, 'title'); // open the first cell so you can type right away.
},
// Duplicate: make the selected rows into new rows right below the originals. A new row needs a new key.
duplicate: (api: GridApi<Row>) => {
const keys = new Set(api.getSelectedKeys());
const all = api.getRows();
for (let i = all.length - 1; i >= 0; i -= 1) {
const source = all[i];
if (!source || !keys.has(source.id)) continue;
nextId += 1;
api.addRows([{ ...source, id: nextId, title: `${source.title} (copy)` }], i + 1);
}
},
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (!keys.length) return say('Select the rows to delete first.');
api.removeRows(keys);
},
// A new row with an empty title is rejected by save(), so it cannot slip through.
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(
report.status === 'invalid'
? `Not saved: ${(report.errors ?? []).map((e) => `row ${e.rowKey} (${e.message})`).join(', ')}`
: `Save result: ${saveText(report)}`,
);
},
// Deleted rows come back with discard, but by default they are appended at the end. Re-sort by the saved order to put them back in place.
discard: (api: GridApi<Row>) => {
const gone = api
.getChanges()
.filter((c) => c.state === 'removed')
.map((c) => Number(c.key));
api.rollbackChanges();
const byId = new Map(api.getRows().map((row) => [row.id, row]));
const ordered = baseline.flatMap((id) => (byId.has(id) ? [byId.get(id) as Row] : []));
api.setRows(ordered);
if (gone.length) {
const where = gone.map((id) => `#${baseline.indexOf(id) + 1}`).join(', ');
// A long log would overflow the frame height, so show this in the reserved note area instead.
paintGhosts(api);
if (ghosts)
ghosts.textContent = `The deleted rows are back in their original places (${where}).`;
}
},
};