SingleStatPanel.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Libraries
  2. import React, { PureComponent, CSSProperties } from 'react';
  3. // Types
  4. import { SingleStatOptions, SingleStatBaseOptions } from './types';
  5. import { DisplayValue, PanelProps, NullValueMode, FieldType, calculateStats } from '@grafana/ui';
  6. import { config } from 'app/core/config';
  7. import { getDisplayProcessor } from '@grafana/ui';
  8. import { ProcessedValuesRepeater } from './ProcessedValuesRepeater';
  9. export const getSingleStatValues = (props: PanelProps<SingleStatBaseOptions>): DisplayValue[] => {
  10. const { data, replaceVariables, options } = props;
  11. const { valueOptions, valueMappings } = options;
  12. const { unit, decimals, stat } = valueOptions;
  13. const display = getDisplayProcessor({
  14. unit,
  15. decimals,
  16. mappings: valueMappings,
  17. thresholds: options.thresholds,
  18. prefix: replaceVariables(valueOptions.prefix),
  19. suffix: replaceVariables(valueOptions.suffix),
  20. theme: config.theme,
  21. });
  22. const values: DisplayValue[] = [];
  23. for (const series of data) {
  24. if (stat === 'name') {
  25. values.push(display(series.name));
  26. }
  27. for (let i = 0; i < series.fields.length; i++) {
  28. const column = series.fields[i];
  29. // Show all columns that are not 'time'
  30. if (column.type === FieldType.number) {
  31. const stats = calculateStats({
  32. series,
  33. fieldIndex: i,
  34. stats: [stat], // The stats to calculate
  35. nullValueMode: NullValueMode.Null,
  36. });
  37. const displayValue = display(stats[stat]);
  38. values.push(displayValue);
  39. }
  40. }
  41. }
  42. if (values.length === 0) {
  43. values.push({
  44. numeric: 0,
  45. text: 'No data',
  46. });
  47. }
  48. return values;
  49. };
  50. export class SingleStatPanel extends PureComponent<PanelProps<SingleStatOptions>> {
  51. renderValue = (value: DisplayValue, width: number, height: number): JSX.Element => {
  52. const style: CSSProperties = {};
  53. style.margin = '0 auto';
  54. style.fontSize = '250%';
  55. style.textAlign = 'center';
  56. if (value.color) {
  57. style.color = value.color;
  58. }
  59. return (
  60. <div style={{ width, height }}>
  61. <div style={style}>{value.text}</div>
  62. </div>
  63. );
  64. };
  65. getProcessedValues = (): DisplayValue[] => {
  66. return getSingleStatValues(this.props);
  67. };
  68. render() {
  69. const { height, width, options, data, renderCounter } = this.props;
  70. return (
  71. <ProcessedValuesRepeater
  72. getProcessedValues={this.getProcessedValues}
  73. renderValue={this.renderValue}
  74. width={width}
  75. height={height}
  76. source={data}
  77. renderCounter={renderCounter}
  78. orientation={options.orientation}
  79. />
  80. );
  81. }
  82. }