내 색으로 테마 만들기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.
코드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)
이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/themes로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));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' });
},
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!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">
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.themes.min.js"></script>
<script>
const { applyTheme, checkTheme, createTheme } = MaxGrid.themes;
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
const depts = ['개발팀', '디자인팀', '영업팀', '인사팀'];
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);
}
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?.();
};
}
const actions = {
// 이 그리드에만 적용돼요. '기본'을 고르면 되돌려요.
theme: (_api, value) => {
choice = value ?? 'default';
show();
if (choice === 'default')
say({ ko: '기본 테마로 되돌렸어요', en: 'Back to the default theme' });
},
};
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('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));
</script>
</body>
</html> 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/react @maxgrid/themes로 설치하세요.
버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="테마"
disabled={!api}
onChange={(event) => api && actions.theme(api, event.target.value)}
>
<option value="default">기본</option>
<option value="green">초록</option>
<option value="purple">보라</option>
<option value="pale">연한 글자</option>
</select>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
import { applyTheme, checkTheme, createTheme } from '@maxgrid/themes';
import type { Theme, ThemeTokens } from '@maxgrid/themes';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
const depts = ['개발팀', '디자인팀', '영업팀', '인사팀'];
export const options: GridOptions<Row> = {
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] as string,
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',
},
};
type Mode = keyof typeof MODES;
type Brand = Pick<ThemeTokens, 'accent' | 'selectionBackground'> & Partial<ThemeTokens>;
const BRANDS: Record<string, Record<Mode, Brand>> = {
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: string, mode: Mode): Theme | undefined {
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 = (): Mode =>
document.documentElement.dataset.mxgTheme === 'dark' ? 'dark' : 'light';
let choice = 'default';
let restore: (() => void) | undefined;
let say: (message: LogText) => void = () => {};
// 대비 검사 결과를 페이지의 기록 줄에도 알려요(콘솔을 열지 않아도 보여요).
function report(violations: { ratio: number }[]): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, value?: string) => {
choice = value ?? 'default';
show();
if (choice === 'default')
say({ ko: '기본 테마로 되돌렸어요', en: 'Back to the default theme' });
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/vue @maxgrid/themes로 설치하세요.
버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="테마"
:disabled="!api"
@change="api && actions.theme(api, ($event.target as HTMLSelectElement).value)"
>
<option value="default" selected>기본</option>
<option value="green">초록</option>
<option value="purple">보라</option>
<option value="pale">연한 글자</option>
</select>
</div>
<Grid style="height: 360px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
import { applyTheme, checkTheme, createTheme } from '@maxgrid/themes';
import type { Theme, ThemeTokens } from '@maxgrid/themes';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
const depts = ['개발팀', '디자인팀', '영업팀', '인사팀'];
export const options: GridOptions<Row> = {
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] as string,
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',
},
};
type Mode = keyof typeof MODES;
type Brand = Pick<ThemeTokens, 'accent' | 'selectionBackground'> & Partial<ThemeTokens>;
const BRANDS: Record<string, Record<Mode, Brand>> = {
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: string, mode: Mode): Theme | undefined {
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 = (): Mode =>
document.documentElement.dataset.mxgTheme === 'dark' ? 'dark' : 'light';
let choice = 'default';
let restore: (() => void) | undefined;
let say: (message: LogText) => void = () => {};
// 대비 검사 결과를 페이지의 기록 줄에도 알려요(콘솔을 열지 않아도 보여요).
function report(violations: { ratio: number }[]): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, value?: string) => {
choice = value ?? 'default';
show();
if (choice === 'default')
say({ ko: '기본 테마로 되돌렸어요', en: 'Back to the default theme' });
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/angular @maxgrid/themes로 설치하세요.
버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="테마"
[disabled]="!api"
(change)="api && actions.theme(api, $any($event.target).value)"
>
<option value="default" selected>기본</option>
<option value="green">초록</option>
<option value="purple">보라</option>
<option value="pale">연한 글자</option>
</select>
</div>
<mx-grid style="height: 360px" [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 { GridApi, GridOptions } from '@maxgrid/angular';
import { applyTheme, checkTheme, createTheme } from '@maxgrid/themes';
import type { Theme, ThemeTokens } from '@maxgrid/themes';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
const depts = ['개발팀', '디자인팀', '영업팀', '인사팀'];
export const options: GridOptions<Row> = {
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] as string,
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',
},
};
type Mode = keyof typeof MODES;
type Brand = Pick<ThemeTokens, 'accent' | 'selectionBackground'> & Partial<ThemeTokens>;
const BRANDS: Record<string, Record<Mode, Brand>> = {
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: string, mode: Mode): Theme | undefined {
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 = (): Mode =>
document.documentElement.dataset.mxgTheme === 'dark' ? 'dark' : 'light';
let choice = 'default';
let restore: (() => void) | undefined;
let say: (message: LogText) => void = () => {};
// 대비 검사 결과를 페이지의 기록 줄에도 알려요(콘솔을 열지 않아도 보여요).
function report(violations: { ratio: number }[]): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, value?: string) => {
choice = value ?? 'default';
show();
if (choice === 'default')
say({ ko: '기본 테마로 되돌렸어요', en: 'Back to the default theme' });
},
}; 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.
<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>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));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');
},
};This HTML also loads an extra bundle (the extra script tag above) and uses it as a global. No install is needed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Create a theme from your own colors</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.themes.min.js"></script>
<script>
const { applyTheme, checkTheme, createTheme } = 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'];
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);
}
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?.();
};
}
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');
},
};
options.ariaLabel = "Create a theme from your own colors";
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('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/themes.
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">
<select
aria-label="Theme"
disabled={!api}
onChange={(event) => api && actions.theme(api, event.target.value)}
>
<option value="default">Default</option>
<option value="green">Green</option>
<option value="purple">Purple</option>
<option value="pale">Pale text</option>
</select>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
import { applyTheme, checkTheme, createTheme } from '@maxgrid/themes';
import type { Theme, ThemeTokens } from '@maxgrid/themes';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
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: GridOptions<Row> = {
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] as string,
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',
},
};
type Mode = keyof typeof MODES;
type Brand = Pick<ThemeTokens, 'accent' | 'selectionBackground'> & Partial<ThemeTokens>;
const BRANDS: Record<string, Record<Mode, Brand>> = {
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: string, mode: Mode): Theme | undefined {
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 = (): Mode =>
document.documentElement.dataset.mxgTheme === 'dark' ? 'dark' : 'light';
let choice = 'default';
let restore: (() => void) | undefined;
let say: (message: LogText) => void = () => {};
// Also report the contrast check result in the page log line (visible without opening the console).
function report(violations: { ratio: number }[]): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, value?: string) => {
choice = value ?? 'default';
show();
if (choice === 'default') say('Back to the default theme');
},
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/vue @maxgrid/themes.
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">
<select
aria-label="Theme"
:disabled="!api"
@change="api && actions.theme(api, ($event.target as HTMLSelectElement).value)"
>
<option value="default" selected>Default</option>
<option value="green">Green</option>
<option value="purple">Purple</option>
<option value="pale">Pale text</option>
</select>
</div>
<Grid style="height: 360px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
import { applyTheme, checkTheme, createTheme } from '@maxgrid/themes';
import type { Theme, ThemeTokens } from '@maxgrid/themes';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
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: GridOptions<Row> = {
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] as string,
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',
},
};
type Mode = keyof typeof MODES;
type Brand = Pick<ThemeTokens, 'accent' | 'selectionBackground'> & Partial<ThemeTokens>;
const BRANDS: Record<string, Record<Mode, Brand>> = {
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: string, mode: Mode): Theme | undefined {
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 = (): Mode =>
document.documentElement.dataset.mxgTheme === 'dark' ? 'dark' : 'light';
let choice = 'default';
let restore: (() => void) | undefined;
let say: (message: LogText) => void = () => {};
// Also report the contrast check result in the page log line (visible without opening the console).
function report(violations: { ratio: number }[]): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, value?: string) => {
choice = value ?? 'default';
show();
if (choice === 'default') say('Back to the default theme');
},
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/angular @maxgrid/themes.
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">
<select
aria-label="Theme"
[disabled]="!api"
(change)="api && actions.theme(api, $any($event.target).value)"
>
<option value="default" selected>Default</option>
<option value="green">Green</option>
<option value="purple">Purple</option>
<option value="pale">Pale text</option>
</select>
</div>
<mx-grid style="height: 360px" [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 { GridApi, GridOptions } from '@maxgrid/angular';
import { applyTheme, checkTheme, createTheme } from '@maxgrid/themes';
import type { Theme, ThemeTokens } from '@maxgrid/themes';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
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: GridOptions<Row> = {
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] as string,
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',
},
};
type Mode = keyof typeof MODES;
type Brand = Pick<ThemeTokens, 'accent' | 'selectionBackground'> & Partial<ThemeTokens>;
const BRANDS: Record<string, Record<Mode, Brand>> = {
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: string, mode: Mode): Theme | undefined {
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 = (): Mode =>
document.documentElement.dataset.mxgTheme === 'dark' ? 'dark' : 'light';
let choice = 'default';
let restore: (() => void) | undefined;
let say: (message: LogText) => void = () => {};
// Also report the contrast check result in the page log line (visible without opening the console).
function report(violations: { ratio: number }[]): void {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, value?: string) => {
choice = value ?? 'default';
show();
if (choice === 'default') say('Back to the default theme');
},
};