The chat responses are generated using Generative AI technology for intuitive search and may not be entirely accurate. They are not intended as professional advice. For full details, including our use rights, privacy practices and potential export control restrictions, please refer to our Generative AI Service Privacy Information. As this is a test version, please let us know if something irritating comes up. Like you get recommended a chocolate fudge ice cream instead of an energy managing application. If that occurs, please use the feedback button in our contact form!
Skip to content

Work item card

2612

The Work item card panel showing title, badges, description, links and the edit forms

AspectDetails
Folderexamples/work-item-card
Identifiercom.example.workitemcard
Viewform extension card
Placement<applicationView id="com.example.workitemcard.card" label="Work item card" height="640px"/>
UsesfetchContext(), REST GET …/workitems/{id}, GET …/linkedworkitems?include=workItem, PATCH …/workitems/{id} (title), GET …/actions/getWorkflowActions and PATCH …?workflowAction= (status), POST …/workitems/{id}/comments

What it does

  1. Fetches the context to learn projectId, workItemId, restBaseUrl and restToken.
  2. Loads the work item with a sparse field set, then its linked work items with include=workItem so that the titles arrive in the same response. Suspect links get a warning badge.
  3. Renders a card: title, badges for type, status, priority and severity with their Polarion names and icons, the HTML description, and the links with roles.
  4. Offers three write operations, each a small component: Rename (PATCH attributes.title), Status (runs a workflow action, so the workflow's conditions and required fields apply) and Add comment (POST …/comments).

Files

  • work-item-card/
    • manifest.json
    • src/
      • App.tsx loading and rendering
      • components/
        • RenameForm.tsx PATCH title
        • StatusForm.tsx workflow action
        • RequiredFields.tsx inputs for required fields
        • CommentForm.tsx POST comment
      • polarion.ts restFetch helper
      • types.ts JSON:API shapes
      • fields.ts field metadata → inputs and values
      • main.tsx
      • styles.css
    • scripts/package.mjs
    • …

manifest.json

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.workitemcard",
  "title": "Work item card",
  "description": "Shows the current work item, its linked work items and lets the user rename it through the Polarion REST API.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.1",
  "views": {
    "formExtensions": [
      {
        "identifier": "card",
        "title": "Work item card",
        "rootDirectory": "card",
        "document": "index.html"
      }
    ]
  }
}

src/polarion.ts

The REST helper used by all REST examples. It is the only place that knows about the token header.

src/polarion.ts
import type { PolarionContext } from "polarion-app-sdk";

/**
 * Calls the Polarion REST API (JSON:API) on behalf of the logged-in user.
 *
 * `context.restBaseUrl` is the absolute base URL of the REST API, for example
 * `https://host/polarion/rest/v1` (no trailing slash). `context.restToken` is a
 * short-lived token that Polarion hands to the application view; it must be
 * sent in the `X-Polarion-REST-Token` header.
 */
export async function restFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
  const headers = new Headers(init.headers);
  headers.set("X-Polarion-REST-Token", context.restToken ?? "");
  headers.set("Accept", "application/json");
  if (init.body !== undefined && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  const response = await fetch(`${context.restBaseUrl}${path}`, { ...init, headers });
  if (!response.ok) {
    throw new Error(`REST ${response.status}: ${await response.text()}`);
  }
  if (response.status === 204) {
    return null as T;
  }
  return (await response.json()) as T;
}

src/types.ts

Only the parts of the JSON:API documents the component reads. Typing the full REST schema is unnecessary; keep the types close to what you use.

src/types.ts
/** Minimal JSON:API shapes used by this example. */

export interface WorkItemAttributes {
  title: string;
  status: string;
  type: string;
  priority?: string;
  severity?: string;
  description?: { type: string; value: string };
}

export interface WorkItemResource {
  /** "PROJECT/WI-ID" */
  id: string;
  type: "workitems";
  attributes: WorkItemAttributes;
}

export interface WorkItemResponse {
  data: WorkItemResource;
}

export interface LinkedWorkItemResource {
  id: string;
  type: "linkedworkitems";
  attributes: { role: string; suspect?: boolean };
  relationships: { workItem: { data: { id: string; type: "workitems" } } };
}

export interface LinkedWorkItemsResponse {
  data: LinkedWorkItemResource[];
  included?: WorkItemResource[];
}

/** A linked work item flattened for rendering. */
export interface LinkedItem {
  role: string;
  suspect: boolean;
  id: string;
  title: string;
  status: string;
}

/** One entry of GET …/workitems/{id}/actions/getWorkflowActions. */
export interface WorkflowAction {
  /** Position in the list; the PATCH does not accept it. */
  id: string;
  /** Action id from the workflow configuration, e.g. "start_progress": the value for `?workflowAction=`. */
  nativeActionId: string;
  name: string;
  targetStatus: string;
  available: boolean;
  unavailableReason?: string;
  requiredFields?: string[];
}

export interface WorkflowActionsResponse {
  data?: WorkflowAction[];
}

/** UI state of a save action. */
export type ActionState = { kind: "idle" | "saving" | "ok" | "error"; text?: string };

src/App.tsx

src/App.tsx
import { useCallback, useEffect, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import DOMPurify from "dompurify";
import { restFetch } from "./polarion";
import type { LinkedItem, LinkedWorkItemsResponse, WorkItemAttributes, WorkItemResponse } from "./types";
import { loadCurrentOption, loadOptionsForType, type EnumOption } from "./fields";
import RenameForm from "./components/RenameForm";
import StatusForm from "./components/StatusForm";
import CommentForm from "./components/CommentForm";

interface Badge {
  field: string;
  /** Shown before the option name where the name alone is ambiguous ("Medium"). */
  label?: string;
  option: EnumOption;
}

interface Card {
  id: string;
  attributes: WorkItemAttributes;
  badges: Badge[];
  linked: LinkedItem[];
}

/** An enumeration value with Polarion's icon and name, colored like in Polarion. */
function OptionBadge({ badge }: { badge: Badge }) {
  const { option } = badge;
  return (
    <span className={`badge ${badge.field}`} style={option.color ? { borderColor: option.color } : undefined} title={`${badge.field}: ${option.id}`}>
      {option.iconURL && <img src={`${window.location.origin}${option.iconURL}`} alt="" />}
      {badge.label && <span className="badge-label">{badge.label}</span>}
      {option.name}
    </span>
  );
}

// Enumeration fields shown as badges, with the label for those whose value alone is unclear.
const BADGE_FIELDS: { field: keyof WorkItemAttributes; label?: string }[] = [{ field: "type" }, { field: "status" }, { field: "priority", label: "Priority" }, { field: "severity", label: "Severity" }];

/**
 * Loads the work item and its links, plus the display names and icons of its enumeration
 * values. The REST API returns enumeration fields as ids ("workpackage", "55.0"); the names
 * come from getCurrentOptions, and for linked items from the status options of their type.
 */
async function loadCard(context: PolarionContext): Promise<Card> {
  const { projectId, workItemId } = context;
  if (!projectId || !workItemId) {
    throw new Error("This view must be placed on a work item form (projectId / workItemId missing).");
  }
  const base = `/projects/${projectId}/workitems/${workItemId}`;

  const item = await restFetch<WorkItemResponse>(context, `${base}?fields[workitems]=id,title,status,type,priority,severity,description`);

  const links = await restFetch<LinkedWorkItemsResponse>(context, `${base}/linkedworkitems?fields[linkedworkitems]=role,suspect,workItem&include=workItem&fields[workitems]=id,title,status,type`);

  // The linked items only carry an id; the full work items travel in `included`.
  const byId = new Map((links.included ?? []).map((wi) => [wi.id, wi]));

  // Display values: one call per badge field, one per work item type among the links.
  const present = BADGE_FIELDS.filter((b) => item.data.attributes[b.field]);
  const linkedTypes = [...new Set((links.included ?? []).map((wi) => wi.attributes.type))];
  const [options, statusByType] = await Promise.all([Promise.all(present.map((b) => loadCurrentOption(context, b.field).catch(() => null))), Promise.all(linkedTypes.map((t) => loadOptionsForType(context, "status", t).catch(() => new Map<string, EnumOption>()))).then((maps) => new Map(linkedTypes.map((t, i) => [t, maps[i]])))]);
  const badges = present.flatMap((b, i) => {
    const option = options[i] ?? { id: String(item.data.attributes[b.field]), name: String(item.data.attributes[b.field]) };
    return [{ field: b.field, label: b.label, option }];
  });

  const linked: LinkedItem[] = links.data.map((link) => {
    const target = byId.get(link.relationships.workItem.data.id);
    const status = target?.attributes.status ?? "";
    return {
      role: link.attributes.role,
      suspect: link.attributes.suspect === true,
      id: link.relationships.workItem.data.id,
      title: target?.attributes.title ?? "",
      status: (target && statusByType.get(target.attributes.type)?.get(status)?.name) ?? status,
    };
  });

  return { id: item.data.id, attributes: item.data.attributes, badges, linked };
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [card, setCard] = useState<Card | null>(null);
  const [error, setError] = useState<string | null>(null);

  const reload = useCallback(async (ctx: PolarionContext) => {
    try {
      setCard(await loadCard(ctx));
      setError(null);
    } catch (error) {
      console.error("Unable to load the work item:", error);
      const message = error instanceof Error ? error.message : String(error);
      setError(`Unable to load the work item: ${message}`);
    }
  }, []);

  useEffect(() => {
    let cancelled = false;

    fetchContext()
      .then((ctx) => {
        if (cancelled) {
          return;
        }
        setContext(ctx);
        return reload(ctx);
      })
      .catch((error: unknown) => {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the Polarion context:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the Polarion context: ${message}`);
      });

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      destroy();
    };
  }, [reload]);

  if (error) {
    return <div className="card error">{error}</div>;
  }
  if (!context || !card) {
    return <p className="muted">Loading work item…</p>;
  }

  const a = card.attributes;
  const origin = window.location.origin;

  return (
    <div className="card">
      <h1>{a.title}</h1>
      <div className="badges">
        {card.badges.map((b) => (
          <OptionBadge key={b.field} badge={b} />
        ))}
      </div>

      <h2>Description</h2>
      {a.description?.value ? (
        // The description is HTML written by users. Sanitize it before it enters the DOM:
        // the view runs on Polarion's origin with the user's session.
        <div className="description" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(a.description.value) }} />
      ) : (
        <p className="muted">No description.</p>
      )}

      <h2>Linked work items</h2>
      {card.linked.length === 0 ? (
        <p className="muted">No links.</p>
      ) : (
        <ul className="links">
          {card.linked.map((link) => {
            const [project, id] = link.id.split("/");
            return (
              <li key={`${link.role}-${link.id}`}>
                <span className="role">{link.role}</span>
                <a href={`${origin}/polarion/#/project/${project}/workitem?id=${id}`} target="_top">
                  {id}
                </a>{" "}
                {link.title} <span className="muted">({link.status})</span>
                {link.suspect && <span className="badge warn">suspect</span>}
              </li>
            );
          })}
        </ul>
      )}

      {/* Three ways of writing through the REST API, each in its own small component. */}
      <RenameForm context={context} resourceId={card.id} currentTitle={a.title} onSaved={() => reload(context)} />
      <StatusForm context={context} resourceId={card.id} currentStatus={a.status} workItemType={a.type} onSaved={() => reload(context)} />
      <CommentForm context={context} />
    </div>
  );
}

Points worth noting:

  • Two requests, joined by id. The linked-work-items response carries the link resources in data and the target work items in included. The byId map joins them. workItem must be listed in fields[linkedworkitems], otherwise the relationship is not returned.
  • The description is HTML written by users. Polarion stores rich text as { type: 'text/html', value }. The view runs on Polarion's origin with the user's session, so a script inside a description would run there too. The example passes the value through DOMPurify before dangerouslySetInnerHTML renders it; keep a sanitizer in front of any Polarion rich text you render.
  • Enumeration values are ids. The REST API returns type, status, priority and severity as ids such as workpackage or 55.0. The card asks GET …/fields/{fieldId}/actions/getCurrentOptions for the selected option, which carries the display name, icon and color Polarion uses, and renders the badges from it. Statuses of linked items and of workflow targets come from GET …/workitems/fields/status/actions/getAvailableOptions?type=<type>, because status names depend on the work item type.
  • Links open in the top window. target="_top" makes the whole Polarion UI navigate instead of loading inside the iframe.
  • Each write is a component with its own state. The rename form is keyed on the current title so that it resets after a reload; the status form keeps its state, so its confirmation stays visible, and reloads the workflow actions when the status changes, dropping the old list first so that a stale transition cannot be chosen.

Writing: status and comments

src/components/StatusForm.tsx
import { useEffect, useState } from "react";
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "../polarion";
import RequiredFields from "./RequiredFields";
import { inputFor, isEmpty, loadFieldsMetadata, loadOptionsForType, toJsonApi, type EnumOption, type FieldMeta } from "../fields";
import type { ActionState, WorkflowAction, WorkflowActionsResponse } from "../types";

interface CurrentValuesResponse {
  data: {
    attributes?: Record<string, unknown>;
    relationships?: Record<string, { data?: unknown }>;
  };
}

interface Props {
  context: PolarionContext;
  resourceId: string;
  currentStatus: string;
  /** Work item type id; status names depend on it. */
  workItemType: string;
  onSaved: () => Promise<void>;
}

/**
 * Changes the status by running a workflow action, as the status menu in Polarion does.
 *
 * Writing `attributes.status` directly would bypass the workflow: conditions, required
 * fields and functions of the transition would not run. Instead the component lists the
 * actions the workflow offers for the current status and runs the chosen one with
 * `PATCH …/workitems/{id}?workflowAction=<nativeActionId>`.
 *
 * When the action requires fields that are still empty, the form asks for them and sends
 * them in the same PATCH, as the transition dialog in Polarion does.
 */
export default function StatusForm({ context, resourceId, currentStatus, workItemType, onSaved }: Props) {
  const [actions, setActions] = useState<WorkflowAction[] | null>(null);
  const [actionId, setActionId] = useState("");
  const [state, setState] = useState<ActionState>({ kind: "idle" });
  // Field types of this work item (built-in and custom), loaded once.
  const [metadata, setMetadata] = useState<Record<string, FieldMeta> | null>(null);
  // Required fields of the chosen action that are empty on the work item, and their new values.
  const [missing, setMissing] = useState<FieldMeta[] | null>(null);
  const [values, setValues] = useState<Record<string, string>>({});

  const path = `/projects/${context.projectId}/workitems/${context.workItemId}`;

  useEffect(() => {
    loadFieldsMetadata(context)
      .then(setMetadata)
      .catch(() => setMetadata({}));
  }, [context]);

  // Display names of the statuses, so actions read "Review → Reviewed" instead of "→ reviewed".
  const [statuses, setStatuses] = useState<Map<string, EnumOption>>(new Map());
  useEffect(() => {
    loadOptionsForType(context, "status", workItemType)
      .then(setStatuses)
      .catch(() => setStatuses(new Map()));
  }, [context, workItemType]);
  const statusName = (id: string) => statuses.get(id)?.name ?? id;

  // The workflow decides which actions exist for the current status and whether the
  // user may run them; unavailable ones carry the reason.
  useEffect(() => {
    let cancelled = false;
    // Drop the previous status's actions at once, so a stale transition cannot be chosen
    // while the new list loads.
    setActions(null);
    setActionId("");
    restFetch<WorkflowActionsResponse>(context, `${path}/actions/getWorkflowActions`)
      .then((r) => {
        if (!cancelled) setActions(r.data ?? []);
      })
      .catch((e: unknown) => {
        if (!cancelled) setState({ kind: "error", text: e instanceof Error ? e.message : String(e) });
      });
    return () => {
      cancelled = true;
    };
  }, [context, path, currentStatus]);

  const selected = actions?.find((a) => a.nativeActionId === actionId);

  // Read the current values of the action's required fields; only empty ones need input.
  // Each field's metadata says whether it is an attribute or a relationship and how to edit it.
  useEffect(() => {
    setValues({});
    const required = selected?.requiredFields ?? [];
    if (required.length === 0) {
      setMissing([]);
      return;
    }
    setMissing(null);
    if (!metadata) return;
    const metas = required.map((id): FieldMeta => metadata[id] ?? { id, label: id, part: "attributes", type: { kind: "unknown" } });
    let cancelled = false;
    restFetch<CurrentValuesResponse>(context, `${path}?fields[workitems]=${required.join(",")}`)
      .then((r) => {
        const empty = metas.filter((m) => (m.part === "attributes" ? isEmpty(r.data.attributes?.[m.id]) : isEmpty(r.data.relationships?.[m.id]?.data)));
        if (cancelled) return;
        setMissing(empty);
        // A checkbox has a value even when it is not ticked.
        setValues(Object.fromEntries(empty.filter((m) => inputFor(m) === "checkbox").map((m) => [m.id, "false"])));
      })
      .catch(() => {
        if (!cancelled) setMissing(metas);
      });
    return () => {
      cancelled = true;
    };
  }, [context, path, selected, metadata]);

  // Run is possible once every empty required field is editable here and has a value.
  const complete = missing !== null && missing.every((m) => inputFor(m) !== null && (values[m.id] ?? "").trim() !== "");

  async function run() {
    if (!selected) return;
    setState({ kind: "saving" });
    try {
      // The action runs on the server with the workflow's conditions and functions. The
      // parameter takes the action id from the workflow configuration (nativeActionId).
      // The body carries the required fields, which Polarion sets before the transition;
      // the action itself sets the target status. The metadata decides where each value
      // goes and in which shape (string, rich text, enumeration list, relationship, …).
      const attributes: Record<string, unknown> = {};
      const relationships: Record<string, unknown> = {};
      for (const field of missing ?? []) {
        (field.part === "attributes" ? attributes : relationships)[field.id] = toJsonApi(field, values[field.id].trim());
      }
      await restFetch(context, `${path}?workflowAction=${encodeURIComponent(selected.nativeActionId)}`, {
        method: "PATCH",
        body: JSON.stringify({ data: { type: "workitems", id: resourceId, attributes, relationships } }),
      });
      await onSaved();
      // The new status offers different actions; they reload through the effect above.
      setState({ kind: "ok", text: `${selected.name}: status is now ${statusName(selected.targetStatus)}.` });
    } catch (e) {
      // A condition or a required field that blocks the transition comes back as an HTTP error.
      setState({ kind: "error", text: e instanceof Error ? e.message : String(e) });
    }
  }

  return (
    <>
      <h2>Status</h2>
      {actions === null && state.kind !== "error" && <p className="muted">Loading workflow actions…</p>}
      {actions !== null && actions.length === 0 && <p className="muted">The workflow offers no action from status {statusName(currentStatus)}.</p>}
      {actions !== null && actions.length > 0 && (
        <div className="row">
          <select value={actionId} onChange={(e) => setActionId(e.target.value)}>
            <option value="">Choose an action…</option>
            {actions.map((a) => (
              <option key={a.nativeActionId} value={a.nativeActionId} disabled={!a.available}>
                {a.name} → {statusName(a.targetStatus)}
                {a.available ? "" : ` (${a.unavailableReason ?? "not available"})`}
              </option>
            ))}
          </select>
          <button onClick={run} disabled={!selected || !selected.available || !complete || state.kind === "saving"}>
            {state.kind === "saving" ? "Saving…" : "Run action"}
          </button>
        </div>
      )}
      {selected && missing && missing.length > 0 && (
        <>
          <p className="muted">{selected.name} requires these fields:</p>
          <RequiredFields context={context} fields={missing} values={values} onChange={(field, value) => setValues((v) => ({ ...v, [field]: value }))} />
        </>
      )}
      {state.kind === "ok" && <p className="ok">{state.text}</p>}
      {state.kind === "error" && <p className="err">{state.text}</p>}
    </>
  );
}

Change the status through a workflow action, never by writing attributes.status. A PATCH that sets status directly is accepted, but it bypasses the workflow: the transition's conditions, required fields and functions do not run, and the work item can end up in a state the workflow cannot leave cleanly.

The component does what the status menu in Polarion does:

  1. GET …/workitems/{id}/actions/getWorkflowActions returns the actions offered from the current status. Each one carries name, targetStatus, available with an unavailableReason, and requiredFields. Unavailable actions are shown disabled with the reason.
  2. PATCH …/workitems/{id}?workflowAction=<nativeActionId> runs the chosen action. Pass nativeActionId, the action id from the workflow configuration (for example reviewed); the numeric id of the list entry is rejected with The workflow action '8' was not found.
  3. Required fields are filled in the same request, as the transition dialog in Polarion does. When an action lists requiredFields, the component reads their current values and asks only for the empty ones. It sends them in attributes (or, for assignee, in relationships) of the PATCH that carries ?workflowAction=. Polarion sets the fields first and then runs the transition. Verified on 2612: Reject with resolution: "invalid" in the body moves a work package to rejected in one call.
  4. The workflow checks still apply. Without the resolution, Reject comes back as HTTP 400: The required field 'Resolution' (id: 'resolution') of Work Item … is empty. The component shows that message.
  5. Fields that the action clears (clearedFields) are emptied after the transition. A value sent for such a field in the same request does not survive.

Nothing in the form is specific to a field. The required fields differ per transition, and the inputs adapt to whatever the workflow and the work item type define, custom fields included:

  • Which fields: the action's requiredFields, filtered to those that are empty on this work item.
  • How to edit them: GET …/workitems/{id}/actions/getFieldsMetadata describes every field of the work item: whether it is an attribute or a relationship, its kind (string, text, enumeration, date, date-time, duration, boolean, relationship, …), the target resource type of a relationship, and multi for multi-value fields. fields.ts maps the kind to an input and converts the entered value into the JSON:API shape: a string, rich text as { type, value }, an enumeration list for multi-value fields, or a relationship { data: … }.
  • Which values: enumeration options come from GET …/fields/{fieldId}/actions/getAvailableOptions, and relationship targets from the list of that resource type (users and plans in this example).

Verified on 2612 with a work package: Quickly Accept asked for Initial Estimate (a duration, text input), Reject for Resolution (an enumeration, select). Both moved the work item in one request. Field kinds the example does not edit, such as structures, show a note pointing to the work item form, and Run action stays disabled.

src/fields.ts
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "./polarion";

/**
 * Field types as returned by GET …/workitems/{id}/actions/getFieldsMetadata.
 * The same call describes built-in and custom fields of this work item's type.
 */
export interface FieldType {
  kind: string; // "string", "text", "enumeration", "date", "date-time", "duration", "boolean", "relationship", …
  enumName?: string;
  targetResourceTypes?: string[];
  multi?: boolean;
}

export interface FieldMeta {
  id: string;
  label: string;
  /** Attributes and relationships travel in different parts of a JSON:API body. */
  part: "attributes" | "relationships";
  type: FieldType;
}

interface MetadataResponse {
  data: {
    attributes?: Record<string, { label?: string; type: FieldType }>;
    relationships?: Record<string, { label?: string; type: FieldType }>;
  };
}

export async function loadFieldsMetadata(context: PolarionContext): Promise<Record<string, FieldMeta>> {
  const r = await restFetch<MetadataResponse>(context, `/projects/${context.projectId}/workitems/${context.workItemId}/actions/getFieldsMetadata`);
  const fields: Record<string, FieldMeta> = {};
  for (const part of ["attributes", "relationships"] as const) {
    for (const [id, f] of Object.entries(r.data[part] ?? {})) {
      fields[id] = { id, label: f.label ?? id, part, type: f.type };
    }
  }
  return fields;
}

/** Relationship targets the form can offer, with the list request that fills the select. */
export const RELATIONSHIP_SOURCES: Record<string, (context: PolarionContext) => string> = {
  users: () => "/users?fields[users]=name&sort=name&page[size]=100",
  plans: (context) => `/projects/${context.projectId}/plans?fields[plans]=name&page[size]=100`,
};

/** How the form edits a field of this type, or null when the example does not support it. */
export function inputFor(meta: FieldMeta): "select" | "text" | "textarea" | "date" | "datetime" | "checkbox" | null {
  const { kind, targetResourceTypes } = meta.type;
  if (kind === "relationship") return targetResourceTypes?.length === 1 && RELATIONSHIP_SOURCES[targetResourceTypes[0]] ? "select" : null;
  switch (kind) {
    case "enumeration":
      return "select";
    case "string":
    case "duration": // for example "1d 4h"
      return "text";
    case "text":
      return "textarea";
    case "date":
      return "date";
    case "date-time":
      return "datetime";
    case "boolean":
      return "checkbox";
    default:
      return null; // structures, tables and other kinds: edit them in the form
  }
}

/** Converts the form's string value into the JSON:API shape the field expects. */
export function toJsonApi(meta: FieldMeta, value: string): unknown {
  const { kind, multi, targetResourceTypes } = meta.type;
  if (kind === "relationship") {
    const ref = { type: targetResourceTypes![0], id: value };
    return { data: multi ? [ref] : ref };
  }
  switch (kind) {
    case "enumeration":
      return multi ? [value] : value;
    case "text":
      return { type: "text/plain", value };
    case "date-time":
      return new Date(value).toISOString();
    case "boolean":
      return value === "true";
    default:
      return value;
  }
}

/** True when a value read from the REST API counts as not filled in. */
export function isEmpty(value: unknown): boolean {
  if (value === undefined || value === null || value === "") return true;
  if (Array.isArray(value)) return value.length === 0;
  if (typeof value === "object" && "value" in value) return isEmpty((value as { value: unknown }).value);
  return false;
}

/** An enumeration option as Polarion shows it: display name, icon and color. */
export interface EnumOption {
  id: string;
  name: string;
  iconURL?: string;
  color?: string;
}

interface OptionsResponse {
  data?: EnumOption[];
}

/** The selected option of an enumeration field of the current work item, for example its status. */
export async function loadCurrentOption(context: PolarionContext, fieldId: string): Promise<EnumOption | null> {
  const r = await restFetch<OptionsResponse>(context, `/projects/${context.projectId}/workitems/${context.workItemId}/fields/${fieldId}/actions/getCurrentOptions`);
  return r.data?.[0] ?? null;
}

/** All options of an enumeration field for one work item type, by id. Status names differ per type. */
export async function loadOptionsForType(context: PolarionContext, fieldId: string, type: string): Promise<Map<string, EnumOption>> {
  const r = await restFetch<OptionsResponse>(context, `/projects/${context.projectId}/workitems/fields/${fieldId}/actions/getAvailableOptions?type=${encodeURIComponent(type)}`);
  return new Map((r.data ?? []).map((o) => [o.id, o]));
}
src/components/RequiredFields.tsx
import { useEffect, useState } from "react";
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "../polarion";
import { inputFor, RELATIONSHIP_SOURCES, type FieldMeta } from "../fields";

interface Props {
  context: PolarionContext;
  /** The required fields of the action that are still empty, with their metadata. */
  fields: FieldMeta[];
  values: Record<string, string>;
  onChange: (field: string, value: string) => void;
}

interface Option {
  id: string;
  name: string;
}

interface ListResponse {
  data?: { id: string; name?: string; attributes?: { name?: string } }[];
}

/**
 * One input per required field, chosen from the field's metadata, so any built-in or custom
 * field works without code changes. Select options come from Polarion as well:
 * - enumerations: GET …/workitems/{id}/fields/{fieldId}/actions/getAvailableOptions
 * - relationships: the list of the target resources (users, plans; see RELATIONSHIP_SOURCES)
 */
export default function RequiredFields({ context, fields, values, onChange }: Props) {
  const [options, setOptions] = useState<Record<string, Option[]>>({});

  useEffect(() => {
    let cancelled = false;
    const base = `/projects/${context.projectId}/workitems/${context.workItemId}`;
    for (const field of fields) {
      if (inputFor(field) !== "select") continue;
      // A real application would search large lists (for example users with `query`) instead of loading 100.
      const url = field.type.kind === "relationship" ? RELATIONSHIP_SOURCES[field.type.targetResourceTypes![0]](context) : `${base}/fields/${field.id}/actions/getAvailableOptions`;
      restFetch<ListResponse>(context, url)
        .then((r) => (r.data ?? []).map((o) => ({ id: o.id, name: o.name ?? o.attributes?.name ?? o.id })))
        .catch(() => [] as Option[])
        .then((list) => {
          if (!cancelled) setOptions((o) => ({ ...o, [field.id]: list }));
        });
    }
    return () => {
      cancelled = true;
    };
  }, [context, fields]);

  return (
    <div className="required">
      {fields.map((field) => {
        const value = values[field.id] ?? "";
        const set = (v: string) => onChange(field.id, v);
        let input;
        switch (inputFor(field)) {
          case "select":
            input = options[field.id] ? (
              <select value={value} onChange={(e) => set(e.target.value)}>
                <option value="">Choose…</option>
                {options[field.id].map((o) => (
                  <option key={o.id} value={o.id}>
                    {o.name}
                  </option>
                ))}
              </select>
            ) : (
              <span className="muted">Loading…</span>
            );
            break;
          case "textarea":
            input = <textarea rows={2} value={value} onChange={(e) => set(e.target.value)} />;
            break;
          case "date":
            input = <input type="date" value={value} onChange={(e) => set(e.target.value)} />;
            break;
          case "datetime":
            input = <input type="datetime-local" value={value} onChange={(e) => set(e.target.value)} />;
            break;
          case "checkbox":
            input = <input type="checkbox" checked={value === "true"} onChange={(e) => set(String(e.target.checked))} />;
            break;
          case "text":
            input = <input value={value} onChange={(e) => set(e.target.value)} placeholder={field.type.kind === "duration" ? "for example 1d 4h" : ""} />;
            break;
          default:
            input = <span className="muted">Not editable here ({field.type.kind}); set it in the work item form.</span>;
        }
        return (
          <label key={field.id} className="row">
            <span className="field-name">{field.label}</span>
            {input}
          </label>
        );
      })}
    </div>
  );
}
src/components/CommentForm.tsx
import { useState } from "react";
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "../polarion";
import type { ActionState } from "../types";

interface Props {
  context: PolarionContext;
}

function escapeHtml(text: string): string {
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

/** Adds a comment through POST …/workitems/{id}/comments. Comment text is HTML. */
export default function CommentForm({ context }: Props) {
  const [text, setText] = useState("");
  const [state, setState] = useState<ActionState>({ kind: "idle" });

  async function add() {
    setState({ kind: "saving" });
    try {
      await restFetch(context, `/projects/${context.projectId}/workitems/${context.workItemId}/comments`, {
        method: "POST",
        body: JSON.stringify({
          data: [
            {
              type: "workitem_comments",
              attributes: { text: { type: "text/html", value: `<p>${escapeHtml(text)}</p>` } },
            },
          ],
        }),
      });
      setText("");
      setState({ kind: "ok", text: "Comment added. Reload the page to see it in the Comments section." });
    } catch (e) {
      setState({ kind: "error", text: e instanceof Error ? e.message : String(e) });
    }
  }

  return (
    <>
      <h2>Add comment</h2>
      <textarea rows={3} value={text} onChange={(e) => setText(e.target.value)} placeholder="Comment text" />
      <div className="row">
        <button onClick={add} disabled={state.kind === "saving" || text.trim() === ""}>
          {state.kind === "saving" ? "Saving…" : "Add comment"}
        </button>
      </div>
      {state.kind === "ok" && <p className="ok">{state.text}</p>}
      {state.kind === "error" && <p className="err">{state.text}</p>}
    </>
  );
}

Comments are a sub-resource of the work item. The text is HTML, so user input is escaped before it is wrapped in a paragraph.

Note

After any write, the Polarion form around the panel still shows the old values until the page is reloaded; the framework has no refresh call yet. The messages say so.

Build and deploy

cd examples/work-item-card
npm install
npm run package          # → com.example.workitemcard.zip

Upload the ZIP, then add the applicationView element to a form layout. Open a work item that has links to see the full card.

Things to try

  • Ask for assignee in the field list and render it from relationships (see the Cookbook).
  • Replace the user select in RequiredFields.tsx with a search box that calls GET /users?query=name:….
  • Add a Create follow-up task button that POSTs a new work item and links it to the current one.