저장이 실패해도 변경은 남기기Keep changes when saving fails
서버가 일부 줄만 거부하거나, 아예 응답하지 않아도 고친 값은 사라지지 않아요. 실패한 줄은 변경으로 남아서 고친 뒤 다시 저장할 수 있고, 응답이 없을 때는 기다리는 시간을 늘려 가며 다시 시도하는 처리기도 보여 줘요.If the server rejects some rows, or does not answer at all, your edits are not lost. Failed rows stay as changes you can fix and save again, and the handler retries with growing waits when the server is down.
코드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="server">
<option value="ok" selected>정상</option>
<option value="partial">일부 줄 거부</option>
<option value="down">응답 없음 (3번 재시도)</option>
</select>
<select aria-label="저장 방식" id="saveMode">
<option value="batch" selected>모아서 저장</option>
<option value="immediate">바로 저장</option>
</select>
<button type="button" id="save">저장</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 280px"></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('server').addEventListener('change', (event) => actions.server(api, event.target.value));
document.getElementById('saveMode').addEventListener('change', (event) => actions.saveMode(api, event.target.value));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 저장 결과를 사람이 읽는 말로 바꿔요(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: '바질', stock: 14 },
{ id: 2, name: '타임', stock: 9 },
{ id: 3, name: '파슬리', stock: 31 },
{ id: 4, name: '민트', stock: 5 },
];
const server = { mode: 'ok' };
let attempts = 0;
let say = () => { };
const wait = (ms, signal) => new Promise((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// 저장 처리기(saveHandler)가 돌려주는 값으로 결과를 알려요:
// - 아무것도 안 돌려주면 모두 저장됨.
// - { failed: [...] }를 돌려주면 그 줄만 실패한 "일부 실패"예요. 나머지는 저장돼요.
// - 예외를 던지면 요청 전체가 실패한 거고, 모든 변경이 그대로 남아서 다시 저장할 수 있어요.
const handler = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: L('다른 사람이 이 재고를 잠그고 있어요', 'Someone else has locked this stock'),
},
],
};
}
if (server.mode === 'down') {
// 서버가 죽었을 때는 세 번까지 기다리는 시간을 늘려 가며 다시 시도하고, 그래도 안 되면 던져요.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say({
ko: ` 시도 ${attempts}: 서버가 응답하지 않아요`,
en: ` attempt ${attempts}: the server does not respond`,
});
await wait(n * 250, signal);
}
throw new Error('서버가 응답하지 않아요');
}
};
export const options = {
columns: [
{ id: 'name', title: '품목', width: 130, editable: true },
{ id: 'stock', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
export function setup(api, log) {
say = log;
attempts = 0;
log({
ko: '칸을 두세 개 고친 뒤 "서버 동작"을 바꿔 가며 "저장"을 눌러 보세요.',
en: 'Edit two or three cells, then press "Save" while changing the "Server behavior".',
});
const offs = [
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('saveFailed', ({ failed, error }) => {
if (failed.length)
log({
ko: `✗ 일부 실패: ${failed.map((f) => `${f.key}번 줄(${f.message})`).join(', ')} — 나머지는 저장됐어요`,
en: `✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`,
});
else
log({
ko: `✗ 요청이 통째로 실패했어요: ${error instanceof Error ? error.message : String(error)} — 변경은 그대로 남아 있어요`,
en: `✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`,
});
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
server: (_api, value) => {
server.mode = (value ?? 'ok');
attempts = 0;
},
// 저장 방식도 바꿔 볼 수 있어요. 'immediate'는 화면에 먼저 보이고(낙관적) 뒤에서 서버가 확인해요.
saveMode: (api, value) => api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api) => {
attempts = 0;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
discard: (api) => 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="server">
<option value="ok" selected>정상</option>
<option value="partial">일부 줄 거부</option>
<option value="down">응답 없음 (3번 재시도)</option>
</select>
<select aria-label="저장 방식" id="saveMode">
<option value="batch" selected>모아서 저장</option>
<option value="immediate">바로 저장</option>
</select>
<button type="button" id="save">저장</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 280px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 저장 결과를 사람이 읽는 말로 바꿔요(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: '바질', stock: 14 },
{ id: 2, name: '타임', stock: 9 },
{ id: 3, name: '파슬리', stock: 31 },
{ id: 4, name: '민트', stock: 5 },
];
const server = { mode: 'ok' };
let attempts = 0;
let say = () => { };
const wait = (ms, signal) => new Promise((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// 저장 처리기(saveHandler)가 돌려주는 값으로 결과를 알려요:
// - 아무것도 안 돌려주면 모두 저장됨.
// - { failed: [...] }를 돌려주면 그 줄만 실패한 "일부 실패"예요. 나머지는 저장돼요.
// - 예외를 던지면 요청 전체가 실패한 거고, 모든 변경이 그대로 남아서 다시 저장할 수 있어요.
const handler = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: L('다른 사람이 이 재고를 잠그고 있어요', 'Someone else has locked this stock'),
},
],
};
}
if (server.mode === 'down') {
// 서버가 죽었을 때는 세 번까지 기다리는 시간을 늘려 가며 다시 시도하고, 그래도 안 되면 던져요.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say({
ko: ` 시도 ${attempts}: 서버가 응답하지 않아요`,
en: ` attempt ${attempts}: the server does not respond`,
});
await wait(n * 250, signal);
}
throw new Error('서버가 응답하지 않아요');
}
};
const options = {
columns: [
{ id: 'name', title: '품목', width: 130, editable: true },
{ id: 'stock', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
function setup(api, log) {
say = log;
attempts = 0;
log({
ko: '칸을 두세 개 고친 뒤 "서버 동작"을 바꿔 가며 "저장"을 눌러 보세요.',
en: 'Edit two or three cells, then press "Save" while changing the "Server behavior".',
});
const offs = [
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('saveFailed', ({ failed, error }) => {
if (failed.length)
log({
ko: `✗ 일부 실패: ${failed.map((f) => `${f.key}번 줄(${f.message})`).join(', ')} — 나머지는 저장됐어요`,
en: `✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`,
});
else
log({
ko: `✗ 요청이 통째로 실패했어요: ${error instanceof Error ? error.message : String(error)} — 변경은 그대로 남아 있어요`,
en: `✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`,
});
}),
];
return () => offs.forEach((off) => off());
}
const actions = {
server: (_api, value) => {
server.mode = (value ?? 'ok');
attempts = 0;
},
// 저장 방식도 바꿔 볼 수 있어요. 'immediate'는 화면에 먼저 보이고(낙관적) 뒤에서 서버가 확인해요.
saveMode: (api, value) => api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api) => {
attempts = 0;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
discard: (api) => 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('server').addEventListener('change', (event) => actions.server(api, event.target.value));
document.getElementById('saveMode').addEventListener('change', (event) => actions.saveMode(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.server(api, event.target.value)}
>
<option value="ok">정상</option>
<option value="partial">일부 줄 거부</option>
<option value="down">응답 없음 (3번 재시도)</option>
</select>
<select defaultValue="ok"
aria-label="저장 방식"
disabled={!api}
onChange={(event) => api && actions.saveMode(api, event.target.value)}
>
<option value="batch">모아서 저장</option>
<option value="immediate">바로 저장</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: 280 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
// 저장 결과를 사람이 읽는 말로 바꿔요(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;
stock: number;
}
const rows: Row[] = [
{ id: 1, name: '바질', stock: 14 },
{ id: 2, name: '타임', stock: 9 },
{ id: 3, name: '파슬리', stock: 31 },
{ id: 4, name: '민트', stock: 5 },
];
// 시험용 가짜 서버예요. 동작을 바꿔 가며 저장해 보세요.
type Behavior = 'ok' | 'partial' | 'down';
const server: { mode: Behavior } = { mode: 'ok' };
let attempts = 0;
let say: (message: LogText) => void = () => {};
const wait = (ms: number, signal: AbortSignal) =>
new Promise<void>((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// 저장 처리기(saveHandler)가 돌려주는 값으로 결과를 알려요:
// - 아무것도 안 돌려주면 모두 저장됨.
// - { failed: [...] }를 돌려주면 그 줄만 실패한 "일부 실패"예요. 나머지는 저장돼요.
// - 예외를 던지면 요청 전체가 실패한 거고, 모든 변경이 그대로 남아서 다시 저장할 수 있어요.
const handler: SaveHandler<Row> = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: L('다른 사람이 이 재고를 잠그고 있어요', 'Someone else has locked this stock'),
},
],
};
}
if (server.mode === 'down') {
// 서버가 죽었을 때는 세 번까지 기다리는 시간을 늘려 가며 다시 시도하고, 그래도 안 되면 던져요.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say({
ko: ` 시도 ${attempts}: 서버가 응답하지 않아요`,
en: ` attempt ${attempts}: the server does not respond`,
});
await wait(n * 250, signal);
}
throw new Error('서버가 응답하지 않아요');
}
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '품목', width: 130, editable: true },
{ id: 'stock', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
attempts = 0;
log({
ko: '칸을 두세 개 고친 뒤 "서버 동작"을 바꿔 가며 "저장"을 눌러 보세요.',
en: 'Edit two or three cells, then press "Save" while changing the "Server behavior".',
});
const offs = [
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('saveFailed', ({ failed, error }) => {
if (failed.length)
log({
ko: `✗ 일부 실패: ${failed.map((f) => `${f.key}번 줄(${f.message})`).join(', ')} — 나머지는 저장됐어요`,
en: `✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`,
});
else
log({
ko: `✗ 요청이 통째로 실패했어요: ${error instanceof Error ? error.message : String(error)} — 변경은 그대로 남아 있어요`,
en: `✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`,
});
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
server: (_api: GridApi<Row>, value?: string) => {
server.mode = (value ?? 'ok') as Behavior;
attempts = 0;
},
// 저장 방식도 바꿔 볼 수 있어요. 'immediate'는 화면에 먼저 보이고(낙관적) 뒤에서 서버가 확인해요.
saveMode: (api: GridApi<Row>, value?: string) =>
api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api: GridApi<Row>) => {
attempts = 0;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
discard: (api: GridApi<Row>) => 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.server(api, ($event.target as HTMLSelectElement).value)"
>
<option value="ok" selected>정상</option>
<option value="partial">일부 줄 거부</option>
<option value="down">응답 없음 (3번 재시도)</option>
</select>
<select
aria-label="저장 방식"
:disabled="!api"
@change="api && actions.saveMode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="batch" selected>모아서 저장</option>
<option value="immediate">바로 저장</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: 280px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
// 저장 결과를 사람이 읽는 말로 바꿔요(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;
stock: number;
}
const rows: Row[] = [
{ id: 1, name: '바질', stock: 14 },
{ id: 2, name: '타임', stock: 9 },
{ id: 3, name: '파슬리', stock: 31 },
{ id: 4, name: '민트', stock: 5 },
];
// 시험용 가짜 서버예요. 동작을 바꿔 가며 저장해 보세요.
type Behavior = 'ok' | 'partial' | 'down';
const server: { mode: Behavior } = { mode: 'ok' };
let attempts = 0;
let say: (message: LogText) => void = () => {};
const wait = (ms: number, signal: AbortSignal) =>
new Promise<void>((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// 저장 처리기(saveHandler)가 돌려주는 값으로 결과를 알려요:
// - 아무것도 안 돌려주면 모두 저장됨.
// - { failed: [...] }를 돌려주면 그 줄만 실패한 "일부 실패"예요. 나머지는 저장돼요.
// - 예외를 던지면 요청 전체가 실패한 거고, 모든 변경이 그대로 남아서 다시 저장할 수 있어요.
const handler: SaveHandler<Row> = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: L('다른 사람이 이 재고를 잠그고 있어요', 'Someone else has locked this stock'),
},
],
};
}
if (server.mode === 'down') {
// 서버가 죽었을 때는 세 번까지 기다리는 시간을 늘려 가며 다시 시도하고, 그래도 안 되면 던져요.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say({
ko: ` 시도 ${attempts}: 서버가 응답하지 않아요`,
en: ` attempt ${attempts}: the server does not respond`,
});
await wait(n * 250, signal);
}
throw new Error('서버가 응답하지 않아요');
}
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '품목', width: 130, editable: true },
{ id: 'stock', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
attempts = 0;
log({
ko: '칸을 두세 개 고친 뒤 "서버 동작"을 바꿔 가며 "저장"을 눌러 보세요.',
en: 'Edit two or three cells, then press "Save" while changing the "Server behavior".',
});
const offs = [
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('saveFailed', ({ failed, error }) => {
if (failed.length)
log({
ko: `✗ 일부 실패: ${failed.map((f) => `${f.key}번 줄(${f.message})`).join(', ')} — 나머지는 저장됐어요`,
en: `✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`,
});
else
log({
ko: `✗ 요청이 통째로 실패했어요: ${error instanceof Error ? error.message : String(error)} — 변경은 그대로 남아 있어요`,
en: `✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`,
});
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
server: (_api: GridApi<Row>, value?: string) => {
server.mode = (value ?? 'ok') as Behavior;
attempts = 0;
},
// 저장 방식도 바꿔 볼 수 있어요. 'immediate'는 화면에 먼저 보이고(낙관적) 뒤에서 서버가 확인해요.
saveMode: (api: GridApi<Row>, value?: string) =>
api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api: GridApi<Row>) => {
attempts = 0;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
discard: (api: GridApi<Row>) => 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.server(api, $any($event.target).value)"
>
<option value="ok" selected>정상</option>
<option value="partial">일부 줄 거부</option>
<option value="down">응답 없음 (3번 재시도)</option>
</select>
<select
aria-label="저장 방식"
[disabled]="!api"
(change)="api && actions.saveMode(api, $any($event.target).value)"
>
<option value="batch" selected>모아서 저장</option>
<option value="immediate">바로 저장</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: 280px" [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';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
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;
stock: number;
}
const rows: Row[] = [
{ id: 1, name: '바질', stock: 14 },
{ id: 2, name: '타임', stock: 9 },
{ id: 3, name: '파슬리', stock: 31 },
{ id: 4, name: '민트', stock: 5 },
];
// 시험용 가짜 서버예요. 동작을 바꿔 가며 저장해 보세요.
type Behavior = 'ok' | 'partial' | 'down';
const server: { mode: Behavior } = { mode: 'ok' };
let attempts = 0;
let say: (message: LogText) => void = () => {};
const wait = (ms: number, signal: AbortSignal) =>
new Promise<void>((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// 저장 처리기(saveHandler)가 돌려주는 값으로 결과를 알려요:
// - 아무것도 안 돌려주면 모두 저장됨.
// - { failed: [...] }를 돌려주면 그 줄만 실패한 "일부 실패"예요. 나머지는 저장돼요.
// - 예외를 던지면 요청 전체가 실패한 거고, 모든 변경이 그대로 남아서 다시 저장할 수 있어요.
const handler: SaveHandler<Row> = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: L('다른 사람이 이 재고를 잠그고 있어요', 'Someone else has locked this stock'),
},
],
};
}
if (server.mode === 'down') {
// 서버가 죽었을 때는 세 번까지 기다리는 시간을 늘려 가며 다시 시도하고, 그래도 안 되면 던져요.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say({
ko: ` 시도 ${attempts}: 서버가 응답하지 않아요`,
en: ` attempt ${attempts}: the server does not respond`,
});
await wait(n * 250, signal);
}
throw new Error('서버가 응답하지 않아요');
}
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '품목', width: 130, editable: true },
{ id: 'stock', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
attempts = 0;
log({
ko: '칸을 두세 개 고친 뒤 "서버 동작"을 바꿔 가며 "저장"을 눌러 보세요.',
en: 'Edit two or three cells, then press "Save" while changing the "Server behavior".',
});
const offs = [
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('saveFailed', ({ failed, error }) => {
if (failed.length)
log({
ko: `✗ 일부 실패: ${failed.map((f) => `${f.key}번 줄(${f.message})`).join(', ')} — 나머지는 저장됐어요`,
en: `✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`,
});
else
log({
ko: `✗ 요청이 통째로 실패했어요: ${error instanceof Error ? error.message : String(error)} — 변경은 그대로 남아 있어요`,
en: `✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`,
});
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
server: (_api: GridApi<Row>, value?: string) => {
server.mode = (value ?? 'ok') as Behavior;
attempts = 0;
},
// 저장 방식도 바꿔 볼 수 있어요. 'immediate'는 화면에 먼저 보이고(낙관적) 뒤에서 서버가 확인해요.
saveMode: (api: GridApi<Row>, value?: string) =>
api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api: GridApi<Row>) => {
attempts = 0;
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
discard: (api: GridApi<Row>) => 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="Server" id="server">
<option value="ok" selected>Normal</option>
<option value="partial">Rejects some rows</option>
<option value="down">No answer (3 retries)</option>
</select>
<select aria-label="Save mode" id="saveMode">
<option value="batch" selected>Save together</option>
<option value="immediate">Save at once</option>
</select>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 280px"></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('server').addEventListener('change', (event) => actions.server(api, event.target.value));
document.getElementById('saveMode').addEventListener('change', (event) => actions.saveMode(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: 'Basil', stock: 14 },
{ id: 2, name: 'Thyme', stock: 9 },
{ id: 3, name: 'Parsley', stock: 31 },
{ id: 4, name: 'Mint', stock: 5 },
];
const server = { mode: 'ok' };
let attempts = 0;
let say = () => { };
const wait = (ms, signal) => new Promise((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// The saveHandler reports the result through its return value:
// - Returning nothing means everything was saved.
// - Returning { failed: [...] } is a "partial failure": only those rows failed and the rest are saved.
// - Throwing means the whole request failed; all changes stay and can be saved again.
const handler = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: 'Someone else has locked this stock',
},
],
};
}
if (server.mode === 'down') {
// When the server is down, retry up to three times with growing waits, then throw if it still fails.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say(` attempt ${attempts}: the server does not respond`);
await wait(n * 250, signal);
}
throw new Error('The server does not respond');
}
};
export const options = {
columns: [
{ id: 'name', title: 'Item', width: 130, editable: true },
{ id: 'stock', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
export function setup(api, log) {
say = log;
attempts = 0;
log('Edit two or three cells, then press "Save" while changing the "Server behavior".');
const offs = [
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed, error }) => {
if (failed.length)
log(`✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`);
else
log(`✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
server: (_api, value) => {
server.mode = (value ?? 'ok');
attempts = 0;
},
// The save mode can be switched too. 'immediate' shows the value on screen first (optimistic) and the server confirms afterwards.
saveMode: (api, value) => api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api) => {
attempts = 0;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
discard: (api) => api.rollbackChanges(),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Keep changes when saving fails</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Server" id="server">
<option value="ok" selected>Normal</option>
<option value="partial">Rejects some rows</option>
<option value="down">No answer (3 retries)</option>
</select>
<select aria-label="Save mode" id="saveMode">
<option value="batch" selected>Save together</option>
<option value="immediate">Save at once</option>
</select>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 280px"></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: 'Basil', stock: 14 },
{ id: 2, name: 'Thyme', stock: 9 },
{ id: 3, name: 'Parsley', stock: 31 },
{ id: 4, name: 'Mint', stock: 5 },
];
const server = { mode: 'ok' };
let attempts = 0;
let say = () => { };
const wait = (ms, signal) => new Promise((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// The saveHandler reports the result through its return value:
// - Returning nothing means everything was saved.
// - Returning { failed: [...] } is a "partial failure": only those rows failed and the rest are saved.
// - Throwing means the whole request failed; all changes stay and can be saved again.
const handler = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: 'Someone else has locked this stock',
},
],
};
}
if (server.mode === 'down') {
// When the server is down, retry up to three times with growing waits, then throw if it still fails.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say(` attempt ${attempts}: the server does not respond`);
await wait(n * 250, signal);
}
throw new Error('The server does not respond');
}
};
const options = {
columns: [
{ id: 'name', title: 'Item', width: 130, editable: true },
{ id: 'stock', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
function setup(api, log) {
say = log;
attempts = 0;
log('Edit two or three cells, then press "Save" while changing the "Server behavior".');
const offs = [
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed, error }) => {
if (failed.length)
log(`✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`);
else
log(`✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`);
}),
];
return () => offs.forEach((off) => off());
}
const actions = {
server: (_api, value) => {
server.mode = (value ?? 'ok');
attempts = 0;
},
// The save mode can be switched too. 'immediate' shows the value on screen first (optimistic) and the server confirms afterwards.
saveMode: (api, value) => api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api) => {
attempts = 0;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
discard: (api) => api.rollbackChanges(),
};
options.ariaLabel = "Keep changes when saving fails";
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('server').addEventListener('change', (event) => actions.server(api, event.target.value));
document.getElementById('saveMode').addEventListener('change', (event) => actions.saveMode(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="Server"
disabled={!api}
onChange={(event) => api && actions.server(api, event.target.value)}
>
<option value="ok">Normal</option>
<option value="partial">Rejects some rows</option>
<option value="down">No answer (3 retries)</option>
</select>
<select defaultValue="ok"
aria-label="Save mode"
disabled={!api}
onChange={(event) => api && actions.saveMode(api, event.target.value)}
>
<option value="batch">Save together</option>
<option value="immediate">Save at once</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: 280 }} 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;
stock: number;
}
const rows: Row[] = [
{ id: 1, name: 'Basil', stock: 14 },
{ id: 2, name: 'Thyme', stock: 9 },
{ id: 3, name: 'Parsley', stock: 31 },
{ id: 4, name: 'Mint', stock: 5 },
];
// A fake server for testing. Save while switching its behavior.
type Behavior = 'ok' | 'partial' | 'down';
const server: { mode: Behavior } = { mode: 'ok' };
let attempts = 0;
let say: (message: LogText) => void = () => {};
const wait = (ms: number, signal: AbortSignal) =>
new Promise<void>((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// The saveHandler reports the result through its return value:
// - Returning nothing means everything was saved.
// - Returning { failed: [...] } is a "partial failure": only those rows failed and the rest are saved.
// - Throwing means the whole request failed; all changes stay and can be saved again.
const handler: SaveHandler<Row> = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: 'Someone else has locked this stock',
},
],
};
}
if (server.mode === 'down') {
// When the server is down, retry up to three times with growing waits, then throw if it still fails.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say(` attempt ${attempts}: the server does not respond`);
await wait(n * 250, signal);
}
throw new Error('The server does not respond');
}
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Item', width: 130, editable: true },
{ id: 'stock', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
attempts = 0;
log('Edit two or three cells, then press "Save" while changing the "Server behavior".');
const offs = [
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed, error }) => {
if (failed.length)
log(
`✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`,
);
else
log(
`✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`,
);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
server: (_api: GridApi<Row>, value?: string) => {
server.mode = (value ?? 'ok') as Behavior;
attempts = 0;
},
// The save mode can be switched too. 'immediate' shows the value on screen first (optimistic) and the server confirms afterwards.
saveMode: (api: GridApi<Row>, value?: string) =>
api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api: GridApi<Row>) => {
attempts = 0;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
discard: (api: GridApi<Row>) => 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="Server"
:disabled="!api"
@change="api && actions.server(api, ($event.target as HTMLSelectElement).value)"
>
<option value="ok" selected>Normal</option>
<option value="partial">Rejects some rows</option>
<option value="down">No answer (3 retries)</option>
</select>
<select
aria-label="Save mode"
:disabled="!api"
@change="api && actions.saveMode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="batch" selected>Save together</option>
<option value="immediate">Save at once</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: 280px" :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;
stock: number;
}
const rows: Row[] = [
{ id: 1, name: 'Basil', stock: 14 },
{ id: 2, name: 'Thyme', stock: 9 },
{ id: 3, name: 'Parsley', stock: 31 },
{ id: 4, name: 'Mint', stock: 5 },
];
// A fake server for testing. Save while switching its behavior.
type Behavior = 'ok' | 'partial' | 'down';
const server: { mode: Behavior } = { mode: 'ok' };
let attempts = 0;
let say: (message: LogText) => void = () => {};
const wait = (ms: number, signal: AbortSignal) =>
new Promise<void>((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// The saveHandler reports the result through its return value:
// - Returning nothing means everything was saved.
// - Returning { failed: [...] } is a "partial failure": only those rows failed and the rest are saved.
// - Throwing means the whole request failed; all changes stay and can be saved again.
const handler: SaveHandler<Row> = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: 'Someone else has locked this stock',
},
],
};
}
if (server.mode === 'down') {
// When the server is down, retry up to three times with growing waits, then throw if it still fails.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say(` attempt ${attempts}: the server does not respond`);
await wait(n * 250, signal);
}
throw new Error('The server does not respond');
}
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Item', width: 130, editable: true },
{ id: 'stock', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
attempts = 0;
log('Edit two or three cells, then press "Save" while changing the "Server behavior".');
const offs = [
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed, error }) => {
if (failed.length)
log(
`✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`,
);
else
log(
`✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`,
);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
server: (_api: GridApi<Row>, value?: string) => {
server.mode = (value ?? 'ok') as Behavior;
attempts = 0;
},
// The save mode can be switched too. 'immediate' shows the value on screen first (optimistic) and the server confirms afterwards.
saveMode: (api: GridApi<Row>, value?: string) =>
api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api: GridApi<Row>) => {
attempts = 0;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
discard: (api: GridApi<Row>) => 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="Server"
[disabled]="!api"
(change)="api && actions.server(api, $any($event.target).value)"
>
<option value="ok" selected>Normal</option>
<option value="partial">Rejects some rows</option>
<option value="down">No answer (3 retries)</option>
</select>
<select
aria-label="Save mode"
[disabled]="!api"
(change)="api && actions.saveMode(api, $any($event.target).value)"
>
<option value="batch" selected>Save together</option>
<option value="immediate">Save at once</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: 280px" [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;
stock: number;
}
const rows: Row[] = [
{ id: 1, name: 'Basil', stock: 14 },
{ id: 2, name: 'Thyme', stock: 9 },
{ id: 3, name: 'Parsley', stock: 31 },
{ id: 4, name: 'Mint', stock: 5 },
];
// A fake server for testing. Save while switching its behavior.
type Behavior = 'ok' | 'partial' | 'down';
const server: { mode: Behavior } = { mode: 'ok' };
let attempts = 0;
let say: (message: LogText) => void = () => {};
const wait = (ms: number, signal: AbortSignal) =>
new Promise<void>((resolve) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
});
// The saveHandler reports the result through its return value:
// - Returning nothing means everything was saved.
// - Returning { failed: [...] } is a "partial failure": only those rows failed and the rest are saved.
// - Throwing means the whole request failed; all changes stay and can be saved again.
const handler: SaveHandler<Row> = async (changes, { signal }) => {
await wait(500, signal);
if (server.mode === 'partial') {
const first = changes[0];
if (first)
return {
failed: [
{
key: first.key,
message: 'Someone else has locked this stock',
},
],
};
}
if (server.mode === 'down') {
// When the server is down, retry up to three times with growing waits, then throw if it still fails.
for (let n = 1; n <= 3; n += 1) {
attempts += 1;
say(` attempt ${attempts}: the server does not respond`);
await wait(n * 250, signal);
}
throw new Error('The server does not respond');
}
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Item', width: 130, editable: true },
{ id: 'stock', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
attempts = 0;
log('Edit two or three cells, then press "Save" while changing the "Server behavior".');
const offs = [
api.on('saveStarted', ({ changes }) => log(`Sending ${changes.length} rows to the server…`)),
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed, error }) => {
if (failed.length)
log(
`✗ Some failed: ${failed.map((f) => `row ${f.key} (${f.message})`).join(', ')} — the rest were saved`,
);
else
log(
`✗ The whole request failed: ${error instanceof Error ? error.message : String(error)} — the changes are still there`,
);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
server: (_api: GridApi<Row>, value?: string) => {
server.mode = (value ?? 'ok') as Behavior;
attempts = 0;
},
// The save mode can be switched too. 'immediate' shows the value on screen first (optimistic) and the server confirms afterwards.
saveMode: (api: GridApi<Row>, value?: string) =>
api.setOptions({ saveMode: value === 'immediate' ? 'immediate' : 'batch' }),
save: async (api: GridApi<Row>) => {
attempts = 0;
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};