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

날짜 편집기: 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.

활용Intermediate
직접 써 보기Live preview날짜 편집기: 2027년 안에서만 고르기Date editor limited to 2027

코드Code

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

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

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

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="edit">첫 일정 날짜 편집</button>
  </div>
  <div id="grid" style="height: 240px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('edit').addEventListener('click', () => actions.edit(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(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'),
};

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

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="edit">Edit date of first event</button>
  </div>
  <div id="grid" style="height: 240px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('edit').addEventListener('click', () => actions.edit(api));
example.js
// 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'),
};