저장 방식 고르기: 모아서·바로·자동·저장 안 함Choose a save mode
고친 값을 모아서 한 번에 저장할지, 확정하는 즉시 저장할지, 가만히 있으면 자동 저장할지, 아예 추적하지 않을지 고를 수 있어요. 저장 전에 보낼 내용을 확인하는 단계를 둘 수도 있어요.Choose whether edits are saved together, at once, automatically after a pause, or not tracked at all. You can also add a review step that shows what will be sent.
코드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">
<select aria-label="저장 방식" id="mode">
<option value="batch" selected>모아서 저장</option>
<option value="immediate">바로 저장</option>
<option value="auto">자동 저장 (1.2초)</option>
<option value="none">저장 안 함</option>
</select>
<select aria-label="저장 전 확인" id="confirm">
<option value="off" selected>끄기</option>
<option value="on">켜기</option>
</select>
<button type="button" id="save">저장</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 200px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('confirm').addEventListener('change', (event) => actions.confirm(api, event.target.value));
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 rows = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '영업', salary: 3800 },
];
let mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer;
let say = () => { };
const AUTO_MS = 1200;
// 서버에 보내는 일을 흉내 내요. 아무것도 돌려주지 않고 끝나면 "모두 저장됨"이에요.
const saveToServer = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// 저장 방식(saveMode):
// - 'batch' 고친 것을 모아 두었다가 save()를 부를 때 한 번에 보내요(기본).
// - 'immediate' 칸을 확정하는 즉시 서버로 보내요.
// - 'none' 변경 추적을 아예 끄고, 값은 getRows()로 직접 읽어요(설정 화면처럼 "적용" 버튼을 페이지가 맡을 때).
// - 자동 저장은 'batch'에 타이머를 얹은 거예요: 마지막 수정 뒤 1.2초 동안 가만히 있으면 save()를 불러요.
export const options = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true, validation: { required: true } },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const labelEn = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
const label = {
batch: '모아서 저장',
immediate: '바로 저장',
auto: '자동 저장',
none: '저장 안 함',
};
export function setup(api, log) {
say = log;
log({
ko: '"저장 방식"을 바꿔 가며 칸을 고쳐 보세요. 모아서 저장은 "저장"을 눌러야 서버로 가요.',
en: 'Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".',
});
// 저장하지 않은 변경이 있는데 탭을 닫거나 새로고침하면 브라우저가 한 번 물어봐요.
const warn = (event) => {
if (mode === 'none' || !api.hasChanges())
return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // 새로 고치면 앞서 확인한 내용은 낡은 거예요.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log({
ko: `저장 안 한 ${count}줄 — 더 고치지 않으면 ${AUTO_MS / 1000}초 뒤 자동으로 저장해요`,
en: `${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`,
});
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) => log({
ko: `자동 저장: ${saveText(report)}`,
en: `Auto save: ${saveText(report, true)}`,
}));
}, AUTO_MS);
}
else if (mode === 'batch' && count > 0)
log({ ko: `저장 안 한 변경 ${count}줄`, en: `${count} unsaved changes` });
}),
api.on('saveStarted', ({ changes }) => log({
ko: `서버로 ${changes.length}줄을 보내는 중…`,
en: `Sending ${changes.length} rows to the server…`,
})),
api.on('changesCommitted', ({ changes }) => log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` })),
api.on('editCommitted', (e) => {
if (mode === 'none')
log({
ko: `저장 안 함 모드예요. 값은 바뀌지만 변경으로 추적하지 않아요(추적 중인 변경 ${api.getChanges().length}건). 바뀐 값: ${String(e.newValue)}`,
en: `No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`,
});
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
export const actions = {
mode: (api, value) => {
mode = (value ?? 'batch');
clearTimeout(timer);
// 자동 저장은 batch 위에서 돌아가요.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say({ ko: `저장 방식: ${label[mode]}`, en: `Save mode: ${labelEn[mode]}` });
},
confirm: (_api, value) => {
confirmFirst = value === 'on';
reviewed = false;
},
// 저장 전에 확인하는 단계를 두면, 첫 번째 누름은 "무엇을 보낼지" 보여 주기만 하고 두 번째 누름이 실제 저장이에요.
save: async (api) => {
if (mode === 'none') {
say({
ko: `저장 안 함 모드예요. 값은 직접 읽어요: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
en: `No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
});
return;
}
const changes = api.getChanges();
if (!changes.length)
return say({ ko: '보낼 변경이 없어요.', en: 'No changes to send.' });
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say({
ko: `보낼 내용 ${changes.length}줄: ${changes.map((c) => `${c.key}번(${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. 맞으면 한 번 더 "저장"을 눌러 주세요.`,
en: `To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`,
});
return;
}
reviewed = false;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 저장 안 함 모드는 변경을 추적하지 않아서 rollbackChanges()를 부르면 오류가 나요. 그래서 이 모드에서는 부르지 않아요.
discard: (api) => {
if (mode === 'none')
return say({
ko: '저장 안 함 모드는 변경을 추적하지 않아서 버릴 것이 없어요.',
en: 'No-save mode does not track changes, so there is nothing to discard.',
});
api.rollbackChanges();
},
};<!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">
<select aria-label="저장 방식" id="mode">
<option value="batch" selected>모아서 저장</option>
<option value="immediate">바로 저장</option>
<option value="auto">자동 저장 (1.2초)</option>
<option value="none">저장 안 함</option>
</select>
<select aria-label="저장 전 확인" id="confirm">
<option value="off" selected>끄기</option>
<option value="on">켜기</option>
</select>
<button type="button" id="save">저장</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 200px"></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 rows = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '영업', salary: 3800 },
];
let mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer;
let say = () => { };
const AUTO_MS = 1200;
// 서버에 보내는 일을 흉내 내요. 아무것도 돌려주지 않고 끝나면 "모두 저장됨"이에요.
const saveToServer = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// 저장 방식(saveMode):
// - 'batch' 고친 것을 모아 두었다가 save()를 부를 때 한 번에 보내요(기본).
// - 'immediate' 칸을 확정하는 즉시 서버로 보내요.
// - 'none' 변경 추적을 아예 끄고, 값은 getRows()로 직접 읽어요(설정 화면처럼 "적용" 버튼을 페이지가 맡을 때).
// - 자동 저장은 'batch'에 타이머를 얹은 거예요: 마지막 수정 뒤 1.2초 동안 가만히 있으면 save()를 불러요.
const options = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true, validation: { required: true } },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const labelEn = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
const label = {
batch: '모아서 저장',
immediate: '바로 저장',
auto: '자동 저장',
none: '저장 안 함',
};
function setup(api, log) {
say = log;
log({
ko: '"저장 방식"을 바꿔 가며 칸을 고쳐 보세요. 모아서 저장은 "저장"을 눌러야 서버로 가요.',
en: 'Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".',
});
// 저장하지 않은 변경이 있는데 탭을 닫거나 새로고침하면 브라우저가 한 번 물어봐요.
const warn = (event) => {
if (mode === 'none' || !api.hasChanges())
return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // 새로 고치면 앞서 확인한 내용은 낡은 거예요.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log({
ko: `저장 안 한 ${count}줄 — 더 고치지 않으면 ${AUTO_MS / 1000}초 뒤 자동으로 저장해요`,
en: `${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`,
});
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) => log({
ko: `자동 저장: ${saveText(report)}`,
en: `Auto save: ${saveText(report, true)}`,
}));
}, AUTO_MS);
}
else if (mode === 'batch' && count > 0)
log({ ko: `저장 안 한 변경 ${count}줄`, en: `${count} unsaved changes` });
}),
api.on('saveStarted', ({ changes }) => log({
ko: `서버로 ${changes.length}줄을 보내는 중…`,
en: `Sending ${changes.length} rows to the server…`,
})),
api.on('changesCommitted', ({ changes }) => log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` })),
api.on('editCommitted', (e) => {
if (mode === 'none')
log({
ko: `저장 안 함 모드예요. 값은 바뀌지만 변경으로 추적하지 않아요(추적 중인 변경 ${api.getChanges().length}건). 바뀐 값: ${String(e.newValue)}`,
en: `No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`,
});
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
const actions = {
mode: (api, value) => {
mode = (value ?? 'batch');
clearTimeout(timer);
// 자동 저장은 batch 위에서 돌아가요.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say({ ko: `저장 방식: ${label[mode]}`, en: `Save mode: ${labelEn[mode]}` });
},
confirm: (_api, value) => {
confirmFirst = value === 'on';
reviewed = false;
},
// 저장 전에 확인하는 단계를 두면, 첫 번째 누름은 "무엇을 보낼지" 보여 주기만 하고 두 번째 누름이 실제 저장이에요.
save: async (api) => {
if (mode === 'none') {
say({
ko: `저장 안 함 모드예요. 값은 직접 읽어요: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
en: `No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
});
return;
}
const changes = api.getChanges();
if (!changes.length)
return say({ ko: '보낼 변경이 없어요.', en: 'No changes to send.' });
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say({
ko: `보낼 내용 ${changes.length}줄: ${changes.map((c) => `${c.key}번(${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. 맞으면 한 번 더 "저장"을 눌러 주세요.`,
en: `To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`,
});
return;
}
reviewed = false;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 저장 안 함 모드는 변경을 추적하지 않아서 rollbackChanges()를 부르면 오류가 나요. 그래서 이 모드에서는 부르지 않아요.
discard: (api) => {
if (mode === 'none')
return say({
ko: '저장 안 함 모드는 변경을 추적하지 않아서 버릴 것이 없어요.',
en: 'No-save mode does not track changes, so there is nothing to discard.',
});
api.rollbackChanges();
},
};
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('confirm').addEventListener('change', (event) => actions.confirm(api, event.target.value));
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">
<select
aria-label="저장 방식"
disabled={!api}
onChange={(event) => api && actions.mode(api, event.target.value)}
>
<option value="batch">모아서 저장</option>
<option value="immediate">바로 저장</option>
<option value="auto">자동 저장 (1.2초)</option>
<option value="none">저장 안 함</option>
</select>
<select defaultValue="batch"
aria-label="저장 전 확인"
disabled={!api}
onChange={(event) => api && actions.confirm(api, event.target.value)}
>
<option value="off">끄기</option>
<option value="on">켜기</option>
</select>
<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: 200 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, SaveHandler } 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;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '영업', salary: 3800 },
];
type Mode = 'batch' | 'immediate' | 'auto' | 'none';
let mode: Mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let say: (message: LogText) => void = () => {};
const AUTO_MS = 1200;
// 서버에 보내는 일을 흉내 내요. 아무것도 돌려주지 않고 끝나면 "모두 저장됨"이에요.
const saveToServer: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// 저장 방식(saveMode):
// - 'batch' 고친 것을 모아 두었다가 save()를 부를 때 한 번에 보내요(기본).
// - 'immediate' 칸을 확정하는 즉시 서버로 보내요.
// - 'none' 변경 추적을 아예 끄고, 값은 getRows()로 직접 읽어요(설정 화면처럼 "적용" 버튼을 페이지가 맡을 때).
// - 자동 저장은 'batch'에 타이머를 얹은 거예요: 마지막 수정 뒤 1.2초 동안 가만히 있으면 save()를 불러요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true, validation: { required: true } },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const labelEn: Record<Mode, string> = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
const label: Record<Mode, string> = {
batch: '모아서 저장',
immediate: '바로 저장',
auto: '자동 저장',
none: '저장 안 함',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '"저장 방식"을 바꿔 가며 칸을 고쳐 보세요. 모아서 저장은 "저장"을 눌러야 서버로 가요.',
en: 'Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".',
});
// 저장하지 않은 변경이 있는데 탭을 닫거나 새로고침하면 브라우저가 한 번 물어봐요.
const warn = (event: BeforeUnloadEvent) => {
if (mode === 'none' || !api.hasChanges()) return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // 새로 고치면 앞서 확인한 내용은 낡은 거예요.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log({
ko: `저장 안 한 ${count}줄 — 더 고치지 않으면 ${AUTO_MS / 1000}초 뒤 자동으로 저장해요`,
en: `${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`,
});
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) =>
log({
ko: `자동 저장: ${saveText(report)}`,
en: `Auto save: ${saveText(report, true)}`,
}),
);
}, AUTO_MS);
} else if (mode === 'batch' && count > 0)
log({ ko: `저장 안 한 변경 ${count}줄`, en: `${count} unsaved changes` });
}),
api.on('saveStarted', ({ changes }) =>
log({
ko: `서버로 ${changes.length}줄을 보내는 중…`,
en: `Sending ${changes.length} rows to the server…`,
}),
),
api.on('changesCommitted', ({ changes }) =>
log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` }),
),
api.on('editCommitted', (e) => {
if (mode === 'none')
log({
ko: `저장 안 함 모드예요. 값은 바뀌지만 변경으로 추적하지 않아요(추적 중인 변경 ${api.getChanges().length}건). 바뀐 값: ${String(e.newValue)}`,
en: `No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`,
});
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = (value ?? 'batch') as Mode;
clearTimeout(timer);
// 자동 저장은 batch 위에서 돌아가요.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say({ ko: `저장 방식: ${label[mode]}`, en: `Save mode: ${labelEn[mode]}` });
},
confirm: (_api: GridApi<Row>, value?: string) => {
confirmFirst = value === 'on';
reviewed = false;
},
// 저장 전에 확인하는 단계를 두면, 첫 번째 누름은 "무엇을 보낼지" 보여 주기만 하고 두 번째 누름이 실제 저장이에요.
save: async (api: GridApi<Row>) => {
if (mode === 'none') {
say({
ko: `저장 안 함 모드예요. 값은 직접 읽어요: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
en: `No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
});
return;
}
const changes = api.getChanges();
if (!changes.length) return say({ ko: '보낼 변경이 없어요.', en: 'No changes to send.' });
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say({
ko: `보낼 내용 ${changes.length}줄: ${changes.map((c) => `${c.key}번(${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. 맞으면 한 번 더 "저장"을 눌러 주세요.`,
en: `To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`,
});
return;
}
reviewed = false;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 저장 안 함 모드는 변경을 추적하지 않아서 rollbackChanges()를 부르면 오류가 나요. 그래서 이 모드에서는 부르지 않아요.
discard: (api: GridApi<Row>) => {
if (mode === 'none')
return say({
ko: '저장 안 함 모드는 변경을 추적하지 않아서 버릴 것이 없어요.',
en: 'No-save mode does not track changes, so there is nothing to discard.',
});
api.rollbackChanges();
},
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="저장 방식"
:disabled="!api"
@change="api && actions.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="batch" selected>모아서 저장</option>
<option value="immediate">바로 저장</option>
<option value="auto">자동 저장 (1.2초)</option>
<option value="none">저장 안 함</option>
</select>
<select
aria-label="저장 전 확인"
:disabled="!api"
@change="api && actions.confirm(api, ($event.target as HTMLSelectElement).value)"
>
<option value="off" selected>끄기</option>
<option value="on">켜기</option>
</select>
<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: 200px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, SaveHandler } 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;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '영업', salary: 3800 },
];
type Mode = 'batch' | 'immediate' | 'auto' | 'none';
let mode: Mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let say: (message: LogText) => void = () => {};
const AUTO_MS = 1200;
// 서버에 보내는 일을 흉내 내요. 아무것도 돌려주지 않고 끝나면 "모두 저장됨"이에요.
const saveToServer: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// 저장 방식(saveMode):
// - 'batch' 고친 것을 모아 두었다가 save()를 부를 때 한 번에 보내요(기본).
// - 'immediate' 칸을 확정하는 즉시 서버로 보내요.
// - 'none' 변경 추적을 아예 끄고, 값은 getRows()로 직접 읽어요(설정 화면처럼 "적용" 버튼을 페이지가 맡을 때).
// - 자동 저장은 'batch'에 타이머를 얹은 거예요: 마지막 수정 뒤 1.2초 동안 가만히 있으면 save()를 불러요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true, validation: { required: true } },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const labelEn: Record<Mode, string> = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
const label: Record<Mode, string> = {
batch: '모아서 저장',
immediate: '바로 저장',
auto: '자동 저장',
none: '저장 안 함',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '"저장 방식"을 바꿔 가며 칸을 고쳐 보세요. 모아서 저장은 "저장"을 눌러야 서버로 가요.',
en: 'Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".',
});
// 저장하지 않은 변경이 있는데 탭을 닫거나 새로고침하면 브라우저가 한 번 물어봐요.
const warn = (event: BeforeUnloadEvent) => {
if (mode === 'none' || !api.hasChanges()) return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // 새로 고치면 앞서 확인한 내용은 낡은 거예요.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log({
ko: `저장 안 한 ${count}줄 — 더 고치지 않으면 ${AUTO_MS / 1000}초 뒤 자동으로 저장해요`,
en: `${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`,
});
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) =>
log({
ko: `자동 저장: ${saveText(report)}`,
en: `Auto save: ${saveText(report, true)}`,
}),
);
}, AUTO_MS);
} else if (mode === 'batch' && count > 0)
log({ ko: `저장 안 한 변경 ${count}줄`, en: `${count} unsaved changes` });
}),
api.on('saveStarted', ({ changes }) =>
log({
ko: `서버로 ${changes.length}줄을 보내는 중…`,
en: `Sending ${changes.length} rows to the server…`,
}),
),
api.on('changesCommitted', ({ changes }) =>
log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` }),
),
api.on('editCommitted', (e) => {
if (mode === 'none')
log({
ko: `저장 안 함 모드예요. 값은 바뀌지만 변경으로 추적하지 않아요(추적 중인 변경 ${api.getChanges().length}건). 바뀐 값: ${String(e.newValue)}`,
en: `No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`,
});
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = (value ?? 'batch') as Mode;
clearTimeout(timer);
// 자동 저장은 batch 위에서 돌아가요.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say({ ko: `저장 방식: ${label[mode]}`, en: `Save mode: ${labelEn[mode]}` });
},
confirm: (_api: GridApi<Row>, value?: string) => {
confirmFirst = value === 'on';
reviewed = false;
},
// 저장 전에 확인하는 단계를 두면, 첫 번째 누름은 "무엇을 보낼지" 보여 주기만 하고 두 번째 누름이 실제 저장이에요.
save: async (api: GridApi<Row>) => {
if (mode === 'none') {
say({
ko: `저장 안 함 모드예요. 값은 직접 읽어요: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
en: `No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
});
return;
}
const changes = api.getChanges();
if (!changes.length) return say({ ko: '보낼 변경이 없어요.', en: 'No changes to send.' });
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say({
ko: `보낼 내용 ${changes.length}줄: ${changes.map((c) => `${c.key}번(${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. 맞으면 한 번 더 "저장"을 눌러 주세요.`,
en: `To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`,
});
return;
}
reviewed = false;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 저장 안 함 모드는 변경을 추적하지 않아서 rollbackChanges()를 부르면 오류가 나요. 그래서 이 모드에서는 부르지 않아요.
discard: (api: GridApi<Row>) => {
if (mode === 'none')
return say({
ko: '저장 안 함 모드는 변경을 추적하지 않아서 버릴 것이 없어요.',
en: 'No-save mode does not track changes, so there is nothing to discard.',
});
api.rollbackChanges();
},
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="저장 방식"
[disabled]="!api"
(change)="api && actions.mode(api, $any($event.target).value)"
>
<option value="batch" selected>모아서 저장</option>
<option value="immediate">바로 저장</option>
<option value="auto">자동 저장 (1.2초)</option>
<option value="none">저장 안 함</option>
</select>
<select
aria-label="저장 전 확인"
[disabled]="!api"
(change)="api && actions.confirm(api, $any($event.target).value)"
>
<option value="off" selected>끄기</option>
<option value="on">켜기</option>
</select>
<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: 200px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, SaveHandler } 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;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: '김서연', department: '개발', salary: 4200 },
{ id: 2, name: '이준호', department: '디자인', salary: 3900 },
{ id: 3, name: '박민지', department: '기획', salary: 4100 },
{ id: 4, name: '최도윤', department: '영업', salary: 3800 },
];
type Mode = 'batch' | 'immediate' | 'auto' | 'none';
let mode: Mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let say: (message: LogText) => void = () => {};
const AUTO_MS = 1200;
// 서버에 보내는 일을 흉내 내요. 아무것도 돌려주지 않고 끝나면 "모두 저장됨"이에요.
const saveToServer: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// 저장 방식(saveMode):
// - 'batch' 고친 것을 모아 두었다가 save()를 부를 때 한 번에 보내요(기본).
// - 'immediate' 칸을 확정하는 즉시 서버로 보내요.
// - 'none' 변경 추적을 아예 끄고, 값은 getRows()로 직접 읽어요(설정 화면처럼 "적용" 버튼을 페이지가 맡을 때).
// - 자동 저장은 'batch'에 타이머를 얹은 거예요: 마지막 수정 뒤 1.2초 동안 가만히 있으면 save()를 불러요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110, editable: true, validation: { required: true } },
{ id: 'department', title: '부서', width: 100, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const labelEn: Record<Mode, string> = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
const label: Record<Mode, string> = {
batch: '모아서 저장',
immediate: '바로 저장',
auto: '자동 저장',
none: '저장 안 함',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '"저장 방식"을 바꿔 가며 칸을 고쳐 보세요. 모아서 저장은 "저장"을 눌러야 서버로 가요.',
en: 'Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".',
});
// 저장하지 않은 변경이 있는데 탭을 닫거나 새로고침하면 브라우저가 한 번 물어봐요.
const warn = (event: BeforeUnloadEvent) => {
if (mode === 'none' || !api.hasChanges()) return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // 새로 고치면 앞서 확인한 내용은 낡은 거예요.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log({
ko: `저장 안 한 ${count}줄 — 더 고치지 않으면 ${AUTO_MS / 1000}초 뒤 자동으로 저장해요`,
en: `${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`,
});
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) =>
log({
ko: `자동 저장: ${saveText(report)}`,
en: `Auto save: ${saveText(report, true)}`,
}),
);
}, AUTO_MS);
} else if (mode === 'batch' && count > 0)
log({ ko: `저장 안 한 변경 ${count}줄`, en: `${count} unsaved changes` });
}),
api.on('saveStarted', ({ changes }) =>
log({
ko: `서버로 ${changes.length}줄을 보내는 중…`,
en: `Sending ${changes.length} rows to the server…`,
}),
),
api.on('changesCommitted', ({ changes }) =>
log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` }),
),
api.on('editCommitted', (e) => {
if (mode === 'none')
log({
ko: `저장 안 함 모드예요. 값은 바뀌지만 변경으로 추적하지 않아요(추적 중인 변경 ${api.getChanges().length}건). 바뀐 값: ${String(e.newValue)}`,
en: `No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`,
});
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = (value ?? 'batch') as Mode;
clearTimeout(timer);
// 자동 저장은 batch 위에서 돌아가요.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say({ ko: `저장 방식: ${label[mode]}`, en: `Save mode: ${labelEn[mode]}` });
},
confirm: (_api: GridApi<Row>, value?: string) => {
confirmFirst = value === 'on';
reviewed = false;
},
// 저장 전에 확인하는 단계를 두면, 첫 번째 누름은 "무엇을 보낼지" 보여 주기만 하고 두 번째 누름이 실제 저장이에요.
save: async (api: GridApi<Row>) => {
if (mode === 'none') {
say({
ko: `저장 안 함 모드예요. 값은 직접 읽어요: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
en: `No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
});
return;
}
const changes = api.getChanges();
if (!changes.length) return say({ ko: '보낼 변경이 없어요.', en: 'No changes to send.' });
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say({
ko: `보낼 내용 ${changes.length}줄: ${changes.map((c) => `${c.key}번(${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. 맞으면 한 번 더 "저장"을 눌러 주세요.`,
en: `To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`,
});
return;
}
reviewed = false;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 저장 안 함 모드는 변경을 추적하지 않아서 rollbackChanges()를 부르면 오류가 나요. 그래서 이 모드에서는 부르지 않아요.
discard: (api: GridApi<Row>) => {
if (mode === 'none')
return say({
ko: '저장 안 함 모드는 변경을 추적하지 않아서 버릴 것이 없어요.',
en: 'No-save mode does not track changes, so there is nothing to discard.',
});
api.rollbackChanges();
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="Save mode" id="mode">
<option value="batch" selected>Save together</option>
<option value="immediate">Save at once</option>
<option value="auto">Auto save (1.2 s)</option>
<option value="none">No saving</option>
</select>
<select aria-label="Review before saving" id="confirm">
<option value="off" selected>Off</option>
<option value="on">On</option>
</select>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 200px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('confirm').addEventListener('change', (event) => actions.confirm(api, event.target.value));
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 rows = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Olivia Park', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Noah Kim', department: 'Sales', salary: 38000 },
];
let mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer;
let say = () => { };
const AUTO_MS = 1200;
// Simulates sending to the server. Finishing without returning anything means "all saved".
const saveToServer = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// Save modes (saveMode):
// - 'batch' collects edits and sends them at once when save() is called (default).
// - 'immediate' sends to the server as soon as a cell is committed.
// - 'none' turns change tracking off; read values yourself with getRows() (when the page owns an "Apply" button, like a settings screen).
// - Auto save is 'batch' plus a timer: save() is called after 1.2 seconds without edits.
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'department', title: 'Department', width: 130, editable: true },
{
id: 'salary',
title: 'Monthly salary ($)',
kind: 'number',
width: 170,
align: 'end',
editable: true,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const label = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
export function setup(api, log) {
say = log;
log('Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".');
// If there are unsaved changes and the tab is closed or reloaded, the browser asks once.
const warn = (event) => {
if (mode === 'none' || !api.hasChanges())
return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // After a new edit, the previously reviewed content is stale.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log(`${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`);
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) => log(`Auto save: ${saveText(report)}`));
}, AUTO_MS);
}
else if (mode === 'batch' && count > 0)
log(`${count} unsaved changes`);
}),
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('editCommitted', (e) => {
if (mode === 'none')
log(`No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`);
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
export const actions = {
mode: (api, value) => {
mode = (value ?? 'batch');
clearTimeout(timer);
// Auto save runs on top of batch.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say(`Save mode: ${label[mode]}`);
},
confirm: (_api, value) => {
confirmFirst = value === 'on';
reviewed = false;
},
// With the review step on, the first press only shows "what will be sent" and the second press really saves.
save: async (api) => {
if (mode === 'none') {
say(`No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`);
return;
}
const changes = api.getChanges();
if (!changes.length)
return say('No changes to send.');
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say(`To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`);
return;
}
reviewed = false;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// No-save mode does not track changes, so rollbackChanges() would throw an error. It is not called in this mode.
discard: (api) => {
if (mode === 'none')
return say('No-save mode does not track changes, so there is nothing to discard.');
api.rollbackChanges();
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Choose a save mode</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Save mode" id="mode">
<option value="batch" selected>Save together</option>
<option value="immediate">Save at once</option>
<option value="auto">Auto save (1.2 s)</option>
<option value="none">No saving</option>
</select>
<select aria-label="Review before saving" id="confirm">
<option value="off" selected>Off</option>
<option value="on">On</option>
</select>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 200px"></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 rows = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Olivia Park', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Noah Kim', department: 'Sales', salary: 38000 },
];
let mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer;
let say = () => { };
const AUTO_MS = 1200;
// Simulates sending to the server. Finishing without returning anything means "all saved".
const saveToServer = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// Save modes (saveMode):
// - 'batch' collects edits and sends them at once when save() is called (default).
// - 'immediate' sends to the server as soon as a cell is committed.
// - 'none' turns change tracking off; read values yourself with getRows() (when the page owns an "Apply" button, like a settings screen).
// - Auto save is 'batch' plus a timer: save() is called after 1.2 seconds without edits.
const options = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'department', title: 'Department', width: 130, editable: true },
{
id: 'salary',
title: 'Monthly salary ($)',
kind: 'number',
width: 170,
align: 'end',
editable: true,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const label = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
function setup(api, log) {
say = log;
log('Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".');
// If there are unsaved changes and the tab is closed or reloaded, the browser asks once.
const warn = (event) => {
if (mode === 'none' || !api.hasChanges())
return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // After a new edit, the previously reviewed content is stale.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log(`${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`);
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) => log(`Auto save: ${saveText(report)}`));
}, AUTO_MS);
}
else if (mode === 'batch' && count > 0)
log(`${count} unsaved changes`);
}),
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('editCommitted', (e) => {
if (mode === 'none')
log(`No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`);
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
const actions = {
mode: (api, value) => {
mode = (value ?? 'batch');
clearTimeout(timer);
// Auto save runs on top of batch.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say(`Save mode: ${label[mode]}`);
},
confirm: (_api, value) => {
confirmFirst = value === 'on';
reviewed = false;
},
// With the review step on, the first press only shows "what will be sent" and the second press really saves.
save: async (api) => {
if (mode === 'none') {
say(`No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`);
return;
}
const changes = api.getChanges();
if (!changes.length)
return say('No changes to send.');
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say(`To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`);
return;
}
reviewed = false;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// No-save mode does not track changes, so rollbackChanges() would throw an error. It is not called in this mode.
discard: (api) => {
if (mode === 'none')
return say('No-save mode does not track changes, so there is nothing to discard.');
api.rollbackChanges();
},
};
options.ariaLabel = "Choose a save mode";
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('confirm').addEventListener('change', (event) => actions.confirm(api, event.target.value));
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">
<select
aria-label="Save mode"
disabled={!api}
onChange={(event) => api && actions.mode(api, event.target.value)}
>
<option value="batch">Save together</option>
<option value="immediate">Save at once</option>
<option value="auto">Auto save (1.2 s)</option>
<option value="none">No saving</option>
</select>
<select defaultValue="batch"
aria-label="Review before saving"
disabled={!api}
onChange={(event) => api && actions.confirm(api, event.target.value)}
>
<option value="off">Off</option>
<option value="on">On</option>
</select>
<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: 200 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, SaveHandler } 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;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Olivia Park', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Noah Kim', department: 'Sales', salary: 38000 },
];
type Mode = 'batch' | 'immediate' | 'auto' | 'none';
let mode: Mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let say: (message: LogText) => void = () => {};
const AUTO_MS = 1200;
// Simulates sending to the server. Finishing without returning anything means "all saved".
const saveToServer: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// Save modes (saveMode):
// - 'batch' collects edits and sends them at once when save() is called (default).
// - 'immediate' sends to the server as soon as a cell is committed.
// - 'none' turns change tracking off; read values yourself with getRows() (when the page owns an "Apply" button, like a settings screen).
// - Auto save is 'batch' plus a timer: save() is called after 1.2 seconds without edits.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'department', title: 'Department', width: 130, editable: true },
{
id: 'salary',
title: 'Monthly salary ($)',
kind: 'number',
width: 170,
align: 'end',
editable: true,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const label: Record<Mode, string> = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(
'Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".',
);
// If there are unsaved changes and the tab is closed or reloaded, the browser asks once.
const warn = (event: BeforeUnloadEvent) => {
if (mode === 'none' || !api.hasChanges()) return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // After a new edit, the previously reviewed content is stale.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log(
`${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`,
);
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) => log(`Auto save: ${saveText(report)}`));
}, AUTO_MS);
} else if (mode === 'batch' && count > 0) log(`${count} unsaved changes`);
}),
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('editCommitted', (e) => {
if (mode === 'none')
log(
`No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`,
);
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = (value ?? 'batch') as Mode;
clearTimeout(timer);
// Auto save runs on top of batch.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say(`Save mode: ${label[mode]}`);
},
confirm: (_api: GridApi<Row>, value?: string) => {
confirmFirst = value === 'on';
reviewed = false;
},
// With the review step on, the first press only shows "what will be sent" and the second press really saves.
save: async (api: GridApi<Row>) => {
if (mode === 'none') {
say(
`No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
);
return;
}
const changes = api.getChanges();
if (!changes.length) return say('No changes to send.');
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say(
`To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`,
);
return;
}
reviewed = false;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// No-save mode does not track changes, so rollbackChanges() would throw an error. It is not called in this mode.
discard: (api: GridApi<Row>) => {
if (mode === 'none')
return say('No-save mode does not track changes, so there is nothing to discard.');
api.rollbackChanges();
},
};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">
<select
aria-label="Save mode"
:disabled="!api"
@change="api && actions.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="batch" selected>Save together</option>
<option value="immediate">Save at once</option>
<option value="auto">Auto save (1.2 s)</option>
<option value="none">No saving</option>
</select>
<select
aria-label="Review before saving"
:disabled="!api"
@change="api && actions.confirm(api, ($event.target as HTMLSelectElement).value)"
>
<option value="off" selected>Off</option>
<option value="on">On</option>
</select>
<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: 200px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, SaveHandler } 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;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Olivia Park', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Noah Kim', department: 'Sales', salary: 38000 },
];
type Mode = 'batch' | 'immediate' | 'auto' | 'none';
let mode: Mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let say: (message: LogText) => void = () => {};
const AUTO_MS = 1200;
// Simulates sending to the server. Finishing without returning anything means "all saved".
const saveToServer: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// Save modes (saveMode):
// - 'batch' collects edits and sends them at once when save() is called (default).
// - 'immediate' sends to the server as soon as a cell is committed.
// - 'none' turns change tracking off; read values yourself with getRows() (when the page owns an "Apply" button, like a settings screen).
// - Auto save is 'batch' plus a timer: save() is called after 1.2 seconds without edits.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'department', title: 'Department', width: 130, editable: true },
{
id: 'salary',
title: 'Monthly salary ($)',
kind: 'number',
width: 170,
align: 'end',
editable: true,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const label: Record<Mode, string> = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(
'Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".',
);
// If there are unsaved changes and the tab is closed or reloaded, the browser asks once.
const warn = (event: BeforeUnloadEvent) => {
if (mode === 'none' || !api.hasChanges()) return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // After a new edit, the previously reviewed content is stale.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log(
`${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`,
);
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) => log(`Auto save: ${saveText(report)}`));
}, AUTO_MS);
} else if (mode === 'batch' && count > 0) log(`${count} unsaved changes`);
}),
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('editCommitted', (e) => {
if (mode === 'none')
log(
`No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`,
);
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = (value ?? 'batch') as Mode;
clearTimeout(timer);
// Auto save runs on top of batch.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say(`Save mode: ${label[mode]}`);
},
confirm: (_api: GridApi<Row>, value?: string) => {
confirmFirst = value === 'on';
reviewed = false;
},
// With the review step on, the first press only shows "what will be sent" and the second press really saves.
save: async (api: GridApi<Row>) => {
if (mode === 'none') {
say(
`No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
);
return;
}
const changes = api.getChanges();
if (!changes.length) return say('No changes to send.');
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say(
`To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`,
);
return;
}
reviewed = false;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// No-save mode does not track changes, so rollbackChanges() would throw an error. It is not called in this mode.
discard: (api: GridApi<Row>) => {
if (mode === 'none')
return say('No-save mode does not track changes, so there is nothing to discard.');
api.rollbackChanges();
},
};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">
<select
aria-label="Save mode"
[disabled]="!api"
(change)="api && actions.mode(api, $any($event.target).value)"
>
<option value="batch" selected>Save together</option>
<option value="immediate">Save at once</option>
<option value="auto">Auto save (1.2 s)</option>
<option value="none">No saving</option>
</select>
<select
aria-label="Review before saving"
[disabled]="!api"
(change)="api && actions.confirm(api, $any($event.target).value)"
>
<option value="off" selected>Off</option>
<option value="on">On</option>
</select>
<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: 200px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, SaveHandler } 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;
name: string;
department: string;
salary: number;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', department: 'Dev', salary: 42000 },
{ id: 2, name: 'Emma Stone', department: 'Design', salary: 39000 },
{ id: 3, name: 'Olivia Park', department: 'Planning', salary: 41000 },
{ id: 4, name: 'Noah Kim', department: 'Sales', salary: 38000 },
];
type Mode = 'batch' | 'immediate' | 'auto' | 'none';
let mode: Mode = 'batch';
let confirmFirst = false;
let reviewed = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let say: (message: LogText) => void = () => {};
const AUTO_MS = 1200;
// Simulates sending to the server. Finishing without returning anything means "all saved".
const saveToServer: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 400));
};
// Save modes (saveMode):
// - 'batch' collects edits and sends them at once when save() is called (default).
// - 'immediate' sends to the server as soon as a cell is committed.
// - 'none' turns change tracking off; read values yourself with getRows() (when the page owns an "Apply" button, like a settings screen).
// - Auto save is 'batch' plus a timer: save() is called after 1.2 seconds without edits.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'department', title: 'Department', width: 130, editable: true },
{
id: 'salary',
title: 'Monthly salary ($)',
kind: 'number',
width: 170,
align: 'end',
editable: true,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
const label: Record<Mode, string> = {
batch: 'batch save',
immediate: 'save at once',
auto: 'auto save',
none: 'no save',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(
'Edit cells while changing "Save mode". With batch save, nothing goes to the server until you press "Save".',
);
// If there are unsaved changes and the tab is closed or reloaded, the browser asks once.
const warn = (event: BeforeUnloadEvent) => {
if (mode === 'none' || !api.hasChanges()) return;
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
const offs = [
api.on('changesCountChanged', ({ count, saving }) => {
reviewed = false; // After a new edit, the previously reviewed content is stale.
clearTimeout(timer);
if (mode === 'auto' && count > 0 && !saving) {
log(
`${count} unsaved rows — saved automatically in ${AUTO_MS / 1000} seconds unless you edit more`,
);
timer = setTimeout(() => {
if (!api.isDestroyed())
void api.save().then((report) => log(`Auto save: ${saveText(report)}`));
}, AUTO_MS);
} else if (mode === 'batch' && count > 0) log(`${count} unsaved changes`);
}),
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('editCommitted', (e) => {
if (mode === 'none')
log(
`No-save mode. Values change but are not tracked as changes (${api.getChanges().length} tracked). Changed value: ${String(e.newValue)}`,
);
}),
];
return () => {
clearTimeout(timer);
window.removeEventListener('beforeunload', warn);
offs.forEach((off) => off());
};
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = (value ?? 'batch') as Mode;
clearTimeout(timer);
// Auto save runs on top of batch.
api.setOptions({ saveMode: mode === 'auto' ? 'batch' : mode });
say(`Save mode: ${label[mode]}`);
},
confirm: (_api: GridApi<Row>, value?: string) => {
confirmFirst = value === 'on';
reviewed = false;
},
// With the review step on, the first press only shows "what will be sent" and the second press really saves.
save: async (api: GridApi<Row>) => {
if (mode === 'none') {
say(
`No-save mode. Read the values yourself: ${JSON.stringify(api.getRows().map((r) => r.salary))}`,
);
return;
}
const changes = api.getChanges();
if (!changes.length) return say('No changes to send.');
if (confirmFirst && !reviewed) {
reviewed = true;
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
say(
`To send: ${changes.length} rows: ${changes.map((c) => `${c.key} (${(c.cells ?? []).map((x) => `${title(x.columnId)} ${String(x.oldValue)}→${String(x.newValue)}`).join(', ') || c.state})`).join(' / ')}. If correct, press "Save" once more.`,
);
return;
}
reviewed = false;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// No-save mode does not track changes, so rollbackChanges() would throw an error. It is not called in this mode.
discard: (api: GridApi<Row>) => {
if (mode === 'none')
return say('No-save mode does not track changes, so there is nothing to discard.');
api.rollbackChanges();
},
};