본문으로 건너뛰기Skip to content
예제 첫화면Examples home

오프라인에서 고친 것을 쌓아 두었다 보내기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.)

활용Intermediate
직접 써 보기Live preview오프라인에서 고친 것을 쌓아 두었다 보내기Queue edits offline and send them later

코드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)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<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>
main.js
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));
example.js
// 예제 틀이 알려 주는 페이지 언어(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(); // 쌓인 변경을 모두 보내요.
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<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>
main.js
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));
example.js
// 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.
  },
};