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

접었다 펴도 상세 패널 입력 그대로 두기Keep detail panels alive when collapsed

주문 줄을 보여 주는 상세 패널을 접어도 부수지 않고 보관해요. 다시 펼치면 안쪽 그리드에 고친 값이 그대로 있어요. 보관은 최대 2개까지예요.Collapsing a detail panel with order lines keeps it instead of destroying it. Expand it again and the edited values are still in the inner grid. At most 2 panels are kept.

심화Advanced
직접 써 보기Live preview접었다 펴도 상세 패널 입력 그대로 두기Keep detail panels alive when collapsed

코드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="keep">
      <option value="on" selected>켜기</option>
      <option value="off">끄기</option>
    </select>
    <button type="button" id="showState">상태 보기</button>
    <button type="button" id="destroyFirst">펼친 패널 부수기</button>
  </div>
  <div id="grid" style="height: 480px"></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('keep').addEventListener('change', (event) => actions.keep(api, event.target.value));
document.getElementById('showState').addEventListener('click', () => actions.showState(api));
document.getElementById('destroyFirst').addEventListener('click', () => actions.destroyFirst(api));
example.js
const rows = [
  { id: 1, customer: '김하늘', status: '준비' },
  { id: 2, customer: '이도윤', status: '배송' },
  { id: 3, customer: '박서연', status: '완료' },
  { id: 4, customer: '최지우', status: '준비' },
];
const lines = [
  { id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
  { id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
  { id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
  { id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
  { id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
  { id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
  { id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
  { id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
  { id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
  { id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
// 렌더러 함수는 한 번만 만들어서 옵션을 다시 만들어도 같은 것을 써요.
const renderer = () => {
  let grid = null;
  let off;
  return {
    mount(element, { row, attachGrid }) {
      element.style.padding = '8px 16px';
      const host = document.createElement('div');
      host.style.height = '130px';
      element.replaceChildren(host);
      grid = MaxGrid.createGrid(host, {
        columns: [
          { id: 'item', title: '상품', width: 140 },
          { id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
          {
            id: 'price',
            title: '단가',
            kind: 'number',
            width: 110,
            editable: true,
            formatValue: won,
          },
        ],
        rows: lines.filter((l) => l.orderId === row.id),
        rowKey: 'id',
        saveMode: 'batch',
        ariaLabel: `${row.customer} 주문 줄`,
      });
      off = attachGrid?.(grid);
    },
    update() { },
    destroy() {
      off?.();
      grid?.destroy();
      grid = null;
    },
  };
};
// 보관 옵션만 바꿔서 setOptions로 다시 넘겨요.
const detailOf = (keepAlive) => ({
  keepAlive,
  maxKeepAlive: 2,
  renderer,
  height: 190,
});
export const options = {
  columns: [
    { id: 'id', title: '주문 번호', kind: 'number', width: 100 },
    { id: 'customer', title: '고객', width: 130 },
    { id: 'status', title: '상태', width: 90 },
  ],
  rows,
  rowKey: 'id',
  detail: { ...detailOf(true), expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
  logger = log;
  const off = api.on('detailChanged', ({ rowKey, expanded }) => {
    log({
      ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
      en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
    });
  });
  return () => off();
}
export const actions = {
  keep: (api, value) => {
    api.setOptions({ detail: detailOf(value !== 'off') });
  },
  showState: (api) => {
    for (const row of api.getRows()) {
      const s = api.getDetailState(row.id);
      logger({
        ko: `${row.id}번: 펼침 ${s.expanded ? '예' : '아니오'}, 만들어짐 ${s.mounted ? '예' : '아니오'}, 저장 안 된 편집 ${s.dirty ? '있음' : '없음'}`,
        en: `Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`,
      });
    }
  },
  destroyFirst: (api) => {
    const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
    api.destroyDetail(row.id);
    logger({ ko: `${row.id}번 패널을 부쉈어요`, en: `Destroyed the panel of order ${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="Keep" id="keep">
      <option value="on" selected>On</option>
      <option value="off">Off</option>
    </select>
    <button type="button" id="showState">Show state</button>
    <button type="button" id="destroyFirst">Destroy open panel</button>
  </div>
  <div id="grid" style="height: 480px"></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('keep').addEventListener('change', (event) => actions.keep(api, event.target.value));
document.getElementById('showState').addEventListener('click', () => actions.showState(api));
document.getElementById('destroyFirst').addEventListener('click', () => actions.destroyFirst(api));
example.js
const rows = [
  { id: 1, customer: 'Liam Carter', status: 'Pending' },
  { id: 2, customer: 'Emma Stone', status: 'Shipping' },
  { id: 3, customer: 'Noah Reed', status: 'Done' },
  { id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines = [
  { id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
  { id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
  { id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
  { id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
  { id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
  { id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
  { id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
  { id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
  { id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
  { id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
// The renderer function is created once, so rebuilding the options reuses the same one.
const renderer = () => {
  let grid = null;
  let off;
  return {
    mount(element, { row, attachGrid }) {
      element.style.padding = '8px 16px';
      const host = document.createElement('div');
      host.style.height = '130px';
      element.replaceChildren(host);
      grid = MaxGrid.createGrid(host, {
        columns: [
          { id: 'item', title: 'Item', width: 140 },
          { id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
          {
            id: 'price',
            title: 'Unit price',
            kind: 'number',
            width: 110,
            editable: true,
            formatValue: dollars,
          },
        ],
        rows: lines.filter((l) => l.orderId === row.id),
        rowKey: 'id',
        saveMode: 'batch',
        ariaLabel: `${row.customer} order lines`,
      });
      off = attachGrid?.(grid);
    },
    update() { },
    destroy() {
      off?.();
      grid?.destroy();
      grid = null;
    },
  };
};
// Only the keep-alive flag changes; the object is passed again through setOptions.
const detailOf = (keepAlive) => ({
  keepAlive,
  maxKeepAlive: 2,
  renderer,
  height: 190,
});
export const options = {
  columns: [
    { id: 'id', title: 'Order ID', kind: 'number', width: 100 },
    { id: 'customer', title: 'Customer', width: 130 },
    { id: 'status', title: 'Status', width: 90 },
  ],
  rows,
  rowKey: 'id',
  detail: { ...detailOf(true), expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
  logger = log;
  const off = api.on('detailChanged', ({ rowKey, expanded }) => {
    log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
  });
  return () => off();
}
export const actions = {
  keep: (api, value) => {
    api.setOptions({ detail: detailOf(value !== 'off') });
  },
  showState: (api) => {
    for (const row of api.getRows()) {
      const s = api.getDetailState(row.id);
      logger(`Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`);
    }
  },
  destroyFirst: (api) => {
    const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
    api.destroyDetail(row.id);
    logger(`Destroyed the panel of order ${row.id}`);
  },
};