오프라인에서 고친 것을 쌓아 두었다 보내기Queue edits offline and send them later
인터넷이 끊겨 서버로 못 보내도 고친 값은 표 안에 대기열로 남아요. 다시 온라인이 되면 쌓인 변경을 한 번에 보내요. (네트워크 상태는 실제가 아니라 선택 상자로 흉내 내요.)Even when the connection is down, edits stay in the grid as a queue and are sent together when back online. (The network state is simulated with the select, not real.)
코드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="net">
<option value="offline" selected>오프라인</option>
<option value="online">온라인</option>
</select>
</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('net').addEventListener('change', (event) => actions.net(api, event.target.value));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const rows = [
{ id: 1, item: '건전지', count: 40 },
{ id: 2, item: '박스 테이프', count: 12 },
{ id: 3, item: '라벨 스티커', count: 300 },
{ id: 4, item: '완충재', count: 75 },
];
// 네트워크를 흉내 내요. 오프라인이면 처리기가 예외를 던지고, 그러면 변경은 표에 그대로 남아서 "대기열"이 돼요.
// 다시 온라인이 되면 쌓인 변경을 한 번에 보내요.
let online = false;
const handler = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online)
throw new Error('오프라인');
};
export const options = {
columns: [
{ id: 'item', title: '품목', width: 150, editable: true },
{ id: 'count', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // 확정할 때마다 보내 보고, 실패하면 대기열에 남겨요.
saveHandler: handler,
};
let badge = null;
// 표 위에 대기 상태를 작은 표시로 보여 줘요(기록을 읽지 않아도 지금 몇 줄이 밀려 있는지 알 수 있어요).
function paint(count) {
if (!badge)
return;
badge.textContent = L(`${online ? '온라인' : '오프라인'} · 대기 중 ${count}줄`, `${online ? 'Online' : 'Offline'} · ${count} rows waiting`);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
export function setup(api, log) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log({
ko: '지금은 오프라인이에요. 재고를 몇 개 고쳐 보세요. 보내지 못한 변경이 대기열에 쌓여요.',
en: 'You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.',
});
const offs = [
// 고칠 때마다 기록을 남기면 시끄러워서, 대기 줄 수는 위의 표시로만 보여 줘요.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () => log({
ko: '보내지 못했어요. 변경은 대기열에 그대로 있어요.',
en: 'Could not send. The changes stay in the queue.',
})),
api.on('changesCommitted', ({ changes }) => log({
ko: `✓ 대기열 ${changes.length}줄을 보냈어요`,
en: `✓ Sent ${changes.length} rows from the queue`,
})),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
export const actions = {
net: async (api, value) => {
online = value === 'online';
paint(api.getChanges().length);
if (online)
await api.save(); // 쌓인 변경을 모두 보내요.
},
};<!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="net">
<option value="offline" selected>오프라인</option>
<option value="online">온라인</option>
</select>
</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>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const rows = [
{ id: 1, item: '건전지', count: 40 },
{ id: 2, item: '박스 테이프', count: 12 },
{ id: 3, item: '라벨 스티커', count: 300 },
{ id: 4, item: '완충재', count: 75 },
];
// 네트워크를 흉내 내요. 오프라인이면 처리기가 예외를 던지고, 그러면 변경은 표에 그대로 남아서 "대기열"이 돼요.
// 다시 온라인이 되면 쌓인 변경을 한 번에 보내요.
let online = false;
const handler = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online)
throw new Error('오프라인');
};
const options = {
columns: [
{ id: 'item', title: '품목', width: 150, editable: true },
{ id: 'count', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // 확정할 때마다 보내 보고, 실패하면 대기열에 남겨요.
saveHandler: handler,
};
let badge = null;
// 표 위에 대기 상태를 작은 표시로 보여 줘요(기록을 읽지 않아도 지금 몇 줄이 밀려 있는지 알 수 있어요).
function paint(count) {
if (!badge)
return;
badge.textContent = L(`${online ? '온라인' : '오프라인'} · 대기 중 ${count}줄`, `${online ? 'Online' : 'Offline'} · ${count} rows waiting`);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
function setup(api, log) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log({
ko: '지금은 오프라인이에요. 재고를 몇 개 고쳐 보세요. 보내지 못한 변경이 대기열에 쌓여요.',
en: 'You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.',
});
const offs = [
// 고칠 때마다 기록을 남기면 시끄러워서, 대기 줄 수는 위의 표시로만 보여 줘요.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () => log({
ko: '보내지 못했어요. 변경은 대기열에 그대로 있어요.',
en: 'Could not send. The changes stay in the queue.',
})),
api.on('changesCommitted', ({ changes }) => log({
ko: `✓ 대기열 ${changes.length}줄을 보냈어요`,
en: `✓ Sent ${changes.length} rows from the queue`,
})),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
const actions = {
net: async (api, value) => {
online = value === 'online';
paint(api.getChanges().length);
if (online)
await api.save(); // 쌓인 변경을 모두 보내요.
},
};
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('net').addEventListener('change', (event) => actions.net(api, event.target.value));
</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.net(api, event.target.value)}
>
<option value="offline">오프라인</option>
<option value="online">온라인</option>
</select>
</div>
<Grid style={{ height: 190 }} 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 };
export interface Row {
id: number;
item: string;
count: number;
}
const rows: Row[] = [
{ id: 1, item: '건전지', count: 40 },
{ id: 2, item: '박스 테이프', count: 12 },
{ id: 3, item: '라벨 스티커', count: 300 },
{ id: 4, item: '완충재', count: 75 },
];
// 네트워크를 흉내 내요. 오프라인이면 처리기가 예외를 던지고, 그러면 변경은 표에 그대로 남아서 "대기열"이 돼요.
// 다시 온라인이 되면 쌓인 변경을 한 번에 보내요.
let online = false;
const handler: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online) throw new Error('오프라인');
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: '품목', width: 150, editable: true },
{ id: 'count', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // 확정할 때마다 보내 보고, 실패하면 대기열에 남겨요.
saveHandler: handler,
};
let badge: HTMLElement | null = null;
// 표 위에 대기 상태를 작은 표시로 보여 줘요(기록을 읽지 않아도 지금 몇 줄이 밀려 있는지 알 수 있어요).
function paint(count: number): void {
if (!badge) return;
badge.textContent = L(
`${online ? '온라인' : '오프라인'} · 대기 중 ${count}줄`,
`${online ? 'Online' : 'Offline'} · ${count} rows waiting`,
);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log({
ko: '지금은 오프라인이에요. 재고를 몇 개 고쳐 보세요. 보내지 못한 변경이 대기열에 쌓여요.',
en: 'You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.',
});
const offs = [
// 고칠 때마다 기록을 남기면 시끄러워서, 대기 줄 수는 위의 표시로만 보여 줘요.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () =>
log({
ko: '보내지 못했어요. 변경은 대기열에 그대로 있어요.',
en: 'Could not send. The changes stay in the queue.',
}),
),
api.on('changesCommitted', ({ changes }) =>
log({
ko: `✓ 대기열 ${changes.length}줄을 보냈어요`,
en: `✓ Sent ${changes.length} rows from the queue`,
}),
),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
export const actions = {
net: async (api: GridApi<Row>, value?: string) => {
online = value === 'online';
paint(api.getChanges().length);
if (online) await api.save(); // 쌓인 변경을 모두 보내요.
},
};버튼을 누르면 이 예제의 코드가 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.net(api, ($event.target as HTMLSelectElement).value)"
>
<option value="offline" selected>오프라인</option>
<option value="online">온라인</option>
</select>
</div>
<Grid style="height: 190px" :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 };
export interface Row {
id: number;
item: string;
count: number;
}
const rows: Row[] = [
{ id: 1, item: '건전지', count: 40 },
{ id: 2, item: '박스 테이프', count: 12 },
{ id: 3, item: '라벨 스티커', count: 300 },
{ id: 4, item: '완충재', count: 75 },
];
// 네트워크를 흉내 내요. 오프라인이면 처리기가 예외를 던지고, 그러면 변경은 표에 그대로 남아서 "대기열"이 돼요.
// 다시 온라인이 되면 쌓인 변경을 한 번에 보내요.
let online = false;
const handler: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online) throw new Error('오프라인');
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: '품목', width: 150, editable: true },
{ id: 'count', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // 확정할 때마다 보내 보고, 실패하면 대기열에 남겨요.
saveHandler: handler,
};
let badge: HTMLElement | null = null;
// 표 위에 대기 상태를 작은 표시로 보여 줘요(기록을 읽지 않아도 지금 몇 줄이 밀려 있는지 알 수 있어요).
function paint(count: number): void {
if (!badge) return;
badge.textContent = L(
`${online ? '온라인' : '오프라인'} · 대기 중 ${count}줄`,
`${online ? 'Online' : 'Offline'} · ${count} rows waiting`,
);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log({
ko: '지금은 오프라인이에요. 재고를 몇 개 고쳐 보세요. 보내지 못한 변경이 대기열에 쌓여요.',
en: 'You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.',
});
const offs = [
// 고칠 때마다 기록을 남기면 시끄러워서, 대기 줄 수는 위의 표시로만 보여 줘요.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () =>
log({
ko: '보내지 못했어요. 변경은 대기열에 그대로 있어요.',
en: 'Could not send. The changes stay in the queue.',
}),
),
api.on('changesCommitted', ({ changes }) =>
log({
ko: `✓ 대기열 ${changes.length}줄을 보냈어요`,
en: `✓ Sent ${changes.length} rows from the queue`,
}),
),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
export const actions = {
net: async (api: GridApi<Row>, value?: string) => {
online = value === 'online';
paint(api.getChanges().length);
if (online) await api.save(); // 쌓인 변경을 모두 보내요.
},
};버튼을 누르면 이 예제의 코드가 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.net(api, $any($event.target).value)"
>
<option value="offline" selected>오프라인</option>
<option value="online">온라인</option>
</select>
</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, 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 };
export interface Row {
id: number;
item: string;
count: number;
}
const rows: Row[] = [
{ id: 1, item: '건전지', count: 40 },
{ id: 2, item: '박스 테이프', count: 12 },
{ id: 3, item: '라벨 스티커', count: 300 },
{ id: 4, item: '완충재', count: 75 },
];
// 네트워크를 흉내 내요. 오프라인이면 처리기가 예외를 던지고, 그러면 변경은 표에 그대로 남아서 "대기열"이 돼요.
// 다시 온라인이 되면 쌓인 변경을 한 번에 보내요.
let online = false;
const handler: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online) throw new Error('오프라인');
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: '품목', width: 150, editable: true },
{ id: 'count', title: '재고', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // 확정할 때마다 보내 보고, 실패하면 대기열에 남겨요.
saveHandler: handler,
};
let badge: HTMLElement | null = null;
// 표 위에 대기 상태를 작은 표시로 보여 줘요(기록을 읽지 않아도 지금 몇 줄이 밀려 있는지 알 수 있어요).
function paint(count: number): void {
if (!badge) return;
badge.textContent = L(
`${online ? '온라인' : '오프라인'} · 대기 중 ${count}줄`,
`${online ? 'Online' : 'Offline'} · ${count} rows waiting`,
);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log({
ko: '지금은 오프라인이에요. 재고를 몇 개 고쳐 보세요. 보내지 못한 변경이 대기열에 쌓여요.',
en: 'You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.',
});
const offs = [
// 고칠 때마다 기록을 남기면 시끄러워서, 대기 줄 수는 위의 표시로만 보여 줘요.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () =>
log({
ko: '보내지 못했어요. 변경은 대기열에 그대로 있어요.',
en: 'Could not send. The changes stay in the queue.',
}),
),
api.on('changesCommitted', ({ changes }) =>
log({
ko: `✓ 대기열 ${changes.length}줄을 보냈어요`,
en: `✓ Sent ${changes.length} rows from the queue`,
}),
),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
export const actions = {
net: async (api: GridApi<Row>, value?: string) => {
online = value === 'online';
paint(api.getChanges().length);
if (online) await api.save(); // 쌓인 변경을 모두 보내요.
},
};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="Network" id="net">
<option value="offline" selected>Offline</option>
<option value="online">Online</option>
</select>
</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('net').addEventListener('change', (event) => actions.net(api, event.target.value));// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko, en) => en;
const rows = [
{ id: 1, item: 'Batteries', count: 40 },
{ id: 2, item: 'Packing tape', count: 12 },
{ id: 3, item: 'Label stickers', count: 300 },
{ id: 4, item: 'Bubble wrap', count: 75 },
];
// Simulates the network. When offline the handler throws, and the changes stay in the table as a "queue".
// When back online, the piled-up changes are sent at once.
let online = false;
const handler = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online)
throw new Error('Offline');
};
export const options = {
columns: [
{ id: 'item', title: 'Item', width: 150, editable: true },
{ id: 'count', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // Tries to send on every commit, and leaves it in the queue on failure.
saveHandler: handler,
};
let badge = null;
// Shows the waiting state as a small badge above the grid (you can tell how many rows are backed up without reading the log).
function paint(count) {
if (!badge)
return;
badge.textContent = L('', `${online ? 'Online' : 'Offline'} · ${count} rows waiting`);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
export function setup(api, log) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log('You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.');
const offs = [
// Logging on every edit would be noisy, so the waiting row count is shown only by the badge above.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () => log('Could not send. The changes stay in the queue.')),
api.on('changesCommitted', ({ changes }) => log(`✓ Sent ${changes.length} rows from the queue`)),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
export const actions = {
net: async (api, value) => {
online = value === 'online';
paint(api.getChanges().length);
if (online)
await api.save(); // Sends all the piled-up changes.
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Queue edits offline and send them later</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Network" id="net">
<option value="offline" selected>Offline</option>
<option value="online">Online</option>
</select>
</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>
// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko, en) => en;
const rows = [
{ id: 1, item: 'Batteries', count: 40 },
{ id: 2, item: 'Packing tape', count: 12 },
{ id: 3, item: 'Label stickers', count: 300 },
{ id: 4, item: 'Bubble wrap', count: 75 },
];
// Simulates the network. When offline the handler throws, and the changes stay in the table as a "queue".
// When back online, the piled-up changes are sent at once.
let online = false;
const handler = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online)
throw new Error('Offline');
};
const options = {
columns: [
{ id: 'item', title: 'Item', width: 150, editable: true },
{ id: 'count', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // Tries to send on every commit, and leaves it in the queue on failure.
saveHandler: handler,
};
let badge = null;
// Shows the waiting state as a small badge above the grid (you can tell how many rows are backed up without reading the log).
function paint(count) {
if (!badge)
return;
badge.textContent = L('', `${online ? 'Online' : 'Offline'} · ${count} rows waiting`);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
function setup(api, log) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log('You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.');
const offs = [
// Logging on every edit would be noisy, so the waiting row count is shown only by the badge above.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () => log('Could not send. The changes stay in the queue.')),
api.on('changesCommitted', ({ changes }) => log(`✓ Sent ${changes.length} rows from the queue`)),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
const actions = {
net: async (api, value) => {
online = value === 'online';
paint(api.getChanges().length);
if (online)
await api.save(); // Sends all the piled-up changes.
},
};
options.ariaLabel = "Queue edits offline and send them later";
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('net').addEventListener('change', (event) => actions.net(api, event.target.value));
</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="Network"
disabled={!api}
onChange={(event) => api && actions.net(api, event.target.value)}
>
<option value="offline">Offline</option>
<option value="online">Online</option>
</select>
</div>
<Grid style={{ height: 190 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/react';
// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko: string, en: string): string => en;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
count: number;
}
const rows: Row[] = [
{ id: 1, item: 'Batteries', count: 40 },
{ id: 2, item: 'Packing tape', count: 12 },
{ id: 3, item: 'Label stickers', count: 300 },
{ id: 4, item: 'Bubble wrap', count: 75 },
];
// Simulates the network. When offline the handler throws, and the changes stay in the table as a "queue".
// When back online, the piled-up changes are sent at once.
let online = false;
const handler: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online) throw new Error('Offline');
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: 'Item', width: 150, editable: true },
{ id: 'count', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // Tries to send on every commit, and leaves it in the queue on failure.
saveHandler: handler,
};
let badge: HTMLElement | null = null;
// Shows the waiting state as a small badge above the grid (you can tell how many rows are backed up without reading the log).
function paint(count: number): void {
if (!badge) return;
badge.textContent = L('', `${online ? 'Online' : 'Offline'} · ${count} rows waiting`);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log(
'You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.',
);
const offs = [
// Logging on every edit would be noisy, so the waiting row count is shown only by the badge above.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () => log('Could not send. The changes stay in the queue.')),
api.on('changesCommitted', ({ changes }) =>
log(`✓ Sent ${changes.length} rows from the queue`),
),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
export const actions = {
net: async (api: GridApi<Row>, value?: string) => {
online = value === 'online';
paint(api.getChanges().length);
if (online) await api.save(); // Sends all the piled-up changes.
},
};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="Network"
:disabled="!api"
@change="api && actions.net(api, ($event.target as HTMLSelectElement).value)"
>
<option value="offline" selected>Offline</option>
<option value="online">Online</option>
</select>
</div>
<Grid style="height: 190px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/vue';
// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko: string, en: string): string => en;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
count: number;
}
const rows: Row[] = [
{ id: 1, item: 'Batteries', count: 40 },
{ id: 2, item: 'Packing tape', count: 12 },
{ id: 3, item: 'Label stickers', count: 300 },
{ id: 4, item: 'Bubble wrap', count: 75 },
];
// Simulates the network. When offline the handler throws, and the changes stay in the table as a "queue".
// When back online, the piled-up changes are sent at once.
let online = false;
const handler: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online) throw new Error('Offline');
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: 'Item', width: 150, editable: true },
{ id: 'count', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // Tries to send on every commit, and leaves it in the queue on failure.
saveHandler: handler,
};
let badge: HTMLElement | null = null;
// Shows the waiting state as a small badge above the grid (you can tell how many rows are backed up without reading the log).
function paint(count: number): void {
if (!badge) return;
badge.textContent = L('', `${online ? 'Online' : 'Offline'} · ${count} rows waiting`);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log(
'You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.',
);
const offs = [
// Logging on every edit would be noisy, so the waiting row count is shown only by the badge above.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () => log('Could not send. The changes stay in the queue.')),
api.on('changesCommitted', ({ changes }) =>
log(`✓ Sent ${changes.length} rows from the queue`),
),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
export const actions = {
net: async (api: GridApi<Row>, value?: string) => {
online = value === 'online';
paint(api.getChanges().length);
if (online) await api.save(); // Sends all the piled-up changes.
},
};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="Network"
[disabled]="!api"
(change)="api && actions.net(api, $any($event.target).value)"
>
<option value="offline" selected>Offline</option>
<option value="online">Online</option>
</select>
</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, SaveHandler } from '@maxgrid/angular';
// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko: string, en: string): string => en;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
count: number;
}
const rows: Row[] = [
{ id: 1, item: 'Batteries', count: 40 },
{ id: 2, item: 'Packing tape', count: 12 },
{ id: 3, item: 'Label stickers', count: 300 },
{ id: 4, item: 'Bubble wrap', count: 75 },
];
// Simulates the network. When offline the handler throws, and the changes stay in the table as a "queue".
// When back online, the piled-up changes are sent at once.
let online = false;
const handler: SaveHandler<Row> = async () => {
await new Promise((resolve) => setTimeout(resolve, 200));
if (!online) throw new Error('Offline');
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: 'Item', width: 150, editable: true },
{ id: 'count', title: 'Stock', kind: 'number', width: 100, align: 'end', editable: true },
],
rows,
rowKey: 'id',
saveMode: 'immediate', // Tries to send on every commit, and leaves it in the queue on failure.
saveHandler: handler,
};
let badge: HTMLElement | null = null;
// Shows the waiting state as a small badge above the grid (you can tell how many rows are backed up without reading the log).
function paint(count: number): void {
if (!badge) return;
badge.textContent = L('', `${online ? 'Online' : 'Offline'} · ${count} rows waiting`);
badge.style.borderColor =
count > 0 && !online ? 'color-mix(in srgb, #e5484d 75%, var(--fg))' : 'var(--line)';
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
online = false;
badge = document.createElement('div');
badge.style.cssText =
'display: inline-block; margin-bottom: 6px; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; color: var(--fg); background: var(--bg);';
document.getElementById('grid')?.before(badge);
paint(0);
log(
'You are offline now. Edit a few stock values. Changes that cannot be sent pile up in the queue.',
);
const offs = [
// Logging on every edit would be noisy, so the waiting row count is shown only by the badge above.
api.on('changesCountChanged', ({ count }) => paint(count)),
api.on('saveFailed', () => log('Could not send. The changes stay in the queue.')),
api.on('changesCommitted', ({ changes }) =>
log(`✓ Sent ${changes.length} rows from the queue`),
),
];
return () => {
offs.forEach((off) => off());
badge?.remove();
badge = null;
};
}
export const actions = {
net: async (api: GridApi<Row>, value?: string) => {
online = value === 'online';
paint(api.getChanges().length);
if (online) await api.save(); // Sends all the piled-up changes.
},
};