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

# React SDK

> The React renderer SDK renders UI configured in the FlowX Designer as a standalone React component.

## React project requirements

Your app MUST use SCSS for styling.

<Check>
  To install the npm libraries provided by FlowX.AI you will need to obtain access to the private FlowX.AI Nexus registry. Please consult with your project DevOps.
</Check>

<Info>
  The library requires React **19**, **npm ≥ 11.0.0** and **node ≥ 24.0.0**.
</Info>

## Installing the library

Use the following command to install the **renderer** library and its required dependencies:

<Check>
  Installing `react` and `react-dom` can be skipped if you already have them installed in your project.
</Check>

```bash theme={"system"}
npm install \
  react@19 \
  react-dom@19 \
  @flowx/core-sdk@<version> \
  @flowx/core-theme@<version> \
  @flowx/react-sdk@<version> \
  @flowx/react-theme@<version> \
  @flowx/react-ui-toolkit@<version> \
  air-datepicker@3 \
  axios \
  ag-grid-react@32
```

<Warning>
  Replace `<version>` with the correct version corresponding to your platform version.

  To find the right version, navigate to: **Release Notes → Choose your platform version → Deployment guidelines → Component versions**.
</Warning>

## Initial setup

Once installed, `FlxProcessRenderer` will be imported from the `@flowx/react-sdk` package.

### Theming

Component theming is done through the `@flowx/react-theme` library. The theme id is a required input for the renderer SDK component and is used to fetch the theme configuration. The id can be obtained from the admin panel in the themes section.

<Frame>
  ![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/2024-04-08%2013.45.10.gif)
</Frame>

### Authorization

<Info>
  It's the responsibility of the client app to implement the authorization flow (using the **OpenID Connect** standard). The renderer SDK will expect the authToken to be passed to the `FlxProcessRenderer` as an input.
</Info>

```tsx theme={"system"}
import { FlxProcessRenderer } from '@flowx/react-sdk';

export function MyFlxContainer() {
    return <FlxProcessRenderer
        apiUrl={'your API url'}
        authToken={...}
        processName={...}
        processStartData={...}
        workspaceId={...}
        processApiPath={...}
        themeId="12345678-1234-1234-1234-123456789012"
        staticAssetsPath={...}
        locale="en-US"
        language="en"
        projectInfo={{
            projectId: ...
        }}
        organizationId={...}
      />
}
```

The `FlxProcessRenderer` component is required in the app module where the process will be rendered. The component accepts a props where you can pass extra config info, register a **custom component** or **custom validators**.

**Custom components** will be referenced by name when creating the template config for a user task.

**Custom validators** will be referenced by name (`customValidator`) in the template config panel in the validators section of each generated form field.

```tsx theme={"system"}
import { FlxProcessRenderer } from '@flowx/react-sdk';

export function MyFlxContainer() {
    return <FlxProcessRenderer
        apiUrl={'your API url'}
        language={...}
        authToken={...}
        processName={...}
        processStartData={...}
        workspaceId={...}
        processApiPath={...}
        themeId="12345678-1234-1234-1234-123456789012"
        components={{ MyCustomComponentIdentifier: MyCustomComponent }}
        validators={{ customValidator: (...params: string[]) => (v: string) => v === '4.5'}}
        staticAssetsPath={...}
        locale="en-US"
        language="en"
        projectInfo={{
            projectId: ...
        }}
        organizationId={...}
      />
}

```

The entry point of the library is the `<FlxProcessRenderer />` component. A list of accepted inputs is found below:

```tsx theme={"system"}
<FlxProcessRenderer
    apiUrl={apiUrl}
    language={language}
    authToken={authToken}
    processName={processName}
    processStartData={processStartData}
    workspaceId={workspaceId}
    processApiPath={apiPath}
    themeId={themeId}
    components={customComponents}
    validators={validators}
    staticAssetsPath={assetsPath}
    locale={locale}
    language={language}
    projectInfo={projectInfo}
    organizationId={organizationId}
    />
```

**Parameters**:

| Name                   | Description                                                                                                                                                                                                                            | Type                                    | Mandatory | Default value | Example                                        |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------- | ------------- | ---------------------------------------------- |
| `apiUrl`               | Your base url                                                                                                                                                                                                                          | `string`                                | true      | -             | `https://yourDomain.dev`                       |
| `processApiPath`       | Process subpath                                                                                                                                                                                                                        | `string`                                | true      | -             | `onboarding`                                   |
| `authToken`            | Authorization token                                                                                                                                                                                                                    | `string`                                | true      | -             | `'eyJhbGciOiJSUzI1NiIsIn....'`                 |
| `themeId`              | Theme id used to style the process. Can be obtained from the themes section in the admin                                                                                                                                               | `string`                                | true      | -             | `'123-456-789'`                                |
| `processName`          | Identifies a process                                                                                                                                                                                                                   | `string`                                | true      | -             | `client_identification`                        |
| `processStartData`     | Data required to start the process                                                                                                                                                                                                     | `json`                                  | true      | -             | `{ "firstName": "John", "lastName": "Smith"}`  |
| `workspaceId`          | Workspace id                                                                                                                                                                                                                           | `string`                                | true      | -             | `'8f52744-8403-4e8d....'`                      |
| `projectInfo`          | Defines which FlowX Project will be run inside the process renderer. Shape: `{ projectId: string, appVersionId?: string }`                                                                                                             | `object`                                | true      | -             | `{ "projectId": "111111-222222-333333-44444"}` |
| `organizationId`       | FlowX-issued organization UUID. On self-hosted deployments it matches the `ORGANIZATION_ID` configured during the backend upgrade — see [License and organization configuration](/5.9/migrating-from-5.1-lts/organization-deployment). | `string`                                | true      | -             | `'10000001-0001-0001-8001-100000000001'`       |
| `language`             | Language used to localize the enumerations inside the app.                                                                                                                                                                             | `string`                                | false     | `ro`          | -                                              |
| `locale`               | Locale used to apply date, currency and number formatting to data model values                                                                                                                                                         | `string`                                | false     | `ro-RO`       | `"en-US"`                                      |
| `isDraft`              | When true, starts the process in draft state                                                                                                                                                                                           | `boolean`                               | false     | `false`       | -                                              |
| `legacyHttpVersion`    | Use legacy HTTP API version                                                                                                                                                                                                            | `boolean`                               | false     | `false`       | -                                              |
| `buildId`              | Pinned build identifier                                                                                                                                                                                                                | `string`                                | false     | -             | -                                              |
| `cache`                | Enable caching                                                                                                                                                                                                                         | `boolean`                               | false     | -             | -                                              |
| `requestInterceptors`  | Axios request interceptors applied to all SDK HTTP calls                                                                                                                                                                               | `HttpRequestInterceptor[]`              | false     | -             | -                                              |
| `responseInterceptors` | Axios response interceptors applied to all SDK HTTP calls                                                                                                                                                                              | `HttpResponseInterceptor[]`             | false     | -             | -                                              |
| `onProcessEnded`       | Callback fired when the main process reaches a terminal state                                                                                                                                                                          | `() => void`                            | false     | -             | -                                              |
| `onProcessStarted`     | Callback fired when the main process instance is started. Receives the new `processInstanceUuid`.                                                                                                                                      | `(processInstanceUuid: string) => void` | false     | -             | -                                              |
| `customLoader`         | Custom loader components for different loading scenarios.                                                                                                                                                                              | `object`                                | false     | -             | `{ startProcess: <LoaderComponent /> }`        |

#### `projectInfo` shape

```typescript theme={"system"}
projectInfo: {
  projectId: string                    // required
  appVersionId?: string                // pin a specific app version
}
```

#### Interceptor types

```typescript theme={"system"}
type HttpRequestInterceptor = {
  onFulfilled?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig>
  onRejected?: (error: any) => any
}

type HttpResponseInterceptor = {
  onFulfilled?: (response: AxiosResponse) => AxiosResponse | Promise<AxiosResponse>
  onRejected?: (error: any) => any
}
```

### Analytics

<Info>
  The SDK provides a mechanism for collecting analytics events through a unified `CustomEvent` system. These events can be used to track screens and action events.
</Info>

To use analytics features, make sure you've imported the necessary SDK module:

```ts theme={"system"}
import {
   ANALYTICS_EVENTS,
   AnalyticsData,
   pushAnalyticsData,
} from '@flowx/core-sdk';
```

#### Emitting analytics events

Analytics events are dispatched using the `pushAnalyticsData(payload: AnalyticsData)` method. The SDK defines two event types:

```ts theme={"system"}
enum ANALYTICS_EVENTS {
  SCREEN = 'SCREEN',
  ACTION = 'ACTION',
}
```

Each analytics event should be an object of type AnalyticsData:

```ts theme={"system"}
type AnalyticsData = {
  type: ANALYTICS_EVENTS;
  value: string;
  screen?: string;
  component?: string;
  label?: string;
  customPayload?: object;
}
```

<Info>
  The value property represents the identifier set in the process definition.

  For ACTION type events there are some additional properties provided:

  * component - The type of component triggering the action
  * label - The label of the component
  * screen - The identifier of the screen containing the component, if set
</Info>

#### Listening for analytics events

You can subscribe to analytics events using the standard CustomEvent API:

```ts theme={"system"}
const analyticsListener = (event: CustomEvent<AnalyticsData>) => {
  console.log('Received flowx:analytics event:', event.detail);
}

useEffect(() => {
  document.addEventListener('flowx:analytics', analyticsListener)

  return () => {
    document.removeEventListener('flowx:analytics', analyticsListener)
  }
}, [])
```

<Check> Ensure that you remove the event listener on component destruction to avoid memory leaks. </Check>

#### Custom payload

This allows you to capture and send custom data alongside standard analytics events.

When analytics custom payload is configured in FlowX Designer, the renderer automatically processes variable substitution and includes the resulting data in analytics events.

<Steps>
  <Step title="Receive custom payload configuration">
    The renderer receives the analytics configuration as a JSON string with variable placeholders:

    ```json theme={"system"}
    "analyticsCustomPayload": "{\n \"name\": ${app.input}\n}"
    ```
  </Step>

  <Step title="Process variable substitution">
    The SDK replaces variables with actual values from the process data store:

    <CodeGroup>
      ```json Template theme={"system"}
      {
          "name": "${app.input}",
          "client": "${app.client}",
          "amount": "${app.amount}"
      }
      ```

      ```json Result theme={"system"}
      {
          "name": "john",
          "client": { "id": "123", "name": "John Doe" },
          "amount": 1500
      }
      ```
    </CodeGroup>
  </Step>

  <Step title="Add to analytics event">
    The processed payload is included in the analytics event under the `customPayload` property:

    ```typescript theme={"system"}
    // Analytics event structure with custom payload
    {
        type: 'ACTION', // or 'SCREEN'
        info: {
            value: 'Save personal data',
            screen: 'Personal Data',
            component: 'BUTTON',
            label: 'Save',
            customPayload: {
                name: "john",
                client: { id: "123", name: "John Doe" },
                amount: 1500
            }
        }
    }
    ```
  </Step>
</Steps>

## Starting a process

### Prerequisites

* **Process Name**: You need to know the name of the process you want to start. This name is used to identify the process in the system.

* **FlowX Project UUID**: You need the UUID of the FlowX Project that contains the process you want to start. This UUID is used to identify the project in the system.

* **Locale**: You can specify the locale of the process to apply date, currency, and number formatting to data model values.

* **Language**: You can specify the language used to localize the enumerations inside the app.

### Getting the project UUID

The project UUID can be obtained from the FlowX Dashboard. Navigate to the Projects section and select the project you want to start a process in. The UUID can be copied from the project actions popover.

![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/4.5/react/copy_uuid_application.png)

### Getting the process identifier

Open the FlowX Designer, navigate to the process, and copy the process name from the breadcrumbs. Use this value as `processName`.

### Initializing the process renderer

To start a process, you need to initialize the `FlxProcessRenderer` component in your app. The component accepts various props that define the process to start, the theme to use, and other configuration options.

```tsx theme={"system"}
import { FlxProcessRenderer } from '@flowx/react-sdk';

export function MyFlxContainer() {
    return <FlxProcessRenderer
        {...props}
        locale="en-US"
        language="en"
        processName={processName}
        projectInfo={{ projectId }}
      />
}
```

## Custom components

Custom components receive an `input` prop of type `FlxCustomComponentData` and are registered through the `components` parameter of `<FlxProcessRenderer />`.

<Warning>
  The object keys passed in the `components` prop **MUST** match the custom component names defined in the FlowX process.
</Warning>

<Check>
  Process data mapped through `inputKeys` is available on `input.data`. The value is whatever lives at the configured path in the process model - it can be an object or a primitive.
</Check>

<Check>
  Process actions are available on `input.actionsFn`, keyed by action name.
</Check>

```typescript theme={"system"}
interface FlxCustomComponentData {
  data: any                                                          // value at the configured inputKey path - object or primitive
  actions: ProcessAction[]                                           // metadata for each bound action
  actionsFn: Record<string, (params?: any) => Observable<any>>      // call to trigger a process action; returns an Observable
}
```

Each custom component receives four props:

| Prop                 | Type                                              | Description                                                                                                                       |
| -------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `input`              | `FlxCustomComponentData`                          | Process data and bound actions                                                                                                    |
| `registerValidation` | `(fn: () => boolean \| Promise<boolean>) => void` | Register a validation function. The SDK calls it when the user submits the process step. Return `true` to pass, `false` to block. |
| `saveData`           | `(fn: () => Record<string, unknown>) => void`     | Register a data extractor. The SDK calls it on submit to collect values to write back to the process model.                       |
| `isSubmitted`        | `boolean`                                         | `true` after the first submit attempt - use to show validation errors.                                                            |

```tsx theme={"system"}
export const MyCustomComponent = ({
  input,
  registerValidation,
  saveData,
  isSubmitted,
}: {
  input: FlxCustomComponentData
  registerValidation: (fn: () => boolean | Promise<boolean>) => void
  saveData: (fn: () => Record<string, unknown>) => void
  isSubmitted: boolean
}) => {
  const { data, actionsFn } = input
  // data - the value mapped via inputKeys; e.g. { firstName: 'John' } or a primitive
  // actionsFn['save_order']() - triggers the 'save_order' process action
}
```

To add a custom component in the template config tree, we need to know its unique identifier and the data it should receive from the process model.

![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/building-blocks/ui-designer/ui_designer_custom.png)

The properties that can be configured are as follows:

* **Identifier** - This enables the custom component to be displayed within the component hierarchy and determines the actions available for the component.
* **Input keys** - These are used to specify the pathway to the process data that components will utilize to receive their information.
* [**Event Handlers**](../docs/building-blocks/ui-designer/event-handlers) - actions defined here will be made available to the custom component

<Frame>
  ![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/building-blocks/ui-designer/ui_designer_custom_settings.png#center)
</Frame>

### Prerequisites (before creation)

* **React Knowledge**: You should have a good understanding of React, as custom components are created and imported using React.

* **Development Environment**: Set up a development environment for React development, including Node.js and npm (Node Package Manager).

* **Component Identifier**: You need a unique identifier for your custom component. This identifier is used for referencing the component within the app.

### Creating a custom component

To create a Custom Component in React, follow these steps:

1. Create a new React component.
2. Implement the necessary HTML structure, TypeScript logic, and SCSS styling to define the appearance and behavior of your custom component.

### Importing the component

After creating the Custom Component, you need to import it into your app.

In your `<FlxProcessRenderer />` component, add the following property:

```tsx theme={"system"}
<FlxProcessRenderer
  {...otherProps}
  components={{ MyCustomComponentIdentifier: MyCustomComponent }}
/>
```

### Using the custom component

Once your Custom Component is declared, you can use it for configuration within your app.

![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/release34/loader_component.gif)

### Data input and actions

The Custom Component accepts input data from processes and can also include actions extracted from a process. These inputs and actions allow you to configure and interact with the component dynamically.

![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/release34/cst_input_data.png)

### Extracting data from processes

There are multiple ways to extract data from processes to use within your Custom Component. You can utilize the data provided by the process or map actions from the BPMN process to React actions within your component.

<Frame>
  ![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/release34/cst_loader_input.png)
</Frame>

<Warning>
  Make sure that the React actions that you declare match the names of the process actions.
</Warning>

### Styling with CSS

To apply CSS classes to UI elements within your Custom Component, you first need to identify the UI element identifiers within your component's HTML structure. Once identified, you can apply defined CSS classes to style these elements as desired.

Example:

<Frame>
  ![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/release34/Screenshot%202023-10-10%20at%2012.29.51.png)
</Frame>

### Additional considerations

* **Naming Conventions**: Be consistent with naming conventions for components, identifiers, and actions. Ensure that React action names match the names of process actions.

* **Component Hierarchy**: Understand how the component fits into the overall component hierarchy of your app. This will help determine where the component is displayed and what actions are available for it.

* **Documentation and Testing**: Document your custom component thoroughly for future reference. Additionally, testing is crucial to ensure that the component behaves as expected in various scenarios.

* **Security**: If your custom component interacts with sensitive data or performs critical actions, consider security measures to protect the app from potential vulnerabilities.

* **Integration with FlowX Designer**: Ensure that your custom component integrates with FlowX Designer, as it is part of the app's process modeling capabilities.

## Custom validators

You may also define custom validators in your FlowX processes and pass their implementation through the `validators` prop of the `<FlxProcessRenderer />` component.

The validators are processed through a custom validation layer backed by [Valtio](https://github.com/pmndrs/valtio) state management, taking into account how the error messages are defined in your process.

A validator must have the following type:

```typescript theme={"system"}
const customValidator = (...params: string[]) => (v: any) => boolean | Promise<boolean>
```

<Warning>
  The object keys passed in the `validators` prop **MUST** match the custom validator names defined in the FlowX process.
</Warning>

## Process end handling

The SDK provides a mechanism for container applications to handle process completion events through the `onProcessEnded` callback. This allows you to implement custom logic when a main process reaches an end state, such as redirecting users or triggering cleanup operations.

The `onProcessEnded` callback is triggered when the **main process** (not subprocesses) reaches any terminal state:

* `FINISHED` - Process completed successfully
* `FAILED` - Process encountered an error
* `ABORTED` - Process was manually terminated
* Other terminal states

<Info>
  Only the main process triggers this callback. Subprocess completions do not trigger the callback to avoid unnecessary interruptions during complex process flows.
</Info>

### Implementation

To handle process end events, pass a function to the `onProcessEnded` prop of the `<FlxProcessRenderer />` component:

```tsx theme={"system"}
import { FlxProcessRenderer } from '@flowx/react-sdk';

export function MyFlxContainer() {
  const handleProcessEnd = () => {
    // Your custom logic here
    console.log('Process has ended');
    
    // Example: Redirect to home page
    window.location.href = '/dashboard';
  };

  return (
    <FlxProcessRenderer
      {...otherProps}
      onProcessEnded={handleProcessEnd}
    />
  );
}
```

## Custom loader

The SDK provides a mechanism for container applications to customize the loader UI displayed during process execution. This allows you to replace the default FlowX loader with your own custom implementation based on different loading scenarios.

### Configuration

To configure custom loaders, pass them through the `customLoader` prop of the `<FlxProcessRenderer />` component:

```tsx theme={"system"}
import { FlxProcessRenderer } from '@flowx/react-sdk';

// Define your custom loader components
const StartProcessLoader = () => (
  <div className="custom-start-loader">
    <div className="spinner" />
    <p>Starting process...</p>
  </div>
);

const SpecificActionLoader = () => (
  <div className="custom-specific-action-loader">
    <div className="spinner" />
    <p>Executing specific action...</p>
  </div>
);

// Register the custom loaders in your component
export function MyFlxContainer() {
  return (
    <FlxProcessRenderer
      {...otherProps}
      customLoader={{
        startProcess: <StartProcessLoader />,
        // reloadProcess: <ReloadProcessLoader />,
        // defaultAction: <DefaultActionLoader />,
        // defaultUpload: <DefaultUploadLoader />,
        actions: {
          action1: <SpecificActionLoader />,
          // action2: <SaveDataLoader />,
        },
      }}
    />
  );
}
```

### API specification

The `customLoader` prop accepts an object of type `CustomLoader`:

```typescript theme={"system"}
type CustomLoader = {
  actions?: Record<string, ReactNode>
  startProcess?: ReactNode
  reloadProcess?: ReactNode
  defaultAction?: ReactNode
  defaultUpload?: ReactNode
}
```

#### Loader types

* **`startProcess`** - Displayed when starting or resuming a process
* **`reloadProcess`** - Displayed when reloading a process
* **`defaultAction`** - Default loader for actions when `loaderType` is `'action'`. Used when no specific action loader is found in the `actions` record
* **`defaultUpload`** - Default loader for file uploads when `loaderType` is `'upload'`
* **`actions`** - Record mapping specific action identifiers to custom loaders. When an action is executed, the SDK will first check for a matching entry in this record before falling back to `defaultAction`

### Fallback behavior

<Info>
  If no custom loader is provided for a specific type, the SDK will automatically fall back to the built-in FlowX loader. This ensures your app continues to function even with partial custom loader configuration.
</Info>

<Tip>
  You can use any React components, including those with animations, styled components, or media assets, to create rich loading experiences that match your app's design system.
</Tip>

## Chat component

To use the `FlxChatRenderer` component, import the module in your project:

```tsx theme={"system"}
import { FlxChatRenderer } from '@flowx/react-sdk';
```

#### Usage

Include the component in your template:

```tsx theme={"system"}
  <FlxChatRenderer
    apiUrl={baseUrl}
    authToken={accessToken}
    staticAssetsPath={staticAssetsPath}
    language={language}
    locale={locale}
    themeId={themeId}
    projectId={projectId}
    workspaceId={workspaceId}
    source={source}
    chatConfig={chatConfig}
    cache={cache}
  />
```

Parameters:

| Name                | Description                                   | Type      | Mandatory | Example                           |
| ------------------- | --------------------------------------------- | --------- | --------- | --------------------------------- |
| `apiUrl`            | Your base API URL                             | `string`  | ✅         | `https://yourDomain.dev`          |
| `authToken`         | Authorization token                           | `string`  | ✅         | (retrieved from auth provider)    |
| `staticAssetsPath`  | Path for static resources                     | `string`  | ❌         | (set via environment)             |
| `language`          | Language used to localize the chat interface  | `string`  | ❌         | `en`                              |
| `locale`            | Locale setting for date and number formatting | `string`  | ❌         | `en-US`                           |
| `themeId`           | Theme identifier for styling                  | `string`  | ❌         | (retrieved dynamically)           |
| `projectId`         | The FlowX project ID                          | `string`  | ✅         | (retrieved dynamically)           |
| `workspaceId`       | The workspace ID                              | `string`  | ✅         | (retrieved dynamically)           |
| `source`            | Source object with type and id                | `object`  | ✅         | `{ type: 'WORKFLOW', id: '...' }` |
| `chatConfig`        | Chat configuration object                     | `object`  | ❌         | `{ welcomeMessage: '...', ... }`  |
| `cache`             | Enable caching for chat responses             | `boolean` | ❌         | `true`                            |
| `buildId`           | Pinned build identifier                       | `string`  | ❌         | (retrieved dynamically)           |
| `legacyHttpVersion` | Use legacy HTTP API version                   | `boolean` | ❌         | -                                 |

#### chatConfig parameters

The `chatConfig` object accepts the following properties:

| Name               | Description                                  | Type      | Default value            |
| ------------------ | -------------------------------------------- | --------- | ------------------------ |
| `welcomeMessage`   | Message displayed when chat is first opened  | `string`  | `'Welcome to the chat!'` |
| `thinkingMessage`  | Message displayed while waiting for response | `string`  | `'Thinking...'`          |
| `title`            | Chat window title                            | `string`  | `'Chat'`                 |
| `subtitle`         | Chat window subtitle                         | `string`  | `'Chat subtitle'`        |
| `showChatIcon`     | Whether to display the chat icon             | `boolean` | `true`                   |
| `showSeparator`    | Whether to show separator between messages   | `boolean` | `true`                   |
| `newChatLabel`     | Label for the new chat button                | `string`  | `'New chat'`             |
| `inputPlaceholder` | Placeholder text for the message input field | `string`  | `'Enter your message'`   |
| `maxInputRows`     | Maximum number of rows for the input field   | `number`  | `10`                     |
| `historyTitle`     | Title displayed on the chat history panel    | `string`  | -                        |
| `errorMessage`     | Message shown when an error occurs           | `string`  | -                        |
| `canRegenerate`    | Show a regenerate button on responses        | `boolean` | -                        |
| `regenerateLabel`  | Label for the regenerate button              | `string`  | -                        |

## Task management component

To use the `FlxTaskManager` component, import the module in your project:

```tsx theme={"system"}
import { FlxTaskManager } from '@flowx/react-sdk';
```

#### Usage

Include the component in your template:

```tsx theme={"system"}
  <FlxTaskManager
    apiUrl={baseUrl}
    authToken={authToken}
    appInfo={appInfo}
    viewId={viewId}
    workspaceId={workspaceId}
    themeId={themeId}
    language={language}
    locale={locale}
    staticAssetsPath={staticAssetsPath}
    buildId={buildId}
  />
```

Parameters:

| Name                | Description                                                               | Type                       | Mandatory | Example                        |
| ------------------- | ------------------------------------------------------------------------- | -------------------------- | --------- | ------------------------------ |
| `apiUrl`            | Endpoint where the tasks are available                                    | `string`                   | ✅         | `https://yourDomain.dev/tasks` |
| `authToken`         | Authorization token                                                       | `string`                   | ✅         | (retrieved from local storage) |
| `appInfo`           | App information object. Shape: `{ appId: string, appVersionId?: string }` | `object`                   | ✅         | `{ appId: "app-123" }`         |
| `viewId`            | The view configuration identifier                                         | `string`                   | ✅         | (retrieved dynamically)        |
| `workspaceId`       | The workspace ID                                                          | `string`                   | ✅         | (retrieved dynamically)        |
| `themeId`           | The theme identifier                                                      | `string`                   | ❌         | (retrieved dynamically)        |
| `language`          | The selected language                                                     | `string`                   | ❌         | (retrieved dynamically)        |
| `locale`            | The localization setting                                                  | `string`                   | ❌         | (retrieved dynamically)        |
| `buildId`           | The current build identifier                                              | `string`                   | ❌         | (retrieved dynamically)        |
| `staticAssetsPath`  | Path for static resources                                                 | `string`                   | ❌         | (set via environment)          |
| `stages`            | Pre-loaded enumeration stages                                             | `TaskManagerEnumeration[]` | ❌         | -                              |
| `legacyHttpVersion` | Use legacy HTTP API version                                               | `boolean`                  | ❌         | -                              |

## Task management public API

The React SDK provides a comprehensive public API for building custom task management interfaces.
This API allows you to fetch tasks, manage comments, handle task actions, and interact with task data programmatically.

### Importing the API

To use the task management public API, import the functions and types from `@flowx/react-sdk`:

```typescript theme={"system"}
import {
  // Functions
  getTaskManagerResources,
  fetchView,
  fetchViewTasks,
  fetchTaskComments,
  fetchTaskHistory,
  fetchTaskAssignees,
  updateTaskAction,
  saveComment,
  removeComment,
  updateTaskPriority,
  updateBulkTaskAction,
  fetchBulkAssignees,
  getEnumerationOptions,
  initSseConnection,
  
  // Types and Interfaces
  TaskManagerSetupOptions,
  View,
  ViewTask,
  ViewColumn,
  ViewFilter,
  TaskActions,
  TaskComment,
  TaskHistory,
  Assignees,
  TaskManagerEnumeration,
  SseConnection,
  SseEventData,
  SseMessageType,
  SseTaskMessageType,
  SseTaskEventType,
} from '@flowx/react-sdk'
```

### Initialization

Before using the task management API, you need to initialize the task manager resources. This fetches the view configuration, enumerations, and filter operators.

```typescript theme={"system"}
const { view, enumerations, filterOperators } = await getTaskManagerResources({
  apiUrl: 'https://yourDomain.dev/tasks',
  authToken: 'your-auth-token',
  appInfo: { appId: 'app-123' },
  viewId: 'view-456',
  workspaceId: 'workspace-789',
  themeId: 'theme-012', // Optional
  language: 'en', // Optional
  locale: 'en-US', // Optional
  buildId: 'build-345', // Optional
  staticAssetsPath: '/static', // Optional
})
```

**Parameters:**

| Name               | Description                             | Type                | Mandatory | Example                        |
| ------------------ | --------------------------------------- | ------------------- | --------- | ------------------------------ |
| `apiUrl`           | Endpoint where the tasks are available  | `string`            | ✅         | `https://yourDomain.dev/tasks` |
| `authToken`        | Authorization token                     | `string`            | ✅         | (retrieved from local storage) |
| `appInfo`          | App information object containing appId | `{ appId: string }` | ✅         | `{ appId: "app-123" }`         |
| `viewId`           | The view configuration identifier       | `string`            | ✅         | (retrieved dynamically)        |
| `workspaceId`      | The workspace ID                        | `string`            | ✅         | (retrieved dynamically)        |
| `themeId`          | The theme identifier                    | `string`            | ❌         | (retrieved dynamically)        |
| `language`         | The selected language                   | `string`            | ❌         | `"en"`                         |
| `locale`           | The localization setting                | `string`            | ❌         | `"en-US"`                      |
| `buildId`          | The current build identifier            | `string`            | ❌         | (retrieved dynamically)        |
| `staticAssetsPath` | Path for static resources               | `string`            | ❌         | (set via environment)          |

**Returns:** Promise resolving to an object containing:

* `view`: The view configuration object
* `enumerations`: Available enumeration options for filters
* `filterOperators`: Available filter operators for each column

### Fetching tasks

#### `fetchViewTasks`

Fetches tasks for a specific view with support for sorting, filtering, pagination, and search.

```typescript theme={"system"}
const response = await fetchViewTasks(
  sort,           // Array of sort configurations
  filters,        // Array of filter configurations
  searchTerm,     // Search string
  view,           // View object from getTaskManagerResources
  pagination,     // Pagination object { page: number, size: number }
  enumerations    // Enumerations from getTaskManagerResources
)
```

**Parameters:**

| Name           | Description                      | Type                             | Mandatory | Example                                       |
| -------------- | -------------------------------- | -------------------------------- | --------- | --------------------------------------------- |
| `sort`         | Array of sort configurations     | `ViewTasksSort[]`                | ✅         | `[{ keyName: "priority", direction: "ASC" }]` |
| `filters`      | Array of filter configurations   | `ViewTasksFilter[]`              | ✅         | See filter examples below                     |
| `searchTerm`   | Search string for task search    | `string`                         | ✅         | `"urgent"`                                    |
| `view`         | View object from initialization  | `View`                           | ✅         | (from `getTaskManagerResources`)              |
| `pagination`   | Pagination configuration         | `{ page: number, size: number }` | ✅         | `{ page: 0, size: 10 }`                       |
| `enumerations` | Enumerations from initialization | `TaskManagerEnumerations`        | ✅         | (from `getTaskManagerResources`)              |

**Returns:** Promise resolving to a paginated response containing:

* `content`: Array of `ViewTask` objects
* `totalElements`: Total number of tasks
* `totalPages`: Total number of pages
* Other pagination metadata

**Example:**

```typescript theme={"system"}
const sort = [{ keyName: 'priority', direction: 'ASC' }]
const filters = [
  {
    keyName: 'status',
    operator: 'EQUALS',
    value: ['PENDING'],
    keyType: 'enumType',
    columnType: 'status',
  },
]
const pagination = { page: 0, size: 10 }

const response = await fetchViewTasks(
  sort,
  filters,
  '', // searchTerm
  view,
  pagination,
  enumerations
)

const tasks = response.content // Array of ViewTask objects
```

#### `fetchView`

Fetches a specific view configuration by ID.

```typescript theme={"system"}
const view = await fetchView(viewId)
```

### Task details

#### `fetchTaskComments`

Fetches all comments for a specific task.

```typescript theme={"system"}
const comments = await fetchTaskComments(taskId)
```

**Parameters:**

| Name     | Description        | Type     | Mandatory | Example      |
| -------- | ------------------ | -------- | --------- | ------------ |
| `taskId` | The unique task ID | `string` | ✅         | `"task-123"` |

**Returns:** Promise resolving to an array of `TaskComment` objects.

**Example:**

```typescript theme={"system"}
const comments = await fetchTaskComments(selectedTask.id)
// Returns: [
//   {
//     commentId: "comment-1",
//     message: "This task needs attention",
//     author: { username: "john.doe", ... },
//     createdAt: "2024-01-15T10:30:00Z"
//   }
// ]
```

#### `fetchTaskHistory`

Fetches the history/audit trail for a specific task.

```typescript theme={"system"}
const history = await fetchTaskHistory(taskId)
```

**Parameters:**

| Name     | Description        | Type     | Mandatory | Example      |
| -------- | ------------------ | -------- | --------- | ------------ |
| `taskId` | The unique task ID | `string` | ✅         | `"task-123"` |

**Returns:** Promise resolving to an array of `TaskHistory` objects.

**Example:**

```typescript theme={"system"}
const history = await fetchTaskHistory(selectedTask.id)
// Returns: [
//   {
//     historyId: "history-1",
//     events: [
//       {
//         type: "STATUS_CHANGED",
//         description: "Status changed from PENDING to IN_PROGRESS"
//       }
//     ]
//   }
// ]
```

#### `fetchTaskAssignees`

Fetches available assignees for a task, with optional search filtering.

```typescript theme={"system"}
const assignees = await fetchTaskAssignees(
  taskId,
  tokenUuid,
  options
)
```

**Parameters:**

| Name        | Description                         | Type     | Mandatory | Example               |
| ----------- | ----------------------------------- | -------- | --------- | --------------------- |
| `taskId`    | The unique task ID                  | `string` | ✅         | `"task-123"`          |
| `tokenUuid` | The token UUID associated with task | `string` | ✅         | `"token-uuid-456"`    |
| `options`   | Search options                      | `object` | ❌         | `{ keyword: "john" }` |

**Returns:** Promise resolving to an array of `Assignees` objects.

**Example:**

```typescript theme={"system"}
const users = await fetchTaskAssignees(
  selectedTask.id,
  selectedTask.tokenUuid,
  { keyword: 'john' }
)
// Returns: [
//   {
//     username: "john.doe",
//     firstName: "John",
//     lastName: "Doe",
//     email: "john.doe@example.com"
//   }
// ]
```

#### `fetchBulkAssignees`

Fetches available assignees for multiple tasks in bulk.

```typescript theme={"system"}
const assignees = await fetchBulkAssignees(
  taskIds,
  options
)
```

**Parameters:**

| Name      | Description       | Type       | Mandatory | Example                |
| --------- | ----------------- | ---------- | --------- | ---------------------- |
| `taskIds` | Array of task IDs | `string[]` | ✅         | `["task-1", "task-2"]` |
| `options` | Search options    | `object`   | ❌         | `{ keyword: "john" }`  |

**Returns:** Promise resolving to an array of `Assignees` objects.

### Task actions

#### `updateTaskAction`

Executes an action on a specific task (e.g., assign, complete, cancel).

```typescript theme={"system"}
await updateTaskAction(
  action,
  taskId,
  tokenUuid,
  username
)
```

**Parameters:**

| Name        | Description                           | Type                 | Mandatory | Example              |
| ----------- | ------------------------------------- | -------------------- | --------- | -------------------- |
| `action`    | The action to execute                 | `ExecuteTaskActions` | ✅         | `TaskActions.ASSIGN` |
| `taskId`    | The unique task ID                    | `string`             | ✅         | `"task-123"`         |
| `tokenUuid` | The token UUID associated with task   | `string`             | ✅         | `"token-uuid-456"`   |
| `username`  | Username for assign action (optional) | `string`             | ❌         | `"john.doe"`         |

**Available Actions:**

* `TaskActions.ASSIGN` - Assign task to a user
* `TaskActions.COMPLETE` - Mark task as complete
* `TaskActions.CANCEL` - Cancel the task
* `TaskActions.CHANGE_PRIORITY` - Change task priority
* `TaskActions.VIEW` - View task details

**Example:**

```typescript theme={"system"}
// Assign task to a user
await updateTaskAction(
  TaskActions.ASSIGN,
  selectedTask.id,
  selectedTask.tokenUuid,
  'john.doe'
)

// Complete a task
await updateTaskAction(
  TaskActions.COMPLETE,
  selectedTask.id,
  selectedTask.tokenUuid
)
```

#### `updateBulkTaskAction`

Applies an action to multiple tasks at once.

```typescript theme={"system"}
await updateBulkTaskAction(
  action,
  taskIds,
  options
)
```

**Parameters:**

| Name      | Description           | Type                 | Mandatory | Example                    |
| --------- | --------------------- | -------------------- | --------- | -------------------------- |
| `action`  | The action to execute | `ExecuteTaskActions` | ✅         | `TaskActions.COMPLETE`     |
| `taskIds` | Array of task IDs     | `string[]`           | ✅         | `["task-1", "task-2"]`     |
| `options` | Additional options    | `object`             | ❌         | `{ username: "john.doe" }` |

**Example:**

```typescript theme={"system"}
await updateBulkTaskAction(
  TaskActions.COMPLETE,
  ['task-1', 'task-2', 'task-3']
)
```

#### `updateTaskPriority`

Updates the priority of a specific task.

```typescript theme={"system"}
await updateTaskPriority(taskId, priority)
```

**Parameters:**

| Name       | Description        | Type     | Mandatory | Example      |
| ---------- | ------------------ | -------- | --------- | ------------ |
| `taskId`   | The unique task ID | `string` | ✅         | `"task-123"` |
| `priority` | New priority value | `number` | ✅         | `5`          |

**Example:**

```typescript theme={"system"}
await updateTaskPriority(selectedTask.id, 10)
```

### Comments management

#### `saveComment`

Adds a new comment to a task.

```typescript theme={"system"}
await saveComment(taskId, commentData)
```

**Parameters:**

| Name          | Description         | Type     | Mandatory | Example                           |
| ------------- | ------------------- | -------- | --------- | --------------------------------- |
| `taskId`      | The unique task ID  | `string` | ✅         | `"task-123"`                      |
| `commentData` | Comment data object | `object` | ✅         | `{ message: "New comment text" }` |

**Example:**

```typescript theme={"system"}
await saveComment(selectedTask.id, {
  message: 'This task requires immediate attention'
})

// Refresh comments after saving
const updatedComments = await fetchTaskComments(selectedTask.id)
```

#### `removeComment`

Removes a comment from a task.

```typescript theme={"system"}
await removeComment(taskId, commentId)
```

**Parameters:**

| Name        | Description           | Type     | Mandatory | Example         |
| ----------- | --------------------- | -------- | --------- | --------------- |
| `taskId`    | The unique task ID    | `string` | ✅         | `"task-123"`    |
| `commentId` | The unique comment ID | `string` | ✅         | `"comment-456"` |

**Example:**

```typescript theme={"system"}
await removeComment(selectedTask.id, comment.commentId)
```

### Enumerations

#### `getEnumerationOptions`

Retrieves enumeration options for a specific enumeration name.

```typescript theme={"system"}
const options = await getEnumerationOptions(enumName)
```

**Parameters:**

| Name       | Description          | Type     | Mandatory | Example    |
| ---------- | -------------------- | -------- | --------- | ---------- |
| `enumName` | The enumeration name | `string` | ✅         | `"Status"` |

**Returns:** Promise resolving to an array of `TaskManagerEnumeration` objects.

### Real-time updates (SSE)

#### `initSseConnection`

Initializes a Server-Sent Events (SSE) connection for real-time task updates.

```typescript theme={"system"}
const sseConnection = initSseConnection(
  resourceId,
  eventHandler
)
```

**Parameters:**

| Name           | Description                            | Type                                                                      | Mandatory | Example           |
| -------------- | -------------------------------------- | ------------------------------------------------------------------------- | --------- | ----------------- |
| `resourceId`   | The resource ID from the view          | `string`                                                                  | ✅         | `"resource-123"`  |
| `eventHandler` | Callback function to handle SSE events | `(event: MessageEvent&lt;string&gt;, data: SseEventData \| null) => void` | ✅         | See example below |

**Returns:** `SseConnection` object with a `close()` method.

**Example:**

```typescript theme={"system"}
const handleSseEvent = (event: MessageEvent<string>, eventData: SseEventData | null) => {
  if (event.type === SseMessageType.Data) {
    if (eventData?.eventType === SseTaskMessageType.VIEW_UPDATED) {
      // Reload tasks when view is updated
      loadTasks()
    }
  }
}

const sseConnection = initSseConnection(view.resourceId, handleSseEvent)

// Cleanup on component unmount
useEffect(() => {
  return () => {
    if (sseConnection) {
      sseConnection.close()
    }
  }
}, [])
```

**SSE Event Types:**

| Enum                 | Value          | Description                         |
| -------------------- | -------------- | ----------------------------------- |
| `SseTaskMessageType` | `VIEW_UPDATED` | View configuration has been updated |
| `SseTaskEventType`   | `TASK_UPDATED` | A task has been updated             |
| `SseTaskEventType`   | `TASK_CREATED` | A new task has been created         |

## UI Flow renderer

`FlxUiFlowRenderer` renders a full UI Flow (multi-view navigation, breadcrumbs, embedded processes, and an optional chat widget) from a single component.

```typescript theme={"system"}
import { FlxUiFlowRenderer } from '@flowx/react-sdk'
```

#### Usage

```tsx theme={"system"}
<FlxUiFlowRenderer
  apiUrl="https://yourDomain.dev"
  authToken={authToken}
  processApiPath="onboarding"
  language="en"
  locale="en-US"
  themeId="12345678-1234-1234-1234-123456789012"
  staticAssetsPath={staticAssetsPath}
  workspaceId={workspaceId}
  appInfo={{ appId: projectId }}
  organizationId={organizationId}
  isDraft={false}
  cache={true}
  uiFlowName="my-ui-flow"
  buildId={buildId}
  components={{ MyCustomComponent }}
  validators={{ myValidator: () => (v) => v !== '' }}
/>
```

#### Parameters

| Name                | Description                                                                                                                                                                                                                          | Type                            | Mandatory |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- | --------- |
| `apiUrl`            | Base API URL                                                                                                                                                                                                                         | `string`                        | ✅         |
| `authToken`         | Authorization token                                                                                                                                                                                                                  | `string`                        | ✅         |
| `processApiPath`    | Process subpath                                                                                                                                                                                                                      | `string`                        | ✅         |
| `language`          | UI language                                                                                                                                                                                                                          | `string`                        | ❌         |
| `locale`            | Date/number formatting locale                                                                                                                                                                                                        | `string`                        | ❌         |
| `themeId`           | Theme identifier                                                                                                                                                                                                                     | `string`                        | ✅         |
| `staticAssetsPath`  | Static resources base path                                                                                                                                                                                                           | `string`                        | ✅         |
| `workspaceId`       | Workspace identifier                                                                                                                                                                                                                 | `string`                        | ✅         |
| `appInfo`           | App identity. Shape: `{ appId: string, appVersionId?: string }`                                                                                                                                                                      | `object`                        | ✅         |
| `organizationId`    | FlowX-issued organization UUID. On self-hosted deployments it matches the `ORGANIZATION_ID` configured during the backend upgrade. See [License and organization configuration](/5.9/migrating-from-5.1-lts/organization-deployment) | `string`                        | ✅         |
| `isDraft`           | Render the draft version of the UI Flow                                                                                                                                                                                              | `boolean`                       | ❌         |
| `cache`             | Enable caching                                                                                                                                                                                                                       | `boolean`                       | ❌         |
| `uiFlowName`        | Name of the UI Flow to start                                                                                                                                                                                                         | `string`                        | ❌         |
| `buildId`           | Pinned build identifier                                                                                                                                                                                                              | `string`                        | ❌         |
| `startParams`       | Initial query parameters passed to the UI Flow                                                                                                                                                                                       | `Record<string, unknown>`       | ❌         |
| `components`        | Custom component registry                                                                                                                                                                                                            | `Record<string, ComponentType>` | ❌         |
| `validators`        | Custom validator registry                                                                                                                                                                                                            | `Record<string, ValidatorFn>`   | ❌         |
| `legacyHttpVersion` | Use legacy HTTP API version                                                                                                                                                                                                          | `boolean`                       | ❌         |

### Starting a UI Flow

#### Prerequisites

* **UI Flow name**: You need the name of the UI Flow to start, passed as `uiFlowName`.
* **FlowX Project UUID**: The `appInfo.appId` value, which identifies which project the UI Flow belongs to. Obtain it the same way as for processes: **FlowX Dashboard → Projects → copy UUID from the project actions popover**.
* **Process API path**: The `processApiPath` subpath used by the embedded process renderer when the UI Flow navigates into a full-screen process.

#### Getting the UI Flow name

Open the FlowX Designer and navigate to **UI Flows**. The flow name displayed in the list is the value to pass as `uiFlowName`.

#### Initializing the UI Flow renderer

Minimal working example:

```tsx theme={"system"}
import { FlxUiFlowRenderer } from '@flowx/react-sdk'

export function MyUiFlowContainer() {
  return (
    <FlxUiFlowRenderer
      apiUrl="https://yourDomain.dev"
      authToken={authToken}
      processApiPath="onboarding"
      language="en"
      locale="en-US"
      themeId={themeId}
      staticAssetsPath={staticAssetsPath}
      workspaceId={workspaceId}
      appInfo={{ appId: projectId }}
      organizationId={organizationId}
      isDraft={false}
      cache={true}
      uiFlowName={uiFlowName}
    />
  )
}
```

#### Passing initial parameters: `startParams`

Use `startParams` to inject query-string key/value pairs into the UI Flow at startup. The values are available inside the flow as URL query parameters.

```tsx theme={"system"}
<FlxUiFlowRenderer
  {...requiredProps}
  startParams={{ referralCode: 'REF123', skipIntro: true }}
/>
```

<Info>
  `startParams` is read once at initialization. To trigger a full re-initialization, change one of the primitive props such as `uiFlowName`.
</Info>

***

## Utility API

These functions and hooks are exported from `@flowx/react-sdk` and can be used independently of the renderer components.

```typescript theme={"system"}
import {
  useEnumeration,
  getEnumeration,
  getStaticAsset,
  getSubstitutionTag,
} from '@flowx/react-sdk'
```

#### `useEnumeration`

React hook that fetches enumeration values reactively. Re-fetches whenever `name` or `parentName` changes.

```typescript theme={"system"}
const values = useEnumeration(name: string, parentName?: string, cached?: boolean): NomenclatorValue[]
```

| Parameter    | Description                           | Type      | Mandatory |
| ------------ | ------------------------------------- | --------- | --------- |
| `name`       | Enumeration name                      | `string`  | ✅         |
| `parentName` | Parent enumeration name for cascading | `string`  | ❌         |
| `cached`     | Use cached result when available      | `boolean` | ❌         |

#### `getEnumeration`

Async function to fetch enumeration values imperatively.

```typescript theme={"system"}
const values = await getEnumeration(name: string, parentName?: string, cached?: boolean)
```

#### `getStaticAsset`

Resolves a static asset URL by its key.

```typescript theme={"system"}
const url = getStaticAsset(key: string)
```

#### `getSubstitutionTag`

Resolves a substitution tag value by its key.

```typescript theme={"system"}
const value = getSubstitutionTag(key: string)
```

***

## Custom CSS

The renderer SDK allows you to pass custom CSS classes on any component inside the process. These classes are then applied to the component's root element.

To add a CSS custom class to a component, you need to define the class in the process designer by navigating to the styles tab of the component, expanding the Advanced accordion and writing down the CSS class.

![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/4.5/react/add_css_class.gif)

<Warning>
  The classes will be applied last on the element, so they will override the classes already defined on the element.
</Warning>

![](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/4.5/react/css_class_inspector.png)

## Storybook

Below you find a Storybook which demonstrates how components behave under different states, props, and conditions, it allows you to preview and interact with individual UI components in isolation, without the need for a full-fledged app:

<Card title="Storybook" href="https://storybooks.flowxai.dev/" icon="book" />
