> ## Documentation Index
> Fetch the complete documentation index at: https://learn.nextedy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Item Script API (Task and Work Item Objects)

> The Item Script in Nextedy GANTT executes server-side JavaScript for each work item during data loading.

export const LastReviewed = ({date}) => {
  if (!date) return null;
  const formatted = new Date(`${date}T00:00:00Z`).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
    timeZone: "UTC"
  });
  return <p className="mt-10 text-sm text-gray-400 dark:text-zinc-500 not-prose">
      Last reviewed on {formatted}
    </p>;
};

Configure the Item Script in **Widget Parameters > Advanced > Item Script**.

## Script Variables

The following variables are available in the Item Script scope:

| Variable           | Type                 | Description                                                                                                  |
| ------------------ | -------------------- | ------------------------------------------------------------------------------------------------------------ |
| `task`             | Task object          | The Gantt task being prepared for client rendering. Modify its properties to change appearance and behavior. |
| `wi`               | IWorkItem            | The source Polarion work item. Read work item fields, status, type, assignees, and linked items.             |
| `item`             | IWorkItem            | Alias for `wi` -- the same source work item object.                                                          |
| `plan`             | IPlan                | The source Polarion plan (Plans Gantt only). Access plan dates, template ID, and contained work items.       |
| `trackerService`   | ITrackerService      | Polarion tracker service for querying work items via Lucene queries.                                         |
| `ganttDataService` | IGanttDataService    | Gantt data service for accessing Gantt-specific data and helpers.                                            |
| `config`           | Configuration object | The current Gantt configuration, including page parameters.                                                  |
| `util`             | Utility helper       | Helper methods for date conversion and plan schedule derivation.                                             |

<Warning title="Polarion 2304+ Scripting Changes">
  Since Polarion version 2304, the scripting engine requires getter methods instead of direct property access. Use `wi.getType().getId()` instead of `wi.type.id`. Use `typeof wi !== 'undefined'` instead of `wi != null` for existence checks.
</Warning>

## Task Object Properties

The `task` object represents a Gantt chart task. You can read and modify these properties:

| Property          | Type      | Default                 | Description                                                                                                                           |
| ----------------- | --------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `task.id`         | `String`  | *from work item*        | Unique task identifier derived from the Polarion work item ID.                                                                        |
| `task.text`       | `String`  | *from work item*        | Display label combining the work item ID and title.                                                                                   |
| `task.start_date` | `Date`    | *from configured field* | Task start date. Set to override the configured start field value.                                                                    |
| `task.duration`   | `Integer` | `10`                    | Task duration in days (or hours in high-precision mode).                                                                              |
| `task.progress`   | `Float`   | *from configured field* | Completion percentage as a decimal (0.0 to 1.0).                                                                                      |
| `task.parent`     | `String`  | *from parent link*      | ID of the parent task in the hierarchy.                                                                                               |
| `task.type`       | `String`  | *from configuration*    | Gantt task type: `task` (normal bar), `project` (summary bar derived from children), or `milestone` (diamond shape, zero duration).   |
| `task.color`      | `String`  | `null`                  | Static CSS color for the task bar. Overrides all dynamic coloring including progress-based colors.                                    |
| `task.taskColor`  | `String`  | `null`                  | Dynamic CSS color for the task bar. Only overrides the default blue color; does not affect progress-based colors (red, orange, gray). |
| `task.itemId`     | `String`  | *from work item*        | Polarion work item ID (e.g., `WI-123`).                                                                                               |
| `task.projectId`  | `String`  | *from work item*        | Polarion project ID containing the work item.                                                                                         |
| `task.readonly`   | `Boolean` | `false`                 | When `true`, prevents the task from being dragged or resized.                                                                         |
| `task.unplanned`  | `Boolean` | `false`                 | When `true`, marks the task as unplanned (no scheduled dates).                                                                        |
| `task.open`       | `Boolean` | `true`                  | Controls whether a parent (summary) task is expanded. Set to `false` to render the item collapsed when the Gantt chart loads.         |
| `task.hide`       | `Boolean` | `false`                 | When `true`, hides the task from the chart. Use for conditional filtering beyond what the widget query provides.                      |
| `task.url`        | `String`  | *generated*             | URL to the Polarion work item.                                                                                                        |

### Custom Fields Map

Pass additional data to the client using `task.getFields()`:

```javascript theme={null}
task.getFields().put("myField", "myValue");
```

Access the value on the client side (e.g., in Gantt Config Script templates):

```javascript theme={null}
task.fields.myField
```

## Color Logic

There are two color properties with different behavior:

| Property         | Behavior                                                              | Use Case                                                          |
| ---------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `task.color`     | **Static** -- overrides ALL colors, including progress-based coloring | Force a specific color regardless of task status                  |
| `task.taskColor` | **Dynamic** -- only overrides the default blue color                  | Change color while preserving red/orange/gray progress indicators |

<Tip title="Static vs. Dynamic Coloring">
  Use `task.taskColor` when you want to keep progress-based color indicators (red for overdue, orange for delayed, gray for resolved). Use `task.color` only when you want to force a specific color regardless of progress status. To use fully static coloring, also set `gantt.config.show_progress_colors=false` in the Gantt Config Script.
</Tip>

### Color by Assignee Example

```javascript theme={null}
var assignee = null;
var aIterator = wi.getAssignees().iterator();
if (aIterator.hasNext()) {
    assignee = aIterator.next();
    if (assignee && assignee.id === "yourAssigneeId") {
        task.taskColor = "#a9d08e";
    }
}
```

### Color by Type and Status Example

```javascript theme={null}
// Requires gantt.config.show_progress_colors=false in Config Script
if (wi.getType().getId() === "workpackage" && wi.getStatus().getId() === "draft") {
    var today = new Date();
    if (task.start_date.getTime() < today.getTime()) {
        task.color = "green";
    }
}
```

## Progress Calculation

Compute progress from time estimates:

```javascript theme={null}
if (wi.getType().getId() === 'workpackage') {
    var all = (wi.getRemainingEstimate() != null ? wi.getRemainingEstimate().getHours() : 0)
            + (wi.getTimeSpent() != null ? wi.getTimeSpent().getHours() : 0);
    var done = (wi.getTimeSpent() != null ? wi.getTimeSpent().getHours() : 0);

    if (wi.getResolution() != null) {
        task.progress = 1;
    } else if (all == 0) {
        task.progress = 0;
    } else {
        task.progress = done / all;
    }

    var progressString = (wi.getTimeSpent() != null ? wi.getTimeSpent() : "0h")
        + " | " + (wi.getRemainingEstimate() != null ? wi.getRemainingEstimate() : "0h")
        + " (" + Math.round(task.progress * 100) + " %)";
    task.getFields().put("progressString", progressString);
}
```

## Milestone Configuration

Set a task to render as a milestone diamond:

```javascript theme={null}
if (wi.getType().getId() === "release" && wi.getStatus().getId() === "inprogress") {
    task.type = "milestone";
}
```

## Schedule Derivation from Plans

Derive a task's schedule from its Polarion plan assignment:

```javascript theme={null}
if (task.unplanned) {
    task.deriveScheduleFromPlans(wi, "iteration");
}
```

Manual plan schedule derivation:

```javascript theme={null}
var plans = wi.getPlannedIn().iterator();
while (plans.hasNext()) {
    var plan = plans.next();
    if (plan.getTemplate().getId() === "Iteration") {
        task.start_date = util.getDate(plan, "startDate");
        task.end_date = util.getDate(plan, "dueDate");
        task.duration = null;
        task.readonly = true;
        task.unplanned = false;
    }
}
```

## Baseline Comparison

Set custom baseline values for schedule comparison:

```javascript theme={null}
task.planned_start_date = util.getDate(wi, "gantt_initial_start");
task.planned_duration = util.getDuration(wi, "gantt_initial_duration");
```

## Passing Data to Right-Side Text

Prepare data in the Item Script, then render it in the Gantt Config Script:

**Item Script:**

```javascript theme={null}
if (wi.getType().getId() === 'epic') {
    var o = wi.getValue("owner");
    if (o != null) {
        task.getFields().put("owner", o.getName());
    }
}
```

**Gantt Config Script:**

```javascript theme={null}
gantt.templates.rightside_text = function(start, end, task) {
    return (task.fields.owner ? "Owner: <b>" + task.fields.owner + "</b>" : "");
};
```

## Script Execution Flow

<Frame>
  <img src="https://mintcdn.com/none-17b4493f/umKaPvHwUHw-ZQFM/gantt/diagrams/reference/api/item-script-api/diagram-1.svg?fit=max&auto=format&n=umKaPvHwUHw-ZQFM&q=85&s=18df5f5c7b50fa7444175d28540cb43b" alt="diagram" style={{ maxWidth: "440px", width: "100%" }} width="440" height="470" data-path="gantt/diagrams/reference/api/item-script-api/diagram-1.svg" />
</Frame>

## Error Handling

* Script errors display as a warning indicator in the Gantt chart toolbar
* The error message includes the prefix **Item Script Error:**
* Add null checks before accessing work item properties: `if (wi != null) { ... }`
* On Polarion 2304+, use `typeof wi !== 'undefined'` for existence checks

## Configuration Example

A complete Item Script combining progress calculation, color logic, and right-side text:

```javascript theme={null}
// Guard against null work items
if (wi != null) {
    // Calculate progress from time estimates
    var all = (wi.getRemainingEstimate() != null ? wi.getRemainingEstimate().getHours() : 0)
            + (wi.getTimeSpent() != null ? wi.getTimeSpent().getHours() : 0);
    var done = (wi.getTimeSpent() != null ? wi.getTimeSpent().getHours() : 0);

    if (wi.getResolution() != null) {
        task.progress = 1;
    } else if (all == 0) {
        task.progress = 0;
    } else {
        task.progress = done / all;
    }

    // Set epics as project items
    if (wi.getType().getId() === 'epic') {
        task.type = 'project';
    }

    // Derive unplanned items from iteration plan
    if (task.unplanned) {
        task.deriveScheduleFromPlans(wi, "iteration");
    }
}
```

## Related Pages

* [Gantt Config Script API](/gantt/reference/api/config-script-api) -- client-side script for templates and events
* [Velocity Context Variables](/gantt/reference/api/velocity-context) -- server-side variables available in script pre-processing
* [Item Color Legend](/gantt/reference/item-color-legend) -- default color behavior and how scripts override it
* [Page Parameters API](/gantt/reference/api/page-parameters-api) -- access user-input parameters in scripts
* [Marker Factory API](/gantt/reference/api/markers-api) -- add milestone markers from scripts

<LastReviewed date="2026-07-07" />
