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

열어 둔 그룹 기억하기: 새로고침·다시 묶기·저장Remember open groups: refresh, regroup, save

그룹을 열어 두고 데이터를 새로 불러오거나 다시 묶어 봐요. 열린 그룹을 저장해 두었다가 되살릴 수도 있어요.Open some groups, then refresh the data or regroup. You can also save the open groups and restore them.

활용Intermediate
직접 써 보기Live preview열어 둔 그룹 기억하기: 새로고침·다시 묶기·저장Remember open groups: refresh, regroup, save

코드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="refresh">데이터 새로고침</button>
    <button type="button" id="regroupKeep">다시 묶기 (유지)</button>
    <button type="button" id="regroupReset">다시 묶기 (초기화)</button>
    <button type="button" id="save">열린 그룹 저장</button>
    <button type="button" id="restore">저장한 그룹 열기</button>
  </div>
  <div id="grid" style="height: 330px"></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('refresh').addEventListener('click', () => actions.refresh(api));
document.getElementById('regroupKeep').addEventListener('click', () => actions.regroupKeep(api));
document.getElementById('regroupReset').addEventListener('click', () => actions.regroupReset(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
example.js
const regions = ['서울', '부산', '대전', '광주'];
const makeRows = (round) => Array.from({ length: 16 }, (_, i) => ({
  id: i + 1,
  region: regions[i % 4],
  store: `${regions[i % 4]} ${Math.floor(i / 4) + 1}호점`,
  sales: 1000 + ((i * 137 + round * 211) % 900),
}));
export const options = {
  columns: [
    { id: 'region', title: '지역', width: 130 },
    { id: 'store', title: '매장', width: 130 },
    {
      id: 'sales',
      title: '매출(만원)',
      kind: 'number',
      width: 120,
      align: 'end',
      aggregate: 'sum',
    },
  ],
  rows: makeRows(0),
  rowKey: 'id',
  grouping: { by: ['region'], expandDepth: 0 },
};
// 그룹의 키는 데이터를 새로 불러와도 같아서, 열어 둔 그룹이 setRows 뒤에도 열려 있어요.
// 반대로 setGroupBy로 다시 묶으면 열고 닫은 상태가 모두 지워져요. 유지하고 싶으면 열린 키를 모아 두었다가 다시 열어요.
let round = 0;
let saved = [];
let say = () => { };
// 그룹 키는 내부 표현이라, 로그에는 "s:서울"의 서울만 꺼내 보여요.
const label = (key) => /s:([^"\]]+)/.exec(String(key))?.[1] ?? String(key);
export function setup(api, log) {
  round = 0;
  saved = [];
  say = log;
  return api.on('expansionChanged', ({ reason, rowKeys }) => {
    const names = {
      toggle: '눌러서 바꿨어요',
      bulk: '한꺼번에 바꿨어요',
      reveal: '줄을 찾아 펼쳤어요',
      data: '데이터가 바뀌어 달라졌어요',
    };
    log(rowKeys.length ? `${names[reason]} (${rowKeys.map(label).join(', ')})` : names[reason]);
  });
}
const openKeys = (api) => {
  const keys = [];
  for (let i = 0; i < api.getVisibleRowCount(); i++) {
    const line = api.getDisplayRow(i);
    if (line?.kind === 'group' && line.expanded)
      keys.push(line.key);
  }
  return keys;
};
export const actions = {
  refresh: (api) => {
    api.setRows(makeRows(++round));
    say({
      ko: '데이터를 새로 불러왔어요. 열어 둔 그룹은 그대로예요.',
      en: 'Loaded the data again. Groups you opened stay open.',
    });
  },
  regroupKeep: (api) => {
    const keys = openKeys(api);
    api.setGroupBy([]);
    api.setGroupBy(['region']); // 새로 묶으면 열고 닫은 상태가 지워져요
    for (const key of keys)
      api.expandRow(key); // 같은 그룹은 같은 이름표라서 저장한 것이 같은 그룹을 가리켜요
    say({
      ko: `다시 묶었어요. 열어 둔 그룹 ${keys.length}개를 다시 열었어요.`,
      en: `Grouped again. Reopened the ${keys.length} groups you had open.`,
    });
  },
  regroupReset: (api) => {
    api.setGroupBy([]);
    api.setGroupBy(['region']);
    say({
      ko: '다시 묶었어요. 열고 닫은 상태가 모두 지워져서 전부 닫혔어요.',
      en: 'Grouped again. The open/closed state was cleared, so everything is closed.',
    });
  },
  save: (api) => {
    saved = openKeys(api);
    say({
      ko: saved.length
        ? `열린 그룹 ${saved.length}개를 저장했어요.`
        : '열린 그룹이 없어서 빈 상태를 저장했어요.',
      en: saved.length
        ? `Saved ${saved.length} open groups.`
        : 'No group is open, so an empty state was saved.',
    });
  },
  restore: (api) => {
    api.collapseAll();
    for (const key of saved)
      api.expandRow(key);
    say({
      ko: `저장한 그룹 ${saved.length}개를 다시 열었어요.`,
      en: `Reopened the ${saved.length} saved groups.`,
    });
  },
};

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="refresh">Refresh data</button>
    <button type="button" id="regroupKeep">Regroup (keep)</button>
    <button type="button" id="regroupReset">Regroup (reset)</button>
    <button type="button" id="save">Save open groups</button>
    <button type="button" id="restore">Restore saved groups</button>
  </div>
  <div id="grid" style="height: 330px"></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('refresh').addEventListener('click', () => actions.refresh(api));
document.getElementById('regroupKeep').addEventListener('click', () => actions.regroupKeep(api));
document.getElementById('regroupReset').addEventListener('click', () => actions.regroupReset(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
example.js
const regions = ['New York', 'Boston', 'Austin', 'Seattle'];
const makeRows = (round) => Array.from({ length: 16 }, (_, i) => ({
  id: i + 1,
  region: regions[i % 4],
  store: `${regions[i % 4]} Store ${Math.floor(i / 4) + 1}`,
  sales: 10000 + ((i * 137 + round * 211) % 900) * 10,
}));
export const options = {
  columns: [
    { id: 'region', title: 'Region', width: 130 },
    { id: 'store', title: 'Store', width: 160 },
    {
      id: 'sales',
      title: 'Sales ($)',
      kind: 'number',
      width: 120,
      align: 'end',
      aggregate: 'sum',
    },
  ],
  rows: makeRows(0),
  rowKey: 'id',
  grouping: { by: ['region'], expandDepth: 0 },
};
// A group's key stays the same when the data is reloaded, so groups you opened are still open after setRows.
// Regrouping with setGroupBy, on the other hand, clears all open/closed state. To keep it, collect the open keys and reopen them.
let round = 0;
let saved = [];
let say = () => { };
// Group keys are an internal format, so the log only shows the region name taken from "s:New York".
const label = (key) => /s:([^"\]]+)/.exec(String(key))?.[1] ?? String(key);
export function setup(api, log) {
  round = 0;
  saved = [];
  say = log;
  return api.on('expansionChanged', ({ reason, rowKeys }) => {
    const names = {
      toggle: 'Changed by a click',
      bulk: 'Changed all at once',
      reveal: 'Found a row and expanded it',
      data: 'Changed because the data changed',
    };
    log(rowKeys.length ? `${names[reason]} (${rowKeys.map(label).join(', ')})` : names[reason]);
  });
}
const openKeys = (api) => {
  const keys = [];
  for (let i = 0; i < api.getVisibleRowCount(); i++) {
    const line = api.getDisplayRow(i);
    if (line?.kind === 'group' && line.expanded)
      keys.push(line.key);
  }
  return keys;
};
export const actions = {
  refresh: (api) => {
    api.setRows(makeRows(++round));
    say('Loaded the data again. Groups you opened stay open.');
  },
  regroupKeep: (api) => {
    const keys = openKeys(api);
    api.setGroupBy([]);
    api.setGroupBy(['region']); // regrouping clears the open/closed state
    for (const key of keys)
      api.expandRow(key); // the same group has the same key, so each saved key points at the same group
    say(`Grouped again. Reopened the ${keys.length} groups you had open.`);
  },
  regroupReset: (api) => {
    api.setGroupBy([]);
    api.setGroupBy(['region']);
    say('Grouped again. The open/closed state was cleared, so everything is closed.');
  },
  save: (api) => {
    saved = openKeys(api);
    say(saved.length
      ? `Saved ${saved.length} open groups.`
      : 'No group is open, so an empty state was saved.');
  },
  restore: (api) => {
    api.collapseAll();
    for (const key of saved)
      api.expandRow(key);
    say(`Reopened the ${saved.length} saved groups.`);
  },
};