더블클릭으로 작업 편집 창 열기Open an edit dialog on double click
막대를 더블클릭하거나 Enter를 누르면 task-open이 오고, 앱이 만든 편집 창이 열려요. 저장하면 서버 승인 뒤 차트와 표가 같이 바뀌어요.Double-click a bar or press Enter and task-open arrives; the app opens its own edit dialog. After the host approves, the chart and the grid change together.
코드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="server">
<option value="approve" selected>승인(0.4초)</option>
<option value="refuse">거절(409)</option>
</select>
</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('server').addEventListener('change', (event) => actions.server(api, event.target.value));import { createGantt, createSplitView } from '@maxgrid/gantt';
// [id, 부모, 작업, 담당자, 시작, 종료, 진행률, 상태]. 날짜가 비면 일정 없음, 시작=종료면 마일스톤이에요.
const T = [
['1', null, '웹사이트 개편', '이준호', '2026-12-01', '2027-01-25', 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', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', '출시', '이준호', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', '품질 점검', '한지우', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', '출시일', '이준호', '2027-01-25', '2027-01-25', 0, 'TODO'],
];
// [앞 작업, 뒤 작업, 종류, 지연(작업일)]
const D = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = 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);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
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,
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: '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, 행 40).
rowHeight: 40,
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,
});
// 좁은 컨테이너(600px 미만)에서는 앞의 열만 남겨 차트 자리를 확보해요. 넓어지면 열이 돌아와요.
const fitColumns = () => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress'])
api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
// 호스트(앱)가 자기 데이터를 따로 쥐어요. 차트에 넘긴 객체를 직접 고치지 않고, 바뀐 값은 applyPatch로 알려요.
const hostTasks = new Map();
const timers = new Set();
let refuse = false;
let view = null;
let openDialogEl = null;
// 가짜 서버: 0.4초 뒤에 승인하거나, 위의 "서버 응답"이 "거절"이면 409로 거절해요.
function fakeServer() {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse)
reject(new Error('409'));
else
resolve();
}, 400);
timers.add(timer);
});
}
// 표 행을 고쳐 써요. 행은 항상 api.getRowByKey로 꺼낸 것을 복사해서 바꿔요(표가 쥔 객체를 직접 고치지 않아요).
function syncRow(api, id, f) {
const row = api.getRowByKey(id);
if (!row)
return;
const next = { ...row };
if (f.name !== undefined)
next.name = f.name;
if (f.assigneeName !== undefined)
next.assignee = f.assigneeName;
if (f.plannedStart !== undefined)
next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined)
next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined)
next.progress = f.progressPct;
api.updateRows([next]);
}
// 서버가 승인한 변경을 호스트 데이터, 차트(applyPatch), 표에 같이 반영해요.
function commit(gantt, api, id, f, intentId) {
const old = hostTasks.get(id);
if (old)
hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL = {
TODO: `할 일`,
IN_PROGRESS: `진행 중`,
DONE: `완료`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make(tag, props = {}, ...kids) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props))
node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label, control, wide = false) {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// 편집 창의 입력칸과 버튼을 만들어요. 값은 호스트가 쥔 작업에서 가져와요.
function buildForm(task) {
const input = (type, value, extra = {}) => make('input', { type, value, ...extra });
const select = (values, labels, value) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL);
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(states, states.map((s) => STATUS_LABEL[s]), task.status),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `진행률(%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `저장`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `닫기` : `취소`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(make('h2', { id: 'ed-title' }, `작업 편집` + ' · ' + task.name), field(`이름`, p.name, true), field(`담당자`, p.assignee), field(`상태`, p.status), field(`시작일`, p.start), field(`종료일`, p.end), field(`진행률(%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true), p.error, p.server);
if (task.hasChildren)
form.append(make('p', { class: 'ed-note' }, `요약 작업은 하위 작업에서 합산돼서 여기서 고칠 수 없어요.`));
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
// 입력 검사(이름이 비지 않았나, 종료일이 시작일보다 앞서지 않나)와 입력칸끼리의 연동을 이어요. 오류는 창 안에 글로 보여요.
function wireForm(f, task) {
const clamp = (v) => String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = () => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `이름을 입력해 주세요.`
: badDate
? `종료일은 시작일과 같거나 뒤여야 해요.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone)
f.end.value = f.start.value; // 마일스톤은 종료일이 시작일을 따라가요.
validate();
});
for (const input of [f.name, f.end])
input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off)
c.disabled = true; // 요약 작업은 읽기 전용, 마일스톤은 날짜 하나만 고쳐요.
return validate;
}
// 저장: 가짜 서버가 승인하면 차트·표에 반영하고 닫아요. 거절(409)이면 창 안에 글로 알리고 열어 둬요.
function submitEdit(f, id, ctx, done) {
const patch = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `저장하는 중…`;
fakeServer().then(() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log({
ko: `${id}번 저장 승인: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
en: `Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
});
done(true);
}, () => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `서버가 409로 거절했어요. 다른 사람이 먼저 고친 작업이에요. 창은 열려 있으니 다시 저장하거나 취소하세요.`;
ctx.log({
ko: `${id}번 저장 거절(409): 창은 그대로 열려 있어요`,
en: `Task ${id} save refused (409): the dialog stays open`,
});
done(false);
});
}
// 더블클릭·Enter로 열린 작업의 편집 창을 열어요. 앱이 직접 만든 네이티브 <dialog>예요(MaxGrid는 창을 주지 않아요).
function openDialog(ctx, id) {
const task = hostTasks.get(id);
if (!task || openDialogEl)
return;
const opener = document.activeElement;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = () => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving)
e.preventDefault(); // 저장하는 중에는 Esc로 닫지 않아요.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// 차트가 그림을 다시 그린 뒤에도 포커스가 막대에 있게 한 번 더 확인해요.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement))
focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren)
return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved)
dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log({ ko: `${id}번 작업의 편집 창을 열었어요`, en: `Opened the edit dialog for task ${id}` });
}
export function setup(api, log) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks)
hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// 끌어서 고치는 편집도 같은 가짜 서버로 가요: 승인하면 확정하고, 거절하면 revertIntent로 막대를 되돌려요.
const settle = (intentId, id, f) => fakeServer().then(() => commit(gantt, api, id, f, intentId), () => {
gantt.revertIntent(intentId);
log({
ko: `${id}번 끌기 거절(409): 막대가 원래대로 돌아가요`,
en: `Task ${id} drag refused (409): the bar goes back`,
});
});
const onRange = (e) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log({
ko: `막대를 더블클릭하거나 막대에서 Enter를 눌러 보세요`,
en: `Double-click a bar, or press Enter on a focused bar`,
});
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
export const actions = {
// 서버 응답을 바꿔요: "approve"면 0.4초 뒤 승인, "refuse"면 409로 거절해요. 다음 저장·편집부터 적용돼요.
server: (_api, value) => {
refuse = value === 'refuse';
},
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>더블클릭으로 작업 편집 창 열기</title>
</head>
<body>
<div class="toolbar">
<select aria-label="서버 응답" id="server">
<option value="approve" selected>승인(0.4초)</option>
<option value="refuse">거절(409)</option>
</select>
</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-01-25', 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', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', '출시', '이준호', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', '품질 점검', '한지우', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', '출시일', '이준호', '2027-01-25', '2027-01-25', 0, 'TODO'],
];
// [앞 작업, 뒤 작업, 종류, 지연(작업일)]
const D = [
['3', '5', 'FS', 0],
['4', '5', 'FS', 0],
['5', '7', 'FS', 0],
['7', '8', 'SS', 3],
['8', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = 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);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
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,
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: '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, 행 40).
rowHeight: 40,
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,
});
// 좁은 컨테이너(600px 미만)에서는 앞의 열만 남겨 차트 자리를 확보해요. 넓어지면 열이 돌아와요.
const fitColumns = () => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress'])
api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
// 호스트(앱)가 자기 데이터를 따로 쥐어요. 차트에 넘긴 객체를 직접 고치지 않고, 바뀐 값은 applyPatch로 알려요.
const hostTasks = new Map();
const timers = new Set();
let refuse = false;
let view = null;
let openDialogEl = null;
// 가짜 서버: 0.4초 뒤에 승인하거나, 위의 "서버 응답"이 "거절"이면 409로 거절해요.
function fakeServer() {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse)
reject(new Error('409'));
else
resolve();
}, 400);
timers.add(timer);
});
}
// 표 행을 고쳐 써요. 행은 항상 api.getRowByKey로 꺼낸 것을 복사해서 바꿔요(표가 쥔 객체를 직접 고치지 않아요).
function syncRow(api, id, f) {
const row = api.getRowByKey(id);
if (!row)
return;
const next = { ...row };
if (f.name !== undefined)
next.name = f.name;
if (f.assigneeName !== undefined)
next.assignee = f.assigneeName;
if (f.plannedStart !== undefined)
next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined)
next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined)
next.progress = f.progressPct;
api.updateRows([next]);
}
// 서버가 승인한 변경을 호스트 데이터, 차트(applyPatch), 표에 같이 반영해요.
function commit(gantt, api, id, f, intentId) {
const old = hostTasks.get(id);
if (old)
hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL = {
TODO: `할 일`,
IN_PROGRESS: `진행 중`,
DONE: `완료`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make(tag, props = {}, ...kids) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props))
node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label, control, wide = false) {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// 편집 창의 입력칸과 버튼을 만들어요. 값은 호스트가 쥔 작업에서 가져와요.
function buildForm(task) {
const input = (type, value, extra = {}) => make('input', { type, value, ...extra });
const select = (values, labels, value) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL);
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(states, states.map((s) => STATUS_LABEL[s]), task.status),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `진행률(%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `저장`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `닫기` : `취소`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(make('h2', { id: 'ed-title' }, `작업 편집` + ' · ' + task.name), field(`이름`, p.name, true), field(`담당자`, p.assignee), field(`상태`, p.status), field(`시작일`, p.start), field(`종료일`, p.end), field(`진행률(%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true), p.error, p.server);
if (task.hasChildren)
form.append(make('p', { class: 'ed-note' }, `요약 작업은 하위 작업에서 합산돼서 여기서 고칠 수 없어요.`));
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
// 입력 검사(이름이 비지 않았나, 종료일이 시작일보다 앞서지 않나)와 입력칸끼리의 연동을 이어요. 오류는 창 안에 글로 보여요.
function wireForm(f, task) {
const clamp = (v) => String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = () => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `이름을 입력해 주세요.`
: badDate
? `종료일은 시작일과 같거나 뒤여야 해요.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone)
f.end.value = f.start.value; // 마일스톤은 종료일이 시작일을 따라가요.
validate();
});
for (const input of [f.name, f.end])
input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off)
c.disabled = true; // 요약 작업은 읽기 전용, 마일스톤은 날짜 하나만 고쳐요.
return validate;
}
// 저장: 가짜 서버가 승인하면 차트·표에 반영하고 닫아요. 거절(409)이면 창 안에 글로 알리고 열어 둬요.
function submitEdit(f, id, ctx, done) {
const patch = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `저장하는 중…`;
fakeServer().then(() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log({
ko: `${id}번 저장 승인: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
en: `Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
});
done(true);
}, () => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `서버가 409로 거절했어요. 다른 사람이 먼저 고친 작업이에요. 창은 열려 있으니 다시 저장하거나 취소하세요.`;
ctx.log({
ko: `${id}번 저장 거절(409): 창은 그대로 열려 있어요`,
en: `Task ${id} save refused (409): the dialog stays open`,
});
done(false);
});
}
// 더블클릭·Enter로 열린 작업의 편집 창을 열어요. 앱이 직접 만든 네이티브 <dialog>예요(MaxGrid는 창을 주지 않아요).
function openDialog(ctx, id) {
const task = hostTasks.get(id);
if (!task || openDialogEl)
return;
const opener = document.activeElement;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = () => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving)
e.preventDefault(); // 저장하는 중에는 Esc로 닫지 않아요.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// 차트가 그림을 다시 그린 뒤에도 포커스가 막대에 있게 한 번 더 확인해요.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement))
focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren)
return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved)
dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log({ ko: `${id}번 작업의 편집 창을 열었어요`, en: `Opened the edit dialog for task ${id}` });
}
function setup(api, log) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks)
hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// 끌어서 고치는 편집도 같은 가짜 서버로 가요: 승인하면 확정하고, 거절하면 revertIntent로 막대를 되돌려요.
const settle = (intentId, id, f) => fakeServer().then(() => commit(gantt, api, id, f, intentId), () => {
gantt.revertIntent(intentId);
log({
ko: `${id}번 끌기 거절(409): 막대가 원래대로 돌아가요`,
en: `Task ${id} drag refused (409): the bar goes back`,
});
});
const onRange = (e) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log({
ko: `막대를 더블클릭하거나 막대에서 Enter를 눌러 보세요`,
en: `Double-click a bar, or press Enter on a focused bar`,
});
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
const actions = {
// 서버 응답을 바꿔요: "approve"면 0.4초 뒤 승인, "refuse"면 409로 거절해요. 다음 저장·편집부터 적용돼요.
server: (_api, value) => {
refuse = value === 'refuse';
},
};
options.ariaLabel = "더블클릭으로 작업 편집 창 열기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('server').addEventListener('change', (event) => actions.server(api, event.target.value));
</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.server(api, event.target.value)}
>
<option value="approve">승인(0.4초)</option>
<option value="refuse">거절(409)</option>
</select>
</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;
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-01-25', 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', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', '출시', '이준호', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', '품질 점검', '한지우', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', '출시일', '이준호', '2027-01-25', '2027-01-25', 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', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map<string | null, number>();
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);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows: Row[] = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
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,
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: '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, 행 40).
rowHeight: 40,
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,
});
// 좁은 컨테이너(600px 미만)에서는 앞의 열만 남겨 차트 자리를 확보해요. 넓어지면 열이 돌아와요.
const fitColumns = (): void => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress']) api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type HostTask = (typeof data.tasks)[number];
type Fields = Partial<
Pick<HostTask, 'name' | 'assigneeName' | 'status' | 'plannedStart' | 'plannedEnd' | 'progressPct'>
>;
// 호스트(앱)가 자기 데이터를 따로 쥐어요. 차트에 넘긴 객체를 직접 고치지 않고, 바뀐 값은 applyPatch로 알려요.
const hostTasks = new Map<string, HostTask>();
const timers = new Set<ReturnType<typeof setTimeout>>();
let refuse = false;
let view: ReturnType<typeof mountGantt> | null = null;
let openDialogEl: HTMLDialogElement | null = null;
// 가짜 서버: 0.4초 뒤에 승인하거나, 위의 "서버 응답"이 "거절"이면 409로 거절해요.
function fakeServer(): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse) reject(new Error('409'));
else resolve();
}, 400);
timers.add(timer);
});
}
// 표 행을 고쳐 써요. 행은 항상 api.getRowByKey로 꺼낸 것을 복사해서 바꿔요(표가 쥔 객체를 직접 고치지 않아요).
function syncRow(api: GridApi<Row>, id: string, f: Fields) {
const row = api.getRowByKey(id);
if (!row) return;
const next = { ...row };
if (f.name !== undefined) next.name = f.name;
if (f.assigneeName !== undefined) next.assignee = f.assigneeName;
if (f.plannedStart !== undefined) next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined) next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined) next.progress = f.progressPct;
api.updateRows([next]);
}
// 서버가 승인한 변경을 호스트 데이터, 차트(applyPatch), 표에 같이 반영해요.
function commit(gantt: Gantt, api: GridApi<Row>, id: string, f: Fields, intentId?: string) {
const old = hostTasks.get(id);
if (old) hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL: Record<Status, string> = {
TODO: `할 일`,
IN_PROGRESS: `진행 중`,
DONE: `완료`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make<K extends keyof HTMLElementTagNameMap>(
tag: K,
props: Record<string, string> = {},
...kids: Array<Node | string>
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props)) node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label: string, control: HTMLElement, wide = false): HTMLLabelElement {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// 편집 창의 입력칸과 버튼을 만들어요. 값은 호스트가 쥔 작업에서 가져와요.
function buildForm(task: HostTask) {
const input = (type: string, value: string, extra: Record<string, string> = {}) =>
make('input', { type, value, ...extra });
const select = (values: string[], labels: string[], value: string) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL) as Status[];
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(
states,
states.map((s) => STATUS_LABEL[s]),
task.status,
),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `진행률(%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `저장`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `닫기` : `취소`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(
make('h2', { id: 'ed-title' }, `작업 편집` + ' · ' + task.name),
field(`이름`, p.name, true),
field(`담당자`, p.assignee),
field(`상태`, p.status),
field(`시작일`, p.start),
field(`종료일`, p.end),
field(`진행률(%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true),
p.error,
p.server,
);
if (task.hasChildren)
form.append(
make('p', { class: 'ed-note' }, `요약 작업은 하위 작업에서 합산돼서 여기서 고칠 수 없어요.`),
);
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
type Form = ReturnType<typeof buildForm>;
// 입력 검사(이름이 비지 않았나, 종료일이 시작일보다 앞서지 않나)와 입력칸끼리의 연동을 이어요. 오류는 창 안에 글로 보여요.
function wireForm(f: Form, task: HostTask): () => boolean {
const clamp = (v: string): string =>
String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = (): boolean => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `이름을 입력해 주세요.`
: badDate
? `종료일은 시작일과 같거나 뒤여야 해요.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone) f.end.value = f.start.value; // 마일스톤은 종료일이 시작일을 따라가요.
validate();
});
for (const input of [f.name, f.end]) input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off) c.disabled = true; // 요약 작업은 읽기 전용, 마일스톤은 날짜 하나만 고쳐요.
return validate;
}
// 저장: 가짜 서버가 승인하면 차트·표에 반영하고 닫아요. 거절(409)이면 창 안에 글로 알리고 열어 둬요.
function submitEdit(f: Form, id: string, ctx: Ctx, done: (saved: boolean) => void): void {
const patch: Fields = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value as Status,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `저장하는 중…`;
fakeServer().then(
() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log({
ko: `${id}번 저장 승인: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
en: `Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
});
done(true);
},
() => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `서버가 409로 거절했어요. 다른 사람이 먼저 고친 작업이에요. 창은 열려 있으니 다시 저장하거나 취소하세요.`;
ctx.log({
ko: `${id}번 저장 거절(409): 창은 그대로 열려 있어요`,
en: `Task ${id} save refused (409): the dialog stays open`,
});
done(false);
},
);
}
type Ctx = { gantt: Gantt; api: GridApi<Row>; log: (m: LogText) => void };
// 더블클릭·Enter로 열린 작업의 편집 창을 열어요. 앱이 직접 만든 네이티브 <dialog>예요(MaxGrid는 창을 주지 않아요).
function openDialog(ctx: Ctx, id: string) {
const task = hostTasks.get(id);
if (!task || openDialogEl) return;
const opener = document.activeElement as HTMLElement | null;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = (): void => {
const bar = view?.box.querySelector<SVGElement>('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving) e.preventDefault(); // 저장하는 중에는 Esc로 닫지 않아요.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// 차트가 그림을 다시 그린 뒤에도 포커스가 막대에 있게 한 번 더 확인해요.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement)) focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren) return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved) dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log({ ko: `${id}번 작업의 편집 창을 열었어요`, en: `Opened the edit dialog for task ${id}` });
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks) hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// 끌어서 고치는 편집도 같은 가짜 서버로 가요: 승인하면 확정하고, 거절하면 revertIntent로 막대를 되돌려요.
const settle = (intentId: string, id: string, f: Fields) =>
fakeServer().then(
() => commit(gantt, api, id, f, intentId),
() => {
gantt.revertIntent(intentId);
log({
ko: `${id}번 끌기 거절(409): 막대가 원래대로 돌아가요`,
en: `Task ${id} drag refused (409): the bar goes back`,
});
},
);
const onRange = (e: {
intentId: string;
taskId: string;
plannedStart: string;
plannedEnd: string;
}) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log({
ko: `막대를 더블클릭하거나 막대에서 Enter를 눌러 보세요`,
en: `Double-click a bar, or press Enter on a focused bar`,
});
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
export const actions = {
// 서버 응답을 바꿔요: "approve"면 0.4초 뒤 승인, "refuse"면 409로 거절해요. 다음 저장·편집부터 적용돼요.
server: (_api: GridApi<Row>, value?: string) => {
refuse = value === 'refuse';
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 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.server(api, ($event.target as HTMLSelectElement).value)"
>
<option value="approve" selected>승인(0.4초)</option>
<option value="refuse">거절(409)</option>
</select>
</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;
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-01-25', 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', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', '출시', '이준호', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', '품질 점검', '한지우', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', '출시일', '이준호', '2027-01-25', '2027-01-25', 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', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map<string | null, number>();
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);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows: Row[] = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
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,
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: '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, 행 40).
rowHeight: 40,
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,
});
// 좁은 컨테이너(600px 미만)에서는 앞의 열만 남겨 차트 자리를 확보해요. 넓어지면 열이 돌아와요.
const fitColumns = (): void => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress']) api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type HostTask = (typeof data.tasks)[number];
type Fields = Partial<
Pick<HostTask, 'name' | 'assigneeName' | 'status' | 'plannedStart' | 'plannedEnd' | 'progressPct'>
>;
// 호스트(앱)가 자기 데이터를 따로 쥐어요. 차트에 넘긴 객체를 직접 고치지 않고, 바뀐 값은 applyPatch로 알려요.
const hostTasks = new Map<string, HostTask>();
const timers = new Set<ReturnType<typeof setTimeout>>();
let refuse = false;
let view: ReturnType<typeof mountGantt> | null = null;
let openDialogEl: HTMLDialogElement | null = null;
// 가짜 서버: 0.4초 뒤에 승인하거나, 위의 "서버 응답"이 "거절"이면 409로 거절해요.
function fakeServer(): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse) reject(new Error('409'));
else resolve();
}, 400);
timers.add(timer);
});
}
// 표 행을 고쳐 써요. 행은 항상 api.getRowByKey로 꺼낸 것을 복사해서 바꿔요(표가 쥔 객체를 직접 고치지 않아요).
function syncRow(api: GridApi<Row>, id: string, f: Fields) {
const row = api.getRowByKey(id);
if (!row) return;
const next = { ...row };
if (f.name !== undefined) next.name = f.name;
if (f.assigneeName !== undefined) next.assignee = f.assigneeName;
if (f.plannedStart !== undefined) next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined) next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined) next.progress = f.progressPct;
api.updateRows([next]);
}
// 서버가 승인한 변경을 호스트 데이터, 차트(applyPatch), 표에 같이 반영해요.
function commit(gantt: Gantt, api: GridApi<Row>, id: string, f: Fields, intentId?: string) {
const old = hostTasks.get(id);
if (old) hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL: Record<Status, string> = {
TODO: `할 일`,
IN_PROGRESS: `진행 중`,
DONE: `완료`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make<K extends keyof HTMLElementTagNameMap>(
tag: K,
props: Record<string, string> = {},
...kids: Array<Node | string>
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props)) node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label: string, control: HTMLElement, wide = false): HTMLLabelElement {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// 편집 창의 입력칸과 버튼을 만들어요. 값은 호스트가 쥔 작업에서 가져와요.
function buildForm(task: HostTask) {
const input = (type: string, value: string, extra: Record<string, string> = {}) =>
make('input', { type, value, ...extra });
const select = (values: string[], labels: string[], value: string) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL) as Status[];
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(
states,
states.map((s) => STATUS_LABEL[s]),
task.status,
),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `진행률(%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `저장`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `닫기` : `취소`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(
make('h2', { id: 'ed-title' }, `작업 편집` + ' · ' + task.name),
field(`이름`, p.name, true),
field(`담당자`, p.assignee),
field(`상태`, p.status),
field(`시작일`, p.start),
field(`종료일`, p.end),
field(`진행률(%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true),
p.error,
p.server,
);
if (task.hasChildren)
form.append(
make('p', { class: 'ed-note' }, `요약 작업은 하위 작업에서 합산돼서 여기서 고칠 수 없어요.`),
);
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
type Form = ReturnType<typeof buildForm>;
// 입력 검사(이름이 비지 않았나, 종료일이 시작일보다 앞서지 않나)와 입력칸끼리의 연동을 이어요. 오류는 창 안에 글로 보여요.
function wireForm(f: Form, task: HostTask): () => boolean {
const clamp = (v: string): string =>
String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = (): boolean => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `이름을 입력해 주세요.`
: badDate
? `종료일은 시작일과 같거나 뒤여야 해요.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone) f.end.value = f.start.value; // 마일스톤은 종료일이 시작일을 따라가요.
validate();
});
for (const input of [f.name, f.end]) input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off) c.disabled = true; // 요약 작업은 읽기 전용, 마일스톤은 날짜 하나만 고쳐요.
return validate;
}
// 저장: 가짜 서버가 승인하면 차트·표에 반영하고 닫아요. 거절(409)이면 창 안에 글로 알리고 열어 둬요.
function submitEdit(f: Form, id: string, ctx: Ctx, done: (saved: boolean) => void): void {
const patch: Fields = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value as Status,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `저장하는 중…`;
fakeServer().then(
() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log({
ko: `${id}번 저장 승인: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
en: `Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
});
done(true);
},
() => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `서버가 409로 거절했어요. 다른 사람이 먼저 고친 작업이에요. 창은 열려 있으니 다시 저장하거나 취소하세요.`;
ctx.log({
ko: `${id}번 저장 거절(409): 창은 그대로 열려 있어요`,
en: `Task ${id} save refused (409): the dialog stays open`,
});
done(false);
},
);
}
type Ctx = { gantt: Gantt; api: GridApi<Row>; log: (m: LogText) => void };
// 더블클릭·Enter로 열린 작업의 편집 창을 열어요. 앱이 직접 만든 네이티브 <dialog>예요(MaxGrid는 창을 주지 않아요).
function openDialog(ctx: Ctx, id: string) {
const task = hostTasks.get(id);
if (!task || openDialogEl) return;
const opener = document.activeElement as HTMLElement | null;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = (): void => {
const bar = view?.box.querySelector<SVGElement>('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving) e.preventDefault(); // 저장하는 중에는 Esc로 닫지 않아요.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// 차트가 그림을 다시 그린 뒤에도 포커스가 막대에 있게 한 번 더 확인해요.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement)) focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren) return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved) dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log({ ko: `${id}번 작업의 편집 창을 열었어요`, en: `Opened the edit dialog for task ${id}` });
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks) hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// 끌어서 고치는 편집도 같은 가짜 서버로 가요: 승인하면 확정하고, 거절하면 revertIntent로 막대를 되돌려요.
const settle = (intentId: string, id: string, f: Fields) =>
fakeServer().then(
() => commit(gantt, api, id, f, intentId),
() => {
gantt.revertIntent(intentId);
log({
ko: `${id}번 끌기 거절(409): 막대가 원래대로 돌아가요`,
en: `Task ${id} drag refused (409): the bar goes back`,
});
},
);
const onRange = (e: {
intentId: string;
taskId: string;
plannedStart: string;
plannedEnd: string;
}) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log({
ko: `막대를 더블클릭하거나 막대에서 Enter를 눌러 보세요`,
en: `Double-click a bar, or press Enter on a focused bar`,
});
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
export const actions = {
// 서버 응답을 바꿔요: "approve"면 0.4초 뒤 승인, "refuse"면 409로 거절해요. 다음 저장·편집부터 적용돼요.
server: (_api: GridApi<Row>, value?: string) => {
refuse = value === 'refuse';
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 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.server(api, $any($event.target).value)"
>
<option value="approve" selected>승인(0.4초)</option>
<option value="refuse">거절(409)</option>
</select>
</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;
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-01-25', 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', '디자인 검토', '최하은', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', '출시', '이준호', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', '품질 점검', '한지우', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', '출시일', '이준호', '2027-01-25', '2027-01-25', 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', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', 'FS', 0],
];
// 같은 부모 안의 순서(sortNo)와 WBS 번호는 배열 순서에서 계산해요.
const parents = new Set(T.map((r) => r[1]));
const counts = new Map<string | null, number>();
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);
}
// 표에 넣을 평평한 행(부모 id만 알면 트리가 돼요).
const rows: Row[] = T.map(([id, parentId, name, assignee, start, end, progress]) => ({
id,
parentId,
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,
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: '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, 행 40).
rowHeight: 40,
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,
});
// 좁은 컨테이너(600px 미만)에서는 앞의 열만 남겨 차트 자리를 확보해요. 넓어지면 열이 돌아와요.
const fitColumns = (): void => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress']) api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'ko',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// 연결을 풀고 표를 원래 자리로 돌려놔요.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type HostTask = (typeof data.tasks)[number];
type Fields = Partial<
Pick<HostTask, 'name' | 'assigneeName' | 'status' | 'plannedStart' | 'plannedEnd' | 'progressPct'>
>;
// 호스트(앱)가 자기 데이터를 따로 쥐어요. 차트에 넘긴 객체를 직접 고치지 않고, 바뀐 값은 applyPatch로 알려요.
const hostTasks = new Map<string, HostTask>();
const timers = new Set<ReturnType<typeof setTimeout>>();
let refuse = false;
let view: ReturnType<typeof mountGantt> | null = null;
let openDialogEl: HTMLDialogElement | null = null;
// 가짜 서버: 0.4초 뒤에 승인하거나, 위의 "서버 응답"이 "거절"이면 409로 거절해요.
function fakeServer(): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse) reject(new Error('409'));
else resolve();
}, 400);
timers.add(timer);
});
}
// 표 행을 고쳐 써요. 행은 항상 api.getRowByKey로 꺼낸 것을 복사해서 바꿔요(표가 쥔 객체를 직접 고치지 않아요).
function syncRow(api: GridApi<Row>, id: string, f: Fields) {
const row = api.getRowByKey(id);
if (!row) return;
const next = { ...row };
if (f.name !== undefined) next.name = f.name;
if (f.assigneeName !== undefined) next.assignee = f.assigneeName;
if (f.plannedStart !== undefined) next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined) next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined) next.progress = f.progressPct;
api.updateRows([next]);
}
// 서버가 승인한 변경을 호스트 데이터, 차트(applyPatch), 표에 같이 반영해요.
function commit(gantt: Gantt, api: GridApi<Row>, id: string, f: Fields, intentId?: string) {
const old = hostTasks.get(id);
if (old) hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL: Record<Status, string> = {
TODO: `할 일`,
IN_PROGRESS: `진행 중`,
DONE: `완료`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make<K extends keyof HTMLElementTagNameMap>(
tag: K,
props: Record<string, string> = {},
...kids: Array<Node | string>
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props)) node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label: string, control: HTMLElement, wide = false): HTMLLabelElement {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// 편집 창의 입력칸과 버튼을 만들어요. 값은 호스트가 쥔 작업에서 가져와요.
function buildForm(task: HostTask) {
const input = (type: string, value: string, extra: Record<string, string> = {}) =>
make('input', { type, value, ...extra });
const select = (values: string[], labels: string[], value: string) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL) as Status[];
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(
states,
states.map((s) => STATUS_LABEL[s]),
task.status,
),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `진행률(%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `저장`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `닫기` : `취소`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(
make('h2', { id: 'ed-title' }, `작업 편집` + ' · ' + task.name),
field(`이름`, p.name, true),
field(`담당자`, p.assignee),
field(`상태`, p.status),
field(`시작일`, p.start),
field(`종료일`, p.end),
field(`진행률(%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true),
p.error,
p.server,
);
if (task.hasChildren)
form.append(
make('p', { class: 'ed-note' }, `요약 작업은 하위 작업에서 합산돼서 여기서 고칠 수 없어요.`),
);
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
type Form = ReturnType<typeof buildForm>;
// 입력 검사(이름이 비지 않았나, 종료일이 시작일보다 앞서지 않나)와 입력칸끼리의 연동을 이어요. 오류는 창 안에 글로 보여요.
function wireForm(f: Form, task: HostTask): () => boolean {
const clamp = (v: string): string =>
String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = (): boolean => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `이름을 입력해 주세요.`
: badDate
? `종료일은 시작일과 같거나 뒤여야 해요.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone) f.end.value = f.start.value; // 마일스톤은 종료일이 시작일을 따라가요.
validate();
});
for (const input of [f.name, f.end]) input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off) c.disabled = true; // 요약 작업은 읽기 전용, 마일스톤은 날짜 하나만 고쳐요.
return validate;
}
// 저장: 가짜 서버가 승인하면 차트·표에 반영하고 닫아요. 거절(409)이면 창 안에 글로 알리고 열어 둬요.
function submitEdit(f: Form, id: string, ctx: Ctx, done: (saved: boolean) => void): void {
const patch: Fields = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value as Status,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `저장하는 중…`;
fakeServer().then(
() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log({
ko: `${id}번 저장 승인: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
en: `Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
});
done(true);
},
() => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `서버가 409로 거절했어요. 다른 사람이 먼저 고친 작업이에요. 창은 열려 있으니 다시 저장하거나 취소하세요.`;
ctx.log({
ko: `${id}번 저장 거절(409): 창은 그대로 열려 있어요`,
en: `Task ${id} save refused (409): the dialog stays open`,
});
done(false);
},
);
}
type Ctx = { gantt: Gantt; api: GridApi<Row>; log: (m: LogText) => void };
// 더블클릭·Enter로 열린 작업의 편집 창을 열어요. 앱이 직접 만든 네이티브 <dialog>예요(MaxGrid는 창을 주지 않아요).
function openDialog(ctx: Ctx, id: string) {
const task = hostTasks.get(id);
if (!task || openDialogEl) return;
const opener = document.activeElement as HTMLElement | null;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = (): void => {
const bar = view?.box.querySelector<SVGElement>('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving) e.preventDefault(); // 저장하는 중에는 Esc로 닫지 않아요.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// 차트가 그림을 다시 그린 뒤에도 포커스가 막대에 있게 한 번 더 확인해요.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement)) focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren) return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved) dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log({ ko: `${id}번 작업의 편집 창을 열었어요`, en: `Opened the edit dialog for task ${id}` });
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks) hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// 끌어서 고치는 편집도 같은 가짜 서버로 가요: 승인하면 확정하고, 거절하면 revertIntent로 막대를 되돌려요.
const settle = (intentId: string, id: string, f: Fields) =>
fakeServer().then(
() => commit(gantt, api, id, f, intentId),
() => {
gantt.revertIntent(intentId);
log({
ko: `${id}번 끌기 거절(409): 막대가 원래대로 돌아가요`,
en: `Task ${id} drag refused (409): the bar goes back`,
});
},
);
const onRange = (e: {
intentId: string;
taskId: string;
plannedStart: string;
plannedEnd: string;
}) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log({
ko: `막대를 더블클릭하거나 막대에서 Enter를 눌러 보세요`,
en: `Double-click a bar, or press Enter on a focused bar`,
});
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
export const actions = {
// 서버 응답을 바꿔요: "approve"면 0.4초 뒤 승인, "refuse"면 409로 거절해요. 다음 저장·편집부터 적용돼요.
server: (_api: GridApi<Row>, value?: string) => {
refuse = value === 'refuse';
},
}; 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 answer" id="server">
<option value="approve" selected>Approve (0.4 s)</option>
<option value="refuse">Refuse (409)</option>
</select>
</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('server').addEventListener('change', (event) => actions.server(api, event.target.value));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-01-25', 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', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', 'Launch', 'Liam Carter', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', 'QA', 'Olivia Park', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', 'Go-live', 'Liam Carter', '2027-01-25', '2027-01-25', 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', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', '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 sortOf = new Map();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, 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,
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,
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: '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 40).
rowHeight: 40,
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,
});
// Narrow container (< 600 px): only the first columns stay so the chart keeps room; the rest come back when it widens.
const fitColumns = () => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress'])
api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
// The host (your app) keeps its own copy of the data. It never edits the objects given to the chart; it reports changed values with applyPatch.
const hostTasks = new Map();
const timers = new Set();
let refuse = false;
let view = null;
let openDialogEl = null;
// Fake server: approves after 0.4 s, or refuses with 409 when "Server answer" above is set to refuse.
function fakeServer() {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse)
reject(new Error('409'));
else
resolve();
}, 400);
timers.add(timer);
});
}
// Update the grid row. Always copy the row from api.getRowByKey and change the copy (never edit the object the grid holds).
function syncRow(api, id, f) {
const row = api.getRowByKey(id);
if (!row)
return;
const next = { ...row };
if (f.name !== undefined)
next.name = f.name;
if (f.assigneeName !== undefined)
next.assignee = f.assigneeName;
if (f.plannedStart !== undefined)
next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined)
next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined)
next.progress = f.progressPct;
api.updateRows([next]);
}
// Apply an approved change to the host data, the chart (applyPatch) and the grid together.
function commit(gantt, api, id, f, intentId) {
const old = hostTasks.get(id);
if (old)
hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL = {
TODO: `To do`,
IN_PROGRESS: `In progress`,
DONE: `Done`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make(tag, props = {}, ...kids) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props))
node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label, control, wide = false) {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// Build the fields and buttons of the edit dialog. The values come from the task the host holds.
function buildForm(task) {
const input = (type, value, extra = {}) => make('input', { type, value, ...extra });
const select = (values, labels, value) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL);
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(states, states.map((s) => STATUS_LABEL[s]), task.status),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `Progress (%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `Save`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `Close` : `Cancel`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(make('h2', { id: 'ed-title' }, `Edit task` + ' · ' + task.name), field(`Name`, p.name, true), field(`Assignee`, p.assignee), field(`Status`, p.status), field(`Start date`, p.start), field(`End date`, p.end), field(`Progress (%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true), p.error, p.server);
if (task.hasChildren)
form.append(make('p', { class: 'ed-note' }, `A summary task is rolled up from its children, so it cannot be edited here.`));
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
// Wire the checks (name not empty, end not before start) and the links between fields. Errors show as text inside the dialog.
function wireForm(f, task) {
const clamp = (v) => String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = () => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `Enter a name.`
: badDate
? `The end date must be on or after the start date.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone)
f.end.value = f.start.value; // A milestone's end follows its start.
validate();
});
for (const input of [f.name, f.end])
input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off)
c.disabled = true; // A summary task is read-only; a milestone edits one date only.
return validate;
}
// Save: when the fake server approves, update the chart and grid and close. On a refusal (409) say so as text in the dialog and keep it open.
function submitEdit(f, id, ctx, done) {
const patch = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `Saving…`;
fakeServer().then(() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log(`Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`);
done(true);
}, () => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `The server refused with 409: someone else changed this task first. The dialog stays open, so save again or cancel.`;
ctx.log(`Task ${id} save refused (409): the dialog stays open`);
done(false);
});
}
// Open the edit dialog for the task opened by double click or Enter. It is a native <dialog> the app builds itself (MaxGrid ships no dialog).
function openDialog(ctx, id) {
const task = hostTasks.get(id);
if (!task || openDialogEl)
return;
const opener = document.activeElement;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = () => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving)
e.preventDefault(); // Esc does not close it while saving.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// Check once more that focus is still on the bar after the chart redraws.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement))
focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren)
return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved)
dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log(`Opened the edit dialog for task ${id}`);
}
export function setup(api, log) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks)
hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// Drag edits go to the same fake server: approve to confirm, refuse to put the bar back with revertIntent.
const settle = (intentId, id, f) => fakeServer().then(() => commit(gantt, api, id, f, intentId), () => {
gantt.revertIntent(intentId);
log(`Task ${id} drag refused (409): the bar goes back`);
});
const onRange = (e) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log(`Double-click a bar, or press Enter on a focused bar`);
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
export const actions = {
// Change the server answer: "approve" approves after 0.4 s, "refuse" answers 409. Applies from the next save or edit.
server: (_api, value) => {
refuse = value === 'refuse';
},
};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>Open an edit dialog on double click</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Server answer" id="server">
<option value="approve" selected>Approve (0.4 s)</option>
<option value="refuse">Refuse (409)</option>
</select>
</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-01-25', 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', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', 'Launch', 'Liam Carter', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', 'QA', 'Olivia Park', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', 'Go-live', 'Liam Carter', '2027-01-25', '2027-01-25', 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', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', '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 sortOf = new Map();
for (const [id, parent] of T) {
const n = (counts.get(parent) ?? 0) + 1;
counts.set(parent, n);
sortOf.set(id, 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,
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,
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: '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 40).
rowHeight: 40,
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,
});
// Narrow container (< 600 px): only the first columns stay so the chart keeps room; the rest come back when it widens.
const fitColumns = () => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress'])
api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
// The host (your app) keeps its own copy of the data. It never edits the objects given to the chart; it reports changed values with applyPatch.
const hostTasks = new Map();
const timers = new Set();
let refuse = false;
let view = null;
let openDialogEl = null;
// Fake server: approves after 0.4 s, or refuses with 409 when "Server answer" above is set to refuse.
function fakeServer() {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse)
reject(new Error('409'));
else
resolve();
}, 400);
timers.add(timer);
});
}
// Update the grid row. Always copy the row from api.getRowByKey and change the copy (never edit the object the grid holds).
function syncRow(api, id, f) {
const row = api.getRowByKey(id);
if (!row)
return;
const next = { ...row };
if (f.name !== undefined)
next.name = f.name;
if (f.assigneeName !== undefined)
next.assignee = f.assigneeName;
if (f.plannedStart !== undefined)
next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined)
next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined)
next.progress = f.progressPct;
api.updateRows([next]);
}
// Apply an approved change to the host data, the chart (applyPatch) and the grid together.
function commit(gantt, api, id, f, intentId) {
const old = hostTasks.get(id);
if (old)
hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL = {
TODO: `To do`,
IN_PROGRESS: `In progress`,
DONE: `Done`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make(tag, props = {}, ...kids) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props))
node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label, control, wide = false) {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// Build the fields and buttons of the edit dialog. The values come from the task the host holds.
function buildForm(task) {
const input = (type, value, extra = {}) => make('input', { type, value, ...extra });
const select = (values, labels, value) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL);
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(states, states.map((s) => STATUS_LABEL[s]), task.status),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `Progress (%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `Save`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `Close` : `Cancel`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(make('h2', { id: 'ed-title' }, `Edit task` + ' · ' + task.name), field(`Name`, p.name, true), field(`Assignee`, p.assignee), field(`Status`, p.status), field(`Start date`, p.start), field(`End date`, p.end), field(`Progress (%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true), p.error, p.server);
if (task.hasChildren)
form.append(make('p', { class: 'ed-note' }, `A summary task is rolled up from its children, so it cannot be edited here.`));
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
// Wire the checks (name not empty, end not before start) and the links between fields. Errors show as text inside the dialog.
function wireForm(f, task) {
const clamp = (v) => String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = () => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `Enter a name.`
: badDate
? `The end date must be on or after the start date.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone)
f.end.value = f.start.value; // A milestone's end follows its start.
validate();
});
for (const input of [f.name, f.end])
input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off)
c.disabled = true; // A summary task is read-only; a milestone edits one date only.
return validate;
}
// Save: when the fake server approves, update the chart and grid and close. On a refusal (409) say so as text in the dialog and keep it open.
function submitEdit(f, id, ctx, done) {
const patch = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `Saving…`;
fakeServer().then(() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log(`Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`);
done(true);
}, () => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `The server refused with 409: someone else changed this task first. The dialog stays open, so save again or cancel.`;
ctx.log(`Task ${id} save refused (409): the dialog stays open`);
done(false);
});
}
// Open the edit dialog for the task opened by double click or Enter. It is a native <dialog> the app builds itself (MaxGrid ships no dialog).
function openDialog(ctx, id) {
const task = hostTasks.get(id);
if (!task || openDialogEl)
return;
const opener = document.activeElement;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = () => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving)
e.preventDefault(); // Esc does not close it while saving.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// Check once more that focus is still on the bar after the chart redraws.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement))
focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren)
return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved)
dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log(`Opened the edit dialog for task ${id}`);
}
function setup(api, log) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks)
hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// Drag edits go to the same fake server: approve to confirm, refuse to put the bar back with revertIntent.
const settle = (intentId, id, f) => fakeServer().then(() => commit(gantt, api, id, f, intentId), () => {
gantt.revertIntent(intentId);
log(`Task ${id} drag refused (409): the bar goes back`);
});
const onRange = (e) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log(`Double-click a bar, or press Enter on a focused bar`);
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
const actions = {
// Change the server answer: "approve" approves after 0.4 s, "refuse" answers 409. Applies from the next save or edit.
server: (_api, value) => {
refuse = value === 'refuse';
},
};
options.ariaLabel = "Open an edit dialog on double click";
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('server').addEventListener('change', (event) => actions.server(api, event.target.value));
</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 answer"
disabled={!api}
onChange={(event) => api && actions.server(api, event.target.value)}
>
<option value="approve">Approve (0.4 s)</option>
<option value="refuse">Refuse (409)</option>
</select>
</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;
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-01-25', 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', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', 'Launch', 'Liam Carter', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', 'QA', 'Olivia Park', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', 'Go-live', 'Liam Carter', '2027-01-25', '2027-01-25', 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', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', '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 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);
}
// 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,
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,
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: '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 40).
rowHeight: 40,
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,
});
// Narrow container (< 600 px): only the first columns stay so the chart keeps room; the rest come back when it widens.
const fitColumns = (): void => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress']) api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type HostTask = (typeof data.tasks)[number];
type Fields = Partial<
Pick<HostTask, 'name' | 'assigneeName' | 'status' | 'plannedStart' | 'plannedEnd' | 'progressPct'>
>;
// The host (your app) keeps its own copy of the data. It never edits the objects given to the chart; it reports changed values with applyPatch.
const hostTasks = new Map<string, HostTask>();
const timers = new Set<ReturnType<typeof setTimeout>>();
let refuse = false;
let view: ReturnType<typeof mountGantt> | null = null;
let openDialogEl: HTMLDialogElement | null = null;
// Fake server: approves after 0.4 s, or refuses with 409 when "Server answer" above is set to refuse.
function fakeServer(): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse) reject(new Error('409'));
else resolve();
}, 400);
timers.add(timer);
});
}
// Update the grid row. Always copy the row from api.getRowByKey and change the copy (never edit the object the grid holds).
function syncRow(api: GridApi<Row>, id: string, f: Fields) {
const row = api.getRowByKey(id);
if (!row) return;
const next = { ...row };
if (f.name !== undefined) next.name = f.name;
if (f.assigneeName !== undefined) next.assignee = f.assigneeName;
if (f.plannedStart !== undefined) next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined) next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined) next.progress = f.progressPct;
api.updateRows([next]);
}
// Apply an approved change to the host data, the chart (applyPatch) and the grid together.
function commit(gantt: Gantt, api: GridApi<Row>, id: string, f: Fields, intentId?: string) {
const old = hostTasks.get(id);
if (old) hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL: Record<Status, string> = {
TODO: `To do`,
IN_PROGRESS: `In progress`,
DONE: `Done`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make<K extends keyof HTMLElementTagNameMap>(
tag: K,
props: Record<string, string> = {},
...kids: Array<Node | string>
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props)) node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label: string, control: HTMLElement, wide = false): HTMLLabelElement {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// Build the fields and buttons of the edit dialog. The values come from the task the host holds.
function buildForm(task: HostTask) {
const input = (type: string, value: string, extra: Record<string, string> = {}) =>
make('input', { type, value, ...extra });
const select = (values: string[], labels: string[], value: string) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL) as Status[];
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(
states,
states.map((s) => STATUS_LABEL[s]),
task.status,
),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `Progress (%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `Save`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `Close` : `Cancel`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(
make('h2', { id: 'ed-title' }, `Edit task` + ' · ' + task.name),
field(`Name`, p.name, true),
field(`Assignee`, p.assignee),
field(`Status`, p.status),
field(`Start date`, p.start),
field(`End date`, p.end),
field(`Progress (%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true),
p.error,
p.server,
);
if (task.hasChildren)
form.append(
make(
'p',
{ class: 'ed-note' },
`A summary task is rolled up from its children, so it cannot be edited here.`,
),
);
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
type Form = ReturnType<typeof buildForm>;
// Wire the checks (name not empty, end not before start) and the links between fields. Errors show as text inside the dialog.
function wireForm(f: Form, task: HostTask): () => boolean {
const clamp = (v: string): string =>
String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = (): boolean => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `Enter a name.`
: badDate
? `The end date must be on or after the start date.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone) f.end.value = f.start.value; // A milestone's end follows its start.
validate();
});
for (const input of [f.name, f.end]) input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off) c.disabled = true; // A summary task is read-only; a milestone edits one date only.
return validate;
}
// Save: when the fake server approves, update the chart and grid and close. On a refusal (409) say so as text in the dialog and keep it open.
function submitEdit(f: Form, id: string, ctx: Ctx, done: (saved: boolean) => void): void {
const patch: Fields = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value as Status,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `Saving…`;
fakeServer().then(
() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log(
`Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
);
done(true);
},
() => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `The server refused with 409: someone else changed this task first. The dialog stays open, so save again or cancel.`;
ctx.log(`Task ${id} save refused (409): the dialog stays open`);
done(false);
},
);
}
type Ctx = { gantt: Gantt; api: GridApi<Row>; log: (m: LogText) => void };
// Open the edit dialog for the task opened by double click or Enter. It is a native <dialog> the app builds itself (MaxGrid ships no dialog).
function openDialog(ctx: Ctx, id: string) {
const task = hostTasks.get(id);
if (!task || openDialogEl) return;
const opener = document.activeElement as HTMLElement | null;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = (): void => {
const bar = view?.box.querySelector<SVGElement>('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving) e.preventDefault(); // Esc does not close it while saving.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// Check once more that focus is still on the bar after the chart redraws.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement)) focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren) return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved) dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log(`Opened the edit dialog for task ${id}`);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks) hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// Drag edits go to the same fake server: approve to confirm, refuse to put the bar back with revertIntent.
const settle = (intentId: string, id: string, f: Fields) =>
fakeServer().then(
() => commit(gantt, api, id, f, intentId),
() => {
gantt.revertIntent(intentId);
log(`Task ${id} drag refused (409): the bar goes back`);
},
);
const onRange = (e: {
intentId: string;
taskId: string;
plannedStart: string;
plannedEnd: string;
}) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log(`Double-click a bar, or press Enter on a focused bar`);
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
export const actions = {
// Change the server answer: "approve" approves after 0.4 s, "refuse" answers 409. Applies from the next save or edit.
server: (_api: GridApi<Row>, value?: string) => {
refuse = value === 'refuse';
},
}; 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 answer"
:disabled="!api"
@change="api && actions.server(api, ($event.target as HTMLSelectElement).value)"
>
<option value="approve" selected>Approve (0.4 s)</option>
<option value="refuse">Refuse (409)</option>
</select>
</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;
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-01-25', 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', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', 'Launch', 'Liam Carter', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', 'QA', 'Olivia Park', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', 'Go-live', 'Liam Carter', '2027-01-25', '2027-01-25', 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', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', '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 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);
}
// 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,
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,
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: '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 40).
rowHeight: 40,
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,
});
// Narrow container (< 600 px): only the first columns stay so the chart keeps room; the rest come back when it widens.
const fitColumns = (): void => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress']) api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type HostTask = (typeof data.tasks)[number];
type Fields = Partial<
Pick<HostTask, 'name' | 'assigneeName' | 'status' | 'plannedStart' | 'plannedEnd' | 'progressPct'>
>;
// The host (your app) keeps its own copy of the data. It never edits the objects given to the chart; it reports changed values with applyPatch.
const hostTasks = new Map<string, HostTask>();
const timers = new Set<ReturnType<typeof setTimeout>>();
let refuse = false;
let view: ReturnType<typeof mountGantt> | null = null;
let openDialogEl: HTMLDialogElement | null = null;
// Fake server: approves after 0.4 s, or refuses with 409 when "Server answer" above is set to refuse.
function fakeServer(): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse) reject(new Error('409'));
else resolve();
}, 400);
timers.add(timer);
});
}
// Update the grid row. Always copy the row from api.getRowByKey and change the copy (never edit the object the grid holds).
function syncRow(api: GridApi<Row>, id: string, f: Fields) {
const row = api.getRowByKey(id);
if (!row) return;
const next = { ...row };
if (f.name !== undefined) next.name = f.name;
if (f.assigneeName !== undefined) next.assignee = f.assigneeName;
if (f.plannedStart !== undefined) next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined) next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined) next.progress = f.progressPct;
api.updateRows([next]);
}
// Apply an approved change to the host data, the chart (applyPatch) and the grid together.
function commit(gantt: Gantt, api: GridApi<Row>, id: string, f: Fields, intentId?: string) {
const old = hostTasks.get(id);
if (old) hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL: Record<Status, string> = {
TODO: `To do`,
IN_PROGRESS: `In progress`,
DONE: `Done`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make<K extends keyof HTMLElementTagNameMap>(
tag: K,
props: Record<string, string> = {},
...kids: Array<Node | string>
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props)) node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label: string, control: HTMLElement, wide = false): HTMLLabelElement {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// Build the fields and buttons of the edit dialog. The values come from the task the host holds.
function buildForm(task: HostTask) {
const input = (type: string, value: string, extra: Record<string, string> = {}) =>
make('input', { type, value, ...extra });
const select = (values: string[], labels: string[], value: string) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL) as Status[];
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(
states,
states.map((s) => STATUS_LABEL[s]),
task.status,
),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `Progress (%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `Save`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `Close` : `Cancel`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(
make('h2', { id: 'ed-title' }, `Edit task` + ' · ' + task.name),
field(`Name`, p.name, true),
field(`Assignee`, p.assignee),
field(`Status`, p.status),
field(`Start date`, p.start),
field(`End date`, p.end),
field(`Progress (%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true),
p.error,
p.server,
);
if (task.hasChildren)
form.append(
make(
'p',
{ class: 'ed-note' },
`A summary task is rolled up from its children, so it cannot be edited here.`,
),
);
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
type Form = ReturnType<typeof buildForm>;
// Wire the checks (name not empty, end not before start) and the links between fields. Errors show as text inside the dialog.
function wireForm(f: Form, task: HostTask): () => boolean {
const clamp = (v: string): string =>
String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = (): boolean => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `Enter a name.`
: badDate
? `The end date must be on or after the start date.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone) f.end.value = f.start.value; // A milestone's end follows its start.
validate();
});
for (const input of [f.name, f.end]) input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off) c.disabled = true; // A summary task is read-only; a milestone edits one date only.
return validate;
}
// Save: when the fake server approves, update the chart and grid and close. On a refusal (409) say so as text in the dialog and keep it open.
function submitEdit(f: Form, id: string, ctx: Ctx, done: (saved: boolean) => void): void {
const patch: Fields = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value as Status,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `Saving…`;
fakeServer().then(
() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log(
`Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
);
done(true);
},
() => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `The server refused with 409: someone else changed this task first. The dialog stays open, so save again or cancel.`;
ctx.log(`Task ${id} save refused (409): the dialog stays open`);
done(false);
},
);
}
type Ctx = { gantt: Gantt; api: GridApi<Row>; log: (m: LogText) => void };
// Open the edit dialog for the task opened by double click or Enter. It is a native <dialog> the app builds itself (MaxGrid ships no dialog).
function openDialog(ctx: Ctx, id: string) {
const task = hostTasks.get(id);
if (!task || openDialogEl) return;
const opener = document.activeElement as HTMLElement | null;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = (): void => {
const bar = view?.box.querySelector<SVGElement>('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving) e.preventDefault(); // Esc does not close it while saving.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// Check once more that focus is still on the bar after the chart redraws.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement)) focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren) return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved) dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log(`Opened the edit dialog for task ${id}`);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks) hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// Drag edits go to the same fake server: approve to confirm, refuse to put the bar back with revertIntent.
const settle = (intentId: string, id: string, f: Fields) =>
fakeServer().then(
() => commit(gantt, api, id, f, intentId),
() => {
gantt.revertIntent(intentId);
log(`Task ${id} drag refused (409): the bar goes back`);
},
);
const onRange = (e: {
intentId: string;
taskId: string;
plannedStart: string;
plannedEnd: string;
}) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log(`Double-click a bar, or press Enter on a focused bar`);
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
export const actions = {
// Change the server answer: "approve" approves after 0.4 s, "refuse" answers 409. Applies from the next save or edit.
server: (_api: GridApi<Row>, value?: string) => {
refuse = value === 'refuse';
},
}; 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 answer"
[disabled]="!api"
(change)="api && actions.server(api, $any($event.target).value)"
>
<option value="approve" selected>Approve (0.4 s)</option>
<option value="refuse">Refuse (409)</option>
</select>
</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;
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-01-25', 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', 'Design review', 'Noah Reed', '2027-01-11', '2027-01-13', 0, 'TODO'],
['10', '1', 'Launch', 'Liam Carter', '2027-01-14', '2027-01-25', 0, 'TODO'],
['11', '10', 'QA', 'Olivia Park', '2027-01-14', '2027-01-22', 0, 'TODO'],
['12', '10', 'Go-live', 'Liam Carter', '2027-01-25', '2027-01-25', 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', '9', 'FF', 0],
['9', '11', 'FS', 0],
['11', '12', '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 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);
}
// 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,
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,
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: '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 40).
rowHeight: 40,
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,
});
// Narrow container (< 600 px): only the first columns stay so the chart keeps room; the rest come back when it widens.
const fitColumns = (): void => {
const narrow = box.clientWidth < 600;
for (const id of ['assignee', 'start', 'end', 'progress']) api.setColumnVisible(id, !narrow);
};
fitColumns();
const fitObserver = new ResizeObserver(fitColumns);
fitObserver.observe(box);
const gantt = createGantt(right, {
rowHeight: 40,
barHeight: 24,
locale: 'en',
verticalScroll: 'external',
...ganttOptions,
});
return {
gantt,
box,
destroy() {
// Detach and put the grid back where it was.
gantt.destroy();
fitObserver.disconnect();
split.destroy();
host.append(gridEl);
box.remove();
},
};
}
type Gantt = ReturnType<typeof createGantt>;
type HostTask = (typeof data.tasks)[number];
type Fields = Partial<
Pick<HostTask, 'name' | 'assigneeName' | 'status' | 'plannedStart' | 'plannedEnd' | 'progressPct'>
>;
// The host (your app) keeps its own copy of the data. It never edits the objects given to the chart; it reports changed values with applyPatch.
const hostTasks = new Map<string, HostTask>();
const timers = new Set<ReturnType<typeof setTimeout>>();
let refuse = false;
let view: ReturnType<typeof mountGantt> | null = null;
let openDialogEl: HTMLDialogElement | null = null;
// Fake server: approves after 0.4 s, or refuses with 409 when "Server answer" above is set to refuse.
function fakeServer(): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
timers.delete(timer);
if (refuse) reject(new Error('409'));
else resolve();
}, 400);
timers.add(timer);
});
}
// Update the grid row. Always copy the row from api.getRowByKey and change the copy (never edit the object the grid holds).
function syncRow(api: GridApi<Row>, id: string, f: Fields) {
const row = api.getRowByKey(id);
if (!row) return;
const next = { ...row };
if (f.name !== undefined) next.name = f.name;
if (f.assigneeName !== undefined) next.assignee = f.assigneeName;
if (f.plannedStart !== undefined) next.start = f.plannedStart ?? '';
if (f.plannedEnd !== undefined) next.end = f.plannedEnd ?? '';
if (f.progressPct !== undefined) next.progress = f.progressPct;
api.updateRows([next]);
}
// Apply an approved change to the host data, the chart (applyPatch) and the grid together.
function commit(gantt: Gantt, api: GridApi<Row>, id: string, f: Fields, intentId?: string) {
const old = hostTasks.get(id);
if (old) hostTasks.set(id, { ...old, ...f });
gantt.applyPatch({ tasks: [{ id, ...f }], ...(intentId === undefined ? {} : { intentId }) });
syncRow(api, id, f);
}
const STATUS_LABEL: Record<Status, string> = {
TODO: `To do`,
IN_PROGRESS: `In progress`,
DONE: `Done`,
};
const DIALOG_CSS = `
.ed-dialog { box-sizing: border-box; width: min(30rem, calc(100% - 16px)); max-height: calc(100% - 16px); overflow: auto; padding: 0; border: 1px solid var(--mxg-border-strong); border-radius: calc(var(--mxg-radius) * 2); background: var(--mxg-bg); color: var(--mxg-fg); font: var(--mxg-font-size) / 1.4 var(--mxg-font); text-align: start; }
.ed-dialog::backdrop { background: var(--mxg-bg-overlay); }
.ed-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; margin: 0; }
.ed-form h2 { margin: 0; font-size: 1.25em; }
.ed-form h2, .ed-wide, .ed-msg, .ed-note, .ed-actions { grid-column: 1 / -1; }
.ed-field { display: grid; gap: 4px; min-width: 0; font-weight: 600; }
.ed-field input, .ed-field select { min-height: 28px; min-width: 0; font-weight: 400; }
.ed-field input[aria-invalid='true'] { border-color: var(--mxg-danger); }
.ed-progress { display: grid; grid-template-columns: 5rem 1fr; gap: 8px; align-items: center; }
.ed-progress input[type='range'] { width: 100%; min-height: 24px; }
.ed-msg { margin: 0; color: var(--mxg-danger); }
.ed-msg:empty { display: none; }
.ed-note { margin: 0; color: var(--mxg-fg-muted); }
.ed-actions { display: flex; gap: 8px; justify-content: flex-end; }
.ed-actions button { min-width: 5rem; min-height: 32px; }
@media (max-width: 480px) {
.ed-dialog { width: 100%; max-width: 100%; margin-block-end: 0; border-radius: calc(var(--mxg-radius) * 3) calc(var(--mxg-radius) * 3) 0 0; }
.ed-form { grid-template-columns: 1fr; padding: 12px; gap: 10px; }
.ed-actions button { min-height: 40px; flex: 1; }
.ed-field input, .ed-field select { min-height: 36px; }
}
@media (prefers-reduced-motion: no-preference) {
.ed-dialog[open] { animation: ed-in 0.12s ease-out; }
@keyframes ed-in { from { opacity: 0; } }
}
`;
function make<K extends keyof HTMLElementTagNameMap>(
tag: K,
props: Record<string, string> = {},
...kids: Array<Node | string>
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props)) node.setAttribute(k, v);
node.append(...kids);
return node;
}
function field(label: string, control: HTMLElement, wide = false): HTMLLabelElement {
return make('label', { class: wide ? 'ed-field ed-wide' : 'ed-field' }, label, control);
}
// Build the fields and buttons of the edit dialog. The values come from the task the host holds.
function buildForm(task: HostTask) {
const input = (type: string, value: string, extra: Record<string, string> = {}) =>
make('input', { type, value, ...extra });
const select = (values: string[], labels: string[], value: string) => {
const el = make('select');
values.forEach((v, i) => el.append(make('option', { value: v }, labels[i] ?? v)));
el.value = value;
return el;
};
const people = [...new Set([...hostTasks.values()].map((t) => t.assigneeName ?? ''))];
const states = Object.keys(STATUS_LABEL) as Status[];
const pct = String(task.progressPct);
const p = {
name: input('text', task.name, { autocomplete: 'off' }),
assignee: select(people, people, task.assigneeName ?? ''),
status: select(
states,
states.map((s) => STATUS_LABEL[s]),
task.status,
),
start: input('date', task.plannedStart ?? ''),
end: input('date', task.plannedEnd ?? '', { 'aria-describedby': 'ed-error' }),
num: input('number', pct, { min: '0', max: '100', step: '1' }),
range: input('range', pct, { min: '0', max: '100', step: '1', 'aria-label': `Progress (%)` }),
error: make('p', { id: 'ed-error', class: 'ed-msg', role: 'alert' }),
server: make('p', { class: 'ed-msg', role: 'alert' }),
save: make('button', { type: 'submit' }, `Save`),
cancel: make('button', { type: 'button' }, task.hasChildren ? `Close` : `Cancel`),
};
const form = make('form', { class: 'ed-form', method: 'dialog', novalidate: '' });
form.append(
make('h2', { id: 'ed-title' }, `Edit task` + ' · ' + task.name),
field(`Name`, p.name, true),
field(`Assignee`, p.assignee),
field(`Status`, p.status),
field(`Start date`, p.start),
field(`End date`, p.end),
field(`Progress (%)`, make('div', { class: 'ed-progress' }, p.num, p.range), true),
p.error,
p.server,
);
if (task.hasChildren)
form.append(
make(
'p',
{ class: 'ed-note' },
`A summary task is rolled up from its children, so it cannot be edited here.`,
),
);
form.append(make('div', { class: 'ed-actions' }, p.cancel, p.save));
return { form, ...p };
}
type Form = ReturnType<typeof buildForm>;
// Wire the checks (name not empty, end not before start) and the links between fields. Errors show as text inside the dialog.
function wireForm(f: Form, task: HostTask): () => boolean {
const clamp = (v: string): string =>
String(Math.min(100, Math.max(0, Math.round(Number(v)) || 0)));
const validate = (): boolean => {
const badName = f.name.value.trim() === '';
const badDate = !task.isMilestone && f.start.value !== '' && f.end.value < f.start.value;
f.name.setAttribute('aria-invalid', String(badName));
f.end.setAttribute('aria-invalid', String(badDate));
f.error.textContent = badName
? `Enter a name.`
: badDate
? `The end date must be on or after the start date.`
: '';
return !badName && !badDate;
};
f.num.addEventListener('input', () => (f.range.value = clamp(f.num.value)));
f.range.addEventListener('input', () => (f.num.value = f.range.value));
f.start.addEventListener('input', () => {
if (task.isMilestone) f.end.value = f.start.value; // A milestone's end follows its start.
validate();
});
for (const input of [f.name, f.end]) input.addEventListener('input', validate);
const off = task.hasChildren
? [f.name, f.assignee, f.status, f.start, f.end, f.num, f.range, f.save]
: task.isMilestone
? [f.end, f.num, f.range]
: [];
for (const c of off) c.disabled = true; // A summary task is read-only; a milestone edits one date only.
return validate;
}
// Save: when the fake server approves, update the chart and grid and close. On a refusal (409) say so as text in the dialog and keep it open.
function submitEdit(f: Form, id: string, ctx: Ctx, done: (saved: boolean) => void): void {
const patch: Fields = {
name: f.name.value.trim(),
assigneeName: f.assignee.value,
status: f.status.value as Status,
plannedStart: f.start.value,
plannedEnd: f.end.disabled ? f.start.value : f.end.value,
progressPct: Math.min(100, Math.max(0, Math.round(Number(f.num.value)) || 0)),
};
f.save.disabled = true;
f.form.setAttribute('aria-busy', 'true');
f.server.setAttribute('role', 'status');
f.server.style.color = 'var(--mxg-fg-muted)';
f.server.textContent = `Saving…`;
fakeServer().then(
() => {
commit(ctx.gantt, ctx.api, id, patch);
ctx.log(
`Task ${id} saved: ${patch.name}, ${patch.plannedStart} ~ ${patch.plannedEnd}, ${patch.progressPct}%`,
);
done(true);
},
() => {
f.save.disabled = false;
f.form.removeAttribute('aria-busy');
f.server.setAttribute('role', 'alert');
f.server.style.color = '';
f.server.textContent = `The server refused with 409: someone else changed this task first. The dialog stays open, so save again or cancel.`;
ctx.log(`Task ${id} save refused (409): the dialog stays open`);
done(false);
},
);
}
type Ctx = { gantt: Gantt; api: GridApi<Row>; log: (m: LogText) => void };
// Open the edit dialog for the task opened by double click or Enter. It is a native <dialog> the app builds itself (MaxGrid ships no dialog).
function openDialog(ctx: Ctx, id: string) {
const task = hostTasks.get(id);
if (!task || openDialogEl) return;
const opener = document.activeElement as HTMLElement | null;
const f = buildForm(task);
const validate = wireForm(f, task);
const dialog = make('dialog', { class: 'ed-dialog mxg-controls', 'aria-labelledby': 'ed-title' });
dialog.append(f.form);
let saving = false;
const focusBar = (): void => {
const bar = view?.box.querySelector<SVGElement>('[data-task="' + CSS.escape(id) + '"]');
(bar ?? opener)?.focus();
};
dialog.addEventListener('cancel', (e) => {
if (saving) e.preventDefault(); // Esc does not close it while saving.
});
dialog.addEventListener('close', () => {
dialog.remove();
openDialogEl = null;
focusBar();
// Check once more that focus is still on the bar after the chart redraws.
requestAnimationFrame(() => {
const bar = view?.box.querySelector('[data-task="' + CSS.escape(id) + '"]');
if (bar && !bar.contains(document.activeElement)) focusBar();
});
});
f.cancel.addEventListener('click', () => !saving && dialog.close());
f.form.addEventListener('submit', (e) => {
e.preventDefault();
if (saving || task.hasChildren) return;
if (!validate())
return void (f.name.getAttribute('aria-invalid') === 'true' ? f.name : f.end).focus();
saving = true;
submitEdit(f, id, ctx, (saved) => {
saving = false;
if (saved) dialog.close();
});
});
view?.box.ownerDocument.body.append(dialog);
openDialogEl = dialog;
dialog.showModal();
(task.hasChildren ? f.cancel : f.name).focus();
ctx.log(`Opened the edit dialog for task ${id}`);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
refuse = false;
hostTasks.clear();
for (const t of data.tasks) hostTasks.set(t.id, { ...t });
view = mountGantt(api, { editable: true });
const gantt: Gantt = view.gantt;
gantt.setData(data);
const unlink = gantt.attachGrid(api);
const style = make('style', {}, DIALOG_CSS);
view.box.ownerDocument.head.append(style);
// Drag edits go to the same fake server: approve to confirm, refuse to put the bar back with revertIntent.
const settle = (intentId: string, id: string, f: Fields) =>
fakeServer().then(
() => commit(gantt, api, id, f, intentId),
() => {
gantt.revertIntent(intentId);
log(`Task ${id} drag refused (409): the bar goes back`);
},
);
const onRange = (e: {
intentId: string;
taskId: string;
plannedStart: string;
plannedEnd: string;
}) => settle(e.intentId, e.taskId, { plannedStart: e.plannedStart, plannedEnd: e.plannedEnd });
const offs = [
gantt.on('task-open', (e) => openDialog({ gantt, api, log }, e.taskId)),
gantt.on('task-move', onRange),
gantt.on('task-resize', onRange),
gantt.on('task-progress', (e) => settle(e.intentId, e.taskId, { progressPct: e.progressPct })),
];
log(`Double-click a bar, or press Enter on a focused bar`);
return () => {
timers.forEach(clearTimeout);
timers.clear();
openDialogEl?.remove();
openDialogEl = null;
style.remove();
offs.forEach((off) => off());
unlink();
view?.destroy();
view = null;
};
}
export const actions = {
// Change the server answer: "approve" approves after 0.4 s, "refuse" answers 409. Applies from the next save or edit.
server: (_api: GridApi<Row>, value?: string) => {
refuse = value === 'refuse';
},
};