SingleStatBase.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import React, { PureComponent } from 'react';
  2. import { processSingleStatPanelData, DisplayValue, PanelProps } from '@grafana/ui';
  3. import { config } from 'app/core/config';
  4. import { VizRepeater, getDisplayProcessor } from '@grafana/ui';
  5. import { SingleStatBaseOptions } from './types';
  6. export interface State {
  7. values: DisplayValue[];
  8. }
  9. export class SingleStatBase<T extends SingleStatBaseOptions> extends PureComponent<PanelProps<T>, State> {
  10. constructor(props: PanelProps<T>) {
  11. super(props);
  12. this.state = {
  13. values: this.findDisplayValues(props),
  14. };
  15. }
  16. componentDidUpdate(prevProps: PanelProps<T>) {
  17. if (this.props.panelData !== prevProps.panelData) {
  18. this.setState({ values: this.findDisplayValues(this.props) });
  19. }
  20. }
  21. findDisplayValues(props: PanelProps<T>): DisplayValue[] {
  22. const { panelData, replaceVariables, options } = this.props;
  23. const { valueOptions, valueMappings } = options;
  24. const processor = getDisplayProcessor({
  25. unit: valueOptions.unit,
  26. decimals: valueOptions.decimals,
  27. mappings: valueMappings,
  28. thresholds: options.thresholds,
  29. prefix: replaceVariables(valueOptions.prefix),
  30. suffix: replaceVariables(valueOptions.suffix),
  31. theme: config.theme,
  32. });
  33. return processSingleStatPanelData({
  34. panelData: panelData,
  35. stat: valueOptions.stat,
  36. }).map(stat => processor(stat.value));
  37. }
  38. /**
  39. * Subclasses will fill in appropriatly
  40. */
  41. renderStat(value: DisplayValue, width: number, height: number) {
  42. return <div style={{ width, height, border: '1px solid red' }}>{value.text}</div>;
  43. }
  44. render() {
  45. const { height, width, options } = this.props;
  46. const { orientation } = options;
  47. const { values } = this.state;
  48. return (
  49. <VizRepeater height={height} width={width} values={values} orientation={orientation}>
  50. {({ vizHeight, vizWidth, value }) => this.renderStat(value, vizWidth, vizHeight)}
  51. </VizRepeater>
  52. );
  53. }
  54. }