줄 안의 버튼: 상세 보기와 삭제Buttons inside a row: details and delete
표의 줄마다 "상세"와 "삭제" 버튼을 넣어요. 버튼을 누르면 그 줄에 대한 일을 해요. 지운 줄은 다시 넣을 수 있어요.Put "Details" and "Delete" buttons in every row. Pressing one acts on that row. Deleted rows can be put back.
코드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="restore">지운 줄 되돌리기</button>
</div>
<div id="grid" style="height: 260px"></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('restore').addEventListener('click', () => actions.restore(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el) => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0)
return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0;
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
// 줄마다 버튼 두 개를 그려요. 버튼에는 data-action만 달고, 누름은 setup에서 cellClicked 한 곳에서 받아 그리드 기능을 불러요.
// 칸마다 따로 이벤트를 달지 않아서 스크롤해도 가벼워요.
const actionsCell = () => {
let box;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', L('상세', 'Details'), L('청구서 내용을 봐요', 'View the invoice')],
['delete', L('삭제', 'Delete'), L('이 청구서를 지워요', 'Delete this invoice')],
]) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// 버튼 이름에 줄의 청구서 번호를 넣어서, 화면 읽기 프로그램이 "INV-401 상세"처럼 읽게 해요.
update(ctx) {
for (const button of box.querySelectorAll('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() { },
};
};
const initial = [
{ id: 1, invoice: 'INV-401', customer: '한빛푸드', total: 1280000 },
{ id: 2, invoice: 'INV-402', customer: '파란마켓', total: 460000 },
{ id: 3, invoice: 'INV-403', customer: '단풍상회', total: 3150000 },
{ id: 4, invoice: 'INV-404', customer: '바다유통', total: 90000 },
];
export const options = {
columns: [
{ id: 'invoice', title: '청구서', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{
id: 'total',
title: '금액(원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{
id: 'actions',
title: '작업',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted = [];
let say = () => { };
export function setup(api, log) {
say = log;
deleted = [];
log({
ko: '"상세"는 내용을 기록에 보여 주고, "삭제"는 그 줄을 지워요.',
en: '"상세" (Details) shows the contents in the log, and "삭제" (Delete) removes the row.',
});
return api.on('cellClicked', (e) => {
const button = e.event.target?.closest('button[data-action]');
if (e.columnId !== 'actions' || !button)
return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest('[role="grid"]');
api.removeRows([e.rowKey]);
// 지운 뒤 포커스가 다음 줄의 "삭제" 버튼으로 옮겨 가면 Enter 한 번에 또 지워져요. 포커스를 칸(청구서)에 둬요.
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near)
api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // 키보드 포커스가 버튼에 남아 있으면 Enter 한 번에 또 지워져요
log({
ko: `${e.row.invoice}${eulReul(e.row.invoice)} 지웠어요. "지운 줄 되돌리기"로 다시 넣을 수 있어요.`,
en: `Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`,
});
}
else {
log({
ko: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('ko-KR')}원`,
en: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('en-US')} KRW`,
});
}
});
}
export const actions = {
restore: (api) => {
if (!deleted.length)
return say({ ko: '되돌릴 청구서가 없어요.', en: 'No invoice to restore.' });
const rows = deleted;
deleted = [];
// 앞쪽 자리부터 차례로 넣어서, 지우기 전 위치로 돌아가요.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say({
ko: `지운 청구서 ${rows.length}개를 원래 자리에 다시 넣었어요.`,
en: `Put the ${rows.length} deleted invoices back in their original places.`,
});
},
};<!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="restore">지운 줄 되돌리기</button>
</div>
<div id="grid" style="height: 260px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el) => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0)
return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0;
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
// 줄마다 버튼 두 개를 그려요. 버튼에는 data-action만 달고, 누름은 setup에서 cellClicked 한 곳에서 받아 그리드 기능을 불러요.
// 칸마다 따로 이벤트를 달지 않아서 스크롤해도 가벼워요.
const actionsCell = () => {
let box;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', L('상세', 'Details'), L('청구서 내용을 봐요', 'View the invoice')],
['delete', L('삭제', 'Delete'), L('이 청구서를 지워요', 'Delete this invoice')],
]) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// 버튼 이름에 줄의 청구서 번호를 넣어서, 화면 읽기 프로그램이 "INV-401 상세"처럼 읽게 해요.
update(ctx) {
for (const button of box.querySelectorAll('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() { },
};
};
const initial = [
{ id: 1, invoice: 'INV-401', customer: '한빛푸드', total: 1280000 },
{ id: 2, invoice: 'INV-402', customer: '파란마켓', total: 460000 },
{ id: 3, invoice: 'INV-403', customer: '단풍상회', total: 3150000 },
{ id: 4, invoice: 'INV-404', customer: '바다유통', total: 90000 },
];
const options = {
columns: [
{ id: 'invoice', title: '청구서', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{
id: 'total',
title: '금액(원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{
id: 'actions',
title: '작업',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted = [];
let say = () => { };
function setup(api, log) {
say = log;
deleted = [];
log({
ko: '"상세"는 내용을 기록에 보여 주고, "삭제"는 그 줄을 지워요.',
en: '"상세" (Details) shows the contents in the log, and "삭제" (Delete) removes the row.',
});
return api.on('cellClicked', (e) => {
const button = e.event.target?.closest('button[data-action]');
if (e.columnId !== 'actions' || !button)
return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest('[role="grid"]');
api.removeRows([e.rowKey]);
// 지운 뒤 포커스가 다음 줄의 "삭제" 버튼으로 옮겨 가면 Enter 한 번에 또 지워져요. 포커스를 칸(청구서)에 둬요.
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near)
api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // 키보드 포커스가 버튼에 남아 있으면 Enter 한 번에 또 지워져요
log({
ko: `${e.row.invoice}${eulReul(e.row.invoice)} 지웠어요. "지운 줄 되돌리기"로 다시 넣을 수 있어요.`,
en: `Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`,
});
}
else {
log({
ko: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('ko-KR')}원`,
en: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('en-US')} KRW`,
});
}
});
}
const actions = {
restore: (api) => {
if (!deleted.length)
return say({ ko: '되돌릴 청구서가 없어요.', en: 'No invoice to restore.' });
const rows = deleted;
deleted = [];
// 앞쪽 자리부터 차례로 넣어서, 지우기 전 위치로 돌아가요.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say({
ko: `지운 청구서 ${rows.length}개를 원래 자리에 다시 넣었어요.`,
en: `Put the ${rows.length} deleted invoices back in their original places.`,
});
},
};
options.ariaLabel = "줄 안의 버튼: 상세 보기와 삭제";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('restore').addEventListener('click', () => actions.restore(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.restore(api)}
>지운 줄 되돌리기</button>
</div>
<Grid style={{ height: 260 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
export interface Row {
id: number;
invoice: string;
customer: string;
total: number;
}
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0) return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0;
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word: string): string => (batchim(word) ? '을' : '를');
// 줄마다 버튼 두 개를 그려요. 버튼에는 data-action만 달고, 누름은 setup에서 cellClicked 한 곳에서 받아 그리드 기능을 불러요.
// 칸마다 따로 이벤트를 달지 않아서 스크롤해도 가벼워요.
const actionsCell = (): CellRendererAdapter<Row> => {
let box: HTMLElement;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', L('상세', 'Details'), L('청구서 내용을 봐요', 'View the invoice')],
['delete', L('삭제', 'Delete'), L('이 청구서를 지워요', 'Delete this invoice')],
] as const) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// 버튼 이름에 줄의 청구서 번호를 넣어서, 화면 읽기 프로그램이 "INV-401 상세"처럼 읽게 해요.
update(ctx) {
for (const button of box.querySelectorAll<HTMLButtonElement>('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() {},
};
};
const initial: Row[] = [
{ id: 1, invoice: 'INV-401', customer: '한빛푸드', total: 1280000 },
{ id: 2, invoice: 'INV-402', customer: '파란마켓', total: 460000 },
{ id: 3, invoice: 'INV-403', customer: '단풍상회', total: 3150000 },
{ id: 4, invoice: 'INV-404', customer: '바다유통', total: 90000 },
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'invoice', title: '청구서', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{
id: 'total',
title: '금액(원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{
id: 'actions',
title: '작업',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted: { row: Row; index: number }[] = [];
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
deleted = [];
log({
ko: '"상세"는 내용을 기록에 보여 주고, "삭제"는 그 줄을 지워요.',
en: '"상세" (Details) shows the contents in the log, and "삭제" (Delete) removes the row.',
});
return api.on('cellClicked', (e) => {
const button = (e.event.target as HTMLElement | null)?.closest<HTMLElement>(
'button[data-action]',
);
if (e.columnId !== 'actions' || !button) return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest<HTMLElement>('[role="grid"]');
api.removeRows([e.rowKey]);
// 지운 뒤 포커스가 다음 줄의 "삭제" 버튼으로 옮겨 가면 Enter 한 번에 또 지워져요. 포커스를 칸(청구서)에 둬요.
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near) api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // 키보드 포커스가 버튼에 남아 있으면 Enter 한 번에 또 지워져요
log({
ko: `${e.row.invoice}${eulReul(e.row.invoice)} 지웠어요. "지운 줄 되돌리기"로 다시 넣을 수 있어요.`,
en: `Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`,
});
} else {
log({
ko: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('ko-KR')}원`,
en: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('en-US')} KRW`,
});
}
});
}
export const actions = {
restore: (api: GridApi<Row>) => {
if (!deleted.length)
return say({ ko: '되돌릴 청구서가 없어요.', en: 'No invoice to restore.' });
const rows = deleted;
deleted = [];
// 앞쪽 자리부터 차례로 넣어서, 지우기 전 위치로 돌아가요.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say({
ko: `지운 청구서 ${rows.length}개를 원래 자리에 다시 넣었어요.`,
en: `Put the ${rows.length} deleted invoices back in their original places.`,
});
},
};버튼을 누르면 이 예제의 코드가 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.restore(api)">지운 줄 되돌리기</button>
</div>
<Grid style="height: 260px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
export interface Row {
id: number;
invoice: string;
customer: string;
total: number;
}
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0) return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0;
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word: string): string => (batchim(word) ? '을' : '를');
// 줄마다 버튼 두 개를 그려요. 버튼에는 data-action만 달고, 누름은 setup에서 cellClicked 한 곳에서 받아 그리드 기능을 불러요.
// 칸마다 따로 이벤트를 달지 않아서 스크롤해도 가벼워요.
const actionsCell = (): CellRendererAdapter<Row> => {
let box: HTMLElement;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', L('상세', 'Details'), L('청구서 내용을 봐요', 'View the invoice')],
['delete', L('삭제', 'Delete'), L('이 청구서를 지워요', 'Delete this invoice')],
] as const) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// 버튼 이름에 줄의 청구서 번호를 넣어서, 화면 읽기 프로그램이 "INV-401 상세"처럼 읽게 해요.
update(ctx) {
for (const button of box.querySelectorAll<HTMLButtonElement>('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() {},
};
};
const initial: Row[] = [
{ id: 1, invoice: 'INV-401', customer: '한빛푸드', total: 1280000 },
{ id: 2, invoice: 'INV-402', customer: '파란마켓', total: 460000 },
{ id: 3, invoice: 'INV-403', customer: '단풍상회', total: 3150000 },
{ id: 4, invoice: 'INV-404', customer: '바다유통', total: 90000 },
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'invoice', title: '청구서', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{
id: 'total',
title: '금액(원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{
id: 'actions',
title: '작업',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted: { row: Row; index: number }[] = [];
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
deleted = [];
log({
ko: '"상세"는 내용을 기록에 보여 주고, "삭제"는 그 줄을 지워요.',
en: '"상세" (Details) shows the contents in the log, and "삭제" (Delete) removes the row.',
});
return api.on('cellClicked', (e) => {
const button = (e.event.target as HTMLElement | null)?.closest<HTMLElement>(
'button[data-action]',
);
if (e.columnId !== 'actions' || !button) return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest<HTMLElement>('[role="grid"]');
api.removeRows([e.rowKey]);
// 지운 뒤 포커스가 다음 줄의 "삭제" 버튼으로 옮겨 가면 Enter 한 번에 또 지워져요. 포커스를 칸(청구서)에 둬요.
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near) api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // 키보드 포커스가 버튼에 남아 있으면 Enter 한 번에 또 지워져요
log({
ko: `${e.row.invoice}${eulReul(e.row.invoice)} 지웠어요. "지운 줄 되돌리기"로 다시 넣을 수 있어요.`,
en: `Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`,
});
} else {
log({
ko: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('ko-KR')}원`,
en: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('en-US')} KRW`,
});
}
});
}
export const actions = {
restore: (api: GridApi<Row>) => {
if (!deleted.length)
return say({ ko: '되돌릴 청구서가 없어요.', en: 'No invoice to restore.' });
const rows = deleted;
deleted = [];
// 앞쪽 자리부터 차례로 넣어서, 지우기 전 위치로 돌아가요.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say({
ko: `지운 청구서 ${rows.length}개를 원래 자리에 다시 넣었어요.`,
en: `Put the ${rows.length} deleted invoices back in their original places.`,
});
},
};버튼을 누르면 이 예제의 코드가 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.restore(api)"
>지운 줄 되돌리기</button>
</div>
<mx-grid style="height: 260px" [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 { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
export interface Row {
id: number;
invoice: string;
customer: string;
total: number;
}
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0) return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0;
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word: string): string => (batchim(word) ? '을' : '를');
// 줄마다 버튼 두 개를 그려요. 버튼에는 data-action만 달고, 누름은 setup에서 cellClicked 한 곳에서 받아 그리드 기능을 불러요.
// 칸마다 따로 이벤트를 달지 않아서 스크롤해도 가벼워요.
const actionsCell = (): CellRendererAdapter<Row> => {
let box: HTMLElement;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', L('상세', 'Details'), L('청구서 내용을 봐요', 'View the invoice')],
['delete', L('삭제', 'Delete'), L('이 청구서를 지워요', 'Delete this invoice')],
] as const) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// 버튼 이름에 줄의 청구서 번호를 넣어서, 화면 읽기 프로그램이 "INV-401 상세"처럼 읽게 해요.
update(ctx) {
for (const button of box.querySelectorAll<HTMLButtonElement>('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() {},
};
};
const initial: Row[] = [
{ id: 1, invoice: 'INV-401', customer: '한빛푸드', total: 1280000 },
{ id: 2, invoice: 'INV-402', customer: '파란마켓', total: 460000 },
{ id: 3, invoice: 'INV-403', customer: '단풍상회', total: 3150000 },
{ id: 4, invoice: 'INV-404', customer: '바다유통', total: 90000 },
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'invoice', title: '청구서', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{
id: 'total',
title: '금액(원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{
id: 'actions',
title: '작업',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted: { row: Row; index: number }[] = [];
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
deleted = [];
log({
ko: '"상세"는 내용을 기록에 보여 주고, "삭제"는 그 줄을 지워요.',
en: '"상세" (Details) shows the contents in the log, and "삭제" (Delete) removes the row.',
});
return api.on('cellClicked', (e) => {
const button = (e.event.target as HTMLElement | null)?.closest<HTMLElement>(
'button[data-action]',
);
if (e.columnId !== 'actions' || !button) return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest<HTMLElement>('[role="grid"]');
api.removeRows([e.rowKey]);
// 지운 뒤 포커스가 다음 줄의 "삭제" 버튼으로 옮겨 가면 Enter 한 번에 또 지워져요. 포커스를 칸(청구서)에 둬요.
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near) api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // 키보드 포커스가 버튼에 남아 있으면 Enter 한 번에 또 지워져요
log({
ko: `${e.row.invoice}${eulReul(e.row.invoice)} 지웠어요. "지운 줄 되돌리기"로 다시 넣을 수 있어요.`,
en: `Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`,
});
} else {
log({
ko: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('ko-KR')}원`,
en: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('en-US')} KRW`,
});
}
});
}
export const actions = {
restore: (api: GridApi<Row>) => {
if (!deleted.length)
return say({ ko: '되돌릴 청구서가 없어요.', en: 'No invoice to restore.' });
const rows = deleted;
deleted = [];
// 앞쪽 자리부터 차례로 넣어서, 지우기 전 위치로 돌아가요.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say({
ko: `지운 청구서 ${rows.length}개를 원래 자리에 다시 넣었어요.`,
en: `Put the ${rows.length} deleted invoices back in their original places.`,
});
},
};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="restore">Put back deleted rows</button>
</div>
<div id="grid" style="height: 260px"></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('restore').addEventListener('click', () => actions.restore(api));// Tells whether this is a touch screen (phone). On such screens the tap targets grow to 40px or more.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el) => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// Draws two buttons per row. The buttons only carry data-action; presses are handled in one cellClicked handler in setup, which calls grid features.
// No per-cell listeners, so scrolling stays light.
const actionsCell = () => {
let box;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', 'Details', 'View the invoice'],
['delete', 'Delete', 'Delete this invoice'],
]) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// Put the row's invoice number in the button name so a screen reader says e.g. "INV-401 Details".
update(ctx) {
for (const button of box.querySelectorAll('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() { },
};
};
const initial = [
{ id: 1, invoice: 'INV-401', customer: 'Bright Foods', total: 1280 },
{ id: 2, invoice: 'INV-402', customer: 'Blue Market', total: 460 },
{ id: 3, invoice: 'INV-403', customer: 'Maple Trading', total: 3150 },
{ id: 4, invoice: 'INV-404', customer: 'Ocean Distribution', total: 90 },
];
export const options = {
columns: [
{ id: 'invoice', title: 'Invoice', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{
id: 'total',
title: 'Total ($)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{
id: 'actions',
title: 'Actions',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted = [];
let say = () => { };
export function setup(api, log) {
say = log;
deleted = [];
log('"Details" shows the contents in the log, and "Delete" removes the row.');
return api.on('cellClicked', (e) => {
const button = e.event.target?.closest('button[data-action]');
if (e.columnId !== 'actions' || !button)
return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest('[role="grid"]');
api.removeRows([e.rowKey]);
// If focus moved to the next row's "Delete" button after removing, one Enter would delete again. Keep focus on a cell (invoice).
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near)
api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // If keyboard focus stays on a button, one Enter would delete again
log(`Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`);
}
else {
log(`${e.row.invoice}: ${e.row.customer}, $${e.row.total.toLocaleString('en-US')}`);
}
});
}
export const actions = {
restore: (api) => {
if (!deleted.length)
return say('No invoice to restore.');
const rows = deleted;
deleted = [];
// Insert from the front so each row returns to its position before deletion.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say(`Put the ${rows.length} deleted invoices back in their original places.`);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Buttons inside a row: details and delete</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="restore">Put back deleted rows</button>
</div>
<div id="grid" style="height: 260px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// Tells whether this is a touch screen (phone). On such screens the tap targets grow to 40px or more.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el) => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// Draws two buttons per row. The buttons only carry data-action; presses are handled in one cellClicked handler in setup, which calls grid features.
// No per-cell listeners, so scrolling stays light.
const actionsCell = () => {
let box;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', 'Details', 'View the invoice'],
['delete', 'Delete', 'Delete this invoice'],
]) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// Put the row's invoice number in the button name so a screen reader says e.g. "INV-401 Details".
update(ctx) {
for (const button of box.querySelectorAll('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() { },
};
};
const initial = [
{ id: 1, invoice: 'INV-401', customer: 'Bright Foods', total: 1280 },
{ id: 2, invoice: 'INV-402', customer: 'Blue Market', total: 460 },
{ id: 3, invoice: 'INV-403', customer: 'Maple Trading', total: 3150 },
{ id: 4, invoice: 'INV-404', customer: 'Ocean Distribution', total: 90 },
];
const options = {
columns: [
{ id: 'invoice', title: 'Invoice', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{
id: 'total',
title: 'Total ($)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{
id: 'actions',
title: 'Actions',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted = [];
let say = () => { };
function setup(api, log) {
say = log;
deleted = [];
log('"Details" shows the contents in the log, and "Delete" removes the row.');
return api.on('cellClicked', (e) => {
const button = e.event.target?.closest('button[data-action]');
if (e.columnId !== 'actions' || !button)
return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest('[role="grid"]');
api.removeRows([e.rowKey]);
// If focus moved to the next row's "Delete" button after removing, one Enter would delete again. Keep focus on a cell (invoice).
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near)
api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // If keyboard focus stays on a button, one Enter would delete again
log(`Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`);
}
else {
log(`${e.row.invoice}: ${e.row.customer}, $${e.row.total.toLocaleString('en-US')}`);
}
});
}
const actions = {
restore: (api) => {
if (!deleted.length)
return say('No invoice to restore.');
const rows = deleted;
deleted = [];
// Insert from the front so each row returns to its position before deletion.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say(`Put the ${rows.length} deleted invoices back in their original places.`);
},
};
options.ariaLabel = "Buttons inside a row: details and delete";
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('restore').addEventListener('click', () => actions.restore(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.restore(api)}
>Put back deleted rows</button>
</div>
<Grid style={{ height: 260 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
// Tells whether this is a touch screen (phone). On such screens the tap targets grow to 40px or more.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
export interface Row {
id: number;
invoice: string;
customer: string;
total: number;
}
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// Draws two buttons per row. The buttons only carry data-action; presses are handled in one cellClicked handler in setup, which calls grid features.
// No per-cell listeners, so scrolling stays light.
const actionsCell = (): CellRendererAdapter<Row> => {
let box: HTMLElement;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', 'Details', 'View the invoice'],
['delete', 'Delete', 'Delete this invoice'],
] as const) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// Put the row's invoice number in the button name so a screen reader says e.g. "INV-401 Details".
update(ctx) {
for (const button of box.querySelectorAll<HTMLButtonElement>('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() {},
};
};
const initial: Row[] = [
{ id: 1, invoice: 'INV-401', customer: 'Bright Foods', total: 1280 },
{ id: 2, invoice: 'INV-402', customer: 'Blue Market', total: 460 },
{ id: 3, invoice: 'INV-403', customer: 'Maple Trading', total: 3150 },
{ id: 4, invoice: 'INV-404', customer: 'Ocean Distribution', total: 90 },
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'invoice', title: 'Invoice', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{
id: 'total',
title: 'Total ($)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{
id: 'actions',
title: 'Actions',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted: { row: Row; index: number }[] = [];
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
deleted = [];
log('"Details" shows the contents in the log, and "Delete" removes the row.');
return api.on('cellClicked', (e) => {
const button = (e.event.target as HTMLElement | null)?.closest<HTMLElement>(
'button[data-action]',
);
if (e.columnId !== 'actions' || !button) return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest<HTMLElement>('[role="grid"]');
api.removeRows([e.rowKey]);
// If focus moved to the next row's "Delete" button after removing, one Enter would delete again. Keep focus on a cell (invoice).
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near) api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // If keyboard focus stays on a button, one Enter would delete again
log(`Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`);
} else {
log(`${e.row.invoice}: ${e.row.customer}, $${e.row.total.toLocaleString('en-US')}`);
}
});
}
export const actions = {
restore: (api: GridApi<Row>) => {
if (!deleted.length) return say('No invoice to restore.');
const rows = deleted;
deleted = [];
// Insert from the front so each row returns to its position before deletion.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say(`Put the ${rows.length} deleted invoices back in their original places.`);
},
};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.restore(api)">Put back deleted rows</button>
</div>
<Grid style="height: 260px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
// Tells whether this is a touch screen (phone). On such screens the tap targets grow to 40px or more.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
export interface Row {
id: number;
invoice: string;
customer: string;
total: number;
}
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// Draws two buttons per row. The buttons only carry data-action; presses are handled in one cellClicked handler in setup, which calls grid features.
// No per-cell listeners, so scrolling stays light.
const actionsCell = (): CellRendererAdapter<Row> => {
let box: HTMLElement;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', 'Details', 'View the invoice'],
['delete', 'Delete', 'Delete this invoice'],
] as const) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// Put the row's invoice number in the button name so a screen reader says e.g. "INV-401 Details".
update(ctx) {
for (const button of box.querySelectorAll<HTMLButtonElement>('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() {},
};
};
const initial: Row[] = [
{ id: 1, invoice: 'INV-401', customer: 'Bright Foods', total: 1280 },
{ id: 2, invoice: 'INV-402', customer: 'Blue Market', total: 460 },
{ id: 3, invoice: 'INV-403', customer: 'Maple Trading', total: 3150 },
{ id: 4, invoice: 'INV-404', customer: 'Ocean Distribution', total: 90 },
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'invoice', title: 'Invoice', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{
id: 'total',
title: 'Total ($)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{
id: 'actions',
title: 'Actions',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted: { row: Row; index: number }[] = [];
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
deleted = [];
log('"Details" shows the contents in the log, and "Delete" removes the row.');
return api.on('cellClicked', (e) => {
const button = (e.event.target as HTMLElement | null)?.closest<HTMLElement>(
'button[data-action]',
);
if (e.columnId !== 'actions' || !button) return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest<HTMLElement>('[role="grid"]');
api.removeRows([e.rowKey]);
// If focus moved to the next row's "Delete" button after removing, one Enter would delete again. Keep focus on a cell (invoice).
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near) api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // If keyboard focus stays on a button, one Enter would delete again
log(`Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`);
} else {
log(`${e.row.invoice}: ${e.row.customer}, $${e.row.total.toLocaleString('en-US')}`);
}
});
}
export const actions = {
restore: (api: GridApi<Row>) => {
if (!deleted.length) return say('No invoice to restore.');
const rows = deleted;
deleted = [];
// Insert from the front so each row returns to its position before deletion.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say(`Put the ${rows.length} deleted invoices back in their original places.`);
},
};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.restore(api)"
>Put back deleted rows</button>
</div>
<mx-grid style="height: 260px" [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 { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
// Tells whether this is a touch screen (phone). On such screens the tap targets grow to 40px or more.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
export interface Row {
id: number;
invoice: string;
customer: string;
total: number;
}
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// Draws two buttons per row. The buttons only carry data-action; presses are handled in one cellClicked handler in setup, which calls grid features.
// No per-cell listeners, so scrolling stays light.
const actionsCell = (): CellRendererAdapter<Row> => {
let box: HTMLElement;
return {
mount(el, ctx) {
box = centered(el);
for (const [action, label, title] of [
['detail', 'Details', 'View the invoice'],
['delete', 'Delete', 'Delete this invoice'],
] as const) {
const button = document.createElement('button');
button.type = 'button';
button.dataset.action = action;
button.textContent = label;
button.title = title;
button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
box.append(button);
}
this.update(ctx);
},
// Put the row's invoice number in the button name so a screen reader says e.g. "INV-401 Details".
update(ctx) {
for (const button of box.querySelectorAll<HTMLButtonElement>('button[data-action]')) {
button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
}
},
destroy() {},
};
};
const initial: Row[] = [
{ id: 1, invoice: 'INV-401', customer: 'Bright Foods', total: 1280 },
{ id: 2, invoice: 'INV-402', customer: 'Blue Market', total: 460 },
{ id: 3, invoice: 'INV-403', customer: 'Maple Trading', total: 3150 },
{ id: 4, invoice: 'INV-404', customer: 'Ocean Distribution', total: 90 },
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'invoice', title: 'Invoice', width: 100 },
{ id: 'customer', title: 'Customer', width: 110 },
{
id: 'total',
title: 'Total ($)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
{
id: 'actions',
title: 'Actions',
width: 130,
sortable: false,
filterable: false,
getValue: () => '',
cellRenderer: actionsCell,
},
],
rows: initial.map((row) => ({ ...row })),
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted: { row: Row; index: number }[] = [];
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
deleted = [];
log('"Details" shows the contents in the log, and "Delete" removes the row.');
return api.on('cellClicked', (e) => {
const button = (e.event.target as HTMLElement | null)?.closest<HTMLElement>(
'button[data-action]',
);
if (e.columnId !== 'actions' || !button) return;
if (button.dataset.action === 'delete') {
deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
const gridRoot = button.closest<HTMLElement>('[role="grid"]');
api.removeRows([e.rowKey]);
// If focus moved to the next row's "Delete" button after removing, one Enter would delete again. Keep focus on a cell (invoice).
const left = api.getRows();
const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
if (near) api.focusCell(near.id, 'invoice');
gridRoot?.focus(); // If keyboard focus stays on a button, one Enter would delete again
log(`Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`);
} else {
log(`${e.row.invoice}: ${e.row.customer}, $${e.row.total.toLocaleString('en-US')}`);
}
});
}
export const actions = {
restore: (api: GridApi<Row>) => {
if (!deleted.length) return say('No invoice to restore.');
const rows = deleted;
deleted = [];
// Insert from the front so each row returns to its position before deletion.
for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
api.addRows([row], index);
say(`Put the ${rows.length} deleted invoices back in their original places.`);
},
};