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

React to selection changes

2612

Sidebars live next to a Work Items table or inside a Document, where the user keeps changing what is selected. The SDK delivers those changes as events.

The Selection inspector sidebar following the table selection

The event

import { events, EventTypes, type SelectionChangedData } from 'polarion-app-sdk';

const unsubscribe = events.subscribe<SelectionChangedData>(
  EventTypes.SELECTION_CHANGED,
  (data) => {
    console.log(data.selectedWorkItemIds); // e.g. ["test/TEST-514", "test/TEST-513"]
  },
);
  • EventTypes.SELECTION_CHANGED is the only event type in SDK 0.5.2-preview.
  • The payload is { selectedWorkItemIds: string[] }. An empty array means nothing is selected.
  • The ids carry the project: test/TEST-514, in the Work Items table and in Documents. Strip the prefix where the REST API expects the local id, for example in an id:(…) query; the Selection sidebar example does that in bareId().
  • subscribe() returns a function; call it to stop receiving events.
  • Only one subscription per event type is allowed. A second subscribe() for the same type throws Already subscribed to event. Keep the subscription at the top of your application and distribute the data through your own state.

Initial state plus events

On Polarion 2612 the context of a sidebar has an empty selectedWorkItemIds, even when rows are selected; the selection arrives with the first event after the user changes it. Read the context for the project and the token, start with the context's list (empty in a sidebar) and replace it on every event:

const context = await fetchContext();
let selected = context.selectedWorkItemIds;        // empty in a sidebar
const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
  selected = data.selectedWorkItemIds;             // updates
  render(selected);
});
render(selected);

React pattern

Subscribe in an effect, store the ids in state, and derive everything else from the ids. This is App.tsx of the Selection sidebar example; the components it renders are in Components.tsx on that page:

examples/selection-sidebar/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:

  • The subscription is created in the same effect as fetchContext(), and the cleanup calls unsubscribe() before destroy().
  • Loading the selected work items happens in a second effect that depends on selectedIds. A Lucene query id:(TEST-514 TEST-513) fetches them with a sparse field set; because the REST API serves at most 100 items per page, selections are split into chunks of 100 and requested in parallel.
  • The helper bareId() strips the project prefix for the Lucene query: Polarion 2612 delivers ids with the project (drivepilot/DP-477) in the event, and the code also accepts bare ids (DP-477).

Keeping up with fast selection changes

Users can change the selection several times per second (keyboard navigation, shift-click). If every change triggers a REST call, responses may arrive out of order. Two simple defenses:

// 1. Debounce: wait until the selection has been stable for 150 ms.
useEffect(() => {
  const timer = setTimeout(() => load(selectedIds), 150);
  return () => clearTimeout(timer);
}, [selectedIds]);

// 2. Ignore stale responses.
useEffect(() => {
  let cancelled = false;
  load(selectedIds).then((items) => { if (!cancelled) setItems(items); });
  return () => { cancelled = true; };
}, [selectedIds]);

Selection in Documents

In a Document, the selection is the work item the cursor is in. The event payload has the same shape, usually with one id. context.spaceId and context.documentId tell you which document; the work item itself is fetched through REST as usual.

Form extensions and navigation topics

Form extensions and navigation topics can subscribe, but they have no selection to follow: a form extension knows its work item from context.workItemId, and a navigation topic has no selection at all. Expect the event only in sidebars.

Unsubscribing

Call the returned function when the view no longer needs updates, and destroy() when the view unmounts. destroy() also unsubscribes everything that is still registered, so forgetting the individual call is not harmful, but doing both keeps the intent clear.