고치면 같이 바뀌는 계산 컬럼Calculated columns that follow your edits
분기별 매출만 저장하고 상반기·하반기·연 매출·최대 분기는 그 줄에서 계산해요. 분기 칸을 고치면 계산 컬럼과 맨 아래 합계 줄이 바로 바뀌어요.Only the quarterly sales are stored. First half, second half, yearly total and best quarter are computed per row, and the total row follows every edit.
코드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="showChanges">고친 칸 보기</button>
<button type="button" id="onlyBestQ4">최대 분기가 4분기인 연도만</button>
<button type="button" id="clearFilter">필터 해제</button>
<button type="button" id="rollback">고친 것 되돌리기</button>
</div>
<div id="grid" style="height: 345px"></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('showChanges').addEventListener('click', () => actions.showChanges(api));
document.getElementById('onlyBestQ4').addEventListener('click', () => actions.onlyBestQ4(api));
document.getElementById('clearFilter').addEventListener('click', () => actions.clearFilter(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(api));// 서버가 주는 값은 연도와 1~4분기 매출뿐이에요. 상반기·하반기·연 합계·최대 분기는 저장하지 않고
// getValue로 그 줄에서 계산해요. 1~4분기 칸을 고치면 이 칸들과 맨 아래 합계 줄이 같이 바뀌어요.
const quarters = ['q1', 'q2', 'q3', 'q4'];
const label = ['1분기', '2분기', '3분기', '4분기'];
const sum = (row, keys) => keys.reduce((total, k) => total + row[k], 0);
const million = (value) => `${Number(value).toLocaleString('ko-KR')}`;
const rows = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id, title, extra) => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
export const options = {
columns: [
{ id: 'year', title: '연도', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '상반기', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '하반기', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', '연 매출', { getValue: (row) => sum(row, quarters), width: 110 }),
{
id: 'best',
title: '최대 분기',
width: 100,
align: 'center',
getValue: (row) => label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: '합계' },
};
let say = () => { };
export function setup(api, log) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log({
ko: `${row.year}년 연 매출이 ${sum(row, quarters).toLocaleString('ko-KR')}(백만원)이 됐어요`,
en: `${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} (million KRW)`,
});
});
}
export const actions = {
// 고친 칸만 모아서 보여 줘요(원래 값 → 지금 값).
showChanges: (api) => {
const changes = api.getChanges();
if (!changes.length)
return say({
ko: '아직 고친 칸이 없어요. 1~4분기 칸을 더블클릭해서 고쳐 보세요.',
en: 'No cell edited yet. Double-click a quarter 1-4 cell to edit it.',
});
const lines = changes.flatMap((c) => (c.cells ?? []).map((cell) => `${c.key}년 ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`));
say({
ko: `고친 칸 ${lines.length}개\n${lines.join('\n')}`,
en: `Edited cells: ${lines.length}\n${lines.join('\n')}`,
});
},
onlyBestQ4: (api) => api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: '4분기' }],
}),
clearFilter: (api) => api.setFilterModel(null),
rollback: (api) => api.rollbackChanges(),
};<!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="showChanges">고친 칸 보기</button>
<button type="button" id="onlyBestQ4">최대 분기가 4분기인 연도만</button>
<button type="button" id="clearFilter">필터 해제</button>
<button type="button" id="rollback">고친 것 되돌리기</button>
</div>
<div id="grid" style="height: 345px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 서버가 주는 값은 연도와 1~4분기 매출뿐이에요. 상반기·하반기·연 합계·최대 분기는 저장하지 않고
// getValue로 그 줄에서 계산해요. 1~4분기 칸을 고치면 이 칸들과 맨 아래 합계 줄이 같이 바뀌어요.
const quarters = ['q1', 'q2', 'q3', 'q4'];
const label = ['1분기', '2분기', '3분기', '4분기'];
const sum = (row, keys) => keys.reduce((total, k) => total + row[k], 0);
const million = (value) => `${Number(value).toLocaleString('ko-KR')}`;
const rows = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id, title, extra) => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
const options = {
columns: [
{ id: 'year', title: '연도', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '상반기', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '하반기', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', '연 매출', { getValue: (row) => sum(row, quarters), width: 110 }),
{
id: 'best',
title: '최대 분기',
width: 100,
align: 'center',
getValue: (row) => label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: '합계' },
};
let say = () => { };
function setup(api, log) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log({
ko: `${row.year}년 연 매출이 ${sum(row, quarters).toLocaleString('ko-KR')}(백만원)이 됐어요`,
en: `${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} (million KRW)`,
});
});
}
const actions = {
// 고친 칸만 모아서 보여 줘요(원래 값 → 지금 값).
showChanges: (api) => {
const changes = api.getChanges();
if (!changes.length)
return say({
ko: '아직 고친 칸이 없어요. 1~4분기 칸을 더블클릭해서 고쳐 보세요.',
en: 'No cell edited yet. Double-click a quarter 1-4 cell to edit it.',
});
const lines = changes.flatMap((c) => (c.cells ?? []).map((cell) => `${c.key}년 ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`));
say({
ko: `고친 칸 ${lines.length}개\n${lines.join('\n')}`,
en: `Edited cells: ${lines.length}\n${lines.join('\n')}`,
});
},
onlyBestQ4: (api) => api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: '4분기' }],
}),
clearFilter: (api) => api.setFilterModel(null),
rollback: (api) => api.rollbackChanges(),
};
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('showChanges').addEventListener('click', () => actions.showChanges(api));
document.getElementById('onlyBestQ4').addEventListener('click', () => actions.onlyBestQ4(api));
document.getElementById('clearFilter').addEventListener('click', () => actions.clearFilter(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(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.showChanges(api)}
>고친 칸 보기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.onlyBestQ4(api)}
>최대 분기가 4분기인 연도만</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clearFilter(api)}
>필터 해제</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.rollback(api)}
>고친 것 되돌리기</button>
</div>
<Grid style={{ height: 345 }} ref={gridRef} options={options} />
</>
);
}import type { ColumnDef, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
year: number;
q1: number;
q2: number;
q3: number;
q4: number;
}
// 서버가 주는 값은 연도와 1~4분기 매출뿐이에요. 상반기·하반기·연 합계·최대 분기는 저장하지 않고
// getValue로 그 줄에서 계산해요. 1~4분기 칸을 고치면 이 칸들과 맨 아래 합계 줄이 같이 바뀌어요.
const quarters = ['q1', 'q2', 'q3', 'q4'] as const;
const label = ['1분기', '2분기', '3분기', '4분기'];
const sum = (row: Row, keys: readonly (typeof quarters)[number][]) =>
keys.reduce((total, k) => total + row[k], 0);
const million = (value: unknown) => `${Number(value).toLocaleString('ko-KR')}`;
const rows: Row[] = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id: string, title: string, extra: Partial<ColumnDef<Row>>): ColumnDef<Row> => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'year', title: '연도', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '상반기', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '하반기', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', '연 매출', { getValue: (row) => sum(row, quarters), width: 110 }),
{
id: 'best',
title: '최대 분기',
width: 100,
align: 'center',
getValue: (row) =>
label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: '합계' },
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log({
ko: `${row.year}년 연 매출이 ${sum(row, quarters).toLocaleString('ko-KR')}(백만원)이 됐어요`,
en: `${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} (million KRW)`,
});
});
}
export const actions = {
// 고친 칸만 모아서 보여 줘요(원래 값 → 지금 값).
showChanges: (api: GridApi<Row>) => {
const changes = api.getChanges();
if (!changes.length)
return say({
ko: '아직 고친 칸이 없어요. 1~4분기 칸을 더블클릭해서 고쳐 보세요.',
en: 'No cell edited yet. Double-click a quarter 1-4 cell to edit it.',
});
const lines = changes.flatMap((c) =>
(c.cells ?? []).map(
(cell) =>
`${c.key}년 ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`,
),
);
say({
ko: `고친 칸 ${lines.length}개\n${lines.join('\n')}`,
en: `Edited cells: ${lines.length}\n${lines.join('\n')}`,
});
},
onlyBestQ4: (api: GridApi<Row>) =>
api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: '4분기' }],
}),
clearFilter: (api: GridApi<Row>) => api.setFilterModel(null),
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 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.showChanges(api)"
>고친 칸 보기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.onlyBestQ4(api)"
>최대 분기가 4분기인 연도만</button>
<button
type="button"
:disabled="!api"
@click="api && actions.clearFilter(api)"
>필터 해제</button>
<button
type="button"
:disabled="!api"
@click="api && actions.rollback(api)"
>고친 것 되돌리기</button>
</div>
<Grid style="height: 345px" :options="options" @ready="onReady" />
</template>import type { ColumnDef, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
year: number;
q1: number;
q2: number;
q3: number;
q4: number;
}
// 서버가 주는 값은 연도와 1~4분기 매출뿐이에요. 상반기·하반기·연 합계·최대 분기는 저장하지 않고
// getValue로 그 줄에서 계산해요. 1~4분기 칸을 고치면 이 칸들과 맨 아래 합계 줄이 같이 바뀌어요.
const quarters = ['q1', 'q2', 'q3', 'q4'] as const;
const label = ['1분기', '2분기', '3분기', '4분기'];
const sum = (row: Row, keys: readonly (typeof quarters)[number][]) =>
keys.reduce((total, k) => total + row[k], 0);
const million = (value: unknown) => `${Number(value).toLocaleString('ko-KR')}`;
const rows: Row[] = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id: string, title: string, extra: Partial<ColumnDef<Row>>): ColumnDef<Row> => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'year', title: '연도', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '상반기', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '하반기', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', '연 매출', { getValue: (row) => sum(row, quarters), width: 110 }),
{
id: 'best',
title: '최대 분기',
width: 100,
align: 'center',
getValue: (row) =>
label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: '합계' },
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log({
ko: `${row.year}년 연 매출이 ${sum(row, quarters).toLocaleString('ko-KR')}(백만원)이 됐어요`,
en: `${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} (million KRW)`,
});
});
}
export const actions = {
// 고친 칸만 모아서 보여 줘요(원래 값 → 지금 값).
showChanges: (api: GridApi<Row>) => {
const changes = api.getChanges();
if (!changes.length)
return say({
ko: '아직 고친 칸이 없어요. 1~4분기 칸을 더블클릭해서 고쳐 보세요.',
en: 'No cell edited yet. Double-click a quarter 1-4 cell to edit it.',
});
const lines = changes.flatMap((c) =>
(c.cells ?? []).map(
(cell) =>
`${c.key}년 ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`,
),
);
say({
ko: `고친 칸 ${lines.length}개\n${lines.join('\n')}`,
en: `Edited cells: ${lines.length}\n${lines.join('\n')}`,
});
},
onlyBestQ4: (api: GridApi<Row>) =>
api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: '4분기' }],
}),
clearFilter: (api: GridApi<Row>) => api.setFilterModel(null),
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 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.showChanges(api)"
>고친 칸 보기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.onlyBestQ4(api)"
>최대 분기가 4분기인 연도만</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clearFilter(api)"
>필터 해제</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.rollback(api)"
>고친 것 되돌리기</button>
</div>
<mx-grid style="height: 345px" [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 { ColumnDef, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
year: number;
q1: number;
q2: number;
q3: number;
q4: number;
}
// 서버가 주는 값은 연도와 1~4분기 매출뿐이에요. 상반기·하반기·연 합계·최대 분기는 저장하지 않고
// getValue로 그 줄에서 계산해요. 1~4분기 칸을 고치면 이 칸들과 맨 아래 합계 줄이 같이 바뀌어요.
const quarters = ['q1', 'q2', 'q3', 'q4'] as const;
const label = ['1분기', '2분기', '3분기', '4분기'];
const sum = (row: Row, keys: readonly (typeof quarters)[number][]) =>
keys.reduce((total, k) => total + row[k], 0);
const million = (value: unknown) => `${Number(value).toLocaleString('ko-KR')}`;
const rows: Row[] = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id: string, title: string, extra: Partial<ColumnDef<Row>>): ColumnDef<Row> => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'year', title: '연도', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '상반기', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '하반기', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', '연 매출', { getValue: (row) => sum(row, quarters), width: 110 }),
{
id: 'best',
title: '최대 분기',
width: 100,
align: 'center',
getValue: (row) =>
label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: '합계' },
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log({
ko: `${row.year}년 연 매출이 ${sum(row, quarters).toLocaleString('ko-KR')}(백만원)이 됐어요`,
en: `${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} (million KRW)`,
});
});
}
export const actions = {
// 고친 칸만 모아서 보여 줘요(원래 값 → 지금 값).
showChanges: (api: GridApi<Row>) => {
const changes = api.getChanges();
if (!changes.length)
return say({
ko: '아직 고친 칸이 없어요. 1~4분기 칸을 더블클릭해서 고쳐 보세요.',
en: 'No cell edited yet. Double-click a quarter 1-4 cell to edit it.',
});
const lines = changes.flatMap((c) =>
(c.cells ?? []).map(
(cell) =>
`${c.key}년 ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`,
),
);
say({
ko: `고친 칸 ${lines.length}개\n${lines.join('\n')}`,
en: `Edited cells: ${lines.length}\n${lines.join('\n')}`,
});
},
onlyBestQ4: (api: GridApi<Row>) =>
api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: '4분기' }],
}),
clearFilter: (api: GridApi<Row>) => api.setFilterModel(null),
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
};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="showChanges">Show edited cells</button>
<button type="button" id="onlyBestQ4">Only years whose best quarter is Q4</button>
<button type="button" id="clearFilter">Clear filter</button>
<button type="button" id="rollback">Undo all edits</button>
</div>
<div id="grid" style="height: 345px"></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('showChanges').addEventListener('click', () => actions.showChanges(api));
document.getElementById('onlyBestQ4').addEventListener('click', () => actions.onlyBestQ4(api));
document.getElementById('clearFilter').addEventListener('click', () => actions.clearFilter(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(api));// The server only gives the year and Q1-Q4 sales. First half, second half, yearly total and best quarter are not stored;
// getValue computes them in that row. Editing a Q1-Q4 cell changes these cells and the summary row at the bottom together.
const quarters = ['q1', 'q2', 'q3', 'q4'];
const label = ['Q1', 'Q2', 'Q3', 'Q4'];
const sum = (row, keys) => keys.reduce((total, k) => total + row[k], 0);
const million = (value) => `${Number(value).toLocaleString('en-US')}`;
const rows = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id, title, extra) => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
export const options = {
columns: [
{ id: 'year', title: 'Year', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '1st half', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '2nd half', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', 'Yearly sales', { getValue: (row) => sum(row, quarters), width: 120 }),
{
id: 'best',
title: 'Best quarter',
width: 100,
align: 'center',
getValue: (row) => label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: 'Total' },
};
let say = () => { };
export function setup(api, log) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log(`${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} ($ million)`);
});
}
export const actions = {
// Show only the edited cells (old value → current value).
showChanges: (api) => {
const changes = api.getChanges();
if (!changes.length)
return say('No cell edited yet. Double-click a Q1-Q4 cell to edit it.');
const lines = changes.flatMap((c) => (c.cells ?? []).map((cell) => `${c.key} ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`));
say(`Edited cells: ${lines.length}\n${lines.join('\n')}`);
},
onlyBestQ4: (api) => api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: 'Q4' }],
}),
clearFilter: (api) => api.setFilterModel(null),
rollback: (api) => api.rollbackChanges(),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Calculated columns that follow your edits</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="showChanges">Show edited cells</button>
<button type="button" id="onlyBestQ4">Only years whose best quarter is Q4</button>
<button type="button" id="clearFilter">Clear filter</button>
<button type="button" id="rollback">Undo all edits</button>
</div>
<div id="grid" style="height: 345px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// The server only gives the year and Q1-Q4 sales. First half, second half, yearly total and best quarter are not stored;
// getValue computes them in that row. Editing a Q1-Q4 cell changes these cells and the summary row at the bottom together.
const quarters = ['q1', 'q2', 'q3', 'q4'];
const label = ['Q1', 'Q2', 'Q3', 'Q4'];
const sum = (row, keys) => keys.reduce((total, k) => total + row[k], 0);
const million = (value) => `${Number(value).toLocaleString('en-US')}`;
const rows = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id, title, extra) => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
const options = {
columns: [
{ id: 'year', title: 'Year', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '1st half', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '2nd half', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', 'Yearly sales', { getValue: (row) => sum(row, quarters), width: 120 }),
{
id: 'best',
title: 'Best quarter',
width: 100,
align: 'center',
getValue: (row) => label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: 'Total' },
};
let say = () => { };
function setup(api, log) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log(`${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} ($ million)`);
});
}
const actions = {
// Show only the edited cells (old value → current value).
showChanges: (api) => {
const changes = api.getChanges();
if (!changes.length)
return say('No cell edited yet. Double-click a Q1-Q4 cell to edit it.');
const lines = changes.flatMap((c) => (c.cells ?? []).map((cell) => `${c.key} ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`));
say(`Edited cells: ${lines.length}\n${lines.join('\n')}`);
},
onlyBestQ4: (api) => api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: 'Q4' }],
}),
clearFilter: (api) => api.setFilterModel(null),
rollback: (api) => api.rollbackChanges(),
};
options.ariaLabel = "Calculated columns that follow your edits";
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('showChanges').addEventListener('click', () => actions.showChanges(api));
document.getElementById('onlyBestQ4').addEventListener('click', () => actions.onlyBestQ4(api));
document.getElementById('clearFilter').addEventListener('click', () => actions.clearFilter(api));
document.getElementById('rollback').addEventListener('click', () => actions.rollback(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.showChanges(api)}
>Show edited cells</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.onlyBestQ4(api)}
>Only years whose best quarter is Q4</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clearFilter(api)}
>Clear filter</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.rollback(api)}
>Undo all edits</button>
</div>
<Grid style={{ height: 345 }} ref={gridRef} options={options} />
</>
);
}import type { ColumnDef, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
year: number;
q1: number;
q2: number;
q3: number;
q4: number;
}
// The server only gives the year and Q1-Q4 sales. First half, second half, yearly total and best quarter are not stored;
// getValue computes them in that row. Editing a Q1-Q4 cell changes these cells and the summary row at the bottom together.
const quarters = ['q1', 'q2', 'q3', 'q4'] as const;
const label = ['Q1', 'Q2', 'Q3', 'Q4'];
const sum = (row: Row, keys: readonly (typeof quarters)[number][]) =>
keys.reduce((total, k) => total + row[k], 0);
const million = (value: unknown) => `${Number(value).toLocaleString('en-US')}`;
const rows: Row[] = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id: string, title: string, extra: Partial<ColumnDef<Row>>): ColumnDef<Row> => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'year', title: 'Year', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '1st half', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '2nd half', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', 'Yearly sales', { getValue: (row) => sum(row, quarters), width: 120 }),
{
id: 'best',
title: 'Best quarter',
width: 100,
align: 'center',
getValue: (row) =>
label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: 'Total' },
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log(
`${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} ($ million)`,
);
});
}
export const actions = {
// Show only the edited cells (old value → current value).
showChanges: (api: GridApi<Row>) => {
const changes = api.getChanges();
if (!changes.length) return say('No cell edited yet. Double-click a Q1-Q4 cell to edit it.');
const lines = changes.flatMap((c) =>
(c.cells ?? []).map(
(cell) =>
`${c.key} ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`,
),
);
say(`Edited cells: ${lines.length}\n${lines.join('\n')}`);
},
onlyBestQ4: (api: GridApi<Row>) =>
api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: 'Q4' }],
}),
clearFilter: (api: GridApi<Row>) => api.setFilterModel(null),
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
};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.showChanges(api)"
>Show edited cells</button>
<button
type="button"
:disabled="!api"
@click="api && actions.onlyBestQ4(api)"
>Only years whose best quarter is Q4</button>
<button
type="button"
:disabled="!api"
@click="api && actions.clearFilter(api)"
>Clear filter</button>
<button
type="button"
:disabled="!api"
@click="api && actions.rollback(api)"
>Undo all edits</button>
</div>
<Grid style="height: 345px" :options="options" @ready="onReady" />
</template>import type { ColumnDef, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
year: number;
q1: number;
q2: number;
q3: number;
q4: number;
}
// The server only gives the year and Q1-Q4 sales. First half, second half, yearly total and best quarter are not stored;
// getValue computes them in that row. Editing a Q1-Q4 cell changes these cells and the summary row at the bottom together.
const quarters = ['q1', 'q2', 'q3', 'q4'] as const;
const label = ['Q1', 'Q2', 'Q3', 'Q4'];
const sum = (row: Row, keys: readonly (typeof quarters)[number][]) =>
keys.reduce((total, k) => total + row[k], 0);
const million = (value: unknown) => `${Number(value).toLocaleString('en-US')}`;
const rows: Row[] = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id: string, title: string, extra: Partial<ColumnDef<Row>>): ColumnDef<Row> => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'year', title: 'Year', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '1st half', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '2nd half', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', 'Yearly sales', { getValue: (row) => sum(row, quarters), width: 120 }),
{
id: 'best',
title: 'Best quarter',
width: 100,
align: 'center',
getValue: (row) =>
label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: 'Total' },
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log(
`${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} ($ million)`,
);
});
}
export const actions = {
// Show only the edited cells (old value → current value).
showChanges: (api: GridApi<Row>) => {
const changes = api.getChanges();
if (!changes.length) return say('No cell edited yet. Double-click a Q1-Q4 cell to edit it.');
const lines = changes.flatMap((c) =>
(c.cells ?? []).map(
(cell) =>
`${c.key} ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`,
),
);
say(`Edited cells: ${lines.length}\n${lines.join('\n')}`);
},
onlyBestQ4: (api: GridApi<Row>) =>
api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: 'Q4' }],
}),
clearFilter: (api: GridApi<Row>) => api.setFilterModel(null),
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
};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.showChanges(api)"
>Show edited cells</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.onlyBestQ4(api)"
>Only years whose best quarter is Q4</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clearFilter(api)"
>Clear filter</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.rollback(api)"
>Undo all edits</button>
</div>
<mx-grid style="height: 345px" [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 { ColumnDef, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
year: number;
q1: number;
q2: number;
q3: number;
q4: number;
}
// The server only gives the year and Q1-Q4 sales. First half, second half, yearly total and best quarter are not stored;
// getValue computes them in that row. Editing a Q1-Q4 cell changes these cells and the summary row at the bottom together.
const quarters = ['q1', 'q2', 'q3', 'q4'] as const;
const label = ['Q1', 'Q2', 'Q3', 'Q4'];
const sum = (row: Row, keys: readonly (typeof quarters)[number][]) =>
keys.reduce((total, k) => total + row[k], 0);
const million = (value: unknown) => `${Number(value).toLocaleString('en-US')}`;
const rows: Row[] = Array.from({ length: 8 }, (_, i) => ({
year: 2018 + i,
q1: 120 + ((i * 17) % 40),
q2: 150 + ((i * 29) % 60),
q3: 140 + ((i * 41) % 50),
q4: 130 + ((i * 53) % 90),
}));
const number = (id: string, title: string, extra: Partial<ColumnDef<Row>>): ColumnDef<Row> => ({
id,
title,
kind: 'number',
width: 100,
align: 'end',
formatValue: million,
aggregate: 'sum',
aggregateFormat: million,
...extra,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'year', title: 'Year', width: 80 },
...quarters.map((q, i) => number(q, label[i], { editable: true })),
number('h1', '1st half', { getValue: (row) => sum(row, ['q1', 'q2']) }),
number('h2', '2nd half', { getValue: (row) => sum(row, ['q3', 'q4']) }),
number('total', 'Yearly sales', { getValue: (row) => sum(row, quarters), width: 120 }),
{
id: 'best',
title: 'Best quarter',
width: 100,
align: 'center',
getValue: (row) =>
label[quarters.reduce((best, q, i) => (row[q] > row[quarters[best]] ? i : best), 0)],
},
],
rows,
rowKey: 'year',
saveMode: 'batch',
summary: { label: 'Total' },
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('editCommitted', ({ rowKey }) => {
const row = api.getRowByKey(rowKey);
if (row)
log(
`${row.year} yearly sales are now ${sum(row, quarters).toLocaleString('en-US')} ($ million)`,
);
});
}
export const actions = {
// Show only the edited cells (old value → current value).
showChanges: (api: GridApi<Row>) => {
const changes = api.getChanges();
if (!changes.length) return say('No cell edited yet. Double-click a Q1-Q4 cell to edit it.');
const lines = changes.flatMap((c) =>
(c.cells ?? []).map(
(cell) =>
`${c.key} ${api.getColumns().find((col) => col.id === cell.columnId)?.title ?? cell.columnId}: ${String(cell.oldValue)} → ${String(cell.newValue)}`,
),
);
say(`Edited cells: ${lines.length}\n${lines.join('\n')}`);
},
onlyBestQ4: (api: GridApi<Row>) =>
api.setFilterModel({
match: 'all',
items: [{ columnId: 'best', operator: 'equals', value: 'Q4' }],
}),
clearFilter: (api: GridApi<Row>) => api.setFilterModel(null),
rollback: (api: GridApi<Row>) => api.rollbackChanges(),
};