# Gantt API and events

> Every option, method, event and exported function of Birch UI Gantt, with defaults, payloads and a pattern for saving changes.

This page is the complete reference for `@birchui/gantt`. The generated type reference is on the [package API page](https://docs.birchui.com/api/gantt.md).

```ts
import {
  createGantt,
  ganttDefinition,
  GANTT_EVENT_NAMES,
  ganttStyles,
  GANTT_VIEW_PRESETS,
  GANTT_ZOOM_LEVELS,
  createGanttProject,
  DEFAULT_CALENDAR,
  parsePredecessors,
  formatPredecessor,
  readMSProjectXML,
  routeDependency,
} from '@birchui/gantt';
```

| Export | Description |
| --- | --- |
| `createGantt(container, options)` | Renders a Gantt and returns a `GanttApi`. Throws a `TypeError` without a container element or an options object. |
| `ganttDefinition` | The widget definition (name `BirchGantt`, tag `birchui-gantt`, the 13 events) for the adapters' generic factories. See [Use it in your framework](https://docs.birchui.com/gantt/overview.md#use-it-in-your-framework). |
| `GANTT_EVENT_NAMES` | The event names. |
| `ganttStyles` | The stylesheet as a string. |
| `GANTT_VIEW_PRESETS`, `GANTT_ZOOM_LEVELS` | View presets and the default zoom ladder. See [Zoom and view presets](https://docs.birchui.com/gantt/interactions.md#zoom-and-view-presets). |
| `createGanttProject(options?)` | The headless engine. See [Headless engine](https://docs.birchui.com/gantt/headless.md). |
| `DEFAULT_CALENDAR` | The standard calendar: Monday to Friday, 08:00–12:00 and 13:00–17:00. |
| `parsePredecessors`, `formatPredecessor` | Predecessor text. See [Predecessor text](https://docs.birchui.com/gantt/task-grid.md#predecessor-text). |
| `readMSProjectXML(xml, warn?)` | Parse MS Project XML into project data. See [MS Project XML](https://docs.birchui.com/gantt/ms-project.md). |
| `routeDependency(from, to, type, gap?)` | The orthogonal link router used by the timeline, for drawing links in your own exports. |

`createGantt<TTask>` is generic over your task type, which types every task in payloads, renderers and return values.

## Options

`tasks` is required; everything else is optional. Change options later with `update(partial)`. Invalid values log one warning and fall back to the default.

### Project and scheduling

| Option | Default | Description |
| --- | --- | --- |
| `tasks` | (required) | Tasks. `parentId` builds the tree; sibling order is array order. See [Tasks](https://docs.birchui.com/gantt/tasks.md). |
| `dependencies` | `[]` | Links. See [Dependencies](https://docs.birchui.com/gantt/dependencies.md). |
| `calendars`, `calendarId` | the standard calendar | Working calendars and the project calendar. See [Calendars](https://docs.birchui.com/gantt/calendars.md). |
| `projectStart` | earliest task start | Project start date. |
| `hoursPerDay`, `daysPerWeek` | `8`, `5` | Convert day and week durations into working hours. |
| `unlinkedTaskStart` | `'keep'` | `'keep'` or `'projectStart'`, for tasks without predecessors. |
| `autoSchedule` | `true` | `false` stops edits from moving successors until `schedule()`. |
| `timeZone` | the browser's zone | IANA zone for scheduling and display. |

### Timeline and grid

| Option | Default | Description |
| --- | --- | --- |
| `viewPreset` | `'weekAndDay'` | Time scale: a preset name or a preset object. |
| `zoomLevels` | `GANTT_ZOOM_LEVELS` | Ladder for `zoomIn()` and `zoomOut()`. |
| `columns` | all seven built-in columns | Built-in ids or column objects. See [Columns](https://docs.birchui.com/gantt/task-grid.md#columns). |
| `gridWidth` | width of the columns, up to 640 | Grid width in pixels. |
| `rowHeight`, `barHeight`, `headerRowHeight` | `36`, half the row, `28` | Sizes in pixels. `barHeight` must leave at least 6 pixels of the row free. |
| `height` | the container's height | Height of the Gantt, in pixels or a CSS length. |
| `showCriticalPath` | `false` | Highlight critical tasks and links. |
| `showBaselines`, `baselineIndex` | `false`, `0` | Show a baseline under each bar. See [Baselines](https://docs.birchui.com/gantt/baselines.md). |
| `showDependencies` | `true` | Draw links. |
| `showTodayLine`, `today` | `true`, now | The today line, and a fixed "today". |
| `locale`, `weekStartsOn` | browser locale, `1` | Header formatting and the first day of the week (`0` is Sunday). |
| `overscanRows`, `overscanPx` | `6`, `300` | Extra rows and pixels rendered outside the view. |

### Editing

| Option | Default | Description |
| --- | --- | --- |
| `readOnly` | `false` | Turn off editing in the UI. |
| `tabToIndent` | `true` | <kbd>Tab</kbd> and <kbd>Shift</kbd>+<kbd>Tab</kbd> indent and outdent in the grid. |
| `validateTaskChange` | none | `(context) => boolean`; return `false` to refuse a move, resize, progress change or edit made in the UI. |
| `validateDependency` | none | `(context) => boolean`; return `false` to refuse a new link. |
| `historyLimit` | `100` | Undo steps kept. |

### Appearance and licensing

| Option | Default | Description |
| --- | --- | --- |
| `theme` | `'light'` | `'light'`, `'dark'` or `'auto'`. |
| `taskTooltip` | `true` | Tooltips on bars: `true`, `false` or `(task) => string`. |
| `ariaLabel` | `'Project schedule'` | Accessible name of the Gantt. |
| `injectStyles` | `true` | `false` skips injecting the stylesheet; import `@birchui/gantt/styles.css`. |
| `licenseKey` | none | License key, or call `setLicenseKey` once. See [Licensing](https://docs.birchui.com/getting-started/licensing.md). |

**`GanttOptions`** (interface from `@birchui/gantt`, full reference: https://docs.birchui.com/api/gantt.md)

```ts
interface GanttOptions<TTask extends GanttTask = GanttTask>
```

| Property | Type | Description |
| --- | --- | --- |
| `tasks` | `TTask[]` |  |
| `dependencies?` | `GanttDependency[]` |  |
| `calendars?` | `GanttCalendar[]` |  |
| `calendarId?` | `string` |  |
| `projectStart?` | `DateInput` |  |
| `hoursPerDay?` | `number` |  |
| `daysPerWeek?` | `number` |  |
| `unlinkedTaskStart?` | `UnlinkedTaskStart` |  |
| `autoSchedule?` | `boolean` |  |
| `timeZone?` | `string` |  |
| `locale?` | `string` |  |
| `weekStartsOn?` | `0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6` |  |
| `viewPreset?` | `GanttViewPresetName \| ViewPreset` |  |
| `zoomLevels?` | `(GanttViewPresetName \| ViewPreset)[]` |  |
| `columns?` | `(GanttColumnId \| GanttColumn<TTask>)[]` |  |
| `gridWidth?` | `number` |  |
| `rowHeight?` | `number` |  |
| `barHeight?` | `number` |  |
| `headerRowHeight?` | `number` |  |
| `showCriticalPath?` | `boolean` |  |
| `showBaselines?` | `boolean` |  |
| `baselineIndex?` | `number` |  |
| `showDependencies?` | `boolean` |  |
| `showTodayLine?` | `boolean` |  |
| `today?` | `DateInput` |  |
| `tabToIndent?` | `boolean` |  |
| `readOnly?` | `boolean` |  |
| `validateTaskChange?` | `(context: TaskChangeContext<TTask>) => boolean` |  |
| `validateDependency?` | `(context: DependencyContext<TTask>) => boolean` |  |
| `taskTooltip?` | `boolean \| ((task: ScheduledTask<TTask>) => string)` |  |
| `theme?` | `GanttTheme` |  |
| `height?` | `number \| string` |  |
| `overscanRows?` | `number` |  |
| `overscanPx?` | `number` |  |
| `historyLimit?` | `number` |  |
| `ariaLabel?` | `string` |  |
| `licenseKey?` | `string` |  |
| `injectStyles?` | `boolean` |  |
| `localeText?` | `LocaleTextInput` |  |
| `rtl?` | `boolean` |  |

## Methods

`GanttApi` includes the widget contract (`element`, `update(partial)`, `on(event, listener)` returning an unsubscribe function, and `destroy()`) plus:

### Tasks and links

| Method | Returns | Description |
| --- | --- | --- |
| `setTasks(tasks)`, `setDependencies(dependencies)` | `void` | Replace the data and reschedule. Clears the undo history. |
| `addTask(task, position?)` | scheduled task or `undefined` | Add a task `{ above }`, `{ below }` or `{ parentId, index }`. |
| `updateTask(id, patch)` | scheduled task or `undefined` | Merge a patch and reschedule. |
| `removeTask(id)` | `boolean` | Remove a task with its subtasks and links. |
| `indent(id)`, `outdent(id)` | `boolean` | Change a task's level. |
| `addDependency(input)` | link or `undefined` | Add a link; `undefined` when it is refused. |
| `removeDependency(id)` | `boolean` | Remove a link. |
| `getTask(id)`, `getTasks()` | scheduled tasks | Scheduled copies. |
| `getDependencies()` | links | Copies of all links. |

### Schedule

| Method | Returns | Description |
| --- | --- | --- |
| `schedule()` | `ScheduleResult` | Full forward and backward pass. |
| `getCriticalPath()` | `{ taskIds, dependencyIds }` | The critical path. |
| `getSlack(id)` | `{ total, free, totalMs, freeMs, isCritical }` | Slack in working days and milliseconds. |
| `getProjectRange()` | `{ start, end }` | Project start and finish. |

### History, view and selection

| Method | Returns | Description |
| --- | --- | --- |
| `undo()`, `redo()` | `boolean` | Undo or redo one step. |
| `canUndo()`, `canRedo()` | `boolean` | Whether a step is available. |
| `setViewPreset(preset)`, `getViewPreset()` | `void` / `ViewPreset` | Set or read the time scale. |
| `zoomIn()`, `zoomOut()` | `boolean` | Move along `zoomLevels`; `false` at the end. |
| `scrollToTask(id)`, `scrollToDate(date, align?)` | `void` | Scroll a task or date into view. |
| `selectTask(id \| null)`, `getSelectedTask()` | `void` / task or `null` | Task selection. |
| `selectDependency(id \| null)` | `void` | Link selection. |
| `expandTask(id)`, `collapseTask(id)`, `expandAll()`, `collapseAll()` | `void` | Summary rows. |
| `xFromDate(date)`, `dateFromX(x)` | `number` / `Date` | Convert between dates and timeline pixels. |
| `getTaskBounds(id)` | `{ left, top, width, height }` or `undefined` | A bar's box in timeline pixels. |
| `refresh()` | `void` | Re-render. |

### Files

| Method | Returns | Description |
| --- | --- | --- |
| `toJSON()`, `fromJSON(data)` | `ProjectData` / `void` | JSON in and out. `fromJSON` clears the history. |
| `toMSProjectXML()`, `fromMSProjectXML(xml)` | `string` / `void` | MS Project XML in and out. `fromMSProjectXML` throws a `SyntaxError` for text without a `<Project>` element. |

**`GanttApi`** (interface from `@birchui/gantt`, full reference: https://docs.birchui.com/api/gantt.md)

```ts
interface GanttApi<TTask extends GanttTask = GanttTask> extends Widget<GanttOptions<TTask>, GanttEvents<TTask>>
```

| Property | Type | Description |
| --- | --- | --- |
| `setTasks` | `(tasks: TTask[]) => void` |  |
| `setDependencies` | `(dependencies: GanttDependency[]) => void` |  |
| `addTask` | `(task: Partial<TTask> & { name: string }, position?: AddTaskPosition) => ScheduledTask<TTask> \| undefined` |  |
| `updateTask` | `(id: string, patch: Partial<TTask>) => ScheduledTask<TTask> \| undefined` |  |
| `removeTask` | `(id: string) => boolean` |  |
| `indent` | `(id: string) => boolean` |  |
| `outdent` | `(id: string) => boolean` |  |
| `addDependency` | `(dependency: DependencyInput) => GanttDependency \| undefined` |  |
| `removeDependency` | `(id: string) => boolean` |  |
| `getTask` | `(id: string) => ScheduledTask<TTask> \| undefined` |  |
| `getTasks` | `() => ScheduledTask<TTask>[]` |  |
| `getDependencies` | `() => GanttDependency[]` |  |
| `schedule` | `() => ScheduleResult` |  |
| `getCriticalPath` | `() => CriticalPath` |  |
| `getSlack` | `(taskId: string) => TaskSlack \| undefined` |  |
| `getProjectRange` | `() => { start: Date; end: Date }` |  |
| `undo` | `() => boolean` |  |
| `redo` | `() => boolean` |  |
| `canUndo` | `() => boolean` |  |
| `canRedo` | `() => boolean` |  |
| `setViewPreset` | `(preset: GanttViewPresetName \| ViewPreset) => void` |  |
| `getViewPreset` | `() => ViewPreset` |  |
| `zoomIn` | `() => boolean` |  |
| `zoomOut` | `() => boolean` |  |
| `scrollToTask` | `(id: string) => void` |  |
| `scrollToDate` | `(date: DateInput, align?: ScrollAlign) => void` |  |
| `selectTask` | `(id: string \| null) => void` |  |
| `getSelectedTask` | `() => ScheduledTask<TTask> \| null` |  |
| `selectDependency` | `(id: string \| null) => void` |  |
| `expandTask` | `(id: string) => void` |  |
| `collapseTask` | `(id: string) => void` |  |
| `expandAll` | `() => void` |  |
| `collapseAll` | `() => void` |  |
| `xFromDate` | `(date: DateInput) => number` |  |
| `dateFromX` | `(x: number) => Date` |  |
| `getTaskBounds` | `(id: string) => TaskBounds \| undefined` |  |
| `toJSON` | `() => ProjectData<TTask>` |  |
| `fromJSON` | `(data: ProjectData<TTask> \| string) => void` |  |
| `toMSProjectXML` | `() => string` |  |
| `fromMSProjectXML` | `(xml: string, options?: MspReadOptions) => void` |  |
| `refresh` | `() => void` |  |
| `readonly element` | `HTMLElement` | Inherited from Widget. |
| `update` | `(options: Partial<GanttOptions<TTask>>) => void` | Inherited from Widget. |
| `on` | `<K extends keyof TEvents & string>(event: K, listener: Listener<TEvents[K]>) => () => void` | Inherited from Widget. |
| `destroy` | `() => void` | Inherited from Widget. |

## Events

Subscribe with `on(event, listener)`. A listener that throws is caught and reported with `console.error`. In framework adapters the same events are `on…` props (React, Solid), kebab-case listeners (Vue), outputs (Angular), `on` handlers of the Svelte action, or kebab-case `CustomEvent`s on a custom element.

| Event | Payload | When |
| --- | --- | --- |
| `ready` | `{ api }` | Once, in a microtask after `createGantt` returns. |
| `taskClick` | `{ task, domEvent }` | A bar is clicked, or <kbd>Enter</kbd> is pressed on a focused bar. |
| `taskDoubleClick` | `{ task, domEvent }` | A bar is double-clicked. |
| `taskChange` | `{ task, previous, source }` | A task was moved, resized, edited, given progress, indented or outdented, or updated through the API. |
| `taskAdd` | `{ task, source }` | A task was added. |
| `taskRemove` | `{ task, source }` | A task was removed; once per removed task, subtasks included. |
| `tasksScheduled` | `{ changed, ms, conflicts }` | After every scheduling run. |
| `dependencyCreate` | `{ dependency, source }` | A link was added. |
| `dependencyRemove` | `{ dependency, source }` | A link was removed. |
| `selectionChange` | `{ task, dependency, previousTask, previousDependency }` | The selected task or link changed. |
| `viewportScroll` | `{ left, top, visibleStart, visibleEnd }` | The timeline scrolled. |
| `cycleDetected` | `{ cycles }` | New dependency loops were found; each cycle has `taskIds` and `dependencyIds`. |
| `viewPresetChanged` | `{ preset, previous }` | The view preset changed. |

`source` is `'drag'`, `'resize'`, `'progress'`, `'edit'`, `'keyboard'` or `'api'`. The `ChangeSource` type also lists `'undo'` and `'redo'`, but undo and redo are reported only through `tasksScheduled`.

**`GanttEvents`** (interface from `@birchui/gantt`, full reference: https://docs.birchui.com/api/gantt.md)

```ts
interface GanttEvents<TTask extends GanttTask = GanttTask>
```

| Property | Type | Description |
| --- | --- | --- |
| `ready` | `{ api: GanttApi<TTask> }` |  |
| `taskClick` | `TaskInteraction<TTask>` |  |
| `taskDoubleClick` | `TaskInteraction<TTask>` |  |
| `taskChange` | `{ task: ScheduledTask<TTask>; previous: ScheduledTask<TTask>; source: ChangeSource }` |  |
| `taskAdd` | `{ task: ScheduledTask<TTask>; source: ChangeSource }` |  |
| `taskRemove` | `{ task: ScheduledTask<TTask>; source: ChangeSource }` |  |
| `tasksScheduled` | `{ changed: string[]; ms: number; conflicts: string[] }` |  |
| `dependencyCreate` | `{ dependency: GanttDependency; source: ChangeSource }` |  |
| `dependencyRemove` | `{ dependency: GanttDependency; source: ChangeSource }` |  |
| `selectionChange` | `{ task: ScheduledTask<TTask> \| null; dependency: GanttDependency \| null; previousTask: ScheduledTask<TTask> \| null; previousDependency: GanttDependency \| null; }` |  |
| `viewportScroll` | `{ left: number; top: number; visibleStart: Date; visibleEnd: Date }` |  |
| `cycleDetected` | `{ cycles: DependencyCycle[] }` |  |
| `viewPresetChanged` | `{ preset: ViewPreset; previous: ViewPreset }` |  |

## Saving changes

The most robust way to persist edits is to listen to `tasksScheduled`, which fires after every change, including undo, redo and the dates of successors that moved, and to save the tasks and links it touched:

```ts
let pending = new Set<string>();
let saveTimer: ReturnType<typeof setTimeout> | undefined;

gantt.on('tasksScheduled', ({ changed }) => {
  for (const id of changed) pending.add(id);
  clearTimeout(saveTimer);
  saveTimer = setTimeout(async () => {
    const ids = [...pending];
    pending = new Set();
    await api.post(`/projects/${projectId}/tasks`, ids.map((id) => gantt.getTask(id)).filter(Boolean));
  }, 600);
});

gantt.on('taskAdd', ({ task }) => api.post(`/projects/${projectId}/tasks`, [task]));
gantt.on('taskRemove', ({ task }) => api.delete(`/projects/${projectId}/tasks/${task.id}`));
gantt.on('dependencyCreate', ({ dependency }) => api.post(`/projects/${projectId}/links`, dependency));
gantt.on('dependencyRemove', ({ dependency }) => api.delete(`/projects/${projectId}/links/${dependency.id}`));
```

For simpler setups, save the whole project with `toJSON()` after `tasksScheduled`. Do not feed every change back through `tasks` or `dependencies` props: each new array reloads the project and clears the undo history.

## Styling hooks

The root has the class `lq-gantt`, a `lq-theme-light`, `lq-theme-dark` or `lq-theme-auto` class, and `lq-gantt--readonly`, `lq-gantt--critical`, `lq-gantt--baselines`, `lq-gantt--dragging` and `lq-gantt--linking` while those states apply. Bars are `lq-gantt-bar` with `--summary`, `--milestone`, `--manual`, `--critical`, `--conflict` and `--selected`. Theme with the shared `--lq-*` tokens and `--lq-gantt-bar-color`, `--lq-gantt-summary`, `--lq-gantt-milestone`, `--lq-gantt-critical`, `--lq-gantt-baseline`, `--lq-gantt-link`, `--lq-gantt-today` and `--lq-gantt-nonworking-bg`. A task's `color` sets its bar color. See the shared [theming guide](https://docs.birchui.com/grid/theming.md).
