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

행을 더한 뒤 바로 보여 주기와 페이지 단축키Reveal a new row and page-level shortcuts

행을 더한 뒤에는 그 행을 선택하고 화면으로 스크롤해 눈이 바로 찾게 해요. 정렬이 켜져 있으면 정렬된 자리로 들어가는 점도 보여 줘요. Alt+N으로 더하고 Delete로 지우는 페이지 단축키는 화면을 떠날 때 꼭 걷어 내야 해요.After adding a row, select it and scroll to it so the eye finds it; with a sort on it lands in sorted position. Page shortcuts Alt+N to add and Delete to remove must be taken away when the screen goes.

활용Intermediate
직접 써 보기Live preview행을 더한 뒤 바로 보여 주기와 페이지 단축키Reveal a new row and page-level shortcuts

코드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="addBottom">맨 아래에 더하기</button>
    <button type="button" id="addTop">맨 위에 더하기</button>
    <button type="button" id="addSorted">정렬해서 더하기</button>
    <button type="button" id="clearSort">정렬 해제</button>
  </div>
  <div id="grid" style="height: 360px"></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('addBottom').addEventListener('click', () => actions.addBottom(api));
document.getElementById('addTop').addEventListener('click', () => actions.addTop(api));
document.getElementById('addSorted').addEventListener('click', () => actions.addSorted(api));
document.getElementById('clearSort').addEventListener('click', () => actions.clearSort(api));
example.js
const owners = ['김민준', '이서연', '박지호'];
export const options = {
  columns: [
    { id: 'task', title: '업무', width: 200 },
    { id: 'owner', title: '담당', width: 120 },
  ],
  rows: Array.from({ length: 30 }, (_, i) => ({
    id: i + 1,
    task: `업무 ${i + 1}`,
    owner: owners[i % 3],
  })),
  rowKey: 'id',
  selection: 'multiple',
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
  const ch = word.trim().slice(-1);
  const digit = '0123456789'.indexOf(ch);
  if (digit >= 0)
    return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
  const code = ch.charCodeAt(0) - 0xac00;
  return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
let say = () => { };
let nextId = 100;
const create = (label) => ({
  id: ++nextId,
  task: `${label} ${nextId}`,
  owner: '이서연',
});
// 행을 추가한 뒤에는 그 행을 선택하고 화면으로 가져와서, 눈이 바로 찾게 해요.
function reveal(api, id) {
  api.setSelectedKeys([id]);
  api.scrollToRow(id);
  api.focusCell(id, 'task');
}
// 페이지 전체 단축키: Alt+N은 맨 위에 행을 더하고, Delete는 고른 행을 지워요. 입력칸이나 선택 목록에
// 글자를 쓰는 중에는 동작하지 않아요. 리스너는 document에 달았으니 정리 함수에서 꼭 지워요.
export function setup(api, log) {
  say = log;
  const onKeyDown = (event) => {
    const target = event.target;
    if (target instanceof HTMLElement && target.closest('input, textarea, select'))
      return;
    if (event.key === 'Delete') {
      const removed = api.removeRows(api.getSelectedKeys());
      if (removed > 0)
        log({ ko: `Delete: ${removed}행을 지웠어요`, en: `Delete: deleted ${removed} rows` });
    }
    else if (event.altKey && event.code === 'KeyN') {
      event.preventDefault();
      const row = create('새 업무');
      api.addRows([row], 0);
      reveal(api, row.id);
      log({
        ko: `Alt+N: ${row.task}${eulReul(row.task)} 맨 위에 더했어요`,
        en: `Alt+N: added ${row.task} at the top`,
      });
    }
  };
  document.addEventListener('keydown', onKeyDown);
  return () => document.removeEventListener('keydown', onKeyDown);
}
export const actions = {
  addBottom: (api) => {
    const row = create('새 업무');
    api.addRows([row]);
    reveal(api, row.id);
    say({
      ko: `${row.task}${eulReul(row.task)} 맨 아래에 더하고 선택했어요`,
      en: `Added ${row.task} at the bottom and selected it`,
    });
  },
  addTop: (api) => {
    const row = create('급한 업무');
    api.addRows([row], 0);
    reveal(api, row.id);
    say({
      ko: `${row.task}${eulReul(row.task)} 맨 위에 더하고 선택했어요`,
      en: `Added ${row.task} at the top and selected it`,
    });
  },
  // 정렬이 켜져 있으면 행이 정렬 자리로 들어가니까, 그 자리를 먼저 찾은 뒤에 스크롤해요.
  addSorted: (api) => {
    const row = create('정렬된 업무');
    api.setSortModel([{ columnId: 'task', direction: 'asc' }]);
    api.addRows([row]);
    reveal(api, row.id);
    say({
      ko: `업무 이름 순으로 정렬하고, ${row.task}${eulReul(row.task)} 제자리(${api.getVisibleIndexOfKey(row.id) + 1}번째 줄)에 더했어요`,
      en: `Sorted by task name and added ${row.task} in place (row ${api.getVisibleIndexOfKey(row.id) + 1})`,
    });
  },
  clearSort: (api) => {
    api.setSortModel([]);
    say({ ko: '정렬을 풀었어요', en: 'Sort cleared' });
  },
};

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="addBottom">Add at bottom</button>
    <button type="button" id="addTop">Add on top</button>
    <button type="button" id="addSorted">Add sorted</button>
    <button type="button" id="clearSort">Clear sort</button>
  </div>
  <div id="grid" style="height: 360px"></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('addBottom').addEventListener('click', () => actions.addBottom(api));
document.getElementById('addTop').addEventListener('click', () => actions.addTop(api));
document.getElementById('addSorted').addEventListener('click', () => actions.addSorted(api));
document.getElementById('clearSort').addEventListener('click', () => actions.clearSort(api));
example.js
const owners = ['Liam Carter', 'Emma Stone', 'Noah Reed'];
export const options = {
  columns: [
    { id: 'task', title: 'Task', width: 200 },
    { id: 'owner', title: 'Owner', width: 120 },
  ],
  rows: Array.from({ length: 30 }, (_, i) => ({
    id: i + 1,
    task: `Task ${i + 1}`,
    owner: owners[i % 3],
  })),
  rowKey: 'id',
  selection: 'multiple',
};
let say = () => { };
let nextId = 100;
const create = (label) => ({
  id: ++nextId,
  task: `${label} ${nextId}`,
  owner: 'Emma Stone',
});
// After adding a row, select it and bring it into view so the eye finds it right away.
function reveal(api, id) {
  api.setSelectedKeys([id]);
  api.scrollToRow(id);
  api.focusCell(id, 'task');
}
// Page-wide shortcuts: Alt+N adds a row at the top, Delete removes the selected rows. They do nothing
// while you type in an input or a select. The listener is on document, so remove it in the cleanup function.
export function setup(api, log) {
  say = log;
  const onKeyDown = (event) => {
    const target = event.target;
    if (target instanceof HTMLElement && target.closest('input, textarea, select'))
      return;
    if (event.key === 'Delete') {
      const removed = api.removeRows(api.getSelectedKeys());
      if (removed > 0)
        log(`Delete: deleted ${removed} rows`);
    }
    else if (event.altKey && event.code === 'KeyN') {
      event.preventDefault();
      const row = create('New task');
      api.addRows([row], 0);
      reveal(api, row.id);
      log(`Alt+N: added ${row.task} at the top`);
    }
  };
  document.addEventListener('keydown', onKeyDown);
  return () => document.removeEventListener('keydown', onKeyDown);
}
export const actions = {
  addBottom: (api) => {
    const row = create('New task');
    api.addRows([row]);
    reveal(api, row.id);
    say(`Added ${row.task} at the bottom and selected it`);
  },
  addTop: (api) => {
    const row = create('Urgent task');
    api.addRows([row], 0);
    reveal(api, row.id);
    say(`Added ${row.task} at the top and selected it`);
  },
  // With sorting on, the row lands in its sorted position, so find that position first and then scroll.
  addSorted: (api) => {
    const row = create('Sorted task');
    api.setSortModel([{ columnId: 'task', direction: 'asc' }]);
    api.addRows([row]);
    reveal(api, row.id);
    say(`Sorted by task name and added ${row.task} in place (row ${api.getVisibleIndexOfKey(row.id) + 1})`);
  },
  clearSort: (api) => {
    api.setSortModel([]);
    say('Sort cleared');
  },
};