-
Notifications
You must be signed in to change notification settings - Fork 14.1k
/
SupersetStyledSelect.tsx
300 lines (276 loc) · 10.2 KB
/
SupersetStyledSelect.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { SyntheticEvent, MutableRefObject, ComponentType } from 'react';
import { merge } from 'lodash';
import BasicSelect, {
OptionTypeBase,
MultiValueProps,
FormatOptionLabelMeta,
ValueType,
SelectComponentsConfig,
components as defaultComponents,
createFilter,
} from 'react-select';
import Async from 'react-select/async';
import Creatable from 'react-select/creatable';
import AsyncCreatable from 'react-select/async-creatable';
import { withAsyncPaginate } from 'react-select-async-paginate';
import { SelectComponents } from 'react-select/src/components';
import {
SortableContainer,
SortableElement,
SortableContainerProps,
} from 'react-sortable-hoc';
import arrayMove from 'array-move';
import { Props as SelectProps } from 'react-select/src/Select';
import {
WindowedSelectComponentType,
WindowedSelectProps,
WindowedSelect,
WindowedAsyncSelect,
WindowedCreatableSelect,
WindowedAsyncCreatableSelect,
} from './WindowedSelect';
import {
DEFAULT_CLASS_NAME,
DEFAULT_CLASS_NAME_PREFIX,
DEFAULT_STYLES,
DEFAULT_THEME,
DEFAULT_COMPONENTS,
VALUE_LABELED_STYLES,
PartialThemeConfig,
PartialStylesConfig,
} from './styles';
import { findValue } from './utils';
type AnyReactSelect<OptionType extends OptionTypeBase> =
| BasicSelect<OptionType>
| Async<OptionType>
| Creatable<OptionType>
| AsyncCreatable<OptionType>;
export type SupersetStyledSelectProps<
OptionType extends OptionTypeBase,
T extends WindowedSelectProps<OptionType> = WindowedSelectProps<OptionType>
> = T & {
// additional props for easier usage or backward compatibility
labelKey?: string;
valueKey?: string;
multi?: boolean;
clearable?: boolean;
sortable?: boolean;
ignoreAccents?: boolean;
creatable?: boolean;
selectRef?:
| React.RefCallback<AnyReactSelect<OptionType>>
| MutableRefObject<AnyReactSelect<OptionType>>;
getInputValue?: (selectBalue: ValueType<OptionType>) => string | undefined;
optionRenderer?: (option: OptionType) => React.ReactNode;
valueRenderer?: (option: OptionType) => React.ReactNode;
valueRenderedAsLabel?: boolean;
// callback for paste event
onPaste?: (e: SyntheticEvent) => void;
// for simplier theme overrides
themeConfig?: PartialThemeConfig;
stylesConfig?: PartialStylesConfig;
};
function styled<
OptionType extends OptionTypeBase,
SelectComponentType extends
| WindowedSelectComponentType<OptionType>
| ComponentType<SelectProps<OptionType>> = WindowedSelectComponentType<
OptionType
>
>(SelectComponent: SelectComponentType) {
type SelectProps = SupersetStyledSelectProps<OptionType>;
type Components = SelectComponents<OptionType>;
const SortableSelectComponent = SortableContainer(SelectComponent, {
withRef: true,
});
// default components for the given OptionType
const supersetDefaultComponents: SelectComponentsConfig<OptionType> = DEFAULT_COMPONENTS;
const getSortableMultiValue = (MultiValue: Components['MultiValue']) => {
return SortableElement((props: MultiValueProps<OptionType>) => {
const onMouseDown = (e: SyntheticEvent) => {
e.preventDefault();
e.stopPropagation();
};
const innerProps = { onMouseDown };
return <MultiValue {...props} innerProps={innerProps} />;
});
};
/**
* Superset styled `Select` component. Apply Superset themed stylesheets and
* consolidate props API for backward compatibility with react-select v1.
*/
function StyledSelect(selectProps: SelectProps) {
let stateManager: AnyReactSelect<OptionType>; // reference to react-select StateManager
const {
// additional props for Superset Select
selectRef,
labelKey = 'label',
valueKey = 'value',
themeConfig,
stylesConfig = {},
optionRenderer,
valueRenderer,
// whether value is rendered as `option-label` in input,
// useful for AdhocMetric and AdhocFilter
valueRenderedAsLabel: valueRenderedAsLabel_,
onPaste,
multi = false, // same as `isMulti`, used for backward compatibility
clearable, // same as `isClearable`
sortable = true, // whether to enable drag & drop sorting
// react-select props
className = DEFAULT_CLASS_NAME,
classNamePrefix = DEFAULT_CLASS_NAME_PREFIX,
options,
value: value_,
components: components_,
isMulti: isMulti_,
isClearable: isClearable_,
minMenuHeight = 100, // apply different defaults
maxMenuHeight = 220,
filterOption,
ignoreAccents = false, // default is `true`, but it is slow
getOptionValue = option =>
typeof option === 'string' ? option : option[valueKey],
getOptionLabel = option =>
typeof option === 'string'
? option
: option[labelKey] || option[valueKey],
formatOptionLabel = (
option: OptionType,
{ context }: FormatOptionLabelMeta<OptionType>,
) => {
if (context === 'value') {
return valueRenderer ? valueRenderer(option) : getOptionLabel(option);
}
return optionRenderer ? optionRenderer(option) : getOptionLabel(option);
},
...restProps
} = selectProps;
// `value` may be rendered values (strings), we want option objects
const value: OptionType[] = findValue(value_, options || [], valueKey);
// Add backward compability to v1 API
const isMulti = isMulti_ === undefined ? multi : isMulti_;
const isClearable = isClearable_ === undefined ? clearable : isClearable_;
// Sort is only applied when there are multiple selected values
const shouldAllowSort =
isMulti && sortable && Array.isArray(value) && value.length > 1;
const MaybeSortableSelect = shouldAllowSort
? SortableSelectComponent
: SelectComponent;
const components = { ...supersetDefaultComponents, ...components_ };
// Make multi-select sortable as per https://react-select.netlify.app/advanced
if (shouldAllowSort) {
components.MultiValue = getSortableMultiValue(
components.MultiValue || defaultComponents.MultiValue,
);
const sortableContainerProps: Partial<SortableContainerProps> = {
getHelperDimensions: ({ node }) => node.getBoundingClientRect(),
axis: 'xy',
onSortEnd: ({ oldIndex, newIndex }) => {
const newValue = arrayMove(value, oldIndex, newIndex);
if (restProps.onChange) {
restProps.onChange(newValue, { action: 'set-value' });
}
},
distance: 4,
};
Object.assign(restProps, sortableContainerProps);
}
// When values are rendered as labels, adjust valueContainer padding
const valueRenderedAsLabel =
valueRenderedAsLabel_ === undefined ? isMulti : valueRenderedAsLabel_;
if (valueRenderedAsLabel && !stylesConfig.valueContainer) {
Object.assign(stylesConfig, VALUE_LABELED_STYLES);
}
// Handle onPaste event
if (onPaste) {
const Input = components.Input || defaultComponents.Input;
components.Input = props => (
<div onPaste={onPaste}>
<Input {...props} />
</div>
);
}
// for CreaTable
if (SelectComponent === WindowedCreatableSelect) {
restProps.getNewOptionData = (inputValue: string, label: string) => ({
label: label || inputValue,
[valueKey]: inputValue,
isNew: true,
});
}
// Make sure always return StateManager for the refs.
// To get the real `Select` component, keep tap into `obj.select`:
// - for normal <Select /> component: StateManager -> Select,
// - for <Creatable />: StateManager -> Creatable -> Select
const setRef = (instance: any) => {
stateManager =
shouldAllowSort && instance && 'refs' in instance
? instance.refs.wrappedInstance // obtain StateManger from SortableContainer
: instance;
if (typeof selectRef === 'function') {
selectRef(stateManager);
} else if (selectRef && 'current' in selectRef) {
selectRef.current = stateManager;
}
};
return (
<MaybeSortableSelect
ref={setRef}
className={className}
classNamePrefix={classNamePrefix}
isMulti={isMulti}
isClearable={isClearable}
options={options}
value={value}
minMenuHeight={minMenuHeight}
maxMenuHeight={maxMenuHeight}
filterOption={
// filterOption may be NULL
filterOption !== undefined
? filterOption
: createFilter({ ignoreAccents })
}
styles={{ ...DEFAULT_STYLES, ...stylesConfig } as SelectProps['styles']}
// merge default theme from `react-select`, default theme for Superset,
// and the theme from props.
theme={defaultTheme => merge(defaultTheme, DEFAULT_THEME, themeConfig)}
formatOptionLabel={formatOptionLabel}
getOptionLabel={getOptionLabel}
getOptionValue={getOptionValue}
components={components}
{...restProps}
/>
);
}
// React.memo makes sure the component does no rerender given the same props
return React.memo(StyledSelect);
}
export const Select = styled(WindowedSelect);
export const AsyncSelect = styled(WindowedAsyncSelect);
export const CreatableSelect = styled(WindowedCreatableSelect);
export const AsyncCreatableSelect = styled(WindowedAsyncCreatableSelect);
export const PaginatedSelect = withAsyncPaginate(
styled<OptionTypeBase, ComponentType<SelectProps<OptionTypeBase>>>(
BasicSelect,
),
);
export default Select;