정렬·필터를 주소 글자로 남기고 되살리기Keep sort and filter in the address and restore them
정렬과 부서 조건이 바뀔 때마다 '?sort=salary.desc&dept=영업팀' 같은 주소 글자로 적고, 페이지를 열 때 그 글자를 읽어 같은 화면을 되살려요. 라우터를 따로 설치하지 않고 브라우저 기본 기능만 써요. 이 미리보기 안에서는 실제 주소창을 바꿀 수 없어서 표 위 줄이 주소창을 대신해요. React, Vue, Angular 탭에는 각 프레임워크의 방식으로 쓴 같은 예제가 들어 있어요.Each time the sort or department filter changes it is written as address text such as ?sort=salary.desc&dept=..., and on load that text is read back to restore the same screen. No router is installed; only built-in browser features are used. The preview cannot change the real address bar, so the line above the table stands in for it. The React, Vue and Angular tabs hold the same example written the way each framework does it.
실행 화면은 JavaScript 버전이에요. 아래 탭의 React·Vue·Angular 코드는 같은 예제를 각 프레임워크로 직접 쓴 코드예요.The preview runs the JavaScript version. The React, Vue, Angular tabs below hold the same example written for each framework.
코드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">
<button type="button" id="sortBySalary">월급 높은 순으로</button>
<select aria-label="부서" id="dept">
<option value="all" selected>전체 부서 (기본)</option>
<option value="dev">개발팀</option>
<option value="design">디자인팀</option>
<option value="sales">영업팀</option>
</select>
<button type="button" id="openLink">링크 열기 흉내</button>
<button type="button" id="clear">모두 지우기</button>
</div>
<div id="grid" style="height: 440px"></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('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
export const DEPTS = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
const NAMES = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
export const options = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3],
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** 정렬과 부서 조건을 '?sort=salary.desc&dept=개발팀' 같은 글자로 바꿔요. */
export function toQuery(sort, dept) {
const params = new URLSearchParams();
const first = sort[0];
if (first)
params.set('sort', `${first.columnId}.${first.direction}`);
if (dept)
params.set('dept', dept);
return params.toString();
}
/** 주소 글자를 읽어요. 이 화면이 만들 수 있는 값만 받아서, 이상한 글자는 무시해요. */
export function fromQuery(query) {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort = known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
export function toFilter(dept) {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// 이 화면(JavaScript 버전): 주소창은 바꿀 수 없어서, 표 위 줄이 주소창을 대신해요.
let bar = null;
let dept = '';
export function setup(api, log) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = () => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar)
bar.textContent = L(`주소창 대신 보여 주는 줄: ?${query}`, `Line shown instead of the address bar: ?${query}`);
// 위 부서 선택 목록도 표의 실제 조건에 맞춰요. (링크 열기, 모두 지우기 때문에 바뀔 수 있어요)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement)
select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last)
return; // 정렬과 필터가 연달아 바뀌어도 같은 말을 두 번 적지 않아요
last = query;
log({
ko: query ? `주소 글자: ?${query}` : '주소 글자를 비웠어요',
en: query ? `Address text: ?${query}` : 'Cleared the address text',
});
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar)
bar.textContent = L('주소창 대신 보여 주는 줄: ?', 'Line shown instead of the address bar: ?');
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
export const actions = {
sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api, value) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// 누군가 ?sort=salary.desc&dept=영업팀 링크를 열었다고 치고, 그 글자를 읽어 표에 되살려요.
openLink: (api) => {
const next = fromQuery('sort=salary.desc&dept=영업팀');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};<!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">
<button type="button" id="sortBySalary">월급 높은 순으로</button>
<select aria-label="부서" id="dept">
<option value="all" selected>전체 부서 (기본)</option>
<option value="dev">개발팀</option>
<option value="design">디자인팀</option>
<option value="sales">영업팀</option>
</select>
<button type="button" id="openLink">링크 열기 흉내</button>
<button type="button" id="clear">모두 지우기</button>
</div>
<div id="grid" style="height: 440px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const DEPTS = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
const NAMES = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
const options = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3],
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** 정렬과 부서 조건을 '?sort=salary.desc&dept=개발팀' 같은 글자로 바꿔요. */
function toQuery(sort, dept) {
const params = new URLSearchParams();
const first = sort[0];
if (first)
params.set('sort', `${first.columnId}.${first.direction}`);
if (dept)
params.set('dept', dept);
return params.toString();
}
/** 주소 글자를 읽어요. 이 화면이 만들 수 있는 값만 받아서, 이상한 글자는 무시해요. */
function fromQuery(query) {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort = known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
function toFilter(dept) {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// 이 화면(JavaScript 버전): 주소창은 바꿀 수 없어서, 표 위 줄이 주소창을 대신해요.
let bar = null;
let dept = '';
function setup(api, log) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = () => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar)
bar.textContent = L(`주소창 대신 보여 주는 줄: ?${query}`, `Line shown instead of the address bar: ?${query}`);
// 위 부서 선택 목록도 표의 실제 조건에 맞춰요. (링크 열기, 모두 지우기 때문에 바뀔 수 있어요)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement)
select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last)
return; // 정렬과 필터가 연달아 바뀌어도 같은 말을 두 번 적지 않아요
last = query;
log({
ko: query ? `주소 글자: ?${query}` : '주소 글자를 비웠어요',
en: query ? `Address text: ?${query}` : 'Cleared the address text',
});
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar)
bar.textContent = L('주소창 대신 보여 주는 줄: ?', 'Line shown instead of the address bar: ?');
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
const actions = {
sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api, value) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// 누군가 ?sort=salary.desc&dept=영업팀 링크를 열었다고 치고, 그 글자를 읽어 표에 되살려요.
openLink: (api) => {
const next = fromQuery('sort=salary.desc&dept=영업팀');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};
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('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Grid, useGridApi } from '@maxgrid/react';
import { useEffect } from 'react';
import { fromQuery, options, toFilter, toQuery, type Row } from './example';
// 주소 글자(쿼리)는 router 없이 브라우저 기본 기능(location, history)으로 읽고 써요.
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
// 그리드가 만들어지면 처음 한 번, 주소의 글자를 읽어 표에 되살려요.
useEffect(() => {
if (!api) return;
const { sort, dept } = fromQuery(location.search);
api.setSortModel(sort);
api.setFilterModel(toFilter(dept));
}, [api]);
// 정렬이나 필터가 바뀔 때마다 주소 글자를 다시 써요. (새 기록을 쌓지 않으려고 replaceState)
const writeAddress = () => {
if (!api) return;
const filter = api.getFilterModel()?.items[0];
const query = toQuery(api.getSortModel(), filter ? String(filter.value) : '');
history.replaceState(null, '', query ? `?${query}` : location.pathname);
};
return (
<div style={{ height: 320 }}>
<Grid<Row>
ref={gridRef}
options={options}
onSortChanged={writeAddress}
onFilterChanged={writeAddress}
/>
</div>
);
}import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const DEPTS = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID: Record<string, string> = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
const NAMES = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** 정렬과 부서 조건을 '?sort=salary.desc&dept=개발팀' 같은 글자로 바꿔요. */
export function toQuery(sort: SortItem[], dept: string): string {
const params = new URLSearchParams();
const first = sort[0];
if (first) params.set('sort', `${first.columnId}.${first.direction}`);
if (dept) params.set('dept', dept);
return params.toString();
}
/** 주소 글자를 읽어요. 이 화면이 만들 수 있는 값만 받아서, 이상한 글자는 무시해요. */
export function fromQuery(query: string): { sort: SortItem[]; dept: string } {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort: SortItem[] =
known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId as string, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
export function toFilter(dept: string): FilterModel | null {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// 이 화면(JavaScript 버전): 주소창은 바꿀 수 없어서, 표 위 줄이 주소창을 대신해요.
let bar: HTMLElement | null = null;
let dept = '';
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = (): void => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar)
bar.textContent = L(
`주소창 대신 보여 주는 줄: ?${query}`,
`Line shown instead of the address bar: ?${query}`,
);
// 위 부서 선택 목록도 표의 실제 조건에 맞춰요. (링크 열기, 모두 지우기 때문에 바뀔 수 있어요)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement) select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last) return; // 정렬과 필터가 연달아 바뀌어도 같은 말을 두 번 적지 않아요
last = query;
log({
ko: query ? `주소 글자: ?${query}` : '주소 글자를 비웠어요',
en: query ? `Address text: ?${query}` : 'Cleared the address text',
});
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar)
bar.textContent = L('주소창 대신 보여 주는 줄: ?', 'Line shown instead of the address bar: ?');
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
export const actions = {
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api: GridApi<Row>, value?: string) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// 누군가 ?sort=salary.desc&dept=영업팀 링크를 열었다고 치고, 그 글자를 읽어 표에 되살려요.
openLink: (api: GridApi<Row>) => {
const next = fromQuery('sort=salary.desc&dept=영업팀');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api: GridApi<Row>) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { Grid, type GridInstance } from '@maxgrid/vue';
import { onMounted, ref } from 'vue';
import { fromQuery, options, toFilter, toQuery, type Row } from './example';
// 주소 글자(쿼리)는 router 없이 브라우저 기본 기능(location, history)으로 읽고 써요.
const grid = ref<GridInstance<Row> | null>(null);
// 마운트되면 처음 한 번, 주소의 글자를 읽어 표에 되살려요.
onMounted(() => {
const api = grid.value?.getApi();
if (!api) return;
const { sort, dept } = fromQuery(location.search);
api.setSortModel(sort);
api.setFilterModel(toFilter(dept));
});
// 정렬이나 필터가 바뀔 때마다 주소 글자를 다시 써요. (새 기록을 쌓지 않으려고 replaceState)
function writeAddress() {
const api = grid.value?.getApi();
if (!api) return;
const filter = api.getFilterModel()?.items[0];
const query = toQuery(api.getSortModel(), filter ? String(filter.value) : '');
history.replaceState(null, '', query ? `?${query}` : location.pathname);
}
</script>
<template>
<Grid
ref="grid"
style="height: 320px"
:options="options"
@sort-changed="writeAddress"
@filter-changed="writeAddress"
/>
</template>import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const DEPTS = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID: Record<string, string> = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
const NAMES = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** 정렬과 부서 조건을 '?sort=salary.desc&dept=개발팀' 같은 글자로 바꿔요. */
export function toQuery(sort: SortItem[], dept: string): string {
const params = new URLSearchParams();
const first = sort[0];
if (first) params.set('sort', `${first.columnId}.${first.direction}`);
if (dept) params.set('dept', dept);
return params.toString();
}
/** 주소 글자를 읽어요. 이 화면이 만들 수 있는 값만 받아서, 이상한 글자는 무시해요. */
export function fromQuery(query: string): { sort: SortItem[]; dept: string } {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort: SortItem[] =
known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId as string, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
export function toFilter(dept: string): FilterModel | null {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// 이 화면(JavaScript 버전): 주소창은 바꿀 수 없어서, 표 위 줄이 주소창을 대신해요.
let bar: HTMLElement | null = null;
let dept = '';
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = (): void => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar)
bar.textContent = L(
`주소창 대신 보여 주는 줄: ?${query}`,
`Line shown instead of the address bar: ?${query}`,
);
// 위 부서 선택 목록도 표의 실제 조건에 맞춰요. (링크 열기, 모두 지우기 때문에 바뀔 수 있어요)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement) select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last) return; // 정렬과 필터가 연달아 바뀌어도 같은 말을 두 번 적지 않아요
last = query;
log({
ko: query ? `주소 글자: ?${query}` : '주소 글자를 비웠어요',
en: query ? `Address text: ?${query}` : 'Cleared the address text',
});
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar)
bar.textContent = L('주소창 대신 보여 주는 줄: ?', 'Line shown instead of the address bar: ?');
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
export const actions = {
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api: GridApi<Row>, value?: string) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// 누군가 ?sort=salary.desc&dept=영업팀 링크를 열었다고 치고, 그 글자를 읽어 표에 되살려요.
openLink: (api: GridApi<Row>) => {
const next = fromQuery('sort=salary.desc&dept=영업팀');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api: GridApi<Row>) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, ViewChild, type AfterViewInit } from '@angular/core';
import {
GridComponent,
isGridEvent,
type GridEventMessage,
type GridEventName,
} from '@maxgrid/angular';
import { fromQuery, options, toFilter, toQuery, type Row } from './example';
// 주소 글자(쿼리)는 router 없이 브라우저 기본 기능(location, history)으로 읽고 써요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `<mx-grid
style="height: 320px"
[options]="options"
[events]="events"
(gridEvent)="onEvent($event)"
/>`,
})
export class ExampleGridComponent implements AfterViewInit {
readonly options = options;
readonly events: GridEventName[] = ['sortChanged', 'filterChanged'];
@ViewChild(GridComponent) private readonly gridRef?: GridComponent<Row>;
// 화면이 만들어지면 처음 한 번, 주소의 글자를 읽어 표에 되살려요.
ngAfterViewInit(): void {
const api = this.gridRef?.getApi();
if (!api) return;
const { sort, dept } = fromQuery(location.search);
api.setSortModel(sort);
api.setFilterModel(toFilter(dept));
}
// 정렬이나 필터가 바뀔 때마다 주소 글자를 다시 써요. (새 기록을 쌓지 않으려고 replaceState)
onEvent(message: GridEventMessage<Row>): void {
const api = this.gridRef?.getApi();
if (!api || !(isGridEvent(message, 'sortChanged') || isGridEvent(message, 'filterChanged')))
return;
const filter = api.getFilterModel()?.items[0];
const query = toQuery(api.getSortModel(), filter ? String(filter.value) : '');
history.replaceState(null, '', query ? `?${query}` : location.pathname);
}
}import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const DEPTS = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID: Record<string, string> = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
const NAMES = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** 정렬과 부서 조건을 '?sort=salary.desc&dept=개발팀' 같은 글자로 바꿔요. */
export function toQuery(sort: SortItem[], dept: string): string {
const params = new URLSearchParams();
const first = sort[0];
if (first) params.set('sort', `${first.columnId}.${first.direction}`);
if (dept) params.set('dept', dept);
return params.toString();
}
/** 주소 글자를 읽어요. 이 화면이 만들 수 있는 값만 받아서, 이상한 글자는 무시해요. */
export function fromQuery(query: string): { sort: SortItem[]; dept: string } {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort: SortItem[] =
known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId as string, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
export function toFilter(dept: string): FilterModel | null {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// 이 화면(JavaScript 버전): 주소창은 바꿀 수 없어서, 표 위 줄이 주소창을 대신해요.
let bar: HTMLElement | null = null;
let dept = '';
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = (): void => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar)
bar.textContent = L(
`주소창 대신 보여 주는 줄: ?${query}`,
`Line shown instead of the address bar: ?${query}`,
);
// 위 부서 선택 목록도 표의 실제 조건에 맞춰요. (링크 열기, 모두 지우기 때문에 바뀔 수 있어요)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement) select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last) return; // 정렬과 필터가 연달아 바뀌어도 같은 말을 두 번 적지 않아요
last = query;
log({
ko: query ? `주소 글자: ?${query}` : '주소 글자를 비웠어요',
en: query ? `Address text: ?${query}` : 'Cleared the address text',
});
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar)
bar.textContent = L('주소창 대신 보여 주는 줄: ?', 'Line shown instead of the address bar: ?');
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
export const actions = {
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api: GridApi<Row>, value?: string) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// 누군가 ?sort=salary.desc&dept=영업팀 링크를 열었다고 치고, 그 글자를 읽어 표에 되살려요.
openLink: (api: GridApi<Row>) => {
const next = fromQuery('sort=salary.desc&dept=영업팀');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api: GridApi<Row>) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="sortBySalary">Sort by salary, high first</button>
<select aria-label="Department" id="dept">
<option value="all" selected>All (default)</option>
<option value="dev">Development</option>
<option value="design">Design</option>
<option value="sales">Sales</option>
</select>
<button type="button" id="openLink">Simulate opening a link</button>
<button type="button" id="clear">Clear all</button>
</div>
<div id="grid" style="height: 440px"></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('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));export const DEPTS = ['Dev', 'Design', 'Sales'];
const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3],
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** Turns the sort and department conditions into text such as '?sort=salary.desc&dept=Dev'. */
export function toQuery(sort, dept) {
const params = new URLSearchParams();
const first = sort[0];
if (first)
params.set('sort', `${first.columnId}.${first.direction}`);
if (dept)
params.set('dept', dept);
return params.toString();
}
/** Reads the address text. It accepts only values this screen can create and ignores odd text. */
export function fromQuery(query) {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort = known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
export function toFilter(dept) {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// This screen (JavaScript version): the address bar cannot be changed, so the line above the table stands in for it.
let bar = null;
let dept = '';
export function setup(api, log) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = () => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar)
bar.textContent = `Line shown instead of the address bar: ?${query}`;
// Also keep the department select above in step with the table's actual condition. (It can change through the link and clear actions)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement)
select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last)
return; // even if sort and filter change in a row, do not write the same line twice
last = query;
log(query ? `Address text: ?${query}` : 'Cleared the address text');
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar)
bar.textContent = 'Line shown instead of the address bar: ?';
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
export const actions = {
sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api, value) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// Pretend someone opened a ?sort=salary.desc&dept=Sales link, then read that text and restore it in the table.
openLink: (api) => {
const next = fromQuery('sort=salary.desc&dept=Sales');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Keep sort and filter in the address and restore them</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="sortBySalary">Sort by salary, high first</button>
<select aria-label="Department" id="dept">
<option value="all" selected>All (default)</option>
<option value="dev">Development</option>
<option value="design">Design</option>
<option value="sales">Sales</option>
</select>
<button type="button" id="openLink">Simulate opening a link</button>
<button type="button" id="clear">Clear all</button>
</div>
<div id="grid" style="height: 440px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const DEPTS = ['Dev', 'Design', 'Sales'];
const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
const options = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3],
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** Turns the sort and department conditions into text such as '?sort=salary.desc&dept=Dev'. */
function toQuery(sort, dept) {
const params = new URLSearchParams();
const first = sort[0];
if (first)
params.set('sort', `${first.columnId}.${first.direction}`);
if (dept)
params.set('dept', dept);
return params.toString();
}
/** Reads the address text. It accepts only values this screen can create and ignores odd text. */
function fromQuery(query) {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort = known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
function toFilter(dept) {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// This screen (JavaScript version): the address bar cannot be changed, so the line above the table stands in for it.
let bar = null;
let dept = '';
function setup(api, log) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = () => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar)
bar.textContent = `Line shown instead of the address bar: ?${query}`;
// Also keep the department select above in step with the table's actual condition. (It can change through the link and clear actions)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement)
select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last)
return; // even if sort and filter change in a row, do not write the same line twice
last = query;
log(query ? `Address text: ?${query}` : 'Cleared the address text');
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar)
bar.textContent = 'Line shown instead of the address bar: ?';
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
const actions = {
sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api, value) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// Pretend someone opened a ?sort=salary.desc&dept=Sales link, then read that text and restore it in the table.
openLink: (api) => {
const next = fromQuery('sort=salary.desc&dept=Sales');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};
options.ariaLabel = "Keep sort and filter in the address and restore them";
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('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Grid, useGridApi } from '@maxgrid/react';
import { useEffect } from 'react';
import { fromQuery, options, toFilter, toQuery, type Row } from './example';
// 주소 글자(쿼리)는 router 없이 브라우저 기본 기능(location, history)으로 읽고 써요.
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
// 그리드가 만들어지면 처음 한 번, 주소의 글자를 읽어 표에 되살려요.
useEffect(() => {
if (!api) return;
const { sort, dept } = fromQuery(location.search);
api.setSortModel(sort);
api.setFilterModel(toFilter(dept));
}, [api]);
// 정렬이나 필터가 바뀔 때마다 주소 글자를 다시 써요. (새 기록을 쌓지 않으려고 replaceState)
const writeAddress = () => {
if (!api) return;
const filter = api.getFilterModel()?.items[0];
const query = toQuery(api.getSortModel(), filter ? String(filter.value) : '');
history.replaceState(null, '', query ? `?${query}` : location.pathname);
};
return (
<div style={{ height: 320 }}>
<Grid<Row>
ref={gridRef}
options={options}
onSortChanged={writeAddress}
onFilterChanged={writeAddress}
/>
</div>
);
}import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const DEPTS = ['Dev', 'Design', 'Sales'];
const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID: Record<string, string> = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** Turns the sort and department conditions into text such as '?sort=salary.desc&dept=Dev'. */
export function toQuery(sort: SortItem[], dept: string): string {
const params = new URLSearchParams();
const first = sort[0];
if (first) params.set('sort', `${first.columnId}.${first.direction}`);
if (dept) params.set('dept', dept);
return params.toString();
}
/** Reads the address text. It accepts only values this screen can create and ignores odd text. */
export function fromQuery(query: string): { sort: SortItem[]; dept: string } {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort: SortItem[] =
known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId as string, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
export function toFilter(dept: string): FilterModel | null {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// This screen (JavaScript version): the address bar cannot be changed, so the line above the table stands in for it.
let bar: HTMLElement | null = null;
let dept = '';
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = (): void => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar) bar.textContent = `Line shown instead of the address bar: ?${query}`;
// Also keep the department select above in step with the table's actual condition. (It can change through the link and clear actions)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement) select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last) return; // even if sort and filter change in a row, do not write the same line twice
last = query;
log(query ? `Address text: ?${query}` : 'Cleared the address text');
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar) bar.textContent = 'Line shown instead of the address bar: ?';
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
export const actions = {
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api: GridApi<Row>, value?: string) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// Pretend someone opened a ?sort=salary.desc&dept=Sales link, then read that text and restore it in the table.
openLink: (api: GridApi<Row>) => {
const next = fromQuery('sort=salary.desc&dept=Sales');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api: GridApi<Row>) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { Grid, type GridInstance } from '@maxgrid/vue';
import { onMounted, ref } from 'vue';
import { fromQuery, options, toFilter, toQuery, type Row } from './example';
// 주소 글자(쿼리)는 router 없이 브라우저 기본 기능(location, history)으로 읽고 써요.
const grid = ref<GridInstance<Row> | null>(null);
// 마운트되면 처음 한 번, 주소의 글자를 읽어 표에 되살려요.
onMounted(() => {
const api = grid.value?.getApi();
if (!api) return;
const { sort, dept } = fromQuery(location.search);
api.setSortModel(sort);
api.setFilterModel(toFilter(dept));
});
// 정렬이나 필터가 바뀔 때마다 주소 글자를 다시 써요. (새 기록을 쌓지 않으려고 replaceState)
function writeAddress() {
const api = grid.value?.getApi();
if (!api) return;
const filter = api.getFilterModel()?.items[0];
const query = toQuery(api.getSortModel(), filter ? String(filter.value) : '');
history.replaceState(null, '', query ? `?${query}` : location.pathname);
}
</script>
<template>
<Grid
ref="grid"
style="height: 320px"
:options="options"
@sort-changed="writeAddress"
@filter-changed="writeAddress"
/>
</template>import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const DEPTS = ['Dev', 'Design', 'Sales'];
const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID: Record<string, string> = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** Turns the sort and department conditions into text such as '?sort=salary.desc&dept=Dev'. */
export function toQuery(sort: SortItem[], dept: string): string {
const params = new URLSearchParams();
const first = sort[0];
if (first) params.set('sort', `${first.columnId}.${first.direction}`);
if (dept) params.set('dept', dept);
return params.toString();
}
/** Reads the address text. It accepts only values this screen can create and ignores odd text. */
export function fromQuery(query: string): { sort: SortItem[]; dept: string } {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort: SortItem[] =
known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId as string, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
export function toFilter(dept: string): FilterModel | null {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// This screen (JavaScript version): the address bar cannot be changed, so the line above the table stands in for it.
let bar: HTMLElement | null = null;
let dept = '';
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = (): void => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar) bar.textContent = `Line shown instead of the address bar: ?${query}`;
// Also keep the department select above in step with the table's actual condition. (It can change through the link and clear actions)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement) select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last) return; // even if sort and filter change in a row, do not write the same line twice
last = query;
log(query ? `Address text: ?${query}` : 'Cleared the address text');
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar) bar.textContent = 'Line shown instead of the address bar: ?';
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
export const actions = {
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api: GridApi<Row>, value?: string) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// Pretend someone opened a ?sort=salary.desc&dept=Sales link, then read that text and restore it in the table.
openLink: (api: GridApi<Row>) => {
const next = fromQuery('sort=salary.desc&dept=Sales');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api: GridApi<Row>) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, ViewChild, type AfterViewInit } from '@angular/core';
import {
GridComponent,
isGridEvent,
type GridEventMessage,
type GridEventName,
} from '@maxgrid/angular';
import { fromQuery, options, toFilter, toQuery, type Row } from './example';
// 주소 글자(쿼리)는 router 없이 브라우저 기본 기능(location, history)으로 읽고 써요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `<mx-grid
style="height: 320px"
[options]="options"
[events]="events"
(gridEvent)="onEvent($event)"
/>`,
})
export class ExampleGridComponent implements AfterViewInit {
readonly options = options;
readonly events: GridEventName[] = ['sortChanged', 'filterChanged'];
@ViewChild(GridComponent) private readonly gridRef?: GridComponent<Row>;
// 화면이 만들어지면 처음 한 번, 주소의 글자를 읽어 표에 되살려요.
ngAfterViewInit(): void {
const api = this.gridRef?.getApi();
if (!api) return;
const { sort, dept } = fromQuery(location.search);
api.setSortModel(sort);
api.setFilterModel(toFilter(dept));
}
// 정렬이나 필터가 바뀔 때마다 주소 글자를 다시 써요. (새 기록을 쌓지 않으려고 replaceState)
onEvent(message: GridEventMessage<Row>): void {
const api = this.gridRef?.getApi();
if (!api || !(isGridEvent(message, 'sortChanged') || isGridEvent(message, 'filterChanged')))
return;
const filter = api.getFilterModel()?.items[0];
const query = toQuery(api.getSortModel(), filter ? String(filter.value) : '');
history.replaceState(null, '', query ? `?${query}` : location.pathname);
}
}import type { FilterModel, GridApi, GridOptions, SortItem } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const DEPTS = ['Dev', 'Design', 'Sales'];
const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID: Record<string, string> = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
/** Turns the sort and department conditions into text such as '?sort=salary.desc&dept=Dev'. */
export function toQuery(sort: SortItem[], dept: string): string {
const params = new URLSearchParams();
const first = sort[0];
if (first) params.set('sort', `${first.columnId}.${first.direction}`);
if (dept) params.set('dept', dept);
return params.toString();
}
/** Reads the address text. It accepts only values this screen can create and ignores odd text. */
export function fromQuery(query: string): { sort: SortItem[]; dept: string } {
const params = new URLSearchParams(query);
const [columnId, direction] = (params.get('sort') ?? '').split('.');
const known = ['name', 'dept', 'salary'].includes(columnId ?? '');
const sort: SortItem[] =
known && (direction === 'asc' || direction === 'desc')
? [{ columnId: columnId as string, direction }]
: [];
const dept = params.get('dept') ?? '';
return { sort, dept: DEPTS.includes(dept) ? dept : '' };
}
export function toFilter(dept: string): FilterModel | null {
return dept
? { match: 'all', items: [{ columnId: 'dept', operator: 'equals', value: dept }] }
: null;
}
// This screen (JavaScript version): the address bar cannot be changed, so the line above the table stands in for it.
let bar: HTMLElement | null = null;
let dept = '';
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
dept = '';
let last = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
const show = (): void => {
const query = decodeURIComponent(toQuery(api.getSortModel(), dept));
if (bar) bar.textContent = `Line shown instead of the address bar: ?${query}`;
// Also keep the department select above in step with the table's actual condition. (It can change through the link and clear actions)
const select = document.getElementById('dept');
if (select instanceof HTMLSelectElement) select.value = ID_BY_DEPT[dept] ?? 'all';
if (query === last) return; // even if sort and filter change in a row, do not write the same line twice
last = query;
log(query ? `Address text: ?${query}` : 'Cleared the address text');
};
const offs = [api.on('sortChanged', show), api.on('filterChanged', show)];
if (bar) bar.textContent = 'Line shown instead of the address bar: ?';
return () => {
offs.forEach((off) => off());
bar?.remove();
bar = null;
};
}
export const actions = {
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
dept: (api: GridApi<Row>, value?: string) => {
dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(toFilter(dept));
},
// Pretend someone opened a ?sort=salary.desc&dept=Sales link, then read that text and restore it in the table.
openLink: (api: GridApi<Row>) => {
const next = fromQuery('sort=salary.desc&dept=Sales');
dept = next.dept;
api.setSortModel(next.sort);
api.setFilterModel(toFilter(dept));
},
clear: (api: GridApi<Row>) => {
dept = '';
api.setSortModel([]);
api.setFilterModel(null);
},
};