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

보기 모드로 컬럼 구성 한 번에 바꾸기Switch column layouts with view presets

'전체', '매출 보기', '인사 보기'처럼 미리 정해 둔 컬럼 구성을 한 번에 바꿔요. 어떤 컬럼을 어떤 순서로, 고정할지까지 한 줄로 적어 두면 돼요. 합계는 지금 보이는 달만 더해서 숨기면 따라서 바뀌어요.Switch between ready-made column layouts such as All, Sales and People in one step. A preset lists which columns show, in what order and pinned or not. The total adds only the months currently shown.

활용Intermediate
직접 써 보기Live preview보기 모드로 컬럼 구성 한 번에 바꾸기Switch column layouts with view presets

코드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="view">
      <option value="all" selected>전체 (기본)</option>
      <option value="sales">매출 보기</option>
      <option value="people">인사 보기</option>
    </select>
    <button type="button" id="toggleFeb">2월 켬/끔</button>
  </div>
  <div id="grid" style="height: 360px"></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('view').addEventListener('change', (event) => actions.view(api, event.target.value));
document.getElementById('toggleFeb').addEventListener('click', () => actions.toggleFeb(api));
example.js
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const cities = ['서울', '부산', '대구', '제주'];
const MONTHS = ['jan', 'feb', 'mar'];
// 합계는 계산 컬럼이에요. 숨긴 달을 합계에 넣을지는 약속하기 나름이라, 지금 보이는 달만 더하도록
// 컬럼 정의를 다시 만들어요(숨기거나 보일 때마다).
const totalColumn = (hidden) => ({
  id: 'total',
  title: '보이는 달 합계',
  kind: 'number',
  width: 140,
  align: 'end',
  getValue: (row) => MONTHS.filter((m) => !hidden.has(m)).reduce((sum, m) => sum + row[m], 0),
  formatValue: (value) => Number(value).toLocaleString('ko-KR'),
});
export const options = {
  columns: [
    { id: 'id', title: '번호', width: 70, align: 'end' },
    { id: 'name', title: '이름', width: 120 },
    { id: 'team', title: '팀', width: 110 },
    { id: 'city', title: '근무지', width: 100 },
    ...MONTHS.map((id, i) => ({
      id,
      title: `${i + 1}월 매출`,
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    })),
    totalColumn(new Set()),
  ],
  rows: Array.from({ length: 8 }, (_, i) => ({
    id: i + 1,
    name: names[i % 6],
    team: teams[(i * 3) % 4],
    city: cities[i % 4],
    jan: 1200 + ((i * 370) % 900),
    feb: 1500 + ((i * 290) % 800),
    mar: 1100 + ((i * 410) % 1100),
  })),
  rowKey: 'id',
};
// 프리셋은 "어떤 컬럼을, 어떤 순서로, 고정할지"만 적은 목록이고, setColumnState로 한 번에 적용해요.
const PRESETS = {
  all: { show: ['id', 'name', 'team', 'city', 'jan', 'feb', 'mar', 'total'] },
  sales: { show: ['name', 'jan', 'feb', 'mar', 'total'], pinned: 'name' },
  people: { show: ['id', 'name', 'team', 'city'], pinned: 'name' },
};
let say = () => { };
function syncTotal(api) {
  const hidden = new Set(api
    .getColumnState()
    .filter((s) => s.hidden)
    .map((s) => s.id));
  api.setColumns(api.getColumns().map((c) => (c.id === 'total' ? totalColumn(hidden) : c)));
  say({
    ko: `합계에 ${MONTHS.filter((m) => !hidden.has(m)).length}개 달이 들어가요`,
    en: `${MONTHS.filter((m) => !hidden.has(m)).length} months are in the total`,
  });
}
export function setup(api, log) {
  say = log;
  const off = api.on('columnVisibilityChanged', ({ columnId }) => {
    if (columnId !== 'total')
      syncTotal(api);
  });
  return () => off();
}
export const actions = {
  view: (api, value) => {
    const preset = PRESETS[value ?? 'all'] ?? PRESETS.all;
    const widths = new Map(api.getColumnState().map((s) => [s.id, s.width]));
    const hidden = api
      .getColumns()
      .map((c) => c.id)
      .filter((id) => !preset.show.includes(id));
    const state = [...preset.show, ...hidden].map((id) => ({
      id,
      width: widths.get(id) ?? 110,
      hidden: !preset.show.includes(id),
      pinned: id === preset.pinned ? 'start' : null,
    }));
    api.setColumnState(state);
  },
  // 달 하나를 켜고 꺼 보면 합계가 따라가요.
  toggleFeb: (api) => {
    const state = api.getColumnState().find((s) => s.id === 'feb');
    if (state)
      api.setColumnVisible('feb', state.hidden);
  },
};

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="View" id="view">
      <option value="all" selected>All (default)</option>
      <option value="sales">Sales</option>
      <option value="people">People</option>
    </select>
    <button type="button" id="toggleFeb">Toggle February</button>
  </div>
  <div id="grid" style="height: 360px"></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('view').addEventListener('change', (event) => actions.view(api, event.target.value));
document.getElementById('toggleFeb').addEventListener('click', () => actions.toggleFeb(api));
example.js
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Parker',
  'Olivia Reed',
  'Ethan Clark',
  'Mia Turner',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const cities = ['Seoul', 'Busan', 'Daegu', 'Jeju'];
const MONTHS = ['jan', 'feb', 'mar'];
// The total is a computed column. Whether hidden months count is a matter of convention, so the
// column definition is rebuilt to add only the months that are visible now (on every hide/show).
const totalColumn = (hidden) => ({
  id: 'total',
  title: 'Visible months total',
  kind: 'number',
  width: 200,
  align: 'end',
  getValue: (row) => MONTHS.filter((m) => !hidden.has(m)).reduce((sum, m) => sum + row[m], 0),
  formatValue: (value) => Number(value).toLocaleString('en-US'),
});
export const options = {
  columns: [
    { id: 'id', title: 'No.', width: 70, align: 'end' },
    { id: 'name', title: 'Name', width: 130 },
    { id: 'team', title: 'Team', width: 110 },
    { id: 'city', title: 'Office', width: 100 },
    ...MONTHS.map((id, i) => ({
      id,
      title: `${['Jan', 'Feb', 'Mar'][i]} sales`,
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    })),
    totalColumn(new Set()),
  ],
  rows: Array.from({ length: 8 }, (_, i) => ({
    id: i + 1,
    name: names[i % 6],
    team: teams[(i * 3) % 4],
    city: cities[i % 4],
    jan: 1200 + ((i * 370) % 900),
    feb: 1500 + ((i * 290) % 800),
    mar: 1100 + ((i * 410) % 1100),
  })),
  rowKey: 'id',
};
// A preset is just a list of which columns, in what order, and which one is pinned; setColumnState applies it in one call.
const PRESETS = {
  all: { show: ['id', 'name', 'team', 'city', 'jan', 'feb', 'mar', 'total'] },
  sales: { show: ['name', 'jan', 'feb', 'mar', 'total'], pinned: 'name' },
  people: { show: ['id', 'name', 'team', 'city'], pinned: 'name' },
};
let say = () => { };
function syncTotal(api) {
  const hidden = new Set(api
    .getColumnState()
    .filter((s) => s.hidden)
    .map((s) => s.id));
  api.setColumns(api.getColumns().map((c) => (c.id === 'total' ? totalColumn(hidden) : c)));
  say(`${MONTHS.filter((m) => !hidden.has(m)).length} months are in the total`);
}
export function setup(api, log) {
  say = log;
  const off = api.on('columnVisibilityChanged', ({ columnId }) => {
    if (columnId !== 'total')
      syncTotal(api);
  });
  return () => off();
}
export const actions = {
  view: (api, value) => {
    const preset = PRESETS[value ?? 'all'] ?? PRESETS.all;
    const widths = new Map(api.getColumnState().map((s) => [s.id, s.width]));
    const hidden = api
      .getColumns()
      .map((c) => c.id)
      .filter((id) => !preset.show.includes(id));
    const state = [...preset.show, ...hidden].map((id) => ({
      id,
      width: widths.get(id) ?? 110,
      hidden: !preset.show.includes(id),
      pinned: id === preset.pinned ? 'start' : null,
    }));
    api.setColumnState(state);
  },
  // Toggle one month and the total follows.
  toggleFeb: (api) => {
    const state = api.getColumnState().find((s) => s.id === 'feb');
    if (state)
      api.setColumnVisible('feb', state.hidden);
  },
};