저장하려는데 누가 먼저 고쳤을 때When someone saved the same row first
서버가 줄마다 버전을 관리하면, 내가 저장하려는 줄이 그 사이 다른 사람에게 먼저 바뀌었을 때 서버가 거부해요. 거부된 줄은 변경으로 남아서 "내 수정을 최신 판 위에 다시 올리기"나 "서버 값 쓰기" 중에서 고를 수 있어요.If the server tracks a version per row, it rejects a save when someone changed that row first. The rejected row stays as a change and you can re-apply your edit on the latest version or take the server's value.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="otherEdits">다른 사람이 먼저 고침</button>
<button type="button" id="save">저장</button>
<button type="button" id="keepMine">내 수정 유지</button>
<button type="button" id="useTheirs">서버 값 쓰기</button>
</div>
<div id="grid" style="height: 240px"></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('otherEdits').addEventListener('click', () => actions.otherEdits(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('keepMine').addEventListener('click', () => actions.keepMine(api));
document.getElementById('useTheirs').addEventListener('click', () => actions.useTheirs(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}`;
};
// 가짜 서버는 줄마다 "버전"을 들고 있어요. 저장하려는 줄의 버전이 서버와 같을 때만 받아 주고, 받으면 버전을 1 올려서 돌려줘요.
// 버전이 다르면 "누가 먼저 고쳤다"는 뜻이라서 그 줄을 실패로 돌려줘요.
const server = new Map([
[1, { id: 1, name: '참나무 테이블', price: 320, version: 1 }],
[2, { id: 2, name: '소나무 선반', price: 90, version: 1 }],
[3, { id: 3, name: '자작나무 의자', price: 45, version: 1 }],
]);
const handler = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok = [];
const failed = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: L(`서버는 ${stored?.version ?? '?'}판인데 내 줄은 ${change.row.version}판이에요. 누군가 먼저 고쳤어요.`, `The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`),
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
export const options = {
columns: [
{ id: 'name', title: '상품', width: 150, editable: true },
{ id: 'price', title: '가격(만원)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: '판', kind: 'number', width: 70, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say = () => { };
export function setup(api, log) {
say = log;
log({
ko: '2번 줄 가격을 고치고, "다른 사람이 먼저 고침"을 누른 뒤 "저장"을 눌러 보세요.',
en: 'Edit the price of row 2, press "Someone else edited first", then press "Save".',
});
const offs = [
api.on('changesCommitted', ({ changes }) => log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` })),
api.on('saveFailed', ({ failed }) => log({
ko: `✗ ${failed.map((f) => `${f.key}번 줄: ${f.message}`).join(' / ')}`,
en: `✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`,
})),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// 다른 사람이 2번 줄을 먼저 고쳤다고 가정해요(서버의 가격과 판이 올라가요).
otherEdits: () => {
const stored = server.get(2);
if (!stored)
return;
server.set(2, { ...stored, price: stored.price + 5, version: stored.version + 1 });
say({
ko: `서버의 2번 줄이 바뀌었어요: 가격 ${stored.price + 5}, ${stored.version + 1}판`,
en: `Row 2 on the server changed: price ${stored.price + 5}, version ${stored.version + 1}`,
});
},
save: async (api) => {
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 출구 1) 내 수정 유지: 같은 수정을 서버의 최신 판 위에 다시 올려 저장해요.
keepMine: async (api) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length)
return say({ ko: '다시 올릴 수정이 없어요.', en: 'No edit to upload again.' });
api.updateRows(mine);
const report = await api.save();
say({
ko: `내 수정을 최신 판 위에 다시 올렸어요 — ${saveText(report)}`,
en: `Put my edit on top of the latest version — ${saveText(report, true)}`,
});
},
// 출구 2) 서버 것 쓰기: 내 수정을 버리고 서버의 줄로 바꾼 뒤 그것을 새 기준으로 삼아요.
useTheirs: (api) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length)
api.updateRows(theirs);
api.commitChanges();
say({
ko: '내 수정을 버리고 서버 값으로 바꿨어요.',
en: 'Discarded my edit and replaced it with the server value.',
});
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>저장하려는데 누가 먼저 고쳤을 때</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="otherEdits">다른 사람이 먼저 고침</button>
<button type="button" id="save">저장</button>
<button type="button" id="keepMine">내 수정 유지</button>
<button type="button" id="useTheirs">서버 값 쓰기</button>
</div>
<div id="grid" style="height: 240px"></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}`;
};
// 가짜 서버는 줄마다 "버전"을 들고 있어요. 저장하려는 줄의 버전이 서버와 같을 때만 받아 주고, 받으면 버전을 1 올려서 돌려줘요.
// 버전이 다르면 "누가 먼저 고쳤다"는 뜻이라서 그 줄을 실패로 돌려줘요.
const server = new Map([
[1, { id: 1, name: '참나무 테이블', price: 320, version: 1 }],
[2, { id: 2, name: '소나무 선반', price: 90, version: 1 }],
[3, { id: 3, name: '자작나무 의자', price: 45, version: 1 }],
]);
const handler = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok = [];
const failed = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: L(`서버는 ${stored?.version ?? '?'}판인데 내 줄은 ${change.row.version}판이에요. 누군가 먼저 고쳤어요.`, `The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`),
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
const options = {
columns: [
{ id: 'name', title: '상품', width: 150, editable: true },
{ id: 'price', title: '가격(만원)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: '판', kind: 'number', width: 70, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say = () => { };
function setup(api, log) {
say = log;
log({
ko: '2번 줄 가격을 고치고, "다른 사람이 먼저 고침"을 누른 뒤 "저장"을 눌러 보세요.',
en: 'Edit the price of row 2, press "Someone else edited first", then press "Save".',
});
const offs = [
api.on('changesCommitted', ({ changes }) => log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` })),
api.on('saveFailed', ({ failed }) => log({
ko: `✗ ${failed.map((f) => `${f.key}번 줄: ${f.message}`).join(' / ')}`,
en: `✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`,
})),
];
return () => offs.forEach((off) => off());
}
const actions = {
// 다른 사람이 2번 줄을 먼저 고쳤다고 가정해요(서버의 가격과 판이 올라가요).
otherEdits: () => {
const stored = server.get(2);
if (!stored)
return;
server.set(2, { ...stored, price: stored.price + 5, version: stored.version + 1 });
say({
ko: `서버의 2번 줄이 바뀌었어요: 가격 ${stored.price + 5}, ${stored.version + 1}판`,
en: `Row 2 on the server changed: price ${stored.price + 5}, version ${stored.version + 1}`,
});
},
save: async (api) => {
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 출구 1) 내 수정 유지: 같은 수정을 서버의 최신 판 위에 다시 올려 저장해요.
keepMine: async (api) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length)
return say({ ko: '다시 올릴 수정이 없어요.', en: 'No edit to upload again.' });
api.updateRows(mine);
const report = await api.save();
say({
ko: `내 수정을 최신 판 위에 다시 올렸어요 — ${saveText(report)}`,
en: `Put my edit on top of the latest version — ${saveText(report, true)}`,
});
},
// 출구 2) 서버 것 쓰기: 내 수정을 버리고 서버의 줄로 바꾼 뒤 그것을 새 기준으로 삼아요.
useTheirs: (api) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length)
api.updateRows(theirs);
api.commitChanges();
say({
ko: '내 수정을 버리고 서버 값으로 바꿨어요.',
en: 'Discarded my edit and replaced it with the server value.',
});
},
};
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('otherEdits').addEventListener('click', () => actions.otherEdits(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('keepMine').addEventListener('click', () => actions.keepMine(api));
document.getElementById('useTheirs').addEventListener('click', () => actions.useTheirs(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.otherEdits(api)}
>다른 사람이 먼저 고침</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>저장</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.keepMine(api)}
>내 수정 유지</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.useTheirs(api)}
>서버 값 쓰기</button>
</div>
<Grid style={{ height: 240 }} 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;
price: number;
version: number;
}
// 가짜 서버는 줄마다 "버전"을 들고 있어요. 저장하려는 줄의 버전이 서버와 같을 때만 받아 주고, 받으면 버전을 1 올려서 돌려줘요.
// 버전이 다르면 "누가 먼저 고쳤다"는 뜻이라서 그 줄을 실패로 돌려줘요.
const server = new Map<number, Row>([
[1, { id: 1, name: '참나무 테이블', price: 320, version: 1 }],
[2, { id: 2, name: '소나무 선반', price: 90, version: 1 }],
[3, { id: 3, name: '자작나무 의자', price: 45, version: 1 }],
]);
const handler: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok: { key: number; row: Row }[] = [];
const failed: { key: number; message: string }[] = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: L(
`서버는 ${stored?.version ?? '?'}판인데 내 줄은 ${change.row.version}판이에요. 누군가 먼저 고쳤어요.`,
`The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`,
),
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '상품', width: 150, editable: true },
{ id: 'price', title: '가격(만원)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: '판', kind: 'number', width: 70, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '2번 줄 가격을 고치고, "다른 사람이 먼저 고침"을 누른 뒤 "저장"을 눌러 보세요.',
en: 'Edit the price of row 2, press "Someone else edited first", then press "Save".',
});
const offs = [
api.on('changesCommitted', ({ changes }) =>
log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` }),
),
api.on('saveFailed', ({ failed }) =>
log({
ko: `✗ ${failed.map((f) => `${f.key}번 줄: ${f.message}`).join(' / ')}`,
en: `✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`,
}),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// 다른 사람이 2번 줄을 먼저 고쳤다고 가정해요(서버의 가격과 판이 올라가요).
otherEdits: () => {
const stored = server.get(2);
if (!stored) return;
server.set(2, { ...stored, price: stored.price + 5, version: stored.version + 1 });
say({
ko: `서버의 2번 줄이 바뀌었어요: 가격 ${stored.price + 5}, ${stored.version + 1}판`,
en: `Row 2 on the server changed: price ${stored.price + 5}, version ${stored.version + 1}`,
});
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 출구 1) 내 수정 유지: 같은 수정을 서버의 최신 판 위에 다시 올려 저장해요.
keepMine: async (api: GridApi<Row>) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length)
return say({ ko: '다시 올릴 수정이 없어요.', en: 'No edit to upload again.' });
api.updateRows(mine);
const report = await api.save();
say({
ko: `내 수정을 최신 판 위에 다시 올렸어요 — ${saveText(report)}`,
en: `Put my edit on top of the latest version — ${saveText(report, true)}`,
});
},
// 출구 2) 서버 것 쓰기: 내 수정을 버리고 서버의 줄로 바꾼 뒤 그것을 새 기준으로 삼아요.
useTheirs: (api: GridApi<Row>) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length) api.updateRows(theirs);
api.commitChanges();
say({
ko: '내 수정을 버리고 서버 값으로 바꿨어요.',
en: 'Discarded my edit and replaced it with the server value.',
});
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.otherEdits(api)"
>다른 사람이 먼저 고침</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">저장</button>
<button
type="button"
:disabled="!api"
@click="api && actions.keepMine(api)"
>내 수정 유지</button>
<button
type="button"
:disabled="!api"
@click="api && actions.useTheirs(api)"
>서버 값 쓰기</button>
</div>
<Grid style="height: 240px" :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;
price: number;
version: number;
}
// 가짜 서버는 줄마다 "버전"을 들고 있어요. 저장하려는 줄의 버전이 서버와 같을 때만 받아 주고, 받으면 버전을 1 올려서 돌려줘요.
// 버전이 다르면 "누가 먼저 고쳤다"는 뜻이라서 그 줄을 실패로 돌려줘요.
const server = new Map<number, Row>([
[1, { id: 1, name: '참나무 테이블', price: 320, version: 1 }],
[2, { id: 2, name: '소나무 선반', price: 90, version: 1 }],
[3, { id: 3, name: '자작나무 의자', price: 45, version: 1 }],
]);
const handler: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok: { key: number; row: Row }[] = [];
const failed: { key: number; message: string }[] = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: L(
`서버는 ${stored?.version ?? '?'}판인데 내 줄은 ${change.row.version}판이에요. 누군가 먼저 고쳤어요.`,
`The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`,
),
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '상품', width: 150, editable: true },
{ id: 'price', title: '가격(만원)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: '판', kind: 'number', width: 70, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '2번 줄 가격을 고치고, "다른 사람이 먼저 고침"을 누른 뒤 "저장"을 눌러 보세요.',
en: 'Edit the price of row 2, press "Someone else edited first", then press "Save".',
});
const offs = [
api.on('changesCommitted', ({ changes }) =>
log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` }),
),
api.on('saveFailed', ({ failed }) =>
log({
ko: `✗ ${failed.map((f) => `${f.key}번 줄: ${f.message}`).join(' / ')}`,
en: `✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`,
}),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// 다른 사람이 2번 줄을 먼저 고쳤다고 가정해요(서버의 가격과 판이 올라가요).
otherEdits: () => {
const stored = server.get(2);
if (!stored) return;
server.set(2, { ...stored, price: stored.price + 5, version: stored.version + 1 });
say({
ko: `서버의 2번 줄이 바뀌었어요: 가격 ${stored.price + 5}, ${stored.version + 1}판`,
en: `Row 2 on the server changed: price ${stored.price + 5}, version ${stored.version + 1}`,
});
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 출구 1) 내 수정 유지: 같은 수정을 서버의 최신 판 위에 다시 올려 저장해요.
keepMine: async (api: GridApi<Row>) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length)
return say({ ko: '다시 올릴 수정이 없어요.', en: 'No edit to upload again.' });
api.updateRows(mine);
const report = await api.save();
say({
ko: `내 수정을 최신 판 위에 다시 올렸어요 — ${saveText(report)}`,
en: `Put my edit on top of the latest version — ${saveText(report, true)}`,
});
},
// 출구 2) 서버 것 쓰기: 내 수정을 버리고 서버의 줄로 바꾼 뒤 그것을 새 기준으로 삼아요.
useTheirs: (api: GridApi<Row>) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length) api.updateRows(theirs);
api.commitChanges();
say({
ko: '내 수정을 버리고 서버 값으로 바꿨어요.',
en: 'Discarded my edit and replaced it with the server value.',
});
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.otherEdits(api)"
>다른 사람이 먼저 고침</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>저장</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.keepMine(api)"
>내 수정 유지</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.useTheirs(api)"
>서버 값 쓰기</button>
</div>
<mx-grid style="height: 240px" [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;
price: number;
version: number;
}
// 가짜 서버는 줄마다 "버전"을 들고 있어요. 저장하려는 줄의 버전이 서버와 같을 때만 받아 주고, 받으면 버전을 1 올려서 돌려줘요.
// 버전이 다르면 "누가 먼저 고쳤다"는 뜻이라서 그 줄을 실패로 돌려줘요.
const server = new Map<number, Row>([
[1, { id: 1, name: '참나무 테이블', price: 320, version: 1 }],
[2, { id: 2, name: '소나무 선반', price: 90, version: 1 }],
[3, { id: 3, name: '자작나무 의자', price: 45, version: 1 }],
]);
const handler: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok: { key: number; row: Row }[] = [];
const failed: { key: number; message: string }[] = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: L(
`서버는 ${stored?.version ?? '?'}판인데 내 줄은 ${change.row.version}판이에요. 누군가 먼저 고쳤어요.`,
`The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`,
),
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '상품', width: 150, editable: true },
{ id: 'price', title: '가격(만원)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: '판', kind: 'number', width: 70, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '2번 줄 가격을 고치고, "다른 사람이 먼저 고침"을 누른 뒤 "저장"을 눌러 보세요.',
en: 'Edit the price of row 2, press "Someone else edited first", then press "Save".',
});
const offs = [
api.on('changesCommitted', ({ changes }) =>
log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` }),
),
api.on('saveFailed', ({ failed }) =>
log({
ko: `✗ ${failed.map((f) => `${f.key}번 줄: ${f.message}`).join(' / ')}`,
en: `✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`,
}),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// 다른 사람이 2번 줄을 먼저 고쳤다고 가정해요(서버의 가격과 판이 올라가요).
otherEdits: () => {
const stored = server.get(2);
if (!stored) return;
server.set(2, { ...stored, price: stored.price + 5, version: stored.version + 1 });
say({
ko: `서버의 2번 줄이 바뀌었어요: 가격 ${stored.price + 5}, ${stored.version + 1}판`,
en: `Row 2 on the server changed: price ${stored.price + 5}, version ${stored.version + 1}`,
});
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
},
// 출구 1) 내 수정 유지: 같은 수정을 서버의 최신 판 위에 다시 올려 저장해요.
keepMine: async (api: GridApi<Row>) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length)
return say({ ko: '다시 올릴 수정이 없어요.', en: 'No edit to upload again.' });
api.updateRows(mine);
const report = await api.save();
say({
ko: `내 수정을 최신 판 위에 다시 올렸어요 — ${saveText(report)}`,
en: `Put my edit on top of the latest version — ${saveText(report, true)}`,
});
},
// 출구 2) 서버 것 쓰기: 내 수정을 버리고 서버의 줄로 바꾼 뒤 그것을 새 기준으로 삼아요.
useTheirs: (api: GridApi<Row>) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length) api.updateRows(theirs);
api.commitChanges();
say({
ko: '내 수정을 버리고 서버 값으로 바꿨어요.',
en: 'Discarded my edit and replaced it with the server value.',
});
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="otherEdits">Someone else edited first</button>
<button type="button" id="save">Save</button>
<button type="button" id="keepMine">Keep my edit</button>
<button type="button" id="useTheirs">Use server value</button>
</div>
<div id="grid" style="height: 240px"></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('otherEdits').addEventListener('click', () => actions.otherEdits(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('keepMine').addEventListener('click', () => actions.keepMine(api));
document.getElementById('useTheirs').addEventListener('click', () => actions.useTheirs(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}`;
};
// The fake server keeps a "version" per row. It accepts a row only when its version matches the server's, and returns it with the version raised by 1.
// A different version means "someone edited it first", so that row is returned as failed.
const server = new Map([
[1, { id: 1, name: 'Oak table', price: 3200, version: 1 }],
[2, { id: 2, name: 'Pine shelf', price: 900, version: 1 }],
[3, { id: 3, name: 'Birch chair', price: 450, version: 1 }],
]);
const handler = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok = [];
const failed = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: `The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`,
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
export const options = {
columns: [
{ id: 'name', title: 'Product', width: 150, editable: true },
{ id: 'price', title: 'Price ($)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: 'Version', kind: 'number', width: 90, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say = () => { };
export function setup(api, log) {
say = log;
log('Edit the price of row 2, press "Someone else edited first", then press "Save".');
const offs = [
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed }) => log(`✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// Pretend someone else edited row 2 first (the server's price and version go up).
otherEdits: () => {
const stored = server.get(2);
if (!stored)
return;
server.set(2, { ...stored, price: stored.price + 50, version: stored.version + 1 });
say(`Row 2 on the server changed: price ${stored.price + 50}, version ${stored.version + 1}`);
},
save: async (api) => {
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// Way out 1) Keep mine: put the same edit on top of the server's latest version and save.
keepMine: async (api) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length)
return say('No edit to upload again.');
api.updateRows(mine);
const report = await api.save();
say(`Put my edit on top of the latest version — ${saveText(report)}`);
},
// Way out 2) Use the server's: discard my edit, switch to the server's row and take that as the new baseline.
useTheirs: (api) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length)
api.updateRows(theirs);
api.commitChanges();
say('Discarded my edit and replaced it with the server value.');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>When someone saved the same row first</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="otherEdits">Someone else edited first</button>
<button type="button" id="save">Save</button>
<button type="button" id="keepMine">Keep my edit</button>
<button type="button" id="useTheirs">Use server value</button>
</div>
<div id="grid" style="height: 240px"></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}`;
};
// The fake server keeps a "version" per row. It accepts a row only when its version matches the server's, and returns it with the version raised by 1.
// A different version means "someone edited it first", so that row is returned as failed.
const server = new Map([
[1, { id: 1, name: 'Oak table', price: 3200, version: 1 }],
[2, { id: 2, name: 'Pine shelf', price: 900, version: 1 }],
[3, { id: 3, name: 'Birch chair', price: 450, version: 1 }],
]);
const handler = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok = [];
const failed = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: `The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`,
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
const options = {
columns: [
{ id: 'name', title: 'Product', width: 150, editable: true },
{ id: 'price', title: 'Price ($)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: 'Version', kind: 'number', width: 90, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say = () => { };
function setup(api, log) {
say = log;
log('Edit the price of row 2, press "Someone else edited first", then press "Save".');
const offs = [
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed }) => log(`✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`)),
];
return () => offs.forEach((off) => off());
}
const actions = {
// Pretend someone else edited row 2 first (the server's price and version go up).
otherEdits: () => {
const stored = server.get(2);
if (!stored)
return;
server.set(2, { ...stored, price: stored.price + 50, version: stored.version + 1 });
say(`Row 2 on the server changed: price ${stored.price + 50}, version ${stored.version + 1}`);
},
save: async (api) => {
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// Way out 1) Keep mine: put the same edit on top of the server's latest version and save.
keepMine: async (api) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length)
return say('No edit to upload again.');
api.updateRows(mine);
const report = await api.save();
say(`Put my edit on top of the latest version — ${saveText(report)}`);
},
// Way out 2) Use the server's: discard my edit, switch to the server's row and take that as the new baseline.
useTheirs: (api) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length)
api.updateRows(theirs);
api.commitChanges();
say('Discarded my edit and replaced it with the server value.');
},
};
options.ariaLabel = "When someone saved the same row first";
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('otherEdits').addEventListener('click', () => actions.otherEdits(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('keepMine').addEventListener('click', () => actions.keepMine(api));
document.getElementById('useTheirs').addEventListener('click', () => actions.useTheirs(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.otherEdits(api)}
>Someone else edited first</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>Save</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.keepMine(api)}
>Keep my edit</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.useTheirs(api)}
>Use server value</button>
</div>
<Grid style={{ height: 240 }} 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;
price: number;
version: number;
}
// The fake server keeps a "version" per row. It accepts a row only when its version matches the server's, and returns it with the version raised by 1.
// A different version means "someone edited it first", so that row is returned as failed.
const server = new Map<number, Row>([
[1, { id: 1, name: 'Oak table', price: 3200, version: 1 }],
[2, { id: 2, name: 'Pine shelf', price: 900, version: 1 }],
[3, { id: 3, name: 'Birch chair', price: 450, version: 1 }],
]);
const handler: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok: { key: number; row: Row }[] = [];
const failed: { key: number; message: string }[] = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: `The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`,
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Product', width: 150, editable: true },
{ id: 'price', title: 'Price ($)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: 'Version', kind: 'number', width: 90, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Edit the price of row 2, press "Someone else edited first", then press "Save".');
const offs = [
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed }) =>
log(`✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// Pretend someone else edited row 2 first (the server's price and version go up).
otherEdits: () => {
const stored = server.get(2);
if (!stored) return;
server.set(2, { ...stored, price: stored.price + 50, version: stored.version + 1 });
say(`Row 2 on the server changed: price ${stored.price + 50}, version ${stored.version + 1}`);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// Way out 1) Keep mine: put the same edit on top of the server's latest version and save.
keepMine: async (api: GridApi<Row>) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length) return say('No edit to upload again.');
api.updateRows(mine);
const report = await api.save();
say(`Put my edit on top of the latest version — ${saveText(report)}`);
},
// Way out 2) Use the server's: discard my edit, switch to the server's row and take that as the new baseline.
useTheirs: (api: GridApi<Row>) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length) api.updateRows(theirs);
api.commitChanges();
say('Discarded my edit and replaced it with the server value.');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.otherEdits(api)"
>Someone else edited first</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">Save</button>
<button
type="button"
:disabled="!api"
@click="api && actions.keepMine(api)"
>Keep my edit</button>
<button
type="button"
:disabled="!api"
@click="api && actions.useTheirs(api)"
>Use server value</button>
</div>
<Grid style="height: 240px" :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;
price: number;
version: number;
}
// The fake server keeps a "version" per row. It accepts a row only when its version matches the server's, and returns it with the version raised by 1.
// A different version means "someone edited it first", so that row is returned as failed.
const server = new Map<number, Row>([
[1, { id: 1, name: 'Oak table', price: 3200, version: 1 }],
[2, { id: 2, name: 'Pine shelf', price: 900, version: 1 }],
[3, { id: 3, name: 'Birch chair', price: 450, version: 1 }],
]);
const handler: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok: { key: number; row: Row }[] = [];
const failed: { key: number; message: string }[] = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: `The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`,
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Product', width: 150, editable: true },
{ id: 'price', title: 'Price ($)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: 'Version', kind: 'number', width: 90, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Edit the price of row 2, press "Someone else edited first", then press "Save".');
const offs = [
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed }) =>
log(`✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// Pretend someone else edited row 2 first (the server's price and version go up).
otherEdits: () => {
const stored = server.get(2);
if (!stored) return;
server.set(2, { ...stored, price: stored.price + 50, version: stored.version + 1 });
say(`Row 2 on the server changed: price ${stored.price + 50}, version ${stored.version + 1}`);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// Way out 1) Keep mine: put the same edit on top of the server's latest version and save.
keepMine: async (api: GridApi<Row>) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length) return say('No edit to upload again.');
api.updateRows(mine);
const report = await api.save();
say(`Put my edit on top of the latest version — ${saveText(report)}`);
},
// Way out 2) Use the server's: discard my edit, switch to the server's row and take that as the new baseline.
useTheirs: (api: GridApi<Row>) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length) api.updateRows(theirs);
api.commitChanges();
say('Discarded my edit and replaced it with the server value.');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.otherEdits(api)"
>Someone else edited first</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>Save</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.keepMine(api)"
>Keep my edit</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.useTheirs(api)"
>Use server value</button>
</div>
<mx-grid style="height: 240px" [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;
price: number;
version: number;
}
// The fake server keeps a "version" per row. It accepts a row only when its version matches the server's, and returns it with the version raised by 1.
// A different version means "someone edited it first", so that row is returned as failed.
const server = new Map<number, Row>([
[1, { id: 1, name: 'Oak table', price: 3200, version: 1 }],
[2, { id: 2, name: 'Pine shelf', price: 900, version: 1 }],
[3, { id: 3, name: 'Birch chair', price: 450, version: 1 }],
]);
const handler: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 250));
const ok: { key: number; row: Row }[] = [];
const failed: { key: number; message: string }[] = [];
for (const change of changes) {
const id = Number(change.key);
const stored = server.get(id);
if (!stored || stored.version !== change.row.version) {
failed.push({
key: id,
message: `The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`,
});
continue;
}
const next = { ...change.row, version: stored.version + 1 };
server.set(id, next);
ok.push({ key: id, row: next });
}
return { ok, failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Product', width: 150, editable: true },
{ id: 'price', title: 'Price ($)', kind: 'number', width: 110, align: 'end', editable: true },
{ id: 'version', title: 'Version', kind: 'number', width: 90, align: 'end' },
],
rows: [...server.values()].map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'batch',
saveHandler: handler,
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Edit the price of row 2, press "Someone else edited first", then press "Save".');
const offs = [
api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
api.on('saveFailed', ({ failed }) =>
log(`✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// Pretend someone else edited row 2 first (the server's price and version go up).
otherEdits: () => {
const stored = server.get(2);
if (!stored) return;
server.set(2, { ...stored, price: stored.price + 50, version: stored.version + 1 });
say(`Row 2 on the server changed: price ${stored.price + 50}, version ${stored.version + 1}`);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(`Save result: ${saveText(report)}`);
},
// Way out 1) Keep mine: put the same edit on top of the server's latest version and save.
keepMine: async (api: GridApi<Row>) => {
const mine = api
.getChanges()
.filter((c) => c.state === 'modified')
.map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
if (!mine.length) return say('No edit to upload again.');
api.updateRows(mine);
const report = await api.save();
say(`Put my edit on top of the latest version — ${saveText(report)}`);
},
// Way out 2) Use the server's: discard my edit, switch to the server's row and take that as the new baseline.
useTheirs: (api: GridApi<Row>) => {
const keys = api.getChanges().map((c) => Number(c.key));
api.rollbackChanges();
const theirs = keys.flatMap((key) => {
const row = server.get(key);
return row ? [{ ...row }] : [];
});
if (theirs.length) api.updateRows(theirs);
api.commitChanges();
say('Discarded my edit and replaced it with the server value.');
},
};