밝은·어두운 화면과 칸 여백을 앱 상태로 바꾸기Switch light/dark and cell padding from app state
칸 여백은 표의 옵션 값으로, 밝은·어두운 화면은 표를 감싼 요소의 data-mxg-theme 속성으로 바꿔요. 둘 다 앱의 상태 값 하나에 묶어 두면 선택 목록을 바꿀 때 표가 바로 따라와요. Angular 탭에는 기기가 어두운 화면을 쓰는지 알아보고, 화면이 사라질 때 듣던 것을 멈추는 부분도 있어요. React, Vue, Angular 탭에는 각 프레임워크의 방식으로 쓴 같은 예제가 들어 있어요.Cell padding is a grid option and light/dark is the data-mxg-theme attribute on the element around the grid. Tie both to one piece of app state and the grid follows the selects. The Angular tab also detects the device dark setting and stops listening when the view goes away. The React, Vue and Angular tabs hold the same example written the way each framework does it.
실행 화면은 JavaScript 버전이에요. 아래 탭의 React·Vue·Angular 코드는 같은 예제를 각 프레임워크로 직접 쓴 코드예요.The preview runs the JavaScript version. The React, Vue, Angular tabs below hold the same example written for each framework.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<select aria-label="칸 여백" id="density">
<option value="compact">촘촘하게</option>
<option value="normal" selected>보통 (기본)</option>
<option value="comfortable">넉넉하게</option>
</select>
<select aria-label="화면" id="theme">
<option value="system" selected>사이트 설정 따라가기 (기본)</option>
<option value="light">밝게</option>
<option value="dark">어둡게</option>
</select>
</div>
<div id="grid" style="height: 420px"></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('density').addEventListener('change', (event) => actions.density(api, event.target.value));
document.getElementById('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));const NAMES = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const DEPTS = ['개발팀', '디자인팀', '영업팀'];
export const options = {
columns: [
{ id: 'name', title: '이름', width: 140 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3],
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
export const DENSITY_WORDS = {
compact: '촘촘하게',
normal: '보통',
comfortable: '넉넉하게',
};
const DENSITY_WORDS_EN = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say = () => { };
export const actions = {
// 칸 여백은 그리드 옵션이에요. 값을 바꿔 setOptions로 넘기면 바로 반영돼요.
density: (api, value) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// 어두운 화면은 CSS 속성이에요. 표(또는 그 위 요소)에 data-mxg-theme="dark"를 달면 그 안쪽만 바뀌어요.
theme: (_api, value) => {
const root = document.querySelector('.mxg');
if (!root)
return;
if (value === 'light' || value === 'dark')
root.setAttribute('data-mxg-theme', value);
else
root.removeAttribute('data-mxg-theme');
say({
ko: `화면: ${value === 'light' ? '밝게' : value === 'dark' ? '어둡게' : '사이트 설정 따라가기'}`,
en: `Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`,
});
},
};
export function setup(api, log) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log({
ko: `칸 여백: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`,
en: `Cell padding: ${DENSITY_WORDS_EN[api.getOptions().density ?? 'normal']}`,
});
}
});
}<!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="density">
<option value="compact">촘촘하게</option>
<option value="normal" selected>보통 (기본)</option>
<option value="comfortable">넉넉하게</option>
</select>
<select aria-label="화면" id="theme">
<option value="system" selected>사이트 설정 따라가기 (기본)</option>
<option value="light">밝게</option>
<option value="dark">어둡게</option>
</select>
</div>
<div id="grid" style="height: 420px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const NAMES = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const DEPTS = ['개발팀', '디자인팀', '영업팀'];
const options = {
columns: [
{ id: 'name', title: '이름', width: 140 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3],
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
const DENSITY_WORDS = {
compact: '촘촘하게',
normal: '보통',
comfortable: '넉넉하게',
};
const DENSITY_WORDS_EN = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say = () => { };
const actions = {
// 칸 여백은 그리드 옵션이에요. 값을 바꿔 setOptions로 넘기면 바로 반영돼요.
density: (api, value) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// 어두운 화면은 CSS 속성이에요. 표(또는 그 위 요소)에 data-mxg-theme="dark"를 달면 그 안쪽만 바뀌어요.
theme: (_api, value) => {
const root = document.querySelector('.mxg');
if (!root)
return;
if (value === 'light' || value === 'dark')
root.setAttribute('data-mxg-theme', value);
else
root.removeAttribute('data-mxg-theme');
say({
ko: `화면: ${value === 'light' ? '밝게' : value === 'dark' ? '어둡게' : '사이트 설정 따라가기'}`,
en: `Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`,
});
},
};
function setup(api, log) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log({
ko: `칸 여백: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`,
en: `Cell padding: ${DENSITY_WORDS_EN[api.getOptions().density ?? 'normal']}`,
});
}
});
}
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('density').addEventListener('change', (event) => actions.density(api, event.target.value));
document.getElementById('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Grid, type GridDensity } from '@maxgrid/react';
import { useMemo, useState } from 'react';
import { DENSITY_WORDS, options as base, type Row } from './example';
type Theme = 'system' | 'light' | 'dark';
// 칸 여백(density)은 그리드 옵션이고, 어두운 화면은 감싸는 요소의 data-mxg-theme 속성이에요.
export function ExampleGrid() {
const [density, setDensity] = useState<GridDensity>('normal');
const [theme, setTheme] = useState<Theme>('system');
// 값이 바뀔 때만 새 options를 만들어요. 그러면 표가 바뀐 부분만 반영해요.
const options = useMemo(() => ({ ...base, density }), [density]);
return (
<>
<label>
칸 여백{' '}
<select value={density} onChange={(e) => setDensity(e.target.value as GridDensity)}>
{Object.entries(DENSITY_WORDS).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</label>{' '}
<label>
화면{' '}
<select value={theme} onChange={(e) => setTheme(e.target.value as Theme)}>
<option value="system">사이트 설정 따라가기</option>
<option value="light">밝게</option>
<option value="dark">어둡게</option>
</select>
</label>
<div
data-mxg-theme={theme === 'system' ? undefined : theme}
style={{ height: 260, marginTop: 8 }}
>
<Grid<Row> options={options} />
</div>
</>
);
}import type { GridApi, GridDensity, GridOptions } from '@maxgrid/react';
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: 140 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
export const DENSITY_WORDS: Record<GridDensity, string> = {
compact: '촘촘하게',
normal: '보통',
comfortable: '넉넉하게',
};
const DENSITY_WORDS_EN: Record<GridDensity, string> = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say: (message: LogText) => void = () => {};
export const actions = {
// 칸 여백은 그리드 옵션이에요. 값을 바꿔 setOptions로 넘기면 바로 반영돼요.
density: (api: GridApi<Row>, value?: string) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// 어두운 화면은 CSS 속성이에요. 표(또는 그 위 요소)에 data-mxg-theme="dark"를 달면 그 안쪽만 바뀌어요.
theme: (_api: GridApi<Row>, value?: string) => {
const root = document.querySelector('.mxg');
if (!root) return;
if (value === 'light' || value === 'dark') root.setAttribute('data-mxg-theme', value);
else root.removeAttribute('data-mxg-theme');
say({
ko: `화면: ${value === 'light' ? '밝게' : value === 'dark' ? '어둡게' : '사이트 설정 따라가기'}`,
en: `Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`,
});
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log({
ko: `칸 여백: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`,
en: `Cell padding: ${DENSITY_WORDS_EN[api.getOptions().density ?? 'normal']}`,
});
}
});
}버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { Grid, type GridDensity } from '@maxgrid/vue';
import { computed, ref } from 'vue';
import { DENSITY_WORDS, options as base } from './example';
type Theme = 'system' | 'light' | 'dark';
// 칸 여백(density)은 그리드 옵션이고, 어두운 화면은 감싸는 요소의 data-mxg-theme 속성이에요.
const density = ref<GridDensity>('normal');
const theme = ref<Theme>('system');
// density가 바뀔 때만 새 options가 만들어지고, 표는 바뀐 부분만 반영해요.
const options = computed(() => ({ ...base, density: density.value }));
</script>
<template>
<label>
칸 여백
<select v-model="density">
<option v-for="(label, value) in DENSITY_WORDS" :key="value" :value="value">
{{ label }}
</option>
</select>
</label>
<label>
화면
<select v-model="theme">
<option value="system">사이트 설정 따라가기</option>
<option value="light">밝게</option>
<option value="dark">어둡게</option>
</select>
</label>
<div
:data-mxg-theme="theme === 'system' ? undefined : theme"
style="height: 260px; margin-top: 8px"
>
<Grid :options="options" />
</div>
</template>import type { GridApi, GridDensity, GridOptions } from '@maxgrid/vue';
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: 140 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
export const DENSITY_WORDS: Record<GridDensity, string> = {
compact: '촘촘하게',
normal: '보통',
comfortable: '넉넉하게',
};
const DENSITY_WORDS_EN: Record<GridDensity, string> = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say: (message: LogText) => void = () => {};
export const actions = {
// 칸 여백은 그리드 옵션이에요. 값을 바꿔 setOptions로 넘기면 바로 반영돼요.
density: (api: GridApi<Row>, value?: string) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// 어두운 화면은 CSS 속성이에요. 표(또는 그 위 요소)에 data-mxg-theme="dark"를 달면 그 안쪽만 바뀌어요.
theme: (_api: GridApi<Row>, value?: string) => {
const root = document.querySelector('.mxg');
if (!root) return;
if (value === 'light' || value === 'dark') root.setAttribute('data-mxg-theme', value);
else root.removeAttribute('data-mxg-theme');
say({
ko: `화면: ${value === 'light' ? '밝게' : value === 'dark' ? '어둡게' : '사이트 설정 따라가기'}`,
en: `Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`,
});
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log({
ko: `칸 여백: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`,
en: `Cell padding: ${DENSITY_WORDS_EN[api.getOptions().density ?? 'normal']}`,
});
}
});
}버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
import { GridComponent, type GridDensity } from '@maxgrid/angular';
import { DENSITY_WORDS, options as base } from './example';
type Theme = 'system' | 'light' | 'dark';
// 칸 여백(density)은 그리드 옵션이고, 어두운 화면은 감싸는 요소의 data-mxg-theme 속성이에요.
// 'system'이면 속성을 달지 않고, 기기가 어두운 화면을 쓰는지는 matchMedia로 따로 알아봐요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<label>
칸 여백
<select (change)="density.set($any($event.target).value)">
@for (item of densities; track item[0]) {
<option [value]="item[0]" [selected]="item[0] === density()">{{ item[1] }}</option>
}
</select>
</label>
<label>
화면
<select (change)="theme.set($any($event.target).value)">
<option value="system">기기 설정 따라가기</option>
<option value="light">밝게</option>
<option value="dark">어둡게</option>
</select>
</label>
<div [attr.data-mxg-theme]="shownTheme()" style="height: 260px; margin-top: 8px">
<mx-grid [options]="options()" />
</div>
`,
})
export class ExampleGridComponent {
readonly densities = Object.entries(DENSITY_WORDS);
readonly density = signal<GridDensity>('normal');
readonly theme = signal<Theme>('system');
readonly options = computed(() => ({ ...base, density: this.density() }));
private readonly dark = signal(false);
readonly shownTheme = computed(() =>
this.theme() === 'system' ? (this.dark() ? 'dark' : 'light') : this.theme(),
);
constructor() {
const query = matchMedia('(prefers-color-scheme: dark)');
this.dark.set(query.matches);
const onChange = (event: MediaQueryListEvent): void => this.dark.set(event.matches);
query.addEventListener('change', onChange);
// 화면이 사라질 때 듣던 것을 꼭 멈춰요.
inject(DestroyRef).onDestroy(() => query.removeEventListener('change', onChange));
}
}import type { GridApi, GridDensity, GridOptions } from '@maxgrid/angular';
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: 140 },
{ id: 'dept', title: '부서', width: 120 },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 130, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
export const DENSITY_WORDS: Record<GridDensity, string> = {
compact: '촘촘하게',
normal: '보통',
comfortable: '넉넉하게',
};
const DENSITY_WORDS_EN: Record<GridDensity, string> = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say: (message: LogText) => void = () => {};
export const actions = {
// 칸 여백은 그리드 옵션이에요. 값을 바꿔 setOptions로 넘기면 바로 반영돼요.
density: (api: GridApi<Row>, value?: string) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// 어두운 화면은 CSS 속성이에요. 표(또는 그 위 요소)에 data-mxg-theme="dark"를 달면 그 안쪽만 바뀌어요.
theme: (_api: GridApi<Row>, value?: string) => {
const root = document.querySelector('.mxg');
if (!root) return;
if (value === 'light' || value === 'dark') root.setAttribute('data-mxg-theme', value);
else root.removeAttribute('data-mxg-theme');
say({
ko: `화면: ${value === 'light' ? '밝게' : value === 'dark' ? '어둡게' : '사이트 설정 따라가기'}`,
en: `Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`,
});
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log({
ko: `칸 여백: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`,
en: `Cell padding: ${DENSITY_WORDS_EN[api.getOptions().density ?? 'normal']}`,
});
}
});
}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="Cell padding" id="density">
<option value="compact">Compact</option>
<option value="normal" selected>Normal (default)</option>
<option value="comfortable">Comfortable</option>
</select>
<select aria-label="Screen" id="theme">
<option value="system" selected>Follow site (default)</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div id="grid" style="height: 420px"></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('density').addEventListener('change', (event) => actions.density(api, event.target.value));
document.getElementById('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const DEPTS = ['Dev', 'Design', 'Sales'];
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3],
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
export const DENSITY_WORDS = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say = () => { };
export const actions = {
// Cell padding is a grid option. Change the value and pass it to setOptions and it applies right away.
density: (api, value) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// Dark mode is a CSS attribute. Put data-mxg-theme="dark" on the grid (or an element above it) and only the inside changes.
theme: (_api, value) => {
const root = document.querySelector('.mxg');
if (!root)
return;
if (value === 'light' || value === 'dark')
root.setAttribute('data-mxg-theme', value);
else
root.removeAttribute('data-mxg-theme');
say(`Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`);
},
};
export function setup(api, log) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log(`Cell padding: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`);
}
});
}<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Switch light/dark and cell padding from app state</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Cell padding" id="density">
<option value="compact">Compact</option>
<option value="normal" selected>Normal (default)</option>
<option value="comfortable">Comfortable</option>
</select>
<select aria-label="Screen" id="theme">
<option value="system" selected>Follow site (default)</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div id="grid" style="height: 420px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const DEPTS = ['Dev', 'Design', 'Sales'];
const options = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3],
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
const DENSITY_WORDS = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say = () => { };
const actions = {
// Cell padding is a grid option. Change the value and pass it to setOptions and it applies right away.
density: (api, value) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// Dark mode is a CSS attribute. Put data-mxg-theme="dark" on the grid (or an element above it) and only the inside changes.
theme: (_api, value) => {
const root = document.querySelector('.mxg');
if (!root)
return;
if (value === 'light' || value === 'dark')
root.setAttribute('data-mxg-theme', value);
else
root.removeAttribute('data-mxg-theme');
say(`Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`);
},
};
function setup(api, log) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log(`Cell padding: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`);
}
});
}
options.ariaLabel = "Switch light/dark and cell padding from app state";
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('density').addEventListener('change', (event) => actions.density(api, event.target.value));
document.getElementById('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Grid, type GridDensity } from '@maxgrid/react';
import { useMemo, useState } from 'react';
import { DENSITY_WORDS, options as base, type Row } from './example';
type Theme = 'system' | 'light' | 'dark';
// 칸 여백(density)은 그리드 옵션이고, 어두운 화면은 감싸는 요소의 data-mxg-theme 속성이에요.
export function ExampleGrid() {
const [density, setDensity] = useState<GridDensity>('normal');
const [theme, setTheme] = useState<Theme>('system');
// 값이 바뀔 때만 새 options를 만들어요. 그러면 표가 바뀐 부분만 반영해요.
const options = useMemo(() => ({ ...base, density }), [density]);
return (
<>
<label>
칸 여백{' '}
<select value={density} onChange={(e) => setDensity(e.target.value as GridDensity)}>
{Object.entries(DENSITY_WORDS).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</label>{' '}
<label>
화면{' '}
<select value={theme} onChange={(e) => setTheme(e.target.value as Theme)}>
<option value="system">사이트 설정 따라가기</option>
<option value="light">밝게</option>
<option value="dark">어둡게</option>
</select>
</label>
<div
data-mxg-theme={theme === 'system' ? undefined : theme}
style={{ height: 260, marginTop: 8 }}
>
<Grid<Row> options={options} />
</div>
</>
);
}import type { GridApi, GridDensity, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const DEPTS = ['Dev', 'Design', 'Sales'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
export const DENSITY_WORDS: Record<GridDensity, string> = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say: (message: LogText) => void = () => {};
export const actions = {
// Cell padding is a grid option. Change the value and pass it to setOptions and it applies right away.
density: (api: GridApi<Row>, value?: string) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// Dark mode is a CSS attribute. Put data-mxg-theme="dark" on the grid (or an element above it) and only the inside changes.
theme: (_api: GridApi<Row>, value?: string) => {
const root = document.querySelector('.mxg');
if (!root) return;
if (value === 'light' || value === 'dark') root.setAttribute('data-mxg-theme', value);
else root.removeAttribute('data-mxg-theme');
say(
`Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`,
);
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log(`Cell padding: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`);
}
});
}When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { Grid, type GridDensity } from '@maxgrid/vue';
import { computed, ref } from 'vue';
import { DENSITY_WORDS, options as base } from './example';
type Theme = 'system' | 'light' | 'dark';
// 칸 여백(density)은 그리드 옵션이고, 어두운 화면은 감싸는 요소의 data-mxg-theme 속성이에요.
const density = ref<GridDensity>('normal');
const theme = ref<Theme>('system');
// density가 바뀔 때만 새 options가 만들어지고, 표는 바뀐 부분만 반영해요.
const options = computed(() => ({ ...base, density: density.value }));
</script>
<template>
<label>
칸 여백
<select v-model="density">
<option v-for="(label, value) in DENSITY_WORDS" :key="value" :value="value">
{{ label }}
</option>
</select>
</label>
<label>
화면
<select v-model="theme">
<option value="system">사이트 설정 따라가기</option>
<option value="light">밝게</option>
<option value="dark">어둡게</option>
</select>
</label>
<div
:data-mxg-theme="theme === 'system' ? undefined : theme"
style="height: 260px; margin-top: 8px"
>
<Grid :options="options" />
</div>
</template>import type { GridApi, GridDensity, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const DEPTS = ['Dev', 'Design', 'Sales'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
export const DENSITY_WORDS: Record<GridDensity, string> = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say: (message: LogText) => void = () => {};
export const actions = {
// Cell padding is a grid option. Change the value and pass it to setOptions and it applies right away.
density: (api: GridApi<Row>, value?: string) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// Dark mode is a CSS attribute. Put data-mxg-theme="dark" on the grid (or an element above it) and only the inside changes.
theme: (_api: GridApi<Row>, value?: string) => {
const root = document.querySelector('.mxg');
if (!root) return;
if (value === 'light' || value === 'dark') root.setAttribute('data-mxg-theme', value);
else root.removeAttribute('data-mxg-theme');
say(
`Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`,
);
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log(`Cell padding: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`);
}
});
}When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
import { GridComponent, type GridDensity } from '@maxgrid/angular';
import { DENSITY_WORDS, options as base } from './example';
type Theme = 'system' | 'light' | 'dark';
// 칸 여백(density)은 그리드 옵션이고, 어두운 화면은 감싸는 요소의 data-mxg-theme 속성이에요.
// 'system'이면 속성을 달지 않고, 기기가 어두운 화면을 쓰는지는 matchMedia로 따로 알아봐요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<label>
칸 여백
<select (change)="density.set($any($event.target).value)">
@for (item of densities; track item[0]) {
<option [value]="item[0]" [selected]="item[0] === density()">{{ item[1] }}</option>
}
</select>
</label>
<label>
화면
<select (change)="theme.set($any($event.target).value)">
<option value="system">기기 설정 따라가기</option>
<option value="light">밝게</option>
<option value="dark">어둡게</option>
</select>
</label>
<div [attr.data-mxg-theme]="shownTheme()" style="height: 260px; margin-top: 8px">
<mx-grid [options]="options()" />
</div>
`,
})
export class ExampleGridComponent {
readonly densities = Object.entries(DENSITY_WORDS);
readonly density = signal<GridDensity>('normal');
readonly theme = signal<Theme>('system');
readonly options = computed(() => ({ ...base, density: this.density() }));
private readonly dark = signal(false);
readonly shownTheme = computed(() =>
this.theme() === 'system' ? (this.dark() ? 'dark' : 'light') : this.theme(),
);
constructor() {
const query = matchMedia('(prefers-color-scheme: dark)');
this.dark.set(query.matches);
const onChange = (event: MediaQueryListEvent): void => this.dark.set(event.matches);
query.addEventListener('change', onChange);
// 화면이 사라질 때 듣던 것을 꼭 멈춰요.
inject(DestroyRef).onDestroy(() => query.removeEventListener('change', onChange));
}
}import type { GridApi, GridDensity, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
const NAMES = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const DEPTS = ['Dev', 'Design', 'Sales'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 120 },
{ id: 'salary', title: 'Monthly pay ($100)', kind: 'number', width: 160, align: 'end' },
],
rows: NAMES.map((name, i) => ({
id: i + 1,
name,
dept: DEPTS[i % 3] as string,
salary: 320 + i * 41,
})),
rowKey: 'id',
density: 'normal',
};
export const DENSITY_WORDS: Record<GridDensity, string> = {
compact: 'compact',
normal: 'normal',
comfortable: 'comfortable',
};
let say: (message: LogText) => void = () => {};
export const actions = {
// Cell padding is a grid option. Change the value and pass it to setOptions and it applies right away.
density: (api: GridApi<Row>, value?: string) => {
if (value === 'compact' || value === 'normal' || value === 'comfortable') {
api.setOptions({ density: value });
}
},
// Dark mode is a CSS attribute. Put data-mxg-theme="dark" on the grid (or an element above it) and only the inside changes.
theme: (_api: GridApi<Row>, value?: string) => {
const root = document.querySelector('.mxg');
if (!root) return;
if (value === 'light' || value === 'dark') root.setAttribute('data-mxg-theme', value);
else root.removeAttribute('data-mxg-theme');
say(
`Appearance: ${value === 'light' ? 'light' : value === 'dark' ? 'dark' : 'follow the site setting'}`,
);
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('optionsChanged', ({ changed }) => {
if (changed.includes('density')) {
log(`Cell padding: ${DENSITY_WORDS[api.getOptions().density ?? 'normal']}`);
}
});
}