forked from alibaba-fusion/next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumber-picker.jsx
626 lines (569 loc) · 18.1 KB
/
number-picker.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { polyfill } from 'react-lifecycles-compat';
import Icon from '../icon';
import Button from '../button';
import Input from '../input';
import ConfigProvider from '../config-provider';
import { func, obj } from '../util';
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;
const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -Math.pow(2, 53) + 1;
/** NumberPicker */
class NumberPicker extends React.Component {
static propTypes = {
/**
* 样式前缀
*/
prefix: PropTypes.string,
/**
* 设置类型
* @enumdesc 普通, 内联
*/
type: PropTypes.oneOf(['normal', 'inline']),
/**
* 大小
*/
size: PropTypes.oneOf(['large', 'medium', 'small']),
/**
* 当前值
*/
value: PropTypes.number,
/**
* 默认值
*/
defaultValue: PropTypes.number,
/**
* 是否禁用
*/
disabled: PropTypes.bool,
/**
* 步长
*/
step: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* 保留小数点后位数
*/
precision: PropTypes.number,
/**
* 用户是否可以输入
*/
editable: PropTypes.bool,
/**
* 自动焦点
*/
autoFocus: PropTypes.bool,
/**
* 数值被改变的事件
* @param {Number} value 数据
* @param {Event} e DOM事件对象
*/
onChange: PropTypes.func,
/**
* 键盘按下
*/
onKeyDown: PropTypes.func,
/**
* 焦点获得
*/
onFocus: PropTypes.func,
/**
* 焦点失去
*/
onBlur: PropTypes.func,
/**
* 数值订正后的回调
* @param {Object} obj {currentValue,oldValue:String}
*/
onCorrect: PropTypes.func,
onDisabled: PropTypes.func, // 兼容0.x onDisabled
/**
* 最大值
*/
max: PropTypes.number,
/**
* 最小值
*/
min: PropTypes.number,
/**
* 自定义class
*/
className: PropTypes.string,
/**
* 自定义内联样式
*/
style: PropTypes.object,
state: PropTypes.oneOf(['error']),
/**
* 格式化当前值
* @param {Number} value
* @return {String|Number}
*/
format: PropTypes.func,
/**
* 增加按钮的props
*/
upBtnProps: PropTypes.object,
/**
* 减少按钮的props
*/
downBtnProps: PropTypes.object,
/**
* 内联 label
*/
label: PropTypes.node,
/**
* inner after
*/
innerAfter: PropTypes.node,
rtl: PropTypes.bool,
/**
* 是否为预览态
*/
isPreview: PropTypes.bool,
/**
* 预览态模式下渲染的内容
* @param {number} value 评分值
*/
renderPreview: PropTypes.func,
/**
* 预设屏幕宽度
*/
device: PropTypes.oneOf(['phone', 'tablet', 'desktop']),
/**
* 是否展示点击按钮
*/
hasTrigger: PropTypes.bool,
/**
* 是否一直显示点击按钮(无须hover)
*/
alwaysShowTrigger: PropTypes.bool,
};
static defaultProps = {
prefix: 'next-',
max: MAX_SAFE_INTEGER,
min: MIN_SAFE_INTEGER,
type: 'normal',
size: 'medium',
step: 1,
style: {},
precision: 0,
editable: true,
onChange: func.noop,
onKeyDown: func.noop,
onBlur: func.noop,
onCorrect: func.noop,
onDisabled: func.noop,
hasTrigger: true,
alwaysShowTrigger: false,
};
constructor(props) {
super(props);
let value;
if ('value' in props) {
value = props.value;
} else {
value = props.defaultValue;
}
this.state = {
value: value === undefined || value === null ? '' : value,
hasFocused: false,
reRender: true,
};
}
static getDerivedStateFromProps(nextProps, prevState) {
if ('value' in nextProps && nextProps.value !== prevState.value && prevState.reRender) {
const value = nextProps.value;
return {
value: value === undefined || value === null ? '' : value,
};
}
return null;
}
onChange(value, e) {
if (this.props.editable === true) {
value = value.trim();
// Compatible Chinese Input Method
value = value.replace('。', '.');
// ignore space
if (this.state.value === value) {
return;
}
// in case of autoCorrect ('0.'=>0, '0.0'=>0) , we have these steps
if (value) {
const precisionCurrent = value.length - value.indexOf('.') - 1;
const precisionSet = this.getPrecision();
const dotNum = value.match(/\./g);
const dotIndex = value.indexOf('.');
// ignore more than one . or -, cut at second . or -
if (dotNum && dotNum.length > 1) value = value.substr(0, value.split('.', 2).join('.').length);
const minusNum = value.match(/-/g);
if (minusNum && minusNum.length > 1) value = value.substr(0, value.split('-', 2).join('.').length);
// ignore . when precision set 0
// leave out digits larger than precision set
if (dotIndex > -1) {
if (precisionSet === 0) value = value.substr(0, dotIndex);
else if (precisionCurrent > precisionSet) value = value.substr(0, dotIndex + 1 + precisionSet);
}
// ignore when input start form '-'
if (value === '-' || this.state.value === '-') {
this.setState({
value,
reRender: false,
});
return;
}
// ignore when input 0./0.0/0.00 to 0.001
// and input *.*0
// but take care of Number('')=0;
if (value.match(/\.0*$/) || value.match(/\.[0-9]*0$/)) {
this.setState({
value,
reRender: false,
});
return;
}
// ignore when value < min (because number is inputted one by one)
if (!isNaN(value) && Number(value) < this.props.min) {
this.setState({
value,
reRender: false,
});
return;
}
}
this.setInputValue(value, e);
}
}
/**
* @param {Float} currentValue correct value
* @param {String} oldValue input value
*/
onCorrect(currentValue, oldValue) {
this.props.onCorrect({
currentValue,
oldValue,
});
}
onKeyDown(e, ...args) {
if (e.keyCode === 38) {
this.up(false, e);
} else if (e.keyCode === 40) {
this.down(false, e);
}
this.props.onKeyDown(e, ...args);
}
onFocus(e, ...args) {
const { onFocus } = this.props;
this.setFocus(true);
onFocus && onFocus(e, ...args);
}
onBlur(e, ...args) {
const value = this.getCurrentValidValue(e.target.value.trim());
if (this.state.value !== value) {
this.setValue(value, e);
}
this.setFocus(false);
const { onBlur } = this.props;
onBlur && onBlur(e, ...args);
}
getCurrentValidValue(value) {
let val = value;
const props = this.props;
if (val === '') {
val = '';
} else if (!isNaN(val)) {
val = Number(val);
if (val < props.min) {
val = props.min;
}
if (val > props.max) {
val = props.max;
}
} else {
val = this.state.value;
}
if (`${val}` !== `${value}`) {
// under controled, set back to props.value
if ('value' in this.props && `${this.props.value}` !== `${this.state.value}`) {
this.setState({
value: this.props.value,
});
}
this.onCorrect(val, value);
}
return val;
}
setValue(v, e, triggerType) {
if (!('value' in this.props)) {
this.setState({
value: v,
});
}
this.setState({
reRender: true,
});
this.props.onChange(isNaN(v) || v === '' ? undefined : v, {
...e,
triggerType,
});
}
setInputValue(v, e) {
const value = this.getCurrentValidValue(v);
if (this.state.value !== value) {
this.setValue(value, e);
}
}
setFocus(status) {
const { format } = this.props;
// Only trigger `setState` if `format` is settled to avoid unnecessary rendering
if (typeof format === 'function') {
this.setState({
hasFocused: status,
});
}
}
getPrecision() {
const props = this.props;
const stepString = props.step.toString();
if (stepString.indexOf('e-') >= 0) {
return parseInt(stepString.slice(stepString.indexOf('e-')), 10);
}
let precision = 0;
if (stepString.indexOf('.') >= 0) {
precision = stepString.length - stepString.indexOf('.') - 1;
}
return Math.max(precision, this.props.precision);
}
getPrecisionFactor() {
const precision = this.getPrecision();
return Math.pow(10, precision);
}
upStep(val) {
const { step, min } = this.props;
const precisionFactor = this.getPrecisionFactor();
let result;
if (typeof val === 'number') {
result = (precisionFactor * val + precisionFactor * step) / precisionFactor;
result = this.hackChrome(result);
} else {
// use old value to calculate
result = (precisionFactor * this.state.value + precisionFactor * step) / precisionFactor;
result = this.hackChrome(result);
}
return result;
}
downStep(val) {
const { step, min } = this.props;
const precisionFactor = this.getPrecisionFactor();
let result;
if (typeof val === 'number') {
result = (precisionFactor * val - precisionFactor * step) / precisionFactor;
result = this.hackChrome(result);
} else {
// use old value to calculate
result = (precisionFactor * this.state.value - precisionFactor * step) / precisionFactor;
result = this.hackChrome(result);
}
return result;
}
/**
* fix bug in chrome browser
* 0.28 + 0.01 = 0.29000000000000004
* 0.29 - 0.01 = 0.27999999999999997
* @param {Number} value value
*/
hackChrome(value) {
const precision = this.getPrecision();
if (precision > 0) {
return Number(Number(value).toFixed(precision));
}
return value;
}
step(type, disabled, e) {
if (e) {
e.preventDefault();
}
const { onDisabled, min, max } = this.props;
if (disabled) {
return onDisabled(e);
}
const value = this.state.value;
if (isNaN(value)) {
return;
}
let val = this[`${type}Step`](value);
if (val > max) {
val = max;
}
if (val < min) {
val = min;
}
this.setValue(val, e, type);
}
down(disabled, e) {
this.step('down', disabled, e);
}
up(disabled, e) {
this.step('up', disabled, e);
}
renderValue() {
const { value, hasFocused } = this.state;
const { format } = this.props;
return typeof format === 'function' && !hasFocused ? format(value) : value;
}
focus() {
this.inputRef.getInstance().focus();
}
saveInputRef(ref) {
this.inputRef = ref;
}
handleMouseDown(e) {
e.preventDefault();
}
render() {
const {
device,
prefix,
rtl,
disabled,
style,
className,
size,
max,
min,
autoFocus,
editable,
state,
label,
upBtnProps = {},
downBtnProps = {},
innerAfter,
isPreview,
renderPreview,
hasTrigger,
alwaysShowTrigger,
} = this.props;
const type = device === 'phone' || this.props.type === 'inline' ? 'inline' : 'normal';
const prefixCls = `${prefix}number-picker`;
const cls = classNames({
[prefixCls]: true,
[`${prefixCls}-${type}`]: type,
[`${prefix}${size}`]: true,
[`${prefixCls}-show-trigger`]: alwaysShowTrigger,
[`${prefixCls}-no-trigger`]: !hasTrigger,
[`${prefix}disabled`]: disabled,
[className]: className,
});
let upDisabled = false;
let downDisabled = false;
const value = this.state.value;
if (!isNaN(value)) {
const val = Number(value);
if (val >= max) {
upDisabled = true;
}
if (val <= min) {
downDisabled = true;
}
}
let extra = null,
innerAfterClassName = null,
addonBefore = null,
addonAfter = null;
if (type === 'normal') {
extra = (
<span className={`${prefixCls}-handler`}>
<Button
{...upBtnProps}
onMouseDown={this.handleMouseDown}
disabled={disabled}
className={`${upBtnProps.className || ''} ${upDisabled ? 'disabled' : ''}`}
onClick={this.up.bind(this, upDisabled)}
>
<Icon type="arrow-up" className={`${prefixCls}-up-icon`} />
</Button>
<Button
{...downBtnProps}
onMouseDown={this.handleMouseDown}
disabled={disabled}
className={`${downBtnProps.className || ''} ${downDisabled ? 'disabled' : ''}`}
onClick={this.down.bind(this, downDisabled)}
>
<Icon type="arrow-down" className={`${prefixCls}-down-icon`} />
</Button>
</span>
);
} else {
addonBefore = (
<Button
{...downBtnProps}
size={size}
disabled={disabled}
className={`${downBtnProps.className || ''} ${downDisabled ? 'disabled' : ''}`}
onClick={this.down.bind(this, downDisabled)}
>
<Icon type="minus" className={`${prefixCls}-minus-icon`} />
</Button>
);
addonAfter = (
<Button
{...upBtnProps}
size={size}
disabled={disabled}
className={`${upBtnProps.className || ''} ${upDisabled ? 'disabled' : ''}`}
onClick={this.up.bind(this, upDisabled)}
>
<Icon type="add" className={`${prefixCls}-add-icon`} />
</Button>
);
}
const others = obj.pickOthers(NumberPicker.propTypes, this.props);
const dataAttrs = obj.pickAttrsWith(this.props, 'data-');
const previewCls = classNames({
[`${prefix}form-preview`]: true,
[className]: !!className,
});
if (isPreview) {
if (typeof renderPreview === 'function') {
return (
<div {...others} style={style} className={previewCls}>
{renderPreview(this.renderValue(), this.props)}
</div>
);
}
return (
<p {...others} style={{ style }} className={previewCls}>
{this.renderValue()}
</p>
);
}
return (
<span className={cls} style={style} dir={rtl ? 'rtl' : undefined} {...dataAttrs}>
<Input
{...others}
hasClear={false}
aria-valuemax={max !== MAX_SAFE_INTEGER ? max : MAX_SAFE_INTEGER}
aria-valuemin={min !== MIN_SAFE_INTEGER ? min : MIN_SAFE_INTEGER}
state={state === 'error' ? 'error' : null}
onBlur={this.onBlur.bind(this)}
onFocus={this.onFocus.bind(this)}
onKeyDown={this.onKeyDown.bind(this)}
autoFocus={autoFocus}
readOnly={!editable}
value={this.renderValue()}
disabled={disabled}
size={size}
onChange={this.onChange.bind(this)}
ref={this.saveInputRef.bind(this)}
label={label}
innerAfter={innerAfter}
extra={hasTrigger ? extra : null}
addonBefore={addonBefore}
addonAfter={addonAfter}
/>
</span>
);
}
}
export default polyfill(NumberPicker);