UNPKG

1.92 kBPlain TextView Raw
1import { filter, getRange, head, isNil, last } from '@antv/util';
2import Base from '../base';
3
4/**
5 * 连续度量的基类
6 * @class
7 */
8export default abstract class Continuous extends Base {
9 public isContinuous?: boolean = true;
10 public nice: boolean;
11
12 public scale(value: any): number {
13 if (isNil(value)) {
14 return NaN;
15 }
16 const rangeMin = this.rangeMin();
17 const rangeMax = this.rangeMax();
18 const max = this.max;
19 const min = this.min;
20 if (max === min) {
21 return rangeMin;
22 }
23 const percent = this.getScalePercent(value);
24 return rangeMin + percent * (rangeMax - rangeMin);
25 }
26
27 protected init() {
28 super.init();
29 // init 完成后保证 min, max 包含 ticks 的范围
30 const ticks = this.ticks;
31 const firstTick = head(ticks);
32 const lastTick = last(ticks);
33 if (firstTick < this.min) {
34 this.min = firstTick;
35 }
36 if (lastTick > this.max) {
37 this.max = lastTick;
38 }
39 // strict-limit 方式
40 if (!isNil(this.minLimit)) {
41 this.min = firstTick;
42 }
43 if (!isNil(this.maxLimit)) {
44 this.max = lastTick;
45 }
46 }
47
48 protected setDomain() {
49 const { min, max } = getRange(this.values);
50 if (isNil(this.min)) {
51 this.min = min;
52 }
53 if (isNil(this.max)) {
54 this.max = max;
55 }
56 if (this.min > this.max) {
57 this.min = min;
58 this.max = max;
59 }
60 }
61
62 protected calculateTicks(): any[] {
63 let ticks = super.calculateTicks();
64 if (!this.nice) {
65 ticks = filter(ticks, (tick) => {
66 return tick >= this.min && tick <= this.max;
67 });
68 }
69 return ticks;
70 }
71
72 // 计算原始值值占的百分比
73 protected getScalePercent(value) {
74 const max = this.max;
75 const min = this.min;
76 return (value - min) / (max - min);
77 }
78
79 protected getInvertPercent(value) {
80 return (value - this.rangeMin()) / (this.rangeMax() - this.rangeMin());
81 }
82}