체크 표시와 켜고 끄는 스위치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.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));// 예제 틀이 알려 주는 페이지 언어(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.' });
},
};<!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">
<button type="button" id="allOn">모두 켜기</button>
<button type="button" id="allOff">모두 끄기</button>
</div>
<div id="grid" style="height: 260px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(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() { },
};
};
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 = () => { };
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);
};
}
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.' });
},
};
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('allOn').addEventListener('click', () => actions.allOn(api));
document.getElementById('allOff').addEventListener('click', () => actions.allOff(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.allOn(api)}
>모두 켜기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.allOff(api)}
>모두 끄기</button>
</div>
<Grid style={{ height: 260 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
feature: string;
beta: boolean;
enabled: boolean;
}
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 줄을 44px로 키워서 누를 곳을 넉넉하게 해요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
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: string): string => (batchim(word) ? '을' : '를');
// 스위치는 span 두 개로 그려요. 키보드로도 쓸 수 있게 Tab으로 이동하고 Space·Enter로 켜고 꺼요(setup에서 한 번만 받아요).
// 칸 어디를 눌러도 바뀌어요. 색은 테마 색에 섞어서 밝은·어두운 화면 모두에서 보여요.
const toggle = (): CellRendererAdapter<Row> => {
let track: HTMLSpanElement;
let pill: HTMLSpanElement;
let knob: HTMLSpanElement;
// 폰에서는 누르는 영역(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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: unknown): void => {
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: KeyboardEvent): void => {
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: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: true })));
say({ ko: '모든 기능을 켰어요.', en: 'Turned every feature on.' });
},
allOff: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: false })));
say({ ko: '모든 기능을 껐어요.', en: 'Turned every feature off.' });
},
};버튼을 누르면 이 예제의 코드가 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">
<button type="button" :disabled="!api" @click="api && actions.allOn(api)">모두 켜기</button>
<button type="button" :disabled="!api" @click="api && actions.allOff(api)">모두 끄기</button>
</div>
<Grid style="height: 260px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
feature: string;
beta: boolean;
enabled: boolean;
}
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 줄을 44px로 키워서 누를 곳을 넉넉하게 해요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
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: string): string => (batchim(word) ? '을' : '를');
// 스위치는 span 두 개로 그려요. 키보드로도 쓸 수 있게 Tab으로 이동하고 Space·Enter로 켜고 꺼요(setup에서 한 번만 받아요).
// 칸 어디를 눌러도 바뀌어요. 색은 테마 색에 섞어서 밝은·어두운 화면 모두에서 보여요.
const toggle = (): CellRendererAdapter<Row> => {
let track: HTMLSpanElement;
let pill: HTMLSpanElement;
let knob: HTMLSpanElement;
// 폰에서는 누르는 영역(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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: unknown): void => {
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: KeyboardEvent): void => {
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: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: true })));
say({ ko: '모든 기능을 켰어요.', en: 'Turned every feature on.' });
},
allOff: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: false })));
say({ ko: '모든 기능을 껐어요.', en: 'Turned every feature off.' });
},
};버튼을 누르면 이 예제의 코드가 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">
<button
type="button"
[disabled]="!api"
(click)="api && actions.allOn(api)"
>모두 켜기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.allOff(api)"
>모두 끄기</button>
</div>
<mx-grid style="height: 260px" [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 { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
feature: string;
beta: boolean;
enabled: boolean;
}
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 줄을 44px로 키워서 누를 곳을 넉넉하게 해요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
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: string): string => (batchim(word) ? '을' : '를');
// 스위치는 span 두 개로 그려요. 키보드로도 쓸 수 있게 Tab으로 이동하고 Space·Enter로 켜고 꺼요(setup에서 한 번만 받아요).
// 칸 어디를 눌러도 바뀌어요. 색은 테마 색에 섞어서 밝은·어두운 화면 모두에서 보여요.
const toggle = (): CellRendererAdapter<Row> => {
let track: HTMLSpanElement;
let pill: HTMLSpanElement;
let knob: HTMLSpanElement;
// 폰에서는 누르는 영역(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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: unknown): void => {
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: KeyboardEvent): void => {
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: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: true })));
say({ ko: '모든 기능을 켰어요.', en: 'Turned every feature on.' });
},
allOff: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: false })));
say({ ko: '모든 기능을 껐어요.', en: 'Turned every feature off.' });
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<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>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));// 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.');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check marks and on/off switches</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 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() { },
};
};
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 = () => { };
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);
};
}
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.');
},
};
options.ariaLabel = "Check marks and on/off switches";
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('allOn').addEventListener('click', () => actions.allOn(api));
document.getElementById('allOff').addEventListener('click', () => actions.allOff(api));
</script>
</body>
</html>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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.allOn(api)}
>All on</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.allOff(api)}
>All off</button>
</div>
<Grid style={{ height: 260 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
feature: string;
beta: boolean;
enabled: boolean;
}
// Tells whether this is a touch screen (phone). On such screens rows grow to 44px to give a roomy tap target.
const coarse = (): boolean => 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: HTMLElement): HTMLElement => {
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 = (): CellRendererAdapter<Row> => {
let track: HTMLSpanElement;
let pill: HTMLSpanElement;
let knob: HTMLSpanElement;
// 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: unknown): void => {
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: KeyboardEvent): void => {
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: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: true })));
say('Turned every feature on.');
},
allOff: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: false })));
say('Turned every feature off.');
},
};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">
<button type="button" :disabled="!api" @click="api && actions.allOn(api)">All on</button>
<button type="button" :disabled="!api" @click="api && actions.allOff(api)">All off</button>
</div>
<Grid style="height: 260px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
feature: string;
beta: boolean;
enabled: boolean;
}
// Tells whether this is a touch screen (phone). On such screens rows grow to 44px to give a roomy tap target.
const coarse = (): boolean => 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: HTMLElement): HTMLElement => {
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 = (): CellRendererAdapter<Row> => {
let track: HTMLSpanElement;
let pill: HTMLSpanElement;
let knob: HTMLSpanElement;
// 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: unknown): void => {
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: KeyboardEvent): void => {
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: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: true })));
say('Turned every feature on.');
},
allOff: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: false })));
say('Turned every feature off.');
},
};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">
<button
type="button"
[disabled]="!api"
(click)="api && actions.allOn(api)"
>All on</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.allOff(api)"
>All off</button>
</div>
<mx-grid style="height: 260px" [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 { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
feature: string;
beta: boolean;
enabled: boolean;
}
// Tells whether this is a touch screen (phone). On such screens rows grow to 44px to give a roomy tap target.
const coarse = (): boolean => 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: HTMLElement): HTMLElement => {
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 = (): CellRendererAdapter<Row> => {
let track: HTMLSpanElement;
let pill: HTMLSpanElement;
let knob: HTMLSpanElement;
// 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: unknown): void => {
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: KeyboardEvent): void => {
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: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: true })));
say('Turned every feature on.');
},
allOff: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, enabled: false })));
say('Turned every feature off.');
},
};