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

서버 페이징에서 필터 트리를 서버로 보내기Send the filter tree to the server with server paging

서버 페이징에서는 그리드가 행을 거르지 않고, 필터 빌더가 만든 트리를 loadPage 요청의 filter.tree로 그대로 보내요. 여기서는 모의 서버가 그 트리를 따라 내려가며 판정해요(실제 서버는 WHERE 조건으로 바꿔요).With server paging the grid does not filter rows; the tree the filter builder makes goes to the server as filter.tree in the loadPage request. Here a mock server walks that tree to decide (a real server would turn it into WHERE conditions).

심화Advanced
직접 써 보기Live preview서버 페이징에서 필터 트리를 서버로 보내기Send the filter tree to the server with server paging

코드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="open">필터 빌더 열기</button>
    <button type="button" id="clear">필터 지우기</button>
  </div>
  <div id="grid" style="height: 520px"></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('open').addEventListener('click', () => actions.open(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const cities = ['서울', '부산', '대구', '광주'];
const ALL = Array.from({ length: 80 }, (_, i) => ({
  id: i + 1,
  name: `상품 ${i + 1}`,
  city: cities[i % 4],
  price: 1000 + ((i * 370) % 9000),
}));
let say = () => undefined;
/** 모의 서버가 조건 하나를 판정해요. 실제 서버라면 SQL의 WHERE 조각으로 바꾸는 자리예요. */
function test(row, item) {
  const cell = row[item.columnId];
  const value = item.value;
  switch (item.operator) {
    case 'equals':
      return cell === value;
    case 'notEquals':
      return cell !== value;
    case 'contains':
      return String(cell).includes(String(value));
    case 'notContains':
      return !String(cell).includes(String(value));
    case 'gt':
      return Number(cell) > Number(value);
    case 'gte':
      return Number(cell) >= Number(value);
    case 'lt':
      return Number(cell) < Number(value);
    case 'lte':
      return Number(cell) <= Number(value);
    default:
      return true;
  }
}
/** 트리를 그대로 따라 내려가며 판정해요(묶음은 모두/하나라도, NOT은 뒤집기). */
function matches(row, node) {
  if (!('children' in node))
    return test(row, node);
  if (node.children.length === 0)
    return true;
  const results = node.children.map((child) => matches(row, child));
  const ok = node.match === 'all' ? results.every(Boolean) : results.some(Boolean);
  return node.not === true ? !ok : ok;
}
// 서버 페이징에서는 그리드가 거르지 않아요. 필터 빌더의 트리는 loadPage 요청의 filter.tree로 서버에 JSON 그대로 가요.
async function loadPage(query) {
  const tree = query.filter?.tree;
  say({
    ko: `요청: ${query.page}쪽 · 필터 ${tree === undefined ? '(없음)' : JSON.stringify(tree)}`,
    en: `Request: page ${query.page} · filter ${tree === undefined ? '(none)' : JSON.stringify(tree)}`,
  });
  const hit = tree === undefined ? ALL : ALL.filter((row) => matches(row, tree));
  await new Promise((resolve) => setTimeout(resolve, 200));
  return {
    rows: hit.slice((query.page - 1) * query.pageSize, query.page * query.pageSize),
    totalRows: hit.length,
  };
}
export const options = {
  filterBuilder: true,
  columns: [
    { id: 'id', title: '번호', kind: 'number', width: 80 },
    { id: 'name', title: '이름', width: 120 },
    { id: 'city', title: '도시', width: 90 },
    { id: 'price', title: '가격(원)', kind: 'number', width: 120, align: 'end' },
  ],
  rows: [],
  rowKey: 'id',
  pagination: { mode: 'server', pageSize: 8, loadPage },
};
export function setup(_api, log) {
  say = log;
  return () => {
    say = () => undefined;
  };
}
export const actions = {
  open: (api) => void api.openFilterBuilder(),
  clear: (api) => api.setFilterTree(null),
};

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="open">Open filter builder</button>
    <button type="button" id="clear">Clear filter</button>
  </div>
  <div id="grid" style="height: 520px"></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('open').addEventListener('click', () => actions.open(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const cities = ['Seattle', 'Austin', 'Denver', 'Boston'];
const ALL = Array.from({ length: 80 }, (_, i) => ({
  id: i + 1,
  name: `Product ${i + 1}`,
  city: cities[i % 4],
  price: 1 + ((i * 370) % 9000) / 1000,
}));
let say = () => undefined;
/** The mock server tests one condition. A real server would turn it into a piece of a WHERE clause. */
function test(row, item) {
  const cell = row[item.columnId];
  const value = item.value;
  switch (item.operator) {
    case 'equals':
      return cell === value;
    case 'notEquals':
      return cell !== value;
    case 'contains':
      return String(cell).includes(String(value));
    case 'notContains':
      return !String(cell).includes(String(value));
    case 'gt':
      return Number(cell) > Number(value);
    case 'gte':
      return Number(cell) >= Number(value);
    case 'lt':
      return Number(cell) < Number(value);
    case 'lte':
      return Number(cell) <= Number(value);
    default:
      return true;
  }
}
/** Walks the tree as it is (groups: all / any, NOT: flip the result). */
function matches(row, node) {
  if (!('children' in node))
    return test(row, node);
  if (node.children.length === 0)
    return true;
  const results = node.children.map((child) => matches(row, child));
  const ok = node.match === 'all' ? results.every(Boolean) : results.some(Boolean);
  return node.not === true ? !ok : ok;
}
// With server paging the grid does not filter. The filter builder's tree goes to the server as JSON in the loadPage request (filter.tree).
async function loadPage(query) {
  const tree = query.filter?.tree;
  say(`Request: page ${query.page} · filter ${tree === undefined ? '(none)' : JSON.stringify(tree)}`);
  const hit = tree === undefined ? ALL : ALL.filter((row) => matches(row, tree));
  await new Promise((resolve) => setTimeout(resolve, 200));
  return {
    rows: hit.slice((query.page - 1) * query.pageSize, query.page * query.pageSize),
    totalRows: hit.length,
  };
}
export const options = {
  filterBuilder: true,
  columns: [
    { id: 'id', title: 'No.', kind: 'number', width: 80 },
    { id: 'name', title: 'Name', width: 130 },
    { id: 'city', title: 'City', width: 100 },
    {
      id: 'price',
      title: 'Price (USD)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => `$${Number(value).toFixed(2)}`,
    },
  ],
  rows: [],
  rowKey: 'id',
  pagination: { mode: 'server', pageSize: 8, loadPage },
};
export function setup(_api, log) {
  say = log;
  return () => {
    say = () => undefined;
  };
}
export const actions = {
  open: (api) => void api.openFilterBuilder(),
  clear: (api) => api.setFilterTree(null),
};