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

찾은 글자를 노란색으로 표시하기Highlight the matched text

검색한 글자를 셀 안에서 형광펜처럼 칠해서 어디가 맞았는지 바로 보여 줘요. 값에 태그 같은 글자가 들어 있어도 글자 그대로 보여 줘서 안전해요.Highlight the matched text inside the cell like a marker so it is clear where the search hit. Values containing tag-like text are shown as plain text, so they stay safe.

심화Advanced
직접 써 보기Live preview찾은 글자를 노란색으로 표시하기Highlight the matched text

코드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="search" />
  </div>
  <div id="grid" style="height: 260px"></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);
document.getElementById('search').addEventListener('input', (event) => actions.search(api, event.target.value));
example.js
let term = '';
// 셀은 글자 조각과 <mark> 요소로 만들어요(HTML 문자열을 쓰지 않아서 '<b>x</b>' 같은 값도 글자 그대로 보여요).
// 필터와 같이 대소문자를 구분하지 않고, 한 셀에 여러 번 나오면 모두 칠해요.
const highlight = () => {
  let box;
  return {
    mount(el, ctx) {
      box = el;
      this.update(ctx);
    },
    update(ctx) {
      const text = ctx.text;
      const lower = text.toLowerCase();
      const word = term.toLowerCase();
      const parts = [];
      let from = 0;
      for (let at = word ? lower.indexOf(word) : -1; at >= 0; at = lower.indexOf(word, from)) {
        if (at > from)
          parts.push(text.slice(from, at));
        const mark = document.createElement('mark');
        mark.textContent = text.slice(at, at + word.length);
        parts.push(mark);
        from = at + word.length;
      }
      parts.push(text.slice(from));
      box.replaceChildren(...parts);
    },
    destroy() { },
  };
};
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 130, cellRenderer: highlight },
    { id: 'email', title: '이메일', width: 220, cellRenderer: highlight },
    { id: 'memo', title: '메모', width: 220, cellRenderer: highlight },
  ],
  rows: [
    { id: 1, name: '김민준', email: 'minjun.kim@maxmine.com', memo: '김 팀장님 추천으로 입사' },
    { id: 2, name: '이서연', email: 'seoyeon.lee@maxmine.com', memo: '디자인팀 신규 입사' },
    { id: 3, name: '박지호', email: 'jiho.park@maxmine.com', memo: '영업 3팀, 김해 지점' },
    { id: 4, name: '김서윤', email: 'seoyun.kim@maxmine.com', memo: '김서윤 대리, 김밥 모임 총무' },
    { id: 5, name: '최유나', email: 'yuna.choi@maxmine.com', memo: '개발팀 입사 동기 김씨 형제' },
    {
      id: 6,
      name: 'William Kim',
      email: 'will.kim@maxmine.com',
      memo: 'Kim is on leave until June',
    },
  ],
  rowKey: 'id',
};
// 강조 색은 호박색을 배경에 섞은 반투명 색이라, 어두운 테마에서도 눈이 부시지 않고 글자색은 그대로 읽혀요.
export function setup(_api) {
  const style = document.createElement('style');
  style.textContent =
    'mark { background: color-mix(in srgb, #f5a524 42%, transparent); color: inherit; border-radius: 2px; padding: 0 1px; }';
  document.head.append(style);
  return () => style.remove();
}
export const actions = {
  search: (api, value) => {
    term = (value ?? '').trim();
    api.setFilterModel(term
      ? {
        match: 'any',
        items: ['name', 'email', 'memo'].map((columnId) => ({
          columnId,
          operator: 'contains',
          value: term,
        })),
      }
      : null);
    api.refresh(); // 이미 그려진 셀도 새 강조를 받도록 다시 그려요
  },
};

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 (e.g. Kim)"
      id="search"
    />
  </div>
  <div id="grid" style="height: 260px"></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);
document.getElementById('search').addEventListener('input', (event) => actions.search(api, event.target.value));
example.js
let term = '';
// The cell is built from text pieces and <mark> elements (no HTML strings, so a value like '<b>x</b>' shows as plain text).
// Like the filter, case is ignored, and every occurrence in a cell is highlighted.
const highlight = () => {
  let box;
  return {
    mount(el, ctx) {
      box = el;
      this.update(ctx);
    },
    update(ctx) {
      const text = ctx.text;
      const lower = text.toLowerCase();
      const word = term.toLowerCase();
      const parts = [];
      let from = 0;
      for (let at = word ? lower.indexOf(word) : -1; at >= 0; at = lower.indexOf(word, from)) {
        if (at > from)
          parts.push(text.slice(from, at));
        const mark = document.createElement('mark');
        mark.textContent = text.slice(at, at + word.length);
        parts.push(mark);
        from = at + word.length;
      }
      parts.push(text.slice(from));
      box.replaceChildren(...parts);
    },
    destroy() { },
  };
};
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 140, cellRenderer: highlight },
    { id: 'email', title: 'Email', width: 220, cellRenderer: highlight },
    { id: 'memo', title: 'Notes', width: 280, cellRenderer: highlight },
  ],
  rows: [
    {
      id: 1,
      name: 'Liam Kim',
      email: 'liam.kim@maxmine.com',
      memo: 'Referred by team lead Kim',
    },
    {
      id: 2,
      name: 'Emma Stone',
      email: 'emma.stone@maxmine.com',
      memo: 'New hire on the design team',
    },
    {
      id: 3,
      name: 'Noah Park',
      email: 'noah.park@maxmine.com',
      memo: 'Sales team 3, Kimberly branch',
    },
    {
      id: 4,
      name: 'Olivia Kim',
      email: 'olivia.kim@maxmine.com',
      memo: 'Olivia Kim, assistant manager, runs the Kimbap club',
    },
    {
      id: 5,
      name: 'Ethan Brooks',
      email: 'ethan.brooks@maxmine.com',
      memo: 'Dev team hire cohort, the Kim brothers',
    },
    {
      id: 6,
      name: 'William Kim',
      email: 'will.kim@maxmine.com',
      memo: 'Kim is on leave until June',
    },
  ],
  rowKey: 'id',
};
// The highlight color is amber mixed translucently into the background, so it is not glaring in dark themes and the text color stays readable.
export function setup(_api) {
  const style = document.createElement('style');
  style.textContent =
    'mark { background: color-mix(in srgb, #f5a524 42%, transparent); color: inherit; border-radius: 2px; padding: 0 1px; }';
  document.head.append(style);
  return () => style.remove();
}
export const actions = {
  search: (api, value) => {
    term = (value ?? '').trim();
    api.setFilterModel(term
      ? {
        match: 'any',
        items: ['name', 'email', 'memo'].map((columnId) => ({
          columnId,
          operator: 'contains',
          value: term,
        })),
      }
      : null);
    api.refresh(); // Redraw so cells that are already drawn also get the new highlight
  },
};