From 45912d89c373916e838871819e84510d51698b44 Mon Sep 17 00:00:00 2001 From: Ioana Gheorghiu Date: Fri, 20 Nov 2026 16:16:30 +0200 Subject: [PATCH 1/4] docs(du): trim the DU widget READMEs to what a basic setup needs The Validation Station, Classification Station and Document Viewer READMEs now cover the path an FDE takes to a working Coded Action App: pick a path (with a shared diagram of how documents get into the widgets), install, host the web component, quick start, saving, core props and troubleshooting. The depth moves to linked pages: - validation-station/docs: data-sources.md, events-and-commands.md, hosting.md, and the shared diagram under assets/ - validation-station/UPGRADING.md: release notes and the 1.0.x migration - classification-station/docs/reference.md: data sources, props, outputs The subcomponents guide is rewritten around five rules and a Coded Action App worked example. Development/License are wrapped in docs:ignore in every README. Co-Authored-By: Claude Opus 5.5 --- packages/classification-station/README.md | 320 +++--- .../classification-station/docs/reference.md | 107 ++ packages/document-viewer/README.md | 155 +-- packages/validation-station/README.md | 981 +++--------------- packages/validation-station/UPGRADING.md | 201 ++++ .../docs/assets/how-documents-get-in.svg | 101 ++ .../validation-station/docs/data-sources.md | 173 +++ .../docs/events-and-commands.md | 275 +++++ packages/validation-station/docs/hosting.md | 109 ++ .../docs/validation-station-subcomponents.md | 403 ++----- 10 files changed, 1439 insertions(+), 1386 deletions(-) create mode 100644 packages/classification-station/docs/reference.md create mode 100644 packages/validation-station/UPGRADING.md create mode 100644 packages/validation-station/docs/assets/how-documents-get-in.svg create mode 100644 packages/validation-station/docs/data-sources.md create mode 100644 packages/validation-station/docs/events-and-commands.md create mode 100644 packages/validation-station/docs/hosting.md diff --git a/packages/classification-station/README.md b/packages/classification-station/README.md index b78e09f4..8867c3a8 100644 --- a/packages/classification-station/README.md +++ b/packages/classification-station/README.md @@ -1,239 +1,179 @@ # @uipath/ui-widgets-classification-station -A React wrapper for the UiPath Document Understanding **Classification Station** — the human-in-the-loop _split and classify_ step. It renders a file's pages next to the original document and lets a reviewer confirm or correct how the classifier split the file into documents, and which document type each one is. It handles web component loading and bucket artifact fetching, and exposes a declarative props API for the station's inputs and outputs. +A React wrapper for the UiPath Document Understanding **Classification Station**, the human-in-the-loop _split and classify_ step. A reviewer sees a file's pages next to the original document, and confirms or corrects how the classifier split it into documents and which document type each one is. The widget loads the file, and saves the review back. -It is the step before extraction; [`@uipath/ui-widgets-validation-station`](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/validation-station) reviews the extracted values of a document that has already been classified. +It is the step before extraction. To review the extracted values of a classified document, use [`@uipath/ui-widgets-validation-station`](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/validation-station). -## Installation +## Pick your path -```bash -npm install @uipath/ui-widgets-classification-station -``` +![How documents get into the widgets](https://raw.githubusercontent.com/UiPath/uipath-ui-widgets/develop/packages/validation-station/docs/assets/how-documents-get-in.svg) -### Peer dependencies +The Classification Station takes **Document Understanding data only**: the `CsContentValidationData` a classification validation task hands over. Flow IDP (IXP) documents are not supported yet. -```bash -npm install react@^19.2.0 react-dom@^19.2.0 @uipath/uipath-typescript@^1.5.1 -``` - -## Quick start - -> **Note: Theming** -> Add either a `light` or `dark` class to your HTML `` element to enable proper theming. - -```tsx -import { - configureClassificationStationWc, - ClassificationStation, - type CsContentValidationData, -} from "@uipath/ui-widgets-classification-station"; -import { UiPath } from "@uipath/uipath-typescript/core"; -import { useEffect, useState } from "react"; +Send it as **① one payload**, `sdk` + `data`, and the widget fetches the rest and saves the review. Or send **② the pieces** you already hold as `artifacts`, and save them yourself. The quick start below takes ①. -// Once, at app startup — loads the web component from `du-cs-wc`, next to -// your app's own root by default. See "Hosting the web component" below. -configureClassificationStationWc(); +## Install -function App({ task }: { task: { data: CsContentValidationData } }) { - const [sdk, setSdk] = useState(null); - - useEffect(() => { - const init = async () => { - const uipath = new UiPath({ - baseUrl: "https://api.uipath.com", - orgName: "your-org", - tenantName: "your-tenant", - clientId: "your-client-id", - // `OR.Buckets` is the widget's own need; `OR.Tasks` is for the host - // code that fetches the task and completes it after submit. - scope: "OR.Buckets OR.Tasks", - redirectUri: "http://localhost:3000/callback", - }); - await uipath.initialize(); - setSdk(uipath); - }; - init(); - }, []); - - if (!sdk) return
Loading...
; - - return ( - { - if (result?.success) completeTask(request.classification); - }} - /> - ); -} +```bash +npm install @uipath/ui-widgets-classification-station @uipath/uipath-typescript @uipath/coded-action-app react@^19.2.0 react-dom@^19.2.0 +npm install --save-dev @uipath/du-classification-station-wc@1.0.0-rc.2 ``` -`theme` defaults to `"light"`, `language` to `ClassificationStationLanguage.English` and `enableSaveAsDraft` to `true`, so the minimal mount just needs `sdk` and `data`. - -> **Warning: Call `configureClassificationStationWc` first** -> You must call it once before rendering `ClassificationStation`, and host the web component's files where it expects them. See [Hosting the web component](#hosting-the-web-component). +`@uipath/uipath-typescript` `>= 1.5.1` is required. `@uipath/coded-action-app` is only for a Coded Action App. Every type the package uses is exported from its root. -## Data sources +## Host the web component -The widget needs the document types to classify into, the classification to review, a document DOM, and the document itself. There are two ways to give it those: +The widget renders the Classification Station web component, loaded at runtime from your app's own files rather than bundled. Three steps: -| Mode | Pass | Who fetches | Who writes back | -| ----------------- | ---------------------------- | -------------------------------------------------------------- | --------------------------------------------------- | -| **Self-fetching** | `sdk` + `data` | The widget, from the bucket paths on `CsContentValidationData` | The widget, to `ValidatedClassificationResultsPath` | -| **Pre-fetched** | `artifacts` (+ `documentId`) | You — hand it a `CsDocumentArtifacts` object you already hold | You, from the request the widget emits | +1. **Stage it.** Copy `node_modules/@uipath/du-classification-station-wc` into `public/du-cs-wc` before every `dev` and `build`. The Validation Station samples' [`stage-du-wc.mjs`](https://github.com/UiPath/uipath-typescript/blob/main/samples/document-validation-app/scripts/stage-du-wc.mjs) does this for its own package; change the package name and the `public/` folder, and wire it to `predev` and `prebuild`. +2. **Load it once,** at startup, before rendering the widget: -**The outputs do not change with the mode.** `onSubmit`, `onSaveAsDraft` and `onReportException` fire for every user action either way, and always carry the request the web component produced. When the widget persisted the classification itself, `onSubmit` and `onSaveAsDraft` get the outcome as a second argument. + ```ts title="src/main.tsx" + import { configureClassificationStationWc } from "@uipath/ui-widgets-classification-station"; -The two modes can be mixed: pass `artifacts` **and** `sdk` + `data` to skip the fetch while keeping the built-in write-back. + configureClassificationStationWc({ includeFonts: true }).catch((error) => { + console.error( + "Classification Station web component failed to load", + error, + ); + }); + ``` -Every bucket call is scoped to the folder `data` names — `FolderKey`, or `FolderId` when there is no key. If neither is there, the widget renders an error instead of fetching. +3. **Keep `public/du-cs-wc` out of git.** It is generated, and about 17 MB. -### What self-fetching reads and writes +> **Note: Keep the `.catch`** +> The returned promise is the only place a load failure surfaces. Without it, a missing `du-cs-wc` leaves the widget on its loading state with no error. -It does what the cloud Classification Station in Action Center does, so either reopens what the other saved: +Serve the **whole** package: without `du-assets/`, pages, thumbnails and translations fail silently. For another location, CSP and version skew, the Validation Station's [Hosting in depth](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/hosting.md) applies here too, with `du-cs-wc` for `du-vs-wc`. -- **Reads** `TaxonomyPath` (for its `DocumentTypes`), `DocumentObjectModelPath`, `TextPath`, `EncodedDocumentPath`, `CustomizationInfoPath` when set (otherwise every customization is off), and the classification: `ValidatedClassificationResultsPath` once a reviewer has saved one, else `AutomaticClassificationResultsPath`. -- **Writes** submits and drafts alike to `ValidatedClassificationResultsPath`: the `Classifications` array, as a `.zip` holding one JSON file. A submit and a draft write the same file — what makes a submit final is the host completing the Action Center task. -- **Never** reports an exception: route `onReportException` yourself, typically via `OrchestratorDuModule.submitExceptionReport(...)`. +## Quick start: a Coded Action App -> **Info: `CsDocumentArtifacts`** -> `{ docTypes, classificationResults, dom, text, original, customizationInfo? }` — `docTypes` is the taxonomy's `DocumentTypes` array, not the taxonomy itself, and `original` is the document as a base64 data URL. `classificationResults: null` is meaningful: it loads an unclassified file. +A Document Understanding workflow raises a classification validation action; Action Center opens your app on it. The app reads the task, renders the widget, and completes the task once the reviewer saves. The wiring is the same as the Validation Station's [quick start](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/validation-station#quick-start-a-coded-action-app); only the widget and its input change. -### Owning the round-trip - -Everything the widget does internally is exported, so a host can drive the same flow: +```ts title="src/uipath.ts" +import { UiPath } from "@uipath/uipath-typescript/core"; +import { CodedActionApp } from "@uipath/coded-action-app"; -| Export | Use | -| ----------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `fetchCsDocumentArtifacts(sdk, data)` | Fetch `CsDocumentArtifacts` imperatively — outside render, ahead of time, or in a loader | -| `useCsDocumentArtifacts(sdk, data)` | The same fetch as a hook | -| `submitClassification(sdk, data, request)` | The submit write-back to `ValidatedClassificationResultsPath` | -| `saveClassificationAsDraft(sdk, data, request)` | The draft write-back, to the same path | +// No arguments and no initialize(): Action Center supplies the auth. +export const sdk = new UiPath(); +export const codedActionApp = new CodedActionApp(); +``` -```tsx +```tsx title="src/Classification.tsx" +import { useEffect, useMemo, useState } from "react"; import { ClassificationStation, - fetchCsDocumentArtifacts, - submitClassification, + type CsContentValidationData, } from "@uipath/ui-widgets-classification-station"; +import { MessageSeverity } from "@uipath/coded-action-app"; +import { codedActionApp, sdk } from "./uipath"; -const artifacts = await fetchCsDocumentArtifacts(sdk, data); +// Name it after the input your action schema declares. +interface ActionInputs { + classificationValidationData?: CsContentValidationData; +} - { - const result = await submitClassification(sdk, data, request); - if (result.success) completeTask(request.classification); - }} -/>; -``` +export function Classification() { + const [task, setTask] = useState<{ + data: ActionInputs; + folderId: number; + isReadOnly: boolean; + } | null>(null); -## Props + useEffect(() => { + codedActionApp.getTask().then((t) => + setTask({ + data: (t.data as ActionInputs) ?? {}, + folderId: t.folderId, + isReadOnly: t.isReadOnly, + }), + ); + }, []); -| Prop | Type | Default | Description | -| ---------------------------- | ------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------- | -| `sdk` | `UiPath` | — | SDK instance. Required for self-fetching and the built-in write-back. | -| `data` | `CsContentValidationData` | — | The classification task's bucket descriptor. Required for self-fetching. | -| `artifacts` | `CsDocumentArtifacts` | — | Pre-fetched artifacts. When supplied, no fetch is performed. | -| `documentId` | `string` | — | Falls back to `data.DocumentId`. The element waits for it, so the widget assigns it after every other input. | -| `theme` | `CsTheme` | `'light'` | `'light'`, `'dark'`, `'light-hc'`, `'dark-hc'`, or the Apollo Modern `'future-light'` / `'future-dark'` | -| `language` | `ClassificationStationLanguage` | `English` | UI language | -| `isReadonly` | `boolean` | `false` | Renders without editing affordances | -| `enableSaveAsDraft` | `boolean` | `true` | Offers a **Save as draft** action | -| `persistent` | `boolean` | `false` | Renders the persistent element variant, which survives portal/DOM detachment and is force-destroyed on unmount | -| `documentViewerOptions` | `DocumentViewerOptions` | — | The embedded viewer's chrome and selection behaviour — the same object the other DU widgets take | -| `enableTokenFeatures` | `boolean` | `true` | Token-level selection in the viewer. Off, the selection-mode button and the search are hidden | -| `allowNotClassifiedGroups` | `boolean` | `true` | Lets pages stay unassigned to any document type | -| `supportNotClassifiedGroups` | `boolean` | `false` | Renders a dedicated "not classified" group for unassigned pages | -| `customNotClassifiedLabel` | `string` | — | Overrides that group's label. Pass it already localized | -| `disableShortcutsPanel` | `boolean` | `false` | Hides the keyboard-shortcuts panel | -| `showCreateNewDocTypeOption` | `boolean` | `false` | Offers "create a new document type" in the type picker; see `onCreateNewDocType` | -| `pdfSettings` | `unknown` | — | PDF viewer settings (`IPDFSettings`) | -| `pageUris` | `string[]` | — | Pre-rendered page images, one per page, used instead of rendering the PDF | -| `className`, `style` | | — | Set on the element | + // The widget reads the bucket in the folder the payload names; fall back to the task's folder. + const data = useMemo(() => { + const payload = task?.data.classificationValidationData; + if (!payload) return null; + return payload.FolderId != null || payload.FolderKey != null + ? payload + : { ...payload, FolderId: task.folderId }; + }, [task]); -Unset inputs are not assigned, so the element keeps its own defaults. Customization flags — `EnablePageReordering`, `DisableKeyboardShortcuts` — live under `FeatureCustomization` in `artifacts.customizationInfo` (typed `ICustomizationInfoDTO`). + if (!task) return

Loading the action…

; + if (!data) return

This action has no classification input.

; -## Outputs + return ( + { + if (!result?.success) { + codedActionApp.showMessage( + result?.error ?? "Failed to save the classification.", + MessageSeverity.Error, + ); + return; + } + // completeTask replaces the task's data: pass all of it back, not just your changes. + await codedActionApp.completeTask("Submit", task.data); + }} + /> + ); +} +``` -| Prop | Fires when | -| ------------------------ | -------------------------------------------------------------------------------------------------------------- | -| `onSubmit` | The user pressed **Save**. `(request: ICsSaveClassificationRequest, result?)` | -| `onSaveAsDraft` | The user pressed **Save as draft**. `(request: ICsSaveClassificationAsDraftRequest, result?)` | -| `onReportException` | The user reported the file as an exception. `(request: ICsSaveExceptionReportRequest)` — always yours to route | -| `onDirtyChange` | Unsaved changes appear or are cleared. A flag set by any edit — gate an "unsaved work" prompt on it | -| `onHasChangesChange` | The classification differs structurally from the one loaded (group count, types, page counts, page positions) | -| `onSplitClassifications` | The current split changed: `{ split: [{ documentTypeId, pageRange: '1-3,5' }] }` | -| `onCreateNewDocType` | The user asked to create a new document type (needs `showCreateNewDocTypeOption`); the creation flow is yours | +> **Note: Theming** +> Add a `light` or `dark` class to ``; the widget's stylesheets key off it. `theme` and `language` default to `"light"` and English. -`dirty` and `hasChanges` are different signals and neither is derived from the other: assigning an OCR reference to a group sets `dirty` but not `hasChanges`. +## Saving -> **Attention: Re-feeding the data is destructive** -> The element compares its inputs by reference. A new `classificationResults` (a new `artifacts` or `data`) replaces the loaded groups wholesale, discarding unsaved edits and the selection. Keep the object stable across renders — React state — and persist pending edits before you switch documents. +| Callback | With `sdk` + `data`, the widget… | Left to you | +| ------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------- | +| `onSubmit` | writes the classification to `ValidatedClassificationResultsPath` | **Completing the task**, and only when `result.success` is true | +| `onSaveAsDraft` | writes the same file; the next load opens on it. On by default (`enableSaveAsDraft`) | Telling the reviewer | +| `onReportException` | nothing | Persisting it yourself | -## Language enum +A submit and a draft write the same file: what makes a submit final is completing the task. The widget shows no errors of its own; tell the reviewer from the callback. It reads and writes what the cloud Classification Station in Action Center does, so either reopens what the other saved. -`ClassificationStationLanguage` lists the 14 languages the station ships translations for: `German` (`de`), `English` (`en`), `Spanish` (`es`), `SpanishMexico` (`es-MX`), `French` (`fr`), `Japanese` (`ja`), `Korean` (`ko`), `Portuguese` (`pt`), `PortugueseBrazil` (`pt-BR`), `Romanian` (`ro`), `Russian` (`ru`), `Turkish` (`tr`), `ChineseSimplified` (`zh-CN`), `ChineseTraditional` (`zh-TW`). +**OAuth scopes.** The widget needs `OR.Buckets`; the app needs `OR.Tasks` to read and complete the task. In a Coded Action App, set them as `scope` in `uipath.json`. -## Hosting the web component +## Core props -`configureClassificationStationWc` loads `@uipath/du-classification-station-wc` at runtime from a URL, rather than bundling it into your app — the bundle is several megabytes, and it resolves its own `du-assets/` (pdf.js, decoders, translations) and `media/` (fonts) relative to where `main.js` is served. +| Prop | Type | Description | +| ------------------------------------------------ | ------------------------------- | ------------------------------------------------------------------------------------------- | +| `sdk` | `UiPath` | The SDK instance. Needed whenever the widget fetches or saves (①) | +| `data` | `CsContentValidationData` | The classification task's payload | +| `artifacts` | `CsDocumentArtifacts` | The pieces you already hold (②). No fetch happens. Pass `documentId` with them | +| `theme` | `CsTheme` | `'light'` (default), `'dark'`, `'light-hc'`, `'dark-hc'`, `'future-light'`, `'future-dark'` | +| `language` | `ClassificationStationLanguage` | Defaults to English | +| `isReadonly` | `boolean` | Read-only review. Pass the task's `isReadOnly` | +| `enableSaveAsDraft` | `boolean` | Offers **Save as draft**. Defaults to `true` | +| `onSubmit`, `onSaveAsDraft`, `onReportException` | `(request, result?) => void` | See [Saving](#saving) | -| Option | Default | Description | -| --------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------- | -| `deploymentUrl` | `du-cs-wc` joined onto `getAppBase()` | Base URL the web component's files are served from. A string, or a `() => string \| Promise` resolver | -| `includeFonts` | `false` | Injects the component's `fonts.css` (Material Icons) as a light-DOM stylesheet | +> **Warning: Keep `data` and `artifacts` stable** +> The element compares its inputs by reference. A new object replaces the loaded classification wholesale and discards unsaved edits. Keep it in React state. -Serve the **whole** contents of `node_modules/@uipath/du-classification-station-wc` at that URL — for Vite, copy it into `public/du-cs-wc` before `dev` and `build`. Without `du-assets/`, page rendering, thumbnails and translations 404 silently; without `media/`, `includeFonts` loads no fonts. Keep the staged copy out of git and in step with the version this package's types are built against (`1.0.0-rc.2`). +The not-classified group, page reordering, shortcuts, the change callbacks (`onDirtyChange`, `onSplitClassifications`, …) and the round-trip helpers are in [Data sources, props and outputs](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/classification-station/docs/reference.md). -The notes in the Validation Station README's [Hosting the web component](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/validation-station#hosting-the-web-component) apply here as well: call it once, the returned promise is the error channel, `deploymentUrl` is a script source — never derive it from user input — and self-hosting needs no more than `script-src 'self'`. +## Troubleshooting -### Fonts +| Symptom | Likely cause | +| ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| The widget stays on its loading state | The web component did not load: check the `.catch` on `configureClassificationStationWc`, and `du-cs-wc` | +| `basedomain query parameter is missing` | The app was opened directly, not from an Action Center task | +| An error naming a missing folder (`FolderId` / `FolderKey`) | The payload has neither. Fill it from `task.folderId`, as in the quick start | +| A 401 or 403 when loading or saving | A missing scope. See [Saving](#saving) | +| Unsaved edits vanish | A new `data` or `artifacts` object on re-render. Keep it stable | +| With `artifacts`: the document does not render | `original` must be a data URI (`data:application/pdf;base64,…`), and `docTypes` the taxonomy's `DocumentTypes` array | -`fonts.css` in the npm package carries **Material Icons only** — the one font the component cannot do without. The component's text inherits your app's font stack; install [`@uipath/apollo-fonts`](https://www.npmjs.com/package/@uipath/apollo-fonts) and import its `font.css` for the UiPath typography. +## Going further -## Exported types +- [Data sources, props and outputs](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/classification-station/docs/reference.md): what self-fetching reads and writes, loading and saving from your own code, every prop and output, the language list. +- [Hosting in depth](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/hosting.md), written for the Validation Station; the same applies with `du-cs-wc`. +- [Validation Station](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/validation-station), the next step: reviewing the extracted values. -```ts -import { - ClassificationStation, - ClassificationStationLanguage, - CLASSIFICATION_STATION_TAG, - configureClassificationStationWc, - fetchCsDocumentArtifacts, - joinDeploymentUrl, - saveClassificationAsDraft, - submitClassification, - useCsDocumentArtifacts, -} from "@uipath/ui-widgets-classification-station"; -import type { - ClassificationStationEventProps, - ClassificationStationProps, - ClassificationStationWcConfig, - CsArtifactsSource, - CsContentValidationData, - CsDocumentArtifacts, - CsSaveCallbacks, - CsTheme, - DocumentViewerFloatingButtonsOptions, - DocumentViewerOptions, - IClassificationDocumentBoundsDTO, - IClassificationResultDTO, - IClassifierResultDTO, - ICsSaveClassificationAsDraftRequest, - ICsSaveClassificationRequest, - ICsSaveExceptionReportRequest, - ICustomizationInfoDTO, - IFeatureCustomization, - InteractionType, - IReportAsExceptionDTO, - SaveClassificationResult, - SplitClassification, - SplitClassifications, -} from "@uipath/ui-widgets-classification-station"; -``` + ## Development @@ -251,3 +191,5 @@ npm run test:watch ## License MIT + + diff --git a/packages/classification-station/docs/reference.md b/packages/classification-station/docs/reference.md new file mode 100644 index 00000000..2d065139 --- /dev/null +++ b/packages/classification-station/docs/reference.md @@ -0,0 +1,107 @@ +# Data sources, props and outputs + +> **Note: Applies to `@uipath/ui-widgets-classification-station` with web component `1.0.0-rc.2`.** +> Start with the [package README](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/classification-station#readme) for install, hosting and a working Coded Action App. + +## Data sources + +The widget needs the document types to classify into, the classification to review, a document DOM, and the document itself. There are two ways to give it those: + +| Mode | Pass | Who fetches | Who writes back | +| ----------------- | ---------------------------- | -------------------------------------------------------------- | --------------------------------------------------- | +| **Self-fetching** | `sdk` + `data` | The widget, from the bucket paths on `CsContentValidationData` | The widget, to `ValidatedClassificationResultsPath` | +| **Pre-fetched** | `artifacts` (+ `documentId`) | You — hand it a `CsDocumentArtifacts` object you already hold | You, from the request the widget emits | + +**The outputs do not change with the mode.** `onSubmit`, `onSaveAsDraft` and `onReportException` fire for every user action either way, and always carry the request the web component produced. When the widget persisted the classification itself, `onSubmit` and `onSaveAsDraft` get the outcome as a second argument. + +The two modes can be mixed: pass `artifacts` **and** `sdk` + `data` to skip the fetch while keeping the built-in write-back. + +Every bucket call is scoped to the folder `data` names — `FolderKey`, or `FolderId` when there is no key. If neither is there, the widget renders an error instead of fetching. + +## What self-fetching reads and writes + +It does what the cloud Classification Station in Action Center does, so either reopens what the other saved: + +- **Reads** `TaxonomyPath` (for its `DocumentTypes`), `DocumentObjectModelPath`, `TextPath`, `EncodedDocumentPath`, `CustomizationInfoPath` when set (otherwise every customization is off), and the classification: `ValidatedClassificationResultsPath` once a reviewer has saved one, else `AutomaticClassificationResultsPath`. +- **Writes** submits and drafts alike to `ValidatedClassificationResultsPath`: the `Classifications` array, as a `.zip` holding one JSON file. A submit and a draft write the same file — what makes a submit final is the host completing the Action Center task. +- **Never** reports an exception: route `onReportException` yourself, typically via `OrchestratorDuModule.submitExceptionReport(...)`. + +> **Info: `CsDocumentArtifacts`** +> `{ docTypes, classificationResults, dom, text, original, customizationInfo? }` — `docTypes` is the taxonomy's `DocumentTypes` array, not the taxonomy itself, and `original` is the document as a base64 data URL. `classificationResults: null` is meaningful: it loads an unclassified file. + +## Owning the round-trip + +Everything the widget does internally is exported, so a host can drive the same flow: + +| Export | Use | +| ----------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `fetchCsDocumentArtifacts(sdk, data)` | Fetch `CsDocumentArtifacts` imperatively — outside render, ahead of time, or in a loader | +| `useCsDocumentArtifacts(sdk, data)` | The same fetch as a hook | +| `submitClassification(sdk, data, request)` | The submit write-back to `ValidatedClassificationResultsPath` | +| `saveClassificationAsDraft(sdk, data, request)` | The draft write-back, to the same path | + +```tsx +import { + ClassificationStation, + fetchCsDocumentArtifacts, + submitClassification, +} from "@uipath/ui-widgets-classification-station"; + +const artifacts = await fetchCsDocumentArtifacts(sdk, data); + + { + const result = await submitClassification(sdk, data, request); + if (result.success) completeTask(request.classification); + }} +/>; +``` + +## Props + +| Prop | Type | Default | Description | +| ---------------------------- | ------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------- | +| `sdk` | `UiPath` | — | SDK instance. Required for self-fetching and the built-in write-back. | +| `data` | `CsContentValidationData` | — | The classification task's bucket descriptor. Required for self-fetching. | +| `artifacts` | `CsDocumentArtifacts` | — | Pre-fetched artifacts. When supplied, no fetch is performed. | +| `documentId` | `string` | — | Falls back to `data.DocumentId`. The element waits for it, so the widget assigns it after every other input. | +| `theme` | `CsTheme` | `'light'` | `'light'`, `'dark'`, `'light-hc'`, `'dark-hc'`, or the Apollo Modern `'future-light'` / `'future-dark'` | +| `language` | `ClassificationStationLanguage` | `English` | UI language | +| `isReadonly` | `boolean` | `false` | Renders without editing affordances | +| `enableSaveAsDraft` | `boolean` | `true` | Offers a **Save as draft** action | +| `persistent` | `boolean` | `false` | Renders the persistent element variant, which survives portal/DOM detachment and is force-destroyed on unmount | +| `documentViewerOptions` | `DocumentViewerOptions` | — | The embedded viewer's chrome and selection behaviour — the same object the other DU widgets take | +| `enableTokenFeatures` | `boolean` | `true` | Token-level selection in the viewer. Off, the selection-mode button and the search are hidden | +| `allowNotClassifiedGroups` | `boolean` | `true` | Lets pages stay unassigned to any document type | +| `supportNotClassifiedGroups` | `boolean` | `false` | Renders a dedicated "not classified" group for unassigned pages | +| `customNotClassifiedLabel` | `string` | — | Overrides that group's label. Pass it already localized | +| `disableShortcutsPanel` | `boolean` | `false` | Hides the keyboard-shortcuts panel | +| `showCreateNewDocTypeOption` | `boolean` | `false` | Offers "create a new document type" in the type picker; see `onCreateNewDocType` | +| `pdfSettings` | `unknown` | — | PDF viewer settings (`IPDFSettings`) | +| `pageUris` | `string[]` | — | Pre-rendered page images, one per page, used instead of rendering the PDF | +| `className`, `style` | | — | Set on the element | + +Unset inputs are not assigned, so the element keeps its own defaults. Customization flags — `EnablePageReordering`, `DisableKeyboardShortcuts` — live under `FeatureCustomization` in `artifacts.customizationInfo` (typed `ICustomizationInfoDTO`). + +## Outputs + +| Prop | Fires when | +| ------------------------ | -------------------------------------------------------------------------------------------------------------- | +| `onSubmit` | The user pressed **Save**. `(request: ICsSaveClassificationRequest, result?)` | +| `onSaveAsDraft` | The user pressed **Save as draft**. `(request: ICsSaveClassificationAsDraftRequest, result?)` | +| `onReportException` | The user reported the file as an exception. `(request: ICsSaveExceptionReportRequest)` — always yours to route | +| `onDirtyChange` | Unsaved changes appear or are cleared. A flag set by any edit — gate an "unsaved work" prompt on it | +| `onHasChangesChange` | The classification differs structurally from the one loaded (group count, types, page counts, page positions) | +| `onSplitClassifications` | The current split changed: `{ split: [{ documentTypeId, pageRange: '1-3,5' }] }` | +| `onCreateNewDocType` | The user asked to create a new document type (needs `showCreateNewDocTypeOption`); the creation flow is yours | + +`dirty` and `hasChanges` are different signals and neither is derived from the other: assigning an OCR reference to a group sets `dirty` but not `hasChanges`. + +> **Attention: Re-feeding the data is destructive** +> The element compares its inputs by reference. A new `classificationResults` (a new `artifacts` or `data`) replaces the loaded groups wholesale, discarding unsaved edits and the selection. Keep the object stable across renders — React state — and persist pending edits before you switch documents. + +## Language enum + +`ClassificationStationLanguage` lists the 14 languages the station ships translations for: `German` (`de`), `English` (`en`), `Spanish` (`es`), `SpanishMexico` (`es-MX`), `French` (`fr`), `Japanese` (`ja`), `Korean` (`ko`), `Portuguese` (`pt`), `PortugueseBrazil` (`pt-BR`), `Romanian` (`ro`), `Russian` (`ru`), `Turkish` (`tr`), `ChineseSimplified` (`zh-CN`), `ChineseTraditional` (`zh-TW`). diff --git a/packages/document-viewer/README.md b/packages/document-viewer/README.md index a3e1585a..f0c668b7 100644 --- a/packages/document-viewer/README.md +++ b/packages/document-viewer/README.md @@ -1,67 +1,61 @@ # @uipath/ui-widgets-document-viewer -A React wrapper for the UiPath Document Understanding **document viewer** — the viewer of Validation Station and Classification Station, as a component of its own. It renders a digitised document's pages, its text, or both; lets the user search, zoom, rotate pages and select words or areas; highlights content references; and reports the user's selection as one. It handles web component loading and bucket artifact fetching. +A React wrapper for the UiPath Document Understanding **document viewer**: the viewer of the Validation Station and the Classification Station, as a component of its own. It renders a digitised document's pages, its text, or both; lets the user search, zoom, rotate and select words or areas; highlights content references; and reports the user's selection as one. -It holds no extraction or classification data and edits nothing. Use it as a document preview, or next to a form of your own, and link the two through content references — the same shape an extracted value's `Reference` has. +It holds no extraction or classification data and edits nothing. Use it as a document preview, or next to a form of your own, linked through content references: the same shape an extracted value's `Reference` has. -## Installation +## Pick your path -```bash -npm install @uipath/ui-widgets-document-viewer -``` +![How documents get into the widgets](https://raw.githubusercontent.com/UiPath/uipath-ui-widgets/develop/packages/validation-station/docs/assets/how-documents-get-in.svg) + +| You have | Pass | Who fetches | +| ------------------------------------------------------------------ | ------------------------------------------- | ----------------------------------------------------------------------------------------- | +| A Validation or Classification Station task's data (DU) | **①** `sdk` + `data` | The widget: `DocumentObjectModelPath`, plus `EncodedDocumentPath` and `TextPath` when set | +| The document's pieces, already fetched (DU or a Flow IXP document) | **②** `artifacts={{ dom, original, text }}` | You | -### Peer dependencies +`data` is any object with the bucket fields the viewer reads: a `ContentValidationData` and a `CsContentValidationData` both qualify. There is no `processedDocument` prop: for a Flow IDP document, pass its pieces. The `artifacts` you already fetched for a station can be passed as they are. + +`original` (a base64 data URI) enables the page view and `text` the text view; with both, the user can switch. + +## Install ```bash -npm install react@^19.2.0 react-dom@^19.2.0 @uipath/uipath-typescript@^1.5.1 +npm install @uipath/ui-widgets-document-viewer @uipath/uipath-typescript react@^19.2.0 react-dom@^19.2.0 +npm install --save-dev @uipath/du-document-viewer-wc@1.0.0-beta.1 ``` -## Quick start +## Host the web component -> **Note: Theming** -> Add either a `light` or `dark` class to your HTML `` element to enable proper theming. +The same three steps as the [Validation Station's](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/validation-station#host-the-web-component), with this package's names: -```tsx -import { - configureDocumentViewerWc, - DocumentViewer, -} from "@uipath/ui-widgets-document-viewer"; +1. **Stage** the whole `node_modules/@uipath/du-document-viewer-wc` into `public/du-dv-wc` before every `dev` and `build`. Without `du-assets/`, rendering and translations fail silently. +2. **Load it once,** at startup: `configureDocumentViewerWc({ includeFonts: true }).catch(console.error)`. The promise is the only place a load failure surfaces. +3. **Keep `public/du-dv-wc` out of git.** It is generated, and about 10 MB. + +`includeFonts` adds Material Icons only; the viewer's text inherits your app's font stack. For another location (`deploymentUrl`), CSP and version skew, see [Hosting in depth](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/hosting.md), with `du-dv-wc` for `du-vs-wc`. -// Once, at app startup — loads the web component from `du-dv-wc`, next to -// your app's own root by default. See "Hosting the web component" below. -configureDocumentViewerWc(); +## Quick start +```tsx +import { DocumentViewer } from "@uipath/ui-widgets-document-viewer"; + +// A Validation or Classification Station task's data: the viewer reads its DOM, original and text paths. function Preview({ sdk, task }) { - // A Validation Station or Classification Station task's data — the viewer - // reads its DOM, original and text paths. return ; } ``` -> **Warning: Call `configureDocumentViewerWc` first** -> You must call it once before rendering `DocumentViewer`, and host the web component's files where it expects them. See [Hosting the web component](#hosting-the-web-component). - -## Data sources - -| Mode | Pass | Who fetches | -| ----------------- | -------------- | ----------------------------------------------------------------------------------------- | -| **Self-fetching** | `sdk` + `data` | The widget: `DocumentObjectModelPath`, plus `EncodedDocumentPath` and `TextPath` when set | -| **Pre-fetched** | `artifacts` | You — hand it `{ dom, original, text }` | - -`data` is any object with the bucket fields the viewer reads (`DocumentViewerContentData`): a Validation Station task's `ContentValidationData` and a Classification Station task's `CsContentValidationData` both qualify. Every bucket call is scoped to its folder — `FolderKey`, or `FolderId` when there is no key. - -`artifacts` takes the `dom`, `original` and `text` members of the Validation Station's `DuDocumentArtifacts` or the Classification Station's `CsDocumentArtifacts`, so artifacts you already fetched for a station can be passed as they are. `original` (a base64 data URL) enables the page view, `text` the text view; with both, the user can switch. +> **Note: Theming** +> Add a `light` or `dark` class to ``; the widget's stylesheets key off it. -| Export | Use | -| ------------------------------------- | ------------------------------------------------------------------------ | -| `fetchDvDocumentArtifacts(sdk, data)` | Fetch `DvDocumentArtifacts` imperatively — outside render, ahead of time | -| `useDvDocumentArtifacts(sdk, data)` | The same fetch as a hook | +In a Coded Action App, `sdk` and the task come from `new UiPath()` and `getTask()`, as in the Validation Station's [quick start](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/validation-station#quick-start-a-coded-action-app). To fetch ahead of time, or once for several components, use `fetchDvDocumentArtifacts(sdk, data)` or the `useDvDocumentArtifacts(sdk, data)` hook, and pass the result as `artifacts`. ## Linking it to a form -The viewer is linked through content references, in and out: +The viewer links through content references, in and out: ```tsx +import { useMemo, useState } from "react"; import { DocumentViewer } from "@uipath/ui-widgets-document-viewer"; import { CompactFieldsForm } from "@uipath/ui-widgets-validation-station"; @@ -81,7 +75,9 @@ function Review({ artifacts }) { artifacts={artifacts} highlightReference={selected} passiveReferences={references} - onReferenceSelect={({ text, reference }) => fill(text, reference)} + onReferenceSelect={({ text, reference }) => + console.log(text, reference) + } /> **Note: Linking through `instanceId`** -> This viewer cannot share a store with the Validation Station subcomponents through `instanceId` yet. When you need that — selecting a field highlights it, a rule click focuses its value, with nothing wired by hand — keep the Validation Station's own (deprecated) `DocumentViewer` subcomponent. +> This viewer cannot share a store with the Validation Station subcomponents through `instanceId` yet. When you need that (selecting a field highlights it, a rule click focuses its value, with nothing wired by hand), use the Validation Station's own `DocumentViewer` subcomponent. See [Building with subcomponents](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/validation-station-subcomponents.md). ## Props | Prop | Type | Default | Description | | -------------------- | -------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------- | -| `sdk` | `UiPath` | — | SDK instance. Required for self-fetching | -| `data` | `DocumentViewerContentData` | — | A task's bucket descriptor. Required for self-fetching | -| `artifacts` | `DvDocumentArtifacts` | — | Pre-fetched `{ dom, original, text }`. When supplied, no fetch is performed | -| `theme` | `DvTheme` | `'light'` | `'light'`, `'dark'`, `'light-hc'`, `'dark-hc'`, or the Apollo Modern `'future-light'` / `'future-dark'` | -| `language` | `DocumentViewerLanguage` | `English` | UI language | -| `options` | `DocumentViewerOptions` | — | Which controls show and how selection behaves — see below | +| `sdk` | `UiPath` | — | Required for self-fetching (①) | +| `data` | `DocumentViewerContentData` | — | A task's bucket descriptor. Required for self-fetching (①) | +| `artifacts` | `DvDocumentArtifacts` | — | `{ dom, original, text }` (②). No fetch happens | +| `theme` | `DvTheme` | `'light'` | `'light'`, `'dark'`, `'light-hc'`, `'dark-hc'`, `'future-light'`, `'future-dark'` | +| `language` | `DocumentViewerLanguage` | `English` | One of the 14 languages the viewer ships; the enum lists them | +| `options` | `DocumentViewerOptions` | — | Which controls show and how selection behaves; see below | | `highlightReference` | `ResultsContentReference \| null` | — | Highlights and scrolls to it; `null` clears the highlight | | `passiveReferences` | `readonly ResultsContentReference[] \| null` | — | Drawn as a passive highlight, e.g. every extracted value. The user can hide it from the viewer menu | | `outlineReference` | `ResultsContentReference \| null` | — | Outlines it, e.g. the value hovered in another component; `null` clears it | @@ -114,7 +110,7 @@ function Review({ artifacts }) { | `persistent` | `boolean` | `false` | Renders the persistent element variant, which survives portal/DOM detachment and is force-destroyed on unmount | | `className`, `style` | | — | Set on the element | -`options` is the same `DocumentViewerOptions` object the Validation Station takes as `options.documentViewerOptions` and the Classification Station as `documentViewerOptions`: `floatingButtonsOptions` (`hideTextView`, `hideInteractionTypeButton`, `defaultInteractionType`, `hideSearch`, `hideKeyboardShortcutsButton`, `hideSwitchPanelSidesButton`, `hideExtractedTokensToggle`), `autoRotationThreshold` and `disableSelection`. Pass a new object to change it. +`options` is the same `DocumentViewerOptions` the Validation Station takes as `options.documentViewerOptions` and the Classification Station as `documentViewerOptions`: `floatingButtonsOptions` (`hideTextView`, `hideInteractionTypeButton`, `defaultInteractionType`, `hideSearch`, `hideKeyboardShortcutsButton`, `hideSwitchPanelSidesButton`, `hideExtractedTokensToggle`), `autoRotationThreshold` and `disableSelection`. Pass a new object to change it. ## Outputs @@ -128,56 +124,17 @@ function Review({ artifacts }) { | `onReferenceSelect` | The user selects words or clears the selection: `{ text, reference }`, with empty `Tokens` when cleared | | `onSwitchPanelSides` | The user asks to move the viewer to the other side of your layout. The element does not move itself | -## Language enum - -`DocumentViewerLanguage` lists the 14 languages the viewer ships translations for: `German` (`de`), `English` (`en`), `Spanish` (`es`), `SpanishMexico` (`es-MX`), `French` (`fr`), `Japanese` (`ja`), `Korean` (`ko`), `Portuguese` (`pt`), `PortugueseBrazil` (`pt-BR`), `Romanian` (`ro`), `Russian` (`ru`), `Turkish` (`tr`), `ChineseSimplified` (`zh-CN`), `ChineseTraditional` (`zh-TW`). - -## Hosting the web component - -`configureDocumentViewerWc` loads `@uipath/du-document-viewer-wc` at runtime from a URL rather than bundling it — it resolves its own `du-assets/` (pdf.js, decoders, translations) and `media/` (fonts) relative to where `main.js` is served. - -| Option | Default | Description | -| --------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------- | -| `deploymentUrl` | `du-dv-wc` joined onto `getAppBase()` | Base URL the web component's files are served from. A string, or a `() => string \| Promise` resolver | -| `includeFonts` | `false` | Injects the component's `fonts.css` (Material Icons) as a light-DOM stylesheet | - -Serve the **whole** contents of `node_modules/@uipath/du-document-viewer-wc` at that URL — for Vite, copy it into `public/du-dv-wc` before `dev` and `build`. Without `du-assets/`, rendering and translations fail silently. Keep the staged copy out of git and in step with the version this package's types are built against (`1.0.0-beta.1`). - -The notes in the Validation Station README's [Hosting the web component](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/validation-station#hosting-the-web-component) apply here as well: call it once, the returned promise is the error channel, `deploymentUrl` is a script source — never derive it from user input — and self-hosting needs no more than `script-src 'self'`. - -### Fonts - -`fonts.css` carries **Material Icons only**. The viewer's text inherits your app's font stack; install [`@uipath/apollo-fonts`](https://www.npmjs.com/package/@uipath/apollo-fonts) and import its `font.css` for the UiPath typography. - -## Exported types - -```ts -import { - configureDocumentViewerWc, - DOCUMENT_VIEWER_TAG, - DocumentViewer, - DocumentViewerLanguage, - fetchDvDocumentArtifacts, - joinDeploymentUrl, - useDvDocumentArtifacts, -} from "@uipath/ui-widgets-document-viewer"; -import type { - DocumentViewerContentData, - DocumentViewerEventProps, - DocumentViewerFloatingButtonsOptions, - DocumentViewerOptions, - DocumentViewerProps, - DocumentViewerSelection, - DocumentViewerWcConfig, - DvArtifactsSource, - DvDocumentArtifacts, - DvTheme, - GoToPage, - GoToPageResult, - GoToPageTarget, - InteractionType, -} from "@uipath/ui-widgets-document-viewer"; -``` +## Troubleshooting + +| Symptom | Likely cause | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------- | +| Nothing renders, no error | The web component did not load: check the `.catch` on `configureDocumentViewerWc`, and `du-dv-wc` | +| Only the text view, or a blank page view | `original` is missing, or not a data URI (`data:application/pdf;base64,…`) | +| Highlights land in the wrong place | A hand-built `dom` whose `Pages[].Size` is not `[0, 0, width, height]` | +| A 401 or 403 when loading | Self-fetching needs `OR.Buckets` (or `OR.Buckets.Read`) | +| `goToPage` works once, then nothing | The same object was passed again. Pass a new one for every navigation | + + ## Development @@ -195,3 +152,5 @@ npm run test:watch ## License MIT + + diff --git a/packages/validation-station/README.md b/packages/validation-station/README.md index 55a4440c..158c37f4 100644 --- a/packages/validation-station/README.md +++ b/packages/validation-station/README.md @@ -1,890 +1,249 @@ # @uipath/ui-widgets-validation-station -A React wrapper for the UiPath Document Understanding **Validation Station**. It handles web component loading and bucket artifact fetching, and exposes a declarative props API for every Validation Station feature. +A React wrapper for the UiPath Document Understanding **Validation Station**: a reviewer checks and corrects the values extracted from one document, next to the document itself. Drop it into your React app, usually a [Coded Action App](https://uipath.github.io/uipath-typescript/coded-action-apps/getting-started/) that opens from an Action Center task. The widget loads the document, and saves the review back. -## Installation +## Pick your path -```bash -npm install @uipath/ui-widgets-validation-station -``` - -### Peer dependencies - -```bash -npm install react@^19.2.0 react-dom@^19.2.0 @uipath/uipath-typescript@^1.5.1 -``` +![How documents get into the widgets: a Document Understanding task produces ContentValidationData, a Flow IDP node produces ProcessedDocument; either is sent as one payload or as pieces, to Validation Station, its subcomponents, or the other widgets](https://raw.githubusercontent.com/UiPath/uipath-ui-widgets/develop/packages/validation-station/docs/assets/how-documents-get-in.svg) -## Quick start +Your workflow decides the contract: -> **Note: Theming** -> Add either a `light` or `dark` class to your HTML `` element to enable proper theming. +- **A Document Understanding task** (IntelligentOCR, DocumentUnderstanding.Activities) hands over a `ContentValidationData`. Pass it as `data`. +- **A Flow IDP node** hands over a `ProcessedDocument` (IXP). Pass it as `processedDocument`. -```tsx -import { - configureValidationStationWc, - ValidationStation, -} from "@uipath/ui-widgets-validation-station"; -import { UiPath } from "@uipath/uipath-typescript/core"; -import type { DuFramework } from "@uipath/uipath-typescript/document-understanding"; -import { useEffect, useState } from "react"; +Send it as **① one payload**, with `sdk` + `data` or `sdk` + `processedDocument`, and the widget fetches the rest and saves the review. Or send **② the pieces** you already hold as `artifacts`, and save them yourself. The quick start below takes ①. -// Once, at app startup — loads the web component from `du-vs-wc`, next to -// your app's own root by default. See "Hosting the web component" below. -configureValidationStationWc(); +| Widget | DU ① | DU ② | IXP ① | IXP ② | +| ------------------------------------------------------------------------------------------------------------------------ | :--: | :--: | :---: | :---: | +| `ValidationStation`, the whole screen | ✓ | ✓ | ✓ | ✓ | +| `CompactFieldsForm`, `CompactTableEditor`, `DocumentViewer`, its [subcomponents](#going-further) | ✓ | ✓ | ✓ | ✓ | +| `CompactBusinessRules`, `CompactDocTypeField`, its subcomponents | ✓ | ✓ | — | — | +| [Document Viewer](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/document-viewer), standalone package | ✓ | ✓ | — | ✓\* | +| [Classification Station](https://github.com/UiPath/uipath-ui-widgets/tree/develop/packages/classification-station) | ✓ | ✓ | — | — | -function App({ task }: { task: { data: DuFramework.ContentValidationData } }) { - const [sdk, setSdk] = useState(null); +\* It takes no taxonomy or extraction, so for IXP pass only `dom`, `text` and `original`. - useEffect(() => { - const init = async () => { - const uipath = new UiPath({ - baseUrl: "https://api.uipath.com", - orgName: "your-org", - tenantName: "your-tenant", - clientId: "your-client-id", - // `OR.Buckets` is the widget's own need; `OR.Tasks` is for the host - // code that fetches the task and completes it after submit. - scope: "OR.Buckets OR.Tasks", - redirectUri: "http://localhost:3000/callback", - }); - await uipath.initialize(); - setSdk(uipath); - }; - init(); - }, []); +Start with `ValidationStation`. Reach for the subcomponents only when the standard screen does not fit your layout. - if (!sdk) return
Loading...
; +## Install - return ; -} +```bash +npm install @uipath/ui-widgets-validation-station @uipath/uipath-typescript @uipath/coded-action-app react@^19.2.0 react-dom@^19.2.0 +npm install --save-dev @uipath/du-validation-station-wc@1.0.0-rc.6 ``` -> **Note: `initialize()` drives the OAuth redirect** -> Under OAuth, `initialize()` navigates the browser to the identity provider and completes the flow when it returns, so keep it inside an effect rather than at module scope, and serve `redirectUri` as a route of this same app — it must match a URI registered on the external application exactly, scheme and path included. - -`theme` defaults to `"light"` and `language` defaults to `ValidationStationLanguage.English`, so the minimal mount just needs `sdk` and `data`. +`@uipath/uipath-typescript` `>= 1.5.1` is required. `@uipath/coded-action-app` is only for a Coded Action App. The package is written in TypeScript, and every type it uses is exported from its root. -> **Warning: Call `configureValidationStationWc` first** -> You must call it once before rendering any widget from this package, and host the web component's files where it expects them. A `deploymentUrl` default handles this for most hosts — override it if yours doesn't. See [Hosting the web component](#hosting-the-web-component). +## Host the web component -## Data sources +The widget renders the Validation Station web component, which is loaded at runtime from your app's own files rather than bundled. There is no bundler configuration to write. Three steps: -The widget needs a taxonomy, an extraction result and a document DOM. There are three mutually exclusive ways to give it those: +1. **Stage it.** Copy `node_modules/@uipath/du-validation-station-wc` into `public/du-vs-wc` before every `dev` and `build`. Take the [`stage-du-wc.mjs`](https://github.com/UiPath/uipath-typescript/blob/main/samples/document-validation-app/scripts/stage-du-wc.mjs) script from the samples as-is: -| Mode | Pass | Who fetches | Who writes back | -| ---------------------- | ---------------------------- | ------------------------------------------------------------- | ----------------------------------------------------- | -| **Self-fetching** | `sdk` + `data` | The widget, from the bucket paths on `ContentValidationData` | The widget, to `ValidatedExtractionResultsPath` | -| **Self-fetching, IXP** | `sdk` + `processedDocument` | The widget, through the Flow run that produced the document | The widget, as a review recorded against the Flow run | -| **Pre-fetched** | `artifacts` (+ `documentId`) | You — hand it a `DuDocumentArtifacts` object you already hold | You, from the request the widget emits | - -If both `data` and `processedDocument` are set, `data` wins. - -**The outputs do not change with the mode.** `onSubmit`, `onSaveAsDraft` and `onReportException` fire for every user action either way, and always carry the request the web component produced. The only difference is a second argument: when the widget persisted the data itself, it passes the outcome too. - -Pre-fetched mode is what you want when the document does not live in a storage bucket, when the artifacts are already in memory (e.g. fetched once and shared with the [subcomponents](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/validation-station-subcomponents.md)), or when persistence goes somewhere other than `ValidatedExtractionResultsPath`. - -```tsx -import { - ValidationStation, - type DuDocumentArtifacts, -} from "@uipath/ui-widgets-validation-station"; + ```json title="package.json" + { + "scripts": { + "stage-du-wc": "node scripts/stage-du-wc.mjs", + "predev": "npm run stage-du-wc", + "prebuild": "npm run stage-du-wc" + } + } + ``` -function App({ artifacts }: { artifacts: DuDocumentArtifacts }) { - return ( - persistItYourself(request)} - /> - ); -} -``` +2. **Load it once,** at startup, before rendering any widget: -Every bucket call is scoped to the folder `data` names — `FolderId`, or `FolderKey` when both are present. The activity that produces the `ContentValidationData` sets one of them; if neither is there, the widget renders an error instead of fetching. + ```ts title="src/main.tsx" + import { configureValidationStationWc } from "@uipath/ui-widgets-validation-station"; -The two modes can be mixed: pass `artifacts` **and** `sdk` + `data` to skip the fetch while keeping the built-in write-back — `onSubmit` then receives the outcome as well. + configureValidationStationWc({ includeFonts: true }).catch((error) => { + console.error("Validation Station web component failed to load", error); + }); + ``` -> **Info: `DuDocumentArtifacts`** -> `{ taxonomy, extractionResult, predictedExtractionResult?, dom, text, customizationInfo, original }` — `original` is the base64-encoded document the viewer renders. In `DuDocumentArtifacts`, `taxonomy` and `extractionResult` are UiPath DU contracts. `ValidationStation` also takes `IxpDocumentArtifacts`, the same shape with all three in the IXP representation (an `IXPTaxonomy` JSON Schema, an `IXPReviewedExtraction` — an `IXPExtraction` plus optional `confirmations` — and an optional `IXPExtraction` prediction). So do the `CompactFieldsForm`, `CompactTableEditor` and `DocumentViewer` subcomponents; `CompactBusinessRules` and `CompactDocTypeField` take `DuDocumentArtifacts` only. +3. **Keep `public/du-vs-wc` out of git.** It is generated, and about 35 MB. -### Comparing against the prediction +> **Note: Keep the `.catch`** +> The returned promise is the only place a load failure surfaces. Without it, a missing or misplaced `du-vs-wc` leaves the widget on its loading state with no error. -`predictedExtractionResult` is the model's prediction — the extraction output nobody edited — as opposed to `extractionResult`, the result the user reviews. Self-fetching fills it from `AutomaticExtractionResultsPath`; in pre-fetched mode it is optional, and a hand-built `DuDocumentArtifacts` without it is still valid. Supply it in the same representation as `extractionResult`: an `IXPExtraction` on `IxpDocumentArtifacts`. A Flow `ProcessedDocument` carries no prediction, so self-fetching one leaves it unset. +The default location works for a Coded App and for a plain host alike. For another location, CSP and version skew, see [Hosting in depth](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/hosting.md). -> **Warning: Change it together with `extractionResult`** -> Once the element has paired a prediction with the loaded values, assigning a different `predictedExtractionResult` (or `null`) on its own reloads the last `extractionResult` it was fed and drops unsaved edits. With `EnablePredictionDiff` on, the element also inserts predicted rows and values the result lacks, as unconfirmed values the user confirms or deletes. +## Quick start: a Coded Action App -By itself it changes nothing visible. It drives the `EnablePredictionDiff` customization flag (compact mode, on `ValidationStation`, `CompactFieldsForm` and `CompactTableEditor`): where the prediction differs from the current values, the element shows the predicted value with a button that takes it over. Like every customization flag, it lives under `FeatureCustomization` in `customizationInfo` — typed by the exported `ICustomizationInfoDTO` / `IFeatureCustomization`: +A Document Understanding workflow raises a validation action; Action Center opens your app on it. The app reads the task, renders the widget, and completes the task once the reviewer submits. This is a cut-down version of the [`action-app-with-document-validation`](https://github.com/UiPath/uipath-typescript/tree/main/samples/coded-action-apps/action-app-with-document-validation) sample, whose action schema declares one input, `contentValidationData`, and one outcome, `Submit`. -```ts -import type { ICustomizationInfoDTO } from "@uipath/ui-widgets-validation-station"; +```ts title="src/uipath.ts" +import { UiPath } from "@uipath/uipath-typescript/core"; +import { CodedActionApp } from "@uipath/coded-action-app"; -// Merge over what the bucket supplied rather than replacing it. -const fetched = artifacts.customizationInfo as - | ICustomizationInfoDTO - | undefined; -const withDiff = { - ...artifacts, - customizationInfo: { - ...fetched, - FeatureCustomization: { - ...fetched?.FeatureCustomization, - EnablePredictionDiff: true, - }, - } satisfies ICustomizationInfoDTO, -}; +// No arguments and no initialize(): Action Center supplies the auth. +export const sdk = new UiPath(); +export const codedActionApp = new CodedActionApp(); ``` -### Owning the round-trip - -Pre-fetched mode does not mean writing the bucket plumbing yourself. Everything the widget does internally is exported, so a host can drive the same flow: - -| Export | Use | -| ---------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `fetchDuDocumentArtifacts(sdk, data)` | Fetch `DuDocumentArtifacts` imperatively — outside render, ahead of time, or in a loader | -| `useDuDocumentArtifacts(sdk, data)` | The same fetch as a hook, for when the fetch belongs to a component's lifecycle | -| `submitValidatedData(sdk, data, request)` | The submit flow: `ProcessExtractedData`, then upload to `ValidatedExtractionResultsPath` | -| `saveValidatedDataAsDraft(sdk, data, request)` | The draft flow: upload `validatedData` straight to the bucket | - -```tsx +```tsx title="src/Validation.tsx" +import { useEffect, useMemo, useState } from "react"; import { - fetchDuDocumentArtifacts, - submitValidatedData, - saveValidatedDataAsDraft, ValidationStation, - type DuDocumentArtifacts, + type IValidationStationOptions, } from "@uipath/ui-widgets-validation-station"; +import type { DuFramework } from "@uipath/uipath-typescript/document-understanding"; +import { MessageSeverity } from "@uipath/coded-action-app"; +import { codedActionApp, sdk } from "./uipath"; -function HostOwnedReview({ sdk, data }) { - const [artifacts, setArtifacts] = useState(null); - - useEffect(() => { - fetchDuDocumentArtifacts(sdk, data).then(setArtifacts); - }, [sdk, data]); - - if (!artifacts) return
Loading document…
; - - return ( - { - const result = await submitValidatedData(sdk, data, request); - afterSubmit(result); - }} - onSaveAsDraft={(request) => saveValidatedDataAsDraft(sdk, data, request)} - /> - ); +interface ActionInputs { + contentValidationData?: DuFramework.ContentValidationData; } -``` - -> **Warning: Handle both callbacks** -> The widget always offers **Save as draft**, so leaving `onSaveAsDraft` unwired means a draft click persists nothing. - -The request payloads are exported too — `IVsSaveValidatedDataRequest`, `IVsSaveValidatedDataAsDraftRequest` and `IVsSaveExceptionReportRequest` — so handlers declared outside JSX can name their parameter. - -### IXP (`ProcessedDocument`) - -A Flow IDP node emits a `ProcessedDocument` rather than a `ContentValidationData`. It carries the taxonomy (an `IXPTaxonomy`) and the result (an `IXPExtraction`) inline, plus `metadata` naming the run that produced it — `traceId`, `spanId` and `folderKey`. The document, its DOM and its OCR text are read through that run's trace. - -```tsx - completeTask(result?.processedDocument)} -/> -``` - -- **Loading.** The document opens on the result last saved against the producing span (a draft), else on the payload's `result`. A draft reopens with the values the reviewer had confirmed. `documentId` defaults to `metadata.traceId`. -- **Saving.** Submit and draft record the review against the producing span; report-as-exception records a rejection with the reason. `onSubmit`, `onSaveAsDraft` and `onReportException` receive the outcome as their second argument. `request.validatedData` is an `IXPExtraction` on submit, and an `IXPReviewedExtraction` — the same plus the reviewer's `confirmations` — on a draft. -- **Record format.** A review is stored as the `ProcessedDocument` the widget was given, with its `result` replaced by the validated one and `metadata.hitl.draft` set — `true` for a draft, `false` for a submit. This is the shape the Angular Validation Station uses, so either reopens a review the other saved. A record in any other shape — including the `{ draft, extraction }` envelope both used before — is ignored on load, and the document opens on the payload's `result`. -- **Completing the task is yours.** The downstream Flow node reads the validated document from the task completion. A submit's `result.processedDocument` is that document — the same one the record holds, a `ValidatedProcessedDocument` — so complete the task with it, verbatim, whatever `result.success` says: a failed record write must not block the review. `toValidatedProcessedDocument(processedDocument, validatedData, draft)` builds it when you persist yourself. -- **Subcomponents.** `CompactFieldsForm`, `CompactTableEditor` and `DocumentViewer` take `processedDocument` or `IxpDocumentArtifacts` too, and `CompactFieldsForm` saves a Flow document as `ValidationStation` does. `CompactBusinessRules` and `CompactDocTypeField` are Document Understanding-only. See the [subcomponents guide](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/validation-station-subcomponents.md#ixp-documents). -- **OAuth scopes.** The `sdk`'s token needs `Traces.Api` (the run's spans, and the review record) and `OR.Buckets.Read` (the document, DOM and OCR text, via ECS). A coded action app completing the task also needs `OR.Tasks`. A missing scope surfaces as a 401/403 in the load or save error. -- **Hosting.** The artifacts are downloaded in the browser from pre-signed ECS storage URLs, so the host's origin must be in the ECS storage account's CORS rules. Coded apps (`https://{org}.{env}.uipath.host`) are. -The widget does this through exported functions, so a host that fetches up front runs exactly the same code: - -| Export | Use | -| ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `fetchProcessedDocumentArtifacts(sdk, processedDocument)` | Fetch the `IxpDocumentArtifacts` — what the widget fetches given `processedDocument` | -| `useProcessedDocumentArtifacts(sdk, processedDocument)` | The same fetch as a hook, for when the fetch belongs to a component's lifecycle | -| `submitProcessedDocument(sdk, processedDocument, request)` | Record a submitted review; its result carries the `processedDocument` to complete the task with | -| `saveProcessedDocumentAsDraft(sdk, processedDocument, request)` | Record a draft — the one the next load opens on | -| `reportProcessedDocumentException(sdk, processedDocument, request)` | Record a rejection with the reviewer's reason. Replaces a saved draft | +const OPTIONS: IValidationStationOptions = { + emitDtoStateChanges: true, // without it, "Save as draft" saves nothing + hideReportAsExceptionButton: true, // it needs a DU validation task, not an app task +}; -```tsx -const artifacts = await fetchProcessedDocumentArtifacts(sdk, processedDocument); +export function Validation() { + const [task, setTask] = useState<{ + data: ActionInputs; + folderId: number; + isReadOnly: boolean; + } | null>(null); - { - const result = await submitProcessedDocument( - sdk, - processedDocument, - request, + useEffect(() => { + codedActionApp.getTask().then((t) => + setTask({ + data: (t.data as ActionInputs) ?? {}, + folderId: t.folderId, + isReadOnly: t.isReadOnly, + }), ); - // Undefined only for a payload the station could not have reviewed. - if (result.processedDocument) completeTask(result.processedDocument); - }} - onSaveAsDraft={(request) => - saveProcessedDocumentAsDraft(sdk, processedDocument, request) - } -/>; -``` - -The save functions are stateless: each one edits the span's newest review record, or creates it when there is none, so the widget and a host saving outside it always land on the same record. - -## Props - -| Prop | Type | Required | Default | Description | -| -------------------------------- | --------------------------------------------- | -------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `sdk` | `UiPath` | No\* | — | UiPath SDK instance for authentication and API calls. Required for self-fetching / persistence | -| `data` | `ContentValidationData` | No\* | — | Document data containing the bucket paths, document ID, and the folder they live in — `FolderId` or `FolderKey`, whichever the producing activity set. Required for self-fetching / persistence | -| `processedDocument` | `ProcessedDocument` | No\* | — | A Flow IDP node's output. With `sdk`, the widget fetches its artifacts and records reviews through the producing run — see [IXP documents](#ixp-documents-processeddocument). Ignored when `data` is set | -| `artifacts` | `DuDocumentArtifacts \| IxpDocumentArtifacts` | No\* | — | Pre-fetched document artifacts. When supplied, no fetch is performed. \*Either `artifacts`, `sdk` + `data` or `sdk` + `processedDocument` must be provided | -| `documentId` | `string` | No | — | Document ID forwarded to the web component. Falls back to `data.DocumentId`, else `processedDocument.metadata.traceId` — pass it in pre-fetched mode | -| `theme` | `DuTheme` | No | `'light'` | Visual theme: `'light'`, `'dark'`, `'light-hc'`, `'dark-hc'`, or the Apollo Modern `'future-light'` / `'future-dark'` | -| `language` | `ValidationStationLanguage` | No | `English` | UI language (see [the enum](#language-enum)) | -| `isReadonly` | `boolean` | No | `false` | When `true`, renders in read-only mode | -| `persistent` | `boolean` | No | `false` | Render the persistent element variant, which survives portal/DOM detachment (e.g. tab switches) | -| `options` | `IValidationStationOptions` | No | — | Fine-grained UI feature flags, passed through to the element as given | -| `save={{ validate: false }}` | `{ validate: boolean }` | No | — | Trigger **save as draft** | -| `save={{ validate: true }}` | `{ validate: boolean }` | No | — | Trigger **submit** — runs validation first, then saves | -| `discardChanges` | `{ value: boolean }` | No | — | Trigger a discard-changes operation. Call `setDiscardChanges({ value: true })` (or `false` — the boolean is ignored) every time you want it to fire. Each call creates a brand-new object even if the content looks identical, and that is what the widget watches for | -| `setFieldValueByPath` | `SetFieldValueByPath` | No | — | Set a field value addressed by a path of `{ fieldName, valueIndex }` segments | -| `selectAndFocusFieldValueByPath` | `SelectAndFocusFieldValueByPath` | No | — | Select and focus a field value addressed by a path; focuses the document reference if any | -| `deleteFieldValueByPath` | `DeleteFieldValueByPath` | No | — | Delete a field value addressed by a path | - -The three save callbacks (`onSubmit`, `onSaveAsDraft`, `onReportException`) are documented [below](#reacting-to-save-draft-and-exception-flows); the state callbacks in [Reading the document state](#reading-the-document-state). - -## Reacting to save, draft and exception flows - -The widget surfaces three user-initiated flows and reports each through exactly one callback, whichever mode it is in. Every callback receives the raw request; `result` is filled in only for the flows the widget persisted itself. - -| Callback | User action | Signature | What the widget does | What the host does | -| ------------------- | ----------------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -| `onSubmit` | **Submit** | `(request, result?) => void` | With `sdk` + `data`: `processExtractedData`, then uploads to `ValidatedExtractionResultsPath`, and passes the outcome as `result`. Without: emits the request only | React to `result`, or — when it is absent — persist the request yourself (`submitValidatedData` does exactly what the widget would have) | -| `onSaveAsDraft` | **Save as draft** | `(request, result?) => void` | With `sdk` + `data`: uploads `validatedData` straight to the bucket (no `processExtractedData`). Without: emits the request only | Same as above; the host-side equivalent is `saveValidatedDataAsDraft` | -| `onReportException` | **Report as exception** | `(request, result?) => void` | With `sdk` + `processedDocument`: records the rejection against the Flow run and passes the outcome as `result`. Otherwise nothing — the reason is at `request.exceptionReport.Reason` | For any other source, persist it yourself — call `OrchestratorDuModule.submitExceptionReport(...)` | - -Submit and draft hand you a `SaveValidatedDataResult` (`{ success, error? }`) — the host owns all UI feedback (toast, retry, etc.); the widget does not surface failures itself. The exception callback hands you `documentId` and `reason` strings ready to forward to the SDK. + }, []); -All three fire on every user action, regardless of mode — that is the contract. Only `result` varies. + // The widget reads the bucket in the folder the payload names; fall back to the task's folder. + const data = useMemo(() => { + const payload = task?.data.contentValidationData; + if (!payload) return null; + return payload.FolderId != null || payload.FolderKey != null + ? payload + : { ...payload, FolderId: task.folderId }; + }, [task]); -```tsx -import { - ValidationStation, - type SaveValidatedDataResult, -} from "@uipath/ui-widgets-validation-station"; -import { OrchestratorDuModule } from "@uipath/uipath-typescript/orchestrator-du-module"; - -function App({ sdk, data, task }) { - // `sdk` + `data` are set, so the widget persisted it and `result` is present. - const handleSubmit = async (request, result?: SaveValidatedDataResult) => { - if (!result?.success) { - console.warn("Submit failed:", result?.error); - return; - } - await task.complete({ action: "Completed", type: "DocumentValidation" }); - }; - - const handleSaveAsDraft = (request, result?: SaveValidatedDataResult) => { - if (!result?.success) console.warn("Draft save failed:", result?.error); - }; - - const handleReportException = async (request) => { - const reason = request.exceptionReport?.Reason ?? ""; - const response = await new OrchestratorDuModule(sdk).submitExceptionReport( - task.id, - request.documentId, - reason || "Reported via Validation Station", - { folderId: task.folderId }, - ); - if (!response.IsSuccessful) { - console.error("submitExceptionReport failed:", response.ErrorMessage); - } - }; + if (!task) return

Loading the action…

; + if (!data) return

This action has no contentValidationData input.

; return ( { + if (!result?.success) { + codedActionApp.showMessage( + result?.error ?? "Failed to submit the document.", + MessageSeverity.Error, + ); + return; + } + // completeTask replaces the task's data: pass all of it back, not just your changes. + await codedActionApp.completeTask("Submit", task.data); + }} + onSaveAsDraft={(_request, result) => + codedActionApp.showMessage( + result?.success + ? "Draft saved." + : (result?.error ?? "Failed to save the draft."), + result?.success ? MessageSeverity.Success : MessageSeverity.Error, + ) + } /> ); } ``` -> **Warning: Failures are silent if you skip the callbacks** -> All three callbacks are optional, but the widget surfaces no errors on its own. Outside a `processedDocument`, `onReportException` is the only place the report goes — without it, the user's **Report as exception** click is a no-op. - -## Reading the document state - -These callbacks report the rest of the element's `IValidationStationStandaloneWcEventMap`; the three save flows are above. - -| Prop | Fires when | -| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `onExtractionResultChanged` | Any change to the extraction result — needs `options={{ emitDtoStateChanges: true }}`. An IXP document reports an `IXPReviewedExtraction`, with its `confirmations` | -| `onLoaded` | The element finished loading | -| `onDirtyChange` | Unsaved changes appear or are cleared | -| `onIsValidChange` | Validity flips (`true` = no Must rule broken, no invalid values) | -| `onDocumentTypeChanged` | The user picks another document type | -| `onFieldValueSelected` | The user selects a field value | -| `onFieldValueChanged` | The user edits a field value | -| `onBusinessRulesEvaluated` | Validation errors and business rules are re-evaluated | -| `onSaveResult` | A `save` command completes | -| `onSetFieldValueByPathResult` | A `setFieldValueByPath` command completes | -| `onSelectAndFocusFieldValueByPathResult` | A `selectAndFocusFieldValueByPath` command completes | -| `onDeleteFieldValueByPathResult` | A `deleteFieldValueByPath` command completes | -| `onFieldsPanelWidthChanged` | The fields panel is resized (width in px) | -| `onFieldsPanelSideChanged` | The panel moves to the other side of the viewer | -| `onWcMessage` | The element publishes a message on its bus (`ui-du-vs-wc-message`) — see below | - -> **Attention: Commands need a loaded document** -> `setFieldValueByPath`, `selectAndFocusFieldValueByPath` and `deleteFieldValueByPath` resolve their `path` against the taxonomy and the current extraction result, so one issued before those arrive fails to resolve. Gate on `onLoaded`, and wire the matching `*Result` callback — it carries the reason (`No field value found at path …`), which is otherwise invisible. - -The subcomponents report subsets of this set — see [subcomponents](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/validation-station-subcomponents.md). +> **Note: Theming** +> Add a `light` or `dark` class to ``; the widget's stylesheets key off it. `theme` and `language` default to `"light"` and English. The sample maps Action Center's theme onto both. -### Rendering your own value-indicator overlay +### From a Flow IDP node (IXP) -Hovering a value's confidence indicator opens a built-in popover. `onWcMessage` receives an `IVsWcMessage`, discriminated on `type`: `indicator-overlay-show` carries the value's confidence, thresholds, confirmation and broken-rule state (`IVsIndicatorOverlayContext`) plus the trigger's viewport rect to position against, and `indicator-overlay-hide` closes it. Hide the built-in popover with CSS, then render your own: - -```css -ui-du-validation-station-standalone-wc-element::part(indicator-overlay) { - display: none; -} -``` +Pass the `ProcessedDocument` instead of `data`, and complete the task with the validated document the widget hands back: ```tsx { - if (message.type === "indicator-overlay-show") showPopover(message.context); - else hidePopover(); - }} -/> -``` - -`message.instanceId` tells elements apart when several report to one handler. `CompactFieldsForm`, `CompactTableEditor` and `CompactBusinessRules` take `onWcMessage` too. - -### Opening a field in your taxonomy editor - -An annotation host — one that sets `options={{ intendedUse: "document-annotation" }}` — gets an _Edit instructions_ link on each prediction-diff warning. Clicking it publishes `taxonomy-field-focus-request` on the same bus, naming the field group or table (`fieldId`) and its `documentTypeId`: - -```tsx - { - if (message.type === "taxonomy-field-focus-request") - openTaxonomyField(message.documentTypeId, message.fieldId); + processedDocument={processedDocument} + onSubmit={(_request, result) => { + // The node downstream reads this document as its output. Complete with it + // verbatim, even when result.success is false: a failed record write must + // not block the review. + completeTask(result?.processedDocument); }} /> ``` -`ValidationStation` and `CompactFieldsForm` publish it; the table editor does not. Since `IVsWcMessage` gained this member, an exhaustive `switch` over `message.type` needs a new case. - -## Language enum - -`ValidationStationLanguage` provides all supported locales: - -```ts -import { ValidationStationLanguage } from "@uipath/ui-widgets-validation-station"; - -ValidationStationLanguage.English; // "en" -ValidationStationLanguage.German; // "de" -ValidationStationLanguage.Spanish; // "es" -ValidationStationLanguage.SpanishMexico; // "es-MX" -ValidationStationLanguage.French; // "fr" -ValidationStationLanguage.Japanese; // "ja" -ValidationStationLanguage.Korean; // "ko" -ValidationStationLanguage.Portuguese; // "pt" -ValidationStationLanguage.PortugueseBrazil; // "pt-BR" -ValidationStationLanguage.Romanian; // "ro" -ValidationStationLanguage.Russian; // "ru" -ValidationStationLanguage.Turkish; // "tr" -ValidationStationLanguage.ChineseSimplified; // "zh-CN" -ValidationStationLanguage.ChineseTraditional; // "zh-TW" -``` - -## Exported types - -All parameter types are re-exported from the package for convenience: - -```ts -import { - configureValidationStationWc, - DU_WC_TAGS, - joinDeploymentUrl, - VALIDATION_STATION_TAG, - ValidationStationLanguage, -} from "@uipath/ui-widgets-validation-station"; -import type { - ValidationStationProps, - ValidationStationWcConfig, - DuArtifactsSource, - ValidationStationArtifactsSource, - DuDocumentArtifacts, - IxpDocumentArtifacts, - ValidationStationArtifacts, - IXPTaxonomy, - IXPExtraction, - IXPReviewedExtraction, - ProcessedDocument, - ValidatedProcessedDocument, - DuTheme, - ValidationStationIntendedUse, - IValidationStationOptions, - FieldFilterOptions, - DocumentViewerOptions, - ICustomizationInfoDTO, - IFeatureCustomization, - IVsWcMessage, - IVsIndicatorOverlayContext, - IVsTaxonomyFieldFocusRequestMessage, - IVsSaveValidatedDataRequest, - IVsSaveValidatedDataAsDraftRequest, - IVsSaveExceptionReportRequest, - SaveValidatedDataResult, - SetFieldValueByPath, - SelectAndFocusFieldValueByPath, - DeleteFieldValueByPath, - ValidationStationEventProps, - VsStateEventProps, - VsAnyRepresentationStateEventProps, - VsSaveResultEventProps, - IFieldValueDetailsDto, - EvaluatedBusinessRulesForFieldValueDto, - ISaveResult, - SetFieldValueByPathResult, - SelectAndFocusFieldValueByPathResult, - DeleteFieldValueByPathResult, -} from "@uipath/ui-widgets-validation-station"; -``` - -`DU_WC_TAGS` and `VALIDATION_STATION_TAG` are the custom-element tag names the loader registers — useful for `document.querySelector` or asserting readiness in tests. The wrappers in this package render them for you. - -## Examples - -### Setting a field value by path - -Address fields by path when you have nested groups or table rows. Each segment is `{ fieldName, valueIndex }`. - -> **Note: Paths resolve only after the document loads** -> See [Reading the document state](#reading-the-document-state). Wire `onSetFieldValueByPathResult` while you are building this, or a mistimed command fails silently. - -```tsx -import { useState } from "react"; -import { - ValidationStation, - type SetFieldValueByPath, -} from "@uipath/ui-widgets-validation-station"; - -function App({ sdk, data }) { - const [fieldValueByPath, setFieldValueByPath] = useState< - SetFieldValueByPath | undefined - >(undefined); - - return ( - <> - - - - ); -} -``` - -### Focusing a field by path - -```tsx -import { useState } from "react"; -import { - ValidationStation, - type SelectAndFocusFieldValueByPath, -} from "@uipath/ui-widgets-validation-station"; +The full IXP behaviour, from loading drafts to the record format, is in [Data sources](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/data-sources.md#ixp-processeddocument). -function App({ sdk, data }) { - const [focus, setFocus] = useState< - SelectAndFocusFieldValueByPath | undefined - >(undefined); +### As a standalone web app - return ( - <> - - - - ); -} -``` +Outside Action Center, construct the SDK with your external application and sign in first: `new UiPath({ baseUrl, orgName, tenantName, clientId, redirectUri, scope })`, then `await sdk.initialize()` inside an effect, since under OAuth it navigates to the identity provider and back. Serve `redirectUri` from the same app. The [`document-validation-app`](https://github.com/UiPath/uipath-typescript/tree/main/samples/document-validation-app) sample is a full inbox built this way. -### Triggering save +## Saving -```tsx -const [save, setSave] = useState<{ validate: boolean } | undefined>(undefined); +The widget's own action bar offers **Submit**, **Save as draft** and **Report as exception**. Each fires one callback, with the request the web component produced and, when the widget saved it itself (①), the outcome as `result`. The widget shows no errors of its own; tell the reviewer from the callback. - - -``` +| Callback | With `sdk` + `data`, the widget… | Left to you | +| ------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| `onSubmit` | runs `ProcessExtractedData` and uploads to `ValidatedExtractionResultsPath` | **Completing the task**, and only when `result.success` is true | +| `onSaveAsDraft` | uploads the in-progress values; the next load opens on them | Telling the reviewer. Needs `options={{ emitDtoStateChanges: true }}` | +| `onReportException` | does nothing for a DU document; records a rejection for a `ProcessedDocument` | For DU, persisting it yourself, or hiding the button with `hideReportAsExceptionButton` | -## Hosting the web component +With ② (`artifacts`, no `sdk`), every callback carries only the request and the saving is yours; the exported `submitValidatedData` and `saveValidatedDataAsDraft` do what the widget would have. See [Data sources](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/data-sources.md#owning-the-round-trip). -The widgets in this package render the Validation Station **web component**, which ships as a prebuilt Angular bundle in [`@uipath/du-validation-station-wc`](https://www.npmjs.com/package/@uipath/du-validation-station-wc). The bundle is **not** imported by the package — it is loaded at runtime from a URL you host, via [`@uipath/du-utils`](https://www.npmjs.com/package/@uipath/du-utils). +**OAuth scopes.** The token needs `OR.Buckets` for a DU document, and `Traces.Api` plus `OR.Buckets.Read` for a `ProcessedDocument`. The app needs `OR.Tasks` to read and complete the task. In a Coded Action App, set them as `scope` in `uipath.json`, on an external application that grants them. -That means there is no bundler configuration to write. You need two things: +## Core props -1. Serve the contents of `node_modules/@uipath/du-validation-station-wc` as static files at `du-vs-wc`, next to your app's own root (see the default below — pass an explicit `deploymentUrl` if you host it somewhere else). -2. Call `configureValidationStationWc` once, before rendering any widget. +| Prop | Type | Description | +| ------------------------------------------------ | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `sdk` | `UiPath` | The SDK instance. Needed whenever the widget fetches or saves (①) | +| `data` | `ContentValidationData` | A Document Understanding task's payload. Wins over `processedDocument` when both are set | +| `processedDocument` | `ProcessedDocument` | A Flow IDP node's output | +| `artifacts` | `DuDocumentArtifacts \| IxpDocumentArtifacts` | The pieces you already hold (②). No fetch happens. Pass `documentId` with them | +| `theme` | `DuTheme` | `'light'` (default), `'dark'`, `'light-hc'`, `'dark-hc'`, `'future-light'`, `'future-dark'` | +| `language` | `ValidationStationLanguage` | Defaults to `ValidationStationLanguage.English` | +| `isReadonly` | `boolean` | Read-only review. Pass the task's `isReadOnly` | +| `options` | `IValidationStationOptions` | UI flags, such as `emitDtoStateChanges`, `hideReportAsExceptionButton`, `hideDiscardButton`, `fieldFilterOptions` | +| `onSubmit`, `onSaveAsDraft`, `onReportException` | `(request, result?) => void` | See [Saving](#saving) | -```ts -import { configureValidationStationWc } from "@uipath/ui-widgets-validation-station"; +Every other prop, the state callbacks (`onLoaded`, `onDirtyChange`, `onFieldValueChanged`, …) and the commands that set or focus a value by path are in [Props, events and commands](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/events-and-commands.md). -configureValidationStationWc({ - // Set true unless your app already loads Material Icons globally — - // otherwise every icon renders as its ligature text. See "Fonts" below. - includeFonts: true, -}).catch((error) => { - console.error("Validation Station web component failed to load", error); -}); -``` +## Troubleshooting -`deploymentUrl` defaults to `du-vs-wc` joined onto `getAppBase()` — `/du-vs-wc` on a plain host, or the deployed app's own base path if you are running as a UiPath Coded App. Most integrations need nothing more than the call above. Pass an explicit `deploymentUrl` only when the web component is hosted somewhere that default doesn't reach: +| Symptom | Likely cause | +| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| The widget stays on its loading state | The web component did not load: check the `.catch` on `configureValidationStationWc`, and that `du-vs-wc` is in your build | +| `basedomain query parameter is missing` | The app was opened directly, not from an Action Center task. Open it from the task | +| An error naming a missing folder (`FolderId` / `FolderKey`) | The payload has neither. Fill it from `task.folderId`, as in the quick start | +| A 401 or 403 when loading or saving | A missing scope. See [Saving](#saving) | +| **Save as draft** does nothing | `options={{ emitDtoStateChanges: true }}` is not set | +| The completed task has empty data | `completeTask` was given only part of the task's data. Pass all of it back | +| Icons render as words such as `expand_more` | Material Icons are not loaded. Pass `includeFonts: true` | +| With `artifacts`: "document format unknown not supported" | `original` is bare base64. It must be a data URI: `data:application/pdf;base64,…` | +| With `artifacts`: no line items in a DU document | The tables are in `ResultsDocument.Tables`, which is ignored. Put them in `ResultsDocument.Fields` as Table fields | +| Subcomponents: fields show "Is missing", or panels don't sync | The `instanceId`: use the same one across one document's panels, and a different one per document and per contract (DU / IXP) | -```ts -import { - configureValidationStationWc, - joinDeploymentUrl, -} from "@uipath/ui-widgets-validation-station"; +## Going further -configureValidationStationWc({ - // A literal, a build-time constant, or a resolver — see "Notes" below. - deploymentUrl: joinDeploymentUrl( - "https://cdn.example.com/my-app", - "du-vs-wc", - ), - includeFonts: true, -}); -``` +- [Data sources and the round trip](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/data-sources.md): pre-fetched artifacts, loading and saving from your own code, the prediction diff, and IXP documents in full. +- [Props, events and commands](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/events-and-commands.md): every prop and callback, setting and focusing values by path, a custom confidence popover, the language list. +- [Hosting in depth](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/hosting.md): the served folder's layout, `deploymentUrl`, fonts, CSP and version skew. +- [Subcomponents](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/docs/validation-station-subcomponents.md): build your own layout from the fields form, table editor, document viewer, business rules and document type panels. +- [Upgrading](https://github.com/UiPath/uipath-ui-widgets/blob/develop/packages/validation-station/UPGRADING.md): what each web component release changed, and moving off `1.0.x`. +- Sample apps, each with setup steps, also in the [Sample Apps Gallery](https://uipath.github.io/uipath-typescript/samples/): -`joinDeploymentUrl(base, path)` exists because hand-rolled string concatenation is an easy way to end up with a doubled or missing slash — it strips any trailing slash from `base` and any leading slash from `path` before joining them, regardless of which one supplied it (or neither). - -The served directory must keep the package's own layout, because the bundle resolves these against its own `import.meta.url`: - -``` -/du-vs-wc/ -├── main.js ← entry, plus its hashed chunk-*.js siblings -├── polyfills.js ← must load before main.js (the loader handles ordering) -├── styles.css ← fetched as raw CSS and adopted into the shadow root -├── fonts.css ← Material Icons only (opt-in via includeFonts) -├── media/ ← the font files fonts.css references -└── du-assets/ ← pdf.js scripts, cmaps, wasm decoders, translations, - the business-rules executor -``` - -Copying the package directory verbatim satisfies this. - -### Serving it with Vite - -> **Success: No `vite.config.ts` changes are needed** -> Since `1.1.0` the web component is fetched at runtime instead of imported, so it never enters the module graph. The `optimizeDeps.exclude`, asset-copy plugin and dev-server middleware that `1.0.x` required are all obsolete — delete them (see [Migrating from 1.0.x](#migrating-from-10x)). A Vite app needs nothing in its config beyond whatever it already has. - -What it does need is the package copied into `public/`, which Vite serves verbatim in dev and copies to `dist/` on build. The four samples below all do it with one script wired to the `predev` and `prebuild` hooks, so a plain `npm run dev` or `npm run build` stages it: - -```json title="package.json" -{ - "scripts": { - "stage-du-wc": "node scripts/stage-du-wc.mjs", - "predev": "npm run stage-du-wc", - "prebuild": "npm run stage-du-wc" - }, - "devDependencies": { - "@uipath/du-validation-station-wc": "1.0.0-rc.6" - } -} -``` - -The script copies `node_modules/@uipath/du-validation-station-wc` to `public/du-vs-wc` — which is exactly where the `deploymentUrl` default looks — skipping the npm metadata, verifying that `main.js`, `polyfills.js`, `styles.css`, `fonts.css` and `du-assets/` all landed, and stamping the staged version so a repeat run is a no-op. Take it as-is: [`scripts/stage-du-wc.mjs`](https://github.com/UiPath/uipath-typescript/blob/main/samples/document-validation-app/scripts/stage-du-wc.mjs). - -> **Tip: Keep `public/du-vs-wc` out of git** -> It is generated, and it is tens of megabytes — the fonts alone are most of it. Add it to `.gitignore` and let the `predev` / `prebuild` hooks produce it. - -### Fonts - -The `fonts.css` in `@uipath/du-validation-station-wc` carries **Material Icons -only** — the one font the component cannot do without. The Apollo text fonts -(Poppins, Noto Sans, Inconsolata) are not in the package, so the component's -text inherits your app's own font stack. A UiPath-styled host already loads -them; to get the UiPath typography otherwise, install -[`@uipath/apollo-fonts`](https://www.npmjs.com/package/@uipath/apollo-fonts) and -import its `font.css` in your app. That file contains Material Icons as well, so -`includeFonts` can then stay off. - -A UiPath-hosted deployment of the web component is built with the full font set, -so `includeFonts: true` against one of those links the Apollo fonts too. - -### Notes - -- **Call it once.** Loading is cached per page, so a second call with a different `deploymentUrl` is ignored. A _failed_ load is not cached — call again to retry. -- **The returned promise is the error channel.** Components only observe success; a bad URL or a 404 surfaces on the promise, so attach a `.catch`. Without it, a load failure leaves the widgets showing their loading state. -- **`du-assets/` and `media/` are outside that promise.** The loader only ever touches `polyfills.js`, `main.js`, `styles.css` and `fonts.css`; the web component fetches those two directories itself, at render time. Without `du-assets/`, PDF rendering and translations 404 silently while business-rules validation rejects outright — its executor is pulled in with a dynamic `import()`, so it fails loudly where the rest degrades quietly. Without `media/`, `fonts.css` resolves but every `url()` inside it 404s, so `includeFonts: true` loads no fonts. -- **`deploymentUrl` accepts a resolver.** Pass `() => string | Promise` instead of a plain string for cases where the URL isn't known synchronously — it is called lazily, at most once per load. -- **`deploymentUrl` is a script source.** The loader injects `