Skip to content

Commit

Permalink
Rupato/BOT-2004/fix: refactored bot functions (binary-com#16230)
Browse files Browse the repository at this point in the history
* fix: refactored bot functions

* fix: removed commented code

* fix: reverted code

* fix: reverted code

* fix: reverted code

* fix: dark mode refresh theme sonar cloud

* fix: for test case

* fix: renamed functions

* fix: added setLoading false on catch

* fix: when strategies are empty

* fix: loader when no strategies

* fix: local file loaded to null on file upload

* fix: test case

* fix: for open on recent strategies

* fix: for recent stratagies

* fix: test cases and refactored load modal

* fix: when there is no strategy updated

* fix: updated test recent-workspace test case and naming for functions

* fix: for cypress added disabled state for open

* fix: for setting disabled button on active tab change

* fix: for cypress loading strategy

* fix: refactored onrecentworkspace click

* fix: removed unused values

---------

Co-authored-by: Farabi <102643568+farabi-deriv@users.noreply.github.com>
  • Loading branch information
rupato-deriv and farabi-deriv committed Aug 26, 2024
1 parent 11d85fa commit 3dec78b
Show file tree
Hide file tree
Showing 10 changed files with 358 additions and 261 deletions.
32 changes: 28 additions & 4 deletions packages/bot-skeleton/src/scratch/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,29 @@ import { error_message_map } from '../../utils/error-config';
import { botNotification } from '../../../../bot-web-ui/src/components/bot-notification/bot-notification';
import { notification_message } from '../../../../bot-web-ui/src/components/bot-notification/bot-notification-utils';

export const inject_workspace_options = {
media: `${__webpack_public_path__}media/`,
zoom: {
wheel: true,
startScale: config.workspaces.previewWorkspaceStartScale,
},
readOnly: true,
scrollbars: true,
renderer: 'zelos',
};

export const updateXmlValues = blockly_options => {
if (!window.Blockly) return;
const { strategy_id, convertedDom, file_name, from } = blockly_options;
window.Blockly.xmlValues = {
...window.Blockly.xmlValues,
strategy_id,
convertedDom,
file_name,
from,
};
};

export const getSelectedTradeType = (workspace = Blockly.derivWorkspace) => {
const trade_type_block = workspace.getAllBlocks(true).find(block => block.type === 'trade_definition_tradetype');
const selected_trade_type = trade_type_block?.getFieldValue('TRADETYPE_LIST');
Expand Down Expand Up @@ -122,9 +145,9 @@ export const load = async ({
showIncompatibleStrategyDialog,
}) => {
if (!DBotStore?.instance || !workspace) return;
const { setLoading } = DBotStore.instance;
const { load_modal } = DBotStore.instance;
const { setLoadedLocalFile } = load_modal;
const { setLoading, load_modal } = DBotStore.instance;
const { setOpenButtonDisabled, setLoadedLocalFile } = load_modal;

setLoading(true);
// Delay execution to allow fully previewing previous strategy if users quickly switch between strategies.
await delayExecution(100);
Expand Down Expand Up @@ -185,7 +208,7 @@ export const load = async ({
workspace,
Array.from(blockly_xml).map(xml_block => xml_block.getAttribute('type'))
);

updateXmlValues({ strategy_id, convertedDom: xml, file_name, from });
if (is_collection) {
loadBlocks(xml, drop_event, event_group, workspace);
} else {
Expand Down Expand Up @@ -218,6 +241,7 @@ export const load = async ({
return showInvalidStrategyError();
} finally {
setLoading(false);
setOpenButtonDisabled(false);
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ describe('LocalFooter', () => {
} as DashboardStore,
load_modal: {
...mock_DBot_store.load_modal,
loadFileFromLocal: jest.fn(),
toggleLoadModal: jest.fn(),
setLoadedLocalFile: jest.fn(),
loadStrategyOnBotBuilder: jest.fn(),
saveStrategyToLocalStorage: jest.fn(),
preview_workspace: jest.fn() as unknown,
selected_strategy: jest.fn() as unknown,
tab_name: 'google_tab',
Expand Down Expand Up @@ -78,7 +79,8 @@ describe('LocalFooter', () => {

userEvent.click(open_button);

expect(mock_DBot_store?.load_modal.loadFileFromLocal).toHaveBeenCalled();
expect(mock_DBot_store?.load_modal.loadStrategyOnBotBuilder).toHaveBeenCalled();
expect(mock_DBot_store?.load_modal.saveStrategyToLocalStorage).toHaveBeenCalled();
expect(mock_DBot_store?.load_modal.toggleLoadModal).toHaveBeenCalled();
expect(mock_DBot_store?.dashboard.setPreviewOnPopup).toHaveBeenCalledWith(false);
expect(mock_DBot_store?.dashboard.setOpenSettings).toHaveBeenCalledWith(NOTIFICATION_TYPE.BOT_IMPORT);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,17 @@ jest.mock('@deriv/bot-skeleton/src/scratch/dbot', () => ({
jest.mock('@deriv/bot-skeleton/src/scratch/hooks/block_svg', () => jest.fn());

window.Blockly = {
derivWorkspace: { asyncClear: () => ({}) },
derivWorkspace: { asyncClear: () => ({}), cleanUp: () => ({}), clearUndo: () => ({}) },
utils: {
xml: { textToDom: jest.fn() },
},
Xml: { domToWorkspace: () => ({}), textToDom: () => ({}) },
Xml: { domToWorkspace: () => ({}), textToDom: () => ({}), clearWorkspaceAndLoadFromXml: () => ({}) },
xmlValues: {
strategy_id: 'strategy_id',
file_name: 'strategy_name',
from: 'xml',
convertedDom: 'convertedDom',
},
};

describe('RecentFooter', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { mock_ws } from 'Utils/mock';
import RootStore from 'Stores/root-store';
import { DBotStoreProvider, mockDBotStore } from 'Stores/useDBotStore';
import RecentWorkspace from '../recent-workspace';
import { TStrategy } from 'Types';

jest.mock('@deriv/bot-skeleton/src/scratch/blockly', () => jest.fn());
jest.mock('@deriv/bot-skeleton/src/scratch/dbot', () => ({
Expand All @@ -22,6 +23,21 @@ const mock_workspace = {
xml: '<xml>Sample</xml>',
};

type TMockStrategy = Array<TStrategy>;

const strategy = {
name: '',
xml: '',
save_type: '',
timestamp: 1,
};

const mock_strategy: TMockStrategy = [
{ ...strategy, name: 'martingale', id: 'test-id-1' },
{ ...strategy, name: 'd_alembert', id: 'test-id-1' },
{ ...strategy, name: 'oscar_grind', id: 'test-id-1' },
];

describe('RecentWorkspace', () => {
let wrapper: ({ children }: { children: JSX.Element }) => JSX.Element, mock_DBot_store: RootStore | undefined;

Expand Down Expand Up @@ -49,9 +65,10 @@ describe('RecentWorkspace', () => {
});

it('should update selected strategy ID on clicking the strategy', () => {
mock_DBot_store?.load_modal?.setRecentStrategies(mock_strategy);
render(<RecentWorkspace workspace={mock_workspace} />, { wrapper });
const recent_workspace_item = screen.getByTestId('dt_recent_workspace_item');
userEvent.click(recent_workspace_item);
expect(mock_DBot_store?.load_modal?.selected_strategy_id).toBe(mock_workspace.id);
expect(mock_DBot_store?.load_modal?.selected_strategy_id).toBe(mock_strategy[0].id);
});
});
14 changes: 12 additions & 2 deletions packages/bot-web-ui/src/components/load-modal/local-footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ import { useDBotStore } from 'Stores/useDBotStore';
const LocalFooter = observer(() => {
const { ui } = useStore();
const { load_modal, dashboard } = useDBotStore();
const { is_open_button_loading, loadFileFromLocal, setLoadedLocalFile, toggleLoadModal } = load_modal;
const {
is_open_button_loading,
is_open_button_disabled,
loadStrategyOnBotBuilder,
setLoadedLocalFile,
saveStrategyToLocalStorage,
toggleLoadModal,
} = load_modal;
const { setOpenSettings, setPreviewOnPopup } = dashboard;

const { is_desktop } = ui;
Expand All @@ -22,7 +29,9 @@ const LocalFooter = observer(() => {
<Button
text={localize('Open')}
onClick={() => {
loadFileFromLocal();
loadStrategyOnBotBuilder();
saveStrategyToLocalStorage();
setLoadedLocalFile(null);
toggleLoadModal();
setPreviewOnPopup(false);
setOpenSettings(NOTIFICATION_TYPE.BOT_IMPORT);
Expand All @@ -31,6 +40,7 @@ const LocalFooter = observer(() => {
has_effect
primary
large
disabled={is_open_button_disabled}
/>
</Wrapper>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,22 @@ import { useDBotStore } from 'Stores/useDBotStore';

const RecentFooter = observer(() => {
const { load_modal, dashboard } = useDBotStore();
const { is_open_button_loading, loadFileFromRecent, toggleLoadModal } = load_modal;
const { is_open_button_loading, is_open_button_disabled, loadStrategyOnBotBuilder, toggleLoadModal } = load_modal;
const { setOpenSettings } = dashboard;

return (
<Button
text={localize('Open')}
onClick={() => {
loadFileFromRecent();
loadStrategyOnBotBuilder();
toggleLoadModal();
setOpenSettings(NOTIFICATION_TYPE.BOT_IMPORT);
}}
is_loading={is_open_button_loading}
has_effect
primary
large
disabled={is_open_button_disabled}
/>
);
});
Expand Down
20 changes: 17 additions & 3 deletions packages/bot-web-ui/src/components/load-modal/recent-workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,30 @@ type TRecentWorkspaceProps = {
};

const RecentWorkspace = observer(({ workspace }: TRecentWorkspaceProps) => {
const { load_modal } = useDBotStore();
const { getRecentFileIcon, getSaveType, previewRecentStrategy, selected_strategy_id } = load_modal;
const { load_modal, blockly_store } = useDBotStore();
const { setLoading } = blockly_store;
const {
getRecentFileIcon,
getSaveType,
loadStrategyOnModalRecentPreview,
selected_strategy_id,
updateXmlValuesOnStrategySelection,
} = load_modal;

const onRecentWorkspaceClick = () => {
if (selected_strategy_id === workspace.id) return;
setLoading(true);
loadStrategyOnModalRecentPreview(workspace.id);
updateXmlValuesOnStrategySelection();
};

return (
<div
className={classnames('load-strategy__recent-item', {
'load-strategy__recent-item--selected': selected_strategy_id === workspace.id,
})}
key={workspace.id}
onClick={selected_strategy_id === workspace.id ? undefined : () => previewRecentStrategy(workspace.id)}
onClick={onRecentWorkspaceClick}
data-testid='dt_recent_workspace_item'
>
<div className='load-strategy__recent-item-text'>
Expand Down
6 changes: 0 additions & 6 deletions packages/bot-web-ui/src/constants/load-modal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,3 @@ export const tabs_title = Object.freeze({
TAB_GOOGLE: 'google_tab',
TAB_RECENT: 'recent_tab',
});

export const clearInjectionDiv = (el_ref?: HTMLElement) => {
if (el_ref && el_ref.getElementsByClassName('injectionDiv').length > 1) {
el_ref.removeChild(el_ref.getElementsByClassName('injectionDiv')[0]);
}
};
14 changes: 1 addition & 13 deletions packages/bot-web-ui/src/stores/dashboard-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { setColors } from '@deriv/bot-skeleton';
import { TStores } from '@deriv/stores/types';
import { botNotification } from 'Components/bot-notification/bot-notification';
import { notification_message, NOTIFICATION_TYPE } from 'Components/bot-notification/bot-notification-utils';
import { clearInjectionDiv } from 'Constants/load-modal';
import * as strategy_description from '../constants/quick-strategies';
import { TDescriptionItem } from '../pages/bot-builder/quick-strategy/types';
import {
Expand Down Expand Up @@ -168,10 +167,6 @@ export default class DashboardStore implements IDashboardStore {
...getQuickStrategyContent,
];

const {
load_modal: { previewRecentStrategy, current_workspace_id },
} = this.root_store;

const refreshBotBuilderTheme = () => {
Blockly.derivWorkspace.asyncClear();
Blockly.Xml.domToWorkspace(
Expand All @@ -191,12 +186,7 @@ export default class DashboardStore implements IDashboardStore {
() => {
if (Blockly) setCurrentXML();
setColors(this.is_dark_mode);
if (this.active_tab === 1) {
refreshBotBuilderTheme();
} else {
refreshBotBuilderTheme();
previewRecentStrategy(current_workspace_id);
}
refreshBotBuilderTheme();
}
);
reaction(
Expand Down Expand Up @@ -360,9 +350,7 @@ export default class DashboardStore implements IDashboardStore {
if (!el_ref) {
// eslint-disable-next-line no-console
console.warn('Could not find preview workspace element.');
return;
}
clearInjectionDiv(el_ref);
};

onCloseDialog = (): void => {
Expand Down
Loading

0 comments on commit 3dec78b

Please sign in to comment.