PromucFlow_constructor/app/client/src/sagas/ContextSwitchingSaga.ts
Hetu Nandu fc34360b2a
fix: Context Switching fixes for Copy and Delete (#29841)
## Description
Fixes issues related to Segmented Lists around Copy / Delete
interactions

- It introduces a method to remove any focus history for a url. This is
added whenever we delete or move an item to another page
- It manages redirects after deleting a JS / Query / Datasource


#### PR fixes following issue(s)
Fixes #29697
Fixes #29694
Fixes #29700
Fixes #29699

#### Type of change

- Bug fix (non-breaking change which fixes an issue)

## Testing
>
#### How Has This Been Tested?
> Please describe the tests that you ran to verify your changes. Also
list any relevant details for your test configuration.
> Delete anything that is not relevant
- [ ] Manual
- [ ] JUnit
- [ ] Jest
- [ ] Cypress
>
>
#### Test Plan
> Add Testsmith test cases links that relate to this PR
>
>
#### Issues raised during DP testing
> Link issues raised during DP testing for better visiblity and tracking
(copy link from comments dropped on this PR)
>
>
>
## Checklist:
#### Dev activity
- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] PR is being merged under a feature flag


#### QA activity:
- [ ] [Speedbreak
features](https://github.com/appsmithorg/TestSmith/wiki/Guidelines-for-test-plans#speedbreakers-)
have been covered
- [ ] Test plan covers all impacted features and [areas of
interest](https://github.com/appsmithorg/TestSmith/wiki/Guidelines-for-test-plans#areas-of-interest-)
- [ ] Test plan has been peer reviewed by project stakeholders and other
QA members
- [ ] Manually tested functionality on DP
- [ ] We had an implementation alignment call with stakeholders post QA
Round 2
- [ ] Cypress test cases have been added and approved by SDET/manual QA
- [ ] Added `Test Plan Approved` label after Cypress tests were reviewed
- [ ] Added `Test Plan Approved` label after JUnit tests were reviewed


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Implemented new redirect logic after deleting JavaScript collections,
actions, and datasources to enhance user experience.
- Added custom routing for JavaScript collection creation and
management.

- **Enhancements**
- Updated focus history handling to improve navigation and entity
tracking within the app.

- **Bug Fixes**
- Fixed entity identification logic in test paths to ensure accurate
testing scenarios.

- **Refactor**
- Centralized datasource grouping logic for better maintainability and
performance.
- Optimized widget deletion process to handle multiple widgets
efficiently.

- **Documentation**
	- No user-facing documentation updates in this release.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2023-12-27 14:17:35 +05:30

310 lines
9.5 KiB
TypeScript

import type { FocusState } from "reducers/uiReducers/focusHistoryReducer";
import type {
CallEffectDescriptor,
PutEffectDescriptor,
SimpleEffect,
} from "redux-saga/effects";
import { call, put, select, take } from "redux-saga/effects";
import { getCurrentFocusInfo } from "selectors/focusHistorySelectors";
import type { FocusEntityInfo } from "navigation/FocusEntity";
import {
FocusEntity,
FocusStoreHierarchy,
identifyEntityFromPath,
} from "navigation/FocusEntity";
import type { Config } from "navigation/FocusElements";
import { ConfigType, FocusElementsConfig } from "navigation/FocusElements";
import {
removeFocusHistory,
storeFocusHistory,
} from "actions/focusHistoryActions";
import type { AppsmithLocationState } from "utils/history";
import { NavigationMethod } from "utils/history";
import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import type { Action } from "entities/Action";
import { getAction, getPlugin } from "@appsmith/selectors/entitiesSelector";
import type { Plugin } from "api/PluginApi";
import { getCurrentGitBranch } from "selectors/gitSyncSelectors";
import { getEntityParentUrl, isPageChange } from "../navigation/FocusUtils";
import { EditorState } from "../entities/IDE/constants";
/**
* Context switching works by restoring the states of ui elements to as they were
* the last time the user was on a particular URL.
*
* To do this, there are two simple steps
* 1. When leaving an url, store the ui or url states
* 2. When entering an url, restore stored ui or url states, or defaults
*
* @param currentPath
* @param previousPath
* @param state
*/
export function* contextSwitchingSaga(
currentPath: string,
previousPath: string,
state: AppsmithLocationState,
) {
if (previousPath) {
/* STORE THE UI STATE OF PREVIOUS URL */
// First get all the entities
const storePaths: Array<{
key: string;
entityInfo: FocusEntityInfo;
}> = yield call(getEntitiesForStore, previousPath);
for (const storePath of storePaths) {
yield call(
storeStateOfPath,
storePath.key,
storePath.entityInfo,
previousPath,
);
}
}
/* RESTORE THE UI STATE OF THE NEW URL */
yield call(waitForPathLoad, currentPath, previousPath);
const setPaths: Array<{
key: string;
entityInfo: FocusEntityInfo;
}> = yield call(getEntitiesForSet, previousPath, currentPath, state);
for (const setPath of setPaths) {
yield call(setStateOfPath, setPath.key, setPath.entityInfo);
}
}
function* waitForPathLoad(currentPath: string, previousPath?: string) {
if (previousPath) {
if (isPageChange(previousPath, currentPath)) {
yield take(ReduxActionTypes.FETCH_PAGE_SUCCESS);
}
}
}
type StoreStateOfPathType = Generator<
| SimpleEffect<"CALL", CallEffectDescriptor<unknown>>
| SimpleEffect<
"PUT",
PutEffectDescriptor<{
payload: { focusState: FocusState; key: string };
type: string;
}>
>,
void,
FocusState | undefined
>;
function* storeStateOfPath(
key: string,
entityInfo: FocusEntityInfo,
fromPath: string,
): StoreStateOfPathType {
const selectors = FocusElementsConfig[entityInfo.entity];
const state: Record<string, any> = {};
for (const selectorInfo of selectors) {
state[selectorInfo.name] = yield call(getState, selectorInfo, fromPath);
}
yield put(
storeFocusHistory(key, {
entityInfo,
state,
}),
);
}
function* setStateOfPath(key: string, entityInfo: FocusEntityInfo) {
const focusHistory: FocusState = yield select(getCurrentFocusInfo, key);
const selectors = FocusElementsConfig[entityInfo.entity];
if (focusHistory) {
for (const selectorInfo of selectors) {
yield call(setState, selectorInfo, focusHistory.state[selectorInfo.name]);
}
} else {
const subType: string | undefined = yield call(
getEntitySubType,
entityInfo,
);
for (const selectorInfo of selectors) {
const { defaultValue, subTypes } = selectorInfo;
if (subType && subTypes && subType in subTypes) {
yield call(setState, selectorInfo, subTypes[subType].defaultValue);
} else if (defaultValue !== undefined) {
if (typeof defaultValue === "function") {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const stateDefaultValue: unknown = yield select(defaultValue);
yield call(setState, selectorInfo, stateDefaultValue);
} else {
yield call(setState, selectorInfo, defaultValue);
}
}
}
}
}
function* getEntitySubType(entityInfo: FocusEntityInfo) {
if ([FocusEntity.API, FocusEntity.QUERY].includes(entityInfo.entity)) {
const action: Action | undefined = yield select(getAction, entityInfo.id);
if (action) {
const plugin: Plugin = yield select(getPlugin, action.pluginId);
return plugin.packageName;
}
}
}
/**
* This method returns boolean to indicate if state should be restored to the path
* @param prevPath
* @param currPath
* @param state
* @returns
*/
function shouldSetState(
prevPath: string,
currPath: string,
state?: AppsmithLocationState,
) {
if (
state &&
state.invokedBy &&
[NavigationMethod.CommandClick, NavigationMethod.Omnibar].includes(
state.invokedBy,
)
) {
// If it is a direct navigation, we will set the state
return true;
}
const prevFocusEntityInfo = identifyEntityFromPath(prevPath);
const currFocusEntityInfo = identifyEntityFromPath(currPath);
const isSamePage = !isPageChange(prevPath, currPath);
// While switching from selected widget state to canvas,
// it should not be restored stored state for canvas
return !(
prevFocusEntityInfo.entity === FocusEntity.PROPERTY_PANE &&
(currFocusEntityInfo.entity === FocusEntity.WIDGET_LIST ||
currFocusEntityInfo.entity === FocusEntity.CANVAS) &&
isSamePage
);
}
function* getEntitiesForStore(previousPath: string) {
const branch: string | undefined = yield select(getCurrentGitBranch);
const entities: Array<{ entityInfo: FocusEntityInfo; key: string }> = [];
const prevFocusEntityInfo = identifyEntityFromPath(previousPath);
if (prevFocusEntityInfo.entity in FocusStoreHierarchy) {
const parentEntity = FocusStoreHierarchy[prevFocusEntityInfo.entity];
if (parentEntity) {
const parentPath = getEntityParentUrl(prevFocusEntityInfo, parentEntity);
entities.push({
entityInfo: {
entity: parentEntity,
id: "",
pageId: prevFocusEntityInfo.pageId,
appState: prevFocusEntityInfo.appState,
},
key: `${parentPath}#${branch}`,
});
}
}
if (prevFocusEntityInfo.appState === EditorState.EDITOR) {
entities.push({
entityInfo: {
entity: FocusEntity.EDITOR,
id: `EDITOR.${prevFocusEntityInfo.pageId}`,
pageId: prevFocusEntityInfo.pageId,
appState: EditorState.EDITOR,
},
key: `EDITOR_STATE.${prevFocusEntityInfo.pageId}#${branch}`,
});
}
// Do not store focus of parents based on url change
if (
!Object.values(FocusStoreHierarchy).includes(prevFocusEntityInfo.entity)
) {
entities.push({
entityInfo: prevFocusEntityInfo,
key: `${previousPath}#${branch}`,
});
}
return entities.filter(
(entity) => entity.entityInfo.entity !== FocusEntity.NONE,
);
}
function* getEntitiesForSet(
previousPath: string,
currentPath: string,
state?: AppsmithLocationState,
) {
if (!shouldSetState(previousPath, currentPath, state)) {
return [];
}
const branch: string | undefined = yield select(getCurrentGitBranch);
const entities: Array<{ entityInfo: FocusEntityInfo; key: string }> = [];
const prevEntityInfo = identifyEntityFromPath(previousPath);
const currentEntityInfo = identifyEntityFromPath(currentPath);
if (
currentEntityInfo.entity === FocusEntity.CANVAS &&
(prevEntityInfo.pageId !== currentEntityInfo.pageId ||
prevEntityInfo.appState !== currentEntityInfo.appState)
) {
entities.push({
key: `EDITOR_STATE.${currentEntityInfo.pageId}#${branch}`,
entityInfo: {
id: `EDITOR.${currentEntityInfo.pageId}`,
appState: EditorState.EDITOR,
entity: FocusEntity.EDITOR,
},
});
}
entities.push({
entityInfo: currentEntityInfo,
key: `${currentPath}#${branch}`,
});
return entities.filter(
(entity) => entity.entityInfo.entity !== FocusEntity.NONE,
);
}
function* getState(config: Config, previousURL: string): unknown {
if (config.type === ConfigType.Redux) {
return yield select(config.selector);
} else if (config.type === ConfigType.URL) {
return config.selector(previousURL);
}
}
function* setState(config: Config, value: unknown): unknown {
if (config.type === ConfigType.Redux) {
yield put(config.setter(value));
} else if (config.type === ConfigType.URL) {
config.setter(value);
}
}
export function* handleRemoveFocusHistory(
action: ReduxAction<{ url: string }>,
) {
const { url } = action.payload;
const branch: string | undefined = yield select(getCurrentGitBranch);
const removeKeys: string[] = [];
const entity = identifyEntityFromPath(url);
removeKeys.push(`${url}#${branch}`);
const parentElement = FocusStoreHierarchy[entity.entity];
if (parentElement) {
const parentPath = getEntityParentUrl(entity, parentElement);
removeKeys.push(`${parentPath}#${branch}`);
}
for (const key of removeKeys) {
yield put(removeFocusHistory(key));
}
}