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

조건에 따라 편집 막기Lock cells depending on conditions

줄마다 규칙으로 편집 가능 여부를 정할 수 있어요. 발송된 주문은 메모를 잠그고, 접수 상태일 때만 금액을 고치게 하는 식이에요. 상태를 바꾸면 규칙이 바로 적용돼요.You can decide per row whether a cell can be edited. A shipped order locks its memo, and the amount is editable only while the status is received. Changing the status applies the rule at once.

활용Intermediate
직접 써 보기Live preview조건에 따라 편집 막기Lock cells depending on conditions

코드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="rule">
      <option value="status" selected>상태에 따라</option>
      <option value="open">모두 열기</option>
      <option value="locked">모두 잠그기</option>
    </select>
  </div>
  <div id="grid" style="height: 300px"></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('rule').addEventListener('change', (event) => actions.rule(api, event.target.value));
example.js
const rows = [
  { id: 1, order: 'A-1001', status: 'open', note: '선물 포장 요청', amount: 120000 },
  { id: 2, order: 'A-1002', status: 'packed', note: '배송 전에 전화 주세요', amount: 80000 },
  { id: 3, order: 'A-1003', status: 'shipped', note: '문 앞에 두었어요', amount: 45000 },
  { id: 4, order: 'A-1004', status: 'open', note: '', amount: 260000 },
  { id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99000 },
  { id: 6, order: 'A-1006', status: 'shipped', note: '경비실 보관', amount: 31000 },
];
let rule = 'status';
const statusLabel = { open: '접수', packed: '포장', shipped: '발송' };
// editable에 함수를 주면 줄마다 고칠 수 있는지가 달라져요. 편집을 시작할 때마다 함수를 다시 읽기 때문에
// 상태를 바꾸는 즉시 규칙이 적용돼요. 규칙(rule)을 "모두 열기"나 "모두 잠그기"로 바꾸면 컬럼 정의를 새로 넣어요.
const noteEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = () => [
  { id: 'order', title: '주문', width: 100 },
  {
    id: 'status',
    title: '상태',
    kind: 'select',
    width: 100,
    editable: rule !== 'locked',
    editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
    formatValue: (value) => statusLabel[String(value)] ?? String(value), // 칸에도 코드(open) 대신 이름(접수)을 보여 줘요.
  },
  { id: 'note', title: '메모 (발송 전만)', width: 190, editable: noteEditable },
  {
    id: 'amount',
    title: '금액 (접수 상태만)',
    kind: 'number',
    width: 140,
    align: 'end',
    editable: amountEditable,
    formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
  },
  // 잠겼는지 한눈에 보도록 같은 규칙으로 계산한 칸을 하나 더 두었어요(저장하지 않고 getValue로 계산).
  {
    id: 'lock',
    title: '메모·금액',
    width: 110,
    getValue: (row) => `${noteEditable(row) ? '메모 ✓' : '메모 ✗'} ${amountEditable(row) ? '금액 ✓' : '금액 ✗'}`,
  },
];
export const options = {
  columns: columns(),
  rows,
  rowKey: 'id',
};
// 잠긴 칸을 더블클릭하면 아무 일도 안 일어나는 것처럼 보이기 쉬워서, 왜 안 열리는지 기록에 알려 줘요.
const titleOf = (api, id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id, value) => id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api, log) {
  log({
    ko: '"메모"와 "금액" 칸을 더블클릭해 보세요. 상태에 따라 열리거나 열리지 않아요.',
    en: 'Double-click a "메모" (note) or "금액" (amount) cell. Whether it opens depends on the status.',
  });
  const offs = [
    api.on('editStarted', (e) => log({
      ko: `${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)} 편집을 시작했어요`,
      en: `Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`,
    })),
    api.on('editCommitted', (e) => {
      const order = api.getRowByKey(e.rowKey)?.order;
      log(`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`);
      // 상태를 바꾸면 잠금 표시 칸이 바로 다시 계산되도록 줄을 다시 그려요.
      if (e.columnId === 'status')
        api.refresh();
    }),
    api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
      const row = api.getRowByKey(rowKey);
      if (!row || !['status', 'note', 'amount'].includes(columnId))
        return;
      const ok = columnId === 'note'
        ? noteEditable(row)
        : columnId === 'amount'
          ? amountEditable(row)
          : rule !== 'locked';
      if (ok)
        return;
      const why = rule === 'locked'
        ? '지금은 "모두 잠그기"라서 모든 칸을 고칠 수 없어요.'
        : columnId === 'note'
          ? `${statusLabel[row.status]} 상태에서는 메모를 고칠 수 없어요(발송 전에만 가능해요).`
          : `${statusLabel[row.status]} 상태에서는 금액을 고칠 수 없어요(접수 상태일 때만 가능해요).`;
      log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
    }),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  rule: (api, value) => {
    rule = (value ?? 'status');
    api.setColumns(columns());
  },
};

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="Lock rule" id="rule">
      <option value="status" selected>By status</option>
      <option value="open">Open all</option>
      <option value="locked">Lock all</option>
    </select>
  </div>
  <div id="grid" style="height: 300px"></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('rule').addEventListener('change', (event) => actions.rule(api, event.target.value));
example.js
const rows = [
  { id: 1, order: 'A-1001', status: 'open', note: 'Gift wrap requested', amount: 120 },
  { id: 2, order: 'A-1002', status: 'packed', note: 'Call before delivery', amount: 80 },
  { id: 3, order: 'A-1003', status: 'shipped', note: 'Left at the door', amount: 45 },
  { id: 4, order: 'A-1004', status: 'open', note: '', amount: 260 },
  { id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99 },
  { id: 6, order: 'A-1006', status: 'shipped', note: 'Kept at the front desk', amount: 31 },
];
let rule = 'status';
const statusLabel = {
  open: 'Received',
  packed: 'Packed',
  shipped: 'Shipped',
};
// When editable is a function, whether a row can be edited differs per row. The function is read again each time editing starts,
// so a rule applies as soon as the status changes. Switching the rule to "Open all" or "Lock all" passes in new column definitions.
const noteEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = () => [
  { id: 'order', title: 'Order', width: 100 },
  {
    id: 'status',
    title: 'Status',
    kind: 'select',
    width: 110,
    editable: rule !== 'locked',
    editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
    formatValue: (value) => statusLabel[String(value)] ?? String(value), // The cell also shows the name (Received) instead of the code (open).
  },
  { id: 'note', title: 'Note (before shipping only)', width: 220, editable: noteEditable },
  {
    id: 'amount',
    title: 'Amount (Received only)',
    kind: 'number',
    width: 180,
    align: 'end',
    editable: amountEditable,
    formatValue: (v) => `$${Number(v).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
  },
  // One more cell computed with the same rules so the lock state is visible at a glance (not stored; computed with getValue).
  {
    id: 'lock',
    title: 'Note / Amount',
    width: 150,
    getValue: (row) => `${noteEditable(row) ? 'Note ✓' : 'Note ✗'} ${amountEditable(row) ? 'Amount ✓' : 'Amount ✗'}`,
  },
];
export const options = {
  columns: columns(),
  rows,
  rowKey: 'id',
};
// Double-clicking a locked cell can look like nothing happens, so the log explains why it does not open.
const titleOf = (api, id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id, value) => id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api, log) {
  log('Double-click a "Note" or "Amount" cell. Whether it opens depends on the status.');
  const offs = [
    api.on('editStarted', (e) => log(`Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`)),
    api.on('editCommitted', (e) => {
      const order = api.getRowByKey(e.rowKey)?.order;
      log(`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`);
      // Redraw rows so the lock-state cell is recomputed right after the status changes.
      if (e.columnId === 'status')
        api.refresh();
    }),
    api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
      const row = api.getRowByKey(rowKey);
      if (!row || !['status', 'note', 'amount'].includes(columnId))
        return;
      const ok = columnId === 'note'
        ? noteEditable(row)
        : columnId === 'amount'
          ? amountEditable(row)
          : rule !== 'locked';
      if (ok)
        return;
      const why = rule === 'locked'
        ? 'The rule is "Lock all" right now, so no cell can be edited.'
        : columnId === 'note'
          ? `The note cannot be edited in the ${statusLabel[row.status]} status (only before shipping).`
          : `The amount cannot be edited in the ${statusLabel[row.status]} status (only while Received).`;
      log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
    }),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  rule: (api, value) => {
    rule = (value ?? 'status');
    api.setColumns(columns());
  },
};