주문 줄을 더하면 주문 번호 자동으로 채우기Fill the order ID automatically on new lines
상세 패널 안 그리드에 주문 번호(orderId) 없이 줄을 더해도 마스터 주문의 id가 자동으로 들어가요. keyFill 옵션 한 줄이면 돼요.Add a line without an order ID (orderId) to the grid inside a detail panel and the master order's id is filled in automatically. One keyFill option does it.
코드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="addLine">줄 더하기</button>
<button type="button" id="showLines">줄 확인</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('addLine').addEventListener('click', () => actions.addLine(api));
document.getElementById('showLines').addEventListener('click', () => actions.showLines(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')}원`;
// 마스터 번호별로 패널 안 그리드를 모아 둬요. 버튼이 이 목록으로 줄을 더해요.
const inner = new Map();
let nextId = 100;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = () => {
let grid = null;
let off;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'item', title: '상품', width: 140, editable: true },
{ 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} 주문 줄`,
});
inner.set(id, grid);
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
export const options = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
// 안쪽 그리드에 새로 넣은 행의 orderId를 마스터의 id로 채워요.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
export const actions = {
addLine: (api) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger({ ko: '먼저 주문 하나를 펼쳐 주세요', en: 'Open an order first' });
return;
}
// orderId 없이 넣어요. 그리드가 마스터의 id로 채워 줘요.
grid.addRows([{ id: nextId++, item: '새 상품', qty: 1, price: 1000 }]);
logger({
ko: `${row.id}번 주문에 orderId 없이 줄을 더했어요`,
en: `Added a line to order ${row.id} without orderId`,
});
},
showLines: (_api) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};<!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="addLine">줄 더하기</button>
<button type="button" id="showLines">줄 확인</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')}원`;
// 마스터 번호별로 패널 안 그리드를 모아 둬요. 버튼이 이 목록으로 줄을 더해요.
const inner = new Map();
let nextId = 100;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = () => {
let grid = null;
let off;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'item', title: '상품', width: 140, editable: true },
{ 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} 주문 줄`,
});
inner.set(id, grid);
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
const options = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
// 안쪽 그리드에 새로 넣은 행의 orderId를 마스터의 id로 채워요.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger = () => { };
function setup(api, log) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
const actions = {
addLine: (api) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger({ ko: '먼저 주문 하나를 펼쳐 주세요', en: 'Open an order first' });
return;
}
// orderId 없이 넣어요. 그리드가 마스터의 id로 채워 줘요.
grid.addRows([{ id: nextId++, item: '새 상품', qty: 1, price: 1000 }]);
logger({
ko: `${row.id}번 주문에 orderId 없이 줄을 더했어요`,
en: `Added a line to order ${row.id} without orderId`,
});
},
showLines: (_api) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};
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('addLine').addEventListener('click', () => actions.addLine(api));
document.getElementById('showLines').addEventListener('click', () => actions.showLines(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.addLine(api)}
>줄 더하기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.showLines(api)}
>줄 확인</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')}원`;
// 마스터 번호별로 패널 안 그리드를 모아 둬요. 버튼이 이 목록으로 줄을 더해요.
const inner = new Map<number, GridApi<Line>>();
let nextId = 100;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'item', title: '상품', width: 140, editable: true },
{ 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} 주문 줄`,
});
inner.set(id, grid);
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
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',
// 안쪽 그리드에 새로 넣은 행의 orderId를 마스터의 id로 채워요.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
export const actions = {
addLine: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger({ ko: '먼저 주문 하나를 펼쳐 주세요', en: 'Open an order first' });
return;
}
// orderId 없이 넣어요. 그리드가 마스터의 id로 채워 줘요.
grid.addRows([{ id: nextId++, item: '새 상품', qty: 1, price: 1000 } as Line]);
logger({
ko: `${row.id}번 주문에 orderId 없이 줄을 더했어요`,
en: `Added a line to order ${row.id} without orderId`,
});
},
showLines: (_api: GridApi<Row>) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};버튼을 누르면 이 예제의 코드가 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.addLine(api)">줄 더하기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.showLines(api)"
>줄 확인</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')}원`;
// 마스터 번호별로 패널 안 그리드를 모아 둬요. 버튼이 이 목록으로 줄을 더해요.
const inner = new Map<number, GridApi<Line>>();
let nextId = 100;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'item', title: '상품', width: 140, editable: true },
{ 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} 주문 줄`,
});
inner.set(id, grid);
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
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',
// 안쪽 그리드에 새로 넣은 행의 orderId를 마스터의 id로 채워요.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
export const actions = {
addLine: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger({ ko: '먼저 주문 하나를 펼쳐 주세요', en: 'Open an order first' });
return;
}
// orderId 없이 넣어요. 그리드가 마스터의 id로 채워 줘요.
grid.addRows([{ id: nextId++, item: '새 상품', qty: 1, price: 1000 } as Line]);
logger({
ko: `${row.id}번 주문에 orderId 없이 줄을 더했어요`,
en: `Added a line to order ${row.id} without orderId`,
});
},
showLines: (_api: GridApi<Row>) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};버튼을 누르면 이 예제의 코드가 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.addLine(api)"
>줄 더하기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.showLines(api)"
>줄 확인</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')}원`;
// 마스터 번호별로 패널 안 그리드를 모아 둬요. 버튼이 이 목록으로 줄을 더해요.
const inner = new Map<number, GridApi<Line>>();
let nextId = 100;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'item', title: '상품', width: 140, editable: true },
{ 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} 주문 줄`,
});
inner.set(id, grid);
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
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',
// 안쪽 그리드에 새로 넣은 행의 orderId를 마스터의 id로 채워요.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
export const actions = {
addLine: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger({ ko: '먼저 주문 하나를 펼쳐 주세요', en: 'Open an order first' });
return;
}
// orderId 없이 넣어요. 그리드가 마스터의 id로 채워 줘요.
grid.addRows([{ id: nextId++, item: '새 상품', qty: 1, price: 1000 } as Line]);
logger({
ko: `${row.id}번 주문에 orderId 없이 줄을 더했어요`,
en: `Added a line to order ${row.id} without orderId`,
});
},
showLines: (_api: GridApi<Row>) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};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="addLine">Add line</button>
<button type="button" id="showLines">Show lines</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('addLine').addEventListener('click', () => actions.addLine(api));
document.getElementById('showLines').addEventListener('click', () => actions.showLines(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)}`;
// Keeps the grid of each panel by master id. The buttons use it to add lines.
const inner = new Map();
let nextId = 100;
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = () => {
let grid = null;
let off;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'item', title: 'Item', width: 140, editable: true },
{ 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`,
});
inner.set(id, grid);
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
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',
// A new row in the inner grid gets its orderId from the master id.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
export const actions = {
addLine: (api) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger('Open an order first');
return;
}
// Added without orderId. The grid fills it from the master id.
grid.addRows([{ id: nextId++, item: 'New item', qty: 1, price: 1 }]);
logger(`Added a line to order ${row.id} without orderId`);
},
showLines: (_api) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Fill the order ID automatically on new lines</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="addLine">Add line</button>
<button type="button" id="showLines">Show lines</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)}`;
// Keeps the grid of each panel by master id. The buttons use it to add lines.
const inner = new Map();
let nextId = 100;
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = () => {
let grid = null;
let off;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'item', title: 'Item', width: 140, editable: true },
{ 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`,
});
inner.set(id, grid);
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
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',
// A new row in the inner grid gets its orderId from the master id.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger = () => { };
function setup(api, log) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
const actions = {
addLine: (api) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger('Open an order first');
return;
}
// Added without orderId. The grid fills it from the master id.
grid.addRows([{ id: nextId++, item: 'New item', qty: 1, price: 1 }]);
logger(`Added a line to order ${row.id} without orderId`);
},
showLines: (_api) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};
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('addLine').addEventListener('click', () => actions.addLine(api));
document.getElementById('showLines').addEventListener('click', () => actions.showLines(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.addLine(api)}
>Add line</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.showLines(api)}
>Show lines</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)}`;
// Keeps the grid of each panel by master id. The buttons use it to add lines.
const inner = new Map<number, GridApi<Line>>();
let nextId = 100;
// 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;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'item', title: 'Item', width: 140, editable: true },
{ 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`,
});
inner.set(id, grid);
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
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',
// A new row in the inner grid gets its orderId from the master id.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
export const actions = {
addLine: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger('Open an order first');
return;
}
// Added without orderId. The grid fills it from the master id.
grid.addRows([{ id: nextId++, item: 'New item', qty: 1, price: 1 } as Line]);
logger(`Added a line to order ${row.id} without orderId`);
},
showLines: (_api: GridApi<Row>) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};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.addLine(api)">Add line</button>
<button
type="button"
:disabled="!api"
@click="api && actions.showLines(api)"
>Show lines</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)}`;
// Keeps the grid of each panel by master id. The buttons use it to add lines.
const inner = new Map<number, GridApi<Line>>();
let nextId = 100;
// 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;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'item', title: 'Item', width: 140, editable: true },
{ 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`,
});
inner.set(id, grid);
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
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',
// A new row in the inner grid gets its orderId from the master id.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
export const actions = {
addLine: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger('Open an order first');
return;
}
// Added without orderId. The grid fills it from the master id.
grid.addRows([{ id: nextId++, item: 'New item', qty: 1, price: 1 } as Line]);
logger(`Added a line to order ${row.id} without orderId`);
},
showLines: (_api: GridApi<Row>) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};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.addLine(api)"
>Add line</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.showLines(api)"
>Show lines</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)}`;
// Keeps the grid of each panel by master id. The buttons use it to add lines.
const inner = new Map<number, GridApi<Line>>();
let nextId = 100;
// 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;
let id = 0;
return {
mount(element, { row, attachGrid }) {
id = row.id;
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '150px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'orderId', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'item', title: 'Item', width: 140, editable: true },
{ 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`,
});
inner.set(id, grid);
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
inner.delete(id);
grid?.destroy();
grid = null;
},
};
};
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',
// A new row in the inner grid gets its orderId from the master id.
detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
export const actions = {
addLine: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
const grid = row === undefined ? undefined : inner.get(row.id);
if (row === undefined || grid === undefined) {
logger('Open an order first');
return;
}
// Added without orderId. The grid fills it from the master id.
grid.addRows([{ id: nextId++, item: 'New item', qty: 1, price: 1 } as Line]);
logger(`Added a line to order ${row.id} without orderId`);
},
showLines: (_api: GridApi<Row>) => {
for (const [id, grid] of inner) {
for (const l of grid.getRows()) {
logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
}
}
},
};