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

체크 표시와 켜고 끄는 스위치Check marks and on/off switches

참/거짓 값을 내장 체크 표시(보기만)와 직접 만든 스위치(눌러서 바꾸기)로 보여 줘요. 스위치를 누르면 값이 바뀌어요.Show true/false values as a built-in check mark (view only) and a custom switch (click to change). Clicking the switch changes the value.

활용Intermediate
직접 써 보기Live preview체크 표시와 켜고 끄는 스위치Check marks and on/off switches

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

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

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="allOn">모두 켜기</button>
    <button type="button" id="allOff">모두 끄기</button>
  </div>
  <div id="grid" style="height: 260px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('allOn').addEventListener('click', () => actions.allOn(api));
document.getElementById('allOff').addEventListener('click', () => actions.allOff(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 줄을 44px로 키워서 누를 곳을 넉넉하게 해요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
  const ch = word.trim().slice(-1);
  const digit = '0123456789'.indexOf(ch);
  if (digit >= 0)
    return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0;
  const code = ch.charCodeAt(0) - 0xac00;
  return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
// 스위치는 span 두 개로 그려요. 키보드로도 쓸 수 있게 Tab으로 이동하고 Space·Enter로 켜고 꺼요(setup에서 한 번만 받아요).
// 칸 어디를 눌러도 바뀌어요. 색은 테마 색에 섞어서 밝은·어두운 화면 모두에서 보여요.
const toggle = () => {
  let track;
  let pill;
  let knob;
  // 폰에서는 누르는 영역(track)을 56×40으로 키우고, 눈에 보이는 알약(pill)은 그 안에서 52×30으로 그려요.
  const pw = coarse() ? 52 : 38;
  const ph = coarse() ? 30 : 22;
  const kn = coarse() ? 24 : 16;
  return {
    mount(el, ctx) {
      track = document.createElement('span');
      track.setAttribute('role', 'switch');
      track.tabIndex = 0;
      track.dataset.switch = 'on';
      track.style.cssText = `position: relative; display: inline-block; width: ${coarse() ? 56 : 38}px; height: ${coarse() ? 40 : 22}px; cursor: pointer;`;
      pill = document.createElement('span');
      pill.style.cssText = `position: absolute; left: 0; top: ${coarse() ? 5 : 0}px; width: ${pw}px; height: ${ph}px; border-radius: ${ph / 2}px; transition: background 0.15s;`;
      knob = document.createElement('span');
      knob.style.cssText = `position: absolute; top: 3px; width: ${kn}px; height: ${kn}px; border-radius: 50%; background: #fff; transition: left 0.15s;`;
      pill.append(knob);
      track.append(pill);
      centered(el).append(track);
      this.update(ctx);
    },
    update(ctx) {
      const on = ctx.value === true;
      track.dataset.key = String(ctx.rowKey);
      track.setAttribute('aria-checked', String(on));
      track.setAttribute('aria-label', L(`${ctx.row.feature} 사용`, `Use ${ctx.row.feature}`));
      pill.style.background = on
        ? '#16a34a'
        : 'color-mix(in srgb, var(--mxg-fg) 35%, var(--mxg-bg))';
      knob.style.left = on ? `${pw - kn - 3}px` : '3px';
    },
    destroy() { },
  };
};
export const options = {
  columns: [
    { id: 'feature', title: '기능', width: 170 },
    // 내장 'checkbox' 렌더러는 참/거짓 값을 읽기 전용 체크 표시로 보여 줘요.
    {
      id: 'beta',
      title: '시험판',
      kind: 'boolean',
      width: 90,
      align: 'center',
      cellRenderer: 'checkbox',
    },
    {
      id: 'enabled',
      title: '사용(눌러서 바꾸기)',
      kind: 'boolean',
      width: 170,
      align: 'center',
      cellRenderer: toggle,
    },
  ],
  rows: [
    { id: 1, feature: '어두운 화면', beta: false, enabled: true },
    { id: 2, feature: '오프라인 동기화', beta: true, enabled: false },
    { id: 3, feature: 'AI 요약', beta: true, enabled: true },
    { id: 4, feature: 'CSV 가져오기', beta: false, enabled: true },
  ],
  rowKey: 'id',
  saveMode: 'none', // 저장 흐름이 아니라서 "저장 안 한 변경" 색을 쓰지 않아요
  ...(coarse() ? { rowHeight: 44 } : {}),
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log({
    ko: '"시험판"은 보기만 하는 체크 표시고, "사용"은 칸을 누르거나, 칸을 고른 뒤 Enter로 들어가 Space로 켜고 꺼요. Esc로 나와요.',
    en: '"시험판" (beta) is a view-only check mark. "사용" (enabled) toggles when you click it, or select it, press Enter to go in and Space to toggle. Esc leaves.',
  });
  const flip = (key) => {
    const row = api.getRows().find((r) => String(r.id) === String(key));
    if (!row)
      return;
    api.updateRows([{ ...row, enabled: !row.enabled }]);
    log({
      ko: `${row.feature}${eulReul(row.feature)} ${row.enabled ? '껐어요' : '켰어요'}.`,
      en: `${row.feature} turned ${row.enabled ? 'off' : 'on'}.`,
    });
  };
  const offClick = api.on('cellClicked', (e) => {
    if (e.columnId === 'enabled')
      flip(e.rowKey);
  });
  const onKey = (event) => {
    const target = event.target;
    if (!(target instanceof HTMLElement) || !target.dataset.switch)
      return;
    if (event.key !== ' ' && event.key !== 'Enter')
      return;
    event.preventDefault();
    flip(target.dataset.key);
  };
  document.addEventListener('keydown', onKey);
  return () => {
    offClick();
    document.removeEventListener('keydown', onKey);
  };
}
export const actions = {
  allOn: (api) => {
    api.updateRows(api.getRows().map((row) => ({ ...row, enabled: true })));
    say({ ko: '모든 기능을 켰어요.', en: 'Turned every feature on.' });
  },
  allOff: (api) => {
    api.updateRows(api.getRows().map((row) => ({ ...row, enabled: false })));
    say({ ko: '모든 기능을 껐어요.', en: 'Turned every feature off.' });
  },
};

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

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="allOn">All on</button>
    <button type="button" id="allOff">All off</button>
  </div>
  <div id="grid" style="height: 260px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('allOn').addEventListener('click', () => actions.allOn(api));
document.getElementById('allOff').addEventListener('click', () => actions.allOff(api));
example.js
// Tells whether this is a touch screen (phone). On such screens rows grow to 44px to give a roomy tap target.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
// The switch is drawn with two spans. For keyboard use, Tab moves to it and Space or Enter toggles it (handled once in setup).
// A click anywhere in the cell toggles it. The colors mix with the theme colors so it shows on light and dark screens.
const toggle = () => {
  let track;
  let pill;
  let knob;
  // On a phone the tap area (track) grows to 56x40, and the visible pill is drawn at 52x30 inside it.
  const pw = coarse() ? 52 : 38;
  const ph = coarse() ? 30 : 22;
  const kn = coarse() ? 24 : 16;
  return {
    mount(el, ctx) {
      track = document.createElement('span');
      track.setAttribute('role', 'switch');
      track.tabIndex = 0;
      track.dataset.switch = 'on';
      track.style.cssText = `position: relative; display: inline-block; width: ${coarse() ? 56 : 38}px; height: ${coarse() ? 40 : 22}px; cursor: pointer;`;
      pill = document.createElement('span');
      pill.style.cssText = `position: absolute; left: 0; top: ${coarse() ? 5 : 0}px; width: ${pw}px; height: ${ph}px; border-radius: ${ph / 2}px; transition: background 0.15s;`;
      knob = document.createElement('span');
      knob.style.cssText = `position: absolute; top: 3px; width: ${kn}px; height: ${kn}px; border-radius: 50%; background: #fff; transition: left 0.15s;`;
      pill.append(knob);
      track.append(pill);
      centered(el).append(track);
      this.update(ctx);
    },
    update(ctx) {
      const on = ctx.value === true;
      track.dataset.key = String(ctx.rowKey);
      track.setAttribute('aria-checked', String(on));
      track.setAttribute('aria-label', `Use ${ctx.row.feature}`);
      pill.style.background = on
        ? '#16a34a'
        : 'color-mix(in srgb, var(--mxg-fg) 35%, var(--mxg-bg))';
      knob.style.left = on ? `${pw - kn - 3}px` : '3px';
    },
    destroy() { },
  };
};
export const options = {
  columns: [
    { id: 'feature', title: 'Feature', width: 170 },
    // The built-in 'checkbox' renderer shows true/false values as a read-only check mark.
    {
      id: 'beta',
      title: 'Beta',
      kind: 'boolean',
      width: 90,
      align: 'center',
      cellRenderer: 'checkbox',
    },
    {
      id: 'enabled',
      title: 'Enabled (click to toggle)',
      kind: 'boolean',
      width: 200,
      align: 'center',
      cellRenderer: toggle,
    },
  ],
  rows: [
    { id: 1, feature: 'Dark mode', beta: false, enabled: true },
    { id: 2, feature: 'Offline sync', beta: true, enabled: false },
    { id: 3, feature: 'AI summary', beta: true, enabled: true },
    { id: 4, feature: 'CSV import', beta: false, enabled: true },
  ],
  rowKey: 'id',
  saveMode: 'none', // not a save flow, so no "unsaved change" color
  ...(coarse() ? { rowHeight: 44 } : {}),
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log('"Beta" is a view-only check mark. "Enabled" toggles when you click it, or select it, press Enter to go in and Space to toggle. Esc leaves.');
  const flip = (key) => {
    const row = api.getRows().find((r) => String(r.id) === String(key));
    if (!row)
      return;
    api.updateRows([{ ...row, enabled: !row.enabled }]);
    log(`${row.feature} turned ${row.enabled ? 'off' : 'on'}.`);
  };
  const offClick = api.on('cellClicked', (e) => {
    if (e.columnId === 'enabled')
      flip(e.rowKey);
  });
  const onKey = (event) => {
    const target = event.target;
    if (!(target instanceof HTMLElement) || !target.dataset.switch)
      return;
    if (event.key !== ' ' && event.key !== 'Enter')
      return;
    event.preventDefault();
    flip(target.dataset.key);
  };
  document.addEventListener('keydown', onKey);
  return () => {
    offClick();
    document.removeEventListener('keydown', onKey);
  };
}
export const actions = {
  allOn: (api) => {
    api.updateRows(api.getRows().map((row) => ({ ...row, enabled: true })));
    say('Turned every feature on.');
  },
  allOff: (api) => {
    api.updateRows(api.getRows().map((row) => ({ ...row, enabled: false })));
    say('Turned every feature off.');
  },
};