트리에서 값 고치기와 다른 조직 아래로 옮기기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.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
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.`,
});
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>트리에서 값 고치기와 다른 조직 아래로 옮기기</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
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)가 보여요.
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 = () => { };
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 ?? ''}.`,
});
}
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.`,
});
},
};
options.ariaLabel = "트리에서 값 고치기와 다른 조직 아래로 옮기기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
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));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="옮길 조직"
disabled={!api}
onChange={(event) => api && actions.who(api, event.target.value)}
>
<option value="1">개발본부</option>
<option value="2">플랫폼팀</option>
<option value="3">인프라파트</option>
<option value="4">데이터파트</option>
<option value="5">모바일팀</option>
<option value="6">디자인본부</option>
<option value="7">브랜드팀</option>
</select>
<select defaultValue="5"
aria-label="새 위치"
disabled={!api}
onChange={(event) => api && actions.where(api, event.target.value)}
>
<option value="0">맨 위 (부모 없음)</option>
<option value="1">개발본부 아래</option>
<option value="2">플랫폼팀 아래</option>
<option value="6">디자인본부 아래</option>
<option value="3">인프라파트 아래</option>
<option value="4">데이터파트 아래</option>
<option value="5">모바일팀 아래</option>
<option value="7">브랜드팀 아래</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.move(api)}
>옮기기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.addTeam(api)}
>새 파트 추가</button>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
headcount: number;
}
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
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: string): string => (batchim(word) ? '은' : '는');
const iGa = (word: string): string => (batchim(word) ? '이' : '가');
const eulReul = (word: string): string => (batchim(word) ? '을' : '를');
const rows: Row[] = [
{ 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, id: number, ancestor: number): boolean => {
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: GridApi<Row>): void {
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: GridApi<Row>, value?: string) => void (who = Number(value ?? '5')),
where: (_api: GridApi<Row>, value?: string) => void (where = Number(value ?? '6')),
move: (api: GridApi<Row>) => move(api),
addTeam: (api: GridApi<Row>) => {
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.`,
});
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="옮길 조직"
:disabled="!api"
@change="api && actions.who(api, ($event.target as HTMLSelectElement).value)"
>
<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="새 위치"
:disabled="!api"
@change="api && actions.where(api, ($event.target as HTMLSelectElement).value)"
>
<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" :disabled="!api" @click="api && actions.move(api)">옮기기</button>
<button type="button" :disabled="!api" @click="api && actions.addTeam(api)">새 파트 추가</button>
</div>
<Grid style="height: 360px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
headcount: number;
}
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
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: string): string => (batchim(word) ? '은' : '는');
const iGa = (word: string): string => (batchim(word) ? '이' : '가');
const eulReul = (word: string): string => (batchim(word) ? '을' : '를');
const rows: Row[] = [
{ 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, id: number, ancestor: number): boolean => {
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: GridApi<Row>): void {
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: GridApi<Row>, value?: string) => void (who = Number(value ?? '5')),
where: (_api: GridApi<Row>, value?: string) => void (where = Number(value ?? '6')),
move: (api: GridApi<Row>) => move(api),
addTeam: (api: GridApi<Row>) => {
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.`,
});
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="옮길 조직"
[disabled]="!api"
(change)="api && actions.who(api, $any($event.target).value)"
>
<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="새 위치"
[disabled]="!api"
(change)="api && actions.where(api, $any($event.target).value)"
>
<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"
[disabled]="!api"
(click)="api && actions.move(api)"
>옮기기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.addTeam(api)"
>새 파트 추가</button>
</div>
<mx-grid style="height: 360px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
headcount: number;
}
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
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: string): string => (batchim(word) ? '은' : '는');
const iGa = (word: string): string => (batchim(word) ? '이' : '가');
const eulReul = (word: string): string => (batchim(word) ? '을' : '를');
const rows: Row[] = [
{ 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, id: number, ancestor: number): boolean => {
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: GridApi<Row>): void {
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: GridApi<Row>, value?: string) => void (who = Number(value ?? '5')),
where: (_api: GridApi<Row>, value?: string) => void (where = Number(value ?? '6')),
move: (api: GridApi<Row>) => move(api),
addTeam: (api: GridApi<Row>) => {
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.`,
});
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<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>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));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.`);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Edit values in a tree and move a node under another parent</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
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.
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 = () => { };
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 ?? ''}.`);
}
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.`);
},
};
options.ariaLabel = "Edit values in a tree and move a node under another parent";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
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));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="Unit to move"
disabled={!api}
onChange={(event) => api && actions.who(api, event.target.value)}
>
<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">Mobile team</option>
<option value="6">Design division</option>
<option value="7">Brand team</option>
</select>
<select defaultValue="5"
aria-label="New place"
disabled={!api}
onChange={(event) => api && actions.where(api, event.target.value)}
>
<option value="0">Top level</option>
<option value="1">Under dev division</option>
<option value="2">Under platform team</option>
<option value="6">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"
disabled={!api}
onClick={() => api && actions.move(api)}
>Move</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.addTeam(api)}
>Add part</button>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
headcount: number;
}
const rows: Row[] = [
{ 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, id: number, ancestor: number): boolean => {
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: GridApi<Row>): void {
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: GridApi<Row>, value?: string) => void (who = Number(value ?? '5')),
where: (_api: GridApi<Row>, value?: string) => void (where = Number(value ?? '6')),
move: (api: GridApi<Row>) => move(api),
addTeam: (api: GridApi<Row>) => {
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.`);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="Unit to move"
:disabled="!api"
@change="api && actions.who(api, ($event.target as HTMLSelectElement).value)"
>
<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"
:disabled="!api"
@change="api && actions.where(api, ($event.target as HTMLSelectElement).value)"
>
<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" :disabled="!api" @click="api && actions.move(api)">Move</button>
<button type="button" :disabled="!api" @click="api && actions.addTeam(api)">Add part</button>
</div>
<Grid style="height: 360px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
headcount: number;
}
const rows: Row[] = [
{ 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, id: number, ancestor: number): boolean => {
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: GridApi<Row>): void {
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: GridApi<Row>, value?: string) => void (who = Number(value ?? '5')),
where: (_api: GridApi<Row>, value?: string) => void (where = Number(value ?? '6')),
move: (api: GridApi<Row>) => move(api),
addTeam: (api: GridApi<Row>) => {
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.`);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="Unit to move"
[disabled]="!api"
(change)="api && actions.who(api, $any($event.target).value)"
>
<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"
[disabled]="!api"
(change)="api && actions.where(api, $any($event.target).value)"
>
<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"
[disabled]="!api"
(click)="api && actions.move(api)"
>Move</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.addTeam(api)"
>Add part</button>
</div>
<mx-grid style="height: 360px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
parentId: number | null;
name: string;
headcount: number;
}
const rows: Row[] = [
{ 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>, id: number, ancestor: number): boolean => {
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: GridApi<Row>): void {
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: GridApi<Row>, value?: string) => void (who = Number(value ?? '5')),
where: (_api: GridApi<Row>, value?: string) => void (where = Number(value ?? '6')),
move: (api: GridApi<Row>) => move(api),
addTeam: (api: GridApi<Row>) => {
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.`);
},
};