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

내가 만드는 편집기: 색상·슬라이더·별점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.

심화Advanced
직접 써 보기Live preview내가 만드는 편집기: 색상·슬라이더·별점Build your own editors: color, slider, stars

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('editColor').addEventListener('click', () => actions.editColor(api));
document.getElementById('editProgress').addEventListener('click', () => actions.editProgress(api));
document.getElementById('editRating').addEventListener('click', () => actions.editRating(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(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'),
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('editColor').addEventListener('click', () => actions.editColor(api));
document.getElementById('editProgress').addEventListener('click', () => actions.editProgress(api));
document.getElementById('editRating').addEventListener('click', () => actions.editRating(api));
example.js
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'),
};