Skip to content

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.

  1. The user drops a bar and the chart emits an event (task-move, for example) with an intentId.
  2. The bar is drawn at the new place right away with a "pending" look. The real data is unchanged.
  3. The host sends the change to the server and waits for the answer.
  4. If accepted, call applyPatch({ tasks, intentId }) with the confirmed values. If refused, call revertIntent(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.

ts
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.

ts
// 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
SwitchWhat is hidden when offKeyboard and API that stopEvents that stop
movedragging the body and the grab cursorAlt+Arrowtask-move
resizeboth edge handles (an edge becomes part of the body)Ctrl+Arrowtask-resize
progressthe progress triangletask-progress
linkthe link handles and the rubber bandDelete on a selected arrowdependency-create, dependency-delete
reorderTab and Shift+Tab indent and outdent, reorderTask (refused as 'disabled')task-reorder
  • true turns all five on and false (the default) turns all off. An object with all five set to false is the same as false.
  • 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 with applyPatch or revertIntent.
  • The type is GanttEditable (import type { GanttEditable } from '@maxgrid/gantt').

What can be dragged ​

ActionWhere to grabEvent
MoveBar bodytask-move
ResizeEither end edge of the bartask-resize
ProgressTriangle under the end of the progress filltask-progress
Create dependencyLink handle just outside either end; drag to another bardependency-create
Delete dependencyClick the arrow, then press Delete or Backspacedependency-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. Esc cancels 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.

EventPayload
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.

ts
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);
  }
});
  • tasks in applyPatch is 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 their intentId). Passing intentId pairs the answer with the intent exactly.
  • Calling revertIntent or applyPatch with an unknown intentId is 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-resize and task-progress the 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 }) and destroy() 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.

html
<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>
ts
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's submit handler and call dialog.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 call api.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.

ts
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 ​

TargetMoveResizeProgressLink
Regular taskyesyesyesyes
Milestoneyesnonoyes
Summary task (hasChildren)nononoyes
Task without datesno 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).

VariableUsed for
pendingOutline of a pending bar
ghostPreview fill while dragging
link-lineDependency line and its end point
link-invalidLine color over an invalid target
progress-handleProgress and edge handles
css
.my-gantt {
  --mxg-gantt-pending: #b54708;
  --mxg-gantt-link-invalid: #d92d20;
}

API reference ​

Options ​

OptionDefaultDescription
editablefalseTurns 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 ​

MethodDescription
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 ​

EventValue
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 ​

Situationkoenja
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.

KeyWhat it does
TabEnter the chart (the first bar is selected)
Up, Down, Home, End, PageUp, PageDownPick another bar
EnterOpen (task-open)
Alt+Left/Right, Alt+Shift+Left/RightMove the bar by a day, by a week (task-move)
Ctrl+Left/Right, Ctrl+Shift+Left/RightCtrl 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)
EscReturn 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.
  • Delete for 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 a task-reorder intent (see "Keyboard and row order" above).
  • The calendar is not consulted. Dropping on a non-working day is allowed; the server corrects it.
  • lagDays is 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 the locale language.
  • A pending bar has aria-busy="true".
  • In edit mode bars get a roving tabindex and 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.