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

트리 검색: 찾은 글자 강조하기Tree search with highlighted matches

안내 글에서 글자를 찾으면 일치하는 줄만 남기고 찾은 글자에 색을 칠해요. 일치하는 줄의 위 단계 줄도 함께 보여요.Search the notes: only matching rows stay and the found text is highlighted. Parent rows of the matches stay visible.

활용Intermediate
직접 써 보기Live preview트리 검색: 찾은 글자 강조하기Tree search with highlighted matches

코드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">
    <input
      type="text"
      aria-label="검색"
      placeholder="안내에서 찾기 (예: 결제)"
      id="find"
    />
    <button type="button" id="clear">검색 지우기</button>
  </div>
  <div id="grid" style="height: 300px"></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('find').addEventListener('input', (event) => actions.find(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
let query = '';
// 찾은 글자를 <mark>로 칠해요. 글자는 텍스트 노드로만 넣어서, 메모에 HTML이 있어도 실행되지 않아요.
const highlight = () => {
  let host;
  const paint = (text) => {
    host.replaceChildren();
    const at = query ? text.toLowerCase().indexOf(query.toLowerCase()) : -1;
    if (at < 0) {
      host.append(text);
      return;
    }
    const mark = document.createElement('mark');
    mark.textContent = text.slice(at, at + query.length);
    // 밝은·어두운 테마 모두에서 보이도록 강조색 변수를 써요.
    mark.style.cssText =
      'background: color-mix(in srgb, var(--mxg-accent) 35%, transparent); color: inherit; border-radius: 2px;';
    host.append(text.slice(0, at), mark, text.slice(at + query.length));
  };
  return {
    mount(el, ctx) {
      host = el;
      paint(ctx.text);
    },
    update(ctx) {
      paint(ctx.text);
    },
    destroy() { },
  };
};
// 트리 컬럼은 기본 칸을 그대로 두어서 펼침 화살표가 나와요. 강조는 메모 컬럼에 칠해요.
export const options = {
  columns: [
    { id: 'name', title: '주제', width: 170 },
    { id: 'note', title: '안내 (찾은 글자 강조)', width: 300, cellRenderer: highlight },
  ],
  rows: [
    { id: 1, parentId: null, name: '결제', note: '청구서와 결제 관련 문의' },
    { id: 2, parentId: 1, name: '청구서', note: '청구서를 내려받는 곳' },
    { id: 3, parentId: 1, name: '환불', note: '환불 기간과 결제 수단 안내' },
    { id: 4, parentId: null, name: '계정', note: '로그인과 프로필' },
    { id: 5, parentId: 4, name: '비밀번호', note: '잃어버린 비밀번호 다시 만들기' },
    { id: 6, parentId: 4, name: '프로필', note: '이름과 이메일 바꾸기' },
    { id: 7, parentId: null, name: '배송', note: '배송 기간과 송장 조회' },
  ],
  rowKey: 'id',
  tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
let say = () => { };
export function setup(api, log) {
  say = log;
  query = '';
  api.setFilterModel(null);
}
function find(api, text) {
  query = text;
  api.setFilterModel(text
    ? { match: 'all', items: [{ columnId: 'note', operator: 'contains', value: text }] }
    : null);
  api.refresh(); // 칸이 재사용되어서, 다시 그리라고 알려야 강조가 바뀌어요
  say({
    ko: text
      ? `찾는 글자 "${text}" — 보이는 줄 ${api.getVisibleRowCount()}개 (위 단계 줄 포함)`
      : '검색을 지웠어요.',
    en: text
      ? `Searching "${text}" — ${api.getVisibleRowCount()} rows visible (including parent rows)`
      : 'Search cleared.',
  });
}
export const actions = {
  find: (api, value) => find(api, (value ?? '').trim()),
  clear: (api) => {
    const box = document.getElementById('find');
    if (box instanceof HTMLInputElement)
      box.value = '';
    find(api, '');
  },
};

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">
    <input
      type="text"
      aria-label="Search"
      placeholder="Search notes (e.g. payment)"
      id="find"
    />
    <button type="button" id="clear">Clear search</button>
  </div>
  <div id="grid" style="height: 300px"></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('find').addEventListener('input', (event) => actions.find(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
let query = '';
// Paint the found text with <mark>. The text goes in only as text nodes, so HTML in a note never runs.
const highlight = () => {
  let host;
  const paint = (text) => {
    host.replaceChildren();
    const at = query ? text.toLowerCase().indexOf(query.toLowerCase()) : -1;
    if (at < 0) {
      host.append(text);
      return;
    }
    const mark = document.createElement('mark');
    mark.textContent = text.slice(at, at + query.length);
    // Use the accent color variable so it shows in both light and dark themes.
    mark.style.cssText =
      'background: color-mix(in srgb, var(--mxg-accent) 35%, transparent); color: inherit; border-radius: 2px;';
    host.append(text.slice(0, at), mark, text.slice(at + query.length));
  };
  return {
    mount(el, ctx) {
      host = el;
      paint(ctx.text);
    },
    update(ctx) {
      paint(ctx.text);
    },
    destroy() { },
  };
};
// The tree column keeps the default cell, so the expand arrow shows. The highlight is painted on the note column.
export const options = {
  columns: [
    { id: 'name', title: 'Topic', width: 170 },
    { id: 'note', title: 'Note (matches highlighted)', width: 320, cellRenderer: highlight },
  ],
  rows: [
    { id: 1, parentId: null, name: 'Billing', note: 'Questions about invoices and payment' },
    { id: 2, parentId: 1, name: 'Invoices', note: 'Where to download invoices' },
    { id: 3, parentId: 1, name: 'Refunds', note: 'Refund period and payment methods' },
    { id: 4, parentId: null, name: 'Account', note: 'Sign-in and profile' },
    { id: 5, parentId: 4, name: 'Password', note: 'Reset a lost password' },
    { id: 6, parentId: 4, name: 'Profile', note: 'Change your name and email' },
    { id: 7, parentId: null, name: 'Shipping', note: 'Delivery time and tracking' },
  ],
  rowKey: 'id',
  tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
let say = () => { };
export function setup(api, log) {
  say = log;
  query = '';
  api.setFilterModel(null);
}
function find(api, text) {
  query = text;
  api.setFilterModel(text
    ? { match: 'all', items: [{ columnId: 'note', operator: 'contains', value: text }] }
    : null);
  api.refresh(); // Cells are reused, so ask for a redraw to update the highlight
  say(text
    ? `Searching "${text}" — ${api.getVisibleRowCount()} rows visible (including parent rows)`
    : 'Search cleared.');
}
export const actions = {
  find: (api, value) => find(api, (value ?? '').trim()),
  clear: (api) => {
    const box = document.getElementById('find');
    if (box instanceof HTMLInputElement)
      box.value = '';
    find(api, '');
  },
};