Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue 1375: rework generation flow #1390

Merged
merged 16 commits into from
Jul 20, 2023
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"max-len": ["error", {"code": 120, "ignoreUrls": true, "ignoreStrings": true, "ignoreTemplateLiterals": true}],
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-unused-vars": ["error", { "args": "after-used" }],
"@typescript-eslint/no-unused-vars": ["error", { "args": "after-used", "argsIgnorePattern": "_", "varsIgnorePattern": "_" }],
"@typescript-eslint/ban-ts-comment": "off"
},
"settings": {
Expand Down
5 changes: 3 additions & 2 deletions src/__tests__/__mocks__/locator.mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const locator1 = {
xPath: "//*[@class='sidebar-menu left']",
output: "//*[@class='sidebar-menu left']",
taskStatus: "SUCCESS",
xPathStatus: "SUCCESS",
cssSelector: ".sidebar-menu.left",
},
name: "radiobuttonsUl",
Expand All @@ -28,7 +29,7 @@ export const locator2 = {
locator: {
xPath: "//*[@class='sidebar-menu left']",
cssSelector: "",
taskStatus: "SUCCESS",
xPathStatus: "SUCCESS",
},
name: "radiobuttonsUl",
predictedAttrId: "",
Expand All @@ -49,7 +50,7 @@ export const locator3 = {
locator: {
xPath: "//*[@class='sidebar-menu left']",
cssSelector: "",
taskStatus: "SUCCESS",
xPathStatus: "SUCCESS",
},
name: "radiobuttonsUl",
predictedAttrId: "",
Expand Down
4 changes: 2 additions & 2 deletions src/__tests__/locators/locatorsSlice.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ describe("changeLocatorAttributes reducer", () => {
expect(changeElementNameSpy).toHaveBeenCalledWith(locator);
});

test("edit type, custom name stays the same", () => {
test("edit type, custom name remains the same", () => {
store.dispatch(
changeLocatorAttributes({
element_id: "8736312404689610766421832473",
Expand Down Expand Up @@ -96,7 +96,7 @@ describe("changeLocatorAttributes reducer", () => {
expect(locator.isCustomLocator).toBeTruthy();
expect(locator.isCustomName).toBeTruthy();
expect(locator.locator.xPath).toBe("//*[@class='any-class']");
expect(locator.locator.taskStatus).toBe(LocatorTaskStatus.SUCCESS);
expect(locator.locator.xPathStatus).toBe(LocatorTaskStatus.SUCCESS);
});

test("warned validation", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ export const getRootState = (_pageObject: PageObject) => ({
locator: {
cssSelector: ".main-content",
output: ".main-content",
taskStatus: "SUCCESS",
xPathStatus: "SUCCESS",
cssSelectorStatus: "SUCCESS",
xPath: "//*[@class='main-content']",
},
locatorType: LocatorType.cssSelector,
Expand All @@ -88,7 +89,8 @@ export const getRootState = (_pageObject: PageObject) => ({
locator: {
cssSelector: ".uui-navigation.nav.navbar-nav.m-l8.any",
output: "//*[@class='uui-navigation nav navbar-nav m-l8 any']",
taskStatus: "SUCCESS",
xPathStatus: "SUCCESS",
cssSelectorStatus: "PENDING",
xPath: "//*[@class='uui-navigation nav navbar-nav m-l8 any']",
},
name: "homeContactFormServiceSupportDatesSearchComplexTableSimpleTa",
Expand All @@ -112,7 +114,8 @@ export const getRootState = (_pageObject: PageObject) => ({
elemAriaLabel: null,
locator: {
cssSelector: '[index="5"] > ul',
taskStatus: "SUCCESS",
xPathStatus: "SUCCESS",
cssSelectorStatus: "FAILURE",
xPath: "//*[@index='5']/ul",
output: "//*[@index='5']/ul",
},
Expand Down Expand Up @@ -141,6 +144,8 @@ export const selectMockedLocators = (pageObject: PageObject) => [
elemAriaLabel: null,
locator: {
taskStatus: "SUCCESS",
cssSelectorStatus: "SUCCESS",
xPathStatus: "SUCCESS",
xPath: "//*[@class='main-content']",
output: ".main-content",
cssSelector: ".main-content",
Expand All @@ -163,7 +168,9 @@ export const selectMockedLocators = (pageObject: PageObject) => [
elemAriaLabel: null,
...(pageObject.locatorType === LocatorType.cssSelector ? { locatorType: LocatorType.cssSelector } : null),
locator: {
taskStatus: "SUCCESS",
taskStatus: "PENDING",
xPathStatus: "SUCCESS",
cssSelectorStatus: "PENDING",
xPath: "//*[@class='uui-navigation nav navbar-nav m-l8 any']",
cssSelector: ".uui-navigation.nav.navbar-nav.m-l8.any",
output:
Expand Down Expand Up @@ -191,7 +198,9 @@ export const selectMockedLocators = (pageObject: PageObject) => [
elemText: "HTML 5",
elemAriaLabel: null,
locator: {
taskStatus: "SUCCESS",
taskStatus: "FAILURE",
xPathStatus: "SUCCESS",
cssSelectorStatus: "FAILURE",
xPath: "//*[@index='5']/ul",
output: "//*[@index='5']/ul",
cssSelector: '[index="5"] > ul',
Expand Down
5 changes: 3 additions & 2 deletions src/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Backdrop } from "./components/Backdrop";
import { StatusBar } from "./components/StatusBar";
import { SeveralTabsWarning } from "./components/SeveralTabsWarning";
import { HttpEndpoint, request } from "../services/backend";
import { checkSession, getSessionId } from "./utils/appUtils";
import { checkSession, initLocatorSocketController } from "./utils/appUtils";
import { selectCurrentPage } from "./main.selectors";
import { RootState, store } from "./store/store";
import { useOnDisconnect } from "./utils/useOnDisconnect";
Expand All @@ -27,6 +27,7 @@ const App = () => {
const [isInvalidSession, setIsInvalidSession] = useState(false);
const [template, setTemplate] = useState<Blob | undefined>(undefined);
const backendAvailable = useSelector((state: RootState) => state.main.backendAvailable);
const xpathConfig = useSelector((state: RootState) => state.main.xpathConfig);
const currentPage = useSelector(selectCurrentPage);
const dispatch = useDispatch();

Expand All @@ -44,7 +45,7 @@ const App = () => {

if (backendAvailable === BackendStatus.Accessed) {
fetchTemplate();
getSessionId();
initLocatorSocketController(xpathConfig);
}
}, [backendAvailable]);

Expand Down
5 changes: 4 additions & 1 deletion src/app/store/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { cancellableActions } from "../../common/components/notification/middlew
import { logger } from "./middlewares/logger";
import { scriptNotifier } from "../../pageServices/scriptNotifier";
import { changePageMiddleware } from "./middlewares/changePage.middleware";
import { updateSocketMessageHandler } from "../../services/webSocketMessageHandler";
import { onSetActive } from "../../features/locators/reducers/onSetActive.middleware";

const rootReducer = {
main: mainSlice,
Expand All @@ -31,10 +33,11 @@ export const store = configureStore({
"main/setScriptMessage",
],
},
}).concat([logger, scriptNotifier, cancellableActions, changePageMiddleware]),
}).concat([logger, scriptNotifier, cancellableActions, changePageMiddleware, onSetActive]),
});

store.subscribe(() => updateMessageHandler(store.dispatch, store.getState()));
store.subscribe(() => updateSocketMessageHandler(store.dispatch, store.getState()));

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
4 changes: 2 additions & 2 deletions src/app/utils/appUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const checkSession = async (setStateCallback: (val: boolean) => void) =>
});
};

export const getSessionId = async () => {
export const initLocatorSocketController = async (xpathConfig: any) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest also type xpathConfig: MainState["xpathConfig"] like in src/features/locators/utils/locatorGenerationController.ts

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, thank you!

const sessionId = await request.get(HttpEndpoint.SESSION_ID);
locatorGenerationController.setSessionId(sessionId);
locatorGenerationController.init(sessionId, xpathConfig);
};
6 changes: 4 additions & 2 deletions src/app/utils/useOnDisconnect.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useDispatch, useSelector } from "react-redux";
import { removeEmptyPageObjects } from "../../features/pageObjects/reducers/removeEmptyPageObjects.thunk";
import { locatorGenerationController } from "../../features/locators/utils/locatorGenerationController";
import connector from "../../pageServices/connector";
import { removeOverlay } from "../../pageServices/pageDataHandlers";
import { clearAll } from "../main.slice";
import { changeIdentificationStatus } from "../../features/locators/locators.slice";
import { IdentificationStatus } from "../../features/locators/types/locator.types";
import { selectInProgressHashes } from "../../features/locators/selectors/locatorsFiltered.selectors";

export const useOnDisconnect = () => {
const dispatch = useDispatch();
const inProgressHashes = useSelector(selectInProgressHashes);

useEffect(() => {
const disconnectHandler = () => {
dispatch(changeIdentificationStatus(IdentificationStatus.noStatus));
dispatch(clearAll());
locatorGenerationController.revokeAll();
locatorGenerationController.revokeTasks(inProgressHashes);
dispatch(removeEmptyPageObjects());
removeOverlay();
};
Expand Down
3 changes: 1 addition & 2 deletions src/common/components/notification/useNotifications.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,10 @@ export const useNotifications = (container?: HTMLElement | null) => {
</div>
);

// container &&
notification[type]({
message: _message,
description,
duration: 50000, // remove before merge
duration: 500,
getContainer: () => container || document.body,
placement: "bottom",
bottom,
Expand Down
55 changes: 33 additions & 22 deletions src/common/utils/debouncer.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
export const accumulateAndDenounce = (fn: (arg: any[]) => any) => {
let accumulatedArgs: any[] = [];
let interval: NodeJS.Timer | null = null;
let cancelTimeout: NodeJS.Timeout | null = null;
class Debouncer {
accumulatedArgs: any[] = [];
interval: NodeJS.Timer | null = null;
cancelTimeout: NodeJS.Timeout | null = null;

const debouncedFn = (args: any[]) => {
accumulatedArgs.push(...args);
};
constructor() {
this.accumulateAndDebounce = this.accumulateAndDebounce.bind(this);
}

const throttledFn = () => {
if (accumulatedArgs.length > 0) {
cancelTimeout && clearTimeout(cancelTimeout);
fn(accumulatedArgs);
accumulatedArgs = [];
} else {
if (cancelTimeout) return;
cancelTimeout = setTimeout(() => interval && clearInterval(interval), 30000);
}
};
accumulateAndDebounce(fn: (arg: any[]) => any) {
const debouncedFn = (args: any[]) => {
this.accumulatedArgs.push(...args);
};

interval = setInterval(throttledFn, 500);
const throttledFn = () => {
if (this.accumulatedArgs.length > 0) {
this.cancelTimeout && clearTimeout(this.cancelTimeout);
fn(this.accumulatedArgs);
this.accumulatedArgs = [];
} else {
if (this.cancelTimeout) return;
this.cancelTimeout = setTimeout(() => {
this.interval && clearInterval(this.interval);
this.interval = null;
}, 30000);
}
};

return (args: any) => {
debouncedFn(args);
};
};
if (!this.interval) this.interval = setInterval(throttledFn, 500);

return (args: any) => {
debouncedFn(args);
};
}
}

export const debouncer = new Debouncer();
6 changes: 6 additions & 0 deletions src/common/utils/getDocument.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import connector from "../../pageServices/connector";

export const getDocument = async () => {
const documentResult = await connector.attachContentScript(() => JSON.stringify(document.documentElement.innerHTML));
return await documentResult[0].result;
};
2 changes: 1 addition & 1 deletion src/features/locators/Locator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export const Locator: React.FC<Props> = ({ element, currentPage, searchState, de
const keyForMultiSelect = isMacPlatform(window) ? evt.metaKey : evt.ctrlKey;
if (keyForMultiSelect) {
if (active) dispatch(elementUnsetActive(element_id));
else dispatch(elementSetActive(element_id));
else dispatch(elementSetActive(element));
} else dispatch(setActiveSingle(element));
};

Expand Down
8 changes: 6 additions & 2 deletions src/features/locators/LocatorsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import {
selectCalculatedGenerateByPageObj,
selectDeletedGenerateByPageObj,
selectCheckedLocators,
selectInProgressGenerateHashes,
selectInProgressHashes,
} from "./selectors/locatorsFiltered.selectors";
import { useNotifications } from "../../common/components/notification/useNotifications";
import { selectCurrentPageObject } from "../pageObjects/selectors/pageObjects.selectors";
Expand All @@ -45,6 +47,8 @@ export const LocatorsPage = () => {
const areUnselectedAll = useSelector(selectIfUnselectedAll);
const locatorIds = useSelector(getLocatorsIdsByPO);
const inProgressGenerate = useSelector(selectInProgressGenerateByPageObj);
const inProgressGenerateHashes = useSelector(selectInProgressGenerateHashes);
const inProgressHashes = useSelector(selectInProgressHashes);
const calculatedGenerate = useSelector(selectCalculatedGenerateByPageObj);
const deletedGenerate = useSelector(selectDeletedGenerateByPageObj);
const { id: currentPOId } = useSelector(selectCurrentPageObject) ?? {};
Expand All @@ -71,7 +75,7 @@ export const LocatorsPage = () => {
okText: "Confirm",
cancelText: "Cancel",
onOk: () => {
locatorGenerationController.revokeAll();
locatorGenerationController.revokeTasks(inProgressGenerateHashes);
pageBack();
},
});
Expand Down Expand Up @@ -109,7 +113,7 @@ export const LocatorsPage = () => {
};

const handleDiscard = () => {
locatorGenerationController.revokeAll();
locatorGenerationController.revokeTasks(inProgressHashes);
if (!size(locatorsSnapshot)) {
dispatch(removeLocators(locatorIds));
dispatch(clearLocators(undefined));
Expand Down
5 changes: 4 additions & 1 deletion src/features/locators/components/LocatorEditDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { createNameValidationRules } from "../utils/nameValidationRules";
import FormItem from "antd/es/form/FormItem";
import { LocatorType, SelectOption } from "../../../common/types/common";
import { isFilteredSelect } from "../../../common/utils/helpers";
import { newLocatorStub } from "../utils/constants";
import { CALCULATING, newLocatorStub } from "../utils/constants";
import { changeLocatorElement } from "../reducers/changeLocatorElement.thunk";
import { addCustomLocator } from "../reducers/addCustomLocator.thunk";
import { OnboardingContext } from "../../onboarding/OnboardingProvider";
Expand Down Expand Up @@ -236,6 +236,8 @@ export const LocatorEditDialog: React.FC<Props> = ({
);
};

const isLocatorDisabled = form.getFieldValue("locator") === CALCULATING;

return (
<DialogWithForm
modalProps={{
Expand Down Expand Up @@ -300,6 +302,7 @@ export const LocatorEditDialog: React.FC<Props> = ({
extra={renderValidationWarning()}
>
<Input.TextArea
disabled={isLocatorDisabled}
autoSize
// expands textarea to view port height
style={{ maxHeight: `calc(100vh - 396px)`, overflowY: "scroll" }}
Expand Down
Loading
Loading