PromucFlow_constructor/app/client/src/sagas/WidgetDeletionSagas.ts
Preet Sidhu fa7bd6a543
feat: add layouts and widgets for sections and zones. (#29713)
## Description

1. Create Section Widget.
2. Create Zone Widget.
3. Create layouts and presets for Sections and zones.
4. Upate layout for Anvil Main Canvas.
5. Refactor BaseLayoutComponent. Separate renderer for edit and view
modes.
6. Add childrenMap context to avoid prop drilling through all layouts.
7. Add Anvil Config for WDS widgets.

#### Type of change
- New feature (non-breaking change which adds functionality)

## Testing
#### How Has This Been Tested?
- [x] Manual
- [ ] JUnit
- [ ] Jest
- [ ] Cypress

#### Test Plan

## Checklist:
#### Dev activity
- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [x] 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**
- Introduced a new `Zone Stepper Control` component for UI interaction.
- Added `AnvilCanvas` and `AnvilMainCanvas` components with improved
performance and interaction features.
- Implemented `LayoutProvider` and `useClickToClearSelections` for
better layout management.
- Launched `AnvilCanvasDraggingArena` and `AnvilHighlightingCanvas`
components with enhanced drag-and-drop capabilities.
- New `useZoneMinWidth` hook to calculate minimum zone width based on
child widgets.
- Added `SectionRow`, `Section`, `ZoneColumn`, and `Zone` components for
advanced layout structuring.
  - New `WidgetRenderer` component for dynamic child widget rendering.

- **Enhancements**
- Improved canvas activation and deactivation logic with
`useCanvasActivation` and `useCanvasActivationStates`.
- Enhanced drag-and-drop experience with updated `useCanvasDragging`
logic.
- Streamlined `AnvilMainCanvas` integration with conditional rendering
based on `renderMode`.
- Optimized `FlexLayout` component to handle new `isContainer` and
`layoutType` properties.

- **Bug Fixes**
- Fixed issues with widget positioning and event handling in
`WidgetNamesCanvas` components.
- Corrected `PageView` width property type for consistent page
rendering.

- **Refactor**
- Consolidated Anvil layout update management with `anvilSagas` and
`anvilChecksSagas`.
- Refined `SectionWidget` and `ZoneWidget` configuration for improved
stability and performance.
- Streamlined `LayoutElementPositionsObserver` with `layoutType`
enhancements.

- **Documentation**
- Updated comments and added clarifications for better developer
understanding of canvas-related hooks and components.

- **Style**
- Modified `.anvil-canvas` class styles for full-width and height
presentation.

- **Chores**
- Cleaned up import statements and removed unused code across various
components and utilities.

- **Tests**
- Enhanced Cypress tests with additional selectors and interaction
commands for `AutoDimension` feature verification.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Ashok Kumar M <35134347+marks0351@users.noreply.github.com>
2023-12-26 09:16:58 -05:00

479 lines
15 KiB
TypeScript

import type {
MultipleWidgetDeletePayload,
WidgetDelete,
} from "actions/pageActions";
import { closePropertyPane, closeTableFilterPane } from "actions/widgetActions";
import { selectWidgetInitAction } from "actions/widgetSelectionActions";
import type {
ApplicationPayload,
ReduxAction,
} from "@appsmith/constants/ReduxActionConstants";
import {
ReduxActionErrorTypes,
ReduxActionTypes,
WidgetReduxActionTypes,
} from "@appsmith/constants/ReduxActionConstants";
import { ENTITY_TYPE } from "entities/AppsmithConsole";
import LOG_TYPE from "entities/AppsmithConsole/logtype";
import { flattenDeep, omit, orderBy } from "lodash";
import type {
CanvasWidgetsReduxState,
FlattenedWidgetProps,
} from "reducers/entityReducers/canvasWidgetsReducer";
import { all, call, put, select, takeEvery } from "redux-saga/effects";
import {
getCanvasWidth,
getIsAutoLayoutMobileBreakPoint,
} from "selectors/editorSelectors";
import { getSelectedWidgets } from "selectors/ui";
import AnalyticsUtil from "utils/AnalyticsUtil";
import AppsmithConsole from "utils/AppsmithConsole";
import type { WidgetProps } from "widgets/BaseWidget";
import {
getSelectedWidget,
getWidget,
getWidgets,
getWidgetsMeta,
} from "./selectors";
import type { WidgetsInTree } from "./WidgetOperationUtils";
import {
getAllWidgetsInTree,
updateListWidgetPropertiesOnChildDelete,
} from "./WidgetOperationUtils";
import { showUndoRedoToast } from "utils/replayHelpers";
import WidgetFactory from "WidgetProvider/factory";
import {
inGuidedTour,
isExploringSelector,
} from "selectors/onboardingSelectors";
import { toggleShowDeviationDialog } from "actions/onboardingActions";
import { generateAutoHeightLayoutTreeAction } from "actions/autoHeightActions";
import { SelectionRequestType } from "sagas/WidgetSelectUtils";
import { updateFlexLayersOnDelete } from "../layoutSystems/autolayout/utils/AutoLayoutUtils";
import { LayoutSystemTypes } from "layoutSystems/types";
import { getLayoutSystemType } from "selectors/layoutSystemSelectors";
import { updateAnvilParentPostWidgetDeletion } from "layoutSystems/anvil/utils/layouts/update/deletionUtils";
import { getCurrentApplication } from "@appsmith/selectors/applicationSelectors";
import { saveAnvilLayout } from "layoutSystems/anvil/integrations/actions/saveLayoutActions";
const WidgetTypes = WidgetFactory.widgetTypes;
interface WidgetDeleteTabChild {
id: string;
index: number;
isVisible: boolean;
label: string;
widgetId: string;
}
function* deleteTabChildSaga(
deleteChildTabAction: ReduxAction<WidgetDeleteTabChild>,
) {
const { index, label, widgetId } = deleteChildTabAction.payload;
const allWidgets: CanvasWidgetsReduxState = yield select(getWidgets);
const tabWidget = allWidgets[widgetId];
if (tabWidget && tabWidget.parentId) {
const tabParentWidget = allWidgets[tabWidget.parentId];
const tabsArray: any = orderBy(
Object.values(tabParentWidget.tabsObj),
"index",
"asc",
);
if (tabsArray && tabsArray.length === 1) return;
const updatedArray = tabsArray.filter((eachItem: any, i: number) => {
return i !== index;
});
const updatedObj = updatedArray.reduce(
(obj: any, each: any, index: number) => {
obj[each.id] = {
...each,
index,
};
return obj;
},
{},
);
const widgetType: string = allWidgets[widgetId].type;
const updatedDslObj: UpdatedDSLPostDelete = yield call(
getUpdatedDslAfterDeletingWidget,
widgetId,
tabWidget.parentId,
);
if (updatedDslObj) {
const { finalWidgets, otherWidgetsToDelete } = updatedDslObj;
const parentUpdatedWidgets = {
...finalWidgets,
[tabParentWidget.widgetId]: {
...finalWidgets[tabParentWidget.widgetId],
tabsObj: updatedObj,
},
};
const layoutSystemType: LayoutSystemTypes =
yield select(getLayoutSystemType);
let finalData: CanvasWidgetsReduxState = parentUpdatedWidgets;
if (layoutSystemType === LayoutSystemTypes.AUTO) {
// Update flex layers of a canvas upon deletion of a widget.
const isMobile: boolean = yield select(getIsAutoLayoutMobileBreakPoint);
const mainCanvasWidth: number = yield select(getCanvasWidth);
const metaProps: Record<string, any> = yield select(getWidgetsMeta);
finalData = yield call(
updateFlexLayersOnDelete,
parentUpdatedWidgets,
widgetId,
tabWidget.parentId,
isMobile,
mainCanvasWidth,
metaProps,
);
} else if (layoutSystemType === LayoutSystemTypes.ANVIL) {
finalData = updateAnvilParentPostWidgetDeletion(
finalData,
tabWidget.parentId,
widgetId,
widgetType,
);
}
yield put(saveAnvilLayout(finalData));
yield call(postDelete, widgetId, label, otherWidgetsToDelete);
}
}
}
function* deleteSagaInit(deleteAction: ReduxAction<WidgetDelete>) {
const { widgetId } = deleteAction.payload;
const selectedWidget: FlattenedWidgetProps | undefined =
yield select(getSelectedWidget);
const selectedWidgets: string[] = yield select(getSelectedWidgets);
const guidedTourEnabled: boolean = yield select(inGuidedTour);
const isExploring: boolean = yield select(isExploringSelector);
if (guidedTourEnabled && !isExploring) {
yield put(toggleShowDeviationDialog(true));
return;
}
if (selectedWidgets.length > 1) {
yield put({
type: WidgetReduxActionTypes.WIDGET_BULK_DELETE,
payload: deleteAction.payload,
});
}
if (!!widgetId || !!selectedWidget) {
yield put({
type: WidgetReduxActionTypes.WIDGET_SINGLE_DELETE,
payload: deleteAction.payload,
});
}
}
type UpdatedDSLPostDelete =
| {
finalWidgets: CanvasWidgetsReduxState;
otherWidgetsToDelete: (WidgetProps & {
children?: string[] | undefined;
})[];
widgetName: string;
}
| undefined;
function* getUpdatedDslAfterDeletingWidget(widgetId: string, parentId: string) {
const stateWidgets: CanvasWidgetsReduxState = yield select(getWidgets);
if (widgetId && parentId) {
const widgets = { ...stateWidgets };
const stateWidget: WidgetProps = yield select(getWidget, widgetId);
const widget = { ...stateWidget };
const stateParent: FlattenedWidgetProps = yield select(getWidget, parentId);
let parent = { ...stateParent };
// Remove entry from parent's children
if (parent.children) {
parent = {
...parent,
children: parent.children.filter((c) => c !== widgetId),
};
}
widgets[parentId] = parent;
const otherWidgetsToDelete = getAllWidgetsInTree(widgetId, widgets);
let widgetName = widget.widgetName;
// SPECIAL HANDLING FOR TABS IN A TABS WIDGET
if (parent.type === WidgetTypes.TABS_WIDGET && widget.tabName) {
widgetName = widget.tabName;
}
let finalWidgets: CanvasWidgetsReduxState =
updateListWidgetPropertiesOnChildDelete(widgets, widgetId, widgetName);
finalWidgets = omit(
finalWidgets,
otherWidgetsToDelete.map((widgets) => widgets.widgetId),
);
return {
finalWidgets,
otherWidgetsToDelete,
widgetName,
} as UpdatedDSLPostDelete;
}
}
function* deleteSaga(deleteAction: ReduxAction<WidgetDelete>) {
try {
let { parentId, widgetId } = deleteAction.payload;
const { disallowUndo, isShortcut } = deleteAction.payload;
if (!widgetId) {
const selectedWidget: FlattenedWidgetProps | undefined =
yield select(getSelectedWidget);
if (!selectedWidget) return;
// if widget is not deletable, don't do anything
if (selectedWidget.isDeletable === false) return false;
widgetId = selectedWidget.widgetId;
parentId = selectedWidget.parentId;
}
if (widgetId && parentId) {
const stateWidget: WidgetProps = yield select(getWidget, widgetId);
const widget = { ...stateWidget };
const updatedObj: UpdatedDSLPostDelete = yield call(
getUpdatedDslAfterDeletingWidget,
widgetId,
parentId,
);
if (updatedObj) {
const { finalWidgets, otherWidgetsToDelete, widgetName } = updatedObj;
const layoutSystemType: LayoutSystemTypes =
yield select(getLayoutSystemType);
let finalData: CanvasWidgetsReduxState = finalWidgets;
if (layoutSystemType === LayoutSystemTypes.AUTO) {
const isMobile: boolean = yield select(
getIsAutoLayoutMobileBreakPoint,
);
const mainCanvasWidth: number = yield select(getCanvasWidth);
const metaProps: Record<string, any> = yield select(getWidgetsMeta);
// Update flex layers of a canvas upon deletion of a widget.
finalData = updateFlexLayersOnDelete(
finalWidgets,
widgetId,
parentId,
isMobile,
mainCanvasWidth,
metaProps,
);
} else if (layoutSystemType === LayoutSystemTypes.ANVIL) {
finalData = updateAnvilParentPostWidgetDeletion(
finalData,
parentId,
widgetId,
widget.type,
);
}
yield put(saveAnvilLayout(finalData));
yield put(generateAutoHeightLayoutTreeAction(true, true));
const currentApplication: ApplicationPayload = yield select(
getCurrentApplication,
);
const analyticsEvent = isShortcut
? "WIDGET_DELETE_VIA_SHORTCUT"
: "WIDGET_DELETE";
AnalyticsUtil.logEvent(analyticsEvent, {
widgetName: widget.widgetName,
widgetType: widget.type,
templateTitle: currentApplication?.forkedFromTemplateTitle,
});
if (!disallowUndo) {
// close property pane after delete
yield put(closePropertyPane());
yield put(
selectWidgetInitAction(SelectionRequestType.Unselect, [widgetId]),
);
yield call(postDelete, widgetId, widgetName, otherWidgetsToDelete);
}
}
}
} catch (error) {
yield put({
type: ReduxActionErrorTypes.WIDGET_OPERATION_ERROR,
payload: {
action: WidgetReduxActionTypes.WIDGET_DELETE,
error,
},
});
}
}
function* deleteAllSelectedWidgetsSaga(
deleteAction: ReduxAction<MultipleWidgetDeletePayload>,
) {
try {
const { disallowUndo = false } = deleteAction.payload;
const stateWidgets: CanvasWidgetsReduxState = yield select(getWidgets);
const widgets = { ...stateWidgets };
const selectedWidgets: string[] = yield select(getSelectedWidgets);
if (!(selectedWidgets && selectedWidgets.length !== 1)) return;
const widgetsToBeDeleted: WidgetsInTree = yield all(
selectedWidgets.map((eachId) => {
return call(getAllWidgetsInTree, eachId, widgets);
}),
);
const flattenedWidgets = flattenDeep(widgetsToBeDeleted);
const parentUpdatedWidgets = flattenedWidgets.reduce(
(allWidgets: any, eachWidget: any) => {
const { parentId, widgetId } = eachWidget;
const stateParent: FlattenedWidgetProps = allWidgets[parentId];
let parent = { ...stateParent };
if (parent.children) {
parent = {
...parent,
children: parent.children.filter((c) => c !== widgetId),
};
allWidgets[parentId] = parent;
}
return allWidgets;
},
widgets,
);
const finalWidgets: CanvasWidgetsReduxState = omit(
parentUpdatedWidgets,
flattenedWidgets.map((widgets: any) => widgets.widgetId),
);
let finalData = finalWidgets;
// assuming only widgets with same parent can be selected
const parentId = widgets[selectedWidgets[0]].parentId;
if (parentId) {
const layoutSystemType: LayoutSystemTypes =
yield select(getLayoutSystemType);
if (layoutSystemType === LayoutSystemTypes.AUTO) {
const isMobile: boolean = yield select(getIsAutoLayoutMobileBreakPoint);
const mainCanvasWidth: number = yield select(getCanvasWidth);
const metaProps: Record<string, any> = yield select(getWidgetsMeta);
for (const widgetId of selectedWidgets) {
finalData = yield call(
updateFlexLayersOnDelete,
finalWidgets,
widgetId,
parentId,
isMobile,
mainCanvasWidth,
metaProps,
);
}
} else if (layoutSystemType === LayoutSystemTypes.ANVIL) {
for (const widgetId of selectedWidgets) {
finalData = updateAnvilParentPostWidgetDeletion(
finalData,
parentId,
widgetId,
widgets[widgetId].type,
);
}
}
}
//Main canvas's minheight keeps varying, hence retrieving updated value
// let mainCanvasMinHeight;
// if (parentId === MAIN_CONTAINER_WIDGET_ID) {
// const mainCanvasProps: MainCanvasReduxState = yield select(
// getMainCanvasProps,
// );
// mainCanvasMinHeight = mainCanvasProps?.height;
// }
// if (parentId && widgetsAfterUpdatingFlexLayers[parentId]) {
// widgetsAfterUpdatingFlexLayers[
// parentId
// ].bottomRow = resizePublishedMainCanvasToLowestWidget(
// widgetsAfterUpdatingFlexLayers,
// parentId,
// finalWidgets[parentId].bottomRow,
// mainCanvasMinHeight,
// );
// }
yield put(saveAnvilLayout(finalData));
yield put(generateAutoHeightLayoutTreeAction(true, true));
yield put(selectWidgetInitAction(SelectionRequestType.Empty));
const bulkDeleteKey = selectedWidgets.join(",");
if (!disallowUndo) {
// close property pane after delete
yield put(closePropertyPane());
yield put(closeTableFilterPane());
showUndoRedoToast(`${selectedWidgets.length}`, true, false, true);
if (bulkDeleteKey) {
flattenedWidgets.map((widget: any) => {
AppsmithConsole.info({
logType: LOG_TYPE.ENTITY_DELETED,
text: "Widget was deleted",
source: {
name: widget.widgetName,
type: ENTITY_TYPE.WIDGET,
id: widget.widgetId,
},
analytics: {
widgetType: widget.type,
},
});
});
}
}
} catch (error) {
yield put({
type: ReduxActionErrorTypes.WIDGET_OPERATION_ERROR,
payload: {
action: WidgetReduxActionTypes.WIDGET_DELETE,
error,
},
});
}
}
function* postDelete(
widgetId: string,
widgetName: string,
otherWidgetsToDelete: (WidgetProps & {
children?: string[] | undefined;
})[],
) {
showUndoRedoToast(widgetName, false, false, true);
if (widgetId) {
otherWidgetsToDelete.map((widget) => {
AppsmithConsole.info({
logType: LOG_TYPE.ENTITY_DELETED,
text: "Widget was deleted",
source: {
name: widget.widgetName,
type: ENTITY_TYPE.WIDGET,
id: widget.widgetId,
},
analytics: {
widgetType: widget.type,
},
});
});
}
}
export default function* widgetDeletionSagas() {
yield all([
takeEvery(WidgetReduxActionTypes.WIDGET_DELETE, deleteSagaInit),
takeEvery(WidgetReduxActionTypes.WIDGET_SINGLE_DELETE, deleteSaga),
takeEvery(
WidgetReduxActionTypes.WIDGET_BULK_DELETE,
deleteAllSelectedWidgetsSaga,
),
takeEvery(ReduxActionTypes.WIDGET_DELETE_TAB_CHILD, deleteTabChildSaga),
]);
}