From b07861c113639b7a8bbe23002dfdd60a1e4a26e2 Mon Sep 17 00:00:00 2001 From: Hendrik de Graaf Date: Tue, 10 Nov 2026 10:54:18 +0100 Subject: [PATCH] fix(shell): keep parentAlertsAdd stable in PluginLoader receivePropsFromParent stored a new alertsAdd wrapper on every message from the host, and post-robot gives a new proxy on every message too. So every prop change on the host gave AppAdapter a new parentAlertsAdd, which changed the identity of useAlert's `show` inside plugins. Keep the latest alertsAdd in a ref and pass one stable function that calls it and returns its result. Add tests that use the real post-robot, with the test acting as the host window, and mock @dhis2/app-adapter. Co-Authored-By: Claude Opus 5.5 --- shell/package.json | 1 + shell/src/PluginLoader.jsx | 15 +++-- shell/src/PluginLoader.test.jsx | 105 ++++++++++++++++++++++++++++++++ 3 files changed, 116 insertions(+), 5 deletions(-) create mode 100644 shell/src/PluginLoader.test.jsx diff --git a/shell/package.json b/shell/package.json index 67cabc71c..78aa617d4 100644 --- a/shell/package.json +++ b/shell/package.json @@ -33,6 +33,7 @@ "analyze": "source-map-explorer 'build/assets/*.js'" }, "devDependencies": { + "@testing-library/react": "^16.0.1", "enzyme": "^3.10.0", "enzyme-adapter-react-16": "^1.14.0", "react-test-renderer": "^16.8.6", diff --git a/shell/src/PluginLoader.jsx b/shell/src/PluginLoader.jsx index 0a06cb1cf..8e38d7ceb 100644 --- a/shell/src/PluginLoader.jsx +++ b/shell/src/PluginLoader.jsx @@ -97,7 +97,15 @@ PluginInner.propTypes = { export const PluginLoader = ({ config, requiredProps, D2App }) => { const [propsFromParent, setPropsFromParent] = useState({}) const [propsThatAreMissing, setPropsThatAreMissing] = useState([]) - const [parentAlertsAdd, setParentAlertsAdd] = useState(() => () => {}) + // post-robot creates a new proxy for alertsAdd on every message from the + // host. Keep the latest one in a ref, and pass AppAdapter one function + // that calls it and never changes, so that useAlert's `show` doesn't + // change identity inside plugins + const alertsAddRef = useRef() + const parentAlertsAdd = useCallback( + (alert, alertRef) => alertsAddRef.current?.(alert, alertRef), + [] + ) const [showAlertsInPlugin, setShowAlertsInPlugin] = useState(false) const [onPluginError, setOnPluginError] = useState(() => () => {}) const [clearPluginError, setClearPluginError] = useState(() => () => {}) @@ -155,9 +163,7 @@ export const PluginLoader = ({ config, requiredProps, D2App }) => { } if (alertsAdd) { - setParentAlertsAdd( - () => (alert, alertRef) => alertsAdd(alert, alertRef) - ) + alertsAddRef.current = alertsAdd } if (showAlertsInPlugin) { @@ -185,7 +191,6 @@ export const PluginLoader = ({ config, requiredProps, D2App }) => { requiredProps, setOnPluginError, setClearPluginError, - setParentAlertsAdd, setShowAlertsInPlugin, setResizePluginHeight, setResizePluginWidth, diff --git a/shell/src/PluginLoader.test.jsx b/shell/src/PluginLoader.test.jsx new file mode 100644 index 000000000..fc1209af9 --- /dev/null +++ b/shell/src/PluginLoader.test.jsx @@ -0,0 +1,105 @@ +import { render, act, waitFor } from '@testing-library/react' +import postRobot from 'post-robot' +import React from 'react' +import { PluginLoader } from './PluginLoader.jsx' + +// Mock AppAdapter to record the props PluginLoader renders it with. +// `virtual: true` lets jest mock the adapter even if it hasn't been built, +// because its package.json `main` points at the build output +const mockAppAdapterProps = [] +jest.mock( + '@dhis2/app-adapter', + () => ({ + __esModule: true, + default: (props) => { + mockAppAdapterProps.push(props) + return null + }, + }), + { virtual: true } +) + +// The real shell passes D2App as a React.lazy component, which is an object, +// and PluginLoader's propTypes expect one. React.memo also returns an object +const MockD2App = React.memo(function MockD2App() { + return null +}) + +// The tests use the real post-robot. In jsdom the test window has no parent, +// so `window.parent === window`, and a test acts as the host by listening and +// sending on `window`. jsdom's postMessage sets neither `event.source` nor +// `event.origin`, and post-robot ignores messages without them, so replace it +// with one that sets both +const originalPostMessage = window.postMessage +beforeAll(() => { + window.postMessage = (data) => + setTimeout(() => + window.dispatchEvent( + new MessageEvent('message', { + data, + source: window, + origin: window.location.origin, + }) + ) + ) +}) +afterAll(() => { + window.postMessage = originalPostMessage +}) + +// post-robot keeps its listeners in module state, and a second listener for +// the same message name throws, so cancel the host's listener after each test +let hostListener +afterEach(() => { + hostListener?.cancel() + mockAppAdapterProps.length = 0 +}) + +const latestParentAlertsAdd = () => + mockAppAdapterProps[mockAppAdapterProps.length - 1].parentAlertsAdd + +const renderPluginLoader = async (initialProps) => { + hostListener = postRobot.on('getPropsFromParent', () => initialProps) + render() + // AppAdapter renders once on mount and again once the host's reply arrives + await waitFor(() => expect(mockAppAdapterProps.length).toBeGreaterThan(1)) +} + +const sendUpdatedFromHost = (props) => + act(() => postRobot.send(window, 'updated', props)) + +describe('parentAlertsAdd', () => { + it('keeps the same identity when the host sends a new alertsAdd', async () => { + await renderPluginLoader({ alertsAdd: jest.fn() }) + const initial = latestParentAlertsAdd() + + await sendUpdatedFromHost({ alertsAdd: jest.fn() }) + await sendUpdatedFromHost({ alertsAdd: jest.fn() }) + + expect(latestParentAlertsAdd()).toBe(initial) + }) + + it('calls the latest alertsAdd from the host and returns its result', async () => { + const firstAlertsAdd = jest.fn() + await renderPluginLoader({ alertsAdd: firstAlertsAdd }) + const parentAlertsAdd = latestParentAlertsAdd() + + const secondAlertsAdd = jest.fn(() => ({ id: 'parent-alert' })) + await sendUpdatedFromHost({ alertsAdd: secondAlertsAdd }) + + // Through post-robot, alertsAdd returns a promise of its result + const alert = { message: 'Hello' } + const alertRef = { current: null } + await expect(parentAlertsAdd(alert, alertRef)).resolves.toEqual({ + id: 'parent-alert', + }) + expect(secondAlertsAdd).toHaveBeenCalledWith(alert, alertRef) + expect(firstAlertsAdd).not.toHaveBeenCalled() + }) + + it('does nothing and returns undefined before alertsAdd has been received', async () => { + await renderPluginLoader({}) + + expect(latestParentAlertsAdd()({ message: 'Hello' })).toBeUndefined() + }) +})