PromucFlow_constructor/app/client/src/widgets/MultiSelectWidgetV2/widget/index.tsx
balajisoundar 64cec91a0f
feat: select and multiselect label value (#24964)
## Description
- Select and multi-select widgets now have two new properties under the
data section label and value.
- The existing options have been renamed to Source data.
- Users can set the label and value of the options through these new
properties.
- We have written migrations to make this work for existing select
widgets.

#### PR fixes following issue(s)
Fixes https://github.com/appsmithorg/appsmith/issues/24022

>
#### 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
>
>
>
## 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
- [x] Manual
- [x] Jest
- [x] 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
- [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
- [x] 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

---------

Co-authored-by: Rishabh Rathod <rishabh.rathod@appsmith.com>
2023-07-25 10:26:33 +05:30

790 lines
25 KiB
TypeScript

import { Alignment } from "@blueprintjs/core";
import { LabelPosition } from "components/constants";
import { EventType } from "constants/AppsmithActionConstants/ActionConstants";
import { Layers } from "constants/Layers";
import type { WidgetType } from "constants/WidgetConstants";
import { ValidationTypes } from "constants/WidgetValidation";
import type { SetterConfig, Stylesheet } from "entities/AppTheming";
import { EvaluationSubstitutionType } from "entities/DataTree/dataTreeFactory";
import equal from "fast-deep-equal/es6";
import { isArray, isFinite, isString, xorWith } from "lodash";
import type { DraftValueType, LabelInValueType } from "rc-select/lib/Select";
import React from "react";
import { AutocompleteDataType } from "utils/autocomplete/AutocompleteDataType";
import { isAutoLayout } from "utils/autoLayout/flexWidgetUtils";
import type { WidgetProps, WidgetState } from "widgets/BaseWidget";
import BaseWidget from "widgets/BaseWidget";
import { GRID_DENSITY_MIGRATION_V1, MinimumPopupRows } from "widgets/constants";
import {
isAutoHeightEnabledForWidget,
DefaultAutocompleteDefinitions,
} from "widgets/WidgetUtils";
import MultiSelectComponent from "../component";
import derivedProperties from "./parseDerivedProperties";
import type { AutocompletionDefinitions } from "widgets/constants";
import {
defaultValueExpressionPrefix,
getDefaultValueExpressionSuffix,
getOptionLabelValueExpressionPrefix,
optionLabelValueExpressionSuffix,
} from "../constants";
import {
defaultOptionValueValidation,
labelKeyValidation,
getLabelValueAdditionalAutocompleteData,
getLabelValueKeyOptions,
valueKeyValidation,
} from "./propertyUtils";
class MultiSelectWidget extends BaseWidget<
MultiSelectWidgetProps,
WidgetState
> {
static getAutocompleteDefinitions(): AutocompletionDefinitions {
return {
"!doc":
"MultiSelect is used to capture user input/s from a specified list of permitted inputs. A MultiSelect captures multiple choices from a list of options",
"!url": "https://docs.appsmith.com/widget-reference/dropdown",
isVisible: DefaultAutocompleteDefinitions.isVisible,
filterText: {
"!type": "string",
"!doc": "The filter text for Server side filtering",
},
selectedOptionValues: {
"!type": "[string]",
"!doc": "The array of values selected in a multi select dropdown",
"!url": "https://docs.appsmith.com/widget-reference/dropdown",
},
selectedOptionLabels: {
"!type": "[string]",
"!doc":
"The array of selected option labels in a multi select dropdown",
"!url": "https://docs.appsmith.com/widget-reference/dropdown",
},
isDisabled: "bool",
isValid: "bool",
isDirty: "bool",
options: "[$__dropdownOption__$]",
};
}
static getPropertyPaneContentConfig() {
return [
{
sectionName: "Data",
children: [
{
helpText:
"Takes in an array of objects to display options. Bind data from an API using {{}}",
propertyName: "sourceData",
label: "Source Data",
controlType: "INPUT_TEXT",
placeholderText: '[{ "label": "Option1", "value": "Option2" }]',
isBindProperty: true,
isTriggerProperty: false,
isJSConvertible: false,
validation: {
type: ValidationTypes.ARRAY,
params: {
children: {
type: ValidationTypes.OBJECT,
params: {
required: true,
},
},
},
},
evaluationSubstitutionType:
EvaluationSubstitutionType.SMART_SUBSTITUTE,
},
{
helpText: "Sets the label of the option",
propertyName: "optionLabel",
label: "Label",
controlType: "DROP_DOWN",
customJSControl: "WRAPPED_CODE_EDITOR",
controlConfig: {
wrapperCode: {
prefix: getOptionLabelValueExpressionPrefix,
suffix: optionLabelValueExpressionSuffix,
},
},
placeholderText: "",
isBindProperty: true,
isTriggerProperty: false,
isJSConvertible: true,
evaluatedDependencies: ["sourceData"],
options: getLabelValueKeyOptions,
alwaysShowSelected: true,
validation: {
type: ValidationTypes.FUNCTION,
params: {
fn: labelKeyValidation,
expected: {
type: "String or Array<string>",
example: `color | ["blue", "green"]`,
autocompleteDataType: AutocompleteDataType.STRING,
},
},
},
additionalAutoComplete: getLabelValueAdditionalAutocompleteData,
},
{
helpText: "Sets the value of the option",
propertyName: "optionValue",
label: "Value",
controlType: "DROP_DOWN",
customJSControl: "WRAPPED_CODE_EDITOR",
controlConfig: {
wrapperCode: {
prefix: getOptionLabelValueExpressionPrefix,
suffix: optionLabelValueExpressionSuffix,
},
},
placeholderText: "",
isBindProperty: true,
isTriggerProperty: false,
isJSConvertible: true,
evaluatedDependencies: ["sourceData"],
options: getLabelValueKeyOptions,
alwaysShowSelected: true,
validation: {
type: ValidationTypes.FUNCTION,
params: {
fn: valueKeyValidation,
expected: {
type: "String or Array<string | number | boolean>",
example: `color | [1, "orange"]`,
autocompleteDataType: AutocompleteDataType.STRING,
},
},
dependentPaths: ["sourceData"],
},
additionalAutoComplete: getLabelValueAdditionalAutocompleteData,
},
{
helpText: "Selects the option(s) with value by default",
propertyName: "defaultOptionValue",
label: "Default selected values",
controlType: "WRAPPED_CODE_EDITOR",
controlConfig: {
wrapperCode: {
prefix: defaultValueExpressionPrefix,
suffix: getDefaultValueExpressionSuffix,
},
},
placeholderText: "[GREEN]",
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.FUNCTION,
params: {
fn: defaultOptionValueValidation,
expected: {
type: "Array of values",
example: ` "option1, option2" | ['option1', 'option2'] | [{ "label": "label1", "value": "value1" }]`,
autocompleteDataType: AutocompleteDataType.ARRAY,
},
},
dependentPaths: ["serverSideFiltering", "options"],
},
dependencies: ["serverSideFiltering", "options"],
},
],
},
{
sectionName: "Label",
children: [
{
helpText: "Sets the label text of the widget",
propertyName: "labelText",
label: "Text",
controlType: "INPUT_TEXT",
placeholderText: "Enter label text",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
helpText: "Sets the label position of the widget",
propertyName: "labelPosition",
label: "Position",
controlType: "ICON_TABS",
fullWidth: true,
hidden: isAutoLayout,
options: [
{ label: "Auto", value: LabelPosition.Auto },
{ label: "Left", value: LabelPosition.Left },
{ label: "Top", value: LabelPosition.Top },
],
defaultValue: LabelPosition.Top,
isBindProperty: false,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
helpText: "Sets the label alignment of the widget",
propertyName: "labelAlignment",
label: "Alignment",
controlType: "LABEL_ALIGNMENT_OPTIONS",
fullWidth: false,
options: [
{
startIcon: "align-left",
value: Alignment.LEFT,
},
{
startIcon: "align-right",
value: Alignment.RIGHT,
},
],
isBindProperty: false,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
hidden: (props: MultiSelectWidgetProps) =>
props.labelPosition !== LabelPosition.Left,
dependencies: ["labelPosition"],
},
{
helpText:
"Sets the label width of the widget as the number of columns",
propertyName: "labelWidth",
label: "Width (in columns)",
controlType: "NUMERIC_INPUT",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
min: 0,
validation: {
type: ValidationTypes.NUMBER,
params: {
natural: true,
},
},
hidden: (props: MultiSelectWidgetProps) =>
props.labelPosition !== LabelPosition.Left,
dependencies: ["labelPosition"],
},
],
},
{
sectionName: "Search & filters",
children: [
{
propertyName: "isFilterable",
label: "Allow searching",
helpText: "Makes the dropdown list filterable",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
helpText: "Enables server side filtering of the data",
propertyName: "serverSideFiltering",
label: "Server side filtering",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
helpText: "Trigger an action on change of filterText",
hidden: (props: MultiSelectWidgetProps) =>
!props.serverSideFiltering,
dependencies: ["serverSideFiltering"],
propertyName: "onFilterUpdate",
label: "onFilterUpdate",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
},
],
},
{
sectionName: "Validations",
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: [
{
helpText: "Show help text or details about current selection",
propertyName: "labelTooltip",
label: "Tooltip",
controlType: "INPUT_TEXT",
placeholderText: "Add tooltip text here",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
helpText: "Sets a Placeholder Text",
propertyName: "placeholderText",
label: "Placeholder",
controlType: "INPUT_TEXT",
placeholderText: "Search",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
helpText: "Controls the visibility of the widget",
propertyName: "isVisible",
label: "Visible",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
propertyName: "isDisabled",
label: "Disabled",
helpText: "Disables input to this widget",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
propertyName: "animateLoading",
label: "Animate loading",
controlType: "SWITCH",
helpText: "Controls the loading of the widget",
defaultValue: true,
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
helpText:
"Controls the visibility of select all option in dropdown.",
propertyName: "allowSelectAll",
label: "Allow select all",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
],
},
{
sectionName: "Events",
children: [
{
helpText: "when a user selects an option",
propertyName: "onOptionChange",
label: "onOptionChange",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
},
{
helpText: "when the dropdown opens",
propertyName: "onDropdownOpen",
label: "onDropdownOpen",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
},
{
helpText: "when the dropdown closes",
propertyName: "onDropdownClose",
label: "onDropdownClose",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
},
],
},
];
}
static getPropertyPaneStyleConfig() {
return [
{
sectionName: "Label styles",
children: [
{
propertyName: "labelTextColor",
label: "Font color",
helpText: "Control the color of the label associated",
controlType: "COLOR_PICKER",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
propertyName: "labelTextSize",
label: "Font size",
helpText: "Control the font size of the label associated",
controlType: "DROP_DOWN",
defaultValue: "0.875rem",
hidden: isAutoLayout,
options: [
{
label: "S",
value: "0.875rem",
subText: "0.875rem",
},
{
label: "M",
value: "1rem",
subText: "1rem",
},
{
label: "L",
value: "1.25rem",
subText: "1.25rem",
},
{
label: "XL",
value: "1.875rem",
subText: "1.875rem",
},
{
label: "2xl",
value: "3rem",
subText: "3rem",
},
{
label: "3xl",
value: "3.75rem",
subText: "3.75rem",
},
],
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
propertyName: "labelStyle",
label: "Emphasis",
helpText: "Control if the label should be bold or italics",
controlType: "BUTTON_GROUP",
options: [
{
icon: "text-bold",
value: "BOLD",
},
{
icon: "text-italic",
value: "ITALIC",
},
],
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
],
},
{
sectionName: "Border and shadow",
children: [
{
propertyName: "borderRadius",
label: "Border radius",
helpText:
"Rounds the corners of the icon button's outer border edge",
controlType: "BORDER_RADIUS_OPTIONS",
isBindProperty: true,
isJSConvertible: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.TEXT,
},
},
{
propertyName: "boxShadow",
label: "Box shadow",
helpText:
"Enables you to cast a drop shadow from the frame of the widget",
controlType: "BOX_SHADOW_OPTIONS",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
propertyName: "accentColor",
label: "Accent color",
controlType: "COLOR_PICKER",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
invisible: true,
},
],
},
];
}
static getStylesheetConfig(): Stylesheet {
return {
accentColor: "{{appsmith.theme.colors.primaryColor}}",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "none",
};
}
static getDerivedPropertiesMap() {
return {
options: `{{(()=>{${derivedProperties.getOptions}})()}}`,
value: `{{this.selectedOptionValues}}`,
isValid: `{{(()=>{${derivedProperties.getIsValid}})()}}`,
selectedOptionValues: `{{(()=>{${derivedProperties.getSelectedOptionValues}})()}}`,
selectedOptionLabels: `{{(()=>{${derivedProperties.getSelectedOptionLabels}})()}}`,
};
}
static getDefaultPropertiesMap(): Record<string, string> {
return {
selectedOptions: "defaultOptionValue",
};
}
static getMetaPropertiesMap(): Record<string, any> {
return {
selectedOptions: undefined,
filterText: "",
isDirty: false,
};
}
componentDidUpdate(prevProps: MultiSelectWidgetProps): void {
// Check if defaultOptionValue is string
let isStringArray = false;
if (
this.props.defaultOptionValue &&
this.props.defaultOptionValue.some(
(value: any) => isString(value) || isFinite(value),
)
) {
isStringArray = true;
}
const hasChanges = isStringArray
? xorWith(
this.props.defaultOptionValue as string[],
prevProps.defaultOptionValue as string[],
equal,
).length > 0
: xorWith(
this.props.defaultOptionValue as OptionValue[],
prevProps.defaultOptionValue as OptionValue[],
equal,
).length > 0;
if (hasChanges && this.props.isDirty) {
this.props.updateWidgetMetaProperty("isDirty", false);
}
}
static getSetterConfig(): SetterConfig {
return {
__setters: {
setVisibility: {
path: "isVisible",
type: "boolean",
},
setDisabled: {
path: "isDisabled",
type: "boolean",
},
setRequired: {
path: "isRequired",
type: "boolean",
},
setSelectedOptions: {
path: "defaultOptionValue",
type: "array",
accessor: "selectedOptionValues",
},
},
};
}
getPageView() {
const options = isArray(this.props.options) ? this.props.options : [];
const minDropDownWidth = MinimumPopupRows * this.props.parentColumnSpace;
const { componentWidth } = this.getComponentDimensions();
const values = this.mergeLabelAndValue();
const isInvalid =
"isValid" in this.props && !this.props.isValid && !!this.props.isDirty;
return (
<MultiSelectComponent
accentColor={this.props.accentColor}
allowSelectAll={this.props.allowSelectAll}
borderRadius={this.props.borderRadius}
boxShadow={this.props.boxShadow}
compactMode={
!(
(this.props.bottomRow - this.props.topRow) /
GRID_DENSITY_MIGRATION_V1 >
1
)
}
disabled={this.props.isDisabled ?? false}
dropDownWidth={minDropDownWidth}
dropdownStyle={{
zIndex: Layers.dropdownModalWidget,
}}
filterText={this.props.filterText}
isDynamicHeightEnabled={isAutoHeightEnabledForWidget(this.props)}
isFilterable={this.props.isFilterable}
isValid={!isInvalid}
labelAlignment={this.props.labelAlignment}
labelPosition={this.props.labelPosition}
labelStyle={this.props.labelStyle}
labelText={this.props.labelText}
labelTextColor={this.props.labelTextColor}
labelTextSize={this.props.labelTextSize}
labelTooltip={this.props.labelTooltip}
labelWidth={this.getLabelWidth()}
loading={this.props.isLoading}
onChange={this.onOptionChange}
onDropdownClose={this.onDropdownClose}
onDropdownOpen={this.onDropdownOpen}
onFilterChange={this.onFilterChange}
options={options}
placeholder={this.props.placeholderText as string}
renderMode={this.props.renderMode}
serverSideFiltering={this.props.serverSideFiltering}
value={values}
widgetId={this.props.widgetId}
width={componentWidth}
/>
);
}
onOptionChange = (value: DraftValueType) => {
this.props.updateWidgetMetaProperty("selectedOptions", value, {
triggerPropertyName: "onOptionChange",
dynamicString: this.props.onOptionChange,
event: {
type: EventType.ON_OPTION_CHANGE,
},
});
if (!this.props.isDirty) {
this.props.updateWidgetMetaProperty("isDirty", true);
}
};
// { label , value } is needed in the widget
mergeLabelAndValue = (): LabelInValueType[] => {
if (!this.props.selectedOptionLabels || !this.props.selectedOptionValues) {
return [];
}
const labels = [...this.props.selectedOptionLabels];
const values = [...this.props.selectedOptionValues];
return values.map((value, index) => ({
value,
label: labels[index],
}));
};
onFilterChange = (value: string) => {
this.props.updateWidgetMetaProperty("filterText", value);
if (this.props.onFilterUpdate && this.props.serverSideFiltering) {
super.executeAction({
triggerPropertyName: "onFilterUpdate",
dynamicString: this.props.onFilterUpdate,
event: {
type: EventType.ON_FILTER_UPDATE,
},
});
}
};
onDropdownOpen = () => {
if (this.props.onDropdownOpen) {
super.executeAction({
triggerPropertyName: "onDropdownOpen",
dynamicString: this.props.onDropdownOpen,
event: {
type: EventType.ON_DROPDOWN_OPEN,
},
});
}
};
onDropdownClose = () => {
if (this.props.onDropdownClose) {
super.executeAction({
triggerPropertyName: "onDropdownClose",
dynamicString: this.props.onDropdownClose,
event: {
type: EventType.ON_DROPDOWN_CLOSE,
},
});
}
};
static getWidgetType(): WidgetType {
return "MULTI_SELECT_WIDGET_V2";
}
}
export interface OptionValue {
label: string;
value: string;
}
export interface DropdownOption extends OptionValue {
disabled?: boolean;
}
export interface MultiSelectWidgetProps extends WidgetProps {
placeholderText?: string;
selectedIndex?: number;
selectedIndexArr?: number[];
selectedOption: DropdownOption;
options?: DropdownOption[];
onOptionChange: string;
onFilterChange: string;
onDropdownOpen?: string;
onDropdownClose?: string;
defaultOptionValue: string[] | OptionValue[];
isRequired: boolean;
isLoading: boolean;
selectedOptions: LabelInValueType[];
filterText: string;
selectedOptionValues?: string[];
selectedOptionLabels?: string[];
serverSideFiltering: boolean;
onFilterUpdate: string;
allowSelectAll?: boolean;
isFilterable: boolean;
labelText: string;
labelPosition?: LabelPosition;
labelAlignment?: Alignment;
labelWidth?: number;
isDirty?: boolean;
}
export default MultiSelectWidget;