날짜 편집기: 2027년 안에서만 고르기Date editor limited to 2027
달력으로 날짜를 고치되 2027년 안의 날짜만 받아요. 달력도 그 범위로 좁히고, 직접 써 넣은 날짜가 범위를 벗어나면 이유와 함께 막아요.Edit dates with a calendar but accept only dates in 2027. The calendar is narrowed to that range, and a typed date outside it is refused with a reason.
코드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">첫 일정 날짜 편집</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;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n) => String(n).padStart(2, '0');
const toInput = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// 2027년만 고를 수 있는 날짜 편집기예요. min·max는 달력의 범위를 좁혀 주지만 날짜를 직접 써 넣으면 범위를 벗어날 수 있어서,
// 아래의 검증 규칙이 진짜 문지기이고 setError가 이유를 보여 줘요.
const dateEditor = () => {
let input;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', L(`${ctx.row.event} 날짜`, `${ctx.row.event} date`));
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// 편집을 시작하자마자 달력이 열리게 해요(브라우저가 막으면 입력칸만 보여요).
try {
input.showPicker();
}
catch {
/* 사용자 동작 없이는 열 수 없는 브라우저면 건너뛰어요 */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
export const options = {
columns: [
{ id: 'event', title: '일정', width: 150 },
{
id: 'date',
title: '날짜(2027년만)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date))
return L('날짜를 골라 주세요.', 'Pick a date.');
return value < MIN || value > MAX
? L('2027년 안의 날짜를 골라 주세요.', 'Pick a date within 2027.')
: null;
},
},
},
],
rows: [
{ id: 1, event: '시작 모임', date: new Date(2027, 1, 8) },
{ id: 2, event: '시험판 공개', date: new Date(2027, 5, 21) },
{ id: 3, event: '정식 출시', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api, log) {
const reason = makeReasonLine();
log({
ko: '날짜 칸을 더블클릭해서 2027년 안의 날짜를 골라 보세요.',
en: 'Double-click a date cell and pick a date within 2027.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log({
ko: `${row?.event ?? e.rowKey} 날짜: ${next}`,
en: `${row?.event ?? e.rowKey} date: ${next}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api) => api.startEdit(1, 'date'),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>날짜 편집기: 2027년 안에서만 고르기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="edit">첫 일정 날짜 편집</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;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n) => String(n).padStart(2, '0');
const toInput = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// 2027년만 고를 수 있는 날짜 편집기예요. min·max는 달력의 범위를 좁혀 주지만 날짜를 직접 써 넣으면 범위를 벗어날 수 있어서,
// 아래의 검증 규칙이 진짜 문지기이고 setError가 이유를 보여 줘요.
const dateEditor = () => {
let input;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', L(`${ctx.row.event} 날짜`, `${ctx.row.event} date`));
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// 편집을 시작하자마자 달력이 열리게 해요(브라우저가 막으면 입력칸만 보여요).
try {
input.showPicker();
}
catch {
/* 사용자 동작 없이는 열 수 없는 브라우저면 건너뛰어요 */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
const options = {
columns: [
{ id: 'event', title: '일정', width: 150 },
{
id: 'date',
title: '날짜(2027년만)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date))
return L('날짜를 골라 주세요.', 'Pick a date.');
return value < MIN || value > MAX
? L('2027년 안의 날짜를 골라 주세요.', 'Pick a date within 2027.')
: null;
},
},
},
],
rows: [
{ id: 1, event: '시작 모임', date: new Date(2027, 1, 8) },
{ id: 2, event: '시험판 공개', date: new Date(2027, 5, 21) },
{ id: 3, event: '정식 출시', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
function setup(api, log) {
const reason = makeReasonLine();
log({
ko: '날짜 칸을 더블클릭해서 2027년 안의 날짜를 골라 보세요.',
en: 'Double-click a date cell and pick a date within 2027.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log({
ko: `${row?.event ?? e.rowKey} 날짜: ${next}`,
en: `${row?.event ?? e.rowKey} date: ${next}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
const actions = {
edit: (api) => api.startEdit(1, 'date'),
};
options.ariaLabel = "날짜 편집기: 2027년 안에서만 고르기";
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)}
>첫 일정 날짜 편집</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;
event: string;
date: Date;
}
// 폰처럼 손가락으로 쓰는 화면에서는 입력 글자를 16px로 해서, 입력칸을 누를 때 화면이 저절로 확대되지 않게 해요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n: number): string => String(n).padStart(2, '0');
const toInput = (d: Date): string =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// 2027년만 고를 수 있는 날짜 편집기예요. min·max는 달력의 범위를 좁혀 주지만 날짜를 직접 써 넣으면 범위를 벗어날 수 있어서,
// 아래의 검증 규칙이 진짜 문지기이고 setError가 이유를 보여 줘요.
const dateEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', L(`${ctx.row.event} 날짜`, `${ctx.row.event} date`));
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// 편집을 시작하자마자 달력이 열리게 해요(브라우저가 막으면 입력칸만 보여요).
try {
input.showPicker();
} catch {
/* 사용자 동작 없이는 열 수 없는 브라우저면 건너뛰어요 */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'event', title: '일정', width: 150 },
{
id: 'date',
title: '날짜(2027년만)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date)) return L('날짜를 골라 주세요.', 'Pick a date.');
return value < MIN || value > MAX
? L('2027년 안의 날짜를 골라 주세요.', 'Pick a date within 2027.')
: null;
},
},
},
],
rows: [
{ id: 1, event: '시작 모임', date: new Date(2027, 1, 8) },
{ id: 2, event: '시험판 공개', date: new Date(2027, 5, 21) },
{ id: 3, event: '정식 출시', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log({
ko: '날짜 칸을 더블클릭해서 2027년 안의 날짜를 골라 보세요.',
en: 'Double-click a date cell and pick a date within 2027.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log({
ko: `${row?.event ?? e.rowKey} 날짜: ${next}`,
en: `${row?.event ?? e.rowKey} date: ${next}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'date'),
};버튼을 누르면 이 예제의 코드가 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)">첫 일정 날짜 편집</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;
event: string;
date: Date;
}
// 폰처럼 손가락으로 쓰는 화면에서는 입력 글자를 16px로 해서, 입력칸을 누를 때 화면이 저절로 확대되지 않게 해요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n: number): string => String(n).padStart(2, '0');
const toInput = (d: Date): string =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// 2027년만 고를 수 있는 날짜 편집기예요. min·max는 달력의 범위를 좁혀 주지만 날짜를 직접 써 넣으면 범위를 벗어날 수 있어서,
// 아래의 검증 규칙이 진짜 문지기이고 setError가 이유를 보여 줘요.
const dateEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', L(`${ctx.row.event} 날짜`, `${ctx.row.event} date`));
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// 편집을 시작하자마자 달력이 열리게 해요(브라우저가 막으면 입력칸만 보여요).
try {
input.showPicker();
} catch {
/* 사용자 동작 없이는 열 수 없는 브라우저면 건너뛰어요 */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'event', title: '일정', width: 150 },
{
id: 'date',
title: '날짜(2027년만)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date)) return L('날짜를 골라 주세요.', 'Pick a date.');
return value < MIN || value > MAX
? L('2027년 안의 날짜를 골라 주세요.', 'Pick a date within 2027.')
: null;
},
},
},
],
rows: [
{ id: 1, event: '시작 모임', date: new Date(2027, 1, 8) },
{ id: 2, event: '시험판 공개', date: new Date(2027, 5, 21) },
{ id: 3, event: '정식 출시', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log({
ko: '날짜 칸을 더블클릭해서 2027년 안의 날짜를 골라 보세요.',
en: 'Double-click a date cell and pick a date within 2027.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log({
ko: `${row?.event ?? e.rowKey} 날짜: ${next}`,
en: `${row?.event ?? e.rowKey} date: ${next}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'date'),
};버튼을 누르면 이 예제의 코드가 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)"
>첫 일정 날짜 편집</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;
event: string;
date: Date;
}
// 폰처럼 손가락으로 쓰는 화면에서는 입력 글자를 16px로 해서, 입력칸을 누를 때 화면이 저절로 확대되지 않게 해요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n: number): string => String(n).padStart(2, '0');
const toInput = (d: Date): string =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// 2027년만 고를 수 있는 날짜 편집기예요. min·max는 달력의 범위를 좁혀 주지만 날짜를 직접 써 넣으면 범위를 벗어날 수 있어서,
// 아래의 검증 규칙이 진짜 문지기이고 setError가 이유를 보여 줘요.
const dateEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', L(`${ctx.row.event} 날짜`, `${ctx.row.event} date`));
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// 편집을 시작하자마자 달력이 열리게 해요(브라우저가 막으면 입력칸만 보여요).
try {
input.showPicker();
} catch {
/* 사용자 동작 없이는 열 수 없는 브라우저면 건너뛰어요 */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'event', title: '일정', width: 150 },
{
id: 'date',
title: '날짜(2027년만)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date)) return L('날짜를 골라 주세요.', 'Pick a date.');
return value < MIN || value > MAX
? L('2027년 안의 날짜를 골라 주세요.', 'Pick a date within 2027.')
: null;
},
},
},
],
rows: [
{ id: 1, event: '시작 모임', date: new Date(2027, 1, 8) },
{ id: 2, event: '시험판 공개', date: new Date(2027, 5, 21) },
{ id: 3, event: '정식 출시', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log({
ko: '날짜 칸을 더블클릭해서 2027년 안의 날짜를 골라 보세요.',
en: 'Double-click a date cell and pick a date within 2027.',
});
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log({
ko: `${row?.event ?? e.rowKey} 날짜: ${next}`,
en: `${row?.event ?? e.rowKey} date: ${next}`,
});
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'date'),
};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 date of first event</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;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n) => String(n).padStart(2, '0');
const toInput = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// A date editor that accepts 2027 only. min and max narrow the calendar, but a typed date can still fall outside,
// so the validation rule below is the real gatekeeper and setError shows the reason.
const dateEditor = () => {
let input;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', `${ctx.row.event} date`);
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// Open the calendar as soon as editing starts (if the browser blocks it, only the input is shown).
try {
input.showPicker();
}
catch {
/* skip in browsers that cannot open it without a user gesture */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
export const options = {
columns: [
{ id: 'event', title: 'Event', width: 150 },
{
id: 'date',
title: 'Date (2027 only)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date))
return 'Pick a date.';
return value < MIN || value > MAX ? 'Pick a date within 2027.' : null;
},
},
},
],
rows: [
{ id: 1, event: 'Kickoff meeting', date: new Date(2027, 1, 8) },
{ id: 2, event: 'Beta release', date: new Date(2027, 5, 21) },
{ id: 3, event: 'General availability', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api, log) {
const reason = makeReasonLine();
log('Double-click a date cell and pick a date within 2027.');
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log(`${row?.event ?? e.rowKey} date: ${next}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api) => api.startEdit(1, 'date'),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Date editor limited to 2027</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="edit">Edit date of first event</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;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n) => String(n).padStart(2, '0');
const toInput = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// A date editor that accepts 2027 only. min and max narrow the calendar, but a typed date can still fall outside,
// so the validation rule below is the real gatekeeper and setError shows the reason.
const dateEditor = () => {
let input;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', `${ctx.row.event} date`);
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// Open the calendar as soon as editing starts (if the browser blocks it, only the input is shown).
try {
input.showPicker();
}
catch {
/* skip in browsers that cannot open it without a user gesture */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
const options = {
columns: [
{ id: 'event', title: 'Event', width: 150 },
{
id: 'date',
title: 'Date (2027 only)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date))
return 'Pick a date.';
return value < MIN || value > MAX ? 'Pick a date within 2027.' : null;
},
},
},
],
rows: [
{ id: 1, event: 'Kickoff meeting', date: new Date(2027, 1, 8) },
{ id: 2, event: 'Beta release', date: new Date(2027, 5, 21) },
{ id: 3, event: 'General availability', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
function setup(api, log) {
const reason = makeReasonLine();
log('Double-click a date cell and pick a date within 2027.');
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log(`${row?.event ?? e.rowKey} date: ${next}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
const actions = {
edit: (api) => api.startEdit(1, 'date'),
};
options.ariaLabel = "Date editor limited to 2027";
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 date of first event</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;
event: string;
date: Date;
}
// 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;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n: number): string => String(n).padStart(2, '0');
const toInput = (d: Date): string =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// A date editor that accepts 2027 only. min and max narrow the calendar, but a typed date can still fall outside,
// so the validation rule below is the real gatekeeper and setError shows the reason.
const dateEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', `${ctx.row.event} date`);
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// Open the calendar as soon as editing starts (if the browser blocks it, only the input is shown).
try {
input.showPicker();
} catch {
/* skip in browsers that cannot open it without a user gesture */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'event', title: 'Event', width: 150 },
{
id: 'date',
title: 'Date (2027 only)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date)) return 'Pick a date.';
return value < MIN || value > MAX ? 'Pick a date within 2027.' : null;
},
},
},
],
rows: [
{ id: 1, event: 'Kickoff meeting', date: new Date(2027, 1, 8) },
{ id: 2, event: 'Beta release', date: new Date(2027, 5, 21) },
{ id: 3, event: 'General availability', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log('Double-click a date cell and pick a date within 2027.');
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log(`${row?.event ?? e.rowKey} date: ${next}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'date'),
};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 date of first event</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;
event: string;
date: Date;
}
// 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;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n: number): string => String(n).padStart(2, '0');
const toInput = (d: Date): string =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// A date editor that accepts 2027 only. min and max narrow the calendar, but a typed date can still fall outside,
// so the validation rule below is the real gatekeeper and setError shows the reason.
const dateEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', `${ctx.row.event} date`);
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// Open the calendar as soon as editing starts (if the browser blocks it, only the input is shown).
try {
input.showPicker();
} catch {
/* skip in browsers that cannot open it without a user gesture */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'event', title: 'Event', width: 150 },
{
id: 'date',
title: 'Date (2027 only)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date)) return 'Pick a date.';
return value < MIN || value > MAX ? 'Pick a date within 2027.' : null;
},
},
},
],
rows: [
{ id: 1, event: 'Kickoff meeting', date: new Date(2027, 1, 8) },
{ id: 2, event: 'Beta release', date: new Date(2027, 5, 21) },
{ id: 3, event: 'General availability', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log('Double-click a date cell and pick a date within 2027.');
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log(`${row?.event ?? e.rowKey} date: ${next}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'date'),
};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 date of first event</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;
event: string;
date: Date;
}
// 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;
const MIN = new Date(2027, 0, 1);
const MAX = new Date(2027, 11, 31);
const pad = (n: number): string => String(n).padStart(2, '0');
const toInput = (d: Date): string =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
// A date editor that accepts 2027 only. min and max narrow the calendar, but a typed date can still fall outside,
// so the validation rule below is the real gatekeeper and setError shows the reason.
const dateEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
return {
mount(el, ctx) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-label', `${ctx.row.event} date`);
input.min = toInput(MIN);
input.max = toInput(MAX);
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: 16px; background: transparent; color: inherit;`;
input.value = ctx.value instanceof Date ? toInput(ctx.value) : '';
el.append(input);
},
getValue() {
const [y, m, d] = input.value.split('-').map(Number);
return y && m && d ? new Date(y, m - 1, d) : null;
},
focus() {
input.focus();
// Open the calendar as soon as editing starts (if the browser blocks it, only the input is shown).
try {
input.showPicker();
} catch {
/* skip in browsers that cannot open it without a user gesture */
}
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
input.style.outline = message ? '2px solid #e5484d' : '';
},
destroy: () => input.remove(),
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'event', title: 'Event', width: 150 },
{
id: 'date',
title: 'Date (2027 only)',
kind: 'date',
width: 180,
editable: true,
cellEditor: dateEditor,
validation: {
custom: (value) => {
if (!(value instanceof Date)) return 'Pick a date.';
return value < MIN || value > MAX ? 'Pick a date within 2027.' : null;
},
},
},
],
rows: [
{ id: 1, event: 'Kickoff meeting', date: new Date(2027, 1, 8) },
{ id: 2, event: 'Beta release', date: new Date(2027, 5, 21) },
{ id: 3, event: 'General availability', date: new Date(2027, 8, 14) },
],
rowKey: 'id',
saveMode: 'none',
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const reason = makeReasonLine();
log('Double-click a date cell and pick a date within 2027.');
const offs = [
api.on('editCancelled', () => reason.show('')),
api.on('editCommitted', (e) => {
reason.show('');
const row = api.getRowByKey(e.rowKey);
const next = e.newValue instanceof Date ? toInput(e.newValue) : String(e.newValue);
log(`${row?.event ?? e.rowKey} date: ${next}`);
}),
api.on('validationFailed', (e) => {
reason.show(`✗ ${e.message}`);
log(`✗ ${e.message}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'date'),
};