auto-format.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.formatLabels = void 0;
  4. var util_1 = require("@antv/util");
  5. var label_1 = require("../../util/label");
  6. var text_1 = require("../../util/text");
  7. function formatLabel(label, unit, suffix, precision) {
  8. var text = label.attr('text');
  9. // 轴的零值标签不参与格式化
  10. if (text === '0') {
  11. return text;
  12. }
  13. var value = parseFloat(text) / unit;
  14. var newText = formatText(value, precision);
  15. label.attr('text', "" + newText + suffix);
  16. }
  17. /** 根据显示空间获取数值format的精度 */
  18. function getPrecision(labels, unit, suffix, limitLength) {
  19. var values = [];
  20. var length = [];
  21. util_1.each(labels, function (label) {
  22. values.push(parseFloat(label.attr('text')) / unit);
  23. length.push(label.getBBox().width);
  24. });
  25. values.sort(function (a, b) {
  26. return b.toString().length - a.toString().length;
  27. });
  28. var maxLength = Math.max.apply(Math, length);
  29. var maxCodeLength = text_1.strLen(values[0].toString());
  30. var suffixLength = text_1.strLen(suffix);
  31. var reseveLength = Math.floor((limitLength / maxLength) * maxCodeLength) - suffixLength;
  32. // 先尝试保留小数点后两位
  33. var valueCodeLength = text_1.strLen(values[0].toFixed(2));
  34. if (valueCodeLength <= reseveLength) {
  35. return 2;
  36. }
  37. // 保留小数点后1位
  38. valueCodeLength = text_1.strLen(values[0].toFixed(1));
  39. if (valueCodeLength <= reseveLength) {
  40. return 1;
  41. }
  42. }
  43. function formatText(value, precision) {
  44. return value.toFixed(precision || 0);
  45. }
  46. function formatLabels(labelGroup, limitLength, unit, suffix) {
  47. var children = labelGroup.getChildren();
  48. var needFormat = false;
  49. util_1.each(children, function (label) {
  50. var rst = label_1.testLabel(label, limitLength);
  51. if (rst === false) {
  52. needFormat = true;
  53. }
  54. });
  55. if (needFormat) {
  56. var precision_1 = getPrecision(children, unit, suffix, limitLength);
  57. util_1.each(children, function (label) {
  58. formatLabel(label, unit, suffix, precision_1);
  59. });
  60. return true;
  61. }
  62. return false;
  63. }
  64. exports.formatLabels = formatLabels;
  65. //# sourceMappingURL=auto-format.js.map