서버에서 정렬·필터하기 (오래된 응답 버리기)Sort and filter on the server (drop stale answers)
정렬이나 필터가 바뀔 때마다 서버에 다시 물어보는 구조예요. 응답이 늦게 오는 순서가 뒤바뀌어도 화면이 옛 결과로 돌아가지 않도록, 요청마다 번호를 붙여 가장 최근 번호의 응답만 반영해요.Every sort or filter change asks the server again. To keep a slow old answer from replacing a newer one, each request gets a number and only the latest is applied.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<select aria-label="지역" id="region">
<option value="all" selected>전체 (기본)</option>
<option value="seoul">서울</option>
<option value="gyeonggi">경기</option>
<option value="busan">부산</option>
<option value="daegu">대구</option>
</select>
<button type="button" id="amountDesc">금액 큰 순</button>
<button type="button" id="amountAsc">금액 작은 순</button>
</div>
<div id="grid" style="height: 560px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('amountDesc').addEventListener('click', () => actions.amountDesc(api));
document.getElementById('amountAsc').addEventListener('click', () => actions.amountAsc(api));export const options = {
columns: [
{ id: 'name', title: '고객', width: 170 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액(천원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// 서버 대신 정렬·필터해서 처음 14건을 돌려주는 함수예요. 응답은 일부러 늦게 오는데, 큰 순 정렬은 1.2초, 나머지는 0.5초 걸려요.
const REGIONS = ['서울', '경기', '부산', '대구'];
// 지역 선택 목록은 영문 id를 넘겨요. 표에 쓰는 지역 이름으로 바꿔요.
const REGION_BY_ID = {
seoul: '서울',
gyeonggi: '경기',
busan: '부산',
daegu: '대구',
};
const TABLE = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `고객 ${i + 1}`,
region: REGIONS[i % REGIONS.length],
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort, filter) {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) => setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay));
}
let latest = 0;
// 정렬이나 필터가 바뀔 때마다 서버에 다시 물어요. 느린 옛 응답이 새 응답을 덮어쓰면 안 되니까,
// 요청마다 번호를 붙이고 가장 최근 번호의 응답만 반영해요.
async function load(api, log) {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log({
ko: `#${request} 요청: 정렬 ${sort[0] ? `${sort[0].columnId === 'amount' ? '금액' : '고객'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : '없음'}, 지역 ${region ?? '전체'}`,
en: `#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`,
});
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed())
return;
if (request !== latest)
return log({
ko: `#${request} 응답은 더 새 요청이 있어서 버렸어요`,
en: `#${request} response dropped because a newer request exists`,
});
api.setRows(rows);
api.setOptions({ loading: false });
log({ ko: `#${request} 반영: ${rows.length}행`, en: `#${request} applied: ${rows.length} rows` });
}
export function setup(api, log) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // 정리한 뒤에 오는 응답은 버려요
offs.forEach((off) => off());
};
}
export const actions = {
region: (api, value) => api.setFilterModel(value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_BY_ID[value] ?? value },
],
}
: null),
amountDesc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>서버에서 정렬·필터하기 (오래된 응답 버리기)</title>
</head>
<body>
<div class="toolbar">
<select aria-label="지역" id="region">
<option value="all" selected>전체 (기본)</option>
<option value="seoul">서울</option>
<option value="gyeonggi">경기</option>
<option value="busan">부산</option>
<option value="daegu">대구</option>
</select>
<button type="button" id="amountDesc">금액 큰 순</button>
<button type="button" id="amountAsc">금액 작은 순</button>
</div>
<div id="grid" style="height: 560px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const options = {
columns: [
{ id: 'name', title: '고객', width: 170 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액(천원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// 서버 대신 정렬·필터해서 처음 14건을 돌려주는 함수예요. 응답은 일부러 늦게 오는데, 큰 순 정렬은 1.2초, 나머지는 0.5초 걸려요.
const REGIONS = ['서울', '경기', '부산', '대구'];
// 지역 선택 목록은 영문 id를 넘겨요. 표에 쓰는 지역 이름으로 바꿔요.
const REGION_BY_ID = {
seoul: '서울',
gyeonggi: '경기',
busan: '부산',
daegu: '대구',
};
const TABLE = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `고객 ${i + 1}`,
region: REGIONS[i % REGIONS.length],
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort, filter) {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) => setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay));
}
let latest = 0;
// 정렬이나 필터가 바뀔 때마다 서버에 다시 물어요. 느린 옛 응답이 새 응답을 덮어쓰면 안 되니까,
// 요청마다 번호를 붙이고 가장 최근 번호의 응답만 반영해요.
async function load(api, log) {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log({
ko: `#${request} 요청: 정렬 ${sort[0] ? `${sort[0].columnId === 'amount' ? '금액' : '고객'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : '없음'}, 지역 ${region ?? '전체'}`,
en: `#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`,
});
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed())
return;
if (request !== latest)
return log({
ko: `#${request} 응답은 더 새 요청이 있어서 버렸어요`,
en: `#${request} response dropped because a newer request exists`,
});
api.setRows(rows);
api.setOptions({ loading: false });
log({ ko: `#${request} 반영: ${rows.length}행`, en: `#${request} applied: ${rows.length} rows` });
}
function setup(api, log) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // 정리한 뒤에 오는 응답은 버려요
offs.forEach((off) => off());
};
}
const actions = {
region: (api, value) => api.setFilterModel(value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_BY_ID[value] ?? value },
],
}
: null),
amountDesc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};
options.ariaLabel = "서버에서 정렬·필터하기 (오래된 응답 버리기)";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('amountDesc').addEventListener('click', () => actions.amountDesc(api));
document.getElementById('amountAsc').addEventListener('click', () => actions.amountAsc(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="지역"
disabled={!api}
onChange={(event) => api && actions.region(api, event.target.value)}
>
<option value="all">전체 (기본)</option>
<option value="seoul">서울</option>
<option value="gyeonggi">경기</option>
<option value="busan">부산</option>
<option value="daegu">대구</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.amountDesc(api)}
>금액 큰 순</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.amountAsc(api)}
>금액 작은 순</button>
</div>
<Grid style={{ height: 560 }} ref={gridRef} options={options} />
</>
);
}import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
region: string;
amount: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '고객', width: 170 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액(천원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// 서버 대신 정렬·필터해서 처음 14건을 돌려주는 함수예요. 응답은 일부러 늦게 오는데, 큰 순 정렬은 1.2초, 나머지는 0.5초 걸려요.
const REGIONS = ['서울', '경기', '부산', '대구'];
// 지역 선택 목록은 영문 id를 넘겨요. 표에 쓰는 지역 이름으로 바꿔요.
const REGION_BY_ID: Record<string, string> = {
seoul: '서울',
gyeonggi: '경기',
busan: '부산',
daegu: '대구',
};
const TABLE: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `고객 ${i + 1}`,
region: REGIONS[i % REGIONS.length] as string,
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort: SortItem[], filter: FilterModel | null): Promise<Row[]> {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) =>
setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId as keyof Row;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay),
);
}
let latest = 0;
// 정렬이나 필터가 바뀔 때마다 서버에 다시 물어요. 느린 옛 응답이 새 응답을 덮어쓰면 안 되니까,
// 요청마다 번호를 붙이고 가장 최근 번호의 응답만 반영해요.
async function load(api: GridApi<Row>, log: (message: LogText) => void): Promise<void> {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log({
ko: `#${request} 요청: 정렬 ${sort[0] ? `${sort[0].columnId === 'amount' ? '금액' : '고객'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : '없음'}, 지역 ${region ?? '전체'}`,
en: `#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`,
});
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed()) return;
if (request !== latest)
return log({
ko: `#${request} 응답은 더 새 요청이 있어서 버렸어요`,
en: `#${request} response dropped because a newer request exists`,
});
api.setRows(rows);
api.setOptions({ loading: false });
log({ ko: `#${request} 반영: ${rows.length}행`, en: `#${request} applied: ${rows.length} rows` });
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // 정리한 뒤에 오는 응답은 버려요
offs.forEach((off) => off());
};
}
export const actions = {
region: (api: GridApi<Row>, value?: string) =>
api.setFilterModel(
value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_BY_ID[value] ?? value },
],
}
: null,
),
amountDesc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="지역"
:disabled="!api"
@change="api && actions.region(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>전체 (기본)</option>
<option value="seoul">서울</option>
<option value="gyeonggi">경기</option>
<option value="busan">부산</option>
<option value="daegu">대구</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.amountDesc(api)"
>금액 큰 순</button>
<button
type="button"
:disabled="!api"
@click="api && actions.amountAsc(api)"
>금액 작은 순</button>
</div>
<Grid style="height: 560px" :options="options" @ready="onReady" />
</template>import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
region: string;
amount: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '고객', width: 170 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액(천원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// 서버 대신 정렬·필터해서 처음 14건을 돌려주는 함수예요. 응답은 일부러 늦게 오는데, 큰 순 정렬은 1.2초, 나머지는 0.5초 걸려요.
const REGIONS = ['서울', '경기', '부산', '대구'];
// 지역 선택 목록은 영문 id를 넘겨요. 표에 쓰는 지역 이름으로 바꿔요.
const REGION_BY_ID: Record<string, string> = {
seoul: '서울',
gyeonggi: '경기',
busan: '부산',
daegu: '대구',
};
const TABLE: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `고객 ${i + 1}`,
region: REGIONS[i % REGIONS.length] as string,
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort: SortItem[], filter: FilterModel | null): Promise<Row[]> {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) =>
setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId as keyof Row;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay),
);
}
let latest = 0;
// 정렬이나 필터가 바뀔 때마다 서버에 다시 물어요. 느린 옛 응답이 새 응답을 덮어쓰면 안 되니까,
// 요청마다 번호를 붙이고 가장 최근 번호의 응답만 반영해요.
async function load(api: GridApi<Row>, log: (message: LogText) => void): Promise<void> {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log({
ko: `#${request} 요청: 정렬 ${sort[0] ? `${sort[0].columnId === 'amount' ? '금액' : '고객'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : '없음'}, 지역 ${region ?? '전체'}`,
en: `#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`,
});
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed()) return;
if (request !== latest)
return log({
ko: `#${request} 응답은 더 새 요청이 있어서 버렸어요`,
en: `#${request} response dropped because a newer request exists`,
});
api.setRows(rows);
api.setOptions({ loading: false });
log({ ko: `#${request} 반영: ${rows.length}행`, en: `#${request} applied: ${rows.length} rows` });
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // 정리한 뒤에 오는 응답은 버려요
offs.forEach((off) => off());
};
}
export const actions = {
region: (api: GridApi<Row>, value?: string) =>
api.setFilterModel(
value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_BY_ID[value] ?? value },
],
}
: null,
),
amountDesc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="지역"
[disabled]="!api"
(change)="api && actions.region(api, $any($event.target).value)"
>
<option value="all" selected>전체 (기본)</option>
<option value="seoul">서울</option>
<option value="gyeonggi">경기</option>
<option value="busan">부산</option>
<option value="daegu">대구</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.amountDesc(api)"
>금액 큰 순</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.amountAsc(api)"
>금액 작은 순</button>
</div>
<mx-grid style="height: 560px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
region: string;
amount: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '고객', width: 170 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액(천원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// 서버 대신 정렬·필터해서 처음 14건을 돌려주는 함수예요. 응답은 일부러 늦게 오는데, 큰 순 정렬은 1.2초, 나머지는 0.5초 걸려요.
const REGIONS = ['서울', '경기', '부산', '대구'];
// 지역 선택 목록은 영문 id를 넘겨요. 표에 쓰는 지역 이름으로 바꿔요.
const REGION_BY_ID: Record<string, string> = {
seoul: '서울',
gyeonggi: '경기',
busan: '부산',
daegu: '대구',
};
const TABLE: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `고객 ${i + 1}`,
region: REGIONS[i % REGIONS.length] as string,
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort: SortItem[], filter: FilterModel | null): Promise<Row[]> {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) =>
setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId as keyof Row;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay),
);
}
let latest = 0;
// 정렬이나 필터가 바뀔 때마다 서버에 다시 물어요. 느린 옛 응답이 새 응답을 덮어쓰면 안 되니까,
// 요청마다 번호를 붙이고 가장 최근 번호의 응답만 반영해요.
async function load(api: GridApi<Row>, log: (message: LogText) => void): Promise<void> {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log({
ko: `#${request} 요청: 정렬 ${sort[0] ? `${sort[0].columnId === 'amount' ? '금액' : '고객'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : '없음'}, 지역 ${region ?? '전체'}`,
en: `#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`,
});
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed()) return;
if (request !== latest)
return log({
ko: `#${request} 응답은 더 새 요청이 있어서 버렸어요`,
en: `#${request} response dropped because a newer request exists`,
});
api.setRows(rows);
api.setOptions({ loading: false });
log({ ko: `#${request} 반영: ${rows.length}행`, en: `#${request} applied: ${rows.length} rows` });
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // 정리한 뒤에 오는 응답은 버려요
offs.forEach((off) => off());
};
}
export const actions = {
region: (api: GridApi<Row>, value?: string) =>
api.setFilterModel(
value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_BY_ID[value] ?? value },
],
}
: null,
),
amountDesc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="Region" id="region">
<option value="all" selected>All (default)</option>
<option value="seoul">New York</option>
<option value="gyeonggi">Boston</option>
<option value="busan">Chicago</option>
<option value="daegu">Austin</option>
</select>
<button type="button" id="amountDesc">Amount high to low</button>
<button type="button" id="amountAsc">Amount low to high</button>
</div>
<div id="grid" style="height: 560px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('amountDesc').addEventListener('click', () => actions.amountDesc(api));
document.getElementById('amountAsc').addEventListener('click', () => actions.amountAsc(api));export const options = {
columns: [
{ id: 'name', title: 'Customer', width: 170 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'amount',
title: 'Amount ($1,000)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// A function that sorts and filters in place of a server and returns the first 14 rows. The response arrives late on purpose: a descending sort takes 1.2 s, the rest 0.5 s.
const REGIONS = ['New York', 'Boston', 'Chicago', 'Austin'];
// The region select passes ASCII ids, so map them to the region names used in the table.
const REGION_VALUES = {
seoul: 'New York',
gyeonggi: 'Boston',
busan: 'Chicago',
daegu: 'Austin',
};
const TABLE = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `Customer ${i + 1}`,
region: REGIONS[i % REGIONS.length],
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort, filter) {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) => setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay));
}
let latest = 0;
// Ask the server again whenever the sort or filter changes. A slow old response must not overwrite a new one,
// so number each request and apply only the response with the latest number.
async function load(api, log) {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log(`#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`);
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed())
return;
if (request !== latest)
return log(`#${request} response dropped because a newer request exists`);
api.setRows(rows);
api.setOptions({ loading: false });
log(`#${request} applied: ${rows.length} rows`);
}
export function setup(api, log) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // discard responses that arrive after cleanup
offs.forEach((off) => off());
};
}
export const actions = {
region: (api, value) => api.setFilterModel(value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_VALUES[value] ?? value },
],
}
: null),
amountDesc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Sort and filter on the server (drop stale answers)</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Region" id="region">
<option value="all" selected>All (default)</option>
<option value="seoul">New York</option>
<option value="gyeonggi">Boston</option>
<option value="busan">Chicago</option>
<option value="daegu">Austin</option>
</select>
<button type="button" id="amountDesc">Amount high to low</button>
<button type="button" id="amountAsc">Amount low to high</button>
</div>
<div id="grid" style="height: 560px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const options = {
columns: [
{ id: 'name', title: 'Customer', width: 170 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'amount',
title: 'Amount ($1,000)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// A function that sorts and filters in place of a server and returns the first 14 rows. The response arrives late on purpose: a descending sort takes 1.2 s, the rest 0.5 s.
const REGIONS = ['New York', 'Boston', 'Chicago', 'Austin'];
// The region select passes ASCII ids, so map them to the region names used in the table.
const REGION_VALUES = {
seoul: 'New York',
gyeonggi: 'Boston',
busan: 'Chicago',
daegu: 'Austin',
};
const TABLE = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `Customer ${i + 1}`,
region: REGIONS[i % REGIONS.length],
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort, filter) {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) => setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay));
}
let latest = 0;
// Ask the server again whenever the sort or filter changes. A slow old response must not overwrite a new one,
// so number each request and apply only the response with the latest number.
async function load(api, log) {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log(`#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`);
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed())
return;
if (request !== latest)
return log(`#${request} response dropped because a newer request exists`);
api.setRows(rows);
api.setOptions({ loading: false });
log(`#${request} applied: ${rows.length} rows`);
}
function setup(api, log) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // discard responses that arrive after cleanup
offs.forEach((off) => off());
};
}
const actions = {
region: (api, value) => api.setFilterModel(value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_VALUES[value] ?? value },
],
}
: null),
amountDesc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};
options.ariaLabel = "Sort and filter on the server (drop stale answers)";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('amountDesc').addEventListener('click', () => actions.amountDesc(api));
document.getElementById('amountAsc').addEventListener('click', () => actions.amountAsc(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="Region"
disabled={!api}
onChange={(event) => api && actions.region(api, event.target.value)}
>
<option value="all">All (default)</option>
<option value="seoul">New York</option>
<option value="gyeonggi">Boston</option>
<option value="busan">Chicago</option>
<option value="daegu">Austin</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.amountDesc(api)}
>Amount high to low</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.amountAsc(api)}
>Amount low to high</button>
</div>
<Grid style={{ height: 560 }} ref={gridRef} options={options} />
</>
);
}import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
region: string;
amount: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Customer', width: 170 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'amount',
title: 'Amount ($1,000)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// A function that sorts and filters in place of a server and returns the first 14 rows. The response arrives late on purpose: a descending sort takes 1.2 s, the rest 0.5 s.
const REGIONS = ['New York', 'Boston', 'Chicago', 'Austin'];
// The region select passes ASCII ids, so map them to the region names used in the table.
const REGION_VALUES: Record<string, string> = {
seoul: 'New York',
gyeonggi: 'Boston',
busan: 'Chicago',
daegu: 'Austin',
};
const TABLE: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `Customer ${i + 1}`,
region: REGIONS[i % REGIONS.length] as string,
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort: SortItem[], filter: FilterModel | null): Promise<Row[]> {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) =>
setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId as keyof Row;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay),
);
}
let latest = 0;
// Ask the server again whenever the sort or filter changes. A slow old response must not overwrite a new one,
// so number each request and apply only the response with the latest number.
async function load(api: GridApi<Row>, log: (message: LogText) => void): Promise<void> {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log(
`#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`,
);
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed()) return;
if (request !== latest) return log(`#${request} response dropped because a newer request exists`);
api.setRows(rows);
api.setOptions({ loading: false });
log(`#${request} applied: ${rows.length} rows`);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // discard responses that arrive after cleanup
offs.forEach((off) => off());
};
}
export const actions = {
region: (api: GridApi<Row>, value?: string) =>
api.setFilterModel(
value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_VALUES[value] ?? value },
],
}
: null,
),
amountDesc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="Region"
:disabled="!api"
@change="api && actions.region(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>All (default)</option>
<option value="seoul">New York</option>
<option value="gyeonggi">Boston</option>
<option value="busan">Chicago</option>
<option value="daegu">Austin</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.amountDesc(api)"
>Amount high to low</button>
<button
type="button"
:disabled="!api"
@click="api && actions.amountAsc(api)"
>Amount low to high</button>
</div>
<Grid style="height: 560px" :options="options" @ready="onReady" />
</template>import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
region: string;
amount: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Customer', width: 170 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'amount',
title: 'Amount ($1,000)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// A function that sorts and filters in place of a server and returns the first 14 rows. The response arrives late on purpose: a descending sort takes 1.2 s, the rest 0.5 s.
const REGIONS = ['New York', 'Boston', 'Chicago', 'Austin'];
// The region select passes ASCII ids, so map them to the region names used in the table.
const REGION_VALUES: Record<string, string> = {
seoul: 'New York',
gyeonggi: 'Boston',
busan: 'Chicago',
daegu: 'Austin',
};
const TABLE: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `Customer ${i + 1}`,
region: REGIONS[i % REGIONS.length] as string,
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort: SortItem[], filter: FilterModel | null): Promise<Row[]> {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) =>
setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId as keyof Row;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay),
);
}
let latest = 0;
// Ask the server again whenever the sort or filter changes. A slow old response must not overwrite a new one,
// so number each request and apply only the response with the latest number.
async function load(api: GridApi<Row>, log: (message: LogText) => void): Promise<void> {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log(
`#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`,
);
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed()) return;
if (request !== latest) return log(`#${request} response dropped because a newer request exists`);
api.setRows(rows);
api.setOptions({ loading: false });
log(`#${request} applied: ${rows.length} rows`);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // discard responses that arrive after cleanup
offs.forEach((off) => off());
};
}
export const actions = {
region: (api: GridApi<Row>, value?: string) =>
api.setFilterModel(
value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_VALUES[value] ?? value },
],
}
: null,
),
amountDesc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="Region"
[disabled]="!api"
(change)="api && actions.region(api, $any($event.target).value)"
>
<option value="all" selected>All (default)</option>
<option value="seoul">New York</option>
<option value="gyeonggi">Boston</option>
<option value="busan">Chicago</option>
<option value="daegu">Austin</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.amountDesc(api)"
>Amount high to low</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.amountAsc(api)"
>Amount low to high</button>
</div>
<mx-grid style="height: 560px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
region: string;
amount: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Customer', width: 170 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'amount',
title: 'Amount ($1,000)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
loading: true,
};
// A function that sorts and filters in place of a server and returns the first 14 rows. The response arrives late on purpose: a descending sort takes 1.2 s, the rest 0.5 s.
const REGIONS = ['New York', 'Boston', 'Chicago', 'Austin'];
// The region select passes ASCII ids, so map them to the region names used in the table.
const REGION_VALUES: Record<string, string> = {
seoul: 'New York',
gyeonggi: 'Boston',
busan: 'Chicago',
daegu: 'Austin',
};
const TABLE: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
name: `Customer ${i + 1}`,
region: REGIONS[i % REGIONS.length] as string,
amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort: SortItem[], filter: FilterModel | null): Promise<Row[]> {
const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
return new Promise((resolve) =>
setTimeout(() => {
const region = filter?.items.find((item) => item.columnId === 'region')?.value;
let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
const first = sort[0];
if (first) {
const key = first.columnId as keyof Row;
const sign = first.direction === 'asc' ? 1 : -1;
rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
resolve(rows.slice(0, 14));
}, delay),
);
}
let latest = 0;
// Ask the server again whenever the sort or filter changes. A slow old response must not overwrite a new one,
// so number each request and apply only the response with the latest number.
async function load(api: GridApi<Row>, log: (message: LogText) => void): Promise<void> {
const request = ++latest;
const sort = api.getSortModel();
const region = api.getFilterModel()?.items[0]?.value;
log(
`#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`,
);
api.setOptions({ loading: true });
const rows = await fakeServer(sort, api.getFilterModel());
if (api.isDestroyed()) return;
if (request !== latest) return log(`#${request} response dropped because a newer request exists`);
api.setRows(rows);
api.setOptions({ loading: false });
log(`#${request} applied: ${rows.length} rows`);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
latest = 0;
void load(api, log);
const offs = [
api.on('sortChanged', () => void load(api, log)),
api.on('filterChanged', () => void load(api, log)),
];
return () => {
latest++; // discard responses that arrive after cleanup
offs.forEach((off) => off());
};
}
export const actions = {
region: (api: GridApi<Row>, value?: string) =>
api.setFilterModel(
value && value !== 'all'
? {
match: 'all',
items: [
{ columnId: 'region', operator: 'equals', value: REGION_VALUES[value] ?? value },
],
}
: null,
),
amountDesc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
amountAsc: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};