UNPKG

2.52 kBPlain TextView Raw
1import { each, isDate, isNil, isNumber, isString } from '@antv/util';
2import { timeFormat, toTimeStamp } from '../util/time';
3import Linear from './linear';
4
5/**
6 * 时间度量
7 * @class
8 */
9class Time extends Linear {
10 public readonly type: string = 'time';
11 public mask: string;
12
13 /**
14 * @override
15 */
16 public getText(value: string | number | Date, index?: number) {
17 const numberValue = this.translate(value);
18 const formatter = this.formatter;
19 return formatter ? formatter(numberValue, index) : timeFormat(numberValue, this.mask);
20 }
21 /**
22 * @override
23 */
24 public scale(value): number {
25 let v = value;
26 if (isString(v) || isDate(v)) {
27 v = this.translate(v);
28 }
29 return super.scale(v);
30 }
31 /**
32 * 将时间转换成数字
33 * @override
34 */
35 public translate(v): number {
36 return toTimeStamp(v);
37 }
38 protected initCfg() {
39 this.tickMethod = 'time-pretty';
40 this.mask = 'YYYY-MM-DD';
41 this.tickCount = 7;
42 this.nice = false;
43 }
44
45 protected setDomain() {
46 const values = this.values;
47 // 是否设置了 min, max,而不是直接取 this.min, this.max
48 const minConfig = this.getConfig('min');
49 const maxConfig = this.getConfig('max');
50 // 如果设置了 min,max 则转换成时间戳
51 if (!isNil(minConfig) || !isNumber(minConfig)) {
52 this.min = this.translate(this.min);
53 }
54 if (!isNil(maxConfig) || !isNumber(maxConfig)) {
55 this.max = this.translate(this.max);
56 }
57 // 没有设置 min, max 时
58 if (values && values.length) {
59 // 重新计算最大最小值
60 const timeStamps = [];
61 let min = Infinity; // 最小值
62 let secondMin = min; // 次小值
63 let max = 0;
64 // 使用一个循环,计算min,max,secondMin
65 each(values, (v) => {
66 const timeStamp = toTimeStamp(v);
67 if (isNaN(timeStamp)) {
68 throw new TypeError(`Invalid Time: ${v} in time scale!`);
69 }
70 if (min > timeStamp) {
71 secondMin = min;
72 min = timeStamp;
73 } else if (secondMin > timeStamp) {
74 secondMin = timeStamp;
75 }
76 if (max < timeStamp) {
77 max = timeStamp;
78 }
79 timeStamps.push(timeStamp);
80 });
81 // 存在多个值时,设置最小间距
82 if (values.length > 1) {
83 this.minTickInterval = secondMin - min;
84 }
85 if (isNil(minConfig)) {
86 this.min = min;
87 }
88 if (isNil(maxConfig)) {
89 this.max = max;
90 }
91 }
92 }
93}
94export default Time;