Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/react-18-support.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"@uipath/ui-widgets-document-viewer": minor
"@uipath/ui-widgets-validation-station": minor
"@uipath/ui-widgets-classification-station": minor
"@uipath/ui-widgets-datatable": minor
"@uipath/ui-widgets-conversational-agent-chat": minor
"@uipath/ui-widgets-decisions-and-reasons": minor
"@uipath/ui-widgets-external-auth": minor
"@uipath/ui-widgets-multi-file-upload": minor
"@uipath/ui-widgets-pdf-viewer": minor
---

Support React 18.3 hosts. The peer range is now `react@^18.3.0 || ^19.0.0`. On React 18, the Document Viewer, Validation Station (and its subcomponents) and Classification Station assign their web component's inputs as properties, as React 19 does, and remove their event listeners (and tear down a `persistent` element) on unmount.
4 changes: 4 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ jobs:
- name: Run tests with coverage
run: npm run test:coverage

- name: Run the DU widget tests on React 18
# The DU widgets support React 18 hosts (Flow); see test/vitest.react18.ts.
run: npm run test:react18

- name: Post Coverage Report to PR
if: github.event_name == 'pull_request'
env:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ Key testing principles:

## 🛠️ Tech Stack

- **React 19** - UI library
- **React 18.3 or 19** - UI library
- **TypeScript** - Type safety
- **Vite** - Build tool
- **ag-Grid** - Data grid component
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
"prepare": "husky",
"changeset": "changeset",
"version": "changeset version",
"release": "changeset publish"
"release": "changeset publish",
"test:react18": "npm ci --prefix test/react18 --no-audit --no-fund && REACT18=1 npm run test -w packages/document-viewer -w packages/validation-station -w packages/classification-station"
},
"dependencies": {
"@emotion/react": "^11.14.0",
Expand Down
4 changes: 3 additions & 1 deletion packages/classification-station/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ npm install @uipath/ui-widgets-classification-station
### Peer dependencies

```bash
npm install react@^19.2.0 react-dom@^19.2.0 @uipath/uipath-typescript@^1.5.1
npm install react react-dom @uipath/uipath-typescript@^1.5.1
```

Works with React 18.3 and React 19.

## Quick start

> **Note: Theming**
Expand Down
4 changes: 2 additions & 2 deletions packages/classification-station/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
},
"peerDependencies": {
"@uipath/uipath-typescript": "^1.5.1",
"react": "^19.2.0",
"react-dom": "^19.2.0"
"react": "^18.3.0 || ^19.0.0",
"react-dom": "^18.3.0 || ^19.0.0"
},
"devDependencies": {
"@testing-library/dom": "^10.4.0",
Expand Down
98 changes: 98 additions & 0 deletions packages/classification-station/src/WcHost.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {
useCallback,
useLayoutEffect,
useRef,
version,
type ElementType,
type ReactElement,
} from "react";
import type { WcElement, WcRefCallback } from "./bindWcEvents.js";

/**
* React 19 assigns a custom element's props as element properties; React 18
* assigns them as attributes, which turns every object input (`dom`,
* `options`, the references) into the string `"[object Object]"`.
*/
const REACT_SETS_PROPERTIES = Number.parseInt(version, 10) >= 19;

/**
* Props that stay on the rendered tag under every React version: `className`,
* `style`, and dashed names, which are attributes by design (`instance-id`).
* React 18 maps `style` on custom elements but not `className`, which it
* would write as a `classname` attribute, so it is passed as `class` there.
*/
function isAttributeProp(key: string): boolean {
return key === "className" || key === "style" || key.includes("-");
}

/**
* The inputs last assigned to each element, keyed by the element itself, so a
* ref that detaches and re-attaches to the same element (a new `elementRef`)
* does not re-assign unchanged inputs.
*/
const assignedInputs = new WeakMap<Element, Record<string, unknown>>();

export interface WcHostProps {
tag: string;
props: Record<string, unknown>;
elementRef: WcRefCallback;
}

/**
* Renders a custom element so that its inputs arrive as properties on React
* 18 and 19.
*
* On React 19 every prop goes on the tag, and React assigns it as a property
* before the element connects. On React 18 only the attribute props go on the
* tag; the rest are assigned as properties in a layout effect, in the order of
* `props`' keys, after the element connects and before the browser paints.
* Only values that changed since the last commit are assigned, and a prop the
* host stops passing goes back to `undefined` before the others are assigned,
* as React 19 does.
*/
export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement {
const elementState = useRef<WcElement | null>(null);

const ref = useCallback(
(el: WcElement | null) => {
elementState.current = el;
elementRef(el);
},
[elementRef],
);

useLayoutEffect(() => {
if (REACT_SETS_PROPERTIES) return;
const el = elementState.current;
if (!el) return;
let assigned = assignedInputs.get(el);
if (!assigned) {
assigned = {};
assignedInputs.set(el, assigned);
}
const target = el as unknown as Record<string, unknown>;
// Clear removed inputs first, as React 19 does, so the last input in
// `props` (Classification Station's `documentId`) still arrives last.
for (const key of Object.keys(assigned)) {
if (!(key in props)) {
target[key] = undefined;
delete assigned[key];
}
}
for (const [key, value] of Object.entries(props)) {
if (isAttributeProp(key) || assigned[key] === value) continue;
target[key] = value;
assigned[key] = value;
}
});

// The tag is a custom element name, which JSX cannot type statically.
const Tag = tag as unknown as ElementType;
if (REACT_SETS_PROPERTIES) return <Tag {...props} ref={ref} />;
const attributes = Object.fromEntries(
Object.entries(props)
.filter(([key]) => isAttributeProp(key))
.map(([key, value]) => [key === "className" ? "class" : key, value]),
);
return <Tag {...attributes} ref={ref} />;
}
119 changes: 119 additions & 0 deletions packages/classification-station/src/__tests__/WcHost.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";

// Take WcHost's React 18 path on the workspace's React 19: it branches on
// React's `version`, read once at import. `npm run test:react18` runs the same
// path on a real React 18.
vi.mock("react", async (importOriginal) => ({
...(await importOriginal<typeof import("react")>()),
version: "18.3.1",
}));

const { WcHost } = await import("../WcHost");

const TAG = "wc-host-test-element";
const OTHER_TAG = "wc-host-test-other-element";

class Recorder extends HTMLElement {
assigned: Array<[string, unknown]> = [];
}
for (const key of ["dom", "options", "documentId", "theme"]) {
Object.defineProperty(Recorder.prototype, key, {
get(this: any) {
return this[`_${key}`];
},
set(this: any, value: unknown) {
this.assigned.push([key, value]);
this[`_${key}`] = value;
},
});
}
for (const tag of [TAG, OTHER_TAG]) {
if (!customElements.get(tag))
customElements.define(tag, class extends Recorder {});
}

const host = (
tag: string,
props: Record<string, unknown>,
elementRef = vi.fn(),
) => <WcHost tag={tag} props={props} elementRef={elementRef} />;

describe("WcHost on React 18", () => {
it("assigns inputs as properties in key order, keeping className, style and dashed names on the tag", () => {
const dom = { Pages: [] };
const { container } = render(
host(TAG, {
className: "c",
style: { height: "10px" },
"instance-id": "i1",
dom,
theme: "dark",
documentId: "d1",
}),
);
const el = container.querySelector(TAG) as Recorder;

expect(el.assigned).toEqual([
["dom", dom],
["theme", "dark"],
["documentId", "d1"],
]);
expect(el.getAttribute("class")).toBe("c");
expect(el.style.height).toBe("10px");
expect(el.getAttribute("instance-id")).toBe("i1");
expect(el.hasAttribute("dom")).toBe(false);
});

it("re-assigns only changed inputs, and resets a removed one to undefined", () => {
const dom = { Pages: [] };
const { container, rerender } = render(host(TAG, { dom, theme: "dark" }));
const el = container.querySelector(TAG) as Recorder;
el.assigned = [];

const options = { a: 1 };
rerender(host(TAG, { dom, options }));

expect(el.assigned).toEqual([
["theme", undefined],
["options", options],
]);
});

it("clears a dropped input before assigning the next document's id", () => {
const { container, rerender } = render(
host(TAG, { dom: { Pages: [1] }, options: { a: 1 }, documentId: "d1" }),
);
const el = container.querySelector(TAG) as Recorder;
el.assigned = [];

const nextDom = { Pages: [2] };
rerender(host(TAG, { dom: nextDom, documentId: "d2" }));

expect(el.assigned).toEqual([
["options", undefined],
["dom", nextDom],
["documentId", "d2"],
]);
});

it("assigns every input afresh to a new element when the tag changes", () => {
const dom = { Pages: [] };
const { container, rerender } = render(host(TAG, { dom }));
rerender(host(OTHER_TAG, { dom }));
const el = container.querySelector(OTHER_TAG) as Recorder;

expect(el.assigned).toEqual([["dom", dom]]);
});

it("hands the element, then null on unmount, to the element ref", () => {
const elementRef = vi.fn();
const { container, unmount } = render(host(TAG, {}, elementRef));
const el = container.querySelector(TAG);

expect(elementRef).toHaveBeenLastCalledWith(el);
unmount();
expect(elementRef).toHaveBeenLastCalledWith(null);
});
});
13 changes: 11 additions & 2 deletions packages/classification-station/src/bindWcEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useCallback, useEffect, useRef } from "react";
export type WcElement = HTMLElement & { forceDestroy?: () => void };

/** React ref-callback shape for a standalone DU element. */
export type WcRefCallback = (el: WcElement | null) => void | (() => void);
export type WcRefCallback = (el: WcElement | null) => void;

type WcHandlers<EventMap> = {
[K in keyof EventMap]?: (detail: EventMap[K]) => void;
Expand Down Expand Up @@ -50,6 +50,10 @@ function bindWcEvents<EventMap>(
* and, on detach, removes them and — when `persistent` — calls `forceDestroy()`
* to tear down the inner Angular component.
*
* Detach is handled on the `null` call rather than through a returned cleanup:
* React 18 ignores a ref callback's return value, and React 19 still calls a
* ref callback with `null` when it returns nothing, so this works on both.
*
* The callback identity changes only when `persistent` changes, so React does
* not detach/re-attach — and never force-destroys a persistent element — on an
* ordinary re-render. (A fresh callback each render, as a plain factory would
Expand All @@ -67,11 +71,16 @@ export function useWcRef<EventMap>(
handlersRef.current = handlers;
});

// The teardown for the element currently attached, run on the next call.
const detachRef = useRef<(() => void) | null>(null);

return useCallback<WcRefCallback>(
(el) => {
detachRef.current?.();
detachRef.current = null;
if (!el) return;
const unbind = bindWcEvents<EventMap>(el, () => handlersRef.current);
return () => {
detachRef.current = () => {
unbind();
if (persistent) el.forceDestroy?.();
};
Expand Down
9 changes: 5 additions & 4 deletions packages/classification-station/src/renderWc.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { createElement, type CSSProperties, type ReactElement } from "react";
import type { WcRefCallback } from "./bindWcEvents.js";
import { WcHost } from "./WcHost.js";

/**
* Renders a custom element by tag name with the given (typed) JSX props and
* ref callback.
* ref callback, on React 18 or 19 (see {@link WcHost}).
*
* Rendering by string tag (rather than a computed JSX component) keeps the
* element out of React's component identity, so its inner Angular component is
* not torn down and recreated on every parent render. React 19 assigns the
* props as element properties, in the order of `props`' keys.
* not torn down and recreated on every parent render. `WcHost` is a single
* module-level component, so it does not change that.
*
* Unset (`undefined`) props are left out rather than assigned, so an input the
* host did not pass keeps the element's own default (`enableTokenFeatures`
Expand All @@ -22,7 +23,7 @@ export function renderWcElement<Props extends object>(
const defined = Object.fromEntries(
Object.entries(props).filter(([, value]) => value !== undefined),
);
return createElement(tag, { ...defined, ref });
return createElement(WcHost, { tag, props: defined, elementRef: ref });
}

/**
Expand Down
Loading
Loading