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

고객을 열어 주문 내역 보기Open a customer to see their orders

고객 줄 아래에 주문 내역 패널이 펼쳐져요. 여러 개를 동시에 열 수도, 하나만 열 수도, 행을 고를 때마다 상세가 따라오게 할 수도 있어요.A panel with the customer's orders opens right under the row. Open several at once, only one, or let the panel follow the selected row.

활용Intermediate
직접 써 보기Live preview고객을 열어 주문 내역 보기Open a customer to see their orders

코드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="mode">
      <option value="free" selected>마음대로 여러 개</option>
      <option value="one">하나만 열기</option>
      <option value="follow">행을 고르면 따라가기</option>
    </select>
    <button type="button" id="closeAll">모두 닫기</button>
  </div>
  <div id="grid" style="height: 460px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('closeAll').addEventListener('click', () => actions.closeAll(api));
example.js
const customers = [
  '한빛물류',
  '푸른식품',
  '북촌상회',
  '단풍리테일',
  '정상테크',
  '바다수산',
  '새봄약품',
  '은하전자',
];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const products = [
  'A4 복사지',
  '라벨 스티커',
  '박스 테이프',
  '포장 완충재',
  '바코드 라벨러',
  '스트레치 필름',
];
// 고객마다 주문이 2~5건. 상세 패널에서 보여 줄 주문 내역을 고객 번호로 만들어요.
// 실제로는 고객 번호로 서버에 요청해서 받아 오는 자리예요.
function ordersOf(index) {
  return Array.from({ length: 2 + (index % 4) }, (_, k) => {
    const qty = 1 + ((index * 3 + k * 5) % 9);
    const price = 4000 + ((index + k) % 6) * 2500;
    return {
      date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
      product: products[(index + k * 2) % products.length],
      qty,
      amount: qty * price,
    };
  });
}
const rows = customers.map((customer, i) => ({
  id: `cust${i + 1}`,
  customer,
  city: cities[i],
  orders: ordersOf(i).length,
  total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const won = (value) => `${value.toLocaleString('ko-KR')}원`;
// 상세 패널은 어댑터가 만들어요. 값은 항상 textContent로 넣어서 HTML로 해석되지 않아요.
const panel = () => {
  let box;
  const fill = (row) => {
    const index = rows.findIndex((r) => r.id === row.id);
    const head = document.createElement('strong');
    head.textContent = `${row.customer} 주문 내역 (${row.orders}건)`;
    const table = document.createElement('table');
    table.style.cssText =
      'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
    const line = (cells, bold) => {
      const tr = document.createElement('tr');
      cells.forEach((text, c) => {
        const td = document.createElement(bold ? 'th' : 'td');
        td.textContent = text;
        td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
        tr.append(td);
      });
      return tr;
    };
    table.append(line(['주문일', '상품', '수량', '금액'], true));
    for (const o of ordersOf(index))
      table.append(line([o.date, o.product, String(o.qty), won(o.amount)], false));
    // 좁은 화면에서는 표만 옆으로 스크롤돼요.
    const scroller = document.createElement('div');
    scroller.style.overflowX = 'auto';
    scroller.append(table);
    box.replaceChildren(head, scroller);
  };
  return {
    mount(element, { row }) {
      box = element;
      element.style.padding = '8px 16px';
      fill(row);
    },
    update({ row }) {
      fill(row);
    },
    destroy() { },
  };
};
export const options = {
  columns: [
    { id: 'customer', title: '고객', width: 150 },
    { id: 'city', title: '지역', width: 90 },
    { id: 'orders', title: '주문 수', kind: 'number', width: 90, align: 'end' },
    {
      id: 'total',
      title: '주문 합계',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (v) => won(Number(v)),
    },
  ],
  rows,
  rowKey: 'id',
  selection: 'single',
  // 주문이 많은 고객일수록 패널을 더 높게. 처음에는 3번 고객(cust3)이 열려 있어요.
  detail: {
    renderer: panel,
    height: (row) => 62 + row.orders * 25,
    expanded: ['cust3'],
  },
};
let mode = 'free';
let busy = false; // 우리가 열고 닫는 동안 오는 이벤트는 무시해서 서로 부르지 않게 해요.
function openOnly(api, key) {
  busy = true;
  for (const row of api.getRows())
    if (row.id !== key && api.isDetailExpanded(row.id))
      api.collapseDetail(row.id);
  if (!api.isDetailExpanded(key))
    api.expandDetail(key);
  busy = false;
}
export function setup(api, log) {
  const nameOf = (key) => api.getRowByKey(key)?.customer ?? key;
  const offs = [
    api.on('detailChanged', ({ rowKey, expanded }) => {
      log({
        ko: `${nameOf(String(rowKey))} 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
        en: `${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`,
      });
      if (!busy && expanded && mode === 'one')
        openOnly(api, String(rowKey));
    }),
    api.on('selectionChanged', ({ selectedKeys }) => {
      const key = selectedKeys[0];
      if (mode === 'follow' && key !== undefined && !busy)
        openOnly(api, String(key));
    }),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  mode: (api, value) => {
    mode = value === 'one' || value === 'follow' ? value : 'free';
    const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
    if (mode !== 'free' && open.length > 1)
      openOnly(api, open[0].id);
  },
  closeAll: (api) => {
    for (const row of api.getRows())
      if (api.isDetailExpanded(row.id))
        api.collapseDetail(row.id);
  },
};

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="Open mode" id="mode">
      <option value="free" selected>Any number</option>
      <option value="one">One at a time</option>
      <option value="follow">Follow the selected row</option>
    </select>
    <button type="button" id="closeAll">Close all</button>
  </div>
  <div id="grid" style="height: 460px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('closeAll').addEventListener('click', () => actions.closeAll(api));
example.js
const customers = [
  'Northwind Logistics',
  'Greenfield Foods',
  'Maple Trading',
  'Autumn Retail',
  'Summit Tech',
  'Ocean Seafood',
  'Springtime Pharma',
  'Galaxy Electronics',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const products = [
  'A4 Copy Paper',
  'Label Stickers',
  'Packing Tape',
  'Bubble Wrap',
  'Barcode Labeler',
  'Stretch Film',
];
// Each customer has 2 to 5 orders. The order history for the detail panel is built from the customer index.
// In practice this is where you would request it from the server by customer number.
function ordersOf(index) {
  return Array.from({ length: 2 + (index % 4) }, (_, k) => {
    const qty = 1 + ((index * 3 + k * 5) % 9);
    const price = 4 + ((index + k) % 6) * 2.5;
    return {
      date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
      product: products[(index + k * 2) % products.length],
      qty,
      amount: qty * price,
    };
  });
}
const rows = customers.map((customer, i) => ({
  id: `cust${i + 1}`,
  customer,
  city: cities[i],
  orders: ordersOf(i).length,
  total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const money = (value) => `$${value.toLocaleString('en-US')}`;
// The detail panel is built by an adapter. Values always go in via textContent, so they are never parsed as HTML.
const panel = () => {
  let box;
  const fill = (row) => {
    const index = rows.findIndex((r) => r.id === row.id);
    const head = document.createElement('strong');
    head.textContent = `${row.customer} orders (${row.orders})`;
    const table = document.createElement('table');
    table.style.cssText =
      'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
    const line = (cells, bold) => {
      const tr = document.createElement('tr');
      cells.forEach((text, c) => {
        const td = document.createElement(bold ? 'th' : 'td');
        td.textContent = text;
        td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
        tr.append(td);
      });
      return tr;
    };
    table.append(line(['Order date', 'Product', 'Qty', 'Amount'], true));
    for (const o of ordersOf(index))
      table.append(line([o.date, o.product, String(o.qty), money(o.amount)], false));
    // On a narrow screen only the table scrolls sideways.
    const scroller = document.createElement('div');
    scroller.style.overflowX = 'auto';
    scroller.append(table);
    box.replaceChildren(head, scroller);
  };
  return {
    mount(element, { row }) {
      box = element;
      element.style.padding = '8px 16px';
      fill(row);
    },
    update({ row }) {
      fill(row);
    },
    destroy() { },
  };
};
export const options = {
  columns: [
    { id: 'customer', title: 'Customer', width: 170 },
    { id: 'city', title: 'City', width: 90 },
    { id: 'orders', title: 'Orders', kind: 'number', width: 90, align: 'end' },
    {
      id: 'total',
      title: 'Order total',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (v) => money(Number(v)),
    },
  ],
  rows,
  rowKey: 'id',
  selection: 'single',
  // The more orders a customer has, the taller the panel. At first customer 3 (cust3) is open.
  detail: {
    renderer: panel,
    height: (row) => 62 + row.orders * 25,
    expanded: ['cust3'],
  },
};
let mode = 'free';
let busy = false; // Ignore events that arrive while we open and close panels, so they do not trigger each other.
function openOnly(api, key) {
  busy = true;
  for (const row of api.getRows())
    if (row.id !== key && api.isDetailExpanded(row.id))
      api.collapseDetail(row.id);
  if (!api.isDetailExpanded(key))
    api.expandDetail(key);
  busy = false;
}
export function setup(api, log) {
  const nameOf = (key) => api.getRowByKey(key)?.customer ?? key;
  const offs = [
    api.on('detailChanged', ({ rowKey, expanded }) => {
      log(`${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`);
      if (!busy && expanded && mode === 'one')
        openOnly(api, String(rowKey));
    }),
    api.on('selectionChanged', ({ selectedKeys }) => {
      const key = selectedKeys[0];
      if (mode === 'follow' && key !== undefined && !busy)
        openOnly(api, String(key));
    }),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  mode: (api, value) => {
    mode = value === 'one' || value === 'follow' ? value : 'free';
    const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
    if (mode !== 'free' && open.length > 1)
      openOnly(api, open[0].id);
  },
  closeAll: (api) => {
    for (const row of api.getRows())
      if (api.isDetailExpanded(row.id))
        api.collapseDetail(row.id);
  },
};