PMS 같은 호스트: 가짜 서버와 409·거절 처리A PMS-like host: fake server, 409 and refusals
막대를 놓으면 가짜 서버가 버전을 확인하고 요약 날짜를 합산해 돌려줘요. 409 충돌, 요약 작업 거절, 시간 초과, 네트워크 오류를 모두 revertIntent로 처리해요.On release a fake server checks the version and rolls up the summary dates. A 409 conflict, a summary refusal, a timeout and a network error all end in revertIntent.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/gantt로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<select aria-label="서버 모드" id="mode">
<option value="normal" selected>정상</option>
<option value="slow">응답 없음</option>
<option value="offline">연결 끊김</option>
</select>
<button type="button" id="other">다른 사용자가 7번 수정</button>
</div>
<div id="grid" style="height: 480px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('other').addEventListener('click', () => actions.other(api));import { createGantt, createSplitView } from '@maxgrid/gantt';
// [id, 부모, 작업, 담당자, 시작, 종료, 진행률, 상태]. 날짜가 비면 일정 없음, 시작=종료면 마일스톤이에요.
const T = [
['1', null, '웹사이트 개편', '이준호', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', '기획', '박민지', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', '요구사항 수집', '박민지', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', '경쟁 서비스 조사', '이준호', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', '범위 확정', '박민지', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', '디자인', '최하은', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', '와이어프레임', '최하은', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', '화면 디자인', '최하은', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', '아이콘 세트', '한지우', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', '개발', '김도윤', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', '프런트엔드', '한지우', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', '백엔드', '김도윤', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', '검색 기능', '이준호', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', '결제 기능', '김도윤', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', '콘텐츠 입력', '박민지', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', '통합', '김도윤', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', '출시', '이준호', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', '품질 점검', '한지우', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', '출시일', '이준호', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', '인수인계', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', '운영 교육', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', '문서화', '한지우', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [앞 작업, 뒤 작업, 종류, 지연(작업일)]
const D = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map();
const wbsOf = new Map();
const sortOf = new Map();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id),
name,
assignee,
start,
end,
progress,
}));
// 간트 차트에 넣을 데이터. 날짜 계산은 하지 않고 받은 값을 그대로 그려요.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id),
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: '표준 달력(월-금)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
export const options = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: '작업', width: 220 },
{ id: 'assignee', title: '담당자', width: 110 },
{ id: 'start', title: '시작', width: 100 },
{ id: 'end', title: '종료', width: 100 },
{ id: 'progress', title: '진행률(%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// 간트와 줄을 맞추려면 행·머리글 높이를 같게 맞춰야 해요(머리글 48, 행 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// 표 옆에 간트 차트를 붙여요: 표 요소를 왼쪽 칸으로 옮기고 createSplitView로 묶어요.
function mountGantt(api, ganttOptions = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
// 표 행을 고쳐 써요.
function syncRow(api, t) {
// rows에는 쓰지 않아요: 표가 그 객체를 그대로 쥐고 있어서, 이미 바뀐 행으로 갱신하면 달라진 게 없다고 보고 화면을 안 고쳐요.
const row = api.getRowByKey(t.id);
if (!row)
return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso, n) => new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode = 'normal';
let view = null;
let other = null;
// 설정을 바꾸면 바로 알려요(기록 + 차트 아래 안내). 설정은 다음 편집부터 적용돼요.
let logLine = null;
function acknowledge(ko, en) {
logLine?.({ ko, en });
const box = view?.box;
if (!box)
return;
let note = box.querySelector('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = ko;
}
export function setup(api, log) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set();
const wait = (ms) => new Promise((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// 가짜 서버: 작업과 의존 관계의 진짜 값을 들고 있어요(버전, 요약 합산 포함).
const server = {
tasks: data.tasks.map((t) => ({ ...t })),
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// 차트가 아는 작업별 버전(낙관적 잠금용)
const versions = new Map(data.tasks.map((t) => [t.id, t.version]));
const find = (id) => server.tasks.find((t) => t.id === id);
// 요약 작업의 날짜를 자식에서 합산해요(서버의 몫).
function rollUp(id, changed) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(call) {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline')
throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// 서버 호출에 시간 제한을 걸어요. 차트는 기다림에 제한이 없어서 호스트가 정해야 해요.
async function send(call) {
const limit = new Promise((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// 확정: 서버가 돌려준 작업들(후행·요약 포함)을 차트와 표에 반영해요.
const accept = (intentId, tasks) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e, status, code) => {
if (code === 'VERSION_CONFLICT')
return '다른 사람이 먼저 바꿨어요(409). 서버 값으로 맞췄어요.';
if (code === 'SUMMARY_READONLY')
return '요약 작업은 서버가 합산해요(422). 이을 수 없어요.';
if (e instanceof Error && e.message === 'timeout')
return '서버가 제때 답하지 않았어요(시간 초과).';
if (e !== undefined)
return '서버에 닿지 못했어요(네트워크 오류).';
return String(status);
};
async function schedule(intentId, taskId, f) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId),
f,
});
if (!alive)
return;
if (res.status === 200) {
res.body.tasks.forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks);
log({ ko: `${taskId}번 확정`, en: `Task ${taskId} confirmed` });
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // 서버의 값으로 맞춰요
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
}
catch (e) {
if (!alive)
return;
gantt.revertIntent(intentId); // 시간 초과·네트워크 오류도 같은 길이에요
const why = explain(e);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
}
}
const deps = server.deps;
const push = () => gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on('task-move', (e) => void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
})),
gantt.on('task-resize', (e) => void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
})),
gantt.on('task-progress', (e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct })),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive)
return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
return;
}
deps.push({
id: res.body.id,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // 의존 관계는 setData로 다시 줘요
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${res.body.id} 만들었어요`, en: `Link ${res.body.id} created` });
}
catch (err) {
if (!alive)
return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive)
return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0)
deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${e.dependencyId} 지웠어요`, en: `Link ${e.dependencyId} deleted` });
}
catch (err) {
if (!alive)
return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `삭제 거절: ${why}`, en: `Delete refused: ${why}` });
}
}),
];
// 다른 사용자가 7번 작업을 서버에서 이틀 미룬 것처럼 꾸며요. 차트는 모르는 변경이에요.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart, 2);
t.plannedEnd = addDays(t.plannedEnd, 2);
t.version += 1;
log({
ko: '서버에서 7번이 바뀌었어요(차트는 몰라요). 7번을 끌어 보세요.',
en: 'Task 7 changed on the server (the chart does not know). Now drag task 7.',
});
};
log({
ko: '편집을 켰어요. 서버 모드를 바꿔 보세요.',
en: 'Editing is on. Try the server modes.',
});
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
export const actions = {
mode: (_api, value) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label = {
normal: ['정상', 'Normal'],
slow: ['응답 없음', 'No answer'],
offline: ['연결 끊김', 'Offline'],
};
const [k, e] = label[value ?? ''] ?? Object.values(label)[0] ?? ['', ''];
acknowledge(`서버 모드: ${k}`, `Server mode: ${e}`);
},
other: () => other?.(),
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>PMS 같은 호스트: 가짜 서버와 409·거절 처리</title>
</head>
<body>
<div class="toolbar">
<select aria-label="서버 모드" id="mode">
<option value="normal" selected>정상</option>
<option value="slow">응답 없음</option>
<option value="offline">연결 끊김</option>
</select>
<button type="button" id="other">다른 사용자가 7번 수정</button>
</div>
<div id="grid" style="height: 480px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<link rel="stylesheet" href="https://cdn.maxmine.com/maxgrid/latest/maxgrid.gantt.css" />
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.gantt.min.js"></script>
<script>
const { createGantt, createSplitView } = MaxGridGantt;
// [id, 부모, 작업, 담당자, 시작, 종료, 진행률, 상태]. 날짜가 비면 일정 없음, 시작=종료면 마일스톤이에요.
const T = [
['1', null, '웹사이트 개편', '이준호', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', '기획', '박민지', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', '요구사항 수집', '박민지', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', '경쟁 서비스 조사', '이준호', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', '범위 확정', '박민지', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', '디자인', '최하은', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', '와이어프레임', '최하은', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', '화면 디자인', '최하은', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', '아이콘 세트', '한지우', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', '개발', '김도윤', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', '프런트엔드', '한지우', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', '백엔드', '김도윤', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', '검색 기능', '이준호', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', '결제 기능', '김도윤', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', '콘텐츠 입력', '박민지', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', '통합', '김도윤', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', '출시', '이준호', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', '품질 점검', '한지우', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', '출시일', '이준호', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', '인수인계', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', '운영 교육', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', '문서화', '한지우', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [앞 작업, 뒤 작업, 종류, 지연(작업일)]
const D = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map();
const wbsOf = new Map();
const sortOf = new Map();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id),
name,
assignee,
start,
end,
progress,
}));
// 간트 차트에 넣을 데이터. 날짜 계산은 하지 않고 받은 값을 그대로 그려요.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id),
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: '표준 달력(월-금)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
const options = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: '작업', width: 220 },
{ id: 'assignee', title: '담당자', width: 110 },
{ id: 'start', title: '시작', width: 100 },
{ id: 'end', title: '종료', width: 100 },
{ id: 'progress', title: '진행률(%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// 간트와 줄을 맞추려면 행·머리글 높이를 같게 맞춰야 해요(머리글 48, 행 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// 표 옆에 간트 차트를 붙여요: 표 요소를 왼쪽 칸으로 옮기고 createSplitView로 묶어요.
function mountGantt(api, ganttOptions = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
// 표 행을 고쳐 써요.
function syncRow(api, t) {
// rows에는 쓰지 않아요: 표가 그 객체를 그대로 쥐고 있어서, 이미 바뀐 행으로 갱신하면 달라진 게 없다고 보고 화면을 안 고쳐요.
const row = api.getRowByKey(t.id);
if (!row)
return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso, n) => new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode = 'normal';
let view = null;
let other = null;
// 설정을 바꾸면 바로 알려요(기록 + 차트 아래 안내). 설정은 다음 편집부터 적용돼요.
let logLine = null;
function acknowledge(ko, en) {
logLine?.({ ko, en });
const box = view?.box;
if (!box)
return;
let note = box.querySelector('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = ko;
}
function setup(api, log) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set();
const wait = (ms) => new Promise((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// 가짜 서버: 작업과 의존 관계의 진짜 값을 들고 있어요(버전, 요약 합산 포함).
const server = {
tasks: data.tasks.map((t) => ({ ...t })),
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// 차트가 아는 작업별 버전(낙관적 잠금용)
const versions = new Map(data.tasks.map((t) => [t.id, t.version]));
const find = (id) => server.tasks.find((t) => t.id === id);
// 요약 작업의 날짜를 자식에서 합산해요(서버의 몫).
function rollUp(id, changed) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(call) {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline')
throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// 서버 호출에 시간 제한을 걸어요. 차트는 기다림에 제한이 없어서 호스트가 정해야 해요.
async function send(call) {
const limit = new Promise((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// 확정: 서버가 돌려준 작업들(후행·요약 포함)을 차트와 표에 반영해요.
const accept = (intentId, tasks) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e, status, code) => {
if (code === 'VERSION_CONFLICT')
return '다른 사람이 먼저 바꿨어요(409). 서버 값으로 맞췄어요.';
if (code === 'SUMMARY_READONLY')
return '요약 작업은 서버가 합산해요(422). 이을 수 없어요.';
if (e instanceof Error && e.message === 'timeout')
return '서버가 제때 답하지 않았어요(시간 초과).';
if (e !== undefined)
return '서버에 닿지 못했어요(네트워크 오류).';
return String(status);
};
async function schedule(intentId, taskId, f) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId),
f,
});
if (!alive)
return;
if (res.status === 200) {
res.body.tasks.forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks);
log({ ko: `${taskId}번 확정`, en: `Task ${taskId} confirmed` });
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // 서버의 값으로 맞춰요
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
}
catch (e) {
if (!alive)
return;
gantt.revertIntent(intentId); // 시간 초과·네트워크 오류도 같은 길이에요
const why = explain(e);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
}
}
const deps = server.deps;
const push = () => gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on('task-move', (e) => void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
})),
gantt.on('task-resize', (e) => void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
})),
gantt.on('task-progress', (e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct })),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive)
return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
return;
}
deps.push({
id: res.body.id,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // 의존 관계는 setData로 다시 줘요
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${res.body.id} 만들었어요`, en: `Link ${res.body.id} created` });
}
catch (err) {
if (!alive)
return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive)
return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0)
deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${e.dependencyId} 지웠어요`, en: `Link ${e.dependencyId} deleted` });
}
catch (err) {
if (!alive)
return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `삭제 거절: ${why}`, en: `Delete refused: ${why}` });
}
}),
];
// 다른 사용자가 7번 작업을 서버에서 이틀 미룬 것처럼 꾸며요. 차트는 모르는 변경이에요.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart, 2);
t.plannedEnd = addDays(t.plannedEnd, 2);
t.version += 1;
log({
ko: '서버에서 7번이 바뀌었어요(차트는 몰라요). 7번을 끌어 보세요.',
en: 'Task 7 changed on the server (the chart does not know). Now drag task 7.',
});
};
log({
ko: '편집을 켰어요. 서버 모드를 바꿔 보세요.',
en: 'Editing is on. Try the server modes.',
});
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
const actions = {
mode: (_api, value) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label = {
normal: ['정상', 'Normal'],
slow: ['응답 없음', 'No answer'],
offline: ['연결 끊김', 'Offline'],
};
const [k, e] = label[value ?? ''] ?? Object.values(label)[0] ?? ['', ''];
acknowledge(`서버 모드: ${k}`, `Server mode: ${e}`);
},
other: () => other?.(),
};
options.ariaLabel = "PMS 같은 호스트: 가짜 서버와 409·거절 처리";
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('other').addEventListener('click', () => actions.other(api));
</script>
</body>
</html> 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/react @maxgrid/gantt로 설치하세요.
버튼을 누르면 이 예제의 코드가 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.mode(api, event.target.value)}
>
<option value="normal">정상</option>
<option value="slow">응답 없음</option>
<option value="offline">연결 끊김</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.other(api)}
>다른 사용자가 7번 수정</button>
</div>
<Grid style={{ height: 480 }} ref={gridRef} options={options} />
</>
);
}import { createGantt, createSplitView } from '@maxgrid/gantt';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
parentId: string | null;
wbs: string;
name: string;
assignee: string;
start: string;
end: string;
progress: number;
}
type Status = 'TODO' | 'IN_PROGRESS' | 'DONE';
// [id, 부모, 작업, 담당자, 시작, 종료, 진행률, 상태]. 날짜가 비면 일정 없음, 시작=종료면 마일스톤이에요.
const T: Array<[string, string | null, string, string, string, string, number, Status]> = [
['1', null, '웹사이트 개편', '이준호', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', '기획', '박민지', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', '요구사항 수집', '박민지', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', '경쟁 서비스 조사', '이준호', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', '범위 확정', '박민지', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', '디자인', '최하은', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', '와이어프레임', '최하은', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', '화면 디자인', '최하은', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', '아이콘 세트', '한지우', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', '개발', '김도윤', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', '프런트엔드', '한지우', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', '백엔드', '김도윤', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', '검색 기능', '이준호', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', '결제 기능', '김도윤', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', '콘텐츠 입력', '박민지', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', '통합', '김도윤', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', '출시', '이준호', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', '품질 점검', '한지우', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', '출시일', '이준호', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', '인수인계', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', '운영 교육', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', '문서화', '한지우', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [앞 작업, 뒤 작업, 종류, 지연(작업일)]
const D: Array<[string, string, 'FS' | 'SS' | 'FF' | 'SF', number]> = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map<string | null, number>();
const wbsOf = new Map<string, string>();
const sortOf = new Map<string, number>();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows: Row[] = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id) as string,
name,
assignee,
start,
end,
progress,
}));
// 간트 차트에 넣을 데이터. 날짜 계산은 하지 않고 받은 값을 그대로 그려요.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id) as number,
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: '표준 달력(월-금)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: '작업', width: 220 },
{ id: 'assignee', title: '담당자', width: 110 },
{ id: 'start', title: '시작', width: 100 },
{ id: 'end', title: '종료', width: 100 },
{ id: 'progress', title: '진행률(%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// 간트와 줄을 맞추려면 행·머리글 높이를 같게 맞춰야 해요(머리글 48, 행 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// 표 옆에 간트 차트를 붙여요: 표 요소를 왼쪽 칸으로 옮기고 createSplitView로 묶어요.
function mountGantt(api: GridApi<Row>, ganttOptions: Parameters<typeof createGantt>[1] = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement as HTMLElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type Fields = { plannedStart?: string; plannedEnd?: string; progressPct?: number };
type Mode = 'normal' | 'offline' | 'slow';
type SrvTask = (typeof data.tasks)[number];
type Reply = {
status: number;
body: { code?: string; tasks?: SrvTask[]; task?: SrvTask; id?: string };
};
// 표 행을 고쳐 써요.
function syncRow(
api: GridApi<Row>,
t: { id: string; plannedStart: string | null; plannedEnd: string | null; progressPct: number },
) {
// rows에는 쓰지 않아요: 표가 그 객체를 그대로 쥐고 있어서, 이미 바뀐 행으로 갱신하면 달라진 게 없다고 보고 화면을 안 고쳐요.
const row = api.getRowByKey(t.id);
if (!row) return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso: string, n: number) =>
new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode: Mode = 'normal';
let view: ReturnType<typeof mountGantt> | null = null;
let other: (() => void) | null = null;
// 설정을 바꾸면 바로 알려요(기록 + 차트 아래 안내). 설정은 다음 편집부터 적용돼요.
let logLine: ((message: LogText) => void) | null = null;
function acknowledge(ko: string, en: string) {
logLine?.({ ko, en });
const box = view?.box;
if (!box) return;
let note = box.querySelector<HTMLElement>('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = ko;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set<ReturnType<typeof setTimeout>>();
const wait = (ms: number) =>
new Promise<void>((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// 가짜 서버: 작업과 의존 관계의 진짜 값을 들고 있어요(버전, 요약 합산 포함).
const server = {
tasks: data.tasks.map((t) => ({ ...t })) as SrvTask[],
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// 차트가 아는 작업별 버전(낙관적 잠금용)
const versions = new Map<string, number>(data.tasks.map((t) => [t.id, t.version]));
const find = (id: string) => server.tasks.find((t) => t.id === id) as SrvTask;
// 요약 작업의 날짜를 자식에서 합산해요(서버의 몫).
function rollUp(id: string | null, changed: SrvTask[]) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart as string).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd as string)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(
call:
| { kind: 'schedule'; id: string; version: number; f: Fields }
| { kind: 'link'; from: string; to: string }
| { kind: 'unlink'; id: string },
): Promise<Reply> {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline') throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren) return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed: SrvTask[] = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// 서버 호출에 시간 제한을 걸어요. 차트는 기다림에 제한이 없어서 호스트가 정해야 해요.
async function send(call: Parameters<typeof request>[0]): Promise<Reply> {
const limit = new Promise<never>((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// 확정: 서버가 돌려준 작업들(후행·요약 포함)을 차트와 표에 반영해요.
const accept = (intentId: string, tasks: SrvTask[]) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e: unknown, status?: number, code?: string): string => {
if (code === 'VERSION_CONFLICT') return '다른 사람이 먼저 바꿨어요(409). 서버 값으로 맞췄어요.';
if (code === 'SUMMARY_READONLY') return '요약 작업은 서버가 합산해요(422). 이을 수 없어요.';
if (e instanceof Error && e.message === 'timeout')
return '서버가 제때 답하지 않았어요(시간 초과).';
if (e !== undefined) return '서버에 닿지 못했어요(네트워크 오류).';
return String(status);
};
async function schedule(intentId: string, taskId: string, f: Fields) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId) as number,
f,
});
if (!alive) return;
if (res.status === 200) {
(res.body.tasks as SrvTask[]).forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks as SrvTask[]);
log({ ko: `${taskId}번 확정`, en: `Task ${taskId} confirmed` });
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // 서버의 값으로 맞춰요
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
} catch (e) {
if (!alive) return;
gantt.revertIntent(intentId); // 시간 초과·네트워크 오류도 같은 길이에요
const why = explain(e);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
}
}
const deps = server.deps;
const push = () =>
gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on(
'task-move',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-resize',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-progress',
(e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct }),
),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive) return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
return;
}
deps.push({
id: res.body.id as string,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // 의존 관계는 setData로 다시 줘요
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${res.body.id} 만들었어요`, en: `Link ${res.body.id} created` });
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive) return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0) deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${e.dependencyId} 지웠어요`, en: `Link ${e.dependencyId} deleted` });
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `삭제 거절: ${why}`, en: `Delete refused: ${why}` });
}
}),
];
// 다른 사용자가 7번 작업을 서버에서 이틀 미룬 것처럼 꾸며요. 차트는 모르는 변경이에요.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart as string, 2);
t.plannedEnd = addDays(t.plannedEnd as string, 2);
t.version += 1;
log({
ko: '서버에서 7번이 바뀌었어요(차트는 몰라요). 7번을 끌어 보세요.',
en: 'Task 7 changed on the server (the chart does not know). Now drag task 7.',
});
};
log({
ko: '편집을 켰어요. 서버 모드를 바꿔 보세요.',
en: 'Editing is on. Try the server modes.',
});
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label: Record<string, [string, string]> = {
normal: ['정상', 'Normal'],
slow: ['응답 없음', 'No answer'],
offline: ['연결 끊김', 'Offline'],
};
const [k, e] = label[value ?? ''] ?? Object.values(label)[0] ?? ['', ''];
acknowledge(`서버 모드: ${k}`, `Server mode: ${e}`);
},
other: () => other?.(),
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/vue @maxgrid/gantt로 설치하세요.
버튼을 누르면 이 예제의 코드가 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.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="normal" selected>정상</option>
<option value="slow">응답 없음</option>
<option value="offline">연결 끊김</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.other(api)">다른 사용자가 7번 수정</button>
</div>
<Grid style="height: 480px" :options="options" @ready="onReady" />
</template>import { createGantt, createSplitView } from '@maxgrid/gantt';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
parentId: string | null;
wbs: string;
name: string;
assignee: string;
start: string;
end: string;
progress: number;
}
type Status = 'TODO' | 'IN_PROGRESS' | 'DONE';
// [id, 부모, 작업, 담당자, 시작, 종료, 진행률, 상태]. 날짜가 비면 일정 없음, 시작=종료면 마일스톤이에요.
const T: Array<[string, string | null, string, string, string, string, number, Status]> = [
['1', null, '웹사이트 개편', '이준호', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', '기획', '박민지', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', '요구사항 수집', '박민지', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', '경쟁 서비스 조사', '이준호', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', '범위 확정', '박민지', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', '디자인', '최하은', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', '와이어프레임', '최하은', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', '화면 디자인', '최하은', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', '아이콘 세트', '한지우', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', '개발', '김도윤', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', '프런트엔드', '한지우', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', '백엔드', '김도윤', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', '검색 기능', '이준호', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', '결제 기능', '김도윤', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', '콘텐츠 입력', '박민지', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', '통합', '김도윤', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', '출시', '이준호', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', '품질 점검', '한지우', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', '출시일', '이준호', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', '인수인계', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', '운영 교육', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', '문서화', '한지우', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [앞 작업, 뒤 작업, 종류, 지연(작업일)]
const D: Array<[string, string, 'FS' | 'SS' | 'FF' | 'SF', number]> = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map<string | null, number>();
const wbsOf = new Map<string, string>();
const sortOf = new Map<string, number>();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows: Row[] = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id) as string,
name,
assignee,
start,
end,
progress,
}));
// 간트 차트에 넣을 데이터. 날짜 계산은 하지 않고 받은 값을 그대로 그려요.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id) as number,
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: '표준 달력(월-금)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: '작업', width: 220 },
{ id: 'assignee', title: '담당자', width: 110 },
{ id: 'start', title: '시작', width: 100 },
{ id: 'end', title: '종료', width: 100 },
{ id: 'progress', title: '진행률(%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// 간트와 줄을 맞추려면 행·머리글 높이를 같게 맞춰야 해요(머리글 48, 행 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// 표 옆에 간트 차트를 붙여요: 표 요소를 왼쪽 칸으로 옮기고 createSplitView로 묶어요.
function mountGantt(api: GridApi<Row>, ganttOptions: Parameters<typeof createGantt>[1] = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement as HTMLElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type Fields = { plannedStart?: string; plannedEnd?: string; progressPct?: number };
type Mode = 'normal' | 'offline' | 'slow';
type SrvTask = (typeof data.tasks)[number];
type Reply = {
status: number;
body: { code?: string; tasks?: SrvTask[]; task?: SrvTask; id?: string };
};
// 표 행을 고쳐 써요.
function syncRow(
api: GridApi<Row>,
t: { id: string; plannedStart: string | null; plannedEnd: string | null; progressPct: number },
) {
// rows에는 쓰지 않아요: 표가 그 객체를 그대로 쥐고 있어서, 이미 바뀐 행으로 갱신하면 달라진 게 없다고 보고 화면을 안 고쳐요.
const row = api.getRowByKey(t.id);
if (!row) return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso: string, n: number) =>
new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode: Mode = 'normal';
let view: ReturnType<typeof mountGantt> | null = null;
let other: (() => void) | null = null;
// 설정을 바꾸면 바로 알려요(기록 + 차트 아래 안내). 설정은 다음 편집부터 적용돼요.
let logLine: ((message: LogText) => void) | null = null;
function acknowledge(ko: string, en: string) {
logLine?.({ ko, en });
const box = view?.box;
if (!box) return;
let note = box.querySelector<HTMLElement>('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = ko;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set<ReturnType<typeof setTimeout>>();
const wait = (ms: number) =>
new Promise<void>((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// 가짜 서버: 작업과 의존 관계의 진짜 값을 들고 있어요(버전, 요약 합산 포함).
const server = {
tasks: data.tasks.map((t) => ({ ...t })) as SrvTask[],
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// 차트가 아는 작업별 버전(낙관적 잠금용)
const versions = new Map<string, number>(data.tasks.map((t) => [t.id, t.version]));
const find = (id: string) => server.tasks.find((t) => t.id === id) as SrvTask;
// 요약 작업의 날짜를 자식에서 합산해요(서버의 몫).
function rollUp(id: string | null, changed: SrvTask[]) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart as string).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd as string)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(
call:
| { kind: 'schedule'; id: string; version: number; f: Fields }
| { kind: 'link'; from: string; to: string }
| { kind: 'unlink'; id: string },
): Promise<Reply> {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline') throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren) return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed: SrvTask[] = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// 서버 호출에 시간 제한을 걸어요. 차트는 기다림에 제한이 없어서 호스트가 정해야 해요.
async function send(call: Parameters<typeof request>[0]): Promise<Reply> {
const limit = new Promise<never>((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// 확정: 서버가 돌려준 작업들(후행·요약 포함)을 차트와 표에 반영해요.
const accept = (intentId: string, tasks: SrvTask[]) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e: unknown, status?: number, code?: string): string => {
if (code === 'VERSION_CONFLICT') return '다른 사람이 먼저 바꿨어요(409). 서버 값으로 맞췄어요.';
if (code === 'SUMMARY_READONLY') return '요약 작업은 서버가 합산해요(422). 이을 수 없어요.';
if (e instanceof Error && e.message === 'timeout')
return '서버가 제때 답하지 않았어요(시간 초과).';
if (e !== undefined) return '서버에 닿지 못했어요(네트워크 오류).';
return String(status);
};
async function schedule(intentId: string, taskId: string, f: Fields) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId) as number,
f,
});
if (!alive) return;
if (res.status === 200) {
(res.body.tasks as SrvTask[]).forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks as SrvTask[]);
log({ ko: `${taskId}번 확정`, en: `Task ${taskId} confirmed` });
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // 서버의 값으로 맞춰요
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
} catch (e) {
if (!alive) return;
gantt.revertIntent(intentId); // 시간 초과·네트워크 오류도 같은 길이에요
const why = explain(e);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
}
}
const deps = server.deps;
const push = () =>
gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on(
'task-move',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-resize',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-progress',
(e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct }),
),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive) return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
return;
}
deps.push({
id: res.body.id as string,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // 의존 관계는 setData로 다시 줘요
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${res.body.id} 만들었어요`, en: `Link ${res.body.id} created` });
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive) return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0) deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${e.dependencyId} 지웠어요`, en: `Link ${e.dependencyId} deleted` });
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `삭제 거절: ${why}`, en: `Delete refused: ${why}` });
}
}),
];
// 다른 사용자가 7번 작업을 서버에서 이틀 미룬 것처럼 꾸며요. 차트는 모르는 변경이에요.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart as string, 2);
t.plannedEnd = addDays(t.plannedEnd as string, 2);
t.version += 1;
log({
ko: '서버에서 7번이 바뀌었어요(차트는 몰라요). 7번을 끌어 보세요.',
en: 'Task 7 changed on the server (the chart does not know). Now drag task 7.',
});
};
log({
ko: '편집을 켰어요. 서버 모드를 바꿔 보세요.',
en: 'Editing is on. Try the server modes.',
});
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label: Record<string, [string, string]> = {
normal: ['정상', 'Normal'],
slow: ['응답 없음', 'No answer'],
offline: ['연결 끊김', 'Offline'],
};
const [k, e] = label[value ?? ''] ?? Object.values(label)[0] ?? ['', ''];
acknowledge(`서버 모드: ${k}`, `Server mode: ${e}`);
},
other: () => other?.(),
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/angular @maxgrid/gantt로 설치하세요.
버튼을 누르면 이 예제의 코드가 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.mode(api, $any($event.target).value)"
>
<option value="normal" selected>정상</option>
<option value="slow">응답 없음</option>
<option value="offline">연결 끊김</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.other(api)"
>다른 사용자가 7번 수정</button>
</div>
<mx-grid style="height: 480px" [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 { createGantt, createSplitView } from '@maxgrid/gantt';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
parentId: string | null;
wbs: string;
name: string;
assignee: string;
start: string;
end: string;
progress: number;
}
type Status = 'TODO' | 'IN_PROGRESS' | 'DONE';
// [id, 부모, 작업, 담당자, 시작, 종료, 진행률, 상태]. 날짜가 비면 일정 없음, 시작=종료면 마일스톤이에요.
const T: Array<[string, string | null, string, string, string, string, number, Status]> = [
['1', null, '웹사이트 개편', '이준호', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', '기획', '박민지', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', '요구사항 수집', '박민지', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', '경쟁 서비스 조사', '이준호', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', '범위 확정', '박민지', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', '디자인', '최하은', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', '와이어프레임', '최하은', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', '화면 디자인', '최하은', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', '아이콘 세트', '한지우', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', '개발', '김도윤', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', '프런트엔드', '한지우', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', '백엔드', '김도윤', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', '검색 기능', '이준호', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', '결제 기능', '김도윤', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', '콘텐츠 입력', '박민지', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', '통합', '김도윤', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', '출시', '이준호', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', '품질 점검', '한지우', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', '출시일', '이준호', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', '인수인계', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', '운영 교육', '박민지', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', '문서화', '한지우', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [앞 작업, 뒤 작업, 종류, 지연(작업일)]
const D: Array<[string, string, 'FS' | 'SS' | 'FF' | 'SF', number]> = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map<string | null, number>();
const wbsOf = new Map<string, string>();
const sortOf = new Map<string, number>();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows: Row[] = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id) as string,
name,
assignee,
start,
end,
progress,
}));
// 간트 차트에 넣을 데이터. 날짜 계산은 하지 않고 받은 값을 그대로 그려요.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id) as number,
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: '표준 달력(월-금)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: '작업', width: 220 },
{ id: 'assignee', title: '담당자', width: 110 },
{ id: 'start', title: '시작', width: 100 },
{ id: 'end', title: '종료', width: 100 },
{ id: 'progress', title: '진행률(%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// 간트와 줄을 맞추려면 행·머리글 높이를 같게 맞춰야 해요(머리글 48, 행 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// 표 옆에 간트 차트를 붙여요: 표 요소를 왼쪽 칸으로 옮기고 createSplitView로 묶어요.
function mountGantt(api: GridApi<Row>, ganttOptions: Parameters<typeof createGantt>[1] = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement as HTMLElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type Fields = { plannedStart?: string; plannedEnd?: string; progressPct?: number };
type Mode = 'normal' | 'offline' | 'slow';
type SrvTask = (typeof data.tasks)[number];
type Reply = {
status: number;
body: { code?: string; tasks?: SrvTask[]; task?: SrvTask; id?: string };
};
// 표 행을 고쳐 써요.
function syncRow(
api: GridApi<Row>,
t: { id: string; plannedStart: string | null; plannedEnd: string | null; progressPct: number },
) {
// rows에는 쓰지 않아요: 표가 그 객체를 그대로 쥐고 있어서, 이미 바뀐 행으로 갱신하면 달라진 게 없다고 보고 화면을 안 고쳐요.
const row = api.getRowByKey(t.id);
if (!row) return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso: string, n: number) =>
new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode: Mode = 'normal';
let view: ReturnType<typeof mountGantt> | null = null;
let other: (() => void) | null = null;
// 설정을 바꾸면 바로 알려요(기록 + 차트 아래 안내). 설정은 다음 편집부터 적용돼요.
let logLine: ((message: LogText) => void) | null = null;
function acknowledge(ko: string, en: string) {
logLine?.({ ko, en });
const box = view?.box;
if (!box) return;
let note = box.querySelector<HTMLElement>('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = ko;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set<ReturnType<typeof setTimeout>>();
const wait = (ms: number) =>
new Promise<void>((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// 가짜 서버: 작업과 의존 관계의 진짜 값을 들고 있어요(버전, 요약 합산 포함).
const server = {
tasks: data.tasks.map((t) => ({ ...t })) as SrvTask[],
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// 차트가 아는 작업별 버전(낙관적 잠금용)
const versions = new Map<string, number>(data.tasks.map((t) => [t.id, t.version]));
const find = (id: string) => server.tasks.find((t) => t.id === id) as SrvTask;
// 요약 작업의 날짜를 자식에서 합산해요(서버의 몫).
function rollUp(id: string | null, changed: SrvTask[]) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart as string).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd as string)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(
call:
| { kind: 'schedule'; id: string; version: number; f: Fields }
| { kind: 'link'; from: string; to: string }
| { kind: 'unlink'; id: string },
): Promise<Reply> {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline') throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren) return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed: SrvTask[] = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// 서버 호출에 시간 제한을 걸어요. 차트는 기다림에 제한이 없어서 호스트가 정해야 해요.
async function send(call: Parameters<typeof request>[0]): Promise<Reply> {
const limit = new Promise<never>((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// 확정: 서버가 돌려준 작업들(후행·요약 포함)을 차트와 표에 반영해요.
const accept = (intentId: string, tasks: SrvTask[]) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e: unknown, status?: number, code?: string): string => {
if (code === 'VERSION_CONFLICT') return '다른 사람이 먼저 바꿨어요(409). 서버 값으로 맞췄어요.';
if (code === 'SUMMARY_READONLY') return '요약 작업은 서버가 합산해요(422). 이을 수 없어요.';
if (e instanceof Error && e.message === 'timeout')
return '서버가 제때 답하지 않았어요(시간 초과).';
if (e !== undefined) return '서버에 닿지 못했어요(네트워크 오류).';
return String(status);
};
async function schedule(intentId: string, taskId: string, f: Fields) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId) as number,
f,
});
if (!alive) return;
if (res.status === 200) {
(res.body.tasks as SrvTask[]).forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks as SrvTask[]);
log({ ko: `${taskId}번 확정`, en: `Task ${taskId} confirmed` });
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // 서버의 값으로 맞춰요
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
} catch (e) {
if (!alive) return;
gantt.revertIntent(intentId); // 시간 초과·네트워크 오류도 같은 길이에요
const why = explain(e);
log({ ko: `${taskId}번 되돌림: ${why}`, en: `Task ${taskId} reverted: ${why}` });
}
}
const deps = server.deps;
const push = () =>
gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on(
'task-move',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-resize',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-progress',
(e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct }),
),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive) return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
return;
}
deps.push({
id: res.body.id as string,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // 의존 관계는 setData로 다시 줘요
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${res.body.id} 만들었어요`, en: `Link ${res.body.id} created` });
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `이음 거절: ${why}`, en: `Link refused: ${why}` });
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive) return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0) deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log({ ko: `이음 ${e.dependencyId} 지웠어요`, en: `Link ${e.dependencyId} deleted` });
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log({ ko: `삭제 거절: ${why}`, en: `Delete refused: ${why}` });
}
}),
];
// 다른 사용자가 7번 작업을 서버에서 이틀 미룬 것처럼 꾸며요. 차트는 모르는 변경이에요.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart as string, 2);
t.plannedEnd = addDays(t.plannedEnd as string, 2);
t.version += 1;
log({
ko: '서버에서 7번이 바뀌었어요(차트는 몰라요). 7번을 끌어 보세요.',
en: 'Task 7 changed on the server (the chart does not know). Now drag task 7.',
});
};
log({
ko: '편집을 켰어요. 서버 모드를 바꿔 보세요.',
en: 'Editing is on. Try the server modes.',
});
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label: Record<string, [string, string]> = {
normal: ['정상', 'Normal'],
slow: ['응답 없음', 'No answer'],
offline: ['연결 끊김', 'Offline'],
};
const [k, e] = label[value ?? ''] ?? Object.values(label)[0] ?? ['', ''];
acknowledge(`서버 모드: ${k}`, `Server mode: ${e}`);
},
other: () => other?.(),
}; This example needs an extra package. To run it locally, install with npm i maxgrid @maxgrid/gantt.
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="Server mode" id="mode">
<option value="normal" selected>Normal</option>
<option value="slow">No answer</option>
<option value="offline">Offline</option>
</select>
<button type="button" id="other">Another user edits task 7</button>
</div>
<div id="grid" style="height: 480px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('other').addEventListener('click', () => actions.other(api));import { createGantt, createSplitView } from '@maxgrid/gantt';
// [id, parent, task, assignee, start, end, progress, status]. No dates means unscheduled; start = end means a milestone.
const T = [
['1', null, 'Website renewal', 'Liam Carter', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', 'Planning', 'Emma Stone', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', 'Requirements', 'Emma Stone', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', 'Competitor review', 'Liam Carter', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', 'Scope sign-off', 'Emma Stone', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', 'Design', 'Noah Reed', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', 'Wireframes', 'Noah Reed', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', 'Visual design', 'Noah Reed', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', 'Icon set', 'Olivia Park', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', 'Build', 'Ethan Cole', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', 'Front end', 'Olivia Park', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', 'Back end', 'Ethan Cole', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', 'Search feature', 'Liam Carter', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', 'Payments', 'Ethan Cole', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', 'Content entry', 'Emma Stone', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', 'Integration', 'Ethan Cole', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', 'Launch', 'Liam Carter', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', 'QA', 'Olivia Park', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', 'Go-live', 'Liam Carter', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', 'Handover', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', 'Training', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', 'Docs', 'Olivia Park', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [predecessor, successor, type, lag (working days)]
const D = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// The order inside a parent (sortNo) and the WBS number come from the array order.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map();
const wbsOf = new Map();
const sortOf = new Map();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// Flat grid rows (a parent id is enough to make a tree).
const rows = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id),
name,
assignee,
start,
end,
progress,
}));
// Data for the Gantt chart. It draws the values as given and does no date math.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id),
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: 'Standard calendar (Mon-Fri)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
export const options = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: 'Task', width: 220 },
{ id: 'assignee', title: 'Assignee', width: 110 },
{ id: 'start', title: 'Start', width: 100 },
{ id: 'end', title: 'End', width: 100 },
{ id: 'progress', title: 'Progress (%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// Keep row and header heights equal to the chart so the lines line up (header 48, row 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// Put the Gantt chart next to the grid: move the grid element into the left pane and join both with createSplitView.
function mountGantt(api, ganttOptions = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
// Writes the change into the grid row.
function syncRow(api, t) {
// Don't write into `rows`: the grid holds those very objects, so an update equal to the old row changes nothing on screen.
const row = api.getRowByKey(t.id);
if (!row)
return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso, n) => new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode = 'normal';
let view = null;
let other = null;
// A changed setting is acknowledged at once (log + a note over the chart). It applies to the next edit.
let logLine = null;
function acknowledge(text) {
logLine?.(text);
const box = view?.box;
if (!box)
return;
let note = box.querySelector('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = text;
}
export function setup(api, log) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set();
const wait = (ms) => new Promise((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// A fake server: it owns the real tasks and links (versions and summary roll-up included).
const server = {
tasks: data.tasks.map((t) => ({ ...t })),
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// The version of each task the chart knows (for optimistic locking)
const versions = new Map(data.tasks.map((t) => [t.id, t.version]));
const find = (id) => server.tasks.find((t) => t.id === id);
// Summary dates come from the children (the server's job).
function rollUp(id, changed) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(call) {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline')
throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// Puts a time limit on the call. The chart waits forever, so the host must set the limit.
async function send(call) {
const limit = new Promise((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// Accepted: the tasks the server returns (summaries included) go to the chart and the grid.
const accept = (intentId, tasks) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e, status, code) => {
if (code === 'VERSION_CONFLICT')
return 'Someone else changed it first (409). Showing the server values.';
if (code === 'SUMMARY_READONLY')
return 'Summaries are computed by the server (422). They cannot be linked.';
if (e instanceof Error && e.message === 'timeout')
return 'The server did not answer in time (timeout).';
if (e !== undefined)
return 'Could not reach the server (network error).';
return String(status);
};
async function schedule(intentId, taskId, f) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId),
f,
});
if (!alive)
return;
if (res.status === 200) {
res.body.tasks.forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks);
log(`Task ${taskId} confirmed`);
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // sync to the server's values
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log(`Task ${taskId} reverted: ${why}`);
}
catch (e) {
if (!alive)
return;
gantt.revertIntent(intentId); // timeout and network errors take the same path
const why = explain(e);
log(`Task ${taskId} reverted: ${why}`);
}
}
const deps = server.deps;
const push = () => gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on('task-move', (e) => void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
})),
gantt.on('task-resize', (e) => void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
})),
gantt.on('task-progress', (e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct })),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive)
return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log(`Link refused: ${why}`);
return;
}
deps.push({
id: res.body.id,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // links come back through setData
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${res.body.id} created`);
}
catch (err) {
if (!alive)
return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Link refused: ${why}`);
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive)
return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0)
deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${e.dependencyId} deleted`);
}
catch (err) {
if (!alive)
return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Delete refused: ${why}`);
}
}),
];
// Pretends another user pushed task 7 two days later on the server. The chart does not know.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart, 2);
t.plannedEnd = addDays(t.plannedEnd, 2);
t.version += 1;
log('Task 7 changed on the server (the chart does not know). Now drag task 7.');
};
log('Editing is on. Try the server modes.');
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
export const actions = {
mode: (_api, value) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label = {
normal: 'Normal',
slow: 'No answer',
offline: 'Offline',
};
const e = label[value ?? ''] ?? Object.values(label)[0] ?? '';
acknowledge(`Server mode: ${e}`);
},
other: () => other?.(),
};This HTML also loads an extra bundle (the extra script tag above) and uses it as a global. No install is needed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>A PMS-like host: fake server, 409 and refusals</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Server mode" id="mode">
<option value="normal" selected>Normal</option>
<option value="slow">No answer</option>
<option value="offline">Offline</option>
</select>
<button type="button" id="other">Another user edits task 7</button>
</div>
<div id="grid" style="height: 480px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<link rel="stylesheet" href="https://cdn.maxmine.com/maxgrid/latest/maxgrid.gantt.css" />
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.gantt.min.js"></script>
<script>
const { createGantt, createSplitView } = MaxGridGantt;
// [id, parent, task, assignee, start, end, progress, status]. No dates means unscheduled; start = end means a milestone.
const T = [
['1', null, 'Website renewal', 'Liam Carter', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', 'Planning', 'Emma Stone', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', 'Requirements', 'Emma Stone', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', 'Competitor review', 'Liam Carter', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', 'Scope sign-off', 'Emma Stone', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', 'Design', 'Noah Reed', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', 'Wireframes', 'Noah Reed', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', 'Visual design', 'Noah Reed', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', 'Icon set', 'Olivia Park', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', 'Build', 'Ethan Cole', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', 'Front end', 'Olivia Park', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', 'Back end', 'Ethan Cole', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', 'Search feature', 'Liam Carter', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', 'Payments', 'Ethan Cole', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', 'Content entry', 'Emma Stone', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', 'Integration', 'Ethan Cole', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', 'Launch', 'Liam Carter', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', 'QA', 'Olivia Park', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', 'Go-live', 'Liam Carter', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', 'Handover', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', 'Training', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', 'Docs', 'Olivia Park', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [predecessor, successor, type, lag (working days)]
const D = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// The order inside a parent (sortNo) and the WBS number come from the array order.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map();
const wbsOf = new Map();
const sortOf = new Map();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// Flat grid rows (a parent id is enough to make a tree).
const rows = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id),
name,
assignee,
start,
end,
progress,
}));
// Data for the Gantt chart. It draws the values as given and does no date math.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id),
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: 'Standard calendar (Mon-Fri)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
const options = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: 'Task', width: 220 },
{ id: 'assignee', title: 'Assignee', width: 110 },
{ id: 'start', title: 'Start', width: 100 },
{ id: 'end', title: 'End', width: 100 },
{ id: 'progress', title: 'Progress (%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// Keep row and header heights equal to the chart so the lines line up (header 48, row 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// Put the Gantt chart next to the grid: move the grid element into the left pane and join both with createSplitView.
function mountGantt(api, ganttOptions = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
// Writes the change into the grid row.
function syncRow(api, t) {
// Don't write into `rows`: the grid holds those very objects, so an update equal to the old row changes nothing on screen.
const row = api.getRowByKey(t.id);
if (!row)
return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso, n) => new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode = 'normal';
let view = null;
let other = null;
// A changed setting is acknowledged at once (log + a note over the chart). It applies to the next edit.
let logLine = null;
function acknowledge(text) {
logLine?.(text);
const box = view?.box;
if (!box)
return;
let note = box.querySelector('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = text;
}
function setup(api, log) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set();
const wait = (ms) => new Promise((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// A fake server: it owns the real tasks and links (versions and summary roll-up included).
const server = {
tasks: data.tasks.map((t) => ({ ...t })),
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// The version of each task the chart knows (for optimistic locking)
const versions = new Map(data.tasks.map((t) => [t.id, t.version]));
const find = (id) => server.tasks.find((t) => t.id === id);
// Summary dates come from the children (the server's job).
function rollUp(id, changed) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(call) {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline')
throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// Puts a time limit on the call. The chart waits forever, so the host must set the limit.
async function send(call) {
const limit = new Promise((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// Accepted: the tasks the server returns (summaries included) go to the chart and the grid.
const accept = (intentId, tasks) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e, status, code) => {
if (code === 'VERSION_CONFLICT')
return 'Someone else changed it first (409). Showing the server values.';
if (code === 'SUMMARY_READONLY')
return 'Summaries are computed by the server (422). They cannot be linked.';
if (e instanceof Error && e.message === 'timeout')
return 'The server did not answer in time (timeout).';
if (e !== undefined)
return 'Could not reach the server (network error).';
return String(status);
};
async function schedule(intentId, taskId, f) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId),
f,
});
if (!alive)
return;
if (res.status === 200) {
res.body.tasks.forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks);
log(`Task ${taskId} confirmed`);
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // sync to the server's values
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log(`Task ${taskId} reverted: ${why}`);
}
catch (e) {
if (!alive)
return;
gantt.revertIntent(intentId); // timeout and network errors take the same path
const why = explain(e);
log(`Task ${taskId} reverted: ${why}`);
}
}
const deps = server.deps;
const push = () => gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on('task-move', (e) => void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
})),
gantt.on('task-resize', (e) => void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
})),
gantt.on('task-progress', (e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct })),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive)
return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log(`Link refused: ${why}`);
return;
}
deps.push({
id: res.body.id,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // links come back through setData
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${res.body.id} created`);
}
catch (err) {
if (!alive)
return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Link refused: ${why}`);
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive)
return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0)
deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${e.dependencyId} deleted`);
}
catch (err) {
if (!alive)
return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Delete refused: ${why}`);
}
}),
];
// Pretends another user pushed task 7 two days later on the server. The chart does not know.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart, 2);
t.plannedEnd = addDays(t.plannedEnd, 2);
t.version += 1;
log('Task 7 changed on the server (the chart does not know). Now drag task 7.');
};
log('Editing is on. Try the server modes.');
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
const actions = {
mode: (_api, value) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label = {
normal: 'Normal',
slow: 'No answer',
offline: 'Offline',
};
const e = label[value ?? ''] ?? Object.values(label)[0] ?? '';
acknowledge(`Server mode: ${e}`);
},
other: () => other?.(),
};
options.ariaLabel = "A PMS-like host: fake server, 409 and refusals";
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('other').addEventListener('click', () => actions.other(api));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/gantt.
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="Server mode"
disabled={!api}
onChange={(event) => api && actions.mode(api, event.target.value)}
>
<option value="normal">Normal</option>
<option value="slow">No answer</option>
<option value="offline">Offline</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.other(api)}
>Another user edits task 7</button>
</div>
<Grid style={{ height: 480 }} ref={gridRef} options={options} />
</>
);
}import { createGantt, createSplitView } from '@maxgrid/gantt';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: string;
parentId: string | null;
wbs: string;
name: string;
assignee: string;
start: string;
end: string;
progress: number;
}
type Status = 'TODO' | 'IN_PROGRESS' | 'DONE';
// [id, parent, task, assignee, start, end, progress, status]. No dates means unscheduled; start = end means a milestone.
const T: Array<[string, string | null, string, string, string, string, number, Status]> = [
['1', null, 'Website renewal', 'Liam Carter', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', 'Planning', 'Emma Stone', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', 'Requirements', 'Emma Stone', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', 'Competitor review', 'Liam Carter', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', 'Scope sign-off', 'Emma Stone', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', 'Design', 'Noah Reed', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', 'Wireframes', 'Noah Reed', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', 'Visual design', 'Noah Reed', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', 'Icon set', 'Olivia Park', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', 'Build', 'Ethan Cole', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', 'Front end', 'Olivia Park', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', 'Back end', 'Ethan Cole', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', 'Search feature', 'Liam Carter', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', 'Payments', 'Ethan Cole', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', 'Content entry', 'Emma Stone', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', 'Integration', 'Ethan Cole', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', 'Launch', 'Liam Carter', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', 'QA', 'Olivia Park', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', 'Go-live', 'Liam Carter', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', 'Handover', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', 'Training', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', 'Docs', 'Olivia Park', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [predecessor, successor, type, lag (working days)]
const D: Array<[string, string, 'FS' | 'SS' | 'FF' | 'SF', number]> = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// The order inside a parent (sortNo) and the WBS number come from the array order.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map<string | null, number>();
const wbsOf = new Map<string, string>();
const sortOf = new Map<string, number>();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// Flat grid rows (a parent id is enough to make a tree).
const rows: Row[] = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id) as string,
name,
assignee,
start,
end,
progress,
}));
// Data for the Gantt chart. It draws the values as given and does no date math.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id) as number,
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: 'Standard calendar (Mon-Fri)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: 'Task', width: 220 },
{ id: 'assignee', title: 'Assignee', width: 110 },
{ id: 'start', title: 'Start', width: 100 },
{ id: 'end', title: 'End', width: 100 },
{ id: 'progress', title: 'Progress (%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// Keep row and header heights equal to the chart so the lines line up (header 48, row 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// Put the Gantt chart next to the grid: move the grid element into the left pane and join both with createSplitView.
function mountGantt(api: GridApi<Row>, ganttOptions: Parameters<typeof createGantt>[1] = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement as HTMLElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type Fields = { plannedStart?: string; plannedEnd?: string; progressPct?: number };
type Mode = 'normal' | 'offline' | 'slow';
type SrvTask = (typeof data.tasks)[number];
type Reply = {
status: number;
body: { code?: string; tasks?: SrvTask[]; task?: SrvTask; id?: string };
};
// Writes the change into the grid row.
function syncRow(
api: GridApi<Row>,
t: { id: string; plannedStart: string | null; plannedEnd: string | null; progressPct: number },
) {
// Don't write into `rows`: the grid holds those very objects, so an update equal to the old row changes nothing on screen.
const row = api.getRowByKey(t.id);
if (!row) return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso: string, n: number) =>
new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode: Mode = 'normal';
let view: ReturnType<typeof mountGantt> | null = null;
let other: (() => void) | null = null;
// A changed setting is acknowledged at once (log + a note over the chart). It applies to the next edit.
let logLine: ((message: LogText) => void) | null = null;
function acknowledge(text: string) {
logLine?.(text);
const box = view?.box;
if (!box) return;
let note = box.querySelector<HTMLElement>('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = text;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set<ReturnType<typeof setTimeout>>();
const wait = (ms: number) =>
new Promise<void>((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// A fake server: it owns the real tasks and links (versions and summary roll-up included).
const server = {
tasks: data.tasks.map((t) => ({ ...t })) as SrvTask[],
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// The version of each task the chart knows (for optimistic locking)
const versions = new Map<string, number>(data.tasks.map((t) => [t.id, t.version]));
const find = (id: string) => server.tasks.find((t) => t.id === id) as SrvTask;
// Summary dates come from the children (the server's job).
function rollUp(id: string | null, changed: SrvTask[]) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart as string).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd as string)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(
call:
| { kind: 'schedule'; id: string; version: number; f: Fields }
| { kind: 'link'; from: string; to: string }
| { kind: 'unlink'; id: string },
): Promise<Reply> {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline') throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren) return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed: SrvTask[] = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// Puts a time limit on the call. The chart waits forever, so the host must set the limit.
async function send(call: Parameters<typeof request>[0]): Promise<Reply> {
const limit = new Promise<never>((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// Accepted: the tasks the server returns (summaries included) go to the chart and the grid.
const accept = (intentId: string, tasks: SrvTask[]) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e: unknown, status?: number, code?: string): string => {
if (code === 'VERSION_CONFLICT')
return 'Someone else changed it first (409). Showing the server values.';
if (code === 'SUMMARY_READONLY')
return 'Summaries are computed by the server (422). They cannot be linked.';
if (e instanceof Error && e.message === 'timeout')
return 'The server did not answer in time (timeout).';
if (e !== undefined) return 'Could not reach the server (network error).';
return String(status);
};
async function schedule(intentId: string, taskId: string, f: Fields) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId) as number,
f,
});
if (!alive) return;
if (res.status === 200) {
(res.body.tasks as SrvTask[]).forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks as SrvTask[]);
log(`Task ${taskId} confirmed`);
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // sync to the server's values
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log(`Task ${taskId} reverted: ${why}`);
} catch (e) {
if (!alive) return;
gantt.revertIntent(intentId); // timeout and network errors take the same path
const why = explain(e);
log(`Task ${taskId} reverted: ${why}`);
}
}
const deps = server.deps;
const push = () =>
gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on(
'task-move',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-resize',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-progress',
(e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct }),
),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive) return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log(`Link refused: ${why}`);
return;
}
deps.push({
id: res.body.id as string,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // links come back through setData
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${res.body.id} created`);
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Link refused: ${why}`);
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive) return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0) deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${e.dependencyId} deleted`);
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Delete refused: ${why}`);
}
}),
];
// Pretends another user pushed task 7 two days later on the server. The chart does not know.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart as string, 2);
t.plannedEnd = addDays(t.plannedEnd as string, 2);
t.version += 1;
log('Task 7 changed on the server (the chart does not know). Now drag task 7.');
};
log('Editing is on. Try the server modes.');
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label: Record<string, string> = {
normal: 'Normal',
slow: 'No answer',
offline: 'Offline',
};
const e = label[value ?? ''] ?? Object.values(label)[0] ?? '';
acknowledge(`Server mode: ${e}`);
},
other: () => other?.(),
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/vue @maxgrid/gantt.
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="Server mode"
:disabled="!api"
@change="api && actions.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="normal" selected>Normal</option>
<option value="slow">No answer</option>
<option value="offline">Offline</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.other(api)">Another user edits task 7</button>
</div>
<Grid style="height: 480px" :options="options" @ready="onReady" />
</template>import { createGantt, createSplitView } from '@maxgrid/gantt';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: string;
parentId: string | null;
wbs: string;
name: string;
assignee: string;
start: string;
end: string;
progress: number;
}
type Status = 'TODO' | 'IN_PROGRESS' | 'DONE';
// [id, parent, task, assignee, start, end, progress, status]. No dates means unscheduled; start = end means a milestone.
const T: Array<[string, string | null, string, string, string, string, number, Status]> = [
['1', null, 'Website renewal', 'Liam Carter', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', 'Planning', 'Emma Stone', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', 'Requirements', 'Emma Stone', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', 'Competitor review', 'Liam Carter', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', 'Scope sign-off', 'Emma Stone', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', 'Design', 'Noah Reed', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', 'Wireframes', 'Noah Reed', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', 'Visual design', 'Noah Reed', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', 'Icon set', 'Olivia Park', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', 'Build', 'Ethan Cole', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', 'Front end', 'Olivia Park', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', 'Back end', 'Ethan Cole', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', 'Search feature', 'Liam Carter', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', 'Payments', 'Ethan Cole', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', 'Content entry', 'Emma Stone', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', 'Integration', 'Ethan Cole', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', 'Launch', 'Liam Carter', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', 'QA', 'Olivia Park', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', 'Go-live', 'Liam Carter', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', 'Handover', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', 'Training', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', 'Docs', 'Olivia Park', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [predecessor, successor, type, lag (working days)]
const D: Array<[string, string, 'FS' | 'SS' | 'FF' | 'SF', number]> = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// The order inside a parent (sortNo) and the WBS number come from the array order.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map<string | null, number>();
const wbsOf = new Map<string, string>();
const sortOf = new Map<string, number>();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// Flat grid rows (a parent id is enough to make a tree).
const rows: Row[] = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id) as string,
name,
assignee,
start,
end,
progress,
}));
// Data for the Gantt chart. It draws the values as given and does no date math.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id) as number,
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: 'Standard calendar (Mon-Fri)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: 'Task', width: 220 },
{ id: 'assignee', title: 'Assignee', width: 110 },
{ id: 'start', title: 'Start', width: 100 },
{ id: 'end', title: 'End', width: 100 },
{ id: 'progress', title: 'Progress (%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// Keep row and header heights equal to the chart so the lines line up (header 48, row 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// Put the Gantt chart next to the grid: move the grid element into the left pane and join both with createSplitView.
function mountGantt(api: GridApi<Row>, ganttOptions: Parameters<typeof createGantt>[1] = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement as HTMLElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type Fields = { plannedStart?: string; plannedEnd?: string; progressPct?: number };
type Mode = 'normal' | 'offline' | 'slow';
type SrvTask = (typeof data.tasks)[number];
type Reply = {
status: number;
body: { code?: string; tasks?: SrvTask[]; task?: SrvTask; id?: string };
};
// Writes the change into the grid row.
function syncRow(
api: GridApi<Row>,
t: { id: string; plannedStart: string | null; plannedEnd: string | null; progressPct: number },
) {
// Don't write into `rows`: the grid holds those very objects, so an update equal to the old row changes nothing on screen.
const row = api.getRowByKey(t.id);
if (!row) return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso: string, n: number) =>
new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode: Mode = 'normal';
let view: ReturnType<typeof mountGantt> | null = null;
let other: (() => void) | null = null;
// A changed setting is acknowledged at once (log + a note over the chart). It applies to the next edit.
let logLine: ((message: LogText) => void) | null = null;
function acknowledge(text: string) {
logLine?.(text);
const box = view?.box;
if (!box) return;
let note = box.querySelector<HTMLElement>('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = text;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set<ReturnType<typeof setTimeout>>();
const wait = (ms: number) =>
new Promise<void>((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// A fake server: it owns the real tasks and links (versions and summary roll-up included).
const server = {
tasks: data.tasks.map((t) => ({ ...t })) as SrvTask[],
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// The version of each task the chart knows (for optimistic locking)
const versions = new Map<string, number>(data.tasks.map((t) => [t.id, t.version]));
const find = (id: string) => server.tasks.find((t) => t.id === id) as SrvTask;
// Summary dates come from the children (the server's job).
function rollUp(id: string | null, changed: SrvTask[]) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart as string).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd as string)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(
call:
| { kind: 'schedule'; id: string; version: number; f: Fields }
| { kind: 'link'; from: string; to: string }
| { kind: 'unlink'; id: string },
): Promise<Reply> {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline') throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren) return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed: SrvTask[] = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// Puts a time limit on the call. The chart waits forever, so the host must set the limit.
async function send(call: Parameters<typeof request>[0]): Promise<Reply> {
const limit = new Promise<never>((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// Accepted: the tasks the server returns (summaries included) go to the chart and the grid.
const accept = (intentId: string, tasks: SrvTask[]) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e: unknown, status?: number, code?: string): string => {
if (code === 'VERSION_CONFLICT')
return 'Someone else changed it first (409). Showing the server values.';
if (code === 'SUMMARY_READONLY')
return 'Summaries are computed by the server (422). They cannot be linked.';
if (e instanceof Error && e.message === 'timeout')
return 'The server did not answer in time (timeout).';
if (e !== undefined) return 'Could not reach the server (network error).';
return String(status);
};
async function schedule(intentId: string, taskId: string, f: Fields) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId) as number,
f,
});
if (!alive) return;
if (res.status === 200) {
(res.body.tasks as SrvTask[]).forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks as SrvTask[]);
log(`Task ${taskId} confirmed`);
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // sync to the server's values
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log(`Task ${taskId} reverted: ${why}`);
} catch (e) {
if (!alive) return;
gantt.revertIntent(intentId); // timeout and network errors take the same path
const why = explain(e);
log(`Task ${taskId} reverted: ${why}`);
}
}
const deps = server.deps;
const push = () =>
gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on(
'task-move',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-resize',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-progress',
(e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct }),
),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive) return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log(`Link refused: ${why}`);
return;
}
deps.push({
id: res.body.id as string,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // links come back through setData
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${res.body.id} created`);
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Link refused: ${why}`);
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive) return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0) deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${e.dependencyId} deleted`);
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Delete refused: ${why}`);
}
}),
];
// Pretends another user pushed task 7 two days later on the server. The chart does not know.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart as string, 2);
t.plannedEnd = addDays(t.plannedEnd as string, 2);
t.version += 1;
log('Task 7 changed on the server (the chart does not know). Now drag task 7.');
};
log('Editing is on. Try the server modes.');
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label: Record<string, string> = {
normal: 'Normal',
slow: 'No answer',
offline: 'Offline',
};
const e = label[value ?? ''] ?? Object.values(label)[0] ?? '';
acknowledge(`Server mode: ${e}`);
},
other: () => other?.(),
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/angular @maxgrid/gantt.
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="Server mode"
[disabled]="!api"
(change)="api && actions.mode(api, $any($event.target).value)"
>
<option value="normal" selected>Normal</option>
<option value="slow">No answer</option>
<option value="offline">Offline</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.other(api)"
>Another user edits task 7</button>
</div>
<mx-grid style="height: 480px" [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 { createGantt, createSplitView } from '@maxgrid/gantt';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: string;
parentId: string | null;
wbs: string;
name: string;
assignee: string;
start: string;
end: string;
progress: number;
}
type Status = 'TODO' | 'IN_PROGRESS' | 'DONE';
// [id, parent, task, assignee, start, end, progress, status]. No dates means unscheduled; start = end means a milestone.
const T: Array<[string, string | null, string, string, string, string, number, Status]> = [
['1', null, 'Website renewal', 'Liam Carter', '2026-12-01', '2027-03-05', 0, 'TODO'],
['2', '1', 'Planning', 'Emma Stone', '2026-12-01', '2026-12-11', 0, 'TODO'],
['3', '2', 'Requirements', 'Emma Stone', '2026-12-01', '2026-12-08', 60, 'IN_PROGRESS'],
['4', '2', 'Competitor review', 'Liam Carter', '2026-12-03', '2026-12-10', 30, 'IN_PROGRESS'],
['5', '2', 'Scope sign-off', 'Emma Stone', '2026-12-11', '2026-12-11', 0, 'TODO'],
['6', '1', 'Design', 'Noah Reed', '2026-12-14', '2027-01-13', 0, 'TODO'],
['7', '6', 'Wireframes', 'Noah Reed', '2026-12-14', '2026-12-23', 40, 'IN_PROGRESS'],
['8', '6', 'Visual design', 'Noah Reed', '2026-12-21', '2027-01-08', 10, 'IN_PROGRESS'],
['9', '6', 'Icon set', 'Olivia Park', '2026-12-28', '2027-01-08', 0, 'TODO'],
['10', '6', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['11', '1', 'Build', 'Ethan Cole', '2027-01-11', '2027-02-19', 0, 'TODO'],
['12', '11', 'Front end', 'Olivia Park', '2027-01-11', '2027-02-05', 0, 'TODO'],
['13', '11', 'Back end', 'Ethan Cole', '2027-01-11', '2027-02-12', 0, 'TODO'],
['14', '11', 'Search feature', 'Liam Carter', '2027-01-25', '2027-02-12', 0, 'TODO'],
['15', '11', 'Payments', 'Ethan Cole', '2027-01-25', '2027-02-19', 0, 'TODO'],
['16', '11', 'Content entry', 'Emma Stone', '2027-01-18', '2027-02-12', 0, 'TODO'],
['17', '11', 'Integration', 'Ethan Cole', '2027-02-08', '2027-02-19', 0, 'TODO'],
['18', '1', 'Launch', 'Liam Carter', '2027-02-15', '2027-03-01', 0, 'TODO'],
['19', '18', 'QA', 'Olivia Park', '2027-02-15', '2027-02-26', 0, 'TODO'],
['20', '18', 'Go-live', 'Liam Carter', '2027-03-01', '2027-03-01', 0, 'TODO'],
['21', '1', 'Handover', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['22', '21', 'Training', 'Emma Stone', '2027-02-22', '2027-03-05', 0, 'TODO'],
['23', '21', 'Docs', 'Olivia Park', '2027-02-22', '2027-03-03', 0, 'TODO'],
];
// [predecessor, successor, type, lag (working days)]
const D: Array<[string, string, 'FS' | 'SS' | 'FF' | 'SF', number]> = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '10', 'FF', 0],
['10', '12', 'FS', 0],
['10', '13', 'FS', 0],
['12', '17', 'FF', 0],
['13', '17', 'FS', 0],
['17', '19', 'FS', 0],
['19', '20', 'FS', 0],
];
// The order inside a parent (sortNo) and the WBS number come from the array order.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map<string | null, number>();
const wbsOf = new Map<string, string>();
const sortOf = new Map<string, number>();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, n);
wbsOf.set(id, parent === null ? String(n) : wbsOf.get(parent) + '.' + n);
}
// Flat grid rows (a parent id is enough to make a tree).
const rows: Row[] = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
wbs: wbsOf.get(id) as string,
name,
assignee,
start,
end,
progress,
}));
// Data for the Gantt chart. It draws the values as given and does no date math.
const data = {
tasks: T.map(([id, parentId, name, assignee, start, end, progressPct, status]) => ({
id,
parentId,
sortNo: sortOf.get(id) as number,
name,
status,
plannedStart: start || null,
plannedEnd: end || null,
progressPct,
isMilestone: start !== '' && start === end,
hasChildren: parents.has(id),
calendarId: null,
wbsCode: wbsOf.get(id),
assigneeName: assignee,
version: 1,
})),
dependencies: D.map(([predecessorId, successorId, depType, lagDays], n) => ({
id: 'd' + (n + 1),
predecessorId,
successorId,
depType,
lagDays,
})),
calendars: [
{
id: 'std',
name: 'Standard calendar (Mon-Fri)',
workDays: 31,
isDefault: true,
exceptions: [],
},
],
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'wbs', title: 'WBS', width: 70 },
{ id: 'name', title: 'Task', width: 220 },
{ id: 'assignee', title: 'Assignee', width: 110 },
{ id: 'start', title: 'Start', width: 100 },
{ id: 'end', title: 'End', width: 100 },
{ id: 'progress', title: 'Progress (%)', kind: 'number', width: 90, align: 'end' },
],
rows,
rowKey: 'id',
// Keep row and header heights equal to the chart so the lines line up (header 48, row 32).
rowHeight: 32,
headerHeight: 48,
verticalScroll: 'external',
selection: 'single',
tree: { parentKey: 'parentId', column: 'name', expandDepth: 'all' },
};
// Put the Gantt chart next to the grid: move the grid element into the left pane and join both with createSplitView.
function mountGantt(api: GridApi<Row>, ganttOptions: Parameters<typeof createGantt>[1] = {}) {
const gridEl = api.getGridElement();
const host = gridEl.parentElement as HTMLElement;
const box = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
box.style.cssText = 'position: relative; width: 100%; height: 100%;';
box.append(left, right);
host.append(box);
left.append(gridEl);
const split = createSplitView({
left,
right,
container: box,
initial: 0.45,
min: box.clientWidth < 600 ? 110 : 240,
});
const gantt = createGantt(right, {
rowHeight: 32,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type Fields = { plannedStart?: string; plannedEnd?: string; progressPct?: number };
type Mode = 'normal' | 'offline' | 'slow';
type SrvTask = (typeof data.tasks)[number];
type Reply = {
status: number;
body: { code?: string; tasks?: SrvTask[]; task?: SrvTask; id?: string };
};
// Writes the change into the grid row.
function syncRow(
api: GridApi<Row>,
t: { id: string; plannedStart: string | null; plannedEnd: string | null; progressPct: number },
) {
// Don't write into `rows`: the grid holds those very objects, so an update equal to the old row changes nothing on screen.
const row = api.getRowByKey(t.id);
if (!row) return;
api.updateRows([
{ ...row, start: t.plannedStart ?? '', end: t.plannedEnd ?? '', progress: t.progressPct },
]);
}
const addDays = (iso: string, n: number) =>
new Date(Date.parse(iso + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const TIMEOUT_MS = 1500;
let mode: Mode = 'normal';
let view: ReturnType<typeof mountGantt> | null = null;
let other: (() => void) | null = null;
// A changed setting is acknowledged at once (log + a note over the chart). It applies to the next edit.
let logLine: ((message: LogText) => void) | null = null;
function acknowledge(text: string) {
logLine?.(text);
const box = view?.box;
if (!box) return;
let note = box.querySelector<HTMLElement>('[data-note]');
if (!note) {
note = document.createElement('div');
note.dataset['note'] = '1';
note.setAttribute('role', 'status');
note.style.cssText =
'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
box.append(note);
}
note.textContent = text;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logLine = log;
mode = 'normal';
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
let alive = true;
const timers = new Set<ReturnType<typeof setTimeout>>();
const wait = (ms: number) =>
new Promise<void>((resolve) => {
const t = setTimeout(() => (timers.delete(t), resolve()), ms);
timers.add(t);
});
// A fake server: it owns the real tasks and links (versions and summary roll-up included).
const server = {
tasks: data.tasks.map((t) => ({ ...t })) as SrvTask[],
deps: data.dependencies.map((d) => ({ ...d })),
nextDep: 100,
};
// The version of each task the chart knows (for optimistic locking)
const versions = new Map<string, number>(data.tasks.map((t) => [t.id, t.version]));
const find = (id: string) => server.tasks.find((t) => t.id === id) as SrvTask;
// Summary dates come from the children (the server's job).
function rollUp(id: string | null, changed: SrvTask[]) {
while (id !== null) {
const parent = find(id);
const kids = server.tasks.filter((t) => t.parentId === id && t.plannedStart && t.plannedEnd);
parent.plannedStart = kids.map((k) => k.plannedStart as string).sort()[0] ?? null;
parent.plannedEnd =
kids
.map((k) => k.plannedEnd as string)
.sort()
.reverse()[0] ?? null;
parent.version += 1;
changed.push({ ...parent });
id = parent.parentId;
}
}
async function request(
call:
| { kind: 'schedule'; id: string; version: number; f: Fields }
| { kind: 'link'; from: string; to: string }
| { kind: 'unlink'; id: string },
): Promise<Reply> {
await wait(mode === 'slow' ? TIMEOUT_MS * 3 : 350);
if (mode === 'offline') throw new TypeError('Failed to fetch');
if (call.kind === 'schedule') {
const t = find(call.id);
if (call.version !== t.version)
return { status: 409, body: { code: 'VERSION_CONFLICT', task: { ...t } } };
if (t.hasChildren) return { status: 422, body: { code: 'SUMMARY_READONLY' } };
Object.assign(t, call.f, { version: t.version + 1 });
const changed: SrvTask[] = [{ ...t }];
rollUp(t.parentId, changed);
return { status: 200, body: { tasks: changed } };
}
if (call.kind === 'link') {
if (find(call.from).hasChildren || find(call.to).hasChildren)
return { status: 422, body: { code: 'SUMMARY_READONLY' } };
server.nextDep += 1;
return { status: 200, body: { id: 'd' + server.nextDep } };
}
return { status: 200, body: {} };
}
// Puts a time limit on the call. The chart waits forever, so the host must set the limit.
async function send(call: Parameters<typeof request>[0]): Promise<Reply> {
const limit = new Promise<never>((_, reject) => {
const t = setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS);
timers.add(t);
});
return Promise.race([request(call), limit]);
}
// Accepted: the tasks the server returns (summaries included) go to the chart and the grid.
const accept = (intentId: string, tasks: SrvTask[]) => {
gantt.applyPatch({ tasks, intentId });
tasks.forEach((t) => syncRow(api, t));
};
const explain = (e: unknown, status?: number, code?: string): string => {
if (code === 'VERSION_CONFLICT')
return 'Someone else changed it first (409). Showing the server values.';
if (code === 'SUMMARY_READONLY')
return 'Summaries are computed by the server (422). They cannot be linked.';
if (e instanceof Error && e.message === 'timeout')
return 'The server did not answer in time (timeout).';
if (e !== undefined) return 'Could not reach the server (network error).';
return String(status);
};
async function schedule(intentId: string, taskId: string, f: Fields) {
try {
const res = await send({
kind: 'schedule',
id: taskId,
version: versions.get(taskId) as number,
f,
});
if (!alive) return;
if (res.status === 200) {
(res.body.tasks as SrvTask[]).forEach((t) => versions.set(t.id, t.version));
accept(intentId, res.body.tasks as SrvTask[]);
log(`Task ${taskId} confirmed`);
return;
}
gantt.revertIntent(intentId);
if (res.body.task) {
versions.set(taskId, res.body.task.version);
gantt.applyPatch({ tasks: [res.body.task] }); // sync to the server's values
syncRow(api, res.body.task);
}
const why = explain(undefined, res.status, res.body.code);
log(`Task ${taskId} reverted: ${why}`);
} catch (e) {
if (!alive) return;
gantt.revertIntent(intentId); // timeout and network errors take the same path
const why = explain(e);
log(`Task ${taskId} reverted: ${why}`);
}
}
const deps = server.deps;
const push = () =>
gantt.setData({
tasks: server.tasks.map((t) => ({ ...t })),
dependencies: deps.map((d) => ({ ...d })),
calendars: data.calendars,
});
const offs = [
gantt.on(
'task-move',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-resize',
(e) =>
void schedule(e.intentId, e.taskId, {
plannedStart: e.plannedStart,
plannedEnd: e.plannedEnd,
}),
),
gantt.on(
'task-progress',
(e) => void schedule(e.intentId, e.taskId, { progressPct: e.progressPct }),
),
gantt.on('dependency-create', async (e) => {
try {
const res = await send({ kind: 'link', from: e.predecessorId, to: e.successorId });
if (!alive) return;
if (res.status !== 200) {
gantt.revertIntent(e.intentId);
const why = explain(undefined, res.status, res.body.code);
log(`Link refused: ${why}`);
return;
}
deps.push({
id: res.body.id as string,
predecessorId: e.predecessorId,
successorId: e.successorId,
depType: e.depType,
lagDays: e.lagDays,
});
push(); // links come back through setData
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${res.body.id} created`);
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Link refused: ${why}`);
}
}),
gantt.on('dependency-delete', async (e) => {
try {
await send({ kind: 'unlink', id: e.dependencyId });
if (!alive) return;
const i = deps.findIndex((d) => d.id === e.dependencyId);
if (i >= 0) deps.splice(i, 1);
push();
gantt.applyPatch({ tasks: [], intentId: e.intentId });
log(`Link ${e.dependencyId} deleted`);
} catch (err) {
if (!alive) return;
gantt.revertIntent(e.intentId);
const why = explain(err);
log(`Delete refused: ${why}`);
}
}),
];
// Pretends another user pushed task 7 two days later on the server. The chart does not know.
other = () => {
const t = find('7');
t.plannedStart = addDays(t.plannedStart as string, 2);
t.plannedEnd = addDays(t.plannedEnd as string, 2);
t.version += 1;
log('Task 7 changed on the server (the chart does not know). Now drag task 7.');
};
log('Editing is on. Try the server modes.');
return () => {
alive = false;
timers.forEach(clearTimeout);
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
other = null;
};
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'offline' || value === 'slow' ? value : 'normal';
const label: Record<string, string> = {
normal: 'Normal',
slow: 'No answer',
offline: 'Offline',
};
const e = label[value ?? ''] ?? Object.values(label)[0] ?? '';
acknowledge(`Server mode: ${e}`);
},
other: () => other?.(),
};