@capillarytech/creatives-library 9.2.0 → 9.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AppRoot.js CHANGED
@@ -14,6 +14,7 @@ import { translationMessages } from './i18n';
14
14
  import initialState from './initialState';
15
15
  import pathConfig from './config/path';
16
16
  import { isMFEMode } from './utils/mfeDetect';
17
+ import { loadBeePlugin } from './utils/beePluginLoader';
17
18
  import { emitFirstPaintReadyIfNotDataLanding } from './utils/mfeFirstPaintReady';
18
19
  import rebaseHistory from './utils/mfeHistory';
19
20
  import { MFEEventBus } from '@capillarytech/cap-ui-utils';
@@ -86,14 +87,10 @@ const AppRoot = ({ basename: _basename = '/creatives/ui', history: hostHistory }
86
87
  }
87
88
  }, []);
88
89
 
89
- // In MFE mode the HOST's index.html is served, not creatives' — so BeePlugin.js
90
- // (declared in creatives/index.html) is never loaded. Inject it here so BeeEditor works.
90
+ // Preload BeePlugin.js in MFE mode (host index.html lacks it); the editors also load it on demand
91
91
  useEffect(() => {
92
- if (isMFEMode() && !window.BeePlugin && !document.querySelector('script[src*="BeePlugin.js"]')) {
93
- const script = document.createElement('script');
94
- script.src = 'https://app-rsrc.getbee.io/plugin/BeePlugin.js';
95
- script.type = 'text/javascript';
96
- document.head.appendChild(script);
92
+ if (isMFEMode()) {
93
+ loadBeePlugin().catch(() => {});
97
94
  }
98
95
  }, []);
99
96
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capillarytech/creatives-library",
3
3
  "author": "meharaj",
4
- "version": "9.2.0",
4
+ "version": "9.2.1",
5
5
  "description": "Capillary creatives ui",
6
6
  "main": "./index.js",
7
7
  "module": "./index.es.js",
@@ -0,0 +1,106 @@
1
+ export const BEE_PLUGIN_SCRIPT_URL = 'https://app-rsrc.getbee.io/plugin/BeePlugin.js';
2
+ export const BEE_PLUGIN_LOAD_TIMEOUT_MS = 30000;
3
+
4
+ let beePluginPromise = null;
5
+
6
+ // Hosts consuming creatives as a library or MFE may not ship BeePlugin.js, so load it on demand
7
+ export const loadBeePlugin = () => {
8
+ if (window.BeePlugin) {
9
+ return Promise.resolve(window.BeePlugin);
10
+ }
11
+ if (beePluginPromise) {
12
+ return beePluginPromise;
13
+ }
14
+ beePluginPromise = new Promise((resolve, reject) => {
15
+ const existingScript = document.querySelector('script[src*="BeePlugin.js"]');
16
+ const script = existingScript || document.createElement('script');
17
+ let timeoutId = null;
18
+ const fail = (error) => {
19
+ clearTimeout(timeoutId);
20
+ beePluginPromise = null;
21
+ // Drop the tag so a retry injects a fresh one instead of waiting on a dead script
22
+ script.remove();
23
+ reject(error);
24
+ };
25
+ const onLoad = () => {
26
+ if (window.BeePlugin) {
27
+ clearTimeout(timeoutId);
28
+ resolve(window.BeePlugin);
29
+ return;
30
+ }
31
+ fail(new Error('BeePlugin.js loaded but window.BeePlugin is undefined'));
32
+ };
33
+ const onError = () => fail(new Error(`Failed to load ${BEE_PLUGIN_SCRIPT_URL}`));
34
+ timeoutId = setTimeout(
35
+ () => fail(new Error(`Timed out loading ${BEE_PLUGIN_SCRIPT_URL}`)),
36
+ BEE_PLUGIN_LOAD_TIMEOUT_MS,
37
+ );
38
+ script.addEventListener('load', onLoad, { once: true });
39
+ script.addEventListener('error', onError, { once: true });
40
+ if (!existingScript) {
41
+ script.src = BEE_PLUGIN_SCRIPT_URL;
42
+ script.type = 'text/javascript';
43
+ script.async = true;
44
+ document.head.appendChild(script);
45
+ }
46
+ });
47
+ return beePluginPromise;
48
+ };
49
+
50
+ // Tears down an editor that will not be used; destroy can throw if BEE never finished mounting
51
+ export const destroyBeeInstance = (instance) => {
52
+ try {
53
+ if (typeof instance?.destroy === 'function') {
54
+ instance.destroy();
55
+ }
56
+ } catch (error) {
57
+ console.warn('[beePluginLoader] Error destroying BEE plugin:', error);
58
+ }
59
+ };
60
+
61
+ // Creates a BEE editor and starts it with the template JSON (string or object) returned by getBeeJson
62
+ export const startBeePlugin = (BeePlugin, {
63
+ tokenData, beeConfig, getBeeJson, isCancelled = () => false,
64
+ }) => new Promise((resolve, reject) => {
65
+ BeePlugin.create(tokenData, beeConfig, (instance) => {
66
+ // create calls back asynchronously; never start an obsolete editor into the shared container
67
+ if (isCancelled()) {
68
+ destroyBeeInstance(instance);
69
+ resolve(null);
70
+ return;
71
+ }
72
+ try {
73
+ const beeJson = getBeeJson();
74
+ instance.start(typeof beeJson === 'string' ? JSON.parse(beeJson) : beeJson);
75
+ resolve(instance);
76
+ } catch (error) {
77
+ destroyBeeInstance(instance);
78
+ reject(error);
79
+ }
80
+ });
81
+ });
82
+
83
+ // Loads BeePlugin.js and starts the editor; resolves null when the caller was cleaned up in the meantime
84
+ export const initBeeEditor = ({
85
+ tokenData,
86
+ beeConfig,
87
+ getBeeJson,
88
+ isCancelled,
89
+ onPluginLoaded = () => {},
90
+ }) => loadBeePlugin()
91
+ .then((BeePlugin) => {
92
+ if (isCancelled()) {
93
+ return null;
94
+ }
95
+ onPluginLoaded();
96
+ return startBeePlugin(BeePlugin, {
97
+ tokenData, beeConfig, getBeeJson, isCancelled,
98
+ });
99
+ })
100
+ .then((instance) => {
101
+ if (instance && isCancelled()) {
102
+ destroyBeeInstance(instance);
103
+ return null;
104
+ }
105
+ return instance;
106
+ });
@@ -0,0 +1,199 @@
1
+ const SCRIPT_SELECTOR = 'script[src*="BeePlugin.js"]';
2
+
3
+ const getLoader = () => {
4
+ let loader;
5
+ jest.isolateModules(() => {
6
+ // Fresh module per test so the cached script promise does not leak between tests
7
+ // eslint-disable-next-line global-require
8
+ loader = require('../beePluginLoader');
9
+ });
10
+ return loader;
11
+ };
12
+
13
+ describe('loadBeePlugin', () => {
14
+ const mockBeePlugin = { create: jest.fn() };
15
+
16
+ beforeEach(() => {
17
+ delete window.BeePlugin;
18
+ document.head.innerHTML = '';
19
+ });
20
+
21
+ afterEach(() => {
22
+ jest.useRealTimers();
23
+ delete window.BeePlugin;
24
+ });
25
+
26
+ it('resolves immediately without injecting a script when BeePlugin is already loaded', async () => {
27
+ window.BeePlugin = mockBeePlugin;
28
+ const { loadBeePlugin } = getLoader();
29
+ await expect(loadBeePlugin()).resolves.toBe(mockBeePlugin);
30
+ expect(document.querySelector(SCRIPT_SELECTOR)).toBeNull();
31
+ });
32
+
33
+ it('injects the script once and resolves when it loads', async () => {
34
+ const { loadBeePlugin, BEE_PLUGIN_SCRIPT_URL } = getLoader();
35
+ const firstLoad = loadBeePlugin();
36
+ const secondLoad = loadBeePlugin();
37
+ const scripts = document.querySelectorAll(SCRIPT_SELECTOR);
38
+ expect(scripts).toHaveLength(1);
39
+ expect(scripts[0].src).toBe(BEE_PLUGIN_SCRIPT_URL);
40
+ expect(secondLoad).toBe(firstLoad);
41
+ window.BeePlugin = mockBeePlugin;
42
+ scripts[0].dispatchEvent(new Event('load'));
43
+ await expect(firstLoad).resolves.toBe(mockBeePlugin);
44
+ });
45
+
46
+ it('waits on a host-provided script instead of injecting another', async () => {
47
+ const hostScript = document.createElement('script');
48
+ hostScript.src = 'https://app-rsrc.getbee.io/plugin/BeePlugin.js';
49
+ document.head.appendChild(hostScript);
50
+ const { loadBeePlugin } = getLoader();
51
+ const load = loadBeePlugin();
52
+ expect(document.querySelectorAll(SCRIPT_SELECTOR)).toHaveLength(1);
53
+ window.BeePlugin = mockBeePlugin;
54
+ hostScript.dispatchEvent(new Event('load'));
55
+ await expect(load).resolves.toBe(mockBeePlugin);
56
+ });
57
+
58
+ it('rejects on script error, removes the tag and allows a retry', async () => {
59
+ const { loadBeePlugin } = getLoader();
60
+ const failedLoad = loadBeePlugin();
61
+ document.querySelector(SCRIPT_SELECTOR).dispatchEvent(new Event('error'));
62
+ await expect(failedLoad).rejects.toThrow('Failed to load');
63
+ expect(document.querySelector(SCRIPT_SELECTOR)).toBeNull();
64
+
65
+ const retryLoad = loadBeePlugin();
66
+ expect(retryLoad).not.toBe(failedLoad);
67
+ window.BeePlugin = mockBeePlugin;
68
+ document.querySelector(SCRIPT_SELECTOR).dispatchEvent(new Event('load'));
69
+ await expect(retryLoad).resolves.toBe(mockBeePlugin);
70
+ });
71
+
72
+ it('rejects when the script loads but does not define BeePlugin', async () => {
73
+ const { loadBeePlugin } = getLoader();
74
+ const load = loadBeePlugin();
75
+ document.querySelector(SCRIPT_SELECTOR).dispatchEvent(new Event('load'));
76
+ await expect(load).rejects.toThrow('window.BeePlugin is undefined');
77
+ });
78
+
79
+ it('rejects after the timeout when the script never settles', async () => {
80
+ jest.useFakeTimers();
81
+ const { loadBeePlugin, BEE_PLUGIN_LOAD_TIMEOUT_MS } = getLoader();
82
+ const load = loadBeePlugin();
83
+ jest.advanceTimersByTime(BEE_PLUGIN_LOAD_TIMEOUT_MS);
84
+ await expect(load).rejects.toThrow('Timed out');
85
+ expect(document.querySelector(SCRIPT_SELECTOR)).toBeNull();
86
+ });
87
+ });
88
+
89
+ describe('startBeePlugin', () => {
90
+ const tokenData = { access_token: 'token' };
91
+ const beeConfig = { uid: 'uid' };
92
+ let instance;
93
+ let BeePlugin;
94
+
95
+ beforeEach(() => {
96
+ instance = { start: jest.fn(), destroy: jest.fn() };
97
+ BeePlugin = { create: jest.fn((token, config, onCreated) => onCreated(instance)) };
98
+ });
99
+
100
+ it('creates the editor and starts it with parsed JSON when given a string', async () => {
101
+ const { startBeePlugin } = getLoader();
102
+ const result = await startBeePlugin(BeePlugin, { tokenData, beeConfig, getBeeJson: () => '{"page":{}}' });
103
+ expect(BeePlugin.create).toHaveBeenCalledWith(tokenData, beeConfig, expect.any(Function));
104
+ expect(instance.start).toHaveBeenCalledWith({ page: {} });
105
+ expect(result).toBe(instance);
106
+ });
107
+
108
+ it('starts the editor with an object template as-is', async () => {
109
+ const { startBeePlugin } = getLoader();
110
+ const template = { page: { rows: [] } };
111
+ await startBeePlugin(BeePlugin, { tokenData, beeConfig, getBeeJson: () => template });
112
+ expect(instance.start).toHaveBeenCalledWith(template);
113
+ });
114
+
115
+ it('rejects without starting when the template JSON is invalid', async () => {
116
+ const { startBeePlugin } = getLoader();
117
+ await expect(
118
+ startBeePlugin(BeePlugin, { tokenData, beeConfig, getBeeJson: () => '{invalid' }),
119
+ ).rejects.toThrow(SyntaxError);
120
+ expect(instance.start).not.toHaveBeenCalled();
121
+ expect(instance.destroy).toHaveBeenCalledTimes(1);
122
+ });
123
+ });
124
+
125
+ describe('destroyBeeInstance', () => {
126
+ it('destroys the editor and tolerates a missing or failing destroy', () => {
127
+ const { destroyBeeInstance } = getLoader();
128
+ const instance = { destroy: jest.fn() };
129
+ destroyBeeInstance(instance);
130
+ expect(instance.destroy).toHaveBeenCalledTimes(1);
131
+
132
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
133
+ expect(() => destroyBeeInstance({ destroy: () => { throw new Error('not mounted'); } })).not.toThrow();
134
+ expect(() => destroyBeeInstance(undefined)).not.toThrow();
135
+ warn.mockRestore();
136
+ });
137
+ });
138
+
139
+ describe('initBeeEditor', () => {
140
+ const tokenData = { access_token: 'token' };
141
+ const beeConfig = { uid: 'uid' };
142
+ let instance;
143
+
144
+ beforeEach(() => {
145
+ instance = { start: jest.fn(), destroy: jest.fn() };
146
+ window.BeePlugin = { create: jest.fn((token, config, onCreated) => onCreated(instance)) };
147
+ });
148
+
149
+ afterEach(() => {
150
+ delete window.BeePlugin;
151
+ });
152
+
153
+ it('loads the plugin, reports it, and resolves the started editor', async () => {
154
+ const { initBeeEditor } = getLoader();
155
+ const onPluginLoaded = jest.fn();
156
+ const result = await initBeeEditor({
157
+ tokenData, beeConfig, getBeeJson: () => '{"page":{}}', isCancelled: () => false, onPluginLoaded,
158
+ });
159
+ expect(onPluginLoaded).toHaveBeenCalledTimes(1);
160
+ expect(instance.start).toHaveBeenCalledWith({ page: {} });
161
+ expect(result).toBe(instance);
162
+ });
163
+
164
+ it('does not create the editor when cancelled before the plugin loads', async () => {
165
+ const { initBeeEditor } = getLoader();
166
+ const result = await initBeeEditor({
167
+ tokenData, beeConfig, getBeeJson: () => '{}', isCancelled: () => true,
168
+ });
169
+ expect(window.BeePlugin.create).not.toHaveBeenCalled();
170
+ expect(result).toBeNull();
171
+ });
172
+
173
+ it('destroys an editor created after cancellation without starting it', async () => {
174
+ const { initBeeEditor } = getLoader();
175
+ let cancelled = false;
176
+ window.BeePlugin.create.mockImplementation((token, config, onCreated) => {
177
+ cancelled = true;
178
+ onCreated(instance);
179
+ });
180
+ const result = await initBeeEditor({
181
+ tokenData, beeConfig, getBeeJson: () => '{}', isCancelled: () => cancelled,
182
+ });
183
+ expect(instance.start).not.toHaveBeenCalled();
184
+ expect(instance.destroy).toHaveBeenCalledTimes(1);
185
+ expect(result).toBeNull();
186
+ });
187
+
188
+ it('destroys an editor cancelled after it started', async () => {
189
+ const { initBeeEditor } = getLoader();
190
+ let cancelled = false;
191
+ instance.start.mockImplementation(() => { cancelled = true; });
192
+ const result = await initBeeEditor({
193
+ tokenData, beeConfig, getBeeJson: () => '{}', isCancelled: () => cancelled,
194
+ });
195
+ expect(instance.start).toHaveBeenCalledTimes(1);
196
+ expect(instance.destroy).toHaveBeenCalledTimes(1);
197
+ expect(result).toBeNull();
198
+ });
199
+ });
@@ -19,7 +19,10 @@ import CapInput from "@capillarytech/cap-ui-library/CapInput";
19
19
  import CapSelect from "@capillarytech/cap-ui-library/CapSelect";
20
20
  import CapSpin from "@capillarytech/cap-ui-library/CapSpin";
21
21
  import CapNotification from "@capillarytech/cap-ui-library/CapNotification";
22
+ import CapError from "@capillarytech/cap-ui-library/CapError";
23
+ import CapColumn from "@capillarytech/cap-ui-library/CapColumn";
22
24
  import config from '../../config/app';
25
+ import { destroyBeeInstance, initBeeEditor } from '../../utils/beePluginLoader';
23
26
  import makeSelectBEE from './selectors';
24
27
  import messages from './messages';
25
28
  import * as beeActions from './actions';
@@ -75,6 +78,9 @@ function BeeEditor(props) {
75
78
  const [rowMetaInfo, setRowMetaInfo] = useState({});
76
79
  const [rowName, setRowName] = useState('');
77
80
  const [rowCategory, setRowCategory] = useState('');
81
+ const [isBeePluginLoading, setIsBeePluginLoading] = useState(false);
82
+ const [hasBeePluginLoadError, setHasBeePluginLoadError] = useState(false);
83
+ const [beePluginLoadAttempt, setBeePluginLoadAttempt] = useState(0);
78
84
  const beePluginInstanceRef = useRef(null);
79
85
  const initializedBeeJsonRef = useRef(null); // Track which beeJson we've initialized for
80
86
  const isInitializingRef = useRef(false); // Track if initialization is in progress
@@ -250,41 +256,48 @@ function BeeEditor(props) {
250
256
 
251
257
  // Clean up previous instance if it exists
252
258
  if (beePluginInstanceRef.current) {
253
- try {
254
- beePluginInstanceRef.current.destroy();
255
- } catch (e) {
256
- console.warn('[BeeEditor] useEffect - Error destroying previous BEE plugin:', e);
257
- }
259
+ destroyBeeInstance(beePluginInstanceRef.current);
258
260
  beePluginInstanceRef.current = null;
259
261
  }
260
262
 
261
- try {
262
- window.BeePlugin.create(currentTokenData, beeConfig, (instance) => {
263
+ let isEffectCancelled = false;
264
+ setHasBeePluginLoadError(false);
265
+ setIsBeePluginLoading(!window.BeePlugin);
266
+ initBeeEditor({
267
+ tokenData: currentTokenData,
268
+ beeConfig,
269
+ getBeeJson: () => beeJson,
270
+ isCancelled: () => isEffectCancelled,
271
+ onPluginLoaded: () => setIsBeePluginLoading(false),
272
+ })
273
+ .then((instance) => {
274
+ if (!instance) {
275
+ return;
276
+ }
263
277
  beePluginInstance = instance;
264
278
  beePluginInstanceRef.current = instance;
265
- const parseJson = typeof beeJson === 'string' ? JSON.parse(beeJson) : beeJson;
266
- beePluginInstance.start(parseJson);
267
279
  saveBeeInstance(beePluginInstance);
268
280
  // Mark this beeJson as initialized and clear initialization flag
269
281
  initializedBeeJsonRef.current = initializationKey;
270
282
  isInitializingRef.current = false;
283
+ })
284
+ .catch((error) => {
285
+ if (isEffectCancelled) {
286
+ return;
287
+ }
288
+ console.error('[BeeEditor] Error creating BEE plugin:', error);
289
+ setIsBeePluginLoading(false);
290
+ setHasBeePluginLoadError(true);
291
+ isInitializingRef.current = false;
271
292
  });
272
- } catch (error) {
273
- // Reset flag on error
274
- console.error('[BeeEditor] Error creating BEE plugin:', error);
275
- isInitializingRef.current = false;
276
- }
277
293
  return () => {
294
+ isEffectCancelled = true;
278
295
  clearInterval(intervalTimer);
279
296
  // Reset initialization flag on cleanup
280
297
  isInitializingRef.current = false;
281
298
  // Clean up BEE plugin instance if it exists
282
299
  if (beePluginInstanceRef.current) {
283
- try {
284
- beePluginInstanceRef.current.destroy();
285
- } catch (e) {
286
- console.warn('[BeeEditor] useEffect cleanup - Error destroying BEE plugin:', e);
287
- }
300
+ destroyBeeInstance(beePluginInstanceRef.current);
288
301
  beePluginInstanceRef.current = null;
289
302
  }
290
303
  // Note: We don't reset initializedBeeJsonRef here because:
@@ -293,7 +306,12 @@ function BeeEditor(props) {
293
306
  };
294
307
  // Only depend on beeJson, uid, and id - not tokenData
295
308
  // tokenData is accessed via ref to prevent re-initialization when it changes
296
- }, [beeJson, uid, id]);
309
+ }, [beeJson, uid, id, beePluginLoadAttempt]);
310
+
311
+ const onRetryBeePluginLoad = () => {
312
+ setBeePluginLoadAttempt((attempt) => attempt + 1);
313
+ };
314
+
297
315
  const callbackSaveRow = (status, errorMsg) => {
298
316
  if (status === 'success') {
299
317
  CapNotification.success({message: formatMessage(messages.rowCreationSuccessMgs), key: 'create-custom-row-success'});
@@ -367,8 +385,17 @@ function BeeEditor(props) {
367
385
  </>
368
386
  );
369
387
  return (
370
- <CapSpin spinning={saveRowRequest || false}>
371
- <div id="bee-plugin-container" style={{ height: "650px" }}></div>
388
+ <CapSpin spinning={saveRowRequest || isBeePluginLoading}>
389
+ {hasBeePluginLoadError ? (
390
+ <CapColumn className="bee-plugin-load-error">
391
+ <CapError type="error">{formatMessage(messages.beePluginLoadError)}</CapError>
392
+ <CapButton type="secondary" onClick={onRetryBeePluginLoad}>
393
+ {formatMessage(messages.retry)}
394
+ </CapButton>
395
+ </CapColumn>
396
+ ) : (
397
+ <CapColumn id="bee-plugin-container" className="bee-plugin-container" />
398
+ )}
372
399
  <TagList
373
400
  moduleFilterEnabled={moduleFilterEnabled}
374
401
  label={label}
@@ -1,3 +1,15 @@
1
+ .bee-plugin-container {
2
+ height: 40.625rem;
3
+ }
4
+
5
+ .bee-plugin-load-error {
6
+ padding: 1.5rem 0;
7
+
8
+ > * + * {
9
+ margin-top: 1rem;
10
+ }
11
+ }
12
+
1
13
  .custom-row-modal {
2
14
  .ant-modal-footer {
3
15
  text-align: left;
@@ -64,4 +64,12 @@ export default defineMessages({
64
64
  id: `${prefix}.rowCreationFailureMgs`,
65
65
  defaultMessage: 'Error in row creation',
66
66
  },
67
+ beePluginLoadError: {
68
+ id: `${prefix}.beePluginLoadError`,
69
+ defaultMessage: 'Unable to load the drag & drop editor. Check your network connection and try again.',
70
+ },
71
+ retry: {
72
+ id: `${prefix}.retry`,
73
+ defaultMessage: 'Retry',
74
+ },
67
75
  });
@@ -0,0 +1,78 @@
1
+ import React from 'react';
2
+ import '@testing-library/jest-dom';
3
+ import { render, screen, fireEvent, waitFor } from '../../../utils/test-utils';
4
+ import { initBeeEditor } from '../../../utils/beePluginLoader';
5
+ import BeeEditor from '../index';
6
+
7
+ // initBeeEditor's own load/start/cancel behaviour is covered in utils/tests/beePluginLoader.test.js
8
+ jest.mock('../../../utils/beePluginLoader', () => ({
9
+ ...jest.requireActual('../../../utils/beePluginLoader'),
10
+ initBeeEditor: jest.fn(),
11
+ }));
12
+
13
+ jest.mock('../../TagList', () => () => null);
14
+
15
+ const mockBeePluginInstance = { start: jest.fn(), destroy: jest.fn() };
16
+
17
+ const defaultProps = {
18
+ uid: 'test-uid',
19
+ id: 'bee-editor',
20
+ beeJson: '{"page":{}}',
21
+ tokenData: { access_token: 'token' },
22
+ saveBeeInstance: jest.fn(),
23
+ saveBeeData: jest.fn(),
24
+ tags: [],
25
+ };
26
+
27
+ const getInitOptions = () => initBeeEditor.mock.calls[initBeeEditor.mock.calls.length - 1][0];
28
+
29
+ describe('BeeEditor BeePlugin loading', () => {
30
+ beforeEach(() => {
31
+ jest.spyOn(console, 'error').mockImplementation(() => {});
32
+ });
33
+
34
+ afterEach(() => {
35
+ console.error.mockRestore();
36
+ });
37
+
38
+ it('starts the BEE editor with its template and saves the instance', async () => {
39
+ initBeeEditor.mockResolvedValue(mockBeePluginInstance);
40
+ const { container } = render(<BeeEditor {...defaultProps} />);
41
+
42
+ await waitFor(() => expect(defaultProps.saveBeeInstance).toHaveBeenCalledWith(mockBeePluginInstance));
43
+ const { tokenData, getBeeJson, isCancelled } = getInitOptions();
44
+ expect(tokenData).toEqual(defaultProps.tokenData);
45
+ expect(getBeeJson()).toBe(defaultProps.beeJson);
46
+ expect(isCancelled()).toBe(false);
47
+ expect(container.querySelector('#bee-plugin-container')).toBeInTheDocument();
48
+ });
49
+
50
+ it('shows an error with retry when the plugin script fails, and recovers on retry', async () => {
51
+ initBeeEditor
52
+ .mockRejectedValueOnce(new Error('Failed to load'))
53
+ .mockResolvedValueOnce(mockBeePluginInstance);
54
+ const { container } = render(<BeeEditor {...defaultProps} />);
55
+
56
+ expect(await screen.findByText(/Unable to load the drag & drop editor/)).toBeInTheDocument();
57
+ expect(container.querySelector('#bee-plugin-container')).not.toBeInTheDocument();
58
+
59
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
60
+
61
+ await waitFor(() => expect(defaultProps.saveBeeInstance).toHaveBeenCalledWith(mockBeePluginInstance));
62
+ expect(initBeeEditor).toHaveBeenCalledTimes(2);
63
+ expect(screen.queryByText(/Unable to load the drag & drop editor/)).not.toBeInTheDocument();
64
+ expect(container.querySelector('#bee-plugin-container')).toBeInTheDocument();
65
+ });
66
+
67
+ it('reports cancellation after unmount and saves nothing when no editor is returned', async () => {
68
+ let resolveInit;
69
+ initBeeEditor.mockReturnValue(new Promise((resolve) => { resolveInit = resolve; }));
70
+ const { unmount } = render(<BeeEditor {...defaultProps} />);
71
+ unmount();
72
+
73
+ expect(getInitOptions().isCancelled()).toBe(true);
74
+ resolveInit(null);
75
+ await Promise.resolve();
76
+ expect(defaultProps.saveBeeInstance).not.toHaveBeenCalled();
77
+ });
78
+ });
@@ -6,6 +6,7 @@ import { connect } from 'react-redux';
6
6
  import { createStructuredSelector } from 'reselect';
7
7
  import CapRow from '@capillarytech/cap-ui-library/CapRow';
8
8
  import { UserIsAuthenticated } from '../../utils/authWrapper';
9
+ import { initBeeEditor } from '../../utils/beePluginLoader';
9
10
  import TagList from '../TagList';
10
11
  import {
11
12
  ANDROID, BEE_LAYOUT_OPTIONS, MOBILE, UNSUBSCRIBE,
@@ -113,18 +114,28 @@ function BeePopupEditor(props) {
113
114
  saveBeeData(jsonFile, htmlFile, device);
114
115
  },
115
116
  };
116
- window.BeePlugin.create(tokenData, beeConfig, (instance) => {
117
- beePluginInstance = instance;
118
- beeInstanceRef.current = instance;
119
- // Use ref to get the latest beeJson — the closure captures the value at effect time,
120
- // but beeJsonRef.current is always up-to-date (e.g. when template data loads async)
121
- const latestBeeJson = beeJsonRef.current;
122
- const parseJson = typeof latestBeeJson === 'string' ? JSON.parse(latestBeeJson) : latestBeeJson;
123
- beePluginInstance.start(parseJson);
124
- saveBeeInstance(beePluginInstance, device);
125
- isInitializedRef.current = true;
126
- });
117
+ let isEffectCancelled = false;
118
+ initBeeEditor({
119
+ tokenData,
120
+ beeConfig,
121
+ // Read the ref at create time: the effect closure may hold stale beeJson when template data loads async
122
+ getBeeJson: () => beeJsonRef.current,
123
+ isCancelled: () => isEffectCancelled,
124
+ })
125
+ .then((instance) => {
126
+ if (!instance) {
127
+ return;
128
+ }
129
+ beePluginInstance = instance;
130
+ beeInstanceRef.current = instance;
131
+ saveBeeInstance(beePluginInstance, device);
132
+ isInitializedRef.current = true;
133
+ })
134
+ .catch((error) => {
135
+ console.error('[BeePopupEditor] Error creating BEE plugin:', error);
136
+ });
127
137
  return () => {
138
+ isEffectCancelled = true;
128
139
  clearInterval(intervalTimer);
129
140
  // Reset initialization flag when component unmounts or layout changes
130
141
  isInitializedRef.current = false;
@@ -756,6 +756,8 @@ export function SlideBoxContent(props) {
756
756
  const isBEETemplate = templateData?.base?.is_drag_drop === true
757
757
  || templateData?.base?.is_drag_drop === 1;
758
758
  if (supportCKEditor || isBEETemplate) {
759
+ // Host-supplied BEE content is the latest edit; fetching by _id would reload the original template over it
760
+ const hasHostBEEContent = isBEETemplate && !isEmpty(templateData?.base?.json_content);
759
761
  return (
760
762
  <Email
761
763
  key="cretives-container-email-edit"
@@ -767,7 +769,7 @@ export function SlideBoxContent(props) {
767
769
  route={{ name: 'email' }}
768
770
  isGetFormData={isGetFormData}
769
771
  getFormdata={getFormData}
770
- params={{ id: templateData._id }}
772
+ params={{ id: hasHostBEEContent ? undefined : templateData._id }}
771
773
  templateData={templateData}
772
774
  getFormSubscriptionData={getFormData}
773
775
  getDefaultTags={type}
@@ -580,7 +580,7 @@ export class Email extends React.Component { // eslint-disable-line react/prefer
580
580
  const beeJson = `BEEeditor${currentTab > 1 ? currentTab : ''}json`;
581
581
  const beeToken = `BEEeditor${currentTab > 1 ? currentTab : ''}token`;
582
582
  let beeJsonValue = '';
583
- const selectedId = _.get(this.props, 'Email.templateDetails._id', '') || '';
583
+ const selectedId = _.get(nextProps, 'Email.templateDetails._id', '') || '';
584
584
 
585
585
  // Get beeJsonValue from template data - check multiple sources
586
586
  // First check if it's already in formData (from setEditData)
@@ -637,7 +637,7 @@ export class Email extends React.Component { // eslint-disable-line react/prefer
637
637
  is_drag_drop: true,
638
638
  [beeJson]: finalBeeJsonValue,
639
639
  [beeToken]: nextProps.Email.CmsSettings.tokenData,
640
- id: selectedId,
640
+ id: selectedId || existingFormData.id,
641
641
  // Also store json-content for reference
642
642
  'json-content': finalBeeJsonValue,
643
643
  };
@@ -83,6 +83,8 @@ const useEmailWrapper = ({
83
83
  pathname: `/email/create`,
84
84
  query: { module: 'library', type: 'embedded' },
85
85
  });
86
+ // On create, `location` is the host app's route (e.g. a promotion /edit/:id URL), so it must not mark the email as an edit
87
+ const routeLocation = isEditEmail ? location : undefined;
86
88
 
87
89
  // Cleanup effect
88
90
  useEffect(() => () => {
@@ -155,7 +157,7 @@ const useEmailWrapper = ({
155
157
  }
156
158
 
157
159
  // Check if we're in edit mode (need to check BEE status for editor selection)
158
- const hasParamsId = params?.id || location?.query?.id || location?.params?.id || location?.pathname?.includes('/edit/');
160
+ const hasParamsId = params?.id || routeLocation?.query?.id || routeLocation?.params?.id || routeLocation?.pathname?.includes('/edit/');
159
161
  const isEditMode = hasParamsId;
160
162
 
161
163
  // Only check BEE enabled status for new flow (when supportCKEditor is false)
@@ -173,7 +175,7 @@ const useEmailWrapper = ({
173
175
  // Make API call to check BEE enabled status using new endpoint
174
176
  emailActions.getCmsAccounts('BEE_PLUGIN');
175
177
  }
176
- }, [currentStep, emailActions, params?.id, location?.query?.id, location?.params?.id, location?.pathname]);
178
+ }, [currentStep, emailActions, params?.id, routeLocation?.query?.id, routeLocation?.params?.id, routeLocation?.pathname]);
177
179
 
178
180
  // Effect to update isBeeEditorEnabled based on new API response
179
181
  // This effect watches for isBeeEnabled from the new API response
@@ -205,23 +207,23 @@ const useEmailWrapper = ({
205
207
  if (!isEditEmail) {
206
208
  return;
207
209
  }
208
- const hasParamsId = params?.id || location?.query?.id || location?.params?.id || location?.pathname?.includes('/edit/');
210
+ const hasParamsId = params?.id || routeLocation?.query?.id || routeLocation?.params?.id || routeLocation?.pathname?.includes('/edit/');
209
211
  const hasTemplateDetails = Email?.templateDetails && !isEmpty(Email.templateDetails);
210
212
  const hasTemplateDataProp = templateData && !isEmpty(templateData);
211
213
  const isTemplateLoading = Email?.getTemplateDetailsInProgress;
212
214
 
213
215
  // Only fetch if we have an ID, don't have template data yet, and not already loading
214
216
  if (hasParamsId && !hasTemplateDetails && !hasTemplateDataProp && !isTemplateLoading && emailActions?.getTemplateDetails) {
215
- let templateId = params?.id || location?.query?.id || location?.params?.id;
216
- if (!templateId && location?.pathname?.includes('/edit/')) {
217
- const [, extractedId] = location.pathname.match(/\/edit\/([^/]+)/) || [];
217
+ let templateId = params?.id || routeLocation?.query?.id || routeLocation?.params?.id;
218
+ if (!templateId && routeLocation?.pathname?.includes('/edit/')) {
219
+ const [, extractedId] = routeLocation.pathname.match(/\/edit\/([^/]+)/) || [];
218
220
  if (extractedId) templateId = extractedId;
219
221
  }
220
222
  if (templateId) {
221
223
  emailActions.getTemplateDetails(templateId, 'email');
222
224
  }
223
225
  }
224
- }, [isEditEmail, params?.id, location?.query?.id, location?.params?.id, location?.pathname, Email?.templateDetails, Email?.getTemplateDetailsInProgress, templateData, emailActions]);
226
+ }, [isEditEmail, params?.id, routeLocation?.query?.id, routeLocation?.params?.id, routeLocation?.pathname, Email?.templateDetails, Email?.getTemplateDetailsInProgress, templateData, emailActions]);
225
227
 
226
228
  // Effect to set BEETemplate when template details are loaded for BEE templates
227
229
  // This ensures Email component can properly initialize BEE editor
@@ -279,9 +281,9 @@ const useEmailWrapper = ({
279
281
  const isBEEAppEnable = checkBeeEditorEnabled();
280
282
  // Check if we're in edit mode - check multiple sources for id
281
283
  const hasParamsId = params?.id
282
- || location?.query?.id
283
- || location?.params?.id
284
- || (location?.pathname && location.pathname.includes('/edit/'));
284
+ || routeLocation?.query?.id
285
+ || routeLocation?.params?.id
286
+ || (routeLocation?.pathname && routeLocation.pathname.includes('/edit/'));
285
287
  const cmsMode = hasParamsId ? 'open' : 'create';
286
288
  // Extract langId from active tab
287
289
  const activeTabForLang = get(editTemplateData, 'versions.base.activeTab', 'en');
@@ -546,9 +548,9 @@ const useEmailWrapper = ({
546
548
  useEffect(() => {
547
549
  // If templateData is cleared/null and we're not in edit mode, reset selectedCreateMode
548
550
  const hasParamsId = params?.id
549
- || location?.query?.id
550
- || location?.params?.id
551
- || location?.pathname?.includes('/edit/');
551
+ || routeLocation?.query?.id
552
+ || routeLocation?.params?.id
553
+ || routeLocation?.pathname?.includes('/edit/');
552
554
  const hasTemplateData = templateData && !isEmpty(templateData);
553
555
  const isEditMode = hasParamsId || hasTemplateData;
554
556
 
@@ -561,7 +563,7 @@ const useEmailWrapper = ({
561
563
  // This preserves user selection while in content creation
562
564
  setSelectedCreateMode('');
563
565
  }
564
- }, [templateData, params?.id, location?.query?.id, location?.params?.id, location?.pathname, selectedCreateMode, templateName, currentStep, emailCreateMode]);
566
+ }, [templateData, params?.id, routeLocation?.query?.id, routeLocation?.params?.id, routeLocation?.pathname, selectedCreateMode, templateName, currentStep, emailCreateMode]);
565
567
 
566
568
  // Derived state
567
569
  const supportCKEditorFlag = hasSupportCKEditor();
@@ -589,7 +591,7 @@ const useEmailWrapper = ({
589
591
  // Check if we're editing an existing template
590
592
  // CRITICAL: Only treat as edit mode if we have params.id (actual edit URL) or templateData prop
591
593
  // Don't use templateDetails existence alone, as it might persist from previous template
592
- const hasParamsId = params?.id || location?.query?.id || location?.params?.id || location?.pathname?.includes('/edit/');
594
+ const hasParamsId = params?.id || routeLocation?.query?.id || routeLocation?.params?.id || routeLocation?.pathname?.includes('/edit/');
593
595
  const hasTemplateDataProp = templateData && !isEmpty(templateData);
594
596
  // CRITICAL: Consider it edit mode if we have params.id OR templateData prop (library mode)
595
597
  // This allows editor type determination even when template data is still loading
@@ -706,13 +708,13 @@ const useEmailWrapper = ({
706
708
  const emailParams = {};
707
709
  if (params?.id) {
708
710
  emailParams.id = params.id;
709
- } else if (location?.query?.id) {
710
- emailParams.id = location.query.id;
711
- } else if (location?.params?.id) {
712
- emailParams.id = location.params.id;
713
- } else if (location?.pathname?.includes('/edit/')) {
711
+ } else if (routeLocation?.query?.id) {
712
+ emailParams.id = routeLocation.query.id;
713
+ } else if (routeLocation?.params?.id) {
714
+ emailParams.id = routeLocation.params.id;
715
+ } else if (routeLocation?.pathname?.includes('/edit/')) {
714
716
  // Extract id from pathname if it's in the format /edit/:id
715
- const match = location.pathname.match(/\/edit\/([^/]+)/);
717
+ const match = routeLocation.pathname.match(/\/edit\/([^/]+)/);
716
718
  // Reject sentinel strings that come from unguarded template literals
717
719
  // (e.g. `/edit/${maybeUndefined}` → "/edit/undefined"), so they don't
718
720
  // get treated as real template ids downstream.
@@ -800,7 +802,7 @@ const useEmailWrapper = ({
800
802
  // Check if we're in edit mode (templateDetails or BEETemplate exists, or params.id exists)
801
803
  const hasTemplateDetails = Email?.templateDetails && !isEmpty(Email.templateDetails);
802
804
  const hasBEETemplate = Email?.BEETemplate && !isEmpty(Email.BEETemplate);
803
- const hasParamsId = params?.id || location?.query?.id || location?.params?.id || location?.pathname?.includes('/edit/');
805
+ const hasParamsId = params?.id || routeLocation?.query?.id || routeLocation?.params?.id || routeLocation?.pathname?.includes('/edit/');
804
806
  const isEditMode = hasTemplateDetails || hasBEETemplate || hasParamsId;
805
807
 
806
808
  // In edit mode (when supportCKEditor is false), always show editor
@@ -842,7 +844,7 @@ const useEmailWrapper = ({
842
844
 
843
845
  // For Editor: Show editor when template is selected
844
846
  return !isEmpty(SelectedEdmDefaultTemplate);
845
- }, [currentStep, selectedCreateMode, supportCKEditorFlag, emailCreateMode, EmailLayout, SelectedEdmDefaultTemplate, Email?.templateDetails, Email?.BEETemplate, params?.id, location?.query?.id, location?.params?.id, location?.pathname, emailProps?.editor, emailProps?.selectedEditorMode]);
847
+ }, [currentStep, selectedCreateMode, supportCKEditorFlag, emailCreateMode, EmailLayout, SelectedEdmDefaultTemplate, Email?.templateDetails, Email?.BEETemplate, params?.id, routeLocation?.query?.id, routeLocation?.params?.id, routeLocation?.pathname, emailProps?.editor, emailProps?.selectedEditorMode]);
846
848
 
847
849
  // Memoize static data
848
850
  const modes = useMemo(() => {