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

Selection sidebar

2612

The Selection inspector sidebar next to the Work Items table with two rows selected

AspectDetails
Folderexamples/selection-sidebar
Identifiercom.example.selectionsidebar
Viewsidebar selection with menuIcon and icon
Placementnone; choose Selection inspector in the Show Sidebar menu
UsesfetchContext(), events.subscribe(EventTypes.SELECTION_CHANGED), REST list with a Lucene id:(…) query

What it does

  1. Fetches the context for the initial selection and subscribes to selection-changed.
  2. Whenever the list of selected ids changes, loads all of them in one REST request.
  3. Shows the count, a compact list with links, type and status chips, and a by status summary.
  4. Reports the time of the last event, which makes it easy to see the event flow while testing.

Files

  • selection-sidebar/
    • manifest.json
    • public/
      • icon16.png menu icon
      • icon32.png header icon
    • src/
      • App.tsx state, events, data loading
      • Components.tsx rendering
      • polarion.ts
      • types.ts
      • main.tsx
      • styles.css
    • …

manifest.json

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.selectionsidebar",
  "title": "Selection inspector",
  "description": "A sidebar that follows the work item selection in the table and shows details of the selected items.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.1.1",
  "views": {
    "sidebars": [
      {
        "identifier": "selection",
        "title": "Selection inspector",
        "rootDirectory": "selection",
        "document": "index.html",
        "menuIcon": "icon16.png",
        "icon": "icon32.png"
      }
    ]
  }
}

Icons live in public/, so Vite copies them to the root of dist/ and they end up next to index.html in the view folder, which is where the manifest paths point.

src/App.tsx

src/App.tsx
import { useEffect, useState } from "react";
import { destroy, events, EventTypes, fetchContext, type PolarionContext, type SelectionChangedData } from "polarion-app-sdk";
import { ErrorMessage, SelectionContent, SelectionSummary } from "./Components";
import { restFetch } from "./polarion";
import type { WorkItemListResponse, WorkItemResource } from "./types";

/** Selection ids may arrive as "WI-1" or "PROJECT/WI-1"; the Lucene query needs the bare id. */
function bareId(id: string): string {
  const separator = id.indexOf("/");
  return separator === -1 ? id : id.slice(separator + 1);
}

function timeNow(): string {
  return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [items, setItems] = useState<WorkItemResource[]>([]);
  const [lastEvent, setLastEvent] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  // Fetch context and subscribe to selection changes when the view mounts.
  useEffect(() => {
    let cancelled = false;

    const loadContext = async () => {
      try {
        const data = await fetchContext();
        if (cancelled) {
          return;
        }
        setContext(data);
        setSelectedIds(data.selectedWorkItemIds ?? []);
        setError(null);
      } 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}`);
      }
    };
    loadContext();

    const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
      // The event contains work item IDs (<project_id>/<workitem_id>) only.
      setSelectedIds(data.selectedWorkItemIds ?? []);
      setLastEvent(timeNow());
    });

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      // Remove the subscription and release the message listener.
      unsubscribe();
      destroy();
    };
  }, []);

  // Whenever the context or selection changes, load the selected work item details.
  // The REST API returns at most 100 items per page, so request IDs in batches
  // of up to 100 and combine the results.
  // Wait 150 ms for rapid selection changes to settle and ignore outdated responses.
  useEffect(() => {
    const projectId = context?.projectId;
    if (!context || !projectId || selectedIds.length === 0) {
      setItems([]);
      return;
    }

    let cancelled = false;

    const loadItems = async () => {
      try {
        const pageSize = 100;
        const requests: Promise<WorkItemListResponse>[] = [];

        for (let i = 0; i < selectedIds.length; i += pageSize) {
          const ids = selectedIds.slice(i, i + pageSize).map(bareId);
          const params = new URLSearchParams({
            "query": `id:(${ids.join(" ")})`,
            "fields[workitems]": "id,title,status,type",
            "page[size]": String(pageSize),
          });
          const path = `/projects/${encodeURIComponent(projectId)}/workitems?${params}`;
          requests.push(restFetch<WorkItemListResponse>(context, path));
        }

        const responses = await Promise.all(requests);
        if (cancelled) {
          return;
        }
        setItems(responses.flatMap((response) => response.data));
        setError(null);
      } catch (error: unknown) {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the selected work items:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the selected work items: ${message}`);
      }
    };
    const timer = setTimeout(loadItems, 150);

    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [context, selectedIds]);

  const byStatus = new Map<string, number>();
  items.forEach((item) => {
    const status = item.attributes.status;
    byStatus.set(status, (byStatus.get(status) ?? 0) + 1);
  });

  return (
    <div>
      <ErrorMessage message={error} />
      <SelectionSummary selectedCount={selectedIds.length} spaceId={context?.spaceId} documentId={context?.documentId} lastEvent={lastEvent} />
      <SelectionContent selectedCount={selectedIds.length} items={items} byStatus={byStatus} />
    </div>
  );
}

Points worth noting:

  • One subscription, created once. The effect with an empty dependency list subscribes on mount and the cleanup unsubscribes and destroys. A second subscription would throw.
  • Late results are ignored. Both effects set a cancelled flag in their cleanup and check it before updating state. That covers the second effect run of React's StrictMode in development and a response that arrives after the selection has changed again.
  • Ids drive everything. The selection is stored as ids; a second effect reacts to changes and loads the data. This separation keeps the event handler trivial.
  • One request per 100 items. The Lucene query id:(TEST-514 TEST-513) returns the selected items with a sparse field set. The REST API serves at most 100 items per page, so larger selections are split into chunks of 100, requested in parallel, and the responses concatenated.
  • Document support. When context.documentId is set, the sidebar is inside a Document and shows the document name; the rest works unchanged.
  • Rendering lives in Components.tsx. App.tsx holds the state and the SDK and REST calls; it passes plain values to the components below.

src/Components.tsx

Small presentational components: the error box, the summary line, the list of work items with a link to each one, and the by status summary. They receive data through props and do not talk to Polarion.

src/Components.tsx
import type { WorkItemResource } from "./types";

type ErrorMessageProps = {
  message: string | null;
};

export function ErrorMessage({ message }: ErrorMessageProps) {
  if (!message) {
    return null;
  }

  return (
    <div className="box error" role="alert">
      {message}
    </div>
  );
}

type SelectionSummaryProps = {
  selectedCount: number;
  documentId?: string;
  spaceId?: string;
  lastEvent: string | null | undefined;
};

export function SelectionSummary({ selectedCount, spaceId, documentId, lastEvent }: SelectionSummaryProps) {
  const headline = selectedCount === 0 ? "Nothing selected" : `${selectedCount} work item(s) selected`;

  return (
    <>
      <p className="headline">{headline}</p>
      {documentId && (
        <p className="muted">
          Document: {spaceId}/{documentId}
        </p>
      )}
      <p className="muted small">Last event received at {lastEvent ?? "—"}</p>
    </>
  );
}

type StatusSummaryProps = {
  byStatus: ReadonlyMap<string, number>;
};

function StatusSummary({ byStatus }: StatusSummaryProps) {
  if (byStatus.size === 0) {
    return null;
  }

  return (
    <div className="box">
      <strong>By status</strong>
      <ul className="summary">
        {[...byStatus.entries()].map(([status, count]) => (
          <li key={status}>
            {status}: {count}
          </li>
        ))}
      </ul>
    </div>
  );
}

type SelectionContentProps = {
  selectedCount: number;
  items: readonly WorkItemResource[];
  byStatus: ReadonlyMap<string, number>;
};

export function SelectionContent({ selectedCount, items, byStatus }: SelectionContentProps) {
  if (selectedCount === 0) {
    return <div className="box hint">Select one or more work items in the table.</div>;
  }

  return (
    <>
      <ul className="items">
        {items.map((item) => (
          <WorkItemRow key={item.id} item={item} />
        ))}
      </ul>
      <StatusSummary byStatus={byStatus} />
    </>
  );
}

type WorkItemRowProps = {
  item: WorkItemResource;
};

function WorkItemRow({ item }: WorkItemRowProps) {
  const separator = item.id.indexOf("/");
  const project = separator > 0 ? item.id.slice(0, separator) : undefined;
  const id = project ? item.id.slice(separator + 1) : item.id;

  return (
    <li>
      {project ? (
        <a href={`${window.location.origin}/polarion/#/project/${encodeURIComponent(project)}/workitem?id=${encodeURIComponent(id)}`} target="_top">
          {id}
        </a>
      ) : (
        <span>{id}</span>
      )}
      <span className="title">{item.attributes.title}</span>
      <span className="chip">{item.attributes.type}</span>
      <span className="chip status">{item.attributes.status}</span>
    </li>
  );
}

src/styles.css

Sidebars are narrow; the styles use a single column, small type and chips.

src/styles.css
:root {
  font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
  font-size: 13px;
  color: #1f2933;
  background: #ffffff;
}

body {
  margin: 0;
  padding: 10px;
}

.headline {
  font-size: 1.05rem;
  font-weight: 600;
  margin: 0 0 4px;
}

.box {
  border: 1px solid #d9e2ec;
  border-radius: 6px;
  padding: 10px 12px;
  margin-top: 10px;
}

.box.hint {
  background: #f5f7fa;
  color: #52606d;
}

.box.error {
  border-color: #e12d39;
  background: #fff5f5;
  color: #a61b25;
}

.items {
  list-style: none;
  padding: 0;
  margin: 8px 0 0;
}

.items li {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  padding: 6px 0;
  border-top: 1px solid #e4e7eb;
}

.items .title {
  flex: 1 1 100%;
}

.chip {
  border: 1px solid #cbd2d9;
  border-radius: 999px;
  padding: 1px 8px;
  font-size: 11px;
  background: #f5f7fa;
}

.chip.status {
  background: #e3f8ff;
  border-color: #9fd8ea;
}

.summary {
  margin: 4px 0 0;
  padding-left: 18px;
}

.muted {
  color: #7b8794;
  margin: 0 0 4px;
}

.small {
  font-size: 11px;
}

Build and deploy

cd examples/selection-sidebar
npm install
npm run package          # → com.example.selectionsidebar.zip

Upload the ZIP. Open a project's Work Items table, click Show Sidebar (top right of the table) and choose Selection inspector. Select rows with click, Shift+click and Ctrl/Cmd+click and watch the sidebar update.

Show Sidebar menu with the Selection inspector entry

Things to try

  • Change the 150 ms debounce and watch how often the REST request runs while you move through the table with the arrow keys (see React to selection changes).
  • Add a bulk action: a button that PATCHes a field on every selected item.
  • Open the sidebar inside a Document and compare the context.