내가 만드는 편집기: 색상·슬라이더·별점Build your own editors: color, slider, stars
내장 편집기로 부족하면 직접 만들 수 있어요. 편집기는 "화면 만들기, 값 돌려주기, 확정 알리기"만 하는 작은 객체예요. 색상 고르기, 슬라이더, 별점을 예로 만들었고, 칸에 보이는 모양(막대·별)은 내장 렌더러를 그대로 써요.When the built-in editors are not enough, write one: a small object that builds its UI, returns a value and says when to commit. Color swatches, a slider and stars are shown, while the cell display reuses built-in renderers.
코드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">
<button type="button" id="editColor">색상 편집</button>
<button type="button" id="editProgress">진행률 편집</button>
<button type="button" id="editRating">중요도 편집</button>
</div>
<div id="grid" style="height: 280px"></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('editColor').addEventListener('click', () => actions.editColor(api));
document.getElementById('editProgress').addEventListener('click', () => actions.editProgress(api));
document.getElementById('editRating').addEventListener('click', () => actions.editRating(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES = {
'#e5484d': '빨강',
'#f5a524': '주황',
'#30a46c': '초록',
'#0091ff': '파랑',
'#8e4ec6': '보라',
};
const rows = [
{ id: 1, label: '긴급 점검', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: '나중에 하기', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: '디자인 검토', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: '문서 정리', color: '#30a46c', progress: 100, rating: 3 },
];
// 편집기 만드는 법: mount(칸 안에 화면 만들기) · getValue(확정할 값) · focus · setError · destroy를 가진 객체를 돌려줘요.
// 값을 정했으면 ctx.commit()으로 "이 값으로 확정해 줘" 하고 알려요. 칸에 보이는 모양은 cellRenderer가 따로 맡아요.
// 1) 색상: 동그라미 버튼 중에서 고르기. 누르면 바로 확정해요.
const swatchRenderer = () => {
let chip;
let name;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() { },
};
};
const swatchEditor = () => {
let value = '';
let box;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() { },
destroy: () => box.remove(),
};
};
// 2) 진행률: 슬라이더. 놓으면(change) 확정해요. 칸에 보이는 막대는 내장 progress 렌더러예요.
const sliderEditor = () => {
let input;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() { },
destroy: () => input.remove(),
};
};
// 3) 별점: 별을 누르면 그 점수로 확정해요. 칸에 보이는 별은 내장 rating 렌더러예요.
const starEditor = () => {
let value = 0;
let box;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', L(`${n}점`, `${n} points`));
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() { },
destroy: () => box.remove(),
};
};
export const options = {
columns: [
{ id: 'label', title: '작업', width: 110 },
{
id: 'color',
title: '색상',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: '진행률',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: '중요도',
kind: 'number',
width: 120,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
export function setup(api, log) {
log({
ko: '색상·진행률·중요도 칸을 더블클릭해 보세요. 칸마다 다른 편집기가 열려요.',
en: 'Double-click the color, progress or importance cells. Each column opens a different editor.',
});
const names = { color: '색상', progress: '진행률', rating: '중요도' };
return api.on('editCommitted', (e) => log({
ko: `${e.rowKey}번 줄 ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
}));
}
export const actions = {
editColor: (api) => api.startEdit(1, 'color'),
editProgress: (api) => api.startEdit(1, 'progress'),
editRating: (api) => api.startEdit(1, 'rating'),
};<!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">
<button type="button" id="editColor">색상 편집</button>
<button type="button" id="editProgress">진행률 편집</button>
<button type="button" id="editRating">중요도 편집</button>
</div>
<div id="grid" style="height: 280px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES = {
'#e5484d': '빨강',
'#f5a524': '주황',
'#30a46c': '초록',
'#0091ff': '파랑',
'#8e4ec6': '보라',
};
const rows = [
{ id: 1, label: '긴급 점검', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: '나중에 하기', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: '디자인 검토', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: '문서 정리', color: '#30a46c', progress: 100, rating: 3 },
];
// 편집기 만드는 법: mount(칸 안에 화면 만들기) · getValue(확정할 값) · focus · setError · destroy를 가진 객체를 돌려줘요.
// 값을 정했으면 ctx.commit()으로 "이 값으로 확정해 줘" 하고 알려요. 칸에 보이는 모양은 cellRenderer가 따로 맡아요.
// 1) 색상: 동그라미 버튼 중에서 고르기. 누르면 바로 확정해요.
const swatchRenderer = () => {
let chip;
let name;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() { },
};
};
const swatchEditor = () => {
let value = '';
let box;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() { },
destroy: () => box.remove(),
};
};
// 2) 진행률: 슬라이더. 놓으면(change) 확정해요. 칸에 보이는 막대는 내장 progress 렌더러예요.
const sliderEditor = () => {
let input;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() { },
destroy: () => input.remove(),
};
};
// 3) 별점: 별을 누르면 그 점수로 확정해요. 칸에 보이는 별은 내장 rating 렌더러예요.
const starEditor = () => {
let value = 0;
let box;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', L(`${n}점`, `${n} points`));
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() { },
destroy: () => box.remove(),
};
};
const options = {
columns: [
{ id: 'label', title: '작업', width: 110 },
{
id: 'color',
title: '색상',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: '진행률',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: '중요도',
kind: 'number',
width: 120,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
function setup(api, log) {
log({
ko: '색상·진행률·중요도 칸을 더블클릭해 보세요. 칸마다 다른 편집기가 열려요.',
en: 'Double-click the color, progress or importance cells. Each column opens a different editor.',
});
const names = { color: '색상', progress: '진행률', rating: '중요도' };
return api.on('editCommitted', (e) => log({
ko: `${e.rowKey}번 줄 ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
}));
}
const actions = {
editColor: (api) => api.startEdit(1, 'color'),
editProgress: (api) => api.startEdit(1, 'progress'),
editRating: (api) => api.startEdit(1, 'rating'),
};
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('editColor').addEventListener('click', () => actions.editColor(api));
document.getElementById('editProgress').addEventListener('click', () => actions.editProgress(api));
document.getElementById('editRating').addEventListener('click', () => actions.editRating(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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.editColor(api)}
>색상 편집</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editProgress(api)}
>진행률 편집</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editRating(api)}
>중요도 편집</button>
</div>
<Grid style={{ height: 280 }} ref={gridRef} options={options} />
</>
);
}import type { CellEditorAdapter, CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
label: string;
color: string;
progress: number;
rating: number;
}
const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES: Record<string, string> = {
'#e5484d': '빨강',
'#f5a524': '주황',
'#30a46c': '초록',
'#0091ff': '파랑',
'#8e4ec6': '보라',
};
const rows: Row[] = [
{ id: 1, label: '긴급 점검', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: '나중에 하기', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: '디자인 검토', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: '문서 정리', color: '#30a46c', progress: 100, rating: 3 },
];
// 편집기 만드는 법: mount(칸 안에 화면 만들기) · getValue(확정할 값) · focus · setError · destroy를 가진 객체를 돌려줘요.
// 값을 정했으면 ctx.commit()으로 "이 값으로 확정해 줘" 하고 알려요. 칸에 보이는 모양은 cellRenderer가 따로 맡아요.
// 1) 색상: 동그라미 버튼 중에서 고르기. 누르면 바로 확정해요.
const swatchRenderer = (): CellRendererAdapter<Row> => {
let chip: HTMLSpanElement;
let name: HTMLSpanElement;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() {},
};
};
const swatchEditor = (): CellEditorAdapter<Row> => {
let value = '';
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
// 2) 진행률: 슬라이더. 놓으면(change) 확정해요. 칸에 보이는 막대는 내장 progress 렌더러예요.
const sliderEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() {},
destroy: () => input.remove(),
};
};
// 3) 별점: 별을 누르면 그 점수로 확정해요. 칸에 보이는 별은 내장 rating 렌더러예요.
const starEditor = (): CellEditorAdapter<Row> => {
let value = 0;
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', L(`${n}점`, `${n} points`));
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'label', title: '작업', width: 110 },
{
id: 'color',
title: '색상',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: '진행률',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: '중요도',
kind: 'number',
width: 120,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '색상·진행률·중요도 칸을 더블클릭해 보세요. 칸마다 다른 편집기가 열려요.',
en: 'Double-click the color, progress or importance cells. Each column opens a different editor.',
});
const names: Record<string, string> = { color: '색상', progress: '진행률', rating: '중요도' };
return api.on('editCommitted', (e) =>
log({
ko: `${e.rowKey}번 줄 ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
}),
);
}
export const actions = {
editColor: (api: GridApi<Row>) => api.startEdit(1, 'color'),
editProgress: (api: GridApi<Row>) => api.startEdit(1, 'progress'),
editRating: (api: GridApi<Row>) => api.startEdit(1, 'rating'),
};버튼을 누르면 이 예제의 코드가 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">
<button
type="button"
:disabled="!api"
@click="api && actions.editColor(api)"
>색상 편집</button>
<button
type="button"
:disabled="!api"
@click="api && actions.editProgress(api)"
>진행률 편집</button>
<button
type="button"
:disabled="!api"
@click="api && actions.editRating(api)"
>중요도 편집</button>
</div>
<Grid style="height: 280px" :options="options" @ready="onReady" />
</template>import type { CellEditorAdapter, CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
label: string;
color: string;
progress: number;
rating: number;
}
const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES: Record<string, string> = {
'#e5484d': '빨강',
'#f5a524': '주황',
'#30a46c': '초록',
'#0091ff': '파랑',
'#8e4ec6': '보라',
};
const rows: Row[] = [
{ id: 1, label: '긴급 점검', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: '나중에 하기', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: '디자인 검토', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: '문서 정리', color: '#30a46c', progress: 100, rating: 3 },
];
// 편집기 만드는 법: mount(칸 안에 화면 만들기) · getValue(확정할 값) · focus · setError · destroy를 가진 객체를 돌려줘요.
// 값을 정했으면 ctx.commit()으로 "이 값으로 확정해 줘" 하고 알려요. 칸에 보이는 모양은 cellRenderer가 따로 맡아요.
// 1) 색상: 동그라미 버튼 중에서 고르기. 누르면 바로 확정해요.
const swatchRenderer = (): CellRendererAdapter<Row> => {
let chip: HTMLSpanElement;
let name: HTMLSpanElement;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() {},
};
};
const swatchEditor = (): CellEditorAdapter<Row> => {
let value = '';
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
// 2) 진행률: 슬라이더. 놓으면(change) 확정해요. 칸에 보이는 막대는 내장 progress 렌더러예요.
const sliderEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() {},
destroy: () => input.remove(),
};
};
// 3) 별점: 별을 누르면 그 점수로 확정해요. 칸에 보이는 별은 내장 rating 렌더러예요.
const starEditor = (): CellEditorAdapter<Row> => {
let value = 0;
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', L(`${n}점`, `${n} points`));
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'label', title: '작업', width: 110 },
{
id: 'color',
title: '색상',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: '진행률',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: '중요도',
kind: 'number',
width: 120,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '색상·진행률·중요도 칸을 더블클릭해 보세요. 칸마다 다른 편집기가 열려요.',
en: 'Double-click the color, progress or importance cells. Each column opens a different editor.',
});
const names: Record<string, string> = { color: '색상', progress: '진행률', rating: '중요도' };
return api.on('editCommitted', (e) =>
log({
ko: `${e.rowKey}번 줄 ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
}),
);
}
export const actions = {
editColor: (api: GridApi<Row>) => api.startEdit(1, 'color'),
editProgress: (api: GridApi<Row>) => api.startEdit(1, 'progress'),
editRating: (api: GridApi<Row>) => api.startEdit(1, 'rating'),
};버튼을 누르면 이 예제의 코드가 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">
<button
type="button"
[disabled]="!api"
(click)="api && actions.editColor(api)"
>색상 편집</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editProgress(api)"
>진행률 편집</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editRating(api)"
>중요도 편집</button>
</div>
<mx-grid style="height: 280px" [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 { CellEditorAdapter, CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
label: string;
color: string;
progress: number;
rating: number;
}
const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES: Record<string, string> = {
'#e5484d': '빨강',
'#f5a524': '주황',
'#30a46c': '초록',
'#0091ff': '파랑',
'#8e4ec6': '보라',
};
const rows: Row[] = [
{ id: 1, label: '긴급 점검', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: '나중에 하기', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: '디자인 검토', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: '문서 정리', color: '#30a46c', progress: 100, rating: 3 },
];
// 편집기 만드는 법: mount(칸 안에 화면 만들기) · getValue(확정할 값) · focus · setError · destroy를 가진 객체를 돌려줘요.
// 값을 정했으면 ctx.commit()으로 "이 값으로 확정해 줘" 하고 알려요. 칸에 보이는 모양은 cellRenderer가 따로 맡아요.
// 1) 색상: 동그라미 버튼 중에서 고르기. 누르면 바로 확정해요.
const swatchRenderer = (): CellRendererAdapter<Row> => {
let chip: HTMLSpanElement;
let name: HTMLSpanElement;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() {},
};
};
const swatchEditor = (): CellEditorAdapter<Row> => {
let value = '';
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
// 2) 진행률: 슬라이더. 놓으면(change) 확정해요. 칸에 보이는 막대는 내장 progress 렌더러예요.
const sliderEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() {},
destroy: () => input.remove(),
};
};
// 3) 별점: 별을 누르면 그 점수로 확정해요. 칸에 보이는 별은 내장 rating 렌더러예요.
const starEditor = (): CellEditorAdapter<Row> => {
let value = 0;
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', L(`${n}점`, `${n} points`));
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'label', title: '작업', width: 110 },
{
id: 'color',
title: '색상',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: '진행률',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: '중요도',
kind: 'number',
width: 120,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '색상·진행률·중요도 칸을 더블클릭해 보세요. 칸마다 다른 편집기가 열려요.',
en: 'Double-click the color, progress or importance cells. Each column opens a different editor.',
});
const names: Record<string, string> = { color: '색상', progress: '진행률', rating: '중요도' };
return api.on('editCommitted', (e) =>
log({
ko: `${e.rowKey}번 줄 ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`,
}),
);
}
export const actions = {
editColor: (api: GridApi<Row>) => api.startEdit(1, 'color'),
editProgress: (api: GridApi<Row>) => api.startEdit(1, 'progress'),
editRating: (api: GridApi<Row>) => api.startEdit(1, 'rating'),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="editColor">Edit color</button>
<button type="button" id="editProgress">Edit progress</button>
<button type="button" id="editRating">Edit rating</button>
</div>
<div id="grid" style="height: 280px"></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('editColor').addEventListener('click', () => actions.editColor(api));
document.getElementById('editProgress').addEventListener('click', () => actions.editProgress(api));
document.getElementById('editRating').addEventListener('click', () => actions.editRating(api));const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES = {
'#e5484d': 'Red',
'#f5a524': 'Orange',
'#30a46c': 'Green',
'#0091ff': 'Blue',
'#8e4ec6': 'Purple',
};
const rows = [
{ id: 1, label: 'Urgent check', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: 'Do later', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: 'Design review', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: 'Tidy docs', color: '#30a46c', progress: 100, rating: 3 },
];
// How to build an editor: return an object with mount (build the UI inside the cell), getValue (the value to commit), focus, setError and destroy.
// Once a value is chosen, call ctx.commit() to say "commit this value". The cell display is handled separately by cellRenderer.
// 1) Color: pick from round buttons. Pressing one commits at once.
const swatchRenderer = () => {
let chip;
let name;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() { },
};
};
const swatchEditor = () => {
let value = '';
let box;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() { },
destroy: () => box.remove(),
};
};
// 2) Progress: a slider. Releasing it (change) commits. The bar in the cell is the built-in progress renderer.
const sliderEditor = () => {
let input;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() { },
destroy: () => input.remove(),
};
};
// 3) Rating: pressing a star commits that score. The stars in the cell are the built-in rating renderer.
const starEditor = () => {
let value = 0;
let box;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', `${n} points`);
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() { },
destroy: () => box.remove(),
};
};
export const options = {
columns: [
{ id: 'label', title: 'Task', width: 110 },
{
id: 'color',
title: 'Color',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: 'Progress',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: 'Importance',
kind: 'number',
width: 130,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
export function setup(api, log) {
log('Double-click the color, progress or importance cells. Each column opens a different editor.');
const names = {
color: 'Color',
progress: 'Progress',
rating: 'Importance',
};
return api.on('editCommitted', (e) => log(`Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`));
}
export const actions = {
editColor: (api) => api.startEdit(1, 'color'),
editProgress: (api) => api.startEdit(1, 'progress'),
editRating: (api) => api.startEdit(1, 'rating'),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Build your own editors: color, slider, stars</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="editColor">Edit color</button>
<button type="button" id="editProgress">Edit progress</button>
<button type="button" id="editRating">Edit rating</button>
</div>
<div id="grid" style="height: 280px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES = {
'#e5484d': 'Red',
'#f5a524': 'Orange',
'#30a46c': 'Green',
'#0091ff': 'Blue',
'#8e4ec6': 'Purple',
};
const rows = [
{ id: 1, label: 'Urgent check', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: 'Do later', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: 'Design review', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: 'Tidy docs', color: '#30a46c', progress: 100, rating: 3 },
];
// How to build an editor: return an object with mount (build the UI inside the cell), getValue (the value to commit), focus, setError and destroy.
// Once a value is chosen, call ctx.commit() to say "commit this value". The cell display is handled separately by cellRenderer.
// 1) Color: pick from round buttons. Pressing one commits at once.
const swatchRenderer = () => {
let chip;
let name;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() { },
};
};
const swatchEditor = () => {
let value = '';
let box;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() { },
destroy: () => box.remove(),
};
};
// 2) Progress: a slider. Releasing it (change) commits. The bar in the cell is the built-in progress renderer.
const sliderEditor = () => {
let input;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() { },
destroy: () => input.remove(),
};
};
// 3) Rating: pressing a star commits that score. The stars in the cell are the built-in rating renderer.
const starEditor = () => {
let value = 0;
let box;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', `${n} points`);
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() { },
destroy: () => box.remove(),
};
};
const options = {
columns: [
{ id: 'label', title: 'Task', width: 110 },
{
id: 'color',
title: 'Color',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: 'Progress',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: 'Importance',
kind: 'number',
width: 130,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
function setup(api, log) {
log('Double-click the color, progress or importance cells. Each column opens a different editor.');
const names = {
color: 'Color',
progress: 'Progress',
rating: 'Importance',
};
return api.on('editCommitted', (e) => log(`Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`));
}
const actions = {
editColor: (api) => api.startEdit(1, 'color'),
editProgress: (api) => api.startEdit(1, 'progress'),
editRating: (api) => api.startEdit(1, 'rating'),
};
options.ariaLabel = "Build your own editors: color, slider, stars";
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('editColor').addEventListener('click', () => actions.editColor(api));
document.getElementById('editProgress').addEventListener('click', () => actions.editProgress(api));
document.getElementById('editRating').addEventListener('click', () => actions.editRating(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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.editColor(api)}
>Edit color</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editProgress(api)}
>Edit progress</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editRating(api)}
>Edit rating</button>
</div>
<Grid style={{ height: 280 }} ref={gridRef} options={options} />
</>
);
}import type { CellEditorAdapter, CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
label: string;
color: string;
progress: number;
rating: number;
}
const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES: Record<string, string> = {
'#e5484d': 'Red',
'#f5a524': 'Orange',
'#30a46c': 'Green',
'#0091ff': 'Blue',
'#8e4ec6': 'Purple',
};
const rows: Row[] = [
{ id: 1, label: 'Urgent check', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: 'Do later', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: 'Design review', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: 'Tidy docs', color: '#30a46c', progress: 100, rating: 3 },
];
// How to build an editor: return an object with mount (build the UI inside the cell), getValue (the value to commit), focus, setError and destroy.
// Once a value is chosen, call ctx.commit() to say "commit this value". The cell display is handled separately by cellRenderer.
// 1) Color: pick from round buttons. Pressing one commits at once.
const swatchRenderer = (): CellRendererAdapter<Row> => {
let chip: HTMLSpanElement;
let name: HTMLSpanElement;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() {},
};
};
const swatchEditor = (): CellEditorAdapter<Row> => {
let value = '';
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
// 2) Progress: a slider. Releasing it (change) commits. The bar in the cell is the built-in progress renderer.
const sliderEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() {},
destroy: () => input.remove(),
};
};
// 3) Rating: pressing a star commits that score. The stars in the cell are the built-in rating renderer.
const starEditor = (): CellEditorAdapter<Row> => {
let value = 0;
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', `${n} points`);
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'label', title: 'Task', width: 110 },
{
id: 'color',
title: 'Color',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: 'Progress',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: 'Importance',
kind: 'number',
width: 130,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Double-click the color, progress or importance cells. Each column opens a different editor.',
);
const names: Record<string, string> = {
color: 'Color',
progress: 'Progress',
rating: 'Importance',
};
return api.on('editCommitted', (e) =>
log(`Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`),
);
}
export const actions = {
editColor: (api: GridApi<Row>) => api.startEdit(1, 'color'),
editProgress: (api: GridApi<Row>) => api.startEdit(1, 'progress'),
editRating: (api: GridApi<Row>) => api.startEdit(1, 'rating'),
};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">
<button
type="button"
:disabled="!api"
@click="api && actions.editColor(api)"
>Edit color</button>
<button
type="button"
:disabled="!api"
@click="api && actions.editProgress(api)"
>Edit progress</button>
<button
type="button"
:disabled="!api"
@click="api && actions.editRating(api)"
>Edit rating</button>
</div>
<Grid style="height: 280px" :options="options" @ready="onReady" />
</template>import type { CellEditorAdapter, CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
label: string;
color: string;
progress: number;
rating: number;
}
const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES: Record<string, string> = {
'#e5484d': 'Red',
'#f5a524': 'Orange',
'#30a46c': 'Green',
'#0091ff': 'Blue',
'#8e4ec6': 'Purple',
};
const rows: Row[] = [
{ id: 1, label: 'Urgent check', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: 'Do later', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: 'Design review', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: 'Tidy docs', color: '#30a46c', progress: 100, rating: 3 },
];
// How to build an editor: return an object with mount (build the UI inside the cell), getValue (the value to commit), focus, setError and destroy.
// Once a value is chosen, call ctx.commit() to say "commit this value". The cell display is handled separately by cellRenderer.
// 1) Color: pick from round buttons. Pressing one commits at once.
const swatchRenderer = (): CellRendererAdapter<Row> => {
let chip: HTMLSpanElement;
let name: HTMLSpanElement;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() {},
};
};
const swatchEditor = (): CellEditorAdapter<Row> => {
let value = '';
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
// 2) Progress: a slider. Releasing it (change) commits. The bar in the cell is the built-in progress renderer.
const sliderEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() {},
destroy: () => input.remove(),
};
};
// 3) Rating: pressing a star commits that score. The stars in the cell are the built-in rating renderer.
const starEditor = (): CellEditorAdapter<Row> => {
let value = 0;
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', `${n} points`);
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'label', title: 'Task', width: 110 },
{
id: 'color',
title: 'Color',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: 'Progress',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: 'Importance',
kind: 'number',
width: 130,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Double-click the color, progress or importance cells. Each column opens a different editor.',
);
const names: Record<string, string> = {
color: 'Color',
progress: 'Progress',
rating: 'Importance',
};
return api.on('editCommitted', (e) =>
log(`Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`),
);
}
export const actions = {
editColor: (api: GridApi<Row>) => api.startEdit(1, 'color'),
editProgress: (api: GridApi<Row>) => api.startEdit(1, 'progress'),
editRating: (api: GridApi<Row>) => api.startEdit(1, 'rating'),
};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">
<button
type="button"
[disabled]="!api"
(click)="api && actions.editColor(api)"
>Edit color</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editProgress(api)"
>Edit progress</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editRating(api)"
>Edit rating</button>
</div>
<mx-grid style="height: 280px" [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 { CellEditorAdapter, CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
label: string;
color: string;
progress: number;
rating: number;
}
const COLORS = ['#e5484d', '#f5a524', '#30a46c', '#0091ff', '#8e4ec6'];
const COLOR_NAMES: Record<string, string> = {
'#e5484d': 'Red',
'#f5a524': 'Orange',
'#30a46c': 'Green',
'#0091ff': 'Blue',
'#8e4ec6': 'Purple',
};
const rows: Row[] = [
{ id: 1, label: 'Urgent check', color: '#e5484d', progress: 80, rating: 5 },
{ id: 2, label: 'Do later', color: '#0091ff', progress: 20, rating: 2 },
{ id: 3, label: 'Design review', color: '#8e4ec6', progress: 55, rating: 4 },
{ id: 4, label: 'Tidy docs', color: '#30a46c', progress: 100, rating: 3 },
];
// How to build an editor: return an object with mount (build the UI inside the cell), getValue (the value to commit), focus, setError and destroy.
// Once a value is chosen, call ctx.commit() to say "commit this value". The cell display is handled separately by cellRenderer.
// 1) Color: pick from round buttons. Pressing one commits at once.
const swatchRenderer = (): CellRendererAdapter<Row> => {
let chip: HTMLSpanElement;
let name: HTMLSpanElement;
return {
mount(el, ctx) {
chip = document.createElement('span');
chip.style.cssText = 'display: inline-block; width: 28px; height: 14px; border-radius: 7px;';
name = document.createElement('span');
name.style.cssText = 'margin-left: 8px;';
el.append(chip, name);
this.update(ctx);
},
update(ctx) {
chip.style.background = String(ctx.value);
chip.title = COLOR_NAMES[String(ctx.value)] ?? String(ctx.value);
name.textContent = chip.title;
},
destroy() {},
};
};
const swatchEditor = (): CellEditorAdapter<Row> => {
let value = '';
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = String(ctx.value);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 6px; align-items: center; padding: 0 8px; height: 100%;';
for (const color of COLORS) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-label', COLOR_NAMES[color] ?? color);
button.title = COLOR_NAMES[color] ?? color;
button.style.cssText = `width: 20px; height: 20px; border-radius: 50%; border: 2px solid ${color === value ? 'var(--mxg-fg)' : 'transparent'}; background: ${color}; cursor: pointer;`;
button.addEventListener('click', () => {
value = color;
ctx.commit();
});
box.append(button);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
// 2) Progress: a slider. Releasing it (change) commits. The bar in the cell is the built-in progress renderer.
const sliderEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
Object.assign(input, {
type: 'range',
min: '0',
max: '100',
step: '5',
value: String(ctx.value ?? 0),
});
input.style.cssText = 'width: 100%; margin: 0;';
input.addEventListener('change', () => ctx.commit());
el.append(input);
},
getValue: () => Number(input.value),
focus: () => input.focus(),
setError() {},
destroy: () => input.remove(),
};
};
// 3) Rating: pressing a star commits that score. The stars in the cell are the built-in rating renderer.
const starEditor = (): CellEditorAdapter<Row> => {
let value = 0;
let box: HTMLDivElement;
return {
mount(el, ctx) {
value = Number(ctx.value ?? 0);
box = document.createElement('div');
box.style.cssText =
'display: flex; gap: 2px; align-items: center; padding: 0 8px; height: 100%; font-size: 18px;';
for (let n = 1; n <= 5; n += 1) {
const star = document.createElement('button');
star.type = 'button';
star.setAttribute('aria-label', `${n} points`);
star.textContent = n <= value ? '★' : '☆';
star.style.cssText =
'border: 0; background: none; cursor: pointer; padding: 0; font: inherit; color: var(--mxg-accent);';
star.addEventListener('click', () => {
value = n;
ctx.commit();
});
box.append(star);
}
el.append(box);
},
getValue: () => value,
focus: () => box.querySelector('button')?.focus(),
setError() {},
destroy: () => box.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'label', title: 'Task', width: 110 },
{
id: 'color',
title: 'Color',
kind: 'custom',
width: 170,
editable: true,
cellRenderer: swatchRenderer,
cellEditor: swatchEditor,
},
{
id: 'progress',
title: 'Progress',
kind: 'number',
width: 150,
editable: true,
cellRenderer: 'progress',
cellEditor: sliderEditor,
},
{
id: 'rating',
title: 'Importance',
kind: 'number',
width: 130,
editable: true,
cellRenderer: 'rating',
cellEditor: starEditor,
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Double-click the color, progress or importance cells. Each column opens a different editor.',
);
const names: Record<string, string> = {
color: 'Color',
progress: 'Progress',
rating: 'Importance',
};
return api.on('editCommitted', (e) =>
log(`Row ${e.rowKey} ${names[e.columnId] ?? e.columnId} → ${String(e.newValue)}`),
);
}
export const actions = {
editColor: (api: GridApi<Row>) => api.startEdit(1, 'color'),
editProgress: (api: GridApi<Row>) => api.startEdit(1, 'progress'),
editRating: (api: GridApi<Row>) => api.startEdit(1, 'rating'),
};