수량 편집기: − 숫자 + 버튼으로 바꾸기Quantity editor with − and + buttons
숫자 칸을 편집할 때 −, + 버튼과 위·아래 화살표 키로 한 칸씩 바꿀 수 있는 편집기를 직접 만들어요. 범위(0~99)를 벗어나면 확정되지 않아요.Build an editor for number cells with − and + buttons and Up/Down arrow keys. A value outside 0–99 is not committed.
코드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="edit">1번 줄 수량 편집</button>
</div>
<div id="grid" style="height: 240px"></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('edit').addEventListener('click', () => actions.edit(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 바로 아래에 눈에 보이는 안내 줄도 둬요.
function makeReasonLine() {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게). 줄 자체는 남겨 두어 상태 알림은 그대로 읽힌다.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
// 폰처럼 손가락으로 쓰는 화면에서는 입력 글자를 16px로 해서, 입력칸을 누를 때 화면이 저절로 확대되지 않게 해요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 숫자 증감 편집기: [−] 값 [+]. 위·아래 화살표 키로도 바꿔요. Enter(확정)와 Esc(취소)는 그리드가 맡고, 편집기는 값만 다뤄요.
const stepper = () => {
let wrap;
let input;
const step = (delta) => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label, delta) => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // 포커스는 입력칸에 그대로 둬요
b.setAttribute('aria-label', delta > 0 ? L('하나 늘리기', 'Increase by one') : L('하나 줄이기', 'Decrease by one'));
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // 입력칸의 포커스를 잃지 않게 해요
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// −/+ 단추가 있으니 브라우저 기본 증감 화살표는 숨겨요(이 편집기 안에서만).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', L(`${ctx.row.item} 수량`, `${ctx.row.item} quantity`));
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
export const options = {
columns: [
{ id: 'item', title: '품목', width: 180 },
{
id: 'qty',
title: '수량(더블클릭)',
kind: 'number',
width: 190,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n))
return L('수량을 적어 주세요.', 'Enter a quantity.');
return n < 0 || n > 99
? L('수량은 0에서 99 사이로 적어 주세요.', 'Enter a quantity between 0 and 99.')
: null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C 케이블', qty: 12 },
{ id: 2, item: '무선 마우스', qty: 4 },
{ id: 3, item: '노트북 받침대', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
export function setup(api, log) {
const reason = makeReasonLine();
log({
ko: '수량 칸을 더블클릭하고 − + 버튼이나 위·아래 화살표 키로 바꿔 보세요.',
en: 'Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log({
ko: `${e.rowKey}번 줄 수량: ${String(e.oldValue)} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(L(`✗ ${e.rowKey}번 줄 수량: ${e.message}`, `✗ Row ${e.rowKey} quantity: ${e.message}`));
log({
ko: `✗ ${e.rowKey}번 줄 수량: ${e.message}`,
en: `✗ Row ${e.rowKey} quantity: ${e.message}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api) => api.startEdit(1, 'qty'),
};<!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="edit">1번 줄 수량 편집</button>
</div>
<div id="grid" style="height: 240px"></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;
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 바로 아래에 눈에 보이는 안내 줄도 둬요.
function makeReasonLine() {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게). 줄 자체는 남겨 두어 상태 알림은 그대로 읽힌다.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
// 폰처럼 손가락으로 쓰는 화면에서는 입력 글자를 16px로 해서, 입력칸을 누를 때 화면이 저절로 확대되지 않게 해요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 숫자 증감 편집기: [−] 값 [+]. 위·아래 화살표 키로도 바꿔요. Enter(확정)와 Esc(취소)는 그리드가 맡고, 편집기는 값만 다뤄요.
const stepper = () => {
let wrap;
let input;
const step = (delta) => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label, delta) => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // 포커스는 입력칸에 그대로 둬요
b.setAttribute('aria-label', delta > 0 ? L('하나 늘리기', 'Increase by one') : L('하나 줄이기', 'Decrease by one'));
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // 입력칸의 포커스를 잃지 않게 해요
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// −/+ 단추가 있으니 브라우저 기본 증감 화살표는 숨겨요(이 편집기 안에서만).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', L(`${ctx.row.item} 수량`, `${ctx.row.item} quantity`));
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
const options = {
columns: [
{ id: 'item', title: '품목', width: 180 },
{
id: 'qty',
title: '수량(더블클릭)',
kind: 'number',
width: 190,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n))
return L('수량을 적어 주세요.', 'Enter a quantity.');
return n < 0 || n > 99
? L('수량은 0에서 99 사이로 적어 주세요.', 'Enter a quantity between 0 and 99.')
: null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C 케이블', qty: 12 },
{ id: 2, item: '무선 마우스', qty: 4 },
{ id: 3, item: '노트북 받침대', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
function setup(api, log) {
const reason = makeReasonLine();
log({
ko: '수량 칸을 더블클릭하고 − + 버튼이나 위·아래 화살표 키로 바꿔 보세요.',
en: 'Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log({
ko: `${e.rowKey}번 줄 수량: ${String(e.oldValue)} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(L(`✗ ${e.rowKey}번 줄 수량: ${e.message}`, `✗ Row ${e.rowKey} quantity: ${e.message}`));
log({
ko: `✗ ${e.rowKey}번 줄 수량: ${e.message}`,
en: `✗ Row ${e.rowKey} quantity: ${e.message}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
const actions = {
edit: (api) => api.startEdit(1, 'qty'),
};
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('edit').addEventListener('click', () => actions.edit(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.edit(api)}
>1번 줄 수량 편집</button>
</div>
<Grid style={{ height: 240 }} ref={gridRef} options={options} />
</>
);
}import type { CellEditorAdapter, 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 };
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 바로 아래에 눈에 보이는 안내 줄도 둬요.
function makeReasonLine(): { show: (text: string) => void; remove: () => void } {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게). 줄 자체는 남겨 두어 상태 알림은 그대로 읽힌다.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
export interface Row {
id: number;
item: string;
qty: number;
}
// 폰처럼 손가락으로 쓰는 화면에서는 입력 글자를 16px로 해서, 입력칸을 누를 때 화면이 저절로 확대되지 않게 해요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 숫자 증감 편집기: [−] 값 [+]. 위·아래 화살표 키로도 바꿔요. Enter(확정)와 Esc(취소)는 그리드가 맡고, 편집기는 값만 다뤄요.
const stepper = (): CellEditorAdapter<Row> => {
let wrap: HTMLDivElement;
let input: HTMLInputElement;
const step = (delta: number): void => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label: string, delta: number): HTMLButtonElement => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // 포커스는 입력칸에 그대로 둬요
b.setAttribute(
'aria-label',
delta > 0 ? L('하나 늘리기', 'Increase by one') : L('하나 줄이기', 'Decrease by one'),
);
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // 입력칸의 포커스를 잃지 않게 해요
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// −/+ 단추가 있으니 브라우저 기본 증감 화살표는 숨겨요(이 편집기 안에서만).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', L(`${ctx.row.item} 수량`, `${ctx.row.item} quantity`));
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: '품목', width: 180 },
{
id: 'qty',
title: '수량(더블클릭)',
kind: 'number',
width: 190,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n))
return L('수량을 적어 주세요.', 'Enter a quantity.');
return n < 0 || n > 99
? L('수량은 0에서 99 사이로 적어 주세요.', 'Enter a quantity between 0 and 99.')
: null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C 케이블', qty: 12 },
{ id: 2, item: '무선 마우스', qty: 4 },
{ id: 3, item: '노트북 받침대', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log({
ko: '수량 칸을 더블클릭하고 − + 버튼이나 위·아래 화살표 키로 바꿔 보세요.',
en: 'Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log({
ko: `${e.rowKey}번 줄 수량: ${String(e.oldValue)} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(
L(`✗ ${e.rowKey}번 줄 수량: ${e.message}`, `✗ Row ${e.rowKey} quantity: ${e.message}`),
);
log({
ko: `✗ ${e.rowKey}번 줄 수량: ${e.message}`,
en: `✗ Row ${e.rowKey} quantity: ${e.message}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'qty'),
};버튼을 누르면 이 예제의 코드가 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.edit(api)">1번 줄 수량 편집</button>
</div>
<Grid style="height: 240px" :options="options" @ready="onReady" />
</template>import type { CellEditorAdapter, 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 };
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 바로 아래에 눈에 보이는 안내 줄도 둬요.
function makeReasonLine(): { show: (text: string) => void; remove: () => void } {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게). 줄 자체는 남겨 두어 상태 알림은 그대로 읽힌다.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
export interface Row {
id: number;
item: string;
qty: number;
}
// 폰처럼 손가락으로 쓰는 화면에서는 입력 글자를 16px로 해서, 입력칸을 누를 때 화면이 저절로 확대되지 않게 해요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 숫자 증감 편집기: [−] 값 [+]. 위·아래 화살표 키로도 바꿔요. Enter(확정)와 Esc(취소)는 그리드가 맡고, 편집기는 값만 다뤄요.
const stepper = (): CellEditorAdapter<Row> => {
let wrap: HTMLDivElement;
let input: HTMLInputElement;
const step = (delta: number): void => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label: string, delta: number): HTMLButtonElement => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // 포커스는 입력칸에 그대로 둬요
b.setAttribute(
'aria-label',
delta > 0 ? L('하나 늘리기', 'Increase by one') : L('하나 줄이기', 'Decrease by one'),
);
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // 입력칸의 포커스를 잃지 않게 해요
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// −/+ 단추가 있으니 브라우저 기본 증감 화살표는 숨겨요(이 편집기 안에서만).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', L(`${ctx.row.item} 수량`, `${ctx.row.item} quantity`));
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: '품목', width: 180 },
{
id: 'qty',
title: '수량(더블클릭)',
kind: 'number',
width: 190,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n))
return L('수량을 적어 주세요.', 'Enter a quantity.');
return n < 0 || n > 99
? L('수량은 0에서 99 사이로 적어 주세요.', 'Enter a quantity between 0 and 99.')
: null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C 케이블', qty: 12 },
{ id: 2, item: '무선 마우스', qty: 4 },
{ id: 3, item: '노트북 받침대', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log({
ko: '수량 칸을 더블클릭하고 − + 버튼이나 위·아래 화살표 키로 바꿔 보세요.',
en: 'Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log({
ko: `${e.rowKey}번 줄 수량: ${String(e.oldValue)} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(
L(`✗ ${e.rowKey}번 줄 수량: ${e.message}`, `✗ Row ${e.rowKey} quantity: ${e.message}`),
);
log({
ko: `✗ ${e.rowKey}번 줄 수량: ${e.message}`,
en: `✗ Row ${e.rowKey} quantity: ${e.message}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'qty'),
};버튼을 누르면 이 예제의 코드가 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.edit(api)"
>1번 줄 수량 편집</button>
</div>
<mx-grid style="height: 240px" [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 { CellEditorAdapter, 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 };
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 바로 아래에 눈에 보이는 안내 줄도 둬요.
function makeReasonLine(): { show: (text: string) => void; remove: () => void } {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게). 줄 자체는 남겨 두어 상태 알림은 그대로 읽힌다.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
export interface Row {
id: number;
item: string;
qty: number;
}
// 폰처럼 손가락으로 쓰는 화면에서는 입력 글자를 16px로 해서, 입력칸을 누를 때 화면이 저절로 확대되지 않게 해요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 숫자 증감 편집기: [−] 값 [+]. 위·아래 화살표 키로도 바꿔요. Enter(확정)와 Esc(취소)는 그리드가 맡고, 편집기는 값만 다뤄요.
const stepper = (): CellEditorAdapter<Row> => {
let wrap: HTMLDivElement;
let input: HTMLInputElement;
const step = (delta: number): void => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label: string, delta: number): HTMLButtonElement => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // 포커스는 입력칸에 그대로 둬요
b.setAttribute(
'aria-label',
delta > 0 ? L('하나 늘리기', 'Increase by one') : L('하나 줄이기', 'Decrease by one'),
);
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // 입력칸의 포커스를 잃지 않게 해요
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// −/+ 단추가 있으니 브라우저 기본 증감 화살표는 숨겨요(이 편집기 안에서만).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', L(`${ctx.row.item} 수량`, `${ctx.row.item} quantity`));
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: '품목', width: 180 },
{
id: 'qty',
title: '수량(더블클릭)',
kind: 'number',
width: 190,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n))
return L('수량을 적어 주세요.', 'Enter a quantity.');
return n < 0 || n > 99
? L('수량은 0에서 99 사이로 적어 주세요.', 'Enter a quantity between 0 and 99.')
: null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C 케이블', qty: 12 },
{ id: 2, item: '무선 마우스', qty: 4 },
{ id: 3, item: '노트북 받침대', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log({
ko: '수량 칸을 더블클릭하고 − + 버튼이나 위·아래 화살표 키로 바꿔 보세요.',
en: 'Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log({
ko: `${e.rowKey}번 줄 수량: ${String(e.oldValue)} → ${String(e.newValue)}`,
en: `Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(
L(`✗ ${e.rowKey}번 줄 수량: ${e.message}`, `✗ Row ${e.rowKey} quantity: ${e.message}`),
);
log({
ko: `✗ ${e.rowKey}번 줄 수량: ${e.message}`,
en: `✗ Row ${e.rowKey} quantity: ${e.message}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'qty'),
};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="edit">Edit quantity of row 1</button>
</div>
<div id="grid" style="height: 240px"></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('edit').addEventListener('click', () => actions.edit(api));// A reason shown only on hover is missed on touch and keyboard, so also put a visible line right under the grid.
function makeReasonLine() {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// With no message the line takes no space (so the gap between grid and log does not widen). The line itself stays, so status announcements are still read.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
// On finger-driven screens such as phones, input text is 16px so the page does not zoom when an input is tapped.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Number stepper editor: [−] value [+]. Up/Down arrow keys also change it. The grid handles Enter (commit) and Esc (cancel); the editor only handles the value.
const stepper = () => {
let wrap;
let input;
const step = (delta) => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label, delta) => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // keep focus on the input
b.setAttribute('aria-label', delta > 0 ? 'Increase by one' : 'Decrease by one');
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // do not steal focus from the input
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// There are −/+ buttons, so hide the browser's default spin arrows (inside this editor only).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', `${ctx.row.item} quantity`);
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
export const options = {
columns: [
{ id: 'item', title: 'Item', width: 180 },
{
id: 'qty',
title: 'Quantity (double-click)',
kind: 'number',
width: 240,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n))
return 'Enter a quantity.';
return n < 0 || n > 99 ? 'Enter a quantity between 0 and 99.' : null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C cable', qty: 12 },
{ id: 2, item: 'Wireless mouse', qty: 4 },
{ id: 3, item: 'Laptop stand', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
export function setup(api, log) {
const reason = makeReasonLine();
log('Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.');
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log(`Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ Row ${e.rowKey} quantity: ${e.message}`);
log(`✗ Row ${e.rowKey} quantity: ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api) => api.startEdit(1, 'qty'),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Quantity editor with − and + buttons</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="edit">Edit quantity of row 1</button>
</div>
<div id="grid" style="height: 240px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// A reason shown only on hover is missed on touch and keyboard, so also put a visible line right under the grid.
function makeReasonLine() {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// With no message the line takes no space (so the gap between grid and log does not widen). The line itself stays, so status announcements are still read.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
// On finger-driven screens such as phones, input text is 16px so the page does not zoom when an input is tapped.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Number stepper editor: [−] value [+]. Up/Down arrow keys also change it. The grid handles Enter (commit) and Esc (cancel); the editor only handles the value.
const stepper = () => {
let wrap;
let input;
const step = (delta) => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label, delta) => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // keep focus on the input
b.setAttribute('aria-label', delta > 0 ? 'Increase by one' : 'Decrease by one');
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // do not steal focus from the input
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// There are −/+ buttons, so hide the browser's default spin arrows (inside this editor only).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', `${ctx.row.item} quantity`);
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
const options = {
columns: [
{ id: 'item', title: 'Item', width: 180 },
{
id: 'qty',
title: 'Quantity (double-click)',
kind: 'number',
width: 240,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n))
return 'Enter a quantity.';
return n < 0 || n > 99 ? 'Enter a quantity between 0 and 99.' : null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C cable', qty: 12 },
{ id: 2, item: 'Wireless mouse', qty: 4 },
{ id: 3, item: 'Laptop stand', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
function setup(api, log) {
const reason = makeReasonLine();
log('Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.');
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log(`Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ Row ${e.rowKey} quantity: ${e.message}`);
log(`✗ Row ${e.rowKey} quantity: ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
const actions = {
edit: (api) => api.startEdit(1, 'qty'),
};
options.ariaLabel = "Quantity editor with − and + buttons";
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('edit').addEventListener('click', () => actions.edit(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.edit(api)}
>Edit quantity of row 1</button>
</div>
<Grid style={{ height: 240 }} ref={gridRef} options={options} />
</>
);
}import type { CellEditorAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
// A reason shown only on hover is missed on touch and keyboard, so also put a visible line right under the grid.
function makeReasonLine(): { show: (text: string) => void; remove: () => void } {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// With no message the line takes no space (so the gap between grid and log does not widen). The line itself stays, so status announcements are still read.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
export interface Row {
id: number;
item: string;
qty: number;
}
// On finger-driven screens such as phones, input text is 16px so the page does not zoom when an input is tapped.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Number stepper editor: [−] value [+]. Up/Down arrow keys also change it. The grid handles Enter (commit) and Esc (cancel); the editor only handles the value.
const stepper = (): CellEditorAdapter<Row> => {
let wrap: HTMLDivElement;
let input: HTMLInputElement;
const step = (delta: number): void => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label: string, delta: number): HTMLButtonElement => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // keep focus on the input
b.setAttribute('aria-label', delta > 0 ? 'Increase by one' : 'Decrease by one');
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // do not steal focus from the input
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// There are −/+ buttons, so hide the browser's default spin arrows (inside this editor only).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', `${ctx.row.item} quantity`);
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: 'Item', width: 180 },
{
id: 'qty',
title: 'Quantity (double-click)',
kind: 'number',
width: 240,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n)) return 'Enter a quantity.';
return n < 0 || n > 99 ? 'Enter a quantity between 0 and 99.' : null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C cable', qty: 12 },
{ id: 2, item: 'Wireless mouse', qty: 4 },
{ id: 3, item: 'Laptop stand', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log(
'Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.',
);
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log(`Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ Row ${e.rowKey} quantity: ${e.message}`);
log(`✗ Row ${e.rowKey} quantity: ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'qty'),
};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.edit(api)">Edit quantity of row 1</button>
</div>
<Grid style="height: 240px" :options="options" @ready="onReady" />
</template>import type { CellEditorAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
// A reason shown only on hover is missed on touch and keyboard, so also put a visible line right under the grid.
function makeReasonLine(): { show: (text: string) => void; remove: () => void } {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// With no message the line takes no space (so the gap between grid and log does not widen). The line itself stays, so status announcements are still read.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
export interface Row {
id: number;
item: string;
qty: number;
}
// On finger-driven screens such as phones, input text is 16px so the page does not zoom when an input is tapped.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Number stepper editor: [−] value [+]. Up/Down arrow keys also change it. The grid handles Enter (commit) and Esc (cancel); the editor only handles the value.
const stepper = (): CellEditorAdapter<Row> => {
let wrap: HTMLDivElement;
let input: HTMLInputElement;
const step = (delta: number): void => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label: string, delta: number): HTMLButtonElement => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // keep focus on the input
b.setAttribute('aria-label', delta > 0 ? 'Increase by one' : 'Decrease by one');
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // do not steal focus from the input
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// There are −/+ buttons, so hide the browser's default spin arrows (inside this editor only).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', `${ctx.row.item} quantity`);
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: 'Item', width: 180 },
{
id: 'qty',
title: 'Quantity (double-click)',
kind: 'number',
width: 240,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n)) return 'Enter a quantity.';
return n < 0 || n > 99 ? 'Enter a quantity between 0 and 99.' : null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C cable', qty: 12 },
{ id: 2, item: 'Wireless mouse', qty: 4 },
{ id: 3, item: 'Laptop stand', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log(
'Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.',
);
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log(`Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ Row ${e.rowKey} quantity: ${e.message}`);
log(`✗ Row ${e.rowKey} quantity: ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'qty'),
};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.edit(api)"
>Edit quantity of row 1</button>
</div>
<mx-grid style="height: 240px" [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 { CellEditorAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
// A reason shown only on hover is missed on touch and keyboard, so also put a visible line right under the grid.
function makeReasonLine(): { show: (text: string) => void; remove: () => void } {
const line = document.createElement('div');
line.setAttribute('role', 'status');
line.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
document.getElementById('grid')?.after(line);
// With no message the line takes no space (so the gap between grid and log does not widen). The line itself stays, so status announcements are still read.
return {
show: (text) => {
line.textContent = text;
line.style.marginTop = text ? '6px' : '0';
},
remove: () => line.remove(),
};
}
export interface Row {
id: number;
item: string;
qty: number;
}
// On finger-driven screens such as phones, input text is 16px so the page does not zoom when an input is tapped.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Number stepper editor: [−] value [+]. Up/Down arrow keys also change it. The grid handles Enter (commit) and Esc (cancel); the editor only handles the value.
const stepper = (): CellEditorAdapter<Row> => {
let wrap: HTMLDivElement;
let input: HTMLInputElement;
const step = (delta: number): void => {
input.value = String(Math.max(0, (Number(input.value) || 0) + delta));
};
const button = (label: string, delta: number): HTMLButtonElement => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = label;
b.tabIndex = -1; // keep focus on the input
b.setAttribute('aria-label', delta > 0 ? 'Increase by one' : 'Decrease by one');
b.style.cssText = `width: 40px; height: 100%; border: 0; background: transparent; font: inherit; cursor: pointer; color: inherit;`;
b.addEventListener('mousedown', (e) => e.preventDefault()); // do not steal focus from the input
b.addEventListener('click', () => step(delta));
return b;
};
return {
mount(el, ctx) {
wrap = document.createElement('div');
wrap.style.cssText = 'display: flex; height: 100%; align-items: center;';
// There are −/+ buttons, so hide the browser's default spin arrows (inside this editor only).
const hideSpin = document.createElement('style');
hideSpin.textContent =
'.mxg-stepper-input{appearance:textfield;-moz-appearance:textfield}' +
'.mxg-stepper-input::-webkit-inner-spin-button,.mxg-stepper-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}';
wrap.append(hideSpin);
input = document.createElement('input');
input.className = 'mxg-stepper-input';
input.type = 'number';
input.setAttribute('aria-label', `${ctx.row.item} quantity`);
input.value = String(ctx.value ?? 0);
input.style.cssText = `flex: 1; min-width: 0; height: 100%; border: 0; text-align: center; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
step(e.key === 'ArrowUp' ? 1 : -1);
}
});
wrap.append(button('−', -1), input, button('+', 1));
el.append(wrap);
},
getValue: () => (input.value === '' ? null : Number(input.value)),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
wrap.title = message ?? '';
},
destroy: () => wrap.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: 'Item', width: 180 },
{
id: 'qty',
title: 'Quantity (double-click)',
kind: 'number',
width: 240,
align: 'center',
editable: true,
cellEditor: stepper,
validation: {
custom: (value) => {
const n = Number(value);
if (value === null || Number.isNaN(n)) return 'Enter a quantity.';
return n < 0 || n > 99 ? 'Enter a quantity between 0 and 99.' : null;
},
},
},
],
rows: [
{ id: 1, item: 'USB-C cable', qty: 12 },
{ id: 2, item: 'Wireless mouse', qty: 4 },
{ id: 3, item: 'Laptop stand', qty: 0 },
],
rowKey: 'id',
saveMode: 'none',
rowHeight: coarse() ? 44 : 40,
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log(
'Double-click a quantity cell and change it with the − + buttons or the up and down arrow keys.',
);
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
log(`Row ${e.rowKey} quantity: ${String(e.oldValue)} → ${String(e.newValue)}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ Row ${e.rowKey} quantity: ${e.message}`);
log(`✗ Row ${e.rowKey} quantity: ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'qty'),
};