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

묶는 기준을 바꾸고 풀기Change or remove the grouping

묶는 컬럼을 고르고, 순서를 뒤집고, 풀어 봐요. 메모처럼 묶을 수 없게 정한 컬럼은 막혀요.Pick the grouping columns, reverse the order, or remove it. Columns marked as not groupable are refused.

활용Intermediate
직접 써 보기Live preview묶는 기준을 바꾸고 풀기Change or remove the grouping

코드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">
    <select aria-label="묶는 기준" id="by">
      <option value="country" selected>국가</option>
      <option value="country,channel">국가 → 채널</option>
      <option value="country,channel,plan">국가 → 채널 → 요금제</option>
      <option value="channel,country">채널 → 국가</option>
      <option value="plan,channel,country">요금제 → 채널 → 국가</option>
      <option value="memo">메모 (묶을 수 없음)</option>
      <option value="none">묶지 않기</option>
    </select>
    <button type="button" id="swap">순서 뒤집기</button>
    <button type="button" id="expandAll">모두 펼치기</button>
    <button type="button" id="collapseAll">모두 접기</button>
  </div>
  <div id="grid" style="height: 300px"></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('by').addEventListener('change', (event) => actions.by(api, event.target.value));
document.getElementById('swap').addEventListener('click', () => actions.swap(api));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
example.js
const countries = ['한국', '일본', '독일'];
const channels = ['웹', '파트너'];
const plans = ['무료', '팀', '비즈니스'];
const rows = Array.from({ length: 24 }, (_, i) => ({
  id: i + 1,
  country: countries[i % 3],
  channel: channels[Math.floor(i / 3) % 2],
  plan: plans[Math.floor(i / 6) % 3],
  memo: `고객 메모 ${i + 1}`,
  revenue: 100 + ((i * 47) % 400),
}));
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
  const ch = word.trim().slice(-1);
  const digit = '0123456789'.indexOf(ch);
  if (digit >= 0)
    return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0;
  const code = ch.charCodeAt(0) - 0xac00;
  return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
// 묶을 수 있는 컬럼은 groupable로 정해요(기본 true). 메모 컬럼은 false라서 묶으려 하면 막혀요.
export const options = {
  columns: [
    { id: 'country', title: '국가', width: 100 },
    { id: 'channel', title: '채널', width: 90 },
    { id: 'plan', title: '요금제', width: 100 },
    { id: 'memo', title: '메모', width: 120, groupable: false },
    { id: 'revenue', title: '매출', kind: 'number', width: 100, align: 'end', aggregate: 'sum' },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['country'], expandDepth: 0 },
  summary: true,
};
const titles = {
  country: '국가',
  channel: '채널',
  plan: '요금제',
  memo: '메모',
};
let say = () => { };
// 선택 상자가 항상 지금 묶음 상태를 가리키게 맞춰요(막힌 요청이나 순서 뒤집기 뒤에도요).
function syncSelect(api) {
  const box = document.getElementById('by');
  if (!(box instanceof HTMLSelectElement))
    return;
  const value = api.getGroupBy().join(',') || 'none';
  if ([...box.options].some((o) => o.value === value))
    box.value = value;
}
export function setup(api, log) {
  say = log;
  syncSelect(api);
  log({
    ko: '위 선택 상자에서 묶는 기준을 바꿔 보세요. 지금은 국가로 묶여 있어요.',
    en: 'Change the grouping in the select above. It is grouped by country now.',
  });
  return api.on('groupingChanged', ({ groupBy }) => {
    syncSelect(api);
    log({
      ko: groupBy.length
        ? `묶는 순서: ${groupBy.map((id) => titles[id] ?? id).join(' → ')}`
        : '묶기를 풀었어요.',
      en: groupBy.length
        ? `Grouping order: ${groupBy.map((id) => titles[id] ?? id).join(' → ')}`
        : 'Grouping removed.',
    });
  });
}
function regroup(api, ids) {
  try {
    api.setGroupBy(ids);
  }
  catch {
    const name = ids.map((id) => titles[id] ?? id).join(' → ');
    say({
      ko: `${name}${eulReul(name)} 묶을 수 없게 정해 둔 칸이에요. 묶음은 그대로 두었어요.`,
      en: `${name} is a column that cannot be grouped. The grouping stays as it was.`,
    });
    syncSelect(api); // 선택 상자를 지금 묶음으로 되돌려요
  }
}
export const actions = {
  by: (api, value) => regroup(api, value === 'none' || !value ? [] : value.split(',')),
  swap: (api) => {
    const now = api.getGroupBy();
    if (now.length < 2)
      return say({
        ko: '두 단계 이상 묶었을 때 순서를 바꿀 수 있어요.',
        en: 'You can change the order when you group by two or more levels.',
      });
    api.setGroupBy([...now].reverse());
  },
  expandAll: (api) => api.expandAll(),
  collapseAll: (api) => api.collapseAll(),
};

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">
    <select aria-label="Group by" id="by">
      <option value="country" selected>Country</option>
      <option value="country,channel">Country → channel</option>
      <option value="country,channel,plan">Country → channel → plan</option>
      <option value="channel,country">Channel → country</option>
      <option value="plan,channel,country">Plan → channel → country</option>
      <option value="memo">Memo (not groupable)</option>
      <option value="none">No grouping</option>
    </select>
    <button type="button" id="swap">Reverse order</button>
    <button type="button" id="expandAll">Expand all</button>
    <button type="button" id="collapseAll">Collapse all</button>
  </div>
  <div id="grid" style="height: 300px"></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('by').addEventListener('change', (event) => actions.by(api, event.target.value));
document.getElementById('swap').addEventListener('click', () => actions.swap(api));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
example.js
const countries = ['USA', 'Japan', 'Germany'];
const channels = ['Web', 'Partner'];
const plans = ['Free', 'Team', 'Business'];
const rows = Array.from({ length: 24 }, (_, i) => ({
  id: i + 1,
  country: countries[i % 3],
  channel: channels[Math.floor(i / 3) % 2],
  plan: plans[Math.floor(i / 6) % 3],
  memo: `Customer note ${i + 1}`,
  revenue: 100 + ((i * 47) % 400),
}));
// Groupable columns are set with groupable (default true). The memo column is false, so grouping by it is rejected.
export const options = {
  columns: [
    { id: 'country', title: 'Country', width: 100 },
    { id: 'channel', title: 'Channel', width: 110 },
    { id: 'plan', title: 'Plan', width: 100 },
    { id: 'memo', title: 'Memo', width: 130, groupable: false },
    { id: 'revenue', title: 'Revenue', kind: 'number', width: 100, align: 'end', aggregate: 'sum' },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['country'], expandDepth: 0 },
  summary: true,
};
const titles = {
  country: 'Country',
  channel: 'Channel',
  plan: 'Plan',
  memo: 'Memo',
};
let say = () => { };
// Keep the select pointing at the current grouping (also after a rejected request or a reversed order).
function syncSelect(api) {
  const box = document.getElementById('by');
  if (!(box instanceof HTMLSelectElement))
    return;
  const value = api.getGroupBy().join(',') || 'none';
  if ([...box.options].some((o) => o.value === value))
    box.value = value;
}
export function setup(api, log) {
  say = log;
  syncSelect(api);
  log('Change the grouping in the select above. It is grouped by country now.');
  return api.on('groupingChanged', ({ groupBy }) => {
    syncSelect(api);
    log(groupBy.length
      ? `Grouping order: ${groupBy.map((id) => titles[id] ?? id).join(' → ')}`
      : 'Grouping removed.');
  });
}
function regroup(api, ids) {
  try {
    api.setGroupBy(ids);
  }
  catch {
    const name = ids.map((id) => titles[id] ?? id).join(' → ');
    say(`${name} is a column that cannot be grouped. The grouping stays as it was.`);
    syncSelect(api); // put the select back to the current grouping
  }
}
export const actions = {
  by: (api, value) => regroup(api, value === 'none' || !value ? [] : value.split(',')),
  swap: (api) => {
    const now = api.getGroupBy();
    if (now.length < 2)
      return say('You can change the order when you group by two or more levels.');
    api.setGroupBy([...now].reverse());
  },
  expandAll: (api) => api.expandAll(),
  collapseAll: (api) => api.collapseAll(),
};