트리 검색: 찾은 글자 강조하기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.
코드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">
<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>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));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, '');
},
};<!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">
<input
type="text"
aria-label="검색"
placeholder="안내에서 찾기 (예: 결제)"
id="find"
/>
<button type="button" id="clear">검색 지우기</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
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() { },
};
};
// 트리 컬럼은 기본 칸을 그대로 두어서 펼침 화살표가 나와요. 강조는 메모 컬럼에 칠해요.
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 = () => { };
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.',
});
}
const actions = {
find: (api, value) => find(api, (value ?? '').trim()),
clear: (api) => {
const box = document.getElementById('find');
if (box instanceof HTMLInputElement)
box.value = '';
find(api, '');
},
};
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('find').addEventListener('input', (event) => actions.find(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<input
type="text"
aria-label="검색"
placeholder="안내에서 찾기 (예: 결제)"
disabled={!api}
onChange={(event) => api && actions.find(api, event.target.value)}
/>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>검색 지우기</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
note: string;
}
let query = '';
// 찾은 글자를 <mark>로 칠해요. 글자는 텍스트 노드로만 넣어서, 메모에 HTML이 있어도 실행되지 않아요.
const highlight = (): CellRendererAdapter<Row> => {
let host: HTMLElement;
const paint = (text: string): void => {
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
query = '';
api.setFilterModel(null);
}
function find(api: GridApi<Row>, text: string): void {
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: GridApi<Row>, value?: string) => find(api, (value ?? '').trim()),
clear: (api: GridApi<Row>) => {
const box = document.getElementById('find');
if (box instanceof HTMLInputElement) box.value = '';
find(api, '');
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<input
type="text"
aria-label="검색"
placeholder="안내에서 찾기 (예: 결제)"
:disabled="!api"
@input="api && actions.find(api, ($event.target as HTMLInputElement).value)"
/>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">검색 지우기</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
note: string;
}
let query = '';
// 찾은 글자를 <mark>로 칠해요. 글자는 텍스트 노드로만 넣어서, 메모에 HTML이 있어도 실행되지 않아요.
const highlight = (): CellRendererAdapter<Row> => {
let host: HTMLElement;
const paint = (text: string): void => {
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
query = '';
api.setFilterModel(null);
}
function find(api: GridApi<Row>, text: string): void {
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: GridApi<Row>, value?: string) => find(api, (value ?? '').trim()),
clear: (api: GridApi<Row>) => {
const box = document.getElementById('find');
if (box instanceof HTMLInputElement) box.value = '';
find(api, '');
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<input
type="text"
aria-label="검색"
placeholder="안내에서 찾기 (예: 결제)"
[disabled]="!api"
(input)="api && actions.find(api, $any($event.target).value)"
/>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>검색 지우기</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
note: string;
}
let query = '';
// 찾은 글자를 <mark>로 칠해요. 글자는 텍스트 노드로만 넣어서, 메모에 HTML이 있어도 실행되지 않아요.
const highlight = (): CellRendererAdapter<Row> => {
let host: HTMLElement;
const paint = (text: string): void => {
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
query = '';
api.setFilterModel(null);
}
function find(api: GridApi<Row>, text: string): void {
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: GridApi<Row>, value?: string) => find(api, (value ?? '').trim()),
clear: (api: GridApi<Row>) => {
const box = document.getElementById('find');
if (box instanceof HTMLInputElement) box.value = '';
find(api, '');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<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>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));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, '');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tree search with highlighted matches</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
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.
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 = () => { };
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.');
}
const actions = {
find: (api, value) => find(api, (value ?? '').trim()),
clear: (api) => {
const box = document.getElementById('find');
if (box instanceof HTMLInputElement)
box.value = '';
find(api, '');
},
};
options.ariaLabel = "Tree search with highlighted matches";
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('find').addEventListener('input', (event) => actions.find(api, event.target.value));
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 { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<input
type="text"
aria-label="Search"
placeholder="Search notes (e.g. payment)"
disabled={!api}
onChange={(event) => api && actions.find(api, event.target.value)}
/>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear search</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
note: string;
}
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 = (): CellRendererAdapter<Row> => {
let host: HTMLElement;
const paint = (text: string): void => {
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
query = '';
api.setFilterModel(null);
}
function find(api: GridApi<Row>, text: string): void {
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: GridApi<Row>, value?: string) => find(api, (value ?? '').trim()),
clear: (api: GridApi<Row>) => {
const box = document.getElementById('find');
if (box instanceof HTMLInputElement) box.value = '';
find(api, '');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<input
type="text"
aria-label="Search"
placeholder="Search notes (e.g. payment)"
:disabled="!api"
@input="api && actions.find(api, ($event.target as HTMLInputElement).value)"
/>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear search</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
note: string;
}
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 = (): CellRendererAdapter<Row> => {
let host: HTMLElement;
const paint = (text: string): void => {
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
query = '';
api.setFilterModel(null);
}
function find(api: GridApi<Row>, text: string): void {
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: GridApi<Row>, value?: string) => find(api, (value ?? '').trim()),
clear: (api: GridApi<Row>) => {
const box = document.getElementById('find');
if (box instanceof HTMLInputElement) box.value = '';
find(api, '');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<input
type="text"
aria-label="Search"
placeholder="Search notes (e.g. payment)"
[disabled]="!api"
(input)="api && actions.find(api, $any($event.target).value)"
/>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear search</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
note: string;
}
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 = (): CellRendererAdapter<Row> => {
let host: HTMLElement;
const paint = (text: string): void => {
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
query = '';
api.setFilterModel(null);
}
function find(api: GridApi<Row>, text: string): void {
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: GridApi<Row>, value?: string) => find(api, (value ?? '').trim()),
clear: (api: GridApi<Row>) => {
const box = document.getElementById('find');
if (box instanceof HTMLInputElement) box.value = '';
find(api, '');
},
};