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

머리글·본문·합계 그리드 셋 맞추기Align a header, a body and a totals grid

alignGrids는 그리드를 2~4개까지 이어요. 머리글만 있는 그리드, 본문 그리드, 합계 그리드를 쌓아 두고 맨 위 머리글에서 컬럼 폭이나 순서를 바꾸면 셋이 함께 바뀌고 스크롤도 같이 움직여요.alignGrids links two to four grids. Stack a header-only grid, a body grid and a totals grid and a width or order change in the top header applies to all three, and the scroll moves together.

심화Advanced
직접 써 보기Live preview머리글·본문·합계 그리드 셋 맞추기Align a header, a body and a totals grid

코드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="widen">항목 넓히기</button>
    <button type="button" id="move">차이 맨 앞으로</button>
    <button type="button" id="plan">계획 숨기기/보이기</button>
  </div>
  <div id="grid" style="height: 240px"></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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('move').addEventListener('click', () => actions.move(api));
document.getElementById('plan').addEventListener('click', () => actions.plan(api));
example.js
// 머리글만 있는 그리드, 본문 그리드, 합계 그리드를 위아래로 쌓고 컬럼 폭·순서·숨김·스크롤을 서로 맞춰요.
const ITEMS = [
  '노트북',
  '태블릿',
  '스마트워치',
  '이어폰',
  '보조배터리',
  '스피커',
  '키보드',
  '모니터',
];
const COLUMNS = [
  { id: 'item', title: '항목', width: 150 },
  {
    id: 'q1',
    title: '1분기',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
  },
  {
    id: 'q2',
    title: '2분기',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
  },
  {
    id: 'q3',
    title: '3분기',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
  },
  {
    id: 'q4',
    title: '4분기',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
  },
  {
    id: 'plan',
    title: '계획',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
  },
  {
    id: 'gap',
    title: '차이',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
  },
];
const body = ITEMS.map((item, i) => {
  const q = [1, 2, 3, 4].map((k) => 40 + ((i * 17 + k * 29) % 60));
  const plan = 190 + i * 5;
  return {
    id: i + 1,
    item,
    q1: q[0] ?? 0,
    q2: q[1] ?? 0,
    q3: q[2] ?? 0,
    q4: q[3] ?? 0,
    plan,
    gap: q.reduce((a, b) => a + b, 0) - plan,
  };
});
const sum = (key) => body.reduce((total, row) => total + (row[key] ?? 0), 0);
// 갤러리 틀이 만드는 그리드가 본문 그리드예요(머리글 없음). 머리글만 있는 그리드를 위에, 합계 그리드를 아래에 놓아요.
export const options = {
  columns: COLUMNS,
  rows: body,
  rowKey: 'id',
  showHeader: false,
};
let grids = [];
let hosts = [];
let link = null;
export function setup(api, log) {
  const gridEl = document.getElementById('grid');
  const place = (where, opts) => {
    const host = document.createElement('div');
    host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
    if (gridEl !== null)
      gridEl[where](host);
    else
      document.body.append(host);
    hosts.push(host);
    return MaxGrid.createGrid(host, opts);
  };
  const header = place('before', {
    columns: COLUMNS,
    rows: [],
    rowKey: 'id',
    overlays: false,
    autoGridHeight: true,
    ariaLabel: '머리글 그리드',
  });
  const bottom = place('after', {
    columns: COLUMNS,
    rows: [
      {
        id: 0,
        item: '합계',
        q1: sum('q1'),
        q2: sum('q2'),
        q3: sum('q3'),
        q4: sum('q4'),
        plan: sum('plan'),
        gap: sum('gap'),
      },
    ],
    rowKey: 'id',
    showHeader: false,
    autoGridHeight: true,
    ariaLabel: '합계 그리드',
  });
  // 첫 그리드(header)가 기준이라 컬럼 폭은 머리글에서 끌어 바꿔요.
  grids = [header, api, bottom];
  link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
  const offs = grids.map((grid, index) => grid.on('gridsAligned', (e) => log({
    ko: `${['머리글', '본문', '합계'][index]} 그리드가 맞춰졌어요(${e.count}개)`,
    en: `${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`,
  })));
  log({
    ko: '맨 위 머리글에서 컬럼 폭을 끌거나 제목을 옮기면 본문과 합계 그리드가 따라가요.',
    en: 'Drag a column width or move a title in the top header and the body and totals grids follow.',
  });
  return () => {
    offs.forEach((off) => off());
    link?.unlink();
    [grids[0], grids[2]].forEach((grid) => grid?.destroy());
    hosts.forEach((host) => host.remove());
    grids = [];
    hosts = [];
    link = null;
  };
}
export const actions = {
  // 항목 컬럼을 넓혀요.
  widen: (api) => {
    const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
    api.resizeColumn('item', width + 50);
  },
  // 차이 컬럼을 맨 앞으로 옮겨요.
  move: (api) => api.moveColumn('gap', 0),
  // 계획 컬럼을 숨기거나 다시 보여요.
  plan: (api) => {
    const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
    api.setColumnVisible('plan', 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">
    <button type="button" id="widen">Widen Item</button>
    <button type="button" id="move">Move Gap first</button>
    <button type="button" id="plan">Hide/Show Plan</button>
  </div>
  <div id="grid" style="height: 240px"></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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('move').addEventListener('click', () => actions.move(api));
document.getElementById('plan').addEventListener('click', () => actions.plan(api));
example.js
// A header-only grid, a body grid and a totals grid are stacked, and their column widths, order, visibility and scroll are aligned.
const ITEMS = [
  'Laptop',
  'Tablet',
  'Smart watch',
  'Earbuds',
  'Power bank',
  'Speaker',
  'Keyboard',
  'Monitor',
];
const COLUMNS = [
  { id: 'item', title: 'Item', width: 150 },
  {
    id: 'q1',
    title: 'Q1',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
  },
  {
    id: 'q2',
    title: 'Q2',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
  },
  {
    id: 'q3',
    title: 'Q3',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
  },
  {
    id: 'q4',
    title: 'Q4',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
  },
  {
    id: 'plan',
    title: 'Plan',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
  },
  {
    id: 'gap',
    title: 'Gap',
    width: 120,
    kind: 'number',
    align: 'end',
    formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
  },
];
const body = ITEMS.map((item, i) => {
  const q = [1, 2, 3, 4].map((k) => 10 * (40 + ((i * 17 + k * 29) % 60)));
  const plan = 10 * (190 + i * 5);
  return {
    id: i + 1,
    item,
    q1: q[0] ?? 0,
    q2: q[1] ?? 0,
    q3: q[2] ?? 0,
    q4: q[3] ?? 0,
    plan,
    gap: q.reduce((a, b) => a + b, 0) - plan,
  };
});
const sum = (key) => body.reduce((total, row) => total + (row[key] ?? 0), 0);
// The grid the frame creates is the body grid (no header). The header-only grid goes above it and the totals grid below.
export const options = {
  columns: COLUMNS,
  rows: body,
  rowKey: 'id',
  showHeader: false,
};
let grids = [];
let hosts = [];
let link = null;
export function setup(api, log) {
  const gridEl = document.getElementById('grid');
  const place = (where, opts) => {
    const host = document.createElement('div');
    host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
    if (gridEl !== null)
      gridEl[where](host);
    else
      document.body.append(host);
    hosts.push(host);
    return MaxGrid.createGrid(host, opts);
  };
  const header = place('before', {
    columns: COLUMNS,
    rows: [],
    rowKey: 'id',
    overlays: false,
    autoGridHeight: true,
    ariaLabel: 'Header grid',
  });
  const bottom = place('after', {
    columns: COLUMNS,
    rows: [
      {
        id: 0,
        item: 'Total',
        q1: sum('q1'),
        q2: sum('q2'),
        q3: sum('q3'),
        q4: sum('q4'),
        plan: sum('plan'),
        gap: sum('gap'),
      },
    ],
    rowKey: 'id',
    showHeader: false,
    autoGridHeight: true,
    ariaLabel: 'Totals grid',
  });
  // The first grid (header) is the master, so drag column widths in the header.
  grids = [header, api, bottom];
  link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
  const offs = grids.map((grid, index) => grid.on('gridsAligned', (e) => log(`${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`)));
  log('Drag a column width or move a title in the top header and the body and totals grids follow.');
  return () => {
    offs.forEach((off) => off());
    link?.unlink();
    [grids[0], grids[2]].forEach((grid) => grid?.destroy());
    hosts.forEach((host) => host.remove());
    grids = [];
    hosts = [];
    link = null;
  };
}
export const actions = {
  // Widen the Item column.
  widen: (api) => {
    const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
    api.resizeColumn('item', width + 50);
  },
  // Move the Gap column to the front.
  move: (api) => api.moveColumn('gap', 0),
  // Hide or show the Plan column.
  plan: (api) => {
    const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
    api.setColumnVisible('plan', hidden);
  },
};