묶는 기준을 하나씩 바꾸고 헤더 그룹 읽기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.
코드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="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>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));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;
}
},
};<!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="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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
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). 묶는 기준은 처음에 부서 하나예요.
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;
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());
}
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;
}
},
};
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('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));
</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.addTeam(api)}
>팀 더하기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeTeam(api)}
>팀 빼기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.swap(api)}
>순서 바꾸기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reset(api)}
>펼침 초기화</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.readGroups(api)}
>그룹 읽기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.saveFold(api)}
>접기 저장·복원</button>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
dept: string;
team: string;
name: string;
base: number;
bonus: number;
}
const rows: Row[] = [
{ 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: GridOptions<Row> = {
aggregates: {
range: (values) => {
const numbers = values.filter((v): v is number => 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: (message: LogText) => void = () => undefined;
let saved: Record<string, { collapsed: boolean }> | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
if (!api.getGroupBy().includes('team')) api.addGroupBy('team');
},
removeTeam: (api: GridApi<Row>) => {
if (api.getGroupBy().includes('team')) api.removeGroupBy('team');
},
swap: (api: GridApi<Row>) => {
if (api.getGroupBy().length > 1) api.moveGroupBy('dept', api.getGroupBy().length - 1);
},
reset: (api: GridApi<Row>) => api.resetExpansion(),
readGroups: (api: GridApi<Row>) =>
say(
api
.getHeaderGroups()
.map((g) => `${g.id}[${g.columnIds.join(',')}]`)
.join(' '),
),
saveFold: (api: GridApi<Row>) => {
if (saved === null) {
saved = api.getHeaderGroupState();
api.setHeaderGroupState({ pay: { collapsed: true } });
} else {
api.setHeaderGroupState(saved);
saved = null;
}
},
};버튼을 누르면 이 예제의 코드가 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.addTeam(api)">팀 더하기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeTeam(api)"
>팀 빼기</button>
<button type="button" :disabled="!api" @click="api && actions.swap(api)">순서 바꾸기</button>
<button type="button" :disabled="!api" @click="api && actions.reset(api)">펼침 초기화</button>
<button
type="button"
:disabled="!api"
@click="api && actions.readGroups(api)"
>그룹 읽기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.saveFold(api)"
>접기 저장·복원</button>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
dept: string;
team: string;
name: string;
base: number;
bonus: number;
}
const rows: Row[] = [
{ 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: GridOptions<Row> = {
aggregates: {
range: (values) => {
const numbers = values.filter((v): v is number => 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: (message: LogText) => void = () => undefined;
let saved: Record<string, { collapsed: boolean }> | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
if (!api.getGroupBy().includes('team')) api.addGroupBy('team');
},
removeTeam: (api: GridApi<Row>) => {
if (api.getGroupBy().includes('team')) api.removeGroupBy('team');
},
swap: (api: GridApi<Row>) => {
if (api.getGroupBy().length > 1) api.moveGroupBy('dept', api.getGroupBy().length - 1);
},
reset: (api: GridApi<Row>) => api.resetExpansion(),
readGroups: (api: GridApi<Row>) =>
say(
api
.getHeaderGroups()
.map((g) => `${g.id}[${g.columnIds.join(',')}]`)
.join(' '),
),
saveFold: (api: GridApi<Row>) => {
if (saved === null) {
saved = api.getHeaderGroupState();
api.setHeaderGroupState({ pay: { collapsed: true } });
} else {
api.setHeaderGroupState(saved);
saved = null;
}
},
};버튼을 누르면 이 예제의 코드가 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.addTeam(api)"
>팀 더하기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeTeam(api)"
>팀 빼기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.swap(api)"
>순서 바꾸기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reset(api)"
>펼침 초기화</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.readGroups(api)"
>그룹 읽기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.saveFold(api)"
>접기 저장·복원</button>
</div>
<mx-grid style="height: 320px" [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 { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
dept: string;
team: string;
name: string;
base: number;
bonus: number;
}
const rows: Row[] = [
{ 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: GridOptions<Row> = {
aggregates: {
range: (values) => {
const numbers = values.filter((v): v is number => 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: (message: LogText) => void = () => undefined;
let saved: Record<string, { collapsed: boolean }> | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
if (!api.getGroupBy().includes('team')) api.addGroupBy('team');
},
removeTeam: (api: GridApi<Row>) => {
if (api.getGroupBy().includes('team')) api.removeGroupBy('team');
},
swap: (api: GridApi<Row>) => {
if (api.getGroupBy().length > 1) api.moveGroupBy('dept', api.getGroupBy().length - 1);
},
reset: (api: GridApi<Row>) => api.resetExpansion(),
readGroups: (api: GridApi<Row>) =>
say(
api
.getHeaderGroups()
.map((g) => `${g.id}[${g.columnIds.join(',')}]`)
.join(' '),
),
saveFold: (api: GridApi<Row>) => {
if (saved === null) {
saved = api.getHeaderGroupState();
api.setHeaderGroupState({ pay: { collapsed: true } });
} else {
api.setHeaderGroupState(saved);
saved = null;
}
},
};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="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>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));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;
}
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Change grouping one column at a time and read header groups</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
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.
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;
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());
}
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;
}
},
};
options.ariaLabel = "Change grouping one column at a time and read header groups";
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('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));
</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.addTeam(api)}
>Add team</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeTeam(api)}
>Remove team</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.swap(api)}
>Swap order</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reset(api)}
>Reset expansion</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.readGroups(api)}
>Read header groups</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.saveFold(api)}
>Save and restore fold</button>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
dept: string;
team: string;
name: string;
base: number;
bonus: number;
}
const rows: Row[] = [
{ 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: GridOptions<Row> = {
aggregates: {
range: (values) => {
const numbers = values.filter((v): v is number => 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: (message: LogText) => void = () => undefined;
let saved: Record<string, { collapsed: boolean }> | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
if (!api.getGroupBy().includes('team')) api.addGroupBy('team');
},
removeTeam: (api: GridApi<Row>) => {
if (api.getGroupBy().includes('team')) api.removeGroupBy('team');
},
swap: (api: GridApi<Row>) => {
if (api.getGroupBy().length > 1) api.moveGroupBy('dept', api.getGroupBy().length - 1);
},
reset: (api: GridApi<Row>) => api.resetExpansion(),
readGroups: (api: GridApi<Row>) =>
say(
api
.getHeaderGroups()
.map((g) => `${g.id}[${g.columnIds.join(',')}]`)
.join(' '),
),
saveFold: (api: GridApi<Row>) => {
if (saved === null) {
saved = api.getHeaderGroupState();
api.setHeaderGroupState({ pay: { collapsed: true } });
} else {
api.setHeaderGroupState(saved);
saved = null;
}
},
};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.addTeam(api)">Add team</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeTeam(api)"
>Remove team</button>
<button type="button" :disabled="!api" @click="api && actions.swap(api)">Swap order</button>
<button type="button" :disabled="!api" @click="api && actions.reset(api)">Reset expansion</button>
<button
type="button"
:disabled="!api"
@click="api && actions.readGroups(api)"
>Read header groups</button>
<button
type="button"
:disabled="!api"
@click="api && actions.saveFold(api)"
>Save and restore fold</button>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
dept: string;
team: string;
name: string;
base: number;
bonus: number;
}
const rows: Row[] = [
{ 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: GridOptions<Row> = {
aggregates: {
range: (values) => {
const numbers = values.filter((v): v is number => 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: (message: LogText) => void = () => undefined;
let saved: Record<string, { collapsed: boolean }> | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
if (!api.getGroupBy().includes('team')) api.addGroupBy('team');
},
removeTeam: (api: GridApi<Row>) => {
if (api.getGroupBy().includes('team')) api.removeGroupBy('team');
},
swap: (api: GridApi<Row>) => {
if (api.getGroupBy().length > 1) api.moveGroupBy('dept', api.getGroupBy().length - 1);
},
reset: (api: GridApi<Row>) => api.resetExpansion(),
readGroups: (api: GridApi<Row>) =>
say(
api
.getHeaderGroups()
.map((g) => `${g.id}[${g.columnIds.join(',')}]`)
.join(' '),
),
saveFold: (api: GridApi<Row>) => {
if (saved === null) {
saved = api.getHeaderGroupState();
api.setHeaderGroupState({ pay: { collapsed: true } });
} else {
api.setHeaderGroupState(saved);
saved = null;
}
},
};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.addTeam(api)"
>Add team</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeTeam(api)"
>Remove team</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.swap(api)"
>Swap order</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reset(api)"
>Reset expansion</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.readGroups(api)"
>Read header groups</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.saveFold(api)"
>Save and restore fold</button>
</div>
<mx-grid style="height: 320px" [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 { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
dept: string;
team: string;
name: string;
base: number;
bonus: number;
}
const rows: Row[] = [
{ 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: GridOptions<Row> = {
aggregates: {
range: (values) => {
const numbers = values.filter((v): v is number => 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: (message: LogText) => void = () => undefined;
let saved: Record<string, { collapsed: boolean }> | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
if (!api.getGroupBy().includes('team')) api.addGroupBy('team');
},
removeTeam: (api: GridApi<Row>) => {
if (api.getGroupBy().includes('team')) api.removeGroupBy('team');
},
swap: (api: GridApi<Row>) => {
if (api.getGroupBy().length > 1) api.moveGroupBy('dept', api.getGroupBy().length - 1);
},
reset: (api: GridApi<Row>) => api.resetExpansion(),
readGroups: (api: GridApi<Row>) =>
say(
api
.getHeaderGroups()
.map((g) => `${g.id}[${g.columnIds.join(',')}]`)
.join(' '),
),
saveFold: (api: GridApi<Row>) => {
if (saved === null) {
saved = api.getHeaderGroupState();
api.setHeaderGroupState({ pay: { collapsed: true } });
} else {
api.setHeaderGroupState(saved);
saved = null;
}
},
};