From e69df056193b0285830078bf9caea38db5d58c02 Mon Sep 17 00:00:00 2001 From: Sergiu Bologa Date: Thu, 26 Nov 2026 11:14:48 +0200 Subject: [PATCH 1/3] feat(du): support React 18.3 hosts in the DU widgets React 18 sets a custom element's props as attributes, so the Document Viewer, Validation Station (and subcomponents) and Classification Station received `dom`, `options` and the references as "[object Object]". It also ignores a ref callback's returned cleanup, so listeners leaked and a persistent element was never force-destroyed. - WcHost renders the element: on React 19 unchanged; on React 18 it assigns the non-attribute props as properties in a layout effect, in key order. - useWcRef tears down on the null ref call, which both versions make. - Peer range react/react-dom ^18.3.0 || ^19.0.0 on all nine packages. - `npm run test:react18` runs the three DU suites against React 18 (test/react18), also in CI. Co-Authored-By: Claude Opus 5.5 --- .changeset/react-18-support.md | 13 +++ .github/workflows/test.yml | 4 + README.md | 2 +- package.json | 3 +- packages/classification-station/README.md | 4 +- packages/classification-station/package.json | 4 +- .../classification-station/src/WcHost.tsx | 85 +++++++++++++++++++ .../src/bindWcEvents.ts | 13 ++- .../classification-station/src/renderWc.ts | 9 +- .../classification-station/vitest.config.ts | 70 ++++++++------- packages/conversational-agent-chat/README.md | 4 +- .../conversational-agent-chat/package.json | 4 +- packages/datatable/README.md | 4 +- packages/datatable/package.json | 4 +- packages/decisions-and-reasons/package.json | 4 +- packages/document-viewer/README.md | 4 +- packages/document-viewer/package.json | 4 +- packages/document-viewer/src/WcHost.tsx | 85 +++++++++++++++++++ packages/document-viewer/src/bindWcEvents.ts | 13 ++- packages/document-viewer/src/renderWc.ts | 9 +- packages/document-viewer/vitest.config.ts | 64 +++++++------- packages/external-auth/README.md | 4 +- packages/external-auth/package.json | 4 +- packages/multi-file-upload/README.md | 4 +- packages/multi-file-upload/package.json | 4 +- packages/pdf-viewer/README.md | 4 +- packages/pdf-viewer/package.json | 4 +- packages/validation-station/README.md | 4 +- packages/validation-station/package.json | 4 +- packages/validation-station/src/WcHost.tsx | 85 +++++++++++++++++++ .../src/__tests__/shared.test.tsx | 14 +-- .../src/__tests__/subcomponents.test.tsx | 18 +++- .../validation-station/src/bindWcEvents.ts | 13 ++- .../src/subcomponents/shared.ts | 12 ++- packages/validation-station/vitest.config.ts | 79 +++++++++-------- test/react18/package-lock.json | 66 ++++++++++++++ test/react18/package.json | 9 ++ test/vitest.react18.ts | 41 +++++++++ 38 files changed, 622 insertions(+), 153 deletions(-) create mode 100644 .changeset/react-18-support.md create mode 100644 packages/classification-station/src/WcHost.tsx create mode 100644 packages/document-viewer/src/WcHost.tsx create mode 100644 packages/validation-station/src/WcHost.tsx create mode 100644 test/react18/package-lock.json create mode 100644 test/react18/package.json create mode 100644 test/vitest.react18.ts diff --git a/.changeset/react-18-support.md b/.changeset/react-18-support.md new file mode 100644 index 00000000..73de3b94 --- /dev/null +++ b/.changeset/react-18-support.md @@ -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. diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index cc4c1b85..14ce2aaf 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -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: diff --git a/README.md b/README.md index daf03d2b..edfa3417 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/package.json b/package.json index c17abe84..b58403e7 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/packages/classification-station/README.md b/packages/classification-station/README.md index b78e09f4..de1284df 100644 --- a/packages/classification-station/README.md +++ b/packages/classification-station/README.md @@ -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** diff --git a/packages/classification-station/package.json b/packages/classification-station/package.json index 9e16e309..7d54875d 100644 --- a/packages/classification-station/package.json +++ b/packages/classification-station/package.json @@ -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", diff --git a/packages/classification-station/src/WcHost.tsx b/packages/classification-station/src/WcHost.tsx new file mode 100644 index 00000000..582a3a3e --- /dev/null +++ b/packages/classification-station/src/WcHost.tsx @@ -0,0 +1,85 @@ +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` + * and `style` (React 18 maps both correctly on custom elements) and dashed + * names, which are attributes by design (`instance-id`). + */ +function isAttributeProp(key: string): boolean { + return key === "className" || key === "style" || key.includes("-"); +} + +export interface WcHostProps { + tag: string; + props: Record; + 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`, as React 19 does. + */ +export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { + const elementState = useRef<{ + el: WcElement | null; + assigned: Record; + }>({ el: null, assigned: {} }); + + const ref = useCallback( + (el: WcElement | null) => { + if (elementState.current.el !== el) { + elementState.current = { el, assigned: {} }; + } + elementRef(el); + }, + [elementRef], + ); + + useLayoutEffect(() => { + if (REACT_SETS_PROPERTIES) return; + const { el, assigned } = elementState.current; + if (!el) return; + const target = el as unknown as Record; + for (const [key, value] of Object.entries(props)) { + if (isAttributeProp(key) || assigned[key] === value) continue; + target[key] = value; + assigned[key] = value; + } + for (const key of Object.keys(assigned)) { + if (!(key in props)) { + target[key] = undefined; + delete assigned[key]; + } + } + }); + + // The tag is a custom element name, which JSX cannot type statically. + const Tag = tag as unknown as ElementType; + if (REACT_SETS_PROPERTIES) return ; + const attributes = Object.fromEntries( + Object.entries(props).filter(([key]) => isAttributeProp(key)), + ); + return ; +} diff --git a/packages/classification-station/src/bindWcEvents.ts b/packages/classification-station/src/bindWcEvents.ts index 267a013a..526d17a4 100644 --- a/packages/classification-station/src/bindWcEvents.ts +++ b/packages/classification-station/src/bindWcEvents.ts @@ -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 = { [K in keyof EventMap]?: (detail: EventMap[K]) => void; @@ -50,6 +50,10 @@ function bindWcEvents( * 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 @@ -67,11 +71,16 @@ export function useWcRef( handlersRef.current = handlers; }); + // The teardown for the element currently attached, run on the next call. + const detachRef = useRef<(() => void) | null>(null); + return useCallback( (el) => { + detachRef.current?.(); + detachRef.current = null; if (!el) return; const unbind = bindWcEvents(el, () => handlersRef.current); - return () => { + detachRef.current = () => { unbind(); if (persistent) el.forceDestroy?.(); }; diff --git a/packages/classification-station/src/renderWc.ts b/packages/classification-station/src/renderWc.ts index e5d6ede3..68788260 100644 --- a/packages/classification-station/src/renderWc.ts +++ b/packages/classification-station/src/renderWc.ts @@ -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` @@ -22,7 +23,7 @@ export function renderWcElement( const defined = Object.fromEntries( Object.entries(props).filter(([, value]) => value !== undefined), ); - return createElement(tag, { ...defined, ref }); + return createElement(WcHost, { tag, props: defined, elementRef: ref }); } /** diff --git a/packages/classification-station/vitest.config.ts b/packages/classification-station/vitest.config.ts index de8cc372..15a285e8 100644 --- a/packages/classification-station/vitest.config.ts +++ b/packages/classification-station/vitest.config.ts @@ -1,38 +1,42 @@ -import { defineConfig } from "vitest/config"; +import { defineConfig, mergeConfig } from "vitest/config"; import react from "@vitejs/plugin-react"; import path from "path"; +import { react18Overrides } from "../../test/vitest.react18"; -export default defineConfig({ - plugins: [react()], - test: { - globals: true, - environment: "jsdom", - setupFiles: ["./test/setup.ts"], - coverage: { - provider: "v8", - reporter: ["text", "json", "json-summary", "html", "lcov"], - exclude: [ - "node_modules/", - "**/__tests__/", - "**/*.spec.ts", - "**/*.spec.tsx", - "**/*.test.ts", - "**/*.test.tsx", - "**/dist/", - "**/*.config.{js,ts}", - "**/index.ts", - "**/*.stories.tsx", - "**/types.ts", - ], - include: ["src/**/*.{ts,tsx}"], +export default mergeConfig( + defineConfig({ + plugins: [react()], + test: { + globals: true, + environment: "jsdom", + setupFiles: ["./test/setup.ts"], + coverage: { + provider: "v8", + reporter: ["text", "json", "json-summary", "html", "lcov"], + exclude: [ + "node_modules/", + "**/__tests__/", + "**/*.spec.ts", + "**/*.spec.tsx", + "**/*.test.ts", + "**/*.test.tsx", + "**/dist/", + "**/*.config.{js,ts}", + "**/index.ts", + "**/*.stories.tsx", + "**/types.ts", + ], + include: ["src/**/*.{ts,tsx}"], + }, }, - }, - resolve: { - alias: { - "@uipath/ui-widgets-classification-station": path.resolve( - __dirname, - "./src", - ), + resolve: { + alias: { + "@uipath/ui-widgets-classification-station": path.resolve( + __dirname, + "./src", + ), + }, }, - }, -}); + }), + react18Overrides(), +); diff --git a/packages/conversational-agent-chat/README.md b/packages/conversational-agent-chat/README.md index ffeb08d5..e8b8160d 100644 --- a/packages/conversational-agent-chat/README.md +++ b/packages/conversational-agent-chat/README.md @@ -21,9 +21,11 @@ npm install @uipath/ui-widgets-conversational-agent-chat ### Peer dependencies ```bash -npm install react@^19.2.0 react-dom@^19.2.0 @uipath/uipath-typescript@^1.5.5 +npm install react react-dom @uipath/uipath-typescript@^1.5.5 ``` +Works with React 18.3 and React 19. + ## Usage > **Note: Theming** diff --git a/packages/conversational-agent-chat/package.json b/packages/conversational-agent-chat/package.json index 33bd4f8a..421540ae 100644 --- a/packages/conversational-agent-chat/package.json +++ b/packages/conversational-agent-chat/package.json @@ -43,8 +43,8 @@ "registry": "https://npm.pkg.github.com" }, "peerDependencies": { - "react": "^19.2.0", - "react-dom": "^19.2.0", + "react": "^18.3.0 || ^19.0.0", + "react-dom": "^18.3.0 || ^19.0.0", "@uipath/uipath-typescript": "^1.8.3" }, "devDependencies": { diff --git a/packages/datatable/README.md b/packages/datatable/README.md index 818f4338..002602f6 100644 --- a/packages/datatable/README.md +++ b/packages/datatable/README.md @@ -23,9 +23,11 @@ npm install @uipath/ui-widgets-datatable ### Peer dependencies ```bash -npm install react@^19.2.0 react-dom@^19.2.0 @uipath/uipath-typescript@^1.7.1 +npm install react react-dom @uipath/uipath-typescript@^1.7.1 ``` +Works with React 18.3 and React 19. + ## Usage > **Note: Theming** diff --git a/packages/datatable/package.json b/packages/datatable/package.json index 06de7bd2..7f61fb68 100644 --- a/packages/datatable/package.json +++ b/packages/datatable/package.json @@ -43,8 +43,8 @@ }, "peerDependencies": { "@uipath/uipath-typescript": "^1.7.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": { "rimraf": "^6.0.1", diff --git a/packages/decisions-and-reasons/package.json b/packages/decisions-and-reasons/package.json index cb3f8dc1..65e85d70 100644 --- a/packages/decisions-and-reasons/package.json +++ b/packages/decisions-and-reasons/package.json @@ -50,8 +50,8 @@ }, "homepage": "https://uipath.github.io/uipath-ui-widgets/?path=/docs/components-caseassessment--docs", "peerDependencies": { - "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": { "rimraf": "^6.0.1", diff --git a/packages/document-viewer/README.md b/packages/document-viewer/README.md index fc42ec0a..b3160985 100644 --- a/packages/document-viewer/README.md +++ b/packages/document-viewer/README.md @@ -13,9 +13,11 @@ npm install @uipath/ui-widgets-document-viewer ### 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 The viewer is a web component that this package loads at runtime, so it needs two things before it renders: its files hosted next to your app, and one call to `configureDocumentViewerWc`. diff --git a/packages/document-viewer/package.json b/packages/document-viewer/package.json index ad753e0b..d9ec59a6 100644 --- a/packages/document-viewer/package.json +++ b/packages/document-viewer/package.json @@ -43,8 +43,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", diff --git a/packages/document-viewer/src/WcHost.tsx b/packages/document-viewer/src/WcHost.tsx new file mode 100644 index 00000000..582a3a3e --- /dev/null +++ b/packages/document-viewer/src/WcHost.tsx @@ -0,0 +1,85 @@ +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` + * and `style` (React 18 maps both correctly on custom elements) and dashed + * names, which are attributes by design (`instance-id`). + */ +function isAttributeProp(key: string): boolean { + return key === "className" || key === "style" || key.includes("-"); +} + +export interface WcHostProps { + tag: string; + props: Record; + 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`, as React 19 does. + */ +export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { + const elementState = useRef<{ + el: WcElement | null; + assigned: Record; + }>({ el: null, assigned: {} }); + + const ref = useCallback( + (el: WcElement | null) => { + if (elementState.current.el !== el) { + elementState.current = { el, assigned: {} }; + } + elementRef(el); + }, + [elementRef], + ); + + useLayoutEffect(() => { + if (REACT_SETS_PROPERTIES) return; + const { el, assigned } = elementState.current; + if (!el) return; + const target = el as unknown as Record; + for (const [key, value] of Object.entries(props)) { + if (isAttributeProp(key) || assigned[key] === value) continue; + target[key] = value; + assigned[key] = value; + } + for (const key of Object.keys(assigned)) { + if (!(key in props)) { + target[key] = undefined; + delete assigned[key]; + } + } + }); + + // The tag is a custom element name, which JSX cannot type statically. + const Tag = tag as unknown as ElementType; + if (REACT_SETS_PROPERTIES) return ; + const attributes = Object.fromEntries( + Object.entries(props).filter(([key]) => isAttributeProp(key)), + ); + return ; +} diff --git a/packages/document-viewer/src/bindWcEvents.ts b/packages/document-viewer/src/bindWcEvents.ts index 267a013a..526d17a4 100644 --- a/packages/document-viewer/src/bindWcEvents.ts +++ b/packages/document-viewer/src/bindWcEvents.ts @@ -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 = { [K in keyof EventMap]?: (detail: EventMap[K]) => void; @@ -50,6 +50,10 @@ function bindWcEvents( * 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 @@ -67,11 +71,16 @@ export function useWcRef( handlersRef.current = handlers; }); + // The teardown for the element currently attached, run on the next call. + const detachRef = useRef<(() => void) | null>(null); + return useCallback( (el) => { + detachRef.current?.(); + detachRef.current = null; if (!el) return; const unbind = bindWcEvents(el, () => handlersRef.current); - return () => { + detachRef.current = () => { unbind(); if (persistent) el.forceDestroy?.(); }; diff --git a/packages/document-viewer/src/renderWc.ts b/packages/document-viewer/src/renderWc.ts index e5d6ede3..68788260 100644 --- a/packages/document-viewer/src/renderWc.ts +++ b/packages/document-viewer/src/renderWc.ts @@ -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` @@ -22,7 +23,7 @@ export function renderWcElement( const defined = Object.fromEntries( Object.entries(props).filter(([, value]) => value !== undefined), ); - return createElement(tag, { ...defined, ref }); + return createElement(WcHost, { tag, props: defined, elementRef: ref }); } /** diff --git a/packages/document-viewer/vitest.config.ts b/packages/document-viewer/vitest.config.ts index 3c48bd91..aaf87f5c 100644 --- a/packages/document-viewer/vitest.config.ts +++ b/packages/document-viewer/vitest.config.ts @@ -1,35 +1,39 @@ -import { defineConfig } from "vitest/config"; +import { defineConfig, mergeConfig } from "vitest/config"; import react from "@vitejs/plugin-react"; import path from "path"; +import { react18Overrides } from "../../test/vitest.react18"; -export default defineConfig({ - plugins: [react()], - test: { - globals: true, - environment: "jsdom", - setupFiles: ["./test/setup.ts"], - coverage: { - provider: "v8", - reporter: ["text", "json", "json-summary", "html", "lcov"], - exclude: [ - "node_modules/", - "**/__tests__/", - "**/*.spec.ts", - "**/*.spec.tsx", - "**/*.test.ts", - "**/*.test.tsx", - "**/dist/", - "**/*.config.{js,ts}", - "**/index.ts", - "**/*.stories.tsx", - "**/types.ts", - ], - include: ["src/**/*.{ts,tsx}"], +export default mergeConfig( + defineConfig({ + plugins: [react()], + test: { + globals: true, + environment: "jsdom", + setupFiles: ["./test/setup.ts"], + coverage: { + provider: "v8", + reporter: ["text", "json", "json-summary", "html", "lcov"], + exclude: [ + "node_modules/", + "**/__tests__/", + "**/*.spec.ts", + "**/*.spec.tsx", + "**/*.test.ts", + "**/*.test.tsx", + "**/dist/", + "**/*.config.{js,ts}", + "**/index.ts", + "**/*.stories.tsx", + "**/types.ts", + ], + include: ["src/**/*.{ts,tsx}"], + }, }, - }, - resolve: { - alias: { - "@uipath/ui-widgets-document-viewer": path.resolve(__dirname, "./src"), + resolve: { + alias: { + "@uipath/ui-widgets-document-viewer": path.resolve(__dirname, "./src"), + }, }, - }, -}); + }), + react18Overrides(), +); diff --git a/packages/external-auth/README.md b/packages/external-auth/README.md index 428a6638..40a6d1e1 100644 --- a/packages/external-auth/README.md +++ b/packages/external-auth/README.md @@ -25,9 +25,11 @@ npm install @uipath/ui-widgets-external-auth ### Peer dependencies ```bash -npm install react@^19.2.0 react-dom@^19.2.0 @uipath/uipath-typescript@^1.4.1 +npm install react react-dom @uipath/uipath-typescript@^1.4.1 ``` +Works with React 18.3 and React 19. + The package declares the SDK as a peer dependency for consistency with the other widgets, even though this one makes no UiPath calls of its own. ## Usage diff --git a/packages/external-auth/package.json b/packages/external-auth/package.json index 56517b5f..9b3299ec 100644 --- a/packages/external-auth/package.json +++ b/packages/external-auth/package.json @@ -52,8 +52,8 @@ "homepage": "https://uipath.github.io/uipath-ui-widgets/?path=/docs/components-externalauth--docs", "peerDependencies": { "@uipath/uipath-typescript": "^1.4.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": { "rimraf": "^6.0.1", diff --git a/packages/multi-file-upload/README.md b/packages/multi-file-upload/README.md index 8e8ac26b..f69f3511 100644 --- a/packages/multi-file-upload/README.md +++ b/packages/multi-file-upload/README.md @@ -20,9 +20,11 @@ npm install @uipath/ui-widgets-multi-file-upload ### Peer dependencies ```bash -npm install react@^19.2.0 react-dom@^19.2.0 @uipath/uipath-typescript@^1.4.1 +npm install react react-dom @uipath/uipath-typescript@^1.4.1 ``` +Works with React 18.3 and React 19. + > **Warning: The published 1.0.0 pins an older SDK** > `@uipath/ui-widgets-multi-file-upload@1.0.0` — currently the only published version — declares an exact peer of `@uipath/uipath-typescript@1.1.1`, which the range above does not satisfy, so npm reports an unmet peer dependency. The `^1.4.1` above is what the widget is built against today and what the next release will carry. diff --git a/packages/multi-file-upload/package.json b/packages/multi-file-upload/package.json index a8cb9415..c3e9b029 100644 --- a/packages/multi-file-upload/package.json +++ b/packages/multi-file-upload/package.json @@ -49,8 +49,8 @@ }, "homepage": "https://uipath.github.io/uipath-ui-widgets/?path=/docs/components-multifileupload--docs", "peerDependencies": { - "react": "^19.2.0", - "react-dom": "^19.2.0", + "react": "^18.3.0 || ^19.0.0", + "react-dom": "^18.3.0 || ^19.0.0", "@uipath/uipath-typescript": "^1.4.1" }, "devDependencies": { diff --git a/packages/pdf-viewer/README.md b/packages/pdf-viewer/README.md index 485d8201..78933d19 100644 --- a/packages/pdf-viewer/README.md +++ b/packages/pdf-viewer/README.md @@ -13,9 +13,11 @@ npm install @uipath/ui-widgets-pdf-viewer ### Peer dependencies ```bash -npm install react@^19.2.0 react-dom@^19.2.0 @uipath/uipath-typescript@^1.7.1 +npm install react react-dom @uipath/uipath-typescript@^1.7.1 ``` +Works with React 18.3 and React 19. + ## Usage diff --git a/packages/pdf-viewer/package.json b/packages/pdf-viewer/package.json index 7c81f053..fcf8ed08 100644 --- a/packages/pdf-viewer/package.json +++ b/packages/pdf-viewer/package.json @@ -53,8 +53,8 @@ }, "homepage": "https://uipath.github.io/uipath-ui-widgets/?path=/docs/components-pdfviewer--docs", "peerDependencies": { - "react": "^19.2.0", - "react-dom": "^19.2.0", + "react": "^18.3.0 || ^19.0.0", + "react-dom": "^18.3.0 || ^19.0.0", "@uipath/uipath-typescript": "^1.7.1" }, "devDependencies": { diff --git a/packages/validation-station/README.md b/packages/validation-station/README.md index 55a4440c..f628666d 100644 --- a/packages/validation-station/README.md +++ b/packages/validation-station/README.md @@ -11,9 +11,11 @@ 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 +npm install react react-dom @uipath/uipath-typescript@^1.5.1 ``` +Works with React 18.3 and React 19. + ## Quick start > **Note: Theming** diff --git a/packages/validation-station/package.json b/packages/validation-station/package.json index 99ecf281..986b9252 100644 --- a/packages/validation-station/package.json +++ b/packages/validation-station/package.json @@ -43,8 +43,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": { "@tailwindcss/oxide": "^4.1.18", diff --git a/packages/validation-station/src/WcHost.tsx b/packages/validation-station/src/WcHost.tsx new file mode 100644 index 00000000..582a3a3e --- /dev/null +++ b/packages/validation-station/src/WcHost.tsx @@ -0,0 +1,85 @@ +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` + * and `style` (React 18 maps both correctly on custom elements) and dashed + * names, which are attributes by design (`instance-id`). + */ +function isAttributeProp(key: string): boolean { + return key === "className" || key === "style" || key.includes("-"); +} + +export interface WcHostProps { + tag: string; + props: Record; + 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`, as React 19 does. + */ +export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { + const elementState = useRef<{ + el: WcElement | null; + assigned: Record; + }>({ el: null, assigned: {} }); + + const ref = useCallback( + (el: WcElement | null) => { + if (elementState.current.el !== el) { + elementState.current = { el, assigned: {} }; + } + elementRef(el); + }, + [elementRef], + ); + + useLayoutEffect(() => { + if (REACT_SETS_PROPERTIES) return; + const { el, assigned } = elementState.current; + if (!el) return; + const target = el as unknown as Record; + for (const [key, value] of Object.entries(props)) { + if (isAttributeProp(key) || assigned[key] === value) continue; + target[key] = value; + assigned[key] = value; + } + for (const key of Object.keys(assigned)) { + if (!(key in props)) { + target[key] = undefined; + delete assigned[key]; + } + } + }); + + // The tag is a custom element name, which JSX cannot type statically. + const Tag = tag as unknown as ElementType; + if (REACT_SETS_PROPERTIES) return ; + const attributes = Object.fromEntries( + Object.entries(props).filter(([key]) => isAttributeProp(key)), + ); + return ; +} diff --git a/packages/validation-station/src/__tests__/shared.test.tsx b/packages/validation-station/src/__tests__/shared.test.tsx index 95919f3d..53423581 100644 --- a/packages/validation-station/src/__tests__/shared.test.tsx +++ b/packages/validation-station/src/__tests__/shared.test.tsx @@ -21,13 +21,13 @@ describe("wcStyle", () => { }); describe("renderWcElement", () => { - it("creates an element of the given tag with props and ref", () => { + it("returns a React element carrying the tag, props and ref", () => { const ref = vi.fn(); const el = renderWcElement("my-tag", { theme: "dark" } as any, ref); expect(isValidElement(el)).toBe(true); - expect(el.type).toBe("my-tag"); - expect((el.props as any).theme).toBe("dark"); - expect((el.props as any).ref).toBe(ref); + expect((el.props as any).tag).toBe("my-tag"); + expect((el.props as any).props).toEqual({ theme: "dark" }); + expect((el.props as any).elementRef).toBe(ref); }); it("renders into the DOM as the requested tag, forwarding props and ref", () => { @@ -41,9 +41,11 @@ describe("renderWcElement", () => { ); const el = container.querySelector("my-tag"); expect(el).toBeInTheDocument(); - // Props must actually land on the element, not just the tag be present. + // Dashed names stay attributes on every React version. expect(el!.getAttribute("instance-id")).toBe("i1"); - expect(el!.getAttribute("theme")).toBe("dark"); + // The undefined element does not declare `theme`, so React 19 sets it as + // an attribute; React 18 (through `WcHost`) assigns it as a property. + expect((el as any).theme ?? el!.getAttribute("theme")).toBe("dark"); // The ref callback receives the real element (this is how event binding attaches). expect(ref).toHaveBeenCalledWith(el); }); diff --git a/packages/validation-station/src/__tests__/subcomponents.test.tsx b/packages/validation-station/src/__tests__/subcomponents.test.tsx index f07dc7f2..40dc17ce 100644 --- a/packages/validation-station/src/__tests__/subcomponents.test.tsx +++ b/packages/validation-station/src/__tests__/subcomponents.test.tsx @@ -74,6 +74,18 @@ const mockArtifacts = { original: undefined, }; +/** + * Reads an input the wrapper handed the element. React 18 (through `WcHost`) + * assigns every input as a property; React 19 assigns it as a property only + * when the element declares it, else as a lower-cased attribute. These stubs + * declare only the object inputs, so a string input lands either way. + */ +function readInput(el: Element, key: string): unknown { + return key in el + ? (el as unknown as Record)[key] + : el.getAttribute(key.toLowerCase()); +} + // React assigns an object prop as a property only when the element already // declares one (otherwise it stringifies it into an attribute), so stand in for // the real elements' artifact inputs on the three IXP-capable tags. Defined @@ -176,8 +188,8 @@ describe.each(cases)("$name", ({ Component, tag }) => { // instanceId → kebab attribute; theme passes through; documentId comes from // the resolved artifacts state, not the caller — proves the wiring end to end. expect(el.getAttribute("instance-id")).toBe("i1"); - expect(el.getAttribute("theme")).toBe("dark"); - expect(el.getAttribute("documentid")).toBe("doc-123"); + expect(readInput(el, "theme")).toBe("dark"); + expect(readInput(el, "documentId")).toBe("doc-123"); }); it("renders the persistent variant when persistent is set", () => { @@ -501,7 +513,7 @@ describe("DocumentViewer IXP document inputs", () => { expect(el.dom).toBe(ixpArtifacts.dom); expect(el.document).toBe(ixpArtifacts.original); - expect(el.getAttribute("text")).toBe(ixpArtifacts.text); + expect(readInput(el, "text")).toBe(ixpArtifacts.text); }); }); diff --git a/packages/validation-station/src/bindWcEvents.ts b/packages/validation-station/src/bindWcEvents.ts index 267a013a..526d17a4 100644 --- a/packages/validation-station/src/bindWcEvents.ts +++ b/packages/validation-station/src/bindWcEvents.ts @@ -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 = { [K in keyof EventMap]?: (detail: EventMap[K]) => void; @@ -50,6 +50,10 @@ function bindWcEvents( * 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 @@ -67,11 +71,16 @@ export function useWcRef( handlersRef.current = handlers; }); + // The teardown for the element currently attached, run on the next call. + const detachRef = useRef<(() => void) | null>(null); + return useCallback( (el) => { + detachRef.current?.(); + detachRef.current = null; if (!el) return; const unbind = bindWcEvents(el, () => handlersRef.current); - return () => { + detachRef.current = () => { unbind(); if (persistent) el.forceDestroy?.(); }; diff --git a/packages/validation-station/src/subcomponents/shared.ts b/packages/validation-station/src/subcomponents/shared.ts index 7b81c68f..34686b08 100644 --- a/packages/validation-station/src/subcomponents/shared.ts +++ b/packages/validation-station/src/subcomponents/shared.ts @@ -1,14 +1,16 @@ import { createElement, type CSSProperties, type ReactElement } from "react"; import type { WcRefCallback } from "../bindWcEvents.js"; +import { WcHost } from "../WcHost.js"; import type { ValidationStationArtifacts } from "../types.js"; /** * Renders a standalone DU custom element by tag name with the given (typed) - * JSX props and ref callback. + * JSX props and 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. `Props` is the web + * not torn down and recreated on every parent render. `WcHost` is a single + * module-level component, so it does not change that. `Props` is the web * component's JSX prop interface, so the caller's props object is fully * type-checked at construction. */ @@ -17,7 +19,11 @@ export function renderWcElement( props: Props, ref: WcRefCallback, ): ReactElement { - return createElement(tag, { ...props, ref }); + return createElement(WcHost, { + tag, + props: props as Record, + elementRef: ref, + }); } /** diff --git a/packages/validation-station/vitest.config.ts b/packages/validation-station/vitest.config.ts index 870d4075..7b1d02f5 100644 --- a/packages/validation-station/vitest.config.ts +++ b/packages/validation-station/vitest.config.ts @@ -1,42 +1,49 @@ -import { defineConfig } from "vitest/config"; +import { defineConfig, mergeConfig } from "vitest/config"; import react from "@vitejs/plugin-react"; import path from "path"; +import { react18Overrides } from "../../test/vitest.react18"; -export default defineConfig({ - plugins: [react()], - test: { - globals: true, - environment: "jsdom", - setupFiles: ["./test/setup.ts"], - coverage: { - provider: "v8", - reporter: ["text", "json", "json-summary", "html", "lcov"], - exclude: [ - "node_modules/", - "**/__tests__/", - "**/*.spec.ts", - "**/*.spec.tsx", - "**/*.test.ts", - "**/*.test.tsx", - "**/dist/", - "**/*.config.{js,ts}", - "**/index.ts", - "**/*.scss", - "**/*.stories.tsx", - "**/types.ts", - ], - include: ["src/**/*.{ts,tsx}"], +export default mergeConfig( + defineConfig({ + plugins: [react()], + test: { + globals: true, + environment: "jsdom", + setupFiles: ["./test/setup.ts"], + coverage: { + provider: "v8", + reporter: ["text", "json", "json-summary", "html", "lcov"], + exclude: [ + "node_modules/", + "**/__tests__/", + "**/*.spec.ts", + "**/*.spec.tsx", + "**/*.test.ts", + "**/*.test.tsx", + "**/dist/", + "**/*.config.{js,ts}", + "**/index.ts", + "**/*.scss", + "**/*.stories.tsx", + "**/types.ts", + ], + include: ["src/**/*.{ts,tsx}"], + }, }, - }, - resolve: { - alias: { - "@uipath/ui-widgets-validation-station": path.resolve(__dirname, "./src"), - "@uipath/validation-station": path.resolve(__dirname, "./src"), + resolve: { + alias: { + "@uipath/ui-widgets-validation-station": path.resolve( + __dirname, + "./src", + ), + "@uipath/validation-station": path.resolve(__dirname, "./src"), + }, }, - }, - css: { - modules: { - classNameStrategy: "non-scoped", + css: { + modules: { + classNameStrategy: "non-scoped", + }, }, - }, -}); + }), + react18Overrides(), +); diff --git a/test/react18/package-lock.json b/test/react18/package-lock.json new file mode 100644 index 00000000..c2ba3e96 --- /dev/null +++ b/test/react18/package-lock.json @@ -0,0 +1,66 @@ +{ + "name": "react18-test-runtime", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "react18-test-runtime", + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + } + } +} diff --git a/test/react18/package.json b/test/react18/package.json new file mode 100644 index 00000000..d47d42b5 --- /dev/null +++ b/test/react18/package.json @@ -0,0 +1,9 @@ +{ + "name": "react18-test-runtime", + "private": true, + "description": "React 18 runtime the DU widget tests run against with REACT18=1 (see vitest.react18.ts). Kept outside the workspaces: React 18 cannot share their dependency tree with React 19.", + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1" + } +} diff --git a/test/vitest.react18.ts b/test/vitest.react18.ts new file mode 100644 index 00000000..481a485f --- /dev/null +++ b/test/vitest.react18.ts @@ -0,0 +1,41 @@ +import path from "path"; +import type { UserConfig } from "vitest/config"; + +const runtime = path.resolve(__dirname, "react18/node_modules"); +const testingLibrary = path.resolve( + __dirname, + "../node_modules/@testing-library/react/dist/@testing-library", +); + +/** + * With `REACT18=1`, runs a package's tests against React 18 instead of the + * workspace's React 19: `react` and `react-dom` (and their subpaths) resolve to + * `test/react18`, and Testing Library is loaded from its ESM build and inlined + * so it imports the same copy. + * Run `npm ci --prefix test/react18` first. + */ +export function react18Overrides(): Pick { + if (!process.env.REACT18) return {}; + return { + resolve: { + alias: [ + // The CommonJS build would `require` the workspace's React 19. + { + find: /^@testing-library\/react$/, + replacement: `${testingLibrary}/react.esm.js`, + }, + { + find: /^@testing-library\/react\/pure$/, + replacement: `${testingLibrary}/react.pure.esm.js`, + }, + { find: /^react$/, replacement: `${runtime}/react` }, + { find: /^react\/(.*)$/, replacement: `${runtime}/react/$1` }, + { find: /^react-dom$/, replacement: `${runtime}/react-dom` }, + { find: /^react-dom\/(.*)$/, replacement: `${runtime}/react-dom/$1` }, + ], + }, + test: { + server: { deps: { inline: [/@testing-library\/react/] } }, + }, + }; +} From 3ae167e9d3a1f8f0bc5fceff9d69b5b788e4c22f Mon Sep 17 00:00:00 2001 From: Sergiu Bologa Date: Thu, 26 Nov 2026 13:24:47 +0200 Subject: [PATCH 2/3] fix(du): pass className as class on React 18 and cover WcHost's React 18 path - React 18 writes `className` on a custom element as a `classname` attribute, so the host's class was lost; WcHost now passes it as `class`. - The inputs already assigned are tracked per element (WeakMap), so a ref that re-attaches to the same element does not re-assign unchanged inputs. - WcHost.test.tsx mocks React's version to run the React 18 path inside the normal (coverage) run. Co-Authored-By: Claude Opus 5.5 --- .../classification-station/src/WcHost.tsx | 34 +++--- .../src/__tests__/WcHost.test.tsx | 102 ++++++++++++++++++ packages/document-viewer/src/WcHost.tsx | 34 +++--- .../src/__tests__/WcHost.test.tsx | 102 ++++++++++++++++++ packages/validation-station/src/WcHost.tsx | 34 +++--- .../src/__tests__/WcHost.test.tsx | 102 ++++++++++++++++++ 6 files changed, 372 insertions(+), 36 deletions(-) create mode 100644 packages/classification-station/src/__tests__/WcHost.test.tsx create mode 100644 packages/document-viewer/src/__tests__/WcHost.test.tsx create mode 100644 packages/validation-station/src/__tests__/WcHost.test.tsx diff --git a/packages/classification-station/src/WcHost.tsx b/packages/classification-station/src/WcHost.tsx index 582a3a3e..74d08d40 100644 --- a/packages/classification-station/src/WcHost.tsx +++ b/packages/classification-station/src/WcHost.tsx @@ -16,14 +16,22 @@ import type { WcElement, WcRefCallback } from "./bindWcEvents.js"; const REACT_SETS_PROPERTIES = Number.parseInt(version, 10) >= 19; /** - * Props that stay on the rendered tag under every React version: `className` - * and `style` (React 18 maps both correctly on custom elements) and dashed - * names, which are attributes by design (`instance-id`). + * 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>(); + export interface WcHostProps { tag: string; props: Record; @@ -42,16 +50,11 @@ export interface WcHostProps { * host stops passing goes back to `undefined`, as React 19 does. */ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { - const elementState = useRef<{ - el: WcElement | null; - assigned: Record; - }>({ el: null, assigned: {} }); + const elementState = useRef(null); const ref = useCallback( (el: WcElement | null) => { - if (elementState.current.el !== el) { - elementState.current = { el, assigned: {} }; - } + elementState.current = el; elementRef(el); }, [elementRef], @@ -59,8 +62,13 @@ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { useLayoutEffect(() => { if (REACT_SETS_PROPERTIES) return; - const { el, assigned } = elementState.current; + 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; for (const [key, value] of Object.entries(props)) { if (isAttributeProp(key) || assigned[key] === value) continue; @@ -79,7 +87,9 @@ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { const Tag = tag as unknown as ElementType; if (REACT_SETS_PROPERTIES) return ; const attributes = Object.fromEntries( - Object.entries(props).filter(([key]) => isAttributeProp(key)), + Object.entries(props) + .filter(([key]) => isAttributeProp(key)) + .map(([key, value]) => [key === "className" ? "class" : key, value]), ); return ; } diff --git a/packages/classification-station/src/__tests__/WcHost.test.tsx b/packages/classification-station/src/__tests__/WcHost.test.tsx new file mode 100644 index 00000000..ef179d66 --- /dev/null +++ b/packages/classification-station/src/__tests__/WcHost.test.tsx @@ -0,0 +1,102 @@ +/* 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()), + 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, + elementRef = vi.fn(), +) => ; + +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([ + ["options", options], + ["theme", undefined], + ]); + }); + + 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); + }); +}); diff --git a/packages/document-viewer/src/WcHost.tsx b/packages/document-viewer/src/WcHost.tsx index 582a3a3e..74d08d40 100644 --- a/packages/document-viewer/src/WcHost.tsx +++ b/packages/document-viewer/src/WcHost.tsx @@ -16,14 +16,22 @@ import type { WcElement, WcRefCallback } from "./bindWcEvents.js"; const REACT_SETS_PROPERTIES = Number.parseInt(version, 10) >= 19; /** - * Props that stay on the rendered tag under every React version: `className` - * and `style` (React 18 maps both correctly on custom elements) and dashed - * names, which are attributes by design (`instance-id`). + * 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>(); + export interface WcHostProps { tag: string; props: Record; @@ -42,16 +50,11 @@ export interface WcHostProps { * host stops passing goes back to `undefined`, as React 19 does. */ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { - const elementState = useRef<{ - el: WcElement | null; - assigned: Record; - }>({ el: null, assigned: {} }); + const elementState = useRef(null); const ref = useCallback( (el: WcElement | null) => { - if (elementState.current.el !== el) { - elementState.current = { el, assigned: {} }; - } + elementState.current = el; elementRef(el); }, [elementRef], @@ -59,8 +62,13 @@ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { useLayoutEffect(() => { if (REACT_SETS_PROPERTIES) return; - const { el, assigned } = elementState.current; + 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; for (const [key, value] of Object.entries(props)) { if (isAttributeProp(key) || assigned[key] === value) continue; @@ -79,7 +87,9 @@ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { const Tag = tag as unknown as ElementType; if (REACT_SETS_PROPERTIES) return ; const attributes = Object.fromEntries( - Object.entries(props).filter(([key]) => isAttributeProp(key)), + Object.entries(props) + .filter(([key]) => isAttributeProp(key)) + .map(([key, value]) => [key === "className" ? "class" : key, value]), ); return ; } diff --git a/packages/document-viewer/src/__tests__/WcHost.test.tsx b/packages/document-viewer/src/__tests__/WcHost.test.tsx new file mode 100644 index 00000000..ef179d66 --- /dev/null +++ b/packages/document-viewer/src/__tests__/WcHost.test.tsx @@ -0,0 +1,102 @@ +/* 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()), + 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, + elementRef = vi.fn(), +) => ; + +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([ + ["options", options], + ["theme", undefined], + ]); + }); + + 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); + }); +}); diff --git a/packages/validation-station/src/WcHost.tsx b/packages/validation-station/src/WcHost.tsx index 582a3a3e..74d08d40 100644 --- a/packages/validation-station/src/WcHost.tsx +++ b/packages/validation-station/src/WcHost.tsx @@ -16,14 +16,22 @@ import type { WcElement, WcRefCallback } from "./bindWcEvents.js"; const REACT_SETS_PROPERTIES = Number.parseInt(version, 10) >= 19; /** - * Props that stay on the rendered tag under every React version: `className` - * and `style` (React 18 maps both correctly on custom elements) and dashed - * names, which are attributes by design (`instance-id`). + * 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>(); + export interface WcHostProps { tag: string; props: Record; @@ -42,16 +50,11 @@ export interface WcHostProps { * host stops passing goes back to `undefined`, as React 19 does. */ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { - const elementState = useRef<{ - el: WcElement | null; - assigned: Record; - }>({ el: null, assigned: {} }); + const elementState = useRef(null); const ref = useCallback( (el: WcElement | null) => { - if (elementState.current.el !== el) { - elementState.current = { el, assigned: {} }; - } + elementState.current = el; elementRef(el); }, [elementRef], @@ -59,8 +62,13 @@ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { useLayoutEffect(() => { if (REACT_SETS_PROPERTIES) return; - const { el, assigned } = elementState.current; + 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; for (const [key, value] of Object.entries(props)) { if (isAttributeProp(key) || assigned[key] === value) continue; @@ -79,7 +87,9 @@ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { const Tag = tag as unknown as ElementType; if (REACT_SETS_PROPERTIES) return ; const attributes = Object.fromEntries( - Object.entries(props).filter(([key]) => isAttributeProp(key)), + Object.entries(props) + .filter(([key]) => isAttributeProp(key)) + .map(([key, value]) => [key === "className" ? "class" : key, value]), ); return ; } diff --git a/packages/validation-station/src/__tests__/WcHost.test.tsx b/packages/validation-station/src/__tests__/WcHost.test.tsx new file mode 100644 index 00000000..ef179d66 --- /dev/null +++ b/packages/validation-station/src/__tests__/WcHost.test.tsx @@ -0,0 +1,102 @@ +/* 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()), + 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, + elementRef = vi.fn(), +) => ; + +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([ + ["options", options], + ["theme", undefined], + ]); + }); + + 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); + }); +}); From 779e2615d52d4a343bd90e4405138f5377914e4f Mon Sep 17 00:00:00 2001 From: Sergiu Bologa Date: Thu, 26 Nov 2026 14:25:18 +0200 Subject: [PATCH 3/3] fix(du): clear removed inputs before assigning the rest on React 18 Classification Station needs documentId to arrive last. WcHost cleared a dropped input (pageUris, customizationInfo) only after assigning the new documentId, so a document switch could reach the element with the previous document's input still set. Clear removed inputs first, as React 19 does. Co-Authored-By: Claude Opus 5.5 --- .../classification-station/src/WcHost.tsx | 15 +++++++++------ .../src/__tests__/WcHost.test.tsx | 19 ++++++++++++++++++- packages/document-viewer/src/WcHost.tsx | 15 +++++++++------ .../src/__tests__/WcHost.test.tsx | 19 ++++++++++++++++++- packages/validation-station/src/WcHost.tsx | 15 +++++++++------ .../src/__tests__/WcHost.test.tsx | 19 ++++++++++++++++++- 6 files changed, 81 insertions(+), 21 deletions(-) diff --git a/packages/classification-station/src/WcHost.tsx b/packages/classification-station/src/WcHost.tsx index 74d08d40..61a4b5c3 100644 --- a/packages/classification-station/src/WcHost.tsx +++ b/packages/classification-station/src/WcHost.tsx @@ -47,7 +47,8 @@ export interface WcHostProps { * 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`, as React 19 does. + * 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(null); @@ -70,17 +71,19 @@ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { assignedInputs.set(el, assigned); } const target = el as unknown as Record; - for (const [key, value] of Object.entries(props)) { - if (isAttributeProp(key) || assigned[key] === value) continue; - target[key] = value; - assigned[key] = value; - } + // 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. diff --git a/packages/classification-station/src/__tests__/WcHost.test.tsx b/packages/classification-station/src/__tests__/WcHost.test.tsx index ef179d66..d960a4d5 100644 --- a/packages/classification-station/src/__tests__/WcHost.test.tsx +++ b/packages/classification-station/src/__tests__/WcHost.test.tsx @@ -76,8 +76,25 @@ describe("WcHost on React 18", () => { rerender(host(TAG, { dom, options })); expect(el.assigned).toEqual([ - ["options", options], ["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"], ]); }); diff --git a/packages/document-viewer/src/WcHost.tsx b/packages/document-viewer/src/WcHost.tsx index 74d08d40..61a4b5c3 100644 --- a/packages/document-viewer/src/WcHost.tsx +++ b/packages/document-viewer/src/WcHost.tsx @@ -47,7 +47,8 @@ export interface WcHostProps { * 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`, as React 19 does. + * 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(null); @@ -70,17 +71,19 @@ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { assignedInputs.set(el, assigned); } const target = el as unknown as Record; - for (const [key, value] of Object.entries(props)) { - if (isAttributeProp(key) || assigned[key] === value) continue; - target[key] = value; - assigned[key] = value; - } + // 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. diff --git a/packages/document-viewer/src/__tests__/WcHost.test.tsx b/packages/document-viewer/src/__tests__/WcHost.test.tsx index ef179d66..d960a4d5 100644 --- a/packages/document-viewer/src/__tests__/WcHost.test.tsx +++ b/packages/document-viewer/src/__tests__/WcHost.test.tsx @@ -76,8 +76,25 @@ describe("WcHost on React 18", () => { rerender(host(TAG, { dom, options })); expect(el.assigned).toEqual([ - ["options", options], ["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"], ]); }); diff --git a/packages/validation-station/src/WcHost.tsx b/packages/validation-station/src/WcHost.tsx index 74d08d40..61a4b5c3 100644 --- a/packages/validation-station/src/WcHost.tsx +++ b/packages/validation-station/src/WcHost.tsx @@ -47,7 +47,8 @@ export interface WcHostProps { * 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`, as React 19 does. + * 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(null); @@ -70,17 +71,19 @@ export function WcHost({ tag, props, elementRef }: WcHostProps): ReactElement { assignedInputs.set(el, assigned); } const target = el as unknown as Record; - for (const [key, value] of Object.entries(props)) { - if (isAttributeProp(key) || assigned[key] === value) continue; - target[key] = value; - assigned[key] = value; - } + // 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. diff --git a/packages/validation-station/src/__tests__/WcHost.test.tsx b/packages/validation-station/src/__tests__/WcHost.test.tsx index ef179d66..d960a4d5 100644 --- a/packages/validation-station/src/__tests__/WcHost.test.tsx +++ b/packages/validation-station/src/__tests__/WcHost.test.tsx @@ -76,8 +76,25 @@ describe("WcHost on React 18", () => { rerender(host(TAG, { dom, options })); expect(el.assigned).toEqual([ - ["options", options], ["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"], ]); });