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

밝은·어두운 화면과 칸 여백을 앱 상태로 바꾸기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.

활용Intermediate
직접 써 보기Live preview밝은·어두운 화면과 칸 여백을 앱 상태로 바꾸기Switch light/dark and cell padding from app state

실행 화면은 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.

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

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

index.html
<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>
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('density').addEventListener('change', (event) => actions.density(api, event.target.value));
document.getElementById('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));
example.js
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']}`,
      });
    }
  });
}

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

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

index.html
<div id="app">
  <div class="toolbar">
    <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>
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('density').addEventListener('change', (event) => actions.density(api, event.target.value));
document.getElementById('theme').addEventListener('change', (event) => actions.theme(api, event.target.value));
example.js
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']}`);
    }
  });
}