주문마다 나눠 저장하고 실패한 주문만 남기기Save each order separately and keep only failures
saveDetails()가 주문마다 저장 함수를 불러요. 성공한 주문은 변경 표시가 지워지고, 실패한 주문은 표시가 남아 다시 저장할 수 있어요. 3번 주문은 일부러 실패해요.saveDetails() calls the save function once per order. Saved orders lose their change marks; failed orders keep them so you can retry. Order 3 fails on purpose.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="saveAll">모두 저장</button>
<button type="button" id="saveFirst">1번만 저장</button>
</div>
<div id="grid" style="height: 480px"></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('saveAll').addEventListener('click', () => actions.saveAll(api));
document.getElementById('saveFirst').addEventListener('click', () => actions.saveFirst(api));const rows = [
{ id: 1, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = () => {
let grid = null;
let off;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 서버 대신 300ms 기다리는 저장 함수예요. 3번 주문은 일부러 실패해요.
const save = ({ rowKey }) => new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3)
reject(new Error('server error'));
else
resolve();
}, 300);
});
export const options = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger = () => { };
export function setup(api, log) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log({
ko: `${rowKey}번 주문 저장 완료 (추가 ${added}, 수정 ${updated}, 삭제 ${removed})`,
en: `Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`,
});
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log({
ko: `${rowKey}번 주문 저장 실패: ${reason}. 변경 표시는 그대로 남아요`,
en: `Order ${rowKey} save failed: ${reason}. Its marks stay`,
});
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
saveAll: async (api) => {
const { saved, failed } = await api.saveDetails();
logger({
ko: `저장한 주문: [${saved.join(', ')}], 실패한 주문: [${failed.join(', ')}]`,
en: `Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`,
});
},
saveFirst: async (api) => {
const { saved, failed } = await api.saveDetails(1);
logger({
ko: `1번 주문만 저장했어요. 저장 [${saved.join(', ')}], 실패 [${failed.join(', ')}]`,
en: `Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`,
});
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>주문마다 나눠 저장하고 실패한 주문만 남기기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="saveAll">모두 저장</button>
<button type="button" id="saveFirst">1번만 저장</button>
</div>
<div id="grid" style="height: 480px"></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, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = () => {
let grid = null;
let off;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 서버 대신 300ms 기다리는 저장 함수예요. 3번 주문은 일부러 실패해요.
const save = ({ rowKey }) => new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3)
reject(new Error('server error'));
else
resolve();
}, 300);
});
const options = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger = () => { };
function setup(api, log) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log({
ko: `${rowKey}번 주문 저장 완료 (추가 ${added}, 수정 ${updated}, 삭제 ${removed})`,
en: `Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`,
});
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log({
ko: `${rowKey}번 주문 저장 실패: ${reason}. 변경 표시는 그대로 남아요`,
en: `Order ${rowKey} save failed: ${reason}. Its marks stay`,
});
}),
];
return () => offs.forEach((off) => off());
}
const actions = {
saveAll: async (api) => {
const { saved, failed } = await api.saveDetails();
logger({
ko: `저장한 주문: [${saved.join(', ')}], 실패한 주문: [${failed.join(', ')}]`,
en: `Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`,
});
},
saveFirst: async (api) => {
const { saved, failed } = await api.saveDetails(1);
logger({
ko: `1번 주문만 저장했어요. 저장 [${saved.join(', ')}], 실패 [${failed.join(', ')}]`,
en: `Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`,
});
},
};
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('saveAll').addEventListener('click', () => actions.saveAll(api));
document.getElementById('saveFirst').addEventListener('click', () => actions.saveFirst(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.saveAll(api)}
>모두 저장</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.saveFirst(api)}
>1번만 저장</button>
</div>
<Grid style={{ height: 480 }} ref={gridRef} options={options} />
</>
);
}import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v: unknown) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 서버 대신 300ms 기다리는 저장 함수예요. 3번 주문은 일부러 실패해요.
const save = ({ rowKey }: { rowKey: unknown }): Promise<void> =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3) reject(new Error('server error'));
else resolve();
}, 300);
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log({
ko: `${rowKey}번 주문 저장 완료 (추가 ${added}, 수정 ${updated}, 삭제 ${removed})`,
en: `Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`,
});
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log({
ko: `${rowKey}번 주문 저장 실패: ${reason}. 변경 표시는 그대로 남아요`,
en: `Order ${rowKey} save failed: ${reason}. Its marks stay`,
});
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
saveAll: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails();
logger({
ko: `저장한 주문: [${saved.join(', ')}], 실패한 주문: [${failed.join(', ')}]`,
en: `Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`,
});
},
saveFirst: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails(1);
logger({
ko: `1번 주문만 저장했어요. 저장 [${saved.join(', ')}], 실패 [${failed.join(', ')}]`,
en: `Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`,
});
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.saveAll(api)">모두 저장</button>
<button
type="button"
:disabled="!api"
@click="api && actions.saveFirst(api)"
>1번만 저장</button>
</div>
<Grid style="height: 480px" :options="options" @ready="onReady" />
</template>import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v: unknown) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 서버 대신 300ms 기다리는 저장 함수예요. 3번 주문은 일부러 실패해요.
const save = ({ rowKey }: { rowKey: unknown }): Promise<void> =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3) reject(new Error('server error'));
else resolve();
}, 300);
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log({
ko: `${rowKey}번 주문 저장 완료 (추가 ${added}, 수정 ${updated}, 삭제 ${removed})`,
en: `Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`,
});
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log({
ko: `${rowKey}번 주문 저장 실패: ${reason}. 변경 표시는 그대로 남아요`,
en: `Order ${rowKey} save failed: ${reason}. Its marks stay`,
});
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
saveAll: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails();
logger({
ko: `저장한 주문: [${saved.join(', ')}], 실패한 주문: [${failed.join(', ')}]`,
en: `Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`,
});
},
saveFirst: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails(1);
logger({
ko: `1번 주문만 저장했어요. 저장 [${saved.join(', ')}], 실패 [${failed.join(', ')}]`,
en: `Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`,
});
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.saveAll(api)"
>모두 저장</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.saveFirst(api)"
>1번만 저장</button>
</div>
<mx-grid style="height: 480px" [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 { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v: unknown) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 서버 대신 300ms 기다리는 저장 함수예요. 3번 주문은 일부러 실패해요.
const save = ({ rowKey }: { rowKey: unknown }): Promise<void> =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3) reject(new Error('server error'));
else resolve();
}, 300);
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log({
ko: `${rowKey}번 주문 저장 완료 (추가 ${added}, 수정 ${updated}, 삭제 ${removed})`,
en: `Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`,
});
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log({
ko: `${rowKey}번 주문 저장 실패: ${reason}. 변경 표시는 그대로 남아요`,
en: `Order ${rowKey} save failed: ${reason}. Its marks stay`,
});
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
saveAll: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails();
logger({
ko: `저장한 주문: [${saved.join(', ')}], 실패한 주문: [${failed.join(', ')}]`,
en: `Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`,
});
},
saveFirst: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails(1);
logger({
ko: `1번 주문만 저장했어요. 저장 [${saved.join(', ')}], 실패 [${failed.join(', ')}]`,
en: `Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`,
});
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="saveAll">Save all</button>
<button type="button" id="saveFirst">Save order 1</button>
</div>
<div id="grid" style="height: 480px"></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('saveAll').addEventListener('click', () => actions.saveAll(api));
document.getElementById('saveFirst').addEventListener('click', () => actions.saveFirst(api));const rows = [
{ id: 1, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = () => {
let grid = null;
let off;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// A save function that waits 300 ms instead of calling a server. Order 3 fails on purpose.
const save = ({ rowKey }) => new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3)
reject(new Error('server error'));
else
resolve();
}, 300);
});
export const options = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger = () => { };
export function setup(api, log) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log(`Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`);
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log(`Order ${rowKey} save failed: ${reason}. Its marks stay`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
saveAll: async (api) => {
const { saved, failed } = await api.saveDetails();
logger(`Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`);
},
saveFirst: async (api) => {
const { saved, failed } = await api.saveDetails(1);
logger(`Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Save each order separately and keep only failures</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="saveAll">Save all</button>
<button type="button" id="saveFirst">Save order 1</button>
</div>
<div id="grid" style="height: 480px"></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, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = () => {
let grid = null;
let off;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// A save function that waits 300 ms instead of calling a server. Order 3 fails on purpose.
const save = ({ rowKey }) => new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3)
reject(new Error('server error'));
else
resolve();
}, 300);
});
const options = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger = () => { };
function setup(api, log) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log(`Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`);
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log(`Order ${rowKey} save failed: ${reason}. Its marks stay`);
}),
];
return () => offs.forEach((off) => off());
}
const actions = {
saveAll: async (api) => {
const { saved, failed } = await api.saveDetails();
logger(`Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`);
},
saveFirst: async (api) => {
const { saved, failed } = await api.saveDetails(1);
logger(`Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`);
},
};
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('saveAll').addEventListener('click', () => actions.saveAll(api));
document.getElementById('saveFirst').addEventListener('click', () => actions.saveFirst(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.saveAll(api)}
>Save all</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.saveFirst(api)}
>Save order 1</button>
</div>
<Grid style={{ height: 480 }} ref={gridRef} options={options} />
</>
);
}import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v: unknown) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// A save function that waits 300 ms instead of calling a server. Order 3 fails on purpose.
const save = ({ rowKey }: { rowKey: unknown }): Promise<void> =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3) reject(new Error('server error'));
else resolve();
}, 300);
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log(`Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`);
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log(`Order ${rowKey} save failed: ${reason}. Its marks stay`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
saveAll: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails();
logger(`Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`);
},
saveFirst: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails(1);
logger(`Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.saveAll(api)">Save all</button>
<button
type="button"
:disabled="!api"
@click="api && actions.saveFirst(api)"
>Save order 1</button>
</div>
<Grid style="height: 480px" :options="options" @ready="onReady" />
</template>import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v: unknown) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// A save function that waits 300 ms instead of calling a server. Order 3 fails on purpose.
const save = ({ rowKey }: { rowKey: unknown }): Promise<void> =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3) reject(new Error('server error'));
else resolve();
}, 300);
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log(`Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`);
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log(`Order ${rowKey} save failed: ${reason}. Its marks stay`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
saveAll: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails();
logger(`Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`);
},
saveFirst: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails(1);
logger(`Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.saveAll(api)"
>Save all</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.saveFirst(api)"
>Save order 1</button>
</div>
<mx-grid style="height: 480px" [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 { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v: unknown) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// A save function that waits 300 ms instead of calling a server. Order 3 fails on purpose.
const save = ({ rowKey }: { rowKey: unknown }): Promise<void> =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (rowKey === 3) reject(new Error('server error'));
else resolve();
}, 300);
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const offs = [
api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
log(`Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`);
}),
api.on('detailSaveFailed', ({ rowKey, error }) => {
const reason = error instanceof Error ? error.message : String(error);
log(`Order ${rowKey} save failed: ${reason}. Its marks stay`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
saveAll: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails();
logger(`Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`);
},
saveFirst: async (api: GridApi<Row>) => {
const { saved, failed } = await api.saveDetails(1);
logger(`Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`);
},
};