Gantt editing
Since 1.8.0
Editing is available from 1.8.0. The chart in 1.7.0 is read-only.
Concept
The chart never changes your data itself. When the user drops a bar, the chart only emits an intent event that carries the new values. The host (your server) decides whether to accept it.
- The user drops a bar and the chart emits an event (
task-move, for example) with anintentId. - The bar is drawn at the new place right away with a "pending" look. The real data is unchanged.
- The host sends the change to the server and waits for the answer.
- If accepted, call
applyPatch({ tasks, intentId })with the confirmed values. If refused, callrevertIntent(intentId)and the bar returns to its place.
The module never recomputes dates. Moving a predecessor does not move its successors unless the host sends their new dates. Summary roll-ups are the server's job too.
Enabling
Set the option editable to true. The default is false (read-only). You can change it later with setOptions({ editable }). While it is off, no editing listeners are attached.
const gantt = createGantt(ganttEl, { rowHeight: 32, locale: 'en', editable: true });Turning on only the edits you need
editable also takes an object, not only true or false. A missing key stays on and false turns that kind off. A kind that is off is not offered at all: no handle is drawn, the cursor does not change, a drag does nothing, the key command is ignored and no event goes out.
// allow moving and resizing only: links, progress and row order are blocked
const gantt = createGantt(el, { editable: { link: false, progress: false, reorder: false } });
// change it later
gantt.setOptions({ editable: { move: false } }); // only moving is off
gantt.setOptions({ editable: true }); // everything on| Switch | What is hidden when off | Keyboard and API that stop | Events that stop |
|---|---|---|---|
move | dragging the body and the grab cursor | Alt+Arrow | task-move |
resize | both edge handles (an edge becomes part of the body) | Ctrl+Arrow | task-resize |
progress | the progress triangle | task-progress | |
link | the link handles and the rubber band | Delete on a selected arrow | dependency-create, dependency-delete |
reorder | Tab and Shift+Tab indent and outdent, reorderTask (refused as 'disabled') | task-reorder |
trueturns all five on andfalse(the default) turns all off. An object with all five set tofalseis the same asfalse.setOptions({ editable })works at run time. If you turn a kind off while a drag is running, nothing is sent on release. "Pending" intents that were already sent stay and are finished withapplyPatchorrevertIntent.- The type is
GanttEditable(import type { GanttEditable } from '@maxgrid/gantt').
What can be dragged
| Action | Where to grab | Event |
|---|---|---|
| Move | Bar body | task-move |
| Resize | Either end edge of the bar | task-resize |
| Progress | Triangle under the end of the progress fill | task-progress |
| Create dependency | Link handle just outside either end; drag to another bar | dependency-create |
| Delete dependency | Click the arrow, then press Delete or Backspace | dependency-delete |
- Dates snap to whole days. At every zoom level (
day,week,month) the change is rounded to the nearest day. Non-working days are not skipped (calendar dates). - A move keeps the bar length. A resize cannot push the start past the end. Progress is an integer from 0 to 100.
- With a mouse, a drag starts after 3px of movement; less is a plain click.
Esccancels a drag. - Near the edge of the chart, dragging auto-scrolls.
- On touch, press and hold a bar for 300ms to start a drag. Moving more than 8px before that counts as scrolling and nothing is edited. Touch uses a wider grab tolerance than the mouse (10px against 6px).
Events
Subscribe with gantt.on(name, fn). Every edit event carries an intentId.
| Event | Payload |
|---|---|
task-move | { intentId, taskId, plannedStart, plannedEnd } |
task-resize | { intentId, taskId, edge: 'start' | 'end', plannedStart, plannedEnd } |
task-progress | { intentId, taskId, progressPct } |
dependency-create | { intentId, predecessorId, successorId, depType, lagDays } |
dependency-delete | { intentId, dependencyId } |
Dates are YYYY-MM-DD strings. If the value is unchanged on release, no event is emitted. lagDays in dependency-create is always 0. depType follows where the line starts and ends: from the predecessor's end to the front half of the successor is FS, to its back half is FF; from the predecessor's start it is SS and SF.
The host loop
Take the event, send it to the server, then call applyPatch or revertIntent. The chart has no waiting limit of its own, so the host must set a timeout for a server that never answers.
const TIMEOUT_MS = 8000;
gantt.on('task-move', async ({ intentId, taskId, plannedStart, plannedEnd }) => {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
try {
const res = await fetch(`/api/tasks/${taskId}/schedule`, {
method: 'PATCH',
signal: ctrl.signal,
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ plannedStart, plannedEnd }),
});
if (!res.ok) throw new Error(String(res.status));
// Pass back the tasks the server recomputed (this task, successors, summaries).
const { tasks } = await res.json();
gantt.applyPatch({ tasks, intentId });
} catch {
gantt.revertIntent(intentId); // refusal, network error and timeout all end here
showToast('Could not change the schedule');
} finally {
clearTimeout(timer);
}
});tasksinapplyPatchis an array of{ id, ...changed fields }. Put successors and summaries in the same call.- Include the accepted values. Once the pending mark is gone the bar is drawn from the real data. If the server accepted the edit but the patch leaves that task out, the bar will look as if it went back. When the dropped values are accepted as they are, put the event's dates into the patch.
- Without
intentId, every pending mark on the tasks in the patch is treated as confirmed (bar edits only; dependency intents close only with theirintentId). PassingintentIdpairs the answer with the intent exactly. - Calling
revertIntentorapplyPatchwith an unknownintentIdis a quiet no-op, so a late answer to an intent that is already closed is safe. - A task with a pending intent cannot be dragged again. Its bar shakes briefly and the chart announces "The previous change is still being processed".
- Handle
task-resizeandtask-progressthe same way.
When the server refuses a bar edit
Some refusals the chart cannot predict: a version conflict (409), a rule only the server knows (for example a link to a summary task), a timeout, a network error. They all take one path: revertIntent(intentId) returns the bar, and on a conflict you sync the latest task the server sent with applyPatch({ tasks: [latest] }) (without intentId; the intent is already closed).
- Events carry no task
version. For optimistic locking the host keeps a version per task and sends it with the request. - A pending intent has no time limit and survives
setData.setOptions({ editable: false })anddestroy()drop them all.
The whole flow (version check, summary roll-up, 409, 422, timeout, network error) is in the example gantt-edit-host.
Open an edit dialog on double click
Double-click a bar (on touch, tap twice), or focus a bar and press Enter, and the chart emits task-open. The value is just { taskId }. MaxGrid ships no edit dialog. The host (your app) builds it, and tells the chart about the saved values with applyPatch once the server has accepted them. Below is the smallest version with the native <dialog> element. With showModal() focus stays inside the dialog and Esc closes it.
<dialog id="edit" aria-labelledby="edit-title">
<form method="dialog">
<h2 id="edit-title">Edit task</h2>
<label>Name <input name="name" /></label>
<label>Start <input name="start" type="date" /></label>
<label>End <input name="end" type="date" /></label>
<button value="cancel">Cancel</button>
<button value="save">Save</button>
</form>
</dialog>const dialog = document.querySelector<HTMLDialogElement>('#edit')!;
const input = (name: string) => dialog.querySelector<HTMLInputElement>(`[name=${name}]`)!;
let openId: string | null = null;
gantt.on('task-open', ({ taskId }) => {
const task = tasks.get(taskId); // your own task data (never edit the objects you gave the chart)
if (!task || task.hasChildren) return; // a summary task is rolled up from its children
openId = taskId;
input('name').value = task.name;
input('start').value = task.plannedStart ?? '';
input('end').value = task.plannedEnd ?? '';
dialog.returnValue = '';
dialog.showModal();
});
dialog.addEventListener('close', async () => {
if (dialog.returnValue !== 'save' || openId === null) return; // Cancel and Esc change nothing
const patch = {
id: openId,
name: input('name').value,
plannedStart: input('start').value,
plannedEnd: input('end').value,
};
const res = await fetch(`/api/tasks/${patch.id}`, {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(patch),
});
if (res.ok)
gantt.applyPatch({ tasks: [patch] }); // tell the chart after the server accepted it
else showToast('Could not save');
});- This version sends to the server after the dialog has closed. To show a refusal inside the dialog and keep it open, call
preventDefault()in the form'ssubmithandler and calldialog.close('save')after the server answers. The example does it this way. - If the end date is before the start date, say so in text next to the field instead of calling
alert(), and do not save. - A native
<dialog>returns focus to the element that had it before. If the dialog was opened by double click, check that focus goes back to the bar. The example focuses the bar after closing. - To update the grid on the left too, take the row from
api.getRowByKey(id), copy it, change the copy and callapi.updateRows([copy]). If you change the object the grid holds, the grid cannot see that anything changed and keeps the old screen.
The full code (assignee, status and progress fields, end date check, 409 refusal, read-only summary tasks, 390 px, RTL and dark theme) is in the example Open an edit dialog on double click.
Creating and deleting dependencies
Before emitting dependency-create, the chart blocks the same task, an existing link, a parent with its child, and cycles. The rubber-band line turns red with a reason and no event is emitted. The server still has to do the final validation.
applyPatch takes tasks only. Let the server create the dependency, then pass the data again with setData.
gantt.on(
'dependency-create',
async ({ intentId, predecessorId, successorId, depType, lagDays }) => {
try {
const data = await api.createDependency({ predecessorId, successorId, depType, lagDays });
gantt.setData(data); // the full data, including the dependency list
gantt.applyPatch({ tasks: [], intentId }); // closes the intent
} catch {
gantt.revertIntent(intentId);
}
},
);dependency-delete follows the same steps. Dependency edits have no separate pending look like bars do. The intent stays until you call applyPatch or revertIntent.
What is not editable
| Target | Move | Resize | Progress | Link |
|---|---|---|---|---|
| Regular task | yes | yes | yes | yes |
| Milestone | yes | no | no | yes |
Summary task (hasChildren) | no | no | no | yes |
| Task without dates | no bar, so nothing to drag | - | - | - |
Summary dates and progress are rolled up by the server. Pressing a summary bar announces "Summary tasks are read-only". A task without dates has no bar, so its schedule cannot be set on the chart. Set it in the grid or send dates from the server.
Pending and rejected look
- A pending bar is drawn dimmed at the new place with an animated dashed outline (
mxg-gantt-bar--pending,aria-busy="true"). With reduced motion the outline does not animate. - While dragging, a translucent preview bar (ghost) follows the pointer. A dependency drag draws a line from the bar and turns red over a target that is not allowed.
- A refusal is the bar returning to its place after
revertIntent. Pressing a task that already has a pending intent shakes its bar once.
Change colors with CSS variables (prefix --mxg-gantt-, with light and dark defaults).
| Variable | Used for |
|---|---|
pending | Outline of a pending bar |
ghost | Preview fill while dragging |
link-line | Dependency line and its end point |
link-invalid | Line color over an invalid target |
progress-handle | Progress and edge handles |
.my-gantt {
--mxg-gantt-pending: #b54708;
--mxg-gantt-link-invalid: #d92d20;
}API reference
Options
| Option | Default | Description |
|---|---|---|
editable | false | Turns on drag to move, resize, progress and linking. true, false or { move?, resize?, progress?, link?, reorder? } (a missing key is on, see Turning on only the edits you need). Can change through setOptions; turning every kind off removes the listeners and pending intents. |
locale | 'ko' | Language of the announcements (ko, en, ja). |
Methods
| Method | Description |
|---|---|
applyPatch({ tasks, intentId? }) | Applies the values the host accepted and clears the pending mark of intentId. tasks is { id, ...changed fields }; a date outside the range widens the time scale. |
revertIntent(intentId) | Cancels an intent the host refused. The bar returns to its real dates. |
setData(data) | Replaces all data. Use it after a dependency was created or deleted. |
reorderTask(taskId, { rowIndex, position }) | Reports a row drop from your grid. Sends task-reorder for a valid spot, otherwise returns the reason. |
setOptions({ editable }) | Turns editing on or off. |
Events
| Event | Value |
|---|---|
task-move | { intentId, taskId, plannedStart, plannedEnd } |
task-resize | { intentId, taskId, edge, plannedStart, plannedEnd } |
task-progress | { intentId, taskId, progressPct } |
dependency-create | { intentId, predecessorId, successorId, depType, lagDays } |
dependency-delete | { intentId, dependencyId } |
task-reorder | { intentId, taskId, parentId, afterTaskId } |
The types are GanttEvents (from @maxgrid/gantt or @maxgrid/gantt-core) and GanttPatch. In the API reference (TypeDoc) look for GanttApi, GanttPatch, GanttEvents and GanttOptions.
Announcements
| Situation | ko | en | ja |
|---|---|---|---|
| Dragging a summary task | 요약 과제는 읽기 전용이에요 | Summary tasks are read-only | 要約タスクは読み取り専用です |
| Dragging a task that is pending | 이전 변경을 처리하는 중이에요 | The previous change is still being processed | 前の変更を処理中です |
| Linking a task to itself | 같은 과제는 이을 수 없어요 | A task cannot depend on itself | 同じタスクは接続できません |
| Link already exists | 이미 이어져 있어요 | These tasks are already linked | すでに接続されています |
| Parent and child | 상위·하위 과제는 이을 수 없어요 | A parent and its child cannot be linked | 親子のタスクは接続できません |
| Would create a cycle | 순환이 생겨서 이을 수 없어요 | This link would create a cycle | 循環が発生するため接続できません |
Keyboard and row order
With editable: true the chart can also be edited from the keyboard: pick a bar, move its dates, indent and outdent. The result goes out as the same intent events as dragging; the bar waits as "pending" until the server accepts.
| Key | What it does |
|---|---|
| Tab | Enter the chart (the first bar is selected) |
| Up, Down, Home, End, PageUp, PageDown | Pick another bar |
| Enter | Open (task-open) |
| Alt+Left/Right, Alt+Shift+Left/Right | Move the bar by a day, by a week (task-move) |
| Ctrl+Left/Right, Ctrl+Shift+Left/Right | Ctrl moves the end date, Ctrl+Shift the start date, by one day (task-resize) |
| Tab, Shift+Tab (on a bar) | Indent under the previous sibling, outdent (task-reorder) |
| Esc | Return the focus to the chart itself |
When a key cannot be applied (summary task, read-only, pending, no sibling to indent under), the reason is announced in the live region.
Row order (task-reorder): dragging rows is the job of the host's grid. Report the drop with api.reorderTask(taskId, { rowIndex, position }) (position is before, after or inside) and the chart checks the spot. For a valid spot it emits { intentId, taskId, parentId, afterTaskId } (both null means first root); otherwise it returns the reason (onto itself, into its own subtree, under a milestone, same spot ...) and sends nothing. When the server accepts, confirm parentId and the order with applyPatch.
Limits
- Read-only is the default. Nothing can be dragged unless you set
editable: true. Deletefor a dependency works only after the arrow has been selected with the mouse or touch. There is no keyboard way to create or delete dependencies.- The chart has no row-dragging screen. Your host takes the drag in its own grid and reports the drop with
api.reorderTask; the chart checks the spot and sends atask-reorderintent (see "Keyboard and row order" above). - The calendar is not consulted. Dropping on a non-working day is allowed; the server corrects it.
lagDaysis always 0. There is no UI to set a lag.
Accessibility
- Messages for blocked or pending edits (summary read-only, previous change pending, why a link is refused) go to a
role="status",aria-live="polite"region, in thelocalelanguage. - A pending bar has
aria-busy="true". - In edit mode bars get a roving
tabindexand can be picked and edited from the keyboard (see "Keyboard and row order" above). When a key cannot be applied, the reason is announced in the live region.
Examples
Gallery examples: basic, create and delete dependencies, refuse and revert, read-only, with a server (fake server: version conflict 409, summary refusal 422, timeout, network error), edit dialog (double click or Enter opens it; Save updates the chart and the grid), keyboard, row order.