PromucFlow_constructor/app/client/src/pages/Editor/utils.ts
Ivan Akulov 424d2f6965
chore: upgrade to prettier v2 + enforce import types (#21013)Co-authored-by: Satish Gandham <hello@satishgandham.com> Co-authored-by: Satish Gandham <satish.iitg@gmail.com>
## Description

This PR upgrades Prettier to v2 + enforces TypeScript’s [`import
type`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export)
syntax where applicable. It’s submitted as a separate PR so we can merge
it easily.

As a part of this PR, we reformat the codebase heavily:
- add `import type` everywhere where it’s required, and
- re-format the code to account for Prettier 2’s breaking changes:
https://prettier.io/blog/2020/03/21/2.0.0.html#breaking-changes

This PR is submitted against `release` to make sure all new code by team
members will adhere to new formatting standards, and we’ll have fewer
conflicts when merging `bundle-optimizations` into `release`. (I’ll
merge `release` back into `bundle-optimizations` once this PR is
merged.)

### Why is this needed?

This PR is needed because, for the Lodash optimization from
7cbb12af88,
we need to use `import type`. Otherwise, `babel-plugin-lodash` complains
that `LoDashStatic` is not a lodash function.

However, just using `import type` in the current codebase will give you
this:

<img width="962" alt="Screenshot 2023-03-08 at 17 45 59"
src="https://user-images.githubusercontent.com/2953267/223775744-407afa0c-e8b9-44a1-90f9-b879348da57f.png">

That’s because Prettier 1 can’t parse `import type` at all. To parse it,
we need to upgrade to Prettier 2.

### Why enforce `import type`?

Apart from just enabling `import type` support, this PR enforces
specifying `import type` everywhere it’s needed. (Developers will get
immediate TypeScript and ESLint errors when they forget to do so.)

I’m doing this because I believe `import type` improves DX and makes
refactorings easier.

Let’s say you had a few imports like below. Can you tell which of these
imports will increase the bundle size? (Tip: it’s not all of them!)

```ts
// app/client/src/workers/Linting/utils.ts
import { Position } from "codemirror";
import { LintError as JSHintError, LintOptions } from "jshint";
import { get, isEmpty, isNumber, keys, last, set } from "lodash";
```

It’s pretty hard, right?

What about now?

```ts
// app/client/src/workers/Linting/utils.ts
import type { Position } from "codemirror";
import type { LintError as JSHintError, LintOptions } from "jshint";
import { get, isEmpty, isNumber, keys, last, set } from "lodash";
```

Now, it’s clear that only `lodash` will be bundled.

This helps developers to see which imports are problematic, but it
_also_ helps with refactorings. Now, if you want to see where
`codemirror` is bundled, you can just grep for `import \{.*\} from
"codemirror"` – and you won’t get any type-only imports.

This also helps (some) bundlers. Upon transpiling, TypeScript erases
type-only imports completely. In some environment (not ours), this makes
the bundle smaller, as the bundler doesn’t need to bundle type-only
imports anymore.

## Type of change

- Chore (housekeeping or task changes that don't impact user perception)


## How Has This Been Tested?

This was tested to not break the build.

### 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
- [x] 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
- [x] 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:
- [ ] Test plan has been approved by relevant developers
- [ ] Test plan has been peer reviewed by QA
- [ ] Cypress test cases have been added and approved by either SDET or
manual QA
- [ ] Organized project review call with relevant stakeholders after
Round 1/2 of QA
- [ ] Added Test Plan Approved label after reveiwing all Cypress test

---------

Co-authored-by: Satish Gandham <hello@satishgandham.com>
Co-authored-by: Satish Gandham <satish.iitg@gmail.com>
2023-03-16 17:11:47 +05:30

299 lines
8.3 KiB
TypeScript

import { getDependenciesFromInverseDependencies } from "components/editorComponents/Debugger/helpers";
import _, { debounce } from "lodash";
import { useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom";
import { useLocation } from "react-router";
import type { WidgetType } from "constants/WidgetConstants";
import ResizeObserver from "resize-observer-polyfill";
import WidgetFactory from "utils/WidgetFactory";
import {
createMessage,
WIDGET_DEPRECATION_MESSAGE,
} from "@appsmith/constants/messages";
import type { URLBuilderParams } from "RouteBuilder";
import { useSelector } from "react-redux";
import { getCurrentPageId } from "selectors/editorSelectors";
export const draggableElement = (
id: string,
element: any,
onPositionChange: any,
parentElement?: Element | null,
initPostion?: any,
renderDragBlockPositions?: {
left?: string;
top?: string;
zIndex?: string;
position?: string;
},
dragHandle?: () => JSX.Element,
cypressSelectorDragHandle?: string,
) => {
let newXPos = 0,
newYPos = 0,
oldXPos = 0,
oldYPos = 0;
let dragHandler = element;
let isDragged = !!initPostion;
const setElementPosition = () => {
element.style.top = initPostion.top + "px";
element.style.left = initPostion.left + "px";
};
const dragMouseDown = (e: MouseEvent) => {
e = e || window.event;
oldXPos = e.clientX;
oldYPos = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
};
const calculateBoundaryConfinedPosition = (
calculatedLeft: number,
calculatedTop: number,
) => {
const bottomBarOffset = 34;
/*
Default to 70 for a save offset that can also
handle the pagination Bar.
*/
const canvasTopOffset = parentElement?.getBoundingClientRect().top || 70;
if (calculatedLeft <= 0) {
calculatedLeft = 0;
}
if (calculatedTop <= canvasTopOffset) {
calculatedTop = canvasTopOffset;
}
if (calculatedLeft >= window.innerWidth - element.clientWidth) {
calculatedLeft = window.innerWidth - element.clientWidth;
}
if (
calculatedTop >=
window.innerHeight - (element.clientHeight + bottomBarOffset)
) {
calculatedTop =
window.innerHeight - element.clientHeight - bottomBarOffset;
}
return {
left: calculatedLeft,
top: calculatedTop,
};
};
const elementDrag = (e: MouseEvent) => {
e = e || window.event;
e.preventDefault();
newXPos = oldXPos - e.clientX;
newYPos = oldYPos - e.clientY;
oldXPos = e.clientX;
oldYPos = e.clientY;
const calculatedTop = element.offsetTop - newYPos;
const calculatedLeft = element.offsetLeft - newXPos;
element.style.top = calculatedTop + "px";
element.style.left = calculatedLeft + "px";
const validFirstDrag = !isDragged && newXPos !== 0 && newYPos !== 0;
if (validFirstDrag) {
resizeObserver.observe(element);
isDragged = true;
}
};
const calculateNewPosition = () => {
const { height, left, top, width } = element.getBoundingClientRect();
const isElementOpen = height && width;
const { left: calculatedLeft, top: calculatedTop } =
calculateBoundaryConfinedPosition(left, top);
return {
updatePosition: isDragged && isElementOpen,
left: calculatedLeft,
top: calculatedTop,
};
};
const updateElementPosition = () => {
const calculatedPositionData = calculateNewPosition();
if (calculatedPositionData.updatePosition) {
const { left, top } = calculatedPositionData;
onPositionChange({
left: left,
top: top,
});
element.style.top = top + "px";
element.style.left = left + "px";
}
};
const closeDragElement = () => {
updateElementPosition();
document.onmouseup = null;
document.onmousemove = null;
};
const debouncedUpdatePosition = debounce(updateElementPosition, 50);
const resizeObserver = new ResizeObserver(function () {
debouncedUpdatePosition();
});
if (isDragged) {
resizeObserver.observe(element);
}
const OnInit = () => {
if (dragHandle) {
dragHandler = createDragHandler(
id,
element,
dragHandle,
renderDragBlockPositions,
cypressSelectorDragHandle,
);
}
if (initPostion) {
setElementPosition();
}
dragHandler.addEventListener("mousedown", dragMouseDown);
// stop clicks from propogating to widget editor.
dragHandler.addEventListener("click", (e: any) => e.stopPropagation());
};
OnInit();
};
const createDragHandler = (
id: string,
el: any,
dragHandle: () => JSX.Element,
renderDragBlockPositions?: {
left?: string;
top?: string;
zIndex?: string;
position?: string;
},
cypressSelectorDragHandle?: string,
) => {
const oldDragHandler = document.getElementById(`${id}-draghandler`);
const dragElement = document.createElement("div");
dragElement.setAttribute("id", `${id}-draghandler`);
dragElement.style.position = renderDragBlockPositions?.position ?? "absolute";
dragElement.style.left = renderDragBlockPositions?.left ?? "135px";
dragElement.style.top = renderDragBlockPositions?.top ?? "0px";
dragElement.style.zIndex = renderDragBlockPositions?.zIndex ?? "3";
if (cypressSelectorDragHandle) {
dragElement.setAttribute("data-cy", cypressSelectorDragHandle);
}
oldDragHandler
? el.replaceChild(dragElement, oldDragHandler)
: el.appendChild(dragElement);
ReactDOM.render(dragHandle(), dragElement);
return dragElement;
};
// Function to access nested property in an object
const getNestedValue = (obj: Record<string, any>, path = "") => {
return path.split(".").reduce((prev, cur) => {
return prev && prev[cur];
}, obj);
};
export const useIsWidgetActionConnectionPresent = (
widgets: any,
actions: any,
deps: any,
): boolean => {
const actionLables = actions.map((action: any) => action.config.name);
let isBindingAvailable = !!Object.values(widgets).find((widget: any) => {
const depsConnections = getDependenciesFromInverseDependencies(
deps,
widget.widgetName,
);
return !!_.intersection(depsConnections?.directDependencies, actionLables)
.length;
});
if (!isBindingAvailable) {
isBindingAvailable = !!Object.values(widgets).find((widget: any) => {
return (
widget.dynamicTriggerPathList &&
!!widget.dynamicTriggerPathList.find((path: { key: string }) => {
return !!actionLables.find((label: string) => {
const snippet = getNestedValue(widget, path.key);
return snippet ? snippet.indexOf(`${label}.run`) > -1 : false;
});
})
);
});
}
return isBindingAvailable;
};
export const useQuery = () => {
const { search } = useLocation();
return useMemo(() => new URLSearchParams(search), [search]);
};
/**
* Method that returns if the WidgetType is deprecated along with,
* deprecated widget's display name (currentWidgetName) and
* the name of the widget that is being replaced with (widgetReplacedWith)
*
* @param WidgetType
* @returns
*/
export function isWidgetDeprecated(WidgetType: WidgetType) {
const currentWidgetConfig = WidgetFactory.widgetConfigMap.get(WidgetType);
const isDeprecated = !!currentWidgetConfig?.isDeprecated;
let widgetReplacedWith;
if (isDeprecated && currentWidgetConfig?.replacement) {
widgetReplacedWith = WidgetFactory.widgetConfigMap.get(
currentWidgetConfig.replacement,
)?.displayName;
}
return {
isDeprecated,
currentWidgetName: currentWidgetConfig?.displayName,
widgetReplacedWith,
};
}
export function buildDeprecationWidgetMessage(replacingWidgetName: string) {
const deprecationMessage = createMessage(
WIDGET_DEPRECATION_MESSAGE,
replacingWidgetName,
);
return `${deprecationMessage}`;
}
/**
* Use this hook if you are try to set href in components that could possibly mount before the application is initialized.
* Eg. Deploy button in header.
* @param urlBuilderFn
* @param params
* @returns URL
*/
export function useHref<T extends URLBuilderParams>(
urlBuilderFn: (params: T) => string,
params: T,
) {
const [href, setHref] = useState("");
// Current pageId selector serves as delay to generate urls
const pageId = useSelector(getCurrentPageId);
useEffect(() => {
if (pageId) setHref(urlBuilderFn(params));
}, [params, urlBuilderFn, pageId]);
return href;
}