forked from alibaba-fusion/next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto-complete.jsx
410 lines (354 loc) · 11.8 KB
/
auto-complete.jsx
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { polyfill } from 'react-lifecycles-compat';
import { func, obj, KEYCODE } from '../util';
import Input from '../input';
import Base from './base';
const { bindCtx, noop } = func;
/**
* Select.AutoComplete
*/
class AutoComplete extends Base {
static propTypes = {
...Base.propTypes,
/**
* 当前值,用于受控模式
*/
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* 初始化的默认值
*/
defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Select发生改变时触发的回调
* @param {*} value 选中的值
* @param {String} actionType 触发的方式, 'itemClick', 'enter', 'change'
* @param {*} item 选中的值的对象数据
*/
onChange: PropTypes.func,
/**
* 传入的数据源,可以动态渲染子项
*/
dataSource: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.shape({
value: PropTypes.string,
label: PropTypes.any,
disabled: PropTypes.bool,
children: PropTypes.array,
}),
PropTypes.string,
])
),
/**
* 填充到选择框里的值的 key,默认是 value
*/
fillProps: PropTypes.string,
/**
* 渲染 MenuItem 内容的方法
* @param {Object} item 渲染节点的 item
* @return {ReactNode} item node
*/
itemRender: PropTypes.func,
// input keydown
onKeyDown: PropTypes.func,
// 是否将当前高亮的选项作为 placeholder
highlightHolder: PropTypes.bool,
style: PropTypes.object,
};
static defaultProps = {
...Base.defaultProps,
onKeyDown: noop,
fillProps: 'value',
};
constructor(props) {
super(props);
this.isAutoComplete = true;
this.isInputing = false;
this.dataStore.setOptions({ key: this.state.value });
Object.assign(this.state, {
dataSource: this.setDataSource(props),
});
bindCtx(this, [
'handleTriggerKeyDown',
'handleMenuSelect',
'handleItemClick',
]);
}
static getDerivedStateFromProps(nextProps, prevState) {
const state = {};
if ('value' in nextProps && nextProps.value !== prevState.value) {
Object.assign(state, {
value: nextProps.value,
});
}
if ('visible' in nextProps && nextProps.visible !== prevState.visible) {
Object.assign(state, {
visible: nextProps.visible,
});
}
if (Object.keys(state).length) {
return state;
}
return null;
}
componentDidUpdate(prevProps, prevState) {
const props = this.props;
if ('value' in props) {
this.dataStore.setOptions({ key: props.value });
}
if (props.filter !== prevProps.filter) {
this.dataStore.setOptions({
filter: props.filter,
});
}
if (props.filterLocal !== prevProps.filterLocal) {
this.dataStore.setOptions({
filterLocal: props.filterLocal,
});
}
if (
prevProps.children !== props.children ||
prevProps.dataSource !== props.dataSource
) {
/* eslint-disable react/no-did-update-set-state */
this.setState({
dataSource: this.setDataSource(props),
});
// remote dataSource and focused
// 因为autoComplete没有下拉数据不展示,搜索并且有数据了需要自动展示下拉
if (!props.filterLocal && this.isInputing) {
this.shouldControlPopup(props, 'update');
}
if (!props.filterLocal && !props.popupContent) {
this.setFirstHightLightKeyForMenu();
}
}
}
shouldControlPopup(props = this.props, type) {
const hasPopup =
props.popupContent || this.dataStore.getMenuDS().length;
if (hasPopup) {
this.setVisible(true, type);
} else {
this.setVisible(false, type);
}
}
handleMenuSelect(keys) {
const key = keys[0];
const mapDS = this.dataStore.getMapDS();
if (key in mapDS) {
const item = mapDS[key];
this.handleSelectEvent(key, item, 'itemClick');
}
}
handleItemClick() {
this.setVisible(false, 'itemClick');
}
handleSelectEvent(key, item, triggerType) {
const value = (item && item[this.props.fillProps]) || key;
if (triggerType === 'itemClick' || triggerType === 'enter') {
// 点击 item 的时候不会触发关闭,需要手动关闭,其它类型比如 keyDown 等都会有其它事件句柄处理
this.setVisible(false, triggerType);
}
this.handleChange(value, triggerType, item);
}
handleChange = (value, proxy, item) => {
const { disabled, readOnly, filterLocal } = this.props;
if (disabled || readOnly) {
return false;
}
const actionType = typeof proxy === 'string' ? proxy : 'change';
this.isInputing = actionType === 'change';
if (filterLocal) {
this.setState({
dataSource: this.dataStore.updateByKey(value),
});
this.shouldControlPopup(this.props, actionType);
this.setFirstHightLightKeyForMenu();
}
// 非受控模式清空内部数据
if (!('value' in this.props)) {
this.setState({
value: value,
});
}
this.props.onChange(value, actionType, item);
if (actionType === 'itemClick' || actionType === 'enter') {
// 点击 item 的时候不会触发关闭,需要手动关闭,其它类型比如 keyDown 等都会有其它事件句柄处理
this.setVisible(false, actionType);
}
};
handleVisibleChange(visible, type) {
if (
!('visible' in this.props) &&
visible &&
!this.props.popupContent &&
!this.dataStore.getMenuDS().length
) {
return;
}
this.setVisible(visible, type);
}
beforeClose() {
this.isInputing = false;
}
/**
* Handle trigger keydown event
* @param {Event} e
*/
handleTriggerKeyDown(e) {
const { popupContent, onToggleHighlightItem, onKeyDown } = this.props;
if (popupContent) {
e.stopPropagation(); //stopPropagation can make use onChange triggerd while typing space('') in Input
return onKeyDown(e);
}
switch (e.keyCode) {
case KEYCODE.UP:
e.preventDefault();
onToggleHighlightItem(this.toggleHighlightItem(-1, e), 'up');
break;
case KEYCODE.DOWN:
e.preventDefault();
onToggleHighlightItem(this.toggleHighlightItem(1, e), 'down');
break;
case KEYCODE.ENTER:
e.preventDefault();
this.chooseHighlightItem(e);
break;
case KEYCODE.SPACE:
// stopPropagation can make use onChange triggerd while typing space('') in Input
e.stopPropagation();
break;
case KEYCODE.ESC:
e.preventDefault();
this.state.visible && this.setVisible(false, 'esc');
break;
default:
break;
}
onKeyDown(e);
}
// 回车 选择高亮的 item
chooseHighlightItem() {
if (!this.state.visible) {
return false;
}
const { highlightKey } = this.state;
const highlightItem = this.dataStore.getEnableDS().find(item => {
return highlightKey === `${item.value}`;
});
if (highlightItem) {
this.handleSelectEvent(highlightKey, highlightItem, 'enter');
}
}
hasClear() {
const { hasClear, readOnly, disabled } = this.props;
const { value } = this.state;
return value && hasClear && !readOnly && !disabled;
}
/**
* 选择器
* @override
* @param {object} props
*/
renderSelect(props = this.props) {
const {
placeholder,
size,
prefix,
className,
style,
label,
readOnly,
disabled,
highlightHolder,
locale,
hasClear,
state,
rtl,
} = props;
const others = obj.pickOthers(AutoComplete.propTypes, props);
const othersData = obj.pickAttrsWith(others, 'data-');
const value = this.state.value;
const visible = this.state.visible;
// // 下拉箭头
// const arrowNode = this.renderArrowNode(props, () => {
// this.focusInput();
// this.setVisible(!this.state.visible);
// });
// trigger className
const triggerClazz = classNames(
[
`${prefix}select`,
`${prefix}select-auto-complete`,
`${prefix}size-${size}`,
className,
],
{
[`${prefix}active`]: visible,
[`${prefix}disabled`]: disabled,
}
);
// highlightKey into placeholder
// compatible with selectPlaceHolder. TODO: removed in 2.0 version
let _placeholder =
placeholder ||
locale.autoCompletePlaceholder ||
locale.autoCompletePlaceHolder;
if (highlightHolder && visible) {
_placeholder = this.state.highlightKey || _placeholder;
}
// Input props
const _inputProps = {
...obj.pickOthers(othersData, others),
state: state,
ref: this.saveInputRef,
hasClear: hasClear,
value,
size,
disabled,
readOnly,
placeholder: _placeholder,
label,
// extra: arrowNode,
onChange: this.handleChange,
onKeyDown: this.handleTriggerKeyDown,
};
return (
<span
{...othersData}
className={triggerClazz}
style={style}
dir={rtl ? 'rtl' : undefined}
ref={this.saveSelectRef}
onClick={this.focusInput}
>
<Input
role="combobox"
aria-autocomplete="list"
aria-disabled={disabled}
aria-expanded={this.state.visible}
{..._inputProps}
/>
<span className={`${prefix}sr-only`} aria-live="polite">
{this.state.srReader}
</span>
</span>
);
}
render() {
if (this.hasClear()) {
// clear 按钮点击后,会在 dom 结构中被删除掉,需要将其额外设置为安全节点,防止触发弹层的显示或隐藏
const safeNode = this.props.popupProps.safeNode || [];
const safeNodes = Array.isArray(safeNode) ? safeNode : [safeNode];
safeNodes.push(() => this.clearNode);
this.props.popupProps.safeNode = safeNodes;
}
return super.render(
Object.assign({}, this.props, { canCloseByTrigger: false })
);
}
}
export default polyfill(AutoComplete);