category.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. const Base = require('./base');
  2. const catAuto = require('./auto/cat');
  3. const each = require('@antv/util/lib/each');
  4. const isNumber = require('@antv/util/lib/type/is-number');
  5. const isString = require('@antv/util/lib/type/is-string');
  6. class Category extends Base {
  7. _initDefaultCfg() {
  8. super._initDefaultCfg();
  9. this.type = 'cat';
  10. /**
  11. * 是否分类度量
  12. * @type {Boolean}
  13. */
  14. this.isCategory = true;
  15. this.isRounding = true; // 是否进行取整操作
  16. }
  17. /**
  18. * @override
  19. */
  20. init() {
  21. const self = this;
  22. const values = self.values;
  23. const tickCount = self.tickCount;
  24. each(values, (v, i) => {
  25. values[i] = v.toString();
  26. });
  27. if (!self.ticks) {
  28. let ticks = values;
  29. if (tickCount) {
  30. const temp = catAuto({
  31. maxCount: tickCount,
  32. data: values,
  33. isRounding: self.isRounding
  34. });
  35. ticks = temp.ticks;
  36. }
  37. this.ticks = ticks;
  38. }
  39. }
  40. /**
  41. * @override
  42. */
  43. getText(value) {
  44. if (this.values.indexOf(value) === -1 && isNumber(value)) {
  45. value = this.values[Math.round(value)];
  46. }
  47. return super.getText.call(this, value);
  48. }
  49. /**
  50. * @override
  51. */
  52. translate(value) {
  53. let index = this.values.indexOf(value);
  54. if (index === -1 && isNumber(value)) {
  55. index = value;
  56. } else if (index === -1) {
  57. index = NaN;
  58. }
  59. return index;
  60. }
  61. /**
  62. * @override
  63. */
  64. scale(value) {
  65. const rangeMin = this.rangeMin();
  66. const rangeMax = this.rangeMax();
  67. let percent;
  68. if (isString(value) || this.values.indexOf(value) !== -1) {
  69. value = this.translate(value);
  70. }
  71. if (this.values.length > 1) {
  72. percent = (value) / (this.values.length - 1);
  73. } else {
  74. percent = value;
  75. }
  76. return rangeMin + percent * (rangeMax - rangeMin);
  77. }
  78. /**
  79. * @override
  80. */
  81. invert(value) {
  82. if (isString(value)) { // 如果已经是字符串
  83. return value;
  84. }
  85. const min = this.rangeMin();
  86. const max = this.rangeMax();
  87. // 归一到 范围内
  88. if (value < min) {
  89. value = min;
  90. }
  91. if (value > max) {
  92. value = max;
  93. }
  94. const percent = (value - min) / (max - min);
  95. let index = Math.round(percent * (this.values.length - 1)) % this.values.length;
  96. index = index || 0;
  97. return this.values[index];
  98. }
  99. }
  100. Base.Cat = Category;
  101. module.exports = Category;