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

줄 안의 버튼: 상세 보기와 삭제Buttons inside a row: details and delete

표의 줄마다 "상세"와 "삭제" 버튼을 넣어요. 버튼을 누르면 그 줄에 대한 일을 해요. 지운 줄은 다시 넣을 수 있어요.Put "Details" and "Delete" buttons in every row. Pressing one acts on that row. Deleted rows can be put back.

활용Intermediate
직접 써 보기Live preview줄 안의 버튼: 상세 보기와 삭제Buttons inside a row: details and delete

코드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="restore">지운 줄 되돌리기</button>
  </div>
  <div id="grid" style="height: 260px"></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('restore').addEventListener('click', () => actions.restore(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
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) ? '을' : '를');
// 줄마다 버튼 두 개를 그려요. 버튼에는 data-action만 달고, 누름은 setup에서 cellClicked 한 곳에서 받아 그리드 기능을 불러요.
// 칸마다 따로 이벤트를 달지 않아서 스크롤해도 가벼워요.
const actionsCell = () => {
  let box;
  return {
    mount(el, ctx) {
      box = centered(el);
      for (const [action, label, title] of [
        ['detail', L('상세', 'Details'), L('청구서 내용을 봐요', 'View the invoice')],
        ['delete', L('삭제', 'Delete'), L('이 청구서를 지워요', 'Delete this invoice')],
      ]) {
        const button = document.createElement('button');
        button.type = 'button';
        button.dataset.action = action;
        button.textContent = label;
        button.title = title;
        button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
        box.append(button);
      }
      this.update(ctx);
    },
    // 버튼 이름에 줄의 청구서 번호를 넣어서, 화면 읽기 프로그램이 "INV-401 상세"처럼 읽게 해요.
    update(ctx) {
      for (const button of box.querySelectorAll('button[data-action]')) {
        button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
      }
    },
    destroy() { },
  };
};
const initial = [
  { id: 1, invoice: 'INV-401', customer: '한빛푸드', total: 1280000 },
  { id: 2, invoice: 'INV-402', customer: '파란마켓', total: 460000 },
  { id: 3, invoice: 'INV-403', customer: '단풍상회', total: 3150000 },
  { id: 4, invoice: 'INV-404', customer: '바다유통', total: 90000 },
];
export const options = {
  columns: [
    { id: 'invoice', title: '청구서', width: 100 },
    { id: 'customer', title: '거래처', width: 110 },
    {
      id: 'total',
      title: '금액(원)',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => Number(v).toLocaleString('ko-KR'),
    },
    {
      id: 'actions',
      title: '작업',
      width: 130,
      sortable: false,
      filterable: false,
      getValue: () => '',
      cellRenderer: actionsCell,
    },
  ],
  rows: initial.map((row) => ({ ...row })),
  rowKey: 'id',
  saveMode: 'none',
  ...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted = [];
let say = () => { };
export function setup(api, log) {
  say = log;
  deleted = [];
  log({
    ko: '"상세"는 내용을 기록에 보여 주고, "삭제"는 그 줄을 지워요.',
    en: '"상세" (Details) shows the contents in the log, and "삭제" (Delete) removes the row.',
  });
  return api.on('cellClicked', (e) => {
    const button = e.event.target?.closest('button[data-action]');
    if (e.columnId !== 'actions' || !button)
      return;
    if (button.dataset.action === 'delete') {
      deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
      const gridRoot = button.closest('[role="grid"]');
      api.removeRows([e.rowKey]);
      // 지운 뒤 포커스가 다음 줄의 "삭제" 버튼으로 옮겨 가면 Enter 한 번에 또 지워져요. 포커스를 칸(청구서)에 둬요.
      const left = api.getRows();
      const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
      if (near)
        api.focusCell(near.id, 'invoice');
      gridRoot?.focus(); // 키보드 포커스가 버튼에 남아 있으면 Enter 한 번에 또 지워져요
      log({
        ko: `${e.row.invoice}${eulReul(e.row.invoice)} 지웠어요. "지운 줄 되돌리기"로 다시 넣을 수 있어요.`,
        en: `Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`,
      });
    }
    else {
      log({
        ko: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('ko-KR')}원`,
        en: `${e.row.invoice}: ${e.row.customer}, ${e.row.total.toLocaleString('en-US')} KRW`,
      });
    }
  });
}
export const actions = {
  restore: (api) => {
    if (!deleted.length)
      return say({ ko: '되돌릴 청구서가 없어요.', en: 'No invoice to restore.' });
    const rows = deleted;
    deleted = [];
    // 앞쪽 자리부터 차례로 넣어서, 지우기 전 위치로 돌아가요.
    for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
      api.addRows([row], index);
    say({
      ko: `지운 청구서 ${rows.length}개를 원래 자리에 다시 넣었어요.`,
      en: `Put the ${rows.length} deleted invoices back in their original places.`,
    });
  },
};

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="restore">Put back deleted rows</button>
  </div>
  <div id="grid" style="height: 260px"></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('restore').addEventListener('click', () => actions.restore(api));
example.js
// Tells whether this is a touch screen (phone). On such screens the tap targets grow to 40px or more.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
// Draws two buttons per row. The buttons only carry data-action; presses are handled in one cellClicked handler in setup, which calls grid features.
// No per-cell listeners, so scrolling stays light.
const actionsCell = () => {
  let box;
  return {
    mount(el, ctx) {
      box = centered(el);
      for (const [action, label, title] of [
        ['detail', 'Details', 'View the invoice'],
        ['delete', 'Delete', 'Delete this invoice'],
      ]) {
        const button = document.createElement('button');
        button.type = 'button';
        button.dataset.action = action;
        button.textContent = label;
        button.title = title;
        button.style.cssText = `margin-right: 6px; padding: 0 10px; height: ${coarse() ? 40 : 22}px; min-width: ${coarse() ? 52 : 0}px; font: inherit; font-size: 12px; border: 1px solid var(--mxg-border); border-radius: 4px; background: var(--mxg-bg); color: var(--mxg-fg); cursor: pointer;`;
        box.append(button);
      }
      this.update(ctx);
    },
    // Put the row's invoice number in the button name so a screen reader says e.g. "INV-401 Details".
    update(ctx) {
      for (const button of box.querySelectorAll('button[data-action]')) {
        button.setAttribute('aria-label', `${ctx.row.invoice} ${button.textContent ?? ''}`);
      }
    },
    destroy() { },
  };
};
const initial = [
  { id: 1, invoice: 'INV-401', customer: 'Bright Foods', total: 1280 },
  { id: 2, invoice: 'INV-402', customer: 'Blue Market', total: 460 },
  { id: 3, invoice: 'INV-403', customer: 'Maple Trading', total: 3150 },
  { id: 4, invoice: 'INV-404', customer: 'Ocean Distribution', total: 90 },
];
export const options = {
  columns: [
    { id: 'invoice', title: 'Invoice', width: 100 },
    { id: 'customer', title: 'Customer', width: 110 },
    {
      id: 'total',
      title: 'Total ($)',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => Number(v).toLocaleString('en-US'),
    },
    {
      id: 'actions',
      title: 'Actions',
      width: 130,
      sortable: false,
      filterable: false,
      getValue: () => '',
      cellRenderer: actionsCell,
    },
  ],
  rows: initial.map((row) => ({ ...row })),
  rowKey: 'id',
  saveMode: 'none',
  ...(coarse() ? { rowHeight: 44 } : {}),
};
let deleted = [];
let say = () => { };
export function setup(api, log) {
  say = log;
  deleted = [];
  log('"Details" shows the contents in the log, and "Delete" removes the row.');
  return api.on('cellClicked', (e) => {
    const button = e.event.target?.closest('button[data-action]');
    if (e.columnId !== 'actions' || !button)
      return;
    if (button.dataset.action === 'delete') {
      deleted.push({ row: e.row, index: api.getRows().findIndex((r) => r.id === e.row.id) });
      const gridRoot = button.closest('[role="grid"]');
      api.removeRows([e.rowKey]);
      // If focus moved to the next row's "Delete" button after removing, one Enter would delete again. Keep focus on a cell (invoice).
      const left = api.getRows();
      const near = left[Math.min(deleted[deleted.length - 1]?.index ?? 0, left.length - 1)];
      if (near)
        api.focusCell(near.id, 'invoice');
      gridRoot?.focus(); // If keyboard focus stays on a button, one Enter would delete again
      log(`Deleted ${e.row.invoice}. "Restore deleted rows" can put it back.`);
    }
    else {
      log(`${e.row.invoice}: ${e.row.customer}, $${e.row.total.toLocaleString('en-US')}`);
    }
  });
}
export const actions = {
  restore: (api) => {
    if (!deleted.length)
      return say('No invoice to restore.');
    const rows = deleted;
    deleted = [];
    // Insert from the front so each row returns to its position before deletion.
    for (const { row, index } of [...rows].sort((a, b) => a.index - b.index))
      api.addRows([row], index);
    say(`Put the ${rows.length} deleted invoices back in their original places.`);
  },
};