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

고치면 같이 바뀌는 계산 컬럼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.

활용Intermediate
직접 써 보기Live preview고치면 같이 바뀌는 계산 컬럼Calculated columns that follow your edits

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

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

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

index.html
<div id="app">
  <div class="toolbar">
    <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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('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));
example.js
// 서버가 주는 값은 연도와 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(),
};

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

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

index.html
<div id="app">
  <div class="toolbar">
    <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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('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));
example.js
// 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(),
};