PromucFlow_constructor/app/client/src/widgets/ButtonWidget/component/index.tsx

487 lines
13 KiB
TypeScript
Raw Normal View History

import React, { useRef, useState } from "react";
import styled, { createGlobalStyle, css } from "styled-components";
import Interweave from "interweave";
2020-02-12 08:23:50 +00:00
import {
IButtonProps,
MaybeElement,
2020-03-30 08:55:52 +00:00
Button,
Alignment,
Position,
Classes,
2020-02-12 08:23:50 +00:00
} from "@blueprintjs/core";
import { Popover2 } from "@blueprintjs/popover2";
import { IconName } from "@blueprintjs/icons";
import { ComponentProps } from "widgets/BaseComponent";
import { useScript, ScriptStatus, AddScriptTo } from "utils/hooks/useScript";
import {
GOOGLE_RECAPTCHA_KEY_ERROR,
GOOGLE_RECAPTCHA_DOMAIN_ERROR,
createMessage,
refactor: admin settings (#9906) * refactor admin settings feature * separated save-restart bar to separate component * created new CE dir to facilitate code split * created separate ee dir and exporting everything we have in ce file. * little mod * minor fix * splitting settings types config * using object literals for category types instead of enums * CE: support use of component for each category * minor style fix * authentication page UI changes implemented * github signup doc url added back * removed comments * routing updates * made subcategories listing in left pane optional * added muted saml to auth listing * added breadcrumbs and enabled button * created separate component for auth page and auth config * added callout and disconnect components * updated breadcrumbs component * minor updates to common components * updated warning callout and added icon * ce: test cases fixed * updated test file name * warning banner callout added on auth page * updated callout banner for form login * CE: Split config files * CE: moved the window declaration in EE file as its dependency will be updated in EE * CE: Splitting ApiConstants and SocialLogin constants * CE: split login page * CE: moved getSocialLoginButtonProps func to EE file as it's dependencies will be updated in EE * added key icon * CE: created a factory class to share social auths list * Minor style fix for social btns * Updated the third party auth styles * Small fixes to styling * ce: splitting forms constants * breadcrumbs implemented for all pages in admin settings * Settings breadcrumbs separated * splitted settings breadcrumbs between ce and ee * renamed default import * minor style fix * added login form config. * updated login/signup pages to use form login disabled config * removed common functionality outside * implemented breadcrumb component from scratch without using blueprint * removed unwanted code * Small style update * updated breadcrumb categories file name and breadcrumb icon * added cypress tests for admin settings auth page * added comments * update locator for upgrade button * added link for intercom on upgrade button * removed unnecessary file * minor style fix * style fix for auth option cards * split messages constant * fixed imports for message constants splitting. * added message constants * updated unit test cases * fixed messages import in cypress index * fixed messages import again, cypress fails to read re-exported objs. * added OIDC auth method on authentication page * updated import statements from ee to @appsmith * removed dead code * updated read more link UI * PR comments fixes * some UI fixes * used color and fonts from theme * fixed some imports * fixed some imports * removed warning imports * updated OIDC logo and auth method desc copies * css changes * css changes * css changes * updated cypress test for breadcrumb * moved callout component to ads as calloutv2 * UI changes for form fields * updated css for spacing between form fields * added sub-text on auth pages * added active class for breadcrumb item * added config for disable signup toggle and fixed UI issues of restart banner * fixed admin settings page bugs * assigned true as default state for signup * fixed messages import statements * updated code for PR comments related suggestions * reverted file path change in cypress support * updated cypress test * updated cypress test Co-authored-by: Ankita Kinger <ankita@appsmith.com>
2022-02-11 18:08:46 +00:00
} from "@appsmith/constants/messages";
import { ThemeProp, Variant } from "components/ads/common";
2020-11-24 07:01:37 +00:00
import { Toaster } from "components/ads/Toast";
import ReCAPTCHA from "react-google-recaptcha";
import { Colors } from "constants/Colors";
import _ from "lodash";
import {
ButtonBoxShadow,
ButtonBoxShadowTypes,
ButtonBorderRadius,
ButtonBorderRadiusTypes,
ButtonVariant,
ButtonVariantTypes,
RecaptchaType,
RecaptchaTypes,
ButtonPlacement,
} from "components/constants";
import {
getCustomBackgroundColor,
getCustomBorderColor,
getCustomTextColor,
getCustomJustifyContent,
getAlignText,
} from "widgets/WidgetUtils";
import { DragContainer } from "./DragContainer";
import { buttonHoverActiveStyles } from "./utils";
const RecaptchaWrapper = styled.div`
position: relative;
.grecaptcha-badge {
visibility: hidden;
}
`;
const ToolTipWrapper = styled.div`
height: 100%;
&& .bp3-popover2-target {
height: 100%;
width: 100%;
& > div {
height: 100%;
}
}
`;
const TooltipStyles = createGlobalStyle`
.btnTooltipContainer {
.bp3-popover2-content {
max-width: 350px;
overflow-wrap: anywhere;
padding: 10px 12px;
border-radius: 0px;
}
}
`;
/*
Don't use buttonHoverActiveStyles in a nested function it won't work -
const buttonHoverActiveStyles = css ``
const Button = styled.button`
// won't work
${({ buttonColor, theme }) => {
&:hover, &:active {
${buttonHoverActiveStyles}
}
}}
// will work
&:hover, &:active {
${buttonHoverActiveStyles}
}`
*/
const buttonBaseStyle = css<ThemeProp & ButtonStyleProps>`
height: 100%;
background-image: none !important;
font-weight: ${(props) => props.theme.fontWeights[2]};
outline: none;
padding: 0px 10px;
2019-10-21 15:12:45 +00:00
&:hover, &:active {
${buttonHoverActiveStyles}
}
${({ buttonColor, buttonVariant, theme }) => `
background: ${
getCustomBackgroundColor(buttonVariant, buttonColor) !== "none"
? getCustomBackgroundColor(buttonVariant, buttonColor)
: buttonVariant === ButtonVariantTypes.PRIMARY
? theme.colors.button.primary.primary.bgColor
: "none"
} !important;
&:disabled, &.${Classes.DISABLED} {
background-color: ${theme.colors.button.disabled.bgColor} !important;
cursor: not-allowed;
color: ${theme.colors.button.disabled.textColor} !important;
border-color: ${theme.colors.button.disabled.bgColor} !important;
> span {
color: ${theme.colors.button.disabled.textColor} !important;
}
}
border: ${
getCustomBorderColor(buttonVariant, buttonColor) !== "none"
? `1px solid ${getCustomBorderColor(buttonVariant, buttonColor)}`
: buttonVariant === ButtonVariantTypes.SECONDARY
? `1px solid ${theme.colors.button.primary.secondary.borderColor}`
: "none"
} !important;
& > span {
max-height: 100%;
max-width: 99%;
text-overflow: ellipsis;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
color: ${
buttonVariant === ButtonVariantTypes.PRIMARY
? getCustomTextColor(theme, buttonColor)
: getCustomBackgroundColor(ButtonVariantTypes.PRIMARY, buttonColor)
} !important;
2019-10-21 15:12:45 +00:00
}
`}
border-radius: ${({ borderRadius }) =>
borderRadius === ButtonBorderRadiusTypes.ROUNDED ? "5px" : 0};
box-shadow: ${({ boxShadow, boxShadowColor, theme }) =>
boxShadow === ButtonBoxShadowTypes.VARIANT1
? `0px 0px 4px 3px ${boxShadowColor ||
theme.colors.button.boxShadow.default.variant1}`
: boxShadow === ButtonBoxShadowTypes.VARIANT2
? `3px 3px 4px ${boxShadowColor ||
theme.colors.button.boxShadow.default.variant2}`
: boxShadow === ButtonBoxShadowTypes.VARIANT3
? `0px 1px 3px ${boxShadowColor ||
theme.colors.button.boxShadow.default.variant3}`
: boxShadow === ButtonBoxShadowTypes.VARIANT4
? `2px 2px 0px ${boxShadowColor ||
theme.colors.button.boxShadow.default.variant4}`
: boxShadow === ButtonBoxShadowTypes.VARIANT5
? `-2px -2px 0px ${boxShadowColor ||
theme.colors.button.boxShadow.default.variant5}`
: "none"} !important;
${({ placement }) =>
placement
? `
justify-content: ${getCustomJustifyContent(placement)};
& > span.bp3-button-text {
flex: unset !important;
}
`
: ""}
`;
2019-10-21 15:12:45 +00:00
const StyledButton = styled((props) => (
<Button
{..._.omit(props, [
"borderRadius",
"boxShadow",
"boxShadowColor",
"buttonColor",
"buttonVariant",
])}
/>
))<ThemeProp & ButtonStyleProps>`
${buttonBaseStyle}
`;
export type ButtonStyleProps = {
buttonColor?: string;
buttonVariant?: ButtonVariant;
boxShadow?: ButtonBoxShadow;
boxShadowColor?: string;
borderRadius?: ButtonBorderRadius;
iconName?: IconName;
iconAlign?: Alignment;
placement?: ButtonPlacement;
2019-10-21 15:12:45 +00:00
};
// To be used in any other part of the app
export function BaseButton(props: IButtonProps & ButtonStyleProps) {
const {
borderRadius,
boxShadow,
boxShadowColor,
buttonColor,
buttonVariant,
className,
disabled,
icon,
iconAlign,
iconName,
loading,
onClick,
placement,
rightIcon,
text,
} = props;
const isRightAlign = iconAlign === Alignment.RIGHT;
return (
<DragContainer
buttonColor={buttonColor}
buttonVariant={buttonVariant}
disabled={disabled}
loading={loading}
onClick={onClick}
showInAllModes
>
<StyledButton
alignText={getAlignText(isRightAlign, iconName)}
borderRadius={borderRadius}
boxShadow={boxShadow}
boxShadowColor={boxShadowColor}
buttonColor={buttonColor}
buttonVariant={buttonVariant}
className={className}
data-test-variant={buttonVariant}
disabled={disabled}
fill
icon={isRightAlign ? icon : iconName || icon}
loading={loading}
onClick={onClick}
placement={placement}
rightIcon={isRightAlign ? iconName || rightIcon : rightIcon}
text={text}
/>
</DragContainer>
);
}
2019-10-21 15:12:45 +00:00
BaseButton.defaultProps = {
buttonColor: Colors.GREEN,
buttonVariant: ButtonVariantTypes.PRIMARY,
disabled: false,
2019-10-21 15:12:45 +00:00
text: "Button Text",
minimal: true,
};
2020-03-06 09:45:21 +00:00
export enum ButtonType {
SUBMIT = "submit",
RESET = "reset",
BUTTON = "button",
}
interface RecaptchaProps {
googleRecaptchaKey?: string;
clickWithRecaptcha: (token: string) => void;
handleRecaptchaV2Loading?: (isLoading: boolean) => void;
recaptchaType?: RecaptchaType;
}
interface ButtonComponentProps extends ComponentProps {
text?: string;
icon?: IconName | MaybeElement;
tooltip?: string;
2019-10-21 15:12:45 +00:00
onClick?: (event: React.MouseEvent<HTMLElement>) => void;
isDisabled?: boolean;
2019-12-03 04:41:10 +00:00
isLoading: boolean;
2020-02-12 08:23:50 +00:00
rightIcon?: IconName | MaybeElement;
2020-03-06 09:45:21 +00:00
type: ButtonType;
buttonColor?: string;
buttonVariant?: ButtonVariant;
borderRadius?: ButtonBorderRadius;
boxShadow?: ButtonBoxShadow;
boxShadowColor?: string;
iconName?: IconName;
iconAlign?: Alignment;
placement?: ButtonPlacement;
2019-10-21 15:12:45 +00:00
}
function RecaptchaV2Component(
props: {
children: any;
2022-03-22 06:52:39 +00:00
isDisabled?: boolean;
recaptchaType?: RecaptchaType;
handleError: (event: React.MouseEvent<HTMLElement>, error: string) => void;
} & RecaptchaProps,
) {
const recaptchaRef = useRef<ReCAPTCHA>(null);
const [isInvalidKey, setInvalidKey] = useState(false);
const handleRecaptchaLoading = (isloading: boolean) => {
props.handleRecaptchaV2Loading && props.handleRecaptchaV2Loading(isloading);
};
const handleBtnClick = async (event: React.MouseEvent<HTMLElement>) => {
2022-03-22 06:52:39 +00:00
if (props.isDisabled) return;
if (isInvalidKey) {
// Handle incorrent google recaptcha site key
props.handleError(event, createMessage(GOOGLE_RECAPTCHA_KEY_ERROR));
} else {
handleRecaptchaLoading(true);
try {
await recaptchaRef?.current?.reset();
const token = await recaptchaRef?.current?.executeAsync();
if (token) {
props.clickWithRecaptcha(token);
} else {
// Handle incorrent google recaptcha site key
props.handleError(event, createMessage(GOOGLE_RECAPTCHA_KEY_ERROR));
}
handleRecaptchaLoading(false);
} catch (err) {
handleRecaptchaLoading(false);
// Handle error due to google recaptcha key of different domain
props.handleError(event, createMessage(GOOGLE_RECAPTCHA_DOMAIN_ERROR));
}
}
};
return (
<RecaptchaWrapper onClick={handleBtnClick}>
{props.children}
<ReCAPTCHA
onErrored={() => setInvalidKey(true)}
ref={recaptchaRef}
sitekey={props.googleRecaptchaKey || ""}
size="invisible"
/>
</RecaptchaWrapper>
);
}
function RecaptchaV3Component(
props: {
children: any;
2022-03-22 06:52:39 +00:00
isDisabled?: boolean;
recaptchaType?: RecaptchaType;
handleError: (event: React.MouseEvent<HTMLElement>, error: string) => void;
} & RecaptchaProps,
) {
// Check if a string is a valid JSON string
const checkValidJson = (inputString: string): boolean => {
return !inputString.includes('"');
};
const handleBtnClick = (event: React.MouseEvent<HTMLElement>) => {
2022-03-22 06:52:39 +00:00
if (props.isDisabled) return;
if (status === ScriptStatus.READY) {
(window as any).grecaptcha.ready(() => {
try {
(window as any).grecaptcha
.execute(props.googleRecaptchaKey, {
action: "submit",
})
.then((token: any) => {
props.clickWithRecaptcha(token);
})
.catch(() => {
// Handle incorrent google recaptcha site key
props.handleError(
event,
createMessage(GOOGLE_RECAPTCHA_KEY_ERROR),
);
});
} catch (err) {
// Handle error due to google recaptcha key of different domain
props.handleError(
event,
createMessage(GOOGLE_RECAPTCHA_DOMAIN_ERROR),
);
}
});
}
};
let validGoogleRecaptchaKey = props.googleRecaptchaKey;
if (validGoogleRecaptchaKey && !checkValidJson(validGoogleRecaptchaKey)) {
validGoogleRecaptchaKey = undefined;
}
const status = useScript(
`https://www.google.com/recaptcha/api.js?render=${validGoogleRecaptchaKey}`,
AddScriptTo.HEAD,
);
return <div onClick={handleBtnClick}>{props.children}</div>;
}
function BtnWrapper(
props: {
children: any;
2022-03-22 06:52:39 +00:00
isDisabled?: boolean;
onClick?: (event: React.MouseEvent<HTMLElement>) => void;
} & RecaptchaProps,
) {
if (!props.googleRecaptchaKey)
return <div onClick={props.onClick}>{props.children}</div>;
else {
const handleError = (
event: React.MouseEvent<HTMLElement>,
error: string,
) => {
Toaster.show({
text: error,
variant: Variant.danger,
});
props.onClick && props.onClick(event);
};
if (props.recaptchaType === RecaptchaTypes.V2) {
return <RecaptchaV2Component {...props} handleError={handleError} />;
} else {
return <RecaptchaV3Component {...props} handleError={handleError} />;
}
}
}
2019-10-21 15:12:45 +00:00
// To be used with the canvas
function ButtonComponent(props: ButtonComponentProps & RecaptchaProps) {
const btnWrapper = (
<BtnWrapper
clickWithRecaptcha={props.clickWithRecaptcha}
googleRecaptchaKey={props.googleRecaptchaKey}
handleRecaptchaV2Loading={props.handleRecaptchaV2Loading}
2022-03-22 06:52:39 +00:00
isDisabled={props.isDisabled}
onClick={props.onClick}
recaptchaType={props.recaptchaType}
>
<BaseButton
borderRadius={props.borderRadius}
boxShadow={props.boxShadow}
boxShadowColor={props.boxShadowColor}
buttonColor={props.buttonColor}
buttonVariant={props.buttonVariant}
disabled={props.isDisabled}
icon={props.icon}
iconAlign={props.iconAlign}
iconName={props.iconName}
loading={props.isLoading}
placement={props.placement}
rightIcon={props.rightIcon}
text={props.text}
type={props.type}
/>
</BtnWrapper>
2019-10-21 15:12:45 +00:00
);
if (props.tooltip) {
return (
<ToolTipWrapper>
<TooltipStyles />
<Popover2
autoFocus={false}
content={<Interweave content={props.tooltip} />}
hoverOpenDelay={200}
interactionKind="hover"
portalClassName="btnTooltipContainer"
position={Position.TOP}
>
{btnWrapper}
</Popover2>
</ToolTipWrapper>
);
} else {
return btnWrapper;
}
}
2019-10-21 15:12:45 +00:00
export default ButtonComponent;