From c0f84ab9e99af62abd5339ba5f935f46ea62f5c1 Mon Sep 17 00:00:00 2001 From: XnpioChV Date: Fri, 13 Dec 2024 14:37:44 -0500 Subject: [PATCH] feat: Intercept cancel button event to close Advanced Editor --- src/editors/AdvancedEditor.test.tsx | 50 +++++++++++++++++++++++++++++ src/editors/AdvancedEditor.tsx | 39 +++++++++++++++++----- 2 files changed, 81 insertions(+), 8 deletions(-) create mode 100644 src/editors/AdvancedEditor.test.tsx diff --git a/src/editors/AdvancedEditor.test.tsx b/src/editors/AdvancedEditor.test.tsx new file mode 100644 index 000000000..d070e8129 --- /dev/null +++ b/src/editors/AdvancedEditor.test.tsx @@ -0,0 +1,50 @@ +import { getConfig } from '@edx/frontend-platform'; + +import { + render, + initializeMocks, + waitFor, +} from '../testUtils'; +import AdvancedEditor from './AdvancedEditor'; + +jest.mock('../library-authoring/LibraryBlock', () => ({ + LibraryBlock: jest.fn(() => (
Advanced Editor Iframe
)), +})); + +describe('AdvancedEditor', () => { + beforeEach(() => { + initializeMocks(); + }); + + it('should call onClose when receiving "cancel-clicked" message', () => { + const onCloseMock = jest.fn(); + + render(); + + const messageEvent = new MessageEvent('message', { + data: 'cancel-clicked', + origin: getConfig().STUDIO_BASE_URL, + }); + + window.dispatchEvent(messageEvent); + + waitFor(() => { + expect(onCloseMock).toHaveBeenCalled(); + }); + }); + + it('should not call onClose if the message is from an invalid origin', () => { + const onCloseMock = jest.fn(); + + render(); + + const messageEvent = new MessageEvent('message', { + data: 'cancel-clicked', + origin: 'https://invalid-origin.com', + }); + + window.dispatchEvent(messageEvent); + + expect(onCloseMock).not.toHaveBeenCalled(); + }); +}); diff --git a/src/editors/AdvancedEditor.tsx b/src/editors/AdvancedEditor.tsx index e081a443d..60f7a6547 100644 --- a/src/editors/AdvancedEditor.tsx +++ b/src/editors/AdvancedEditor.tsx @@ -1,3 +1,6 @@ +import { useEffect } from 'react'; +import { getConfig } from '@edx/frontend-platform'; + import { LibraryBlock } from '../library-authoring/LibraryBlock'; import { EditorModalWrapper } from './containers/EditorContainer'; @@ -6,13 +9,33 @@ interface AdvancedEditorProps { onClose: Function | null, } -const AdvancedEditor = ({ usageKey, onClose }: AdvancedEditorProps) => ( - void}> - - -); +const AdvancedEditor = ({ usageKey, onClose }: AdvancedEditorProps) => { + useEffect(() => { + const handleIframeMessage = (event) => { + if (event.origin !== getConfig().STUDIO_BASE_URL) { + return; + } + + if (event.data === 'cancel-clicked' && onClose) { + onClose(); + } + }; + + window.addEventListener('message', handleIframeMessage); + + return () => { + window.removeEventListener('message', handleIframeMessage); + }; + }, []); + + return ( + void}> + + + ); +}; export default AdvancedEditor;