서버가 보낸 새 값과 내 수정 합치기Merge fresh server rows with your edits
다른 사람이 서버에서 값을 바꿨을 때, 서버가 보내 준 새 데이터를 표에 합칠 수 있어요. 내가 아직 저장하지 않은 수정과 부딪치면 서버 값을 따를지, 내 수정을 지킬지, 지키면서 어느 칸이 부딪쳤는지 알려 받을지 정할 수 있어요.When someone changes data on the server, merge the fresh rows into the grid. If it clashes with your unsaved edit, choose to follow the server, keep your edit, or keep it and be told which cells clashed.
코드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="policy">
<option value="server" selected>서버 값 우선</option>
<option value="mine">내 수정 우선</option>
<option value="notify">내 수정 우선 + 충돌 알림</option>
</select>
<button type="button" id="myEdit">내 수정 만들기</button>
<button type="button" id="serverUpdate">서버가 새 값 보냄</button>
<button type="button" id="acceptTheirs">충돌 칸 서버 값으로</button>
<button type="button" id="discard">변경 버리기</button>
<button type="button" id="reset">처음 상태로</button>
</div>
<div id="grid" style="height: 190px"></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('policy').addEventListener('change', (event) => actions.policy(api, event.target.value));
document.getElementById('myEdit').addEventListener('click', () => actions.myEdit(api));
document.getElementById('serverUpdate').addEventListener('click', () => actions.serverUpdate(api));
document.getElementById('acceptTheirs').addEventListener('click', () => actions.acceptTheirs(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));const rows = [
{ id: 1, name: '한빛상사', status: '신규' },
{ id: 2, name: '푸른식품', status: '신규' },
];
let policy = 'server';
let pending = [];
let say = () => { };
export const options = {
columns: [
{ id: 'name', title: '거래처', width: 180, editable: true },
{ id: 'status', title: '상태', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
export function setup(api, log) {
say = log;
log({
ko: '먼저 "내 수정 만들기"를 누르고, 이어서 "서버가 새 값 보냄"을 눌러 정책에 따라 어떻게 합쳐지는지 보세요.',
en: 'Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.',
});
const offs = [
api.on('changesCountChanged', ({ count }) => log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` })),
// 'notify'에서는 내 값을 지키되, 서로 다른 칸을 이 이벤트로 알려 줘요.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log({
ko: `⚠ ${e.rowKey}번 줄 ${title}: 내 값 "${String(cell.mine)}", 서버 값 "${String(cell.theirs)}"`,
en: `⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`,
});
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName = {
server: '서버 값 우선',
mine: '내 수정 우선',
notify: '내 수정 우선 + 충돌 알림',
};
const policyNameEn = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
export const actions = {
policy: (_api, value) => {
policy = (value ?? 'server');
},
// 아직 저장하지 않은 내 수정을 하나 만들어요.
myEdit: (api) => {
const row = api.getRowByKey(1);
if (row)
api.updateRows([{ ...row, name: '한빛상사 (내가 고침)' }]);
},
// 서버가 새 데이터를 보내 줘서 합쳐요. mergeRows는 키가 같은 줄은 갱신하고, 없는 줄은 추가해요.
// 내가 고친 칸과 서버 값이 부딪칠 때 어떻게 할지를 conflict 정책이 정해요.
serverUpdate: (api) => {
pending = [];
const incoming = [
{ id: 1, name: '한빛상사㈜', status: '거래중' },
{ id: 2, name: '푸른식품', status: '보류' },
{ id: 3, name: '새봄약품', status: '신규' },
];
// 서버가 보낸 값이 지금 표와 같으면 합칠 것이 없어요(같은 값을 또 보내도 "갱신"이라고 세지 않아요).
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say({
ko: '바뀐 값이 없어요. 서버가 보낸 값이 지금 표와 같아요.',
en: 'No value changed. The values the server sent are the same as the table now.',
});
const report = api.mergeRows(incoming, { conflict: policy });
say({
ko: `합친 결과(${policyName[policy]}): 새 줄 ${report.added}, 갱신 ${report.updated}, 서버 값이 덮은 줄 ${report.overwritten}, 내 수정을 지킨 줄 ${report.kept}`,
en: `Merge result (${policyNameEn[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`,
});
},
// 'notify'로 알림 받은 충돌 칸을 서버 값으로 바꿔요.
acceptTheirs: (api) => {
if (!pending.length)
return say({
ko: '받아들일 충돌이 없어요. 정책을 "내 수정 우선 + 충돌 알림"으로 두고 합쳐 보세요.',
en: 'No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.',
});
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row)
api.updateRows([{ ...row, [columnId]: theirs }]);
}
say({
ko: `${pending.length}칸을 서버 값으로 바꿨어요.`,
en: `Replaced ${pending.length} cells with the server values.`,
});
pending = [];
},
discard: (api) => api.rollbackChanges(),
// 처음 상태로: 처음 줄 두 개만 남기고 저장 안 한 변경·충돌 목록을 모두 지워요.
reset: (api) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say({ ko: '처음 상태로 되돌렸어요.', en: 'Back to the starting state.' });
},
};<!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="policy">
<option value="server" selected>서버 값 우선</option>
<option value="mine">내 수정 우선</option>
<option value="notify">내 수정 우선 + 충돌 알림</option>
</select>
<button type="button" id="myEdit">내 수정 만들기</button>
<button type="button" id="serverUpdate">서버가 새 값 보냄</button>
<button type="button" id="acceptTheirs">충돌 칸 서버 값으로</button>
<button type="button" id="discard">변경 버리기</button>
<button type="button" id="reset">처음 상태로</button>
</div>
<div id="grid" style="height: 190px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, name: '한빛상사', status: '신규' },
{ id: 2, name: '푸른식품', status: '신규' },
];
let policy = 'server';
let pending = [];
let say = () => { };
const options = {
columns: [
{ id: 'name', title: '거래처', width: 180, editable: true },
{ id: 'status', title: '상태', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
function setup(api, log) {
say = log;
log({
ko: '먼저 "내 수정 만들기"를 누르고, 이어서 "서버가 새 값 보냄"을 눌러 정책에 따라 어떻게 합쳐지는지 보세요.',
en: 'Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.',
});
const offs = [
api.on('changesCountChanged', ({ count }) => log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` })),
// 'notify'에서는 내 값을 지키되, 서로 다른 칸을 이 이벤트로 알려 줘요.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log({
ko: `⚠ ${e.rowKey}번 줄 ${title}: 내 값 "${String(cell.mine)}", 서버 값 "${String(cell.theirs)}"`,
en: `⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`,
});
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName = {
server: '서버 값 우선',
mine: '내 수정 우선',
notify: '내 수정 우선 + 충돌 알림',
};
const policyNameEn = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
const actions = {
policy: (_api, value) => {
policy = (value ?? 'server');
},
// 아직 저장하지 않은 내 수정을 하나 만들어요.
myEdit: (api) => {
const row = api.getRowByKey(1);
if (row)
api.updateRows([{ ...row, name: '한빛상사 (내가 고침)' }]);
},
// 서버가 새 데이터를 보내 줘서 합쳐요. mergeRows는 키가 같은 줄은 갱신하고, 없는 줄은 추가해요.
// 내가 고친 칸과 서버 값이 부딪칠 때 어떻게 할지를 conflict 정책이 정해요.
serverUpdate: (api) => {
pending = [];
const incoming = [
{ id: 1, name: '한빛상사㈜', status: '거래중' },
{ id: 2, name: '푸른식품', status: '보류' },
{ id: 3, name: '새봄약품', status: '신규' },
];
// 서버가 보낸 값이 지금 표와 같으면 합칠 것이 없어요(같은 값을 또 보내도 "갱신"이라고 세지 않아요).
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say({
ko: '바뀐 값이 없어요. 서버가 보낸 값이 지금 표와 같아요.',
en: 'No value changed. The values the server sent are the same as the table now.',
});
const report = api.mergeRows(incoming, { conflict: policy });
say({
ko: `합친 결과(${policyName[policy]}): 새 줄 ${report.added}, 갱신 ${report.updated}, 서버 값이 덮은 줄 ${report.overwritten}, 내 수정을 지킨 줄 ${report.kept}`,
en: `Merge result (${policyNameEn[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`,
});
},
// 'notify'로 알림 받은 충돌 칸을 서버 값으로 바꿔요.
acceptTheirs: (api) => {
if (!pending.length)
return say({
ko: '받아들일 충돌이 없어요. 정책을 "내 수정 우선 + 충돌 알림"으로 두고 합쳐 보세요.',
en: 'No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.',
});
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row)
api.updateRows([{ ...row, [columnId]: theirs }]);
}
say({
ko: `${pending.length}칸을 서버 값으로 바꿨어요.`,
en: `Replaced ${pending.length} cells with the server values.`,
});
pending = [];
},
discard: (api) => api.rollbackChanges(),
// 처음 상태로: 처음 줄 두 개만 남기고 저장 안 한 변경·충돌 목록을 모두 지워요.
reset: (api) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say({ ko: '처음 상태로 되돌렸어요.', en: 'Back to the starting state.' });
},
};
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('policy').addEventListener('change', (event) => actions.policy(api, event.target.value));
document.getElementById('myEdit').addEventListener('click', () => actions.myEdit(api));
document.getElementById('serverUpdate').addEventListener('click', () => actions.serverUpdate(api));
document.getElementById('acceptTheirs').addEventListener('click', () => actions.acceptTheirs(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(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.policy(api, event.target.value)}
>
<option value="server">서버 값 우선</option>
<option value="mine">내 수정 우선</option>
<option value="notify">내 수정 우선 + 충돌 알림</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.myEdit(api)}
>내 수정 만들기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.serverUpdate(api)}
>서버가 새 값 보냄</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.acceptTheirs(api)}
>충돌 칸 서버 값으로</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>변경 버리기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reset(api)}
>처음 상태로</button>
</div>
<Grid style={{ height: 190 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
status: string;
}
const rows: Row[] = [
{ id: 1, name: '한빛상사', status: '신규' },
{ id: 2, name: '푸른식품', status: '신규' },
];
type Policy = 'server' | 'mine' | 'notify';
let policy: Policy = 'server';
let pending: { rowKey: number; columnId: string; theirs: unknown }[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '거래처', width: 180, editable: true },
{ id: 'status', title: '상태', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '먼저 "내 수정 만들기"를 누르고, 이어서 "서버가 새 값 보냄"을 눌러 정책에 따라 어떻게 합쳐지는지 보세요.',
en: 'Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.',
});
const offs = [
api.on('changesCountChanged', ({ count }) =>
log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` }),
),
// 'notify'에서는 내 값을 지키되, 서로 다른 칸을 이 이벤트로 알려 줘요.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey as number, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log({
ko: `⚠ ${e.rowKey}번 줄 ${title}: 내 값 "${String(cell.mine)}", 서버 값 "${String(cell.theirs)}"`,
en: `⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`,
});
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName: Record<Policy, string> = {
server: '서버 값 우선',
mine: '내 수정 우선',
notify: '내 수정 우선 + 충돌 알림',
};
const policyNameEn: Record<Policy, string> = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
export const actions = {
policy: (_api: GridApi<Row>, value?: string) => {
policy = (value ?? 'server') as Policy;
},
// 아직 저장하지 않은 내 수정을 하나 만들어요.
myEdit: (api: GridApi<Row>) => {
const row = api.getRowByKey(1);
if (row) api.updateRows([{ ...row, name: '한빛상사 (내가 고침)' }]);
},
// 서버가 새 데이터를 보내 줘서 합쳐요. mergeRows는 키가 같은 줄은 갱신하고, 없는 줄은 추가해요.
// 내가 고친 칸과 서버 값이 부딪칠 때 어떻게 할지를 conflict 정책이 정해요.
serverUpdate: (api: GridApi<Row>) => {
pending = [];
const incoming: Row[] = [
{ id: 1, name: '한빛상사㈜', status: '거래중' },
{ id: 2, name: '푸른식품', status: '보류' },
{ id: 3, name: '새봄약품', status: '신규' },
];
// 서버가 보낸 값이 지금 표와 같으면 합칠 것이 없어요(같은 값을 또 보내도 "갱신"이라고 세지 않아요).
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say({
ko: '바뀐 값이 없어요. 서버가 보낸 값이 지금 표와 같아요.',
en: 'No value changed. The values the server sent are the same as the table now.',
});
const report = api.mergeRows(incoming, { conflict: policy });
say({
ko: `합친 결과(${policyName[policy]}): 새 줄 ${report.added}, 갱신 ${report.updated}, 서버 값이 덮은 줄 ${report.overwritten}, 내 수정을 지킨 줄 ${report.kept}`,
en: `Merge result (${policyNameEn[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`,
});
},
// 'notify'로 알림 받은 충돌 칸을 서버 값으로 바꿔요.
acceptTheirs: (api: GridApi<Row>) => {
if (!pending.length)
return say({
ko: '받아들일 충돌이 없어요. 정책을 "내 수정 우선 + 충돌 알림"으로 두고 합쳐 보세요.',
en: 'No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.',
});
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row) api.updateRows([{ ...row, [columnId]: theirs }]);
}
say({
ko: `${pending.length}칸을 서버 값으로 바꿨어요.`,
en: `Replaced ${pending.length} cells with the server values.`,
});
pending = [];
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
// 처음 상태로: 처음 줄 두 개만 남기고 저장 안 한 변경·충돌 목록을 모두 지워요.
reset: (api: GridApi<Row>) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say({ ko: '처음 상태로 되돌렸어요.', en: 'Back to the starting state.' });
},
};버튼을 누르면 이 예제의 코드가 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.policy(api, ($event.target as HTMLSelectElement).value)"
>
<option value="server" selected>서버 값 우선</option>
<option value="mine">내 수정 우선</option>
<option value="notify">내 수정 우선 + 충돌 알림</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.myEdit(api)">내 수정 만들기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.serverUpdate(api)"
>서버가 새 값 보냄</button>
<button
type="button"
:disabled="!api"
@click="api && actions.acceptTheirs(api)"
>충돌 칸 서버 값으로</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">변경 버리기</button>
<button type="button" :disabled="!api" @click="api && actions.reset(api)">처음 상태로</button>
</div>
<Grid style="height: 190px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
status: string;
}
const rows: Row[] = [
{ id: 1, name: '한빛상사', status: '신규' },
{ id: 2, name: '푸른식품', status: '신규' },
];
type Policy = 'server' | 'mine' | 'notify';
let policy: Policy = 'server';
let pending: { rowKey: number; columnId: string; theirs: unknown }[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '거래처', width: 180, editable: true },
{ id: 'status', title: '상태', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '먼저 "내 수정 만들기"를 누르고, 이어서 "서버가 새 값 보냄"을 눌러 정책에 따라 어떻게 합쳐지는지 보세요.',
en: 'Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.',
});
const offs = [
api.on('changesCountChanged', ({ count }) =>
log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` }),
),
// 'notify'에서는 내 값을 지키되, 서로 다른 칸을 이 이벤트로 알려 줘요.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey as number, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log({
ko: `⚠ ${e.rowKey}번 줄 ${title}: 내 값 "${String(cell.mine)}", 서버 값 "${String(cell.theirs)}"`,
en: `⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`,
});
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName: Record<Policy, string> = {
server: '서버 값 우선',
mine: '내 수정 우선',
notify: '내 수정 우선 + 충돌 알림',
};
const policyNameEn: Record<Policy, string> = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
export const actions = {
policy: (_api: GridApi<Row>, value?: string) => {
policy = (value ?? 'server') as Policy;
},
// 아직 저장하지 않은 내 수정을 하나 만들어요.
myEdit: (api: GridApi<Row>) => {
const row = api.getRowByKey(1);
if (row) api.updateRows([{ ...row, name: '한빛상사 (내가 고침)' }]);
},
// 서버가 새 데이터를 보내 줘서 합쳐요. mergeRows는 키가 같은 줄은 갱신하고, 없는 줄은 추가해요.
// 내가 고친 칸과 서버 값이 부딪칠 때 어떻게 할지를 conflict 정책이 정해요.
serverUpdate: (api: GridApi<Row>) => {
pending = [];
const incoming: Row[] = [
{ id: 1, name: '한빛상사㈜', status: '거래중' },
{ id: 2, name: '푸른식품', status: '보류' },
{ id: 3, name: '새봄약품', status: '신규' },
];
// 서버가 보낸 값이 지금 표와 같으면 합칠 것이 없어요(같은 값을 또 보내도 "갱신"이라고 세지 않아요).
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say({
ko: '바뀐 값이 없어요. 서버가 보낸 값이 지금 표와 같아요.',
en: 'No value changed. The values the server sent are the same as the table now.',
});
const report = api.mergeRows(incoming, { conflict: policy });
say({
ko: `합친 결과(${policyName[policy]}): 새 줄 ${report.added}, 갱신 ${report.updated}, 서버 값이 덮은 줄 ${report.overwritten}, 내 수정을 지킨 줄 ${report.kept}`,
en: `Merge result (${policyNameEn[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`,
});
},
// 'notify'로 알림 받은 충돌 칸을 서버 값으로 바꿔요.
acceptTheirs: (api: GridApi<Row>) => {
if (!pending.length)
return say({
ko: '받아들일 충돌이 없어요. 정책을 "내 수정 우선 + 충돌 알림"으로 두고 합쳐 보세요.',
en: 'No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.',
});
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row) api.updateRows([{ ...row, [columnId]: theirs }]);
}
say({
ko: `${pending.length}칸을 서버 값으로 바꿨어요.`,
en: `Replaced ${pending.length} cells with the server values.`,
});
pending = [];
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
// 처음 상태로: 처음 줄 두 개만 남기고 저장 안 한 변경·충돌 목록을 모두 지워요.
reset: (api: GridApi<Row>) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say({ ko: '처음 상태로 되돌렸어요.', en: 'Back to the starting state.' });
},
};버튼을 누르면 이 예제의 코드가 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.policy(api, $any($event.target).value)"
>
<option value="server" selected>서버 값 우선</option>
<option value="mine">내 수정 우선</option>
<option value="notify">내 수정 우선 + 충돌 알림</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.myEdit(api)"
>내 수정 만들기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.serverUpdate(api)"
>서버가 새 값 보냄</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.acceptTheirs(api)"
>충돌 칸 서버 값으로</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>변경 버리기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reset(api)"
>처음 상태로</button>
</div>
<mx-grid style="height: 190px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
status: string;
}
const rows: Row[] = [
{ id: 1, name: '한빛상사', status: '신규' },
{ id: 2, name: '푸른식품', status: '신규' },
];
type Policy = 'server' | 'mine' | 'notify';
let policy: Policy = 'server';
let pending: { rowKey: number; columnId: string; theirs: unknown }[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '거래처', width: 180, editable: true },
{ id: 'status', title: '상태', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '먼저 "내 수정 만들기"를 누르고, 이어서 "서버가 새 값 보냄"을 눌러 정책에 따라 어떻게 합쳐지는지 보세요.',
en: 'Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.',
});
const offs = [
api.on('changesCountChanged', ({ count }) =>
log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` }),
),
// 'notify'에서는 내 값을 지키되, 서로 다른 칸을 이 이벤트로 알려 줘요.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey as number, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log({
ko: `⚠ ${e.rowKey}번 줄 ${title}: 내 값 "${String(cell.mine)}", 서버 값 "${String(cell.theirs)}"`,
en: `⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`,
});
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName: Record<Policy, string> = {
server: '서버 값 우선',
mine: '내 수정 우선',
notify: '내 수정 우선 + 충돌 알림',
};
const policyNameEn: Record<Policy, string> = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
export const actions = {
policy: (_api: GridApi<Row>, value?: string) => {
policy = (value ?? 'server') as Policy;
},
// 아직 저장하지 않은 내 수정을 하나 만들어요.
myEdit: (api: GridApi<Row>) => {
const row = api.getRowByKey(1);
if (row) api.updateRows([{ ...row, name: '한빛상사 (내가 고침)' }]);
},
// 서버가 새 데이터를 보내 줘서 합쳐요. mergeRows는 키가 같은 줄은 갱신하고, 없는 줄은 추가해요.
// 내가 고친 칸과 서버 값이 부딪칠 때 어떻게 할지를 conflict 정책이 정해요.
serverUpdate: (api: GridApi<Row>) => {
pending = [];
const incoming: Row[] = [
{ id: 1, name: '한빛상사㈜', status: '거래중' },
{ id: 2, name: '푸른식품', status: '보류' },
{ id: 3, name: '새봄약품', status: '신규' },
];
// 서버가 보낸 값이 지금 표와 같으면 합칠 것이 없어요(같은 값을 또 보내도 "갱신"이라고 세지 않아요).
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say({
ko: '바뀐 값이 없어요. 서버가 보낸 값이 지금 표와 같아요.',
en: 'No value changed. The values the server sent are the same as the table now.',
});
const report = api.mergeRows(incoming, { conflict: policy });
say({
ko: `합친 결과(${policyName[policy]}): 새 줄 ${report.added}, 갱신 ${report.updated}, 서버 값이 덮은 줄 ${report.overwritten}, 내 수정을 지킨 줄 ${report.kept}`,
en: `Merge result (${policyNameEn[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`,
});
},
// 'notify'로 알림 받은 충돌 칸을 서버 값으로 바꿔요.
acceptTheirs: (api: GridApi<Row>) => {
if (!pending.length)
return say({
ko: '받아들일 충돌이 없어요. 정책을 "내 수정 우선 + 충돌 알림"으로 두고 합쳐 보세요.',
en: 'No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.',
});
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row) api.updateRows([{ ...row, [columnId]: theirs }]);
}
say({
ko: `${pending.length}칸을 서버 값으로 바꿨어요.`,
en: `Replaced ${pending.length} cells with the server values.`,
});
pending = [];
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
// 처음 상태로: 처음 줄 두 개만 남기고 저장 안 한 변경·충돌 목록을 모두 지워요.
reset: (api: GridApi<Row>) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say({ ko: '처음 상태로 되돌렸어요.', en: 'Back to the starting state.' });
},
};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="On conflict" id="policy">
<option value="server" selected>Server wins</option>
<option value="mine">Mine wins</option>
<option value="notify">Mine wins + notify</option>
</select>
<button type="button" id="myEdit">Make my edit</button>
<button type="button" id="serverUpdate">Server sent new values</button>
<button type="button" id="acceptTheirs">Take server for clashes</button>
<button type="button" id="discard">Discard changes</button>
<button type="button" id="reset">Back to start</button>
</div>
<div id="grid" style="height: 190px"></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('policy').addEventListener('change', (event) => actions.policy(api, event.target.value));
document.getElementById('myEdit').addEventListener('click', () => actions.myEdit(api));
document.getElementById('serverUpdate').addEventListener('click', () => actions.serverUpdate(api));
document.getElementById('acceptTheirs').addEventListener('click', () => actions.acceptTheirs(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));const rows = [
{ id: 1, name: 'Northwind Trading', status: 'New' },
{ id: 2, name: 'Greenfield Foods', status: 'New' },
];
let policy = 'server';
let pending = [];
let say = () => { };
export const options = {
columns: [
{ id: 'name', title: 'Client', width: 220, editable: true },
{ id: 'status', title: 'Status', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
export function setup(api, log) {
say = log;
log('Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.');
const offs = [
api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`)),
// With 'notify' my value is kept, and this event reports the cells where the two differ.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log(`⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`);
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
export const actions = {
policy: (_api, value) => {
policy = (value ?? 'server');
},
// Creates one edit of mine that is not saved yet.
myEdit: (api) => {
const row = api.getRowByKey(1);
if (row)
api.updateRows([{ ...row, name: 'Northwind Trading (my edit)' }]);
},
// The server sent new data and it is merged. mergeRows updates rows with the same key and adds rows that do not exist.
// The conflict policy decides what to do when a cell I edited collides with the server value.
serverUpdate: (api) => {
pending = [];
const incoming = [
{ id: 1, name: 'Northwind Trading Inc.', status: 'Active' },
{ id: 2, name: 'Greenfield Foods', status: 'On hold' },
{ id: 3, name: 'Spring Pharma', status: 'New' },
];
// If the values the server sent equal the current table, there is nothing to merge (sending the same value again is not counted as an "update").
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say('No value changed. The values the server sent are the same as the table now.');
const report = api.mergeRows(incoming, { conflict: policy });
say(`Merge result (${policyName[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`);
},
// Replaces the conflicting cells reported by 'notify' with the server values.
acceptTheirs: (api) => {
if (!pending.length)
return say('No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.');
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row)
api.updateRows([{ ...row, [columnId]: theirs }]);
}
say(`Replaced ${pending.length} cells with the server values.`);
pending = [];
},
discard: (api) => api.rollbackChanges(),
// Back to the start: keeps only the first two rows and clears all unsaved changes and the conflict list.
reset: (api) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say('Back to the starting state.');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Merge fresh server rows with your edits</title>
</head>
<body>
<div class="toolbar">
<select aria-label="On conflict" id="policy">
<option value="server" selected>Server wins</option>
<option value="mine">Mine wins</option>
<option value="notify">Mine wins + notify</option>
</select>
<button type="button" id="myEdit">Make my edit</button>
<button type="button" id="serverUpdate">Server sent new values</button>
<button type="button" id="acceptTheirs">Take server for clashes</button>
<button type="button" id="discard">Discard changes</button>
<button type="button" id="reset">Back to start</button>
</div>
<div id="grid" style="height: 190px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, name: 'Northwind Trading', status: 'New' },
{ id: 2, name: 'Greenfield Foods', status: 'New' },
];
let policy = 'server';
let pending = [];
let say = () => { };
const options = {
columns: [
{ id: 'name', title: 'Client', width: 220, editable: true },
{ id: 'status', title: 'Status', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
function setup(api, log) {
say = log;
log('Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.');
const offs = [
api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`)),
// With 'notify' my value is kept, and this event reports the cells where the two differ.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log(`⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`);
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
const actions = {
policy: (_api, value) => {
policy = (value ?? 'server');
},
// Creates one edit of mine that is not saved yet.
myEdit: (api) => {
const row = api.getRowByKey(1);
if (row)
api.updateRows([{ ...row, name: 'Northwind Trading (my edit)' }]);
},
// The server sent new data and it is merged. mergeRows updates rows with the same key and adds rows that do not exist.
// The conflict policy decides what to do when a cell I edited collides with the server value.
serverUpdate: (api) => {
pending = [];
const incoming = [
{ id: 1, name: 'Northwind Trading Inc.', status: 'Active' },
{ id: 2, name: 'Greenfield Foods', status: 'On hold' },
{ id: 3, name: 'Spring Pharma', status: 'New' },
];
// If the values the server sent equal the current table, there is nothing to merge (sending the same value again is not counted as an "update").
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say('No value changed. The values the server sent are the same as the table now.');
const report = api.mergeRows(incoming, { conflict: policy });
say(`Merge result (${policyName[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`);
},
// Replaces the conflicting cells reported by 'notify' with the server values.
acceptTheirs: (api) => {
if (!pending.length)
return say('No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.');
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row)
api.updateRows([{ ...row, [columnId]: theirs }]);
}
say(`Replaced ${pending.length} cells with the server values.`);
pending = [];
},
discard: (api) => api.rollbackChanges(),
// Back to the start: keeps only the first two rows and clears all unsaved changes and the conflict list.
reset: (api) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say('Back to the starting state.');
},
};
options.ariaLabel = "Merge fresh server rows with your edits";
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('policy').addEventListener('change', (event) => actions.policy(api, event.target.value));
document.getElementById('myEdit').addEventListener('click', () => actions.myEdit(api));
document.getElementById('serverUpdate').addEventListener('click', () => actions.serverUpdate(api));
document.getElementById('acceptTheirs').addEventListener('click', () => actions.acceptTheirs(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(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="On conflict"
disabled={!api}
onChange={(event) => api && actions.policy(api, event.target.value)}
>
<option value="server">Server wins</option>
<option value="mine">Mine wins</option>
<option value="notify">Mine wins + notify</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.myEdit(api)}
>Make my edit</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.serverUpdate(api)}
>Server sent new values</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.acceptTheirs(api)}
>Take server for clashes</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>Discard changes</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reset(api)}
>Back to start</button>
</div>
<Grid style={{ height: 190 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
status: string;
}
const rows: Row[] = [
{ id: 1, name: 'Northwind Trading', status: 'New' },
{ id: 2, name: 'Greenfield Foods', status: 'New' },
];
type Policy = 'server' | 'mine' | 'notify';
let policy: Policy = 'server';
let pending: { rowKey: number; columnId: string; theirs: unknown }[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Client', width: 220, editable: true },
{ id: 'status', title: 'Status', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(
'Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.',
);
const offs = [
api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`)),
// With 'notify' my value is kept, and this event reports the cells where the two differ.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey as number, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log(
`⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`,
);
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName: Record<Policy, string> = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
export const actions = {
policy: (_api: GridApi<Row>, value?: string) => {
policy = (value ?? 'server') as Policy;
},
// Creates one edit of mine that is not saved yet.
myEdit: (api: GridApi<Row>) => {
const row = api.getRowByKey(1);
if (row) api.updateRows([{ ...row, name: 'Northwind Trading (my edit)' }]);
},
// The server sent new data and it is merged. mergeRows updates rows with the same key and adds rows that do not exist.
// The conflict policy decides what to do when a cell I edited collides with the server value.
serverUpdate: (api: GridApi<Row>) => {
pending = [];
const incoming: Row[] = [
{ id: 1, name: 'Northwind Trading Inc.', status: 'Active' },
{ id: 2, name: 'Greenfield Foods', status: 'On hold' },
{ id: 3, name: 'Spring Pharma', status: 'New' },
];
// If the values the server sent equal the current table, there is nothing to merge (sending the same value again is not counted as an "update").
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say('No value changed. The values the server sent are the same as the table now.');
const report = api.mergeRows(incoming, { conflict: policy });
say(
`Merge result (${policyName[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`,
);
},
// Replaces the conflicting cells reported by 'notify' with the server values.
acceptTheirs: (api: GridApi<Row>) => {
if (!pending.length)
return say(
'No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.',
);
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row) api.updateRows([{ ...row, [columnId]: theirs }]);
}
say(`Replaced ${pending.length} cells with the server values.`);
pending = [];
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
// Back to the start: keeps only the first two rows and clears all unsaved changes and the conflict list.
reset: (api: GridApi<Row>) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say('Back to the starting state.');
},
};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="On conflict"
:disabled="!api"
@change="api && actions.policy(api, ($event.target as HTMLSelectElement).value)"
>
<option value="server" selected>Server wins</option>
<option value="mine">Mine wins</option>
<option value="notify">Mine wins + notify</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.myEdit(api)">Make my edit</button>
<button
type="button"
:disabled="!api"
@click="api && actions.serverUpdate(api)"
>Server sent new values</button>
<button
type="button"
:disabled="!api"
@click="api && actions.acceptTheirs(api)"
>Take server for clashes</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">Discard changes</button>
<button type="button" :disabled="!api" @click="api && actions.reset(api)">Back to start</button>
</div>
<Grid style="height: 190px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
status: string;
}
const rows: Row[] = [
{ id: 1, name: 'Northwind Trading', status: 'New' },
{ id: 2, name: 'Greenfield Foods', status: 'New' },
];
type Policy = 'server' | 'mine' | 'notify';
let policy: Policy = 'server';
let pending: { rowKey: number; columnId: string; theirs: unknown }[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Client', width: 220, editable: true },
{ id: 'status', title: 'Status', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(
'Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.',
);
const offs = [
api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`)),
// With 'notify' my value is kept, and this event reports the cells where the two differ.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey as number, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log(
`⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`,
);
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName: Record<Policy, string> = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
export const actions = {
policy: (_api: GridApi<Row>, value?: string) => {
policy = (value ?? 'server') as Policy;
},
// Creates one edit of mine that is not saved yet.
myEdit: (api: GridApi<Row>) => {
const row = api.getRowByKey(1);
if (row) api.updateRows([{ ...row, name: 'Northwind Trading (my edit)' }]);
},
// The server sent new data and it is merged. mergeRows updates rows with the same key and adds rows that do not exist.
// The conflict policy decides what to do when a cell I edited collides with the server value.
serverUpdate: (api: GridApi<Row>) => {
pending = [];
const incoming: Row[] = [
{ id: 1, name: 'Northwind Trading Inc.', status: 'Active' },
{ id: 2, name: 'Greenfield Foods', status: 'On hold' },
{ id: 3, name: 'Spring Pharma', status: 'New' },
];
// If the values the server sent equal the current table, there is nothing to merge (sending the same value again is not counted as an "update").
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say('No value changed. The values the server sent are the same as the table now.');
const report = api.mergeRows(incoming, { conflict: policy });
say(
`Merge result (${policyName[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`,
);
},
// Replaces the conflicting cells reported by 'notify' with the server values.
acceptTheirs: (api: GridApi<Row>) => {
if (!pending.length)
return say(
'No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.',
);
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row) api.updateRows([{ ...row, [columnId]: theirs }]);
}
say(`Replaced ${pending.length} cells with the server values.`);
pending = [];
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
// Back to the start: keeps only the first two rows and clears all unsaved changes and the conflict list.
reset: (api: GridApi<Row>) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say('Back to the starting state.');
},
};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="On conflict"
[disabled]="!api"
(change)="api && actions.policy(api, $any($event.target).value)"
>
<option value="server" selected>Server wins</option>
<option value="mine">Mine wins</option>
<option value="notify">Mine wins + notify</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.myEdit(api)"
>Make my edit</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.serverUpdate(api)"
>Server sent new values</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.acceptTheirs(api)"
>Take server for clashes</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>Discard changes</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reset(api)"
>Back to start</button>
</div>
<mx-grid style="height: 190px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
status: string;
}
const rows: Row[] = [
{ id: 1, name: 'Northwind Trading', status: 'New' },
{ id: 2, name: 'Greenfield Foods', status: 'New' },
];
type Policy = 'server' | 'mine' | 'notify';
let policy: Policy = 'server';
let pending: { rowKey: number; columnId: string; theirs: unknown }[] = [];
let say: (message: LogText) => void = () => {};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Client', width: 220, editable: true },
{ id: 'status', title: 'Status', width: 110, editable: true },
],
rows,
rowKey: 'id',
saveMode: 'batch',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(
'Press "Make my edit" first, then "Server sent a new value", and see how the policy merges them.',
);
const offs = [
api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`)),
// With 'notify' my value is kept, and this event reports the cells where the two differ.
api.on('mergeConflict', (e) => {
for (const cell of e.cells) {
pending.push({ rowKey: e.rowKey as number, columnId: cell.columnId, theirs: cell.theirs });
const title = api.getColumns().find((c) => c.id === cell.columnId)?.title ?? cell.columnId;
log(
`⚠ Row ${e.rowKey} ${title}: my value "${String(cell.mine)}", server value "${String(cell.theirs)}"`,
);
}
}),
];
return () => offs.forEach((off) => off());
}
const policyName: Record<Policy, string> = {
server: 'server value wins',
mine: 'my edit wins',
notify: 'my edit wins + conflict notice',
};
export const actions = {
policy: (_api: GridApi<Row>, value?: string) => {
policy = (value ?? 'server') as Policy;
},
// Creates one edit of mine that is not saved yet.
myEdit: (api: GridApi<Row>) => {
const row = api.getRowByKey(1);
if (row) api.updateRows([{ ...row, name: 'Northwind Trading (my edit)' }]);
},
// The server sent new data and it is merged. mergeRows updates rows with the same key and adds rows that do not exist.
// The conflict policy decides what to do when a cell I edited collides with the server value.
serverUpdate: (api: GridApi<Row>) => {
pending = [];
const incoming: Row[] = [
{ id: 1, name: 'Northwind Trading Inc.', status: 'Active' },
{ id: 2, name: 'Greenfield Foods', status: 'On hold' },
{ id: 3, name: 'Spring Pharma', status: 'New' },
];
// If the values the server sent equal the current table, there is nothing to merge (sending the same value again is not counted as an "update").
const differs = incoming.some((row) => {
const now = api.getRowByKey(row.id);
return !now || now.name !== row.name || now.status !== row.status;
});
if (!differs)
return say('No value changed. The values the server sent are the same as the table now.');
const report = api.mergeRows(incoming, { conflict: policy });
say(
`Merge result (${policyName[policy]}): ${report.added} new rows, ${report.updated} updated, ${report.overwritten} overwritten by the server, ${report.kept} kept as my edit`,
);
},
// Replaces the conflicting cells reported by 'notify' with the server values.
acceptTheirs: (api: GridApi<Row>) => {
if (!pending.length)
return say(
'No conflict to accept. Set the policy to "my edit wins + conflict notice" and merge.',
);
for (const { rowKey, columnId, theirs } of pending) {
const row = api.getRowByKey(rowKey);
if (row) api.updateRows([{ ...row, [columnId]: theirs }]);
}
say(`Replaced ${pending.length} cells with the server values.`);
pending = [];
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
// Back to the start: keeps only the first two rows and clears all unsaved changes and the conflict list.
reset: (api: GridApi<Row>) => {
pending = [];
api.setRows(rows.map((row) => ({ ...row })));
say('Back to the starting state.');
},
};