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

필터를 주소 글자로 바꾸고 되살리기 (주소창 흉내)Turn a filter into address text and back (address bar simulated)

필터를 걸 때마다 조건을 '?dept=개발팀&min=500' 같은 주소 글자로 바꿔 보여 줘요. 그 글자를 읽어 같은 필터를 다시 걸 수도 있어요. 이 미리보기 안에서는 실제 주소창을 바꿀 수 없어서 아래 줄이 주소창을 대신해요.Each filter change is turned into address text such as ?dept=...&min=500, and the same filter can be rebuilt from that text. The preview cannot change the real address bar, so the line below stands in for it.

심화Advanced
직접 써 보기Live preview필터를 주소 글자로 바꾸고 되살리기 (주소창 흉내)Turn a filter into address text and back (address bar simulated)

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="부서" id="dept">
      <option value="all" selected>전체 부서 (기본)</option>
      <option value="dev">개발팀</option>
      <option value="design">디자인팀</option>
      <option value="sales">영업팀</option>
    </select>
    <select aria-label="최소 월급" id="minSalary">
      <option value="0" selected>제한 없음 (기본)</option>
      <option value="400">400만원 이상</option>
      <option value="500">500만원 이상</option>
    </select>
    <button type="button" id="clear">모두 지우기</button>
    <button type="button" id="openLink">링크 열기 흉내</button>
  </div>
  <div id="grid" style="height: 440px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('minSalary').addEventListener('change', (event) => actions.minSalary(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const names = [
  '김민준',
  '이서연',
  '박지호',
  '최유나',
  '정도윤',
  '한소희',
  '오세훈',
  '김서윤',
  '장하은',
  '윤재민',
];
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]));
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 130 },
    { id: 'dept', title: '부서', width: 120 },
    {
      id: 'salary',
      title: '월급(만원)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: names.map((name, i) => ({
    id: i + 1,
    name,
    dept: depts[i % 3],
    salary: 320 + ((i * 83) % 400),
  })),
  rowKey: 'id',
};
// 이 화면이 만들 수 있는 조건만 쿼리 글자로 적고, 읽을 때도 그 조건만 받아요.
// 그래서 주소에 이상한 글자가 들어와도 그리드에는 예상한 조건만 전달돼요.
function toQuery(model) {
  const params = new URLSearchParams();
  for (const item of model?.items ?? []) {
    if (item.columnId === 'dept')
      params.set('dept', String(item.value));
    if (item.columnId === 'salary')
      params.set('min', String(item.value));
  }
  return params.toString();
}
function fromQuery(query) {
  const params = new URLSearchParams(query);
  const items = [];
  const dept = params.get('dept');
  const min = Number(params.get('min'));
  if (dept && depts.includes(dept))
    items.push({ columnId: 'dept', operator: 'equals', value: dept });
  if (params.get('min') && Number.isFinite(min)) {
    items.push({ columnId: 'salary', operator: 'gte', value: min });
  }
  return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // 실제 앱에서는 history.replaceState(null, '', `?${query}`)로 쓰고, 열 때 location.search를 읽어요
let bar = null;
const put = (id, value) => {
  const el = document.getElementById(id);
  if (el instanceof HTMLSelectElement)
    el.value = value;
};
const show = () => {
  if (bar)
    bar.textContent = L(`주소창 대신 보여 주는 줄: ?${decodeURIComponent(saved)}`, `Line shown instead of the address bar: ?${decodeURIComponent(saved)}`);
};
export function setup(api, log) {
  state.dept = '';
  state.min = '';
  saved = '';
  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);
  show();
  const off = api.on('filterChanged', ({ filterModel }) => {
    saved = toQuery(filterModel);
    show();
    // 어떤 경로로 조건이 바뀌어도(링크 열기 포함) 위 선택 목록이 표와 어긋나지 않게 맞춰요.
    const item = (id) => filterModel?.items.find((it) => it.columnId === id);
    put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
    put('minSalary', String(item('salary')?.value ?? '0'));
    log({
      ko: `주소창 대신 보여 주는 줄에 적었어요: ?${decodeURIComponent(saved)}`,
      en: `Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`,
    });
  });
  return () => {
    off();
    bar?.remove();
    bar = null;
  };
}
export const actions = {
  dept: (api, value) => {
    state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
    api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
  },
  minSalary: (api, value) => {
    state.min = value && value !== '0' ? value : '';
    api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
  },
  clear: (api) => {
    state.dept = '';
    state.min = '';
    api.setFilterModel(null);
  },
  // 누군가 ?dept=영업팀&min=400 링크를 열었다고 치고, 그 쿼리를 읽어 필터를 되살려요(새로고침할 때와 같은 일이에요).
  openLink: (api) => {
    const query = 'dept=영업팀&min=400';
    state.dept = '영업팀';
    state.min = '400';
    api.setFilterModel(fromQuery(query));
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="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>
    <select aria-label="Min salary" id="minSalary">
      <option value="0" selected>No limit (default)</option>
      <option value="400">400+</option>
      <option value="500">500+</option>
    </select>
    <button type="button" id="clear">Clear all</button>
    <button type="button" id="openLink">Simulate opening a link</button>
  </div>
  <div id="grid" style="height: 440px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('minSalary').addEventListener('change', (event) => actions.minSalary(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(api));
example.js
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Reed',
  'Olivia Hayes',
  'Ethan Brooks',
  'Sophia Bell',
  'Mason Gray',
  'Ava Morgan',
  'Lucas Hart',
  'Mia Foster',
];
const depts = ['Dev', 'Design', 'Sales'];
// 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: 150,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    },
  ],
  rows: names.map((name, i) => ({
    id: i + 1,
    name,
    dept: depts[i % 3],
    salary: 320 + ((i * 83) % 400),
  })),
  rowKey: 'id',
};
// Only conditions this screen can create are written to the query string, and only those are accepted when reading.
// So even if odd text appears in the address, the grid receives only the expected conditions.
function toQuery(model) {
  const params = new URLSearchParams();
  for (const item of model?.items ?? []) {
    if (item.columnId === 'dept')
      params.set('dept', String(item.value));
    if (item.columnId === 'salary')
      params.set('min', String(item.value));
  }
  return params.toString();
}
function fromQuery(query) {
  const params = new URLSearchParams(query);
  const items = [];
  const dept = params.get('dept');
  const min = Number(params.get('min'));
  if (dept && depts.includes(dept))
    items.push({ columnId: 'dept', operator: 'equals', value: dept });
  if (params.get('min') && Number.isFinite(min)) {
    items.push({ columnId: 'salary', operator: 'gte', value: min });
  }
  return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // a real app would use history.replaceState(null, '', `?${query}`) to write and read location.search on open
let bar = null;
const put = (id, value) => {
  const el = document.getElementById(id);
  if (el instanceof HTMLSelectElement)
    el.value = value;
};
const show = () => {
  if (bar)
    bar.textContent = `Line shown instead of the address bar: ?${decodeURIComponent(saved)}`;
};
export function setup(api, log) {
  state.dept = '';
  state.min = '';
  saved = '';
  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);
  show();
  const off = api.on('filterChanged', ({ filterModel }) => {
    saved = toQuery(filterModel);
    show();
    // However the condition changes (including opening a link), keep the select lists above in step with the table.
    const item = (id) => filterModel?.items.find((it) => it.columnId === id);
    put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
    put('minSalary', String(item('salary')?.value ?? '0'));
    log(`Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`);
  });
  return () => {
    off();
    bar?.remove();
    bar = null;
  };
}
export const actions = {
  dept: (api, value) => {
    state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
    api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
  },
  minSalary: (api, value) => {
    state.min = value && value !== '0' ? value : '';
    api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
  },
  clear: (api) => {
    state.dept = '';
    state.min = '';
    api.setFilterModel(null);
  },
  // Pretend someone opened a ?dept=Sales&min=400 link, then read that query to restore the filter (same as on reload).
  openLink: (api) => {
    const query = 'dept=Sales&min=400';
    state.dept = 'Sales';
    state.min = '400';
    api.setFilterModel(fromQuery(query));
  },
};