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

내 색으로 테마 만들기Create a theme from your own colors

색 몇 개만 정하면 나머지 색은 자동으로 계산해서 이 표에만 적용해요. 글자 대비가 모자라면 알려줘요.Pick a few colors and the rest are derived and applied to this grid only. Low text contrast is reported.

활용Intermediate
직접 써 보기Live preview내 색으로 테마 만들기Create a theme from your own colors

코드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 탭이나 직접 해보기를 쓰세요.

이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/themes로 설치하세요.

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

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="테마" id="theme">
      <option value="default" selected>기본</option>
      <option value="green">초록</option>
      <option value="purple">보라</option>
      <option value="pale">연한 글자</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></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('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));
example.js
import { applyTheme, checkTheme, createTheme } from '@maxgrid/themes';
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
const depts = ['개발팀', '디자인팀', '영업팀', '인사팀'];
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 150 },
    { id: 'dept', title: '부서', width: 130 },
    { id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
  ],
  rows: names.map((name, i) => ({
    id: i + 1,
    name,
    dept: depts[i % 4],
    salary: 320 + i * 41,
  })),
  rowKey: 'id',
  selection: 'single',
};
// 핵심 토큰 8개만 정하면 나머지 변수는 자동으로 계산돼요.
// 사이트가 밝을 때와 어두울 때의 바탕·글자색을 따로 두고, 브랜드 색(강조색·선택 배경)만 바꿔요.
const FONT = "system-ui, 'Noto Sans KR', sans-serif";
const MODES = {
  light: {
    background: '#ffffff',
    text: '#1f2933',
    border: '#d9dee5',
    headerBackground: '#f3f5f8',
    danger: '#b42318',
  },
  dark: {
    background: '#151a21',
    text: '#e6e9ee',
    border: '#323b47',
    headerBackground: '#1f262f',
    danger: '#ff8a80',
  },
};
const BRANDS = {
  green: {
    light: { accent: '#0b7a45', selectionBackground: '#d8f1e3' },
    dark: { accent: '#4cc38a', selectionBackground: '#1d4a33' },
  },
  purple: {
    light: { accent: '#6b3fc4', selectionBackground: '#e6dcf8', radius: '8px' },
    dark: { accent: '#b79cf5', selectionBackground: '#3a2a63', radius: '8px' },
  },
  // 글자색이 연해서 대비 검사가 위반을 알려줘요(개발자 콘솔 경고).
  pale: {
    light: { text: '#aab4bf', accent: '#7aa7f5', selectionBackground: '#eef3fd' },
    dark: { text: '#4a5563', accent: '#3d5f99', selectionBackground: '#1a2433' },
  },
};
function makeTheme(brand, mode) {
  const colors = BRANDS[brand]?.[mode];
  if (!colors)
    return undefined;
  const tokens = { ...MODES[mode], font: FONT, ...colors };
  return createTheme({ name: `example-${brand}-${mode}`, base: mode, tokens });
}
// 사이트의 밝게/어둡게 설정을 따라가요. 테마를 적용한 요소는 사이트 설정과 별개로 자기 테마를 써요.
const siteMode = () => document.documentElement.dataset.mxgTheme === 'dark' ? 'dark' : 'light';
let choice = 'default';
let restore;
let say = () => { };
// 대비 검사 결과를 페이지의 기록 줄에도 알려요(콘솔을 열지 않아도 보여요).
function report(violations) {
  if (violations.length === 0)
    return say({
      ko: '글자·경계 색 대비 검사: 문제 없어요',
      en: 'Text and border color contrast check: no problems',
    });
  const lowest = Math.min(...violations.map((v) => v.ratio));
  say({
    ko: `색 대비가 모자란 곳이 ${violations.length}군데예요 (가장 낮은 값 ${lowest}:1, 글자는 4.5:1 이상이 필요해요)`,
    en: `Low contrast in ${violations.length} places (lowest ${lowest}:1, text needs 4.5:1 or more)`,
  });
}
function show() {
  const root = document.querySelector('.mxg');
  restore?.();
  restore = undefined;
  const theme = makeTheme(choice, siteMode());
  if (!root || !theme)
    return;
  report(checkTheme(theme));
  restore = applyTheme(root, theme);
}
export function setup(api, log) {
  say = log;
  // 처음부터 한 행을 골라 두면 강조색과 선택 색이 바로 보여요.
  api.setSelectedKeys([2]);
  log({
    ko: '두 번째 행을 골라 뒀어요. 테마를 바꾸면 강조색과 선택 색이 바뀌어요.',
    en: 'The second row is selected. Change the theme and the accent and selection colors change.',
  });
  // 사이트 모드가 바뀌면 같은 브랜드 색으로 다시 만들어 적용해요.
  const watcher = new MutationObserver(show);
  watcher.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['data-mxg-theme'],
  });
  return () => {
    watcher.disconnect();
    restore?.();
  };
}
export const actions = {
  // 이 그리드에만 적용돼요. '기본'을 고르면 되돌려요.
  theme: (_api, value) => {
    choice = value ?? 'default';
    show();
    if (choice === 'default')
      say({ ko: '기본 테마로 되돌렸어요', en: 'Back to the default theme' });
  },
};

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

This example needs an extra package. To run it locally, install with npm i maxgrid @maxgrid/themes.

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">
    <select aria-label="Theme" id="theme">
      <option value="default" selected>Default</option>
      <option value="green">Green</option>
      <option value="purple">Purple</option>
      <option value="pale">Pale text</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></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('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));
example.js
import { applyTheme, checkTheme, createTheme } from '@maxgrid/themes';
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Brooks',
  'Olivia Reed',
  'Ethan Hall',
  'Ava Morgan',
  'Mason Gray',
  'Mia Foster',
];
const depts = ['Dev', 'Design', 'Sales', 'HR'];
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 150 },
    { id: 'dept', title: 'Dept', width: 130 },
    { id: 'salary', title: 'Monthly pay ($)', kind: 'number', width: 130, align: 'end' },
  ],
  rows: names.map((name, i) => ({
    id: i + 1,
    name,
    dept: depts[i % 4],
    salary: 3200 + i * 410,
  })),
  rowKey: 'id',
  selection: 'single',
};
// Set just the 8 core tokens and the remaining variables are computed automatically.
// Keep separate background/text colors for light and dark site modes, and change only the brand colors (accent, selection background).
const FONT = "system-ui, 'Noto Sans KR', sans-serif";
const MODES = {
  light: {
    background: '#ffffff',
    text: '#1f2933',
    border: '#d9dee5',
    headerBackground: '#f3f5f8',
    danger: '#b42318',
  },
  dark: {
    background: '#151a21',
    text: '#e6e9ee',
    border: '#323b47',
    headerBackground: '#1f262f',
    danger: '#ff8a80',
  },
};
const BRANDS = {
  green: {
    light: { accent: '#0b7a45', selectionBackground: '#d8f1e3' },
    dark: { accent: '#4cc38a', selectionBackground: '#1d4a33' },
  },
  purple: {
    light: { accent: '#6b3fc4', selectionBackground: '#e6dcf8', radius: '8px' },
    dark: { accent: '#b79cf5', selectionBackground: '#3a2a63', radius: '8px' },
  },
  // The text color is pale, so the contrast check reports violations (developer console warning).
  pale: {
    light: { text: '#aab4bf', accent: '#7aa7f5', selectionBackground: '#eef3fd' },
    dark: { text: '#4a5563', accent: '#3d5f99', selectionBackground: '#1a2433' },
  },
};
function makeTheme(brand, mode) {
  const colors = BRANDS[brand]?.[mode];
  if (!colors)
    return undefined;
  const tokens = { ...MODES[mode], font: FONT, ...colors };
  return createTheme({ name: `example-${brand}-${mode}`, base: mode, tokens });
}
// Follows the site's light/dark setting. An element with a theme applied uses its own theme regardless of the site setting.
const siteMode = () => document.documentElement.dataset.mxgTheme === 'dark' ? 'dark' : 'light';
let choice = 'default';
let restore;
let say = () => { };
// Also report the contrast check result in the page log line (visible without opening the console).
function report(violations) {
  if (violations.length === 0)
    return say('Text and border color contrast check: no problems');
  const lowest = Math.min(...violations.map((v) => v.ratio));
  say(`Low contrast in ${violations.length} places (lowest ${lowest}:1, text needs 4.5:1 or more)`);
}
function show() {
  const root = document.querySelector('.mxg');
  restore?.();
  restore = undefined;
  const theme = makeTheme(choice, siteMode());
  if (!root || !theme)
    return;
  report(checkTheme(theme));
  restore = applyTheme(root, theme);
}
export function setup(api, log) {
  say = log;
  // Selecting a row from the start shows the accent and selection colors right away.
  api.setSelectedKeys([2]);
  log('The second row is selected. Change the theme and the accent and selection colors change.');
  // When the site mode changes, rebuild and apply the theme with the same brand color.
  const watcher = new MutationObserver(show);
  watcher.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['data-mxg-theme'],
  });
  return () => {
    watcher.disconnect();
    restore?.();
  };
}
export const actions = {
  // Applies to this grid only. Choosing 'default' reverts it.
  theme: (_api, value) => {
    choice = value ?? 'default';
    show();
    if (choice === 'default')
      say('Back to the default theme');
  },
};