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

트리에서 값 고치기와 다른 조직 아래로 옮기기Edit values in a tree and move a node under another parent

조직 트리에서 이름과 인원을 직접 고치면 위 단계 합계가 바뀌고, 조직을 고른 다른 조직 아래로 옮겨요. 자기 아래로는 옮길 수 없어요.Edit names and headcounts in an org tree and watch parent sums change; move a unit under another parent. Moving it under itself is refused.

활용Intermediate
직접 써 보기Live preview트리에서 값 고치기와 다른 조직 아래로 옮기기Edit values in a tree and move a node under another parent

코드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="who">
      <option value="1">개발본부</option>
      <option value="2">플랫폼팀</option>
      <option value="3">인프라파트</option>
      <option value="4">데이터파트</option>
      <option value="5" selected>모바일팀</option>
      <option value="6">디자인본부</option>
      <option value="7">브랜드팀</option>
    </select>
    <select aria-label="새 위치" id="where">
      <option value="0">맨 위 (부모 없음)</option>
      <option value="1">개발본부 아래</option>
      <option value="2">플랫폼팀 아래</option>
      <option value="6" selected>디자인본부 아래</option>
      <option value="3">인프라파트 아래</option>
      <option value="4">데이터파트 아래</option>
      <option value="5">모바일팀 아래</option>
      <option value="7">브랜드팀 아래</option>
    </select>
    <button type="button" id="move">옮기기</button>
    <button type="button" id="addTeam">새 파트 추가</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('who').addEventListener('change', (event) => actions.who(api, event.target.value));
document.getElementById('where').addEventListener('change', (event) => actions.where(api, event.target.value));
document.getElementById('move').addEventListener('click', () => actions.move(api));
document.getElementById('addTeam').addEventListener('click', () => actions.addTeam(api));
example.js
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
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 eunNeun = (word) => (batchim(word) ? '은' : '는');
const iGa = (word) => (batchim(word) ? '이' : '가');
const eulReul = (word) => (batchim(word) ? '을' : '를');
const rows = [
  { id: 1, parentId: null, name: '개발본부', headcount: 0 },
  { id: 2, parentId: 1, name: '플랫폼팀', headcount: 0 },
  { id: 3, parentId: 2, name: '인프라파트', headcount: 6 },
  { id: 4, parentId: 2, name: '데이터파트', headcount: 5 },
  { id: 5, parentId: 1, name: '모바일팀', headcount: 8 },
  { id: 6, parentId: null, name: '디자인본부', headcount: 0 },
  { id: 7, parentId: 6, name: '브랜드팀', headcount: 4 },
];
// 이름과 인원은 직접 고칠 수 있고, 위 단계 줄에는 아래 줄의 인원 합계(aggregate)가 보여요.
export const options = {
  columns: [
    { id: 'name', title: '조직', width: 200, editable: true, validation: { required: true } },
    {
      id: 'headcount',
      title: '인원',
      kind: 'number',
      width: 100,
      align: 'end',
      editable: true,
      validation: { min: 0 },
      aggregate: 'sum',
    },
  ],
  rows,
  rowKey: 'id',
  tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all', parentAggregates: true },
};
let who = 5;
let where = 6;
let added = 0;
let say = () => { };
export function setup(api, log) {
  say = log;
  added = 0;
  return api.on('editCommitted', ({ rowKey, columnId, oldValue, newValue }) => {
    const row = api.getRowByKey(rowKey);
    const title = columnId === 'name' ? '이름' : '인원';
    log({
      ko: `${row?.name ?? rowKey}의 ${title}: ${String(oldValue)} → ${String(newValue)}`,
      en: `${row?.name ?? rowKey} ${title}: ${String(oldValue)} → ${String(newValue)}`,
    });
  });
}
const isUnder = (api, id, ancestor) => {
  for (let at = api.getRowByKey(id); at; at = at.parentId === null ? undefined : api.getRowByKey(at.parentId)) {
    if (at.id === ancestor)
      return true;
  }
  return false;
};
// 그리드에는 끌어서 옮기는 기능이 없어서, 부모를 바꾸는 것은 데이터를 바꾸는 일이에요: 새 부모의 id를 써 넣어요.
// 자기 자신이나 자기 자손 밑으로 옮기면 부모-자식이 서로 맞물려 끝나지 않으니 막아요.
function move(api) {
  const row = api.getRowByKey(who);
  const target = where === 0 ? null : api.getRowByKey(where);
  if (!row)
    return;
  const newParent = where === 0 ? null : where;
  if (where !== 0 && !target)
    return;
  if (row.parentId === newParent) {
    return say({
      ko: newParent === null
        ? `${row.name}${iGa(row.name)} 이미 맨 위에 있어요.`
        : `${row.name}${iGa(row.name)} 이미 그 아래에 있어요.`,
      en: newParent === null
        ? `${row.name} is already at the top.`
        : `${row.name} is already under that row.`,
    });
  }
  if (newParent !== null && isUnder(api, newParent, who)) {
    return say({
      ko: `${row.name}${eulReul(row.name)} 자기 자손 밑으로는 못 옮겨요.`,
      en: `${row.name} cannot move under its own descendant.`,
    });
  }
  api.updateRows([{ ...row, parentId: newParent }]);
  if (newParent !== null)
    api.revealRow(who);
  say({
    ko: newParent === null
      ? `${row.name}${eunNeun(row.name)} 맨 위로 옮겼어요.`
      : `${row.name}${eunNeun(row.name)} ${target?.name ?? ''} 아래로 옮겼어요.`,
    en: newParent === null
      ? `Moved ${row.name} to the top.`
      : `Moved ${row.name} under ${target?.name ?? ''}.`,
  });
}
export const actions = {
  who: (_api, value) => void (who = Number(value ?? '5')),
  where: (_api, value) => void (where = Number(value ?? '6')),
  move: (api) => move(api),
  addTeam: (api) => {
    added += 1;
    const id = Math.max(...api.getRows().map((r) => r.id)) + 1;
    api.addRows([{ id, parentId: 2, name: `새 파트 ${added}`, headcount: 3 }]);
    api.revealRow(id);
    say({
      ko: `플랫폼팀 아래에 새 파트 ${added}${eulReul(String(added))} 추가했어요.`,
      en: `Added a new part ${added} under the Platform team.`,
    });
  },
};

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="Unit to move" id="who">
      <option value="1">Dev division</option>
      <option value="2">Platform team</option>
      <option value="3">Infra part</option>
      <option value="4">Data part</option>
      <option value="5" selected>Mobile team</option>
      <option value="6">Design division</option>
      <option value="7">Brand team</option>
    </select>
    <select aria-label="New place" id="where">
      <option value="0">Top level</option>
      <option value="1">Under dev division</option>
      <option value="2">Under platform team</option>
      <option value="6" selected>Under design division</option>
      <option value="3">Under infra part</option>
      <option value="4">Under data part</option>
      <option value="5">Under mobile team</option>
      <option value="7">Under brand team</option>
    </select>
    <button type="button" id="move">Move</button>
    <button type="button" id="addTeam">Add part</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('who').addEventListener('change', (event) => actions.who(api, event.target.value));
document.getElementById('where').addEventListener('change', (event) => actions.where(api, event.target.value));
document.getElementById('move').addEventListener('click', () => actions.move(api));
document.getElementById('addTeam').addEventListener('click', () => actions.addTeam(api));
example.js
const rows = [
  { id: 1, parentId: null, name: 'Dev Division', headcount: 0 },
  { id: 2, parentId: 1, name: 'Platform Team', headcount: 0 },
  { id: 3, parentId: 2, name: 'Infra Part', headcount: 6 },
  { id: 4, parentId: 2, name: 'Data Part', headcount: 5 },
  { id: 5, parentId: 1, name: 'Mobile Team', headcount: 8 },
  { id: 6, parentId: null, name: 'Design Division', headcount: 0 },
  { id: 7, parentId: 6, name: 'Brand Team', headcount: 4 },
];
// Names and headcounts can be edited directly, and parent rows show the sum (aggregate) of the headcounts below them.
export const options = {
  columns: [
    { id: 'name', title: 'Unit', width: 200, editable: true, validation: { required: true } },
    {
      id: 'headcount',
      title: 'Headcount',
      kind: 'number',
      width: 110,
      align: 'end',
      editable: true,
      validation: { min: 0 },
      aggregate: 'sum',
    },
  ],
  rows,
  rowKey: 'id',
  tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all', parentAggregates: true },
};
let who = 5;
let where = 6;
let added = 0;
let say = () => { };
export function setup(api, log) {
  say = log;
  added = 0;
  return api.on('editCommitted', ({ rowKey, columnId, oldValue, newValue }) => {
    const row = api.getRowByKey(rowKey);
    const title = columnId === 'name' ? 'name' : 'headcount';
    log(`${row?.name ?? rowKey} ${title}: ${String(oldValue)} → ${String(newValue)}`);
  });
}
const isUnder = (api, id, ancestor) => {
  for (let at = api.getRowByKey(id); at; at = at.parentId === null ? undefined : api.getRowByKey(at.parentId)) {
    if (at.id === ancestor)
      return true;
  }
  return false;
};
// The grid has no drag-to-move here, so changing the parent means changing the data: write the new parent's id.
// Moving a row under itself or its own descendant would make parent and child loop forever, so it is refused.
function move(api) {
  const row = api.getRowByKey(who);
  const target = where === 0 ? null : api.getRowByKey(where);
  if (!row)
    return;
  const newParent = where === 0 ? null : where;
  if (where !== 0 && !target)
    return;
  if (row.parentId === newParent) {
    return say(newParent === null
      ? `${row.name} is already at the top.`
      : `${row.name} is already under that row.`);
  }
  if (newParent !== null && isUnder(api, newParent, who)) {
    return say(`${row.name} cannot move under its own descendant.`);
  }
  api.updateRows([{ ...row, parentId: newParent }]);
  if (newParent !== null)
    api.revealRow(who);
  say(newParent === null
    ? `Moved ${row.name} to the top.`
    : `Moved ${row.name} under ${target?.name ?? ''}.`);
}
export const actions = {
  who: (_api, value) => void (who = Number(value ?? '5')),
  where: (_api, value) => void (where = Number(value ?? '6')),
  move: (api) => move(api),
  addTeam: (api) => {
    added += 1;
    const id = Math.max(...api.getRows().map((r) => r.id)) + 1;
    api.addRows([{ id, parentId: 2, name: `New part ${added}`, headcount: 3 }]);
    api.revealRow(id);
    say(`Added a new part ${added} under the Platform team.`);
  },
};