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

엑셀처럼 칸을 끌어서 고르기Drag to pick cells like a spreadsheet

칸을 끌면 구간이 골라지고, Shift+클릭으로 넓히고, Ctrl+클릭으로 구간을 더할 수 있어요. 행 단위·한 칸 단위·선택 끄기도 설정 한 줄로 바꿔요.Drag to pick a block of cells, widen it with Shift+click and add another block with Ctrl+click. Row-only, single-cell and no-selection modes are one setting away.

입문Beginner
직접 써 보기Live preview엑셀처럼 칸을 끌어서 고르기Drag to pick cells like a spreadsheet

코드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">
    <select aria-label="선택 방식" id="mode">
      <option value="cell-multiple" selected>칸 여러 구간 (기본)</option>
      <option value="cell-single">칸 하나</option>
      <option value="row-single">행 하나</option>
      <option value="row-multiple">행 여러 개</option>
      <option value="none">선택 끄기</option>
    </select>
    <button type="button" id="report">고른 구간 알려 주기</button>
    <button type="button" id="pickBlock">코드로 구간 고르기</button>
    <button type="button" id="pickCell">코드로 한 칸 고르기</button>
    <button type="button" id="clear">선택 지우기</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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('report').addEventListener('click', () => actions.report(api));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickCell').addEventListener('click', () => actions.pickCell(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
// 카페 메뉴별 분기 판매량(잔). 칸을 끌어서 구간을 고르는 연습용 표예요.
const menus = [
  '아메리카노',
  '카페라떼',
  '바닐라라떼',
  '콜드브루',
  '카푸치노',
  '녹차라떼',
  '딸기스무디',
  '레몬에이드',
  '허니브레드',
  '치즈케이크',
];
// cellSelection: 'multiple'이면 칸을 끌어서 구간을 고르고, Shift+클릭으로 구간을 넓히고,
// Ctrl+클릭(또는 Ctrl+끌기)으로 구간을 더해요. 행 선택(selection)과는 따로 켜고 끄고, 함께 써도 돼요.
export const options = {
  columns: [
    { id: 'menu', title: '메뉴', width: 140 },
    ...['q1', 'q2', 'q3', 'q4'].map((id, i) => ({
      id,
      title: `${i + 1}분기`,
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    })),
  ],
  rows: menus.map((menu, i) => ({
    id: i + 1,
    menu,
    q1: 1200 + ((i * 370) % 900),
    q2: 1450 + ((i * 290) % 800),
    q3: 980 + ((i * 410) % 1100),
    q4: 1800 + ((i * 230) % 700),
  })),
  rowKey: 'id',
  cellSelection: 'multiple',
};
const MODES = {
  'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
  'cell-single': { cellSelection: 'single', selection: 'none' },
  'row-single': { cellSelection: 'none', selection: 'single' },
  'row-multiple': { cellSelection: 'none', selection: 'multiple' },
  none: { cellSelection: 'none', selection: 'none' },
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say = () => { };
const NEED_MULTIPLE = {
  ko: "이 방식에서는 코드로 고를 수 없어요. 위 '선택 방식'을 칸 모드로 바꿔 보세요",
  en: "This mode cannot select by code. Switch 'Selection mode' above to a cell mode",
};
export function setup(api, log) {
  say = log;
  const offCells = api.on('cellSelectionChanged', ({ ranges }) => log({
    ko: `고른 칸 ${api.getSelectedCells().length}개 (구간 ${ranges.length}개)`,
    en: `Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`,
  }));
  const offRows = api.on('selectionChanged', ({ selectedKeys }) => log({ ko: `고른 행 ${selectedKeys.length}개`, en: `Selected rows: ${selectedKeys.length}` }));
  return () => {
    offCells();
    offRows();
  };
}
// 칸 이름을 "메뉴·행번호 / 컬럼 제목" 꼴로 읽기 좋게 바꿔요.
const label = (api, ref) => {
  const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
  return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey}의 ${title}`;
};
export const actions = {
  // 선택 방식을 바꿔요. 바꾸기 전에 이전 선택은 지워요.
  mode: (api, value) => {
    api.clearCellSelection();
    api.clearSelection();
    api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']);
  },
  // 지금 고른 구간이 어디서 어디까지인지 알려 줘요(getCellRanges).
  report: (api) => {
    const ranges = api.getCellRanges();
    say({
      ko: ranges.length === 0
        ? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
        : ranges
          .map((r) => {
          const a = label(api, r.from);
          const b = label(api, r.to);
          return a === b ? a : `${a} ~ ${b}`;
        })
          .join(' / '),
      en: ranges.length === 0
        ? 'No cells selected. Drag across some cells first'
        : ranges
          .map((r) => {
          const a = label(api, r.from);
          const b = label(api, r.to);
          return a === b ? a : `${a} ~ ${b}`;
        })
          .join(' / '),
    });
  },
  // 코드로 구간을 골라요: 2행 1분기부터 4행 3분기까지. 칸 선택이 꺼져 있으면 알려 줘요.
  pickBlock: (api) => {
    if (api.getOptions().cellSelection !== 'multiple')
      return say(NEED_MULTIPLE);
    api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
  },
  // 칸 하나만 골라요.
  pickCell: (api) => {
    if (api.getOptions().cellSelection === 'none')
      return say(NEED_MULTIPLE);
    api.selectCells({ rowKey: 5, columnId: 'q2' });
  },
  clear: (api) => {
    api.clearCellSelection();
    api.clearSelection();
  },
};

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">
    <select aria-label="Selection mode" id="mode">
      <option value="cell-multiple" selected>Many blocks of cells</option>
      <option value="cell-single">One cell</option>
      <option value="row-single">One row</option>
      <option value="row-multiple">Many rows</option>
      <option value="none">No selection</option>
    </select>
    <button type="button" id="report">Tell me the selection</button>
    <button type="button" id="pickBlock">Pick a block in code</button>
    <button type="button" id="pickCell">Pick one cell in code</button>
    <button type="button" id="clear">Clear selection</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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('report').addEventListener('click', () => actions.report(api));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickCell').addEventListener('click', () => actions.pickCell(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
// Quarterly cups sold per cafe menu item. A practice table for selecting ranges by dragging cells.
const menus = [
  'Americano',
  'Cafe Latte',
  'Vanilla Latte',
  'Cold Brew',
  'Cappuccino',
  'Green Tea Latte',
  'Strawberry Smoothie',
  'Lemonade',
  'Honey Bread',
  'Cheesecake',
];
// With cellSelection: 'multiple', drag across cells to pick a range, Shift+click to extend it,
// and Ctrl+click (or Ctrl+drag) to add another range. It is switched on and off separately from row selection (selection), and both can be used together.
export const options = {
  columns: [
    { id: 'menu', title: 'Menu', width: 170 },
    ...['q1', 'q2', 'q3', 'q4'].map((id, i) => ({
      id,
      title: `Q${i + 1}`,
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    })),
  ],
  rows: menus.map((menu, i) => ({
    id: i + 1,
    menu,
    q1: 1200 + ((i * 370) % 900),
    q2: 1450 + ((i * 290) % 800),
    q3: 980 + ((i * 410) % 1100),
    q4: 1800 + ((i * 230) % 700),
  })),
  rowKey: 'id',
  cellSelection: 'multiple',
};
const MODES = {
  'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
  'cell-single': { cellSelection: 'single', selection: 'none' },
  'row-single': { cellSelection: 'none', selection: 'single' },
  'row-multiple': { cellSelection: 'none', selection: 'multiple' },
  none: { cellSelection: 'none', selection: 'none' },
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say = () => { };
const NEED_MULTIPLE = "This mode cannot select by code. Switch 'Selection mode' above to a cell mode";
export function setup(api, log) {
  say = log;
  const offCells = api.on('cellSelectionChanged', ({ ranges }) => log(`Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`));
  const offRows = api.on('selectionChanged', ({ selectedKeys }) => log(`Selected rows: ${selectedKeys.length}`));
  return () => {
    offCells();
    offRows();
  };
}
// Turn a cell reference into a readable "menu item / column title" label.
const label = (api, ref) => {
  const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
  return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey} ${title}`;
};
export const actions = {
  // Change the selection mode. The previous selection is cleared first.
  mode: (api, value) => {
    api.clearCellSelection();
    api.clearSelection();
    api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']);
  },
  // Report where the current ranges start and end (getCellRanges).
  report: (api) => {
    const ranges = api.getCellRanges();
    say(ranges.length === 0
      ? 'No cells selected. Drag across some cells first'
      : ranges
        .map((r) => {
        const a = label(api, r.from);
        const b = label(api, r.to);
        return a === b ? a : `${a} ~ ${b}`;
      })
        .join(' / '));
  },
  // Select a range by code: from row 2 Q1 to row 4 Q3. Tell the user if cell selection is off.
  pickBlock: (api) => {
    if (api.getOptions().cellSelection !== 'multiple')
      return say(NEED_MULTIPLE);
    api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
  },
  // Select a single cell.
  pickCell: (api) => {
    if (api.getOptions().cellSelection === 'none')
      return say(NEED_MULTIPLE);
    api.selectCells({ rowKey: 5, columnId: 'q2' });
  },
  clear: (api) => {
    api.clearCellSelection();
    api.clearSelection();
  },
};