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

색 고르기 편집기Color picker editor

색 칸은 색 네모와 색 코드를 보여 주고, 편집할 때는 브라우저의 색 고르기가 열려요. 색을 고르면 바로 확정돼요.The color cell shows a swatch and its code, and editing opens the browser’s color picker. Picking a color commits at once.

활용Intermediate
직접 써 보기Live preview색 고르기 편집기Color picker editor

코드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="edit">첫 색 편집</button>
    <button type="button" id="reset">처음 색으로</button>
  </div>
  <div id="grid" style="height: 260px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('edit').addEventListener('click', () => actions.edit(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 폰처럼 손가락으로 쓰는 화면인지 알려 줘요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
// 칸에는 색 네모와 색 코드를 보여 주고, 편집기는 브라우저의 색 고르기 입력칸(<input type="color">)이에요.
const swatch = () => {
  let box;
  let text;
  return {
    mount(el, ctx) {
      box = document.createElement('span');
      box.setAttribute('aria-hidden', 'true');
      box.style.cssText =
        'display: inline-block; width: 14px; height: 14px; margin-right: 8px; border-radius: 3px; border: 1px solid var(--mxg-border); vertical-align: middle;';
      text = document.createTextNode('');
      centered(el).append(box, text);
      this.update(ctx);
    },
    update(ctx) {
      // 올바른 색 코드일 때만 스타일에 넣어서, 이상한 글자가 CSS로 들어가지 못하게 해요.
      box.style.background = /^#[0-9a-f]{6}$/i.test(ctx.text) ? ctx.text : 'transparent';
      text.data = ctx.text;
    },
    destroy() { },
  };
};
const colorEditor = () => {
  let input;
  return {
    mount(el, ctx) {
      input = document.createElement('input');
      input.type = 'color';
      input.value = /^#[0-9a-f]{6}$/i.test(String(ctx.value)) ? String(ctx.value) : '#000000';
      input.style.cssText =
        'width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 2px 6px; background: transparent;';
      input.setAttribute('aria-label', L(`${ctx.row.label} 색 고르기`, `Pick a color for ${ctx.row.label}`));
      input.addEventListener('change', () => ctx.commit());
      el.append(input);
    },
    getValue: () => input.value,
    focus() {
      input.focus();
      // 편집을 시작하자마자 색 고르기 창이 열리게 해요(브라우저가 막으면 입력칸만 보여요).
      try {
        input.showPicker();
      }
      catch {
        /* 사용자 동작 없이는 열 수 없는 브라우저면 건너뛰어요 */
      }
    },
    setError(message) {
      input.title = message ?? '';
    },
    destroy: () => input.remove(),
  };
};
export const options = {
  columns: [
    { id: 'label', title: '이름', width: 130 },
    {
      id: 'color',
      title: '색(더블클릭)',
      width: 170,
      editable: true,
      cellRenderer: swatch,
      cellEditor: colorEditor,
    },
  ],
  rows: [
    { id: 1, label: '대표 색', color: '#1a56c4' },
    { id: 2, label: '성공', color: '#1a7f37' },
    { id: 3, label: '주의', color: '#bf8700' },
    { id: 4, label: '위험', color: '#cf222e' },
  ],
  rowKey: 'id',
  saveMode: 'none',
  ...(coarse() ? { rowHeight: 44 } : {}),
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log({
    ko: '색 칸을 더블클릭해서 색을 골라 보세요. 고르면 바로 확정돼요.',
    en: 'Double-click a color cell and pick a color. It is confirmed as soon as you pick.',
  });
  return api.on('editCommitted', (e) => {
    const row = api.getRowByKey(e.rowKey);
    log(`${row?.label ?? e.rowKey}: ${String(e.oldValue)} → ${String(e.newValue)}`);
  });
}
export const actions = {
  edit: (api) => api.startEdit(1, 'color'),
  reset: (api) => {
    api.updateRows([
      { id: 1, label: '대표 색', color: '#1a56c4' },
      { id: 2, label: '성공', color: '#1a7f37' },
      { id: 3, label: '주의', color: '#bf8700' },
      { id: 4, label: '위험', color: '#cf222e' },
    ]);
    say({ ko: '처음 색으로 되돌렸어요.', en: 'Back to the first color.' });
  },
};

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="edit">Edit first color</button>
    <button type="button" id="reset">Back to start</button>
  </div>
  <div id="grid" style="height: 260px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('edit').addEventListener('click', () => actions.edit(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
// Tells whether the screen is finger-driven, like a phone.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
// The cell shows a color square and the color code; the editor is the browser's color input (<input type="color">).
const swatch = () => {
  let box;
  let text;
  return {
    mount(el, ctx) {
      box = document.createElement('span');
      box.setAttribute('aria-hidden', 'true');
      box.style.cssText =
        'display: inline-block; width: 14px; height: 14px; margin-right: 8px; border-radius: 3px; border: 1px solid var(--mxg-border); vertical-align: middle;';
      text = document.createTextNode('');
      centered(el).append(box, text);
      this.update(ctx);
    },
    update(ctx) {
      // Only a valid color code goes into the style, so odd text cannot enter the CSS.
      box.style.background = /^#[0-9a-f]{6}$/i.test(ctx.text) ? ctx.text : 'transparent';
      text.data = ctx.text;
    },
    destroy() { },
  };
};
const colorEditor = () => {
  let input;
  return {
    mount(el, ctx) {
      input = document.createElement('input');
      input.type = 'color';
      input.value = /^#[0-9a-f]{6}$/i.test(String(ctx.value)) ? String(ctx.value) : '#000000';
      input.style.cssText =
        'width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 2px 6px; background: transparent;';
      input.setAttribute('aria-label', `Pick a color for ${ctx.row.label}`);
      input.addEventListener('change', () => ctx.commit());
      el.append(input);
    },
    getValue: () => input.value,
    focus() {
      input.focus();
      // Open the color picker as soon as editing starts (if the browser blocks it, only the input is shown).
      try {
        input.showPicker();
      }
      catch {
        /* skip in browsers that cannot open it without a user gesture */
      }
    },
    setError(message) {
      input.title = message ?? '';
    },
    destroy: () => input.remove(),
  };
};
export const options = {
  columns: [
    { id: 'label', title: 'Name', width: 130 },
    {
      id: 'color',
      title: 'Color (double-click)',
      width: 170,
      editable: true,
      cellRenderer: swatch,
      cellEditor: colorEditor,
    },
  ],
  rows: [
    { id: 1, label: 'Primary', color: '#1a56c4' },
    { id: 2, label: 'Success', color: '#1a7f37' },
    { id: 3, label: 'Warning', color: '#bf8700' },
    { id: 4, label: 'Danger', color: '#cf222e' },
  ],
  rowKey: 'id',
  saveMode: 'none',
  ...(coarse() ? { rowHeight: 44 } : {}),
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log('Double-click a color cell and pick a color. It is confirmed as soon as you pick.');
  return api.on('editCommitted', (e) => {
    const row = api.getRowByKey(e.rowKey);
    log(`${row?.label ?? e.rowKey}: ${String(e.oldValue)} → ${String(e.newValue)}`);
  });
}
export const actions = {
  edit: (api) => api.startEdit(1, 'color'),
  reset: (api) => {
    api.updateRows([
      { id: 1, label: 'Primary', color: '#1a56c4' },
      { id: 2, label: 'Success', color: '#1a7f37' },
      { id: 3, label: 'Warning', color: '#bf8700' },
      { id: 4, label: 'Danger', color: '#cf222e' },
    ]);
    say('Back to the first color.');
  },
};