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

저장 안 된 편집이 있으면 정렬·필터 막기Block sort and filter while edits are unsaved

상세 패널 안 그리드에 저장 안 된 편집이 있는 동안에는 마스터의 정렬과 필터가 막히고, 막을 때마다 로그가 남아요. 편집을 버리면 다시 풀려요.While the grid inside a detail panel has unsaved edits, sorting and filtering of the master are blocked and each block is logged. Discard the edits and they work again.

심화Advanced
직접 써 보기Live preview저장 안 된 편집이 있으면 정렬·필터 막기Block sort and filter while edits are unsaved

코드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="sortDesc">고객 내림차순 정렬</button>
    <button type="button" id="filterOne">준비만 보기</button>
    <button type="button" id="clear">정렬·필터 지우기</button>
    <button type="button" id="discard">편집 버리기</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('sortDesc').addEventListener('click', () => actions.sortDesc(api));
document.getElementById('filterOne').addEventListener('click', () => actions.filterOne(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(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')}원`;
// 패널 안의 그리드를 모아 둬요. 버리기 버튼이 이 목록을 써요.
const inner = new Map();
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = () => {
  let grid = null;
  let off;
  let id = 0;
  return {
    mount(element, { row, attachGrid }) {
      id = row.id;
      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} 주문 줄`,
      });
      inner.set(id, grid);
      off = attachGrid?.(grid);
    },
    update() { },
    destroy() {
      off?.();
      inner.delete(id);
      grid?.destroy();
      grid = null;
    },
  };
};
export const options = {
  columns: [
    { id: 'id', title: '주문 번호', kind: 'number', width: 100 },
    { id: 'customer', title: '고객', width: 130 },
    { id: 'status', title: '상태', width: 90 },
  ],
  rows,
  rowKey: 'id',
  filterRow: true,
  detail: { dirtyLock: true, renderer, height: 190, expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
  logger = log;
  const actionKo = { sort: '정렬', filter: '필터', page: '쪽 이동', group: '그룹' };
  const actionEn = { sort: 'sort', filter: 'filter', page: 'page change', group: 'grouping' };
  const offs = [
    api.on('detailDirtyBlocked', ({ rowKeys, action }) => {
      log({
        ko: `${actionKo[action]}을(를) 막았어요. 저장 안 된 편집이 있는 주문: ${rowKeys.join(', ')}`,
        en: `Blocked ${actionEn[action]}. Orders with unsaved edits: ${rowKeys.join(', ')}`,
      });
    }),
    api.on('detailSaved', ({ rowKey }) => {
      log({ ko: `${rowKey}번 주문 줄을 저장했어요`, en: `Saved the lines of order ${rowKey}` });
    }),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  sortDesc: (api) => {
    api.setSortModel([{ columnId: 'customer', direction: 'desc' }]);
  },
  filterOne: (api) => {
    api.setFilterModel({
      match: 'all',
      items: [{ columnId: 'status', operator: 'equals', value: '준비' }],
    });
  },
  clear: (api) => {
    api.setSortModel([]);
    api.setFilterModel(null);
  },
  discard: (_api) => {
    let count = 0;
    for (const grid of inner.values()) {
      count += grid.revertRows(grid.getChanges().map((c) => c.key));
    }
    logger({
      ko: `저장 안 된 편집 ${count}건을 되돌렸어요`,
      en: `Reverted ${count} unsaved edit(s)`,
    });
  },
};

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="sortDesc">Sort customer descending</button>
    <button type="button" id="filterOne">Show Pending only</button>
    <button type="button" id="clear">Clear sort and filter</button>
    <button type="button" id="discard">Discard edits</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('sortDesc').addEventListener('click', () => actions.sortDesc(api));
document.getElementById('filterOne').addEventListener('click', () => actions.filterOne(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(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)}`;
// Keeps the grids inside the panels. The discard button uses this map.
const inner = new Map();
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = () => {
  let grid = null;
  let off;
  let id = 0;
  return {
    mount(element, { row, attachGrid }) {
      id = row.id;
      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`,
      });
      inner.set(id, grid);
      off = attachGrid?.(grid);
    },
    update() { },
    destroy() {
      off?.();
      inner.delete(id);
      grid?.destroy();
      grid = null;
    },
  };
};
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',
  filterRow: true,
  detail: { dirtyLock: true, renderer, height: 190, expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
  logger = log;
  const names = { sort: 'sort', filter: 'filter', page: 'page change', group: 'grouping' };
  const offs = [
    api.on('detailDirtyBlocked', ({ rowKeys, action }) => {
      log(`Blocked ${names[action]}. Orders with unsaved edits: ${rowKeys.join(', ')}`);
    }),
    api.on('detailSaved', ({ rowKey }) => {
      log(`Saved the lines of order ${rowKey}`);
    }),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  sortDesc: (api) => {
    api.setSortModel([{ columnId: 'customer', direction: 'desc' }]);
  },
  filterOne: (api) => {
    api.setFilterModel({
      match: 'all',
      items: [{ columnId: 'status', operator: 'equals', value: 'Pending' }],
    });
  },
  clear: (api) => {
    api.setSortModel([]);
    api.setFilterModel(null);
  },
  discard: (_api) => {
    let count = 0;
    for (const grid of inner.values()) {
      count += grid.revertRows(grid.getChanges().map((c) => c.key));
    }
    logger(`Reverted ${count} unsaved edit(s)`);
  },
};