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

칸 모양이 달라도 정렬·검색은 원래 값으로Different cell looks, but sort and filter use the real value

아바타, 배지, 진행 막대, 별점, 태그를 한 표에 모두 쓰고, 그래도 정렬과 검색이 그려진 모양이 아니라 원래 값으로 되는 것을 확인해요.Use avatar, badge, progress, rating and tags in one grid and see that sort and filter still work on the real values, not the drawn look.

활용Intermediate
직접 써 보기Live preview칸 모양이 달라도 정렬·검색은 원래 값으로Different cell looks, but sort and filter use the real value

코드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="sort">
      <option value="none" selected>정렬 없음</option>
      <option value="progress">진행률 높은 순</option>
      <option value="priority">중요도 높은 순</option>
    </select>
    <select aria-label="상태 보기" id="status">
      <option value="all" selected>전체</option>
      <option value="active">진행</option>
      <option value="done">완료</option>
      <option value="blocked">막힘</option>
    </select>
  </div>
  <div id="grid" style="height: 320px"></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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));
example.js
// 내장 진행 막대에는 화면 읽기 프로그램용 이름이 없어서, 줄의 첫 칸 글자를 붙여 이름을 달아 줘요.
function nameBars(label, cell = 0) {
  const root = document.getElementById('grid');
  if (!root)
    return () => undefined;
  const apply = () => {
    for (const bar of root.querySelectorAll('[role="progressbar"]')) {
      if (bar.getAttribute('aria-label'))
        continue;
      const row = bar.closest('[role="row"]');
      const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
      const mine = bar.closest('[role="gridcell"]');
      const headers = root.querySelectorAll('[role="columnheader"]');
      const header = headers[cells.indexOf(mine)]?.textContent?.trim();
      bar.setAttribute('aria-label', `${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim());
    }
  };
  const observer = new MutationObserver(apply);
  observer.observe(root, { childList: true, subtree: true });
  apply();
  return () => observer.disconnect();
}
// 내장 칸 모양을 한 표에 모두 썼어요. 칸의 모양이 달라도 값은 그냥 글자·숫자·배열이라서,
// 정렬과 검색(필터)은 그려진 모양이 아니라 원래 값으로 해요. 예: 진행률은 "72%" 글자가 아니라 숫자 72로 정렬돼요.
export const options = {
  columns: [
    { id: 'owner', title: '담당', width: 140, cellRenderer: 'avatar' },
    { id: 'project', title: '프로젝트', width: 120 },
    {
      id: 'status',
      title: '상태',
      width: 100,
      cellRenderer: 'badge',
      cellRendererParams: {
        map: {
          active: { label: '진행', tone: 'info' },
          done: { label: '완료', tone: 'success' },
          blocked: { label: '막힘', tone: 'danger' },
        },
      },
    },
    {
      id: 'progress',
      title: '진행률',
      width: 160,
      kind: 'number',
      formatValue: (value) => `${String(value)}%`,
      cellRenderer: 'progress',
      cellRendererParams: {
        ranges: [
          { upTo: 40, tone: 'danger' },
          { upTo: 80, tone: 'warning' },
          { upTo: 100, tone: 'success' },
        ],
      },
    },
    {
      id: 'priority',
      title: '중요도',
      width: 100,
      kind: 'number',
      cellRenderer: 'rating',
      cellRendererParams: { max: 3 },
    },
    {
      id: 'labels',
      title: '라벨',
      width: 170,
      cellRenderer: 'tags',
      cellRendererParams: { max: 2 },
      sortable: false,
      filterable: false,
    },
  ],
  rows: [
    {
      id: 1,
      owner: '김서연',
      project: '결제',
      status: 'active',
      progress: 72,
      priority: 3,
      labels: ['결제', '4분기', '감사'],
    },
    {
      id: 2,
      owner: '이준호',
      project: '검색',
      status: 'done',
      progress: 100,
      priority: 2,
      labels: ['검색'],
    },
    {
      id: 3,
      owner: '박민지',
      project: '모바일 앱',
      status: 'blocked',
      progress: 25,
      priority: 3,
      labels: ['모바일', '출시'],
    },
    {
      id: 4,
      owner: '최도윤',
      project: '문서 사이트',
      status: 'active',
      progress: 9,
      priority: 1,
      labels: ['문서'],
    },
    {
      id: 5,
      owner: '정하은',
      project: '데이터 내보내기',
      status: 'active',
      progress: 90,
      priority: 2,
      labels: [],
    },
  ],
  rowKey: 'id',
  filterRow: true,
  saveMode: 'none',
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log({
    ko: '머리글을 눌러 정렬하거나, 머리글 아래 입력 칸으로 거를 수 있어요.',
    en: 'Click a header to sort, or filter with the inputs under the headers.',
  });
  const stop = nameBars('진행률', 1);
  // 머리글을 눌러 정렬하거나 입력 칸으로 걸러도 위의 선택 상자가 지금 상태를 따라가게 맞춰요.
  const sortBox = document.getElementById('sort');
  const statusBox = document.getElementById('status');
  const offs = [
    api.on('sortChanged', ({ sortModel }) => {
      const only = sortModel.length === 1 ? sortModel[0] : undefined;
      const value = only &&
        only.direction === 'desc' &&
        (only.columnId === 'progress' || only.columnId === 'priority')
        ? only.columnId
        : 'none';
      if (sortBox instanceof HTMLSelectElement)
        sortBox.value = value;
    }),
    api.on('filterChanged', ({ filterModel }) => {
      const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
      const value = only && only.columnId === 'status' && only.operator === 'equals'
        ? String(only.value)
        : 'all';
      if (statusBox instanceof HTMLSelectElement)
        statusBox.value = value;
    }),
  ];
  return () => {
    stop();
    offs.forEach((off) => off());
  };
}
export const actions = {
  sort: (api, value) => {
    const by = value === 'progress' || value === 'priority' ? value : '';
    api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
    say({
      ko: by
        ? `${by === 'progress' ? '진행률' : '중요도'} 높은 순으로 정렬했어요. (숫자 기준)`
        : '정렬을 풀었어요.',
      en: by
        ? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
        : 'Sort cleared.',
    });
  },
  status: (api, value) => {
    api.setFilterModel(value && value !== 'all'
      ? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
      : null);
    say({
      ko: value && value !== 'all'
        ? `상태가 "${value}"인 줄만 남겼어요. (배지 뒤의 원래 값으로 걸러요)`
        : '필터를 풀었어요.',
      en: value && value !== 'all'
        ? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
        : 'Filter cleared.',
    });
  },
};

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="Sort" id="sort">
      <option value="none" selected>No sort</option>
      <option value="progress">Progress high first</option>
      <option value="priority">Priority high first</option>
    </select>
    <select aria-label="Show status" id="status">
      <option value="all" selected>All</option>
      <option value="active">Active</option>
      <option value="done">Done</option>
      <option value="blocked">Blocked</option>
    </select>
  </div>
  <div id="grid" style="height: 320px"></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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));
example.js
// The built-in progress bar has no name for screen readers, so this adds one using the text of the row's first cell.
function nameBars(label, cell = 0) {
  const root = document.getElementById('grid');
  if (!root)
    return () => undefined;
  const apply = () => {
    for (const bar of root.querySelectorAll('[role="progressbar"]')) {
      if (bar.getAttribute('aria-label'))
        continue;
      const row = bar.closest('[role="row"]');
      const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
      const mine = bar.closest('[role="gridcell"]');
      const headers = root.querySelectorAll('[role="columnheader"]');
      const header = headers[cells.indexOf(mine)]?.textContent?.trim();
      bar.setAttribute('aria-label', `${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim());
    }
  };
  const observer = new MutationObserver(apply);
  observer.observe(root, { childList: true, subtree: true });
  apply();
  return () => observer.disconnect();
}
// All the built-in cell looks are used in one table. Whatever the cell looks like, the value is still plain text, a number or an array,
// so sorting and search (filter) use the original value, not the drawn look. Example: progress sorts as the number 72, not the text "72%".
export const options = {
  columns: [
    { id: 'owner', title: 'Owner', width: 140, cellRenderer: 'avatar' },
    { id: 'project', title: 'Project', width: 140 },
    {
      id: 'status',
      title: 'Status',
      width: 100,
      cellRenderer: 'badge',
      cellRendererParams: {
        map: {
          active: { label: 'Active', tone: 'info' },
          done: { label: 'Done', tone: 'success' },
          blocked: { label: 'Blocked', tone: 'danger' },
        },
      },
    },
    {
      id: 'progress',
      title: 'Progress',
      width: 160,
      kind: 'number',
      formatValue: (value) => `${String(value)}%`,
      cellRenderer: 'progress',
      cellRendererParams: {
        ranges: [
          { upTo: 40, tone: 'danger' },
          { upTo: 80, tone: 'warning' },
          { upTo: 100, tone: 'success' },
        ],
      },
    },
    {
      id: 'priority',
      title: 'Priority',
      width: 100,
      kind: 'number',
      cellRenderer: 'rating',
      cellRendererParams: { max: 3 },
    },
    {
      id: 'labels',
      title: 'Labels',
      width: 170,
      cellRenderer: 'tags',
      cellRendererParams: { max: 2 },
      sortable: false,
      filterable: false,
    },
  ],
  rows: [
    {
      id: 1,
      owner: 'Olivia Reed',
      project: 'Payments',
      status: 'active',
      progress: 72,
      priority: 3,
      labels: ['payments', 'Q4', 'audit'],
    },
    {
      id: 2,
      owner: 'Liam Carter',
      project: 'Search',
      status: 'done',
      progress: 100,
      priority: 2,
      labels: ['search'],
    },
    {
      id: 3,
      owner: 'Emma Stone',
      project: 'Mobile app',
      status: 'blocked',
      progress: 25,
      priority: 3,
      labels: ['mobile', 'launch'],
    },
    {
      id: 4,
      owner: 'Noah Wright',
      project: 'Docs site',
      status: 'active',
      progress: 9,
      priority: 1,
      labels: ['docs'],
    },
    {
      id: 5,
      owner: 'Ava Brooks',
      project: 'Data export',
      status: 'active',
      progress: 90,
      priority: 2,
      labels: [],
    },
  ],
  rowKey: 'id',
  filterRow: true,
  saveMode: 'none',
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log('Click a header to sort, or filter with the inputs under the headers.');
  const stop = nameBars('Progress', 1);
  // Keep the select boxes above in step with the current state when you sort by header click or filter with the inputs.
  const sortBox = document.getElementById('sort');
  const statusBox = document.getElementById('status');
  const offs = [
    api.on('sortChanged', ({ sortModel }) => {
      const only = sortModel.length === 1 ? sortModel[0] : undefined;
      const value = only &&
        only.direction === 'desc' &&
        (only.columnId === 'progress' || only.columnId === 'priority')
        ? only.columnId
        : 'none';
      if (sortBox instanceof HTMLSelectElement)
        sortBox.value = value;
    }),
    api.on('filterChanged', ({ filterModel }) => {
      const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
      const value = only && only.columnId === 'status' && only.operator === 'equals'
        ? String(only.value)
        : 'all';
      if (statusBox instanceof HTMLSelectElement)
        statusBox.value = value;
    }),
  ];
  return () => {
    stop();
    offs.forEach((off) => off());
  };
}
export const actions = {
  sort: (api, value) => {
    const by = value === 'progress' || value === 'priority' ? value : '';
    api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
    say(by
      ? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
      : 'Sort cleared.');
  },
  status: (api, value) => {
    api.setFilterModel(value && value !== 'all'
      ? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
      : null);
    say(value && value !== 'all'
      ? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
      : 'Filter cleared.');
  },
};