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

Application context

2612

The Application context sidebar next to the Work Items table: the context fields of the sidebar placement

AspectDetails
Folderexamples/application-context
Identifiercom.example.context
Viewsform extension form, sidebar sidebar, navigation topic topic; one build for all three
Placement<applicationView id="com.example.context.form" label="Application context" height="460px"/> in a form layout; <applicationView id="com.example.context.topic"/> in Topics; the sidebar needs no configuration
UsesfetchContext(), destroy()

Hello Polarion shows a page and nothing else. This example adds the first thing most views need: knowing where they are. It reads the context once, shows every field, and makes the rules from Application context visible:

  • which fields are set depends on the placement;
  • the context is a snapshot: it is read once and does not change while the view is open;
  • a sidebar gets no selection in its context; the selection arrives only through selection-changed events, which the Selection sidebar example shows;
  • the REST token is a credential and is never displayed.

What each placement receives

The same build runs in three places. viewId tells the code which one it is; the optional fields say what the view is attached to.

FieldForm extensionSidebar, Work Items tableSidebar, DocumentNavigation topic
viewIdformsidebarsidebartopic
projectIdsetsetsetset
workItemIdthe open itemnot setnot setnot set
spaceId, documentIdnot setnot setthe Documentnot set
selectedWorkItemIdsthe open item, ["drivepilot/DP-477"]; in the multi-item edit form all ticked itemsemptyemptyempty

All four columns were read on Polarion 2612; the screenshots are on this page. Ids in selectedWorkItemIds include the project, workItemId does not. In the table the sidebar was opened with three rows selected and selectedWorkItemIds stayed empty, also after Read again: a sidebar learns the selection only from selection-changed events. With three rows ticked, the form extension in the multi-item edit form below the table listed all three ids, and workItemId was the current item.

The Application context form extension in a work item: workItemId is DP-477, selectedWorkItemIds is drivepilot/DP-477

The Application context sidebar in a Document: spaceId and documentId are set

The Application context navigation topic: only projectId is set

Files

  • application-context/
    • manifest.json
    • package.json
    • vite.config.ts
    • index.html
    • public/
      • icon16.png sidebar menu icon
      • icon30.png navigation icon
      • icon32.png sidebar header icon
    • src/
      • main.tsx
      • App.tsx reads the context
      • Table.tsx shows the fields
      • styles.css
    • scripts/
      • package.mjs

manifest.json

Three views that share one rootDirectory, app. Several views may point to the same folder, so the single dist/ build ends up in the ZIP once and serves all three placements.

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.context",
  "title": "Application context",
  "description": "One page placed as a form extension, a sidebar and a navigation topic. It shows the context Polarion hands to each placement.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.0",
  "views": {
    "formExtensions": [
      {
        "identifier": "form",
        "title": "Application context",
        "rootDirectory": "app",
        "document": "index.html"
      }
    ],
    "sidebars": [
      {
        "identifier": "sidebar",
        "title": "Application context",
        "rootDirectory": "app",
        "document": "index.html",
        "menuIcon": "icon16.png",
        "icon": "icon32.png"
      }
    ],
    "navigationTopics": [
      {
        "identifier": "topic",
        "title": "Application context",
        "icon": "icon30.png",
        "rootDirectory": "app",
        "document": "index.html"
      }
    ]
  }
}

src/App.tsx

src/App.tsx
import { useEffect, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import Table from "./Table";

/**
 * Describes where the view runs. The same build is placed three times; `viewId` (from manifest.json)
 * tells which placement this is, and the optional fields say what it is attached to.
 */
function placement(context: PolarionContext): string {
  switch (context.viewId) {
    case "form":
      return `the form of work item ${context.workItemId}`;
    case "sidebar":
      if (!context.documentId) {
        return "a sidebar next to the Work Items table";
      }
      const documentName = context.spaceId ? `${context.spaceId}/${context.documentId}` : `${context.documentId}`;
      return `a sidebar of Document ${documentName}`;
    case "topic":
      return `a navigation topic of project ${context.projectId}`;
    default:
      return "an unknown placement";
  }
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [readAt, setReadAt] = useState<Date | null>(null);
  const [error, setError] = useState<string | null>(null);
  // Used as a refresh trigger for re-fetching the context
  const [readCount, setReadCount] = useState(0);

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

    fetchContext()
      .then((context) => {
        if (cancelled) {
          return;
        }
        setContext(context);
        setReadAt(new Date());
      })
      .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();
    };
  }, [readCount]);

  if (error !== null) {
    return (
      <div className="card error" role="alert">
        <strong>Could not load the Polarion context.</strong>
        <p>{error}</p>
      </div>
    );
  }

  if (context === null) {
    return <p className="muted">Waiting for the Polarion context...</p>;
  }

  return (
    <div className="card">
      <h1>Application context</h1>
      <p>
        View <strong>{context.viewId}</strong> is running in {placement(context)}.
      </p>
      <Table context={context} />
      <p className="footer">
        <button type="button" onClick={() => setReadCount((count) => count + 1)}>
          Read again
        </button>
        <span className="muted">Read at {readAt?.toLocaleTimeString() ?? "-"}. The context does not update by itself.</span>
      </p>
    </div>
  );
}
  • Three states. Waiting for the context, context received, or failed. fetchContext() fails after five seconds when the page is not embedded by Polarion, for example when you open the view URL directly.
  • StrictMode. In development React mounts the component twice. The cleanup sets a cancelled flag before destroy(), so whatever the first mount's fetchContext() returns, including its rejection, is ignored.
  • Optional fields. projectId, workItemId, spaceId and documentId are optional in the type and absent where they do not apply. The table shows not set instead of failing.
  • The token. restToken is shown as present or not set, never as its value. Not set means that REST token authentication is off on the server; see Enable Applications in Polarion.
  • Read again. The button increments readCount, which re-runs the effect: the cleanup destroys the previous SDK instance and the effect fetches a new snapshot. Nothing in the object changes by itself.
  • Rendering in Table.tsx. App.tsx reads the context and handles the states; Table.tsx shows one row per field.

src/Table.tsx

One row per context field. Optional fields that do not apply to the placement show not set; the token shows only whether it is present.

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

type TableProps = {
  context: PolarionContext;
};

/** Shows an optional value, or that it is not set in this placement. */
function optional(value: string | undefined) {
  return value ? value : <span className="muted">not set</span>;
}

export default function Table({ context }: TableProps) {
  return (
    <table>
      <tbody>
        <tr>
          <th>applicationId</th>
          <td>{context.applicationId}</td>
        </tr>
        <tr>
          <th>viewId</th>
          <td>{context.viewId}</td>
        </tr>
        <tr>
          <th>projectId</th>
          <td>{optional(context.projectId)}</td>
        </tr>
        <tr>
          <th>workItemId</th>
          <td>{optional(context.workItemId)}</td>
        </tr>
        <tr>
          <th>spaceId</th>
          <td>{optional(context.spaceId)}</td>
        </tr>
        <tr>
          <th>documentId</th>
          <td>{optional(context.documentId)}</td>
        </tr>
        <tr>
          <th>selectedWorkItemIds</th>
          <td>{context.selectedWorkItemIds.length > 0 ? context.selectedWorkItemIds.join(", ") : <span className="muted">empty</span>}</td>
        </tr>
        <tr>
          <th>restBaseUrl</th>
          <td>{context.restBaseUrl}</td>
        </tr>
        <tr>
          <th>appEndpoint</th>
          <td>{context.appEndpoint}</td>
        </tr>
        <tr>
          <th>restToken</th>
          {/* The token is a credential: show that it is there, never its value. */}
          <td>{context.restToken ? "present (hidden)" : <span className="muted">not set: token authentication is off</span>}</td>
        </tr>
      </tbody>
    </table>
  );
}

Build and deploy

cd examples/application-context
npm install
npm run package          # → com.example.context.zip

Upload the ZIP in Global Administration → Applications. Then place the views:

  • Form extension: add <applicationView id="com.example.context.form" label="Application context" height="460px"/> to a form layout, as in Form extensions.
  • Navigation topic: add <applicationView id="com.example.context.topic"/> to the project's Topics, as in Navigation topics.
  • Sidebar: nothing to configure. Open the Work Items table or a Document, click Show Sidebar and choose Application context.

Things to try

  • Open the sidebar in the table, select rows and click Read again: selectedWorkItemIds stays empty. Follow the selection with events in the Selection sidebar example.
  • Open the same sidebar inside a Document and look at spaceId and documentId.
  • Open https://<host>/polarion/apps/com.example.context/views/form directly. After five seconds the error state appears.