kbn.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import {
  2. DecimalCount,
  3. deprecationWarning,
  4. formattedValueToString,
  5. getValueFormat,
  6. getValueFormats,
  7. getValueFormatterIndex,
  8. stringToJsRegex,
  9. TimeRange,
  10. ValueFormatterIndex,
  11. rangeUtil,
  12. } from '@grafana/data';
  13. const kbn = {
  14. valueFormats: {} as ValueFormatterIndex,
  15. intervalRegex: /(\d+(?:\.\d+)?)(ms|[Mwdhmsy])/,
  16. intervalsInSeconds: {
  17. y: 31536000,
  18. M: 2592000,
  19. w: 604800,
  20. d: 86400,
  21. h: 3600,
  22. m: 60,
  23. s: 1,
  24. ms: 0.001,
  25. } as { [index: string]: number },
  26. regexEscape: (value: string) => value.replace(/[\\^$*+?.()|[\]{}\/]/g, '\\$&'),
  27. /** @deprecated since 7.2, use grafana/data */
  28. roundInterval: (interval: number) => {
  29. deprecationWarning('kbn.ts', 'kbn.roundInterval()', '@grafana/data');
  30. return rangeUtil.roundInterval(interval);
  31. },
  32. /** @deprecated since 7.2, use grafana/data */
  33. secondsToHms: (s: number) => {
  34. deprecationWarning('kbn.ts', 'kbn.secondsToHms()', '@grafana/data');
  35. return rangeUtil.secondsToHms(s);
  36. },
  37. secondsToHhmmss: (seconds: number) => {
  38. const strings: string[] = [];
  39. const numHours = Math.floor(seconds / 3600);
  40. const numMinutes = Math.floor((seconds % 3600) / 60);
  41. const numSeconds = Math.floor((seconds % 3600) % 60);
  42. numHours > 9 ? strings.push('' + numHours) : strings.push('0' + numHours);
  43. numMinutes > 9 ? strings.push('' + numMinutes) : strings.push('0' + numMinutes);
  44. numSeconds > 9 ? strings.push('' + numSeconds) : strings.push('0' + numSeconds);
  45. return strings.join(':');
  46. },
  47. toPercent: (nr: number, outOf: number) => Math.floor((nr / outOf) * 10000) / 100 + '%',
  48. addSlashes: (str: string) => str.replace(/[\'\"\\0]/g, '\\$&'),
  49. /** @deprecated since 7.2, use grafana/data */
  50. describeInterval: (str: string) => {
  51. deprecationWarning('kbn.ts', 'kbn.describeInterval()', '@grafana/data');
  52. return rangeUtil.describeInterval(str);
  53. },
  54. /** @deprecated since 7.2, use grafana/data */
  55. intervalToSeconds: (str: string) => {
  56. deprecationWarning('kbn.ts', 'rangeUtil.intervalToSeconds()', '@grafana/data');
  57. return rangeUtil.intervalToSeconds(str);
  58. },
  59. /** @deprecated since 7.2, use grafana/data */
  60. intervalToMs: (str: string) => {
  61. deprecationWarning('kbn.ts', 'rangeUtil.intervalToMs()', '@grafana/data');
  62. return rangeUtil.intervalToMs(str);
  63. },
  64. /** @deprecated since 7.2, use grafana/data */
  65. calculateInterval: (range: TimeRange, resolution: number, lowLimitInterval?: string) => {
  66. deprecationWarning('kbn.ts', 'kbn.calculateInterval()', '@grafana/data');
  67. return rangeUtil.calculateInterval(range, resolution, lowLimitInterval);
  68. },
  69. queryColorDot: (color: string, diameter: string) => {
  70. return (
  71. '<div class="icon-circle" style="' +
  72. ['display:inline-block', 'color:' + color, 'font-size:' + diameter + 'px'].join(';') +
  73. '"></div>'
  74. );
  75. },
  76. slugifyForUrl: (str: string) => {
  77. return str
  78. .toLowerCase()
  79. .replace(/[^\w ]+/g, '')
  80. .replace(/ +/g, '-');
  81. },
  82. /** @deprecated since 6.1, use grafana/data */
  83. stringToJsRegex: (str: string) => {
  84. deprecationWarning('kbn.ts', 'kbn.stringToJsRegex()', '@grafana/data');
  85. return stringToJsRegex(str);
  86. },
  87. toFixed: (value: number | null, decimals: number) => {
  88. if (value === null) {
  89. return '';
  90. }
  91. const factor = decimals ? Math.pow(10, Math.max(0, decimals)) : 1;
  92. const formatted = String(Math.round(value * factor) / factor);
  93. // if exponent return directly
  94. if (formatted.indexOf('e') !== -1 || value === 0) {
  95. return formatted;
  96. }
  97. // If tickDecimals was specified, ensure that we have exactly that
  98. // much precision; otherwise default to the value's own precision.
  99. if (decimals != null) {
  100. const decimalPos = formatted.indexOf('.');
  101. const precision = decimalPos === -1 ? 0 : formatted.length - decimalPos - 1;
  102. if (precision < decimals) {
  103. return (precision ? formatted : formatted + '.') + String(factor).slice(1, decimals - precision + 1);
  104. }
  105. }
  106. return formatted;
  107. },
  108. toFixedScaled: (
  109. value: number,
  110. decimals: number,
  111. scaledDecimals: number | null,
  112. additionalDecimals: number,
  113. ext: number
  114. ) => {
  115. if (scaledDecimals === null) {
  116. return kbn.toFixed(value, decimals) + ext;
  117. } else {
  118. return kbn.toFixed(value, scaledDecimals + additionalDecimals) + ext;
  119. }
  120. },
  121. roundValue: (num: number, decimals: number) => {
  122. if (num === null) {
  123. return null;
  124. }
  125. const n = Math.pow(10, decimals);
  126. const formatted = (n * num).toFixed(decimals);
  127. return Math.round(parseFloat(formatted)) / n;
  128. },
  129. // FORMAT MENU
  130. getUnitFormats: getValueFormats,
  131. };
  132. /**
  133. * Backward compatible layer for value formats to support old plugins
  134. */
  135. if (typeof Proxy !== 'undefined') {
  136. kbn.valueFormats = new Proxy(kbn.valueFormats, {
  137. get(target, name, receiver) {
  138. if (typeof name !== 'string') {
  139. throw { message: `Value format ${String(name)} is not a string` };
  140. }
  141. const formatter = getValueFormat(name);
  142. if (formatter) {
  143. // Return the results as a simple string
  144. return (value: number, decimals?: DecimalCount, scaledDecimals?: DecimalCount, isUtc?: boolean) => {
  145. return formattedValueToString(formatter(value, decimals, scaledDecimals, isUtc ? 'utc' : 'browser'));
  146. };
  147. }
  148. // default to look here
  149. return Reflect.get(target, name, receiver);
  150. },
  151. });
  152. } else {
  153. kbn.valueFormats = getValueFormatterIndex();
  154. }
  155. export default kbn;