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

키보드로 행 넣고 지우기Add and remove rows with the keyboard

keyboardRows: true로 Insert는 새 행, Ctrl+Delete는 선택 행 삭제를 켜요. 새 행은 컬럼 기본값으로 채우고, 훅에는 source: 'keyboard'로 알려서 막거나 되물을 수 있어요.keyboardRows: true turns on Insert for a new row and Ctrl+Delete for removing the selected rows. The new row gets the column defaults, and hooks see source: 'keyboard' so you can veto or confirm.

활용Intermediate
직접 써 보기Live preview키보드로 행 넣고 지우기Add and remove rows with the keyboard

코드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="focusFirst">첫 칸 포커스</button>
    <button type="button" id="selectAll">모두 선택</button>
  </div>
  <div id="grid" style="height: 320px"></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('focusFirst').addEventListener('click', () => actions.focusFirst(api));
document.getElementById('selectAll').addEventListener('click', () => actions.selectAll(api));
example.js
const en = document.documentElement.dataset.lang === 'en';
export const options = {
  columns: [
    {
      id: 'task',
      title: en ? 'Task' : '업무',
      width: 200,
      editable: true,
      defaultValue: en ? 'New task' : '새 업무',
    },
    {
      id: 'owner',
      title: en ? 'Owner' : '담당',
      width: 130,
      editable: true,
      defaultValue: en ? 'TBD' : '미정',
    },
  ],
  rows: [
    { id: 1, task: en ? 'Improve login' : '로그인 개선', owner: en ? 'Minjun Kim' : '김민준' },
    { id: 2, task: en ? 'Check export' : '내보내기 점검', owner: en ? 'Seoyeon Lee' : '이서연' },
    { id: 3, task: en ? 'Dark mode' : '다크 모드', owner: en ? 'Jiho Park' : '박지호' },
  ],
  rowKey: 'id',
  selection: 'multiple',
  // keyboardRows: true는 Insert(또는 Ctrl+더하기)로 행 넣기, Ctrl+Delete(Mac은 ⌘+Backspace)로 지우기를 켜요.
  keyboardRows: true,
  hooks: {
    // source: 'keyboard'면 키보드에서 온 요청이에요. 3행 이상 한꺼번에 지우는 것만 막아 봤어요.
    beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
  },
  ariaLabel: en ? 'Add and remove rows with the keyboard' : '키보드로 행 넣고 지우기',
};
export function setup(api, log) {
  log({
    ko: '칸을 하나 누른 뒤 Insert를 눌러 보세요. 그 행 뒤에 새 행이 생기고 첫 칸 편집이 시작돼요. Ctrl+Delete는 고른 행(없으면 포커스 행)을 지워요.',
    en: 'Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).',
  });
  const offs = [
    api.on('rowsChanged', (e) => log({
      ko: `행 ${e.reason === 'add' ? '추가' : e.reason === 'remove' ? '삭제' : e.reason} ${e.count}개 → 전체 ${api.getRowCount()}행`,
      en: `Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`,
    })),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  focusFirst: (api) => {
    api.focusCell(1, 'task');
    // 버튼이 DOM 포커스를 쥐고 있으면 Insert 키가 그리드에 닿지 않아요. 그리드로 DOM 포커스도 옮겨요.
    document.querySelector('.mxg')?.focus({ preventScroll: true });
  },
  selectAll: (api) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};

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="focusFirst">Focus first cell</button>
    <button type="button" id="selectAll">Select all</button>
  </div>
  <div id="grid" style="height: 320px"></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('focusFirst').addEventListener('click', () => actions.focusFirst(api));
document.getElementById('selectAll').addEventListener('click', () => actions.selectAll(api));
example.js
export const options = {
  columns: [
    {
      id: 'task',
      title: 'Task',
      width: 200,
      editable: true,
      defaultValue: 'New task',
    },
    {
      id: 'owner',
      title: 'Owner',
      width: 130,
      editable: true,
      defaultValue: 'TBD',
    },
  ],
  rows: [
    { id: 1, task: 'Improve login', owner: 'Liam Carter' },
    { id: 2, task: 'Check export', owner: 'Emma Stone' },
    { id: 3, task: 'Dark mode', owner: 'Noah Kim' },
  ],
  rowKey: 'id',
  selection: 'multiple',
  // keyboardRows: true turns on inserting a row with Insert (or Ctrl+Plus) and removing with Ctrl+Delete (⌘+Backspace on Mac).
  keyboardRows: true,
  hooks: {
    // source: 'keyboard' means the request came from the keyboard. Only removing 3 or more rows at once is blocked, as a trial.
    beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
  },
  ariaLabel: 'Add and remove rows with the keyboard',
};
export function setup(api, log) {
  log('Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).');
  const offs = [
    api.on('rowsChanged', (e) => log(`Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`)),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  focusFirst: (api) => {
    api.focusCell(1, 'task');
    // If a button holds the DOM focus, the Insert key does not reach the grid. Move the DOM focus to the grid as well.
    document.querySelector('.mxg')?.focus({ preventScroll: true });
  },
  selectAll: (api) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};