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

묶는 기준을 하나씩 바꾸고 헤더 그룹 읽기Change grouping one column at a time and read header groups

addGroupBy, removeGroupBy, moveGroupBy로 묶는 기준을 하나씩 바꾸고, resetExpansion으로 펼침을 처음으로 되돌려요. 헤더 그룹은 getHeaderGroups와 상태 저장·복원으로 읽고 되살려요. 합계는 aggregates에 등록한 이름(range)으로 계산해요.addGroupBy, removeGroupBy and moveGroupBy change the grouping one column at a time, and resetExpansion returns the expansion to its start. Header groups are read with getHeaderGroups and saved or restored as a state. The total uses a name (range) registered in aggregates.

심화Advanced
직접 써 보기Live preview묶는 기준을 하나씩 바꾸고 헤더 그룹 읽기Change grouping one column at a time and read header groups

코드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="addTeam">팀 더하기</button>
    <button type="button" id="removeTeam">팀 빼기</button>
    <button type="button" id="swap">순서 바꾸기</button>
    <button type="button" id="reset">펼침 초기화</button>
    <button type="button" id="readGroups">그룹 읽기</button>
    <button type="button" id="saveFold">접기 저장·복원</button>
  </div>
  <div id="grid" style="height: 320px"></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('addTeam').addEventListener('click', () => actions.addTeam(api));
document.getElementById('removeTeam').addEventListener('click', () => actions.removeTeam(api));
document.getElementById('swap').addEventListener('click', () => actions.swap(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
document.getElementById('readGroups').addEventListener('click', () => actions.readGroups(api));
document.getElementById('saveFold').addEventListener('click', () => actions.saveFold(api));
example.js
const rows = [
  { id: 1, dept: '개발', team: '웹', name: '김서연', base: 5200, bonus: 800 },
  { id: 2, dept: '개발', team: '웹', name: '이준호', base: 4800, bonus: 600 },
  { id: 3, dept: '개발', team: '앱', name: '박민지', base: 5000, bonus: 700 },
  { id: 4, dept: '영업', team: '국내', name: '최하늘', base: 4300, bonus: 1200 },
  { id: 5, dept: '영업', team: '해외', name: '정우진', base: 4600, bonus: 1500 },
  { id: 6, dept: '영업', team: '국내', name: '한소희', base: 4100, bonus: 900 },
];
// aggregates에는 이 그리드에서만 쓰는 이름 붙인 집계를 등록해요. range는 최댓값과 최솟값의 차이예요.
// 헤더 그룹 "보수"는 접을 수 있어요(collapsible). 묶는 기준은 처음에 부서 하나예요.
export const options = {
  aggregates: {
    range: (values) => {
      const numbers = values.filter((v) => typeof v === 'number');
      return numbers.length === 0 ? 0 : Math.max(...numbers) - Math.min(...numbers);
    },
  },
  columns: [
    { id: 'dept', title: '부서', width: 100 },
    { id: 'team', title: '팀', width: 90 },
    { id: 'name', title: '이름', width: 100 },
    { id: 'base', title: '기본급', kind: 'number', width: 100, aggregate: 'range' },
    { id: 'bonus', title: '상여', kind: 'number', width: 100, aggregate: 'sum' },
  ],
  headerGroups: [
    { id: 'who', title: '사람', children: ['dept', 'team', 'name'] },
    { id: 'pay', title: '보수', collapsible: true, children: ['base', 'bonus'] },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['dept'], expandDepth: 1 },
  summary: true,
};
let say = () => undefined;
let saved = null;
export function setup(api, log) {
  say = log;
  saved = null;
  log({
    ko: '버튼으로 묶는 기준을 하나씩 바꿔 보세요. 기본급 합계 칸은 최댓값-최솟값(range)이에요.',
    en: 'Use the buttons to change the grouping one column at a time. The base-pay total is max - min (range).',
  });
  const offs = [
    api.on('groupingChanged', (e) => log(`groupBy: ${e.groupBy.join(' > ') || '-'}`)),
    api.on('headerGroupToggled', (e) => log(`${e.groupId}: ${e.collapsed ? 'collapsed' : 'expanded'}`)),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  // 이미 있는 단계를 또 더하거나 없는 단계를 지우면 오류라서, 있는지 보고 눌러도 괜찮게 해요.
  addTeam: (api) => {
    if (!api.getGroupBy().includes('team'))
      api.addGroupBy('team');
  },
  removeTeam: (api) => {
    if (api.getGroupBy().includes('team'))
      api.removeGroupBy('team');
  },
  swap: (api) => {
    if (api.getGroupBy().length > 1)
      api.moveGroupBy('dept', api.getGroupBy().length - 1);
  },
  reset: (api) => api.resetExpansion(),
  readGroups: (api) => say(api
    .getHeaderGroups()
    .map((g) => `${g.id}[${g.columnIds.join(',')}]`)
    .join('  ')),
  saveFold: (api) => {
    if (saved === null) {
      saved = api.getHeaderGroupState();
      api.setHeaderGroupState({ pay: { collapsed: true } });
    }
    else {
      api.setHeaderGroupState(saved);
      saved = null;
    }
  },
};

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="addTeam">Add team</button>
    <button type="button" id="removeTeam">Remove team</button>
    <button type="button" id="swap">Swap order</button>
    <button type="button" id="reset">Reset expansion</button>
    <button type="button" id="readGroups">Read header groups</button>
    <button type="button" id="saveFold">Save and restore fold</button>
  </div>
  <div id="grid" style="height: 320px"></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('addTeam').addEventListener('click', () => actions.addTeam(api));
document.getElementById('removeTeam').addEventListener('click', () => actions.removeTeam(api));
document.getElementById('swap').addEventListener('click', () => actions.swap(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
document.getElementById('readGroups').addEventListener('click', () => actions.readGroups(api));
document.getElementById('saveFold').addEventListener('click', () => actions.saveFold(api));
example.js
const rows = [
  { id: 1, dept: 'Dev', team: 'Web', name: 'Emma Stone', base: 52000, bonus: 8000 },
  { id: 2, dept: 'Dev', team: 'Web', name: 'Liam Carter', base: 48000, bonus: 6000 },
  { id: 3, dept: 'Dev', team: 'App', name: 'Mia Johnson', base: 50000, bonus: 7000 },
  { id: 4, dept: 'Sales', team: 'Domestic', name: 'Ava Brown', base: 43000, bonus: 12000 },
  { id: 5, dept: 'Sales', team: 'Overseas', name: 'Noah Kim', base: 46000, bonus: 15000 },
  { id: 6, dept: 'Sales', team: 'Domestic', name: 'Olivia Park', base: 41000, bonus: 9000 },
];
// aggregates registers a named aggregate that only this grid uses. range is the difference between the max and the min.
// The header group "Pay" can be collapsed (collapsible). The grouping starts with department only.
export const options = {
  aggregates: {
    range: (values) => {
      const numbers = values.filter((v) => typeof v === 'number');
      return numbers.length === 0 ? 0 : Math.max(...numbers) - Math.min(...numbers);
    },
  },
  columns: [
    { id: 'dept', title: 'Dept', width: 100 },
    { id: 'team', title: 'Team', width: 90 },
    { id: 'name', title: 'Name', width: 100 },
    { id: 'base', title: 'Base pay', kind: 'number', width: 120, aggregate: 'range' },
    { id: 'bonus', title: 'Bonus', kind: 'number', width: 100, aggregate: 'sum' },
  ],
  headerGroups: [
    { id: 'who', title: 'Person', children: ['dept', 'team', 'name'] },
    { id: 'pay', title: 'Pay', collapsible: true, children: ['base', 'bonus'] },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['dept'], expandDepth: 1 },
  summary: true,
};
let say = () => undefined;
let saved = null;
export function setup(api, log) {
  say = log;
  saved = null;
  log('Use the buttons to change the grouping one column at a time. The base-pay total is max - min (range).');
  const offs = [
    api.on('groupingChanged', (e) => log(`groupBy: ${e.groupBy.join(' > ') || '-'}`)),
    api.on('headerGroupToggled', (e) => log(`${e.groupId}: ${e.collapsed ? 'collapsed' : 'expanded'}`)),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  // Adding a level that already exists or removing one that does not is an error, so check first to make the buttons safe to click.
  addTeam: (api) => {
    if (!api.getGroupBy().includes('team'))
      api.addGroupBy('team');
  },
  removeTeam: (api) => {
    if (api.getGroupBy().includes('team'))
      api.removeGroupBy('team');
  },
  swap: (api) => {
    if (api.getGroupBy().length > 1)
      api.moveGroupBy('dept', api.getGroupBy().length - 1);
  },
  reset: (api) => api.resetExpansion(),
  readGroups: (api) => say(api
    .getHeaderGroups()
    .map((g) => `${g.id}[${g.columnIds.join(',')}]`)
    .join('  ')),
  saveFold: (api) => {
    if (saved === null) {
      saved = api.getHeaderGroupState();
      api.setHeaderGroupState({ pay: { collapsed: true } });
    }
    else {
      api.setHeaderGroupState(saved);
      saved = null;
    }
  },
};