PromucFlow_constructor/app/client/src/widgets/PhoneInputWidget/widget/index.tsx
albinAppsmith 629999f124
feat: [epic] appsmith design system version 2 deduplication (#22030)
## Description

### Fixes
- [x] https://github.com/appsmithorg/appsmith/issues/19383
- [x] https://github.com/appsmithorg/appsmith/issues/19384
- [x] https://github.com/appsmithorg/appsmith/issues/19385
- [x] https://github.com/appsmithorg/appsmith/issues/19386
- [x] https://github.com/appsmithorg/appsmith/issues/19387
- [x] https://github.com/appsmithorg/appsmith/issues/19388
- [x] https://github.com/appsmithorg/appsmith/issues/19389
- [x] https://github.com/appsmithorg/appsmith/issues/19390
- [x] https://github.com/appsmithorg/appsmith/issues/19391
- [x] https://github.com/appsmithorg/appsmith/issues/19392
- [x] https://github.com/appsmithorg/appsmith/issues/19393
- [x] https://github.com/appsmithorg/appsmith/issues/19394
- [x] https://github.com/appsmithorg/appsmith/issues/19395
- [x] https://github.com/appsmithorg/appsmith/issues/19396
- [x] https://github.com/appsmithorg/appsmith/issues/19397
- [x] https://github.com/appsmithorg/appsmith/issues/19398
- [x] https://github.com/appsmithorg/appsmith/issues/19399
- [x] https://github.com/appsmithorg/appsmith/issues/19400
- [x] https://github.com/appsmithorg/appsmith/issues/19401
- [x] https://github.com/appsmithorg/appsmith/issues/19402
- [x] https://github.com/appsmithorg/appsmith/issues/19403
- [x] https://github.com/appsmithorg/appsmith/issues/19404
- [x] https://github.com/appsmithorg/appsmith/issues/19405
- [x] https://github.com/appsmithorg/appsmith/issues/19406
- [x] https://github.com/appsmithorg/appsmith/issues/19407
- [x] https://github.com/appsmithorg/appsmith/issues/19408
- [x] https://github.com/appsmithorg/appsmith/issues/19409

Fixes # (issue)
> if no issue exists, please create an issue and ask the maintainers
about this first


Media
> A video or a GIF is preferred. when using Loom, don’t embed because it
looks like it’s a GIF. instead, just link to the video


## Type of change

> Please delete options that are not relevant.

- Bug fix (non-breaking change which fixes an issue)
- New feature (non-breaking change which adds functionality)
- Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- Chore (housekeeping or task changes that don't impact user perception)
- This change requires a documentation update


## How Has This Been Tested?
> Please describe the tests that you ran to verify your changes. Provide
instructions, so we can reproduce.
> Please also list any relevant details for your test configuration.
> Delete anything that is not important

- Manual
- 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:
- [ ] 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: Ankita Kinger <ankita@appsmith.com>
Co-authored-by: akash-codemonk <67054171+akash-codemonk@users.noreply.github.com>
Co-authored-by: Tanvi Bhakta <tanvi@appsmith.com>
Co-authored-by: Arsalan <arsalanyaldram0211@outlook.com>
Co-authored-by: Aman Agarwal <aman@appsmith.com>
Co-authored-by: Rohit Agarwal <rohit_agarwal@live.in>
Co-authored-by: Nilesh Sarupriya <nilesh@appsmith.com>
Co-authored-by: Nilesh Sarupriya <20905988+nsarupr@users.noreply.github.com>
Co-authored-by: Tanvi Bhakta <tanvibhakta@gmail.com>
Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
Co-authored-by: Parthvi Goswami <parthvigoswami@Parthvis-MacBook-Pro.local>
Co-authored-by: Vijetha-Kaja <vijetha@appsmith.com>
Co-authored-by: Parthvi <80334441+Parthvi12@users.noreply.github.com>
Co-authored-by: Apple <nandan@thinkify.io>
Co-authored-by: Saroj <43822041+sarojsarab@users.noreply.github.com>
Co-authored-by: Sangeeth Sivan <74818788+berzerkeer@users.noreply.github.com>
Co-authored-by: Ashok Kumar M <35134347+marks0351@users.noreply.github.com>
Co-authored-by: Aishwarya-U-R <91450662+Aishwarya-U-R@users.noreply.github.com>
Co-authored-by: rahulramesha <rahul@appsmith.com>
Co-authored-by: Aswath K <aswath.sana@gmail.com>
Co-authored-by: Preet Sidhu <preetsidhu.bits@gmail.com>
Co-authored-by: Vijetha-Kaja <119562824+Vijetha-Kaja@users.noreply.github.com>
Co-authored-by: Shrikant Sharat Kandula <shrikant@appsmith.com>
2023-05-20 00:07:06 +05:30

438 lines
13 KiB
TypeScript

import React from "react";
import type { WidgetState } from "widgets/BaseWidget";
import type { WidgetType } from "constants/WidgetConstants";
import type { PhoneInputComponentProps } from "../component";
import PhoneInputComponent from "../component";
import { EventType } from "constants/AppsmithActionConstants/ActionConstants";
import type { ValidationResponse } from "constants/WidgetValidation";
import { ValidationTypes } from "constants/WidgetValidation";
import {
createMessage,
FIELD_REQUIRED_ERROR,
} from "@appsmith/constants/messages";
import type { DerivedPropertiesMap } from "utils/WidgetFactory";
import {
getCountryCode,
ISDCodeDropdownOptions,
} from "../component/ISDCodeDropdown";
import { AutocompleteDataType } from "utils/autocomplete/AutocompleteDataType";
import _ from "lodash";
import BaseInputWidget from "widgets/BaseInputWidget";
import derivedProperties from "./parsedDerivedProperties";
import type { BaseInputWidgetProps } from "widgets/BaseInputWidget/widget";
import { mergeWidgetConfig } from "utils/helpers";
import type { CountryCode } from "libphonenumber-js";
import { AsYouType, parseIncompletePhoneNumber } from "libphonenumber-js";
import * as Sentry from "@sentry/react";
import log from "loglevel";
import { GRID_DENSITY_MIGRATION_V1 } from "widgets/constants";
import type { Stylesheet } from "entities/AppTheming";
import {
isAutoHeightEnabledForWidget,
DefaultAutocompleteDefinitions,
} from "widgets/WidgetUtils";
import type { AutocompletionDefinitions } from "widgets/constants";
export function defaultValueValidation(
value: any,
props: PhoneInputWidgetProps,
_?: any,
): ValidationResponse {
const STRING_ERROR_MESSAGE = {
name: "TypeError",
message: "This value must be string",
};
const EMPTY_ERROR_MESSAGE = { name: "", message: "" };
if (_.isObject(value)) {
return {
isValid: false,
parsed: JSON.stringify(value, null, 2),
messages: [STRING_ERROR_MESSAGE],
};
}
let parsed = value;
if (!_.isString(value)) {
try {
parsed = _.toString(value);
} catch (e) {
return {
isValid: false,
parsed: "",
messages: [STRING_ERROR_MESSAGE],
};
}
}
return {
isValid: _.isString(parsed),
parsed: parsed,
messages: [EMPTY_ERROR_MESSAGE],
};
}
class PhoneInputWidget extends BaseInputWidget<
PhoneInputWidgetProps,
WidgetState
> {
static getPropertyPaneContentConfig() {
return mergeWidgetConfig(
[
{
sectionName: "Data",
children: [
{
helpText:
"Sets the default text of the widget. The text is updated if the default text changes",
propertyName: "defaultText",
label: "Default value",
controlType: "INPUT_TEXT",
placeholderText: "(000) 000-0000",
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.FUNCTION,
params: {
fn: defaultValueValidation,
expected: {
type: "string",
example: `(000) 000-0000`,
autocompleteDataType: AutocompleteDataType.STRING,
},
},
},
},
{
helpText: "Changes the country code",
propertyName: "defaultDialCode",
label: "Default country code",
enableSearch: true,
dropdownHeight: "156px",
controlType: "DROP_DOWN",
searchPlaceholderText: "Search by code or country name",
options: ISDCodeDropdownOptions,
virtual: true,
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.TEXT,
},
},
{
propertyName: "allowDialCodeChange",
label: "Change country code",
helpText: "Search by country",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
],
},
{
sectionName: "Label",
children: [],
},
{
sectionName: "Validation",
children: [
{
propertyName: "isRequired",
label: "Required",
helpText: "Makes input to the widget mandatory",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
],
},
// {
// sectionName: "General",
// children: [
// {
// propertyName: "allowFormatting",
// label: "Enable Formatting",
// helpText: "Formats the phone number as per the country selected",
// controlType: "SWITCH",
// isJSConvertible: true,
// isBindProperty: true,
// isTriggerProperty: false,
// validation: { type: ValidationTypes.BOOLEAN },
// },
// ],
// },
],
super.getPropertyPaneContentConfig(),
);
}
static getAutocompleteDefinitions(): AutocompletionDefinitions {
return {
"!doc":
"An input text field is used to capture a phone number. Inputs are used in forms and can have custom validations.",
"!url": "https://docs.appsmith.com/widget-reference/phone-input",
text: {
"!type": "string",
"!doc": "The text value of the input",
"!url": "https://docs.appsmith.com/widget-reference/phone-input",
},
value: {
"!type": "string",
"!doc": "The unformatted text value of the input",
"!url": "https://docs.appsmith.com/widget-reference/phone-input",
},
isValid: "bool",
isVisible: DefaultAutocompleteDefinitions.isVisible,
isDisabled: "bool",
countryCode: {
"!type": "string",
"!doc": "Selected country code for Phone Number",
},
dialCode: {
"!type": "string",
"!doc": "Selected dialing code for Phone Number",
},
};
}
static getPropertyPaneStyleConfig() {
return super.getPropertyPaneStyleConfig();
}
static getDerivedPropertiesMap(): DerivedPropertiesMap {
return {
isValid: `{{(() => {${derivedProperties.isValid}})()}}`,
};
}
static getMetaPropertiesMap(): Record<string, any> {
return _.merge(super.getMetaPropertiesMap(), {
value: "",
dialCode: undefined,
});
}
static getDefaultPropertiesMap(): Record<string, string> {
return _.merge(super.getDefaultPropertiesMap(), {
dialCode: "defaultDialCode",
});
}
static getStylesheetConfig(): Stylesheet {
return {
accentColor: "{{appsmith.theme.colors.primaryColor}}",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "none",
};
}
getFormattedPhoneNumber(value: string) {
const countryCode = getCountryCode(this.props.dialCode);
let formattedValue;
if (!value) {
formattedValue = value;
} else if (this.props.allowFormatting) {
formattedValue = new AsYouType(countryCode as CountryCode).input(value);
} else {
formattedValue = parseIncompletePhoneNumber(value);
}
return formattedValue;
}
componentDidMount() {
//format the defaultText and store it in text
if (!!this.props.text) {
try {
const formattedValue = this.getFormattedPhoneNumber(this.props.text);
this.props.updateWidgetMetaProperty("value", this.props.text);
this.props.updateWidgetMetaProperty("text", formattedValue);
} catch (e) {
log.error(e);
Sentry.captureException(e);
}
}
}
componentDidUpdate(prevProps: PhoneInputWidgetProps) {
if (prevProps.dialCode !== this.props.dialCode) {
this.onISDCodeChange(this.props.dialCode);
}
if (prevProps.allowFormatting !== this.props.allowFormatting) {
const formattedValue = this.getFormattedPhoneNumber(this.props.value);
this.props.updateWidgetMetaProperty("text", formattedValue);
}
// When the default text changes
if (
prevProps.text !== this.props.text &&
this.props.text === this.props.defaultText
) {
const formattedValue = this.getFormattedPhoneNumber(this.props.text);
this.props.updateWidgetMetaProperty(
"value",
parseIncompletePhoneNumber(formattedValue),
);
this.props.updateWidgetMetaProperty("text", formattedValue);
}
// If defaultText property has changed, reset isDirty to false
if (this.props.defaultText !== prevProps.defaultText) {
if (this.props.isDirty) {
this.props.updateWidgetMetaProperty("isDirty", false);
}
}
}
onISDCodeChange = (dialCode?: string) => {
const countryCode = getCountryCode(dialCode);
this.props.updateWidgetMetaProperty("dialCode", dialCode);
this.props.updateWidgetMetaProperty("countryCode", countryCode);
if (this.props.value && this.props.allowFormatting) {
const formattedValue = this.getFormattedPhoneNumber(this.props.value);
this.props.updateWidgetMetaProperty("text", formattedValue);
}
};
onValueChange = (value: string) => {
let formattedValue;
// Don't format, as value is typed, when user is deleting
if (value && value.length > this.props.text?.length) {
formattedValue = this.getFormattedPhoneNumber(value);
} else {
formattedValue = value;
}
this.props.updateWidgetMetaProperty(
"value",
parseIncompletePhoneNumber(formattedValue),
);
this.props.updateWidgetMetaProperty("text", formattedValue, {
triggerPropertyName: "onTextChanged",
dynamicString: this.props.onTextChanged,
event: {
type: EventType.ON_TEXT_CHANGE,
},
});
if (!this.props.isDirty) {
this.props.updateWidgetMetaProperty("isDirty", true);
}
};
handleFocusChange = (focusState: boolean) => {
if (focusState) {
this.props.updateWidgetMetaProperty("isFocused", focusState, {
triggerPropertyName: "onFocus",
dynamicString: this.props.onFocus,
event: {
type: EventType.ON_FOCUS,
},
});
}
if (!focusState) {
this.props.updateWidgetMetaProperty("isFocused", focusState, {
triggerPropertyName: "onBlur",
dynamicString: this.props.onBlur,
event: {
type: EventType.ON_BLUR,
},
});
}
super.handleFocusChange(focusState);
};
handleKeyDown = (
e:
| React.KeyboardEvent<HTMLTextAreaElement>
| React.KeyboardEvent<HTMLInputElement>,
) => {
super.handleKeyDown(e);
};
resetWidgetText = () => {
super.resetWidgetText();
this.props.updateWidgetMetaProperty("value", undefined);
};
getPageView() {
const value = this.props.text ?? "";
const isInvalid =
"isValid" in this.props && !this.props.isValid && !!this.props.isDirty;
const countryCode = this.props.countryCode;
const conditionalProps: Partial<PhoneInputComponentProps> = {};
conditionalProps.errorMessage = this.props.errorMessage;
if (this.props.isRequired && value.length === 0) {
conditionalProps.errorMessage = createMessage(FIELD_REQUIRED_ERROR);
}
return (
<PhoneInputComponent
accentColor={this.props.accentColor}
allowDialCodeChange={this.props.allowDialCodeChange}
autoFocus={this.props.autoFocus}
borderRadius={this.props.borderRadius}
boxShadow={this.props.boxShadow}
compactMode={
!(
(this.props.bottomRow - this.props.topRow) /
GRID_DENSITY_MIGRATION_V1 >
1
)
}
countryCode={countryCode}
defaultValue={this.props.defaultText}
dialCode={this.props.dialCode}
disableNewLineOnPressEnterKey={!!this.props.onSubmit}
disabled={this.props.isDisabled}
iconAlign={this.props.iconAlign}
iconName={this.props.iconName}
inputType={this.props.inputType}
isDynamicHeightEnabled={isAutoHeightEnabledForWidget(this.props)}
isInvalid={isInvalid}
isLoading={this.props.isLoading}
label={this.props.label}
labelAlignment={this.props.labelAlignment}
labelPosition={this.props.labelPosition}
labelStyle={this.props.labelStyle}
labelTextColor={this.props.labelTextColor}
labelTextSize={this.props.labelTextSize}
labelWidth={this.getLabelWidth()}
onFocusChange={this.handleFocusChange}
onISDCodeChange={this.onISDCodeChange}
onKeyDown={this.handleKeyDown}
onValueChange={this.onValueChange}
placeholder={this.props.placeholderText}
showError={!!this.props.isFocused}
tooltip={this.props.tooltip}
value={value}
widgetId={this.props.widgetId}
{...conditionalProps}
/>
);
}
static getWidgetType(): WidgetType {
return "PHONE_INPUT_WIDGET";
}
}
export interface PhoneInputWidgetProps extends BaseInputWidgetProps {
dialCode?: string;
countryCode?: CountryCode;
defaultText?: string;
allowDialCodeChange: boolean;
}
export default PhoneInputWidget;