ProcessedValuesRepeater.tsx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import React, { PureComponent } from 'react';
  2. import { VizOrientation } from '@grafana/ui';
  3. import { VizRepeater } from '@grafana/ui';
  4. export interface Props<T> {
  5. width: number;
  6. height: number;
  7. orientation: VizOrientation;
  8. source: any; // If this changes, the values will be processed
  9. renderCounter: number; // change to force processing
  10. getProcessedValues: () => T[];
  11. renderValue: (value: T, width: number, height: number) => JSX.Element;
  12. }
  13. interface State<T> {
  14. values: T[];
  15. }
  16. /**
  17. * This is essentially a cache of processed values. This checks for changes
  18. * to the source and then saves the processed values in the State
  19. */
  20. export class ProcessedValuesRepeater<T> extends PureComponent<Props<T>, State<T>> {
  21. constructor(props: Props<T>) {
  22. super(props);
  23. this.state = {
  24. values: props.getProcessedValues(),
  25. };
  26. }
  27. componentDidUpdate(prevProps: Props<T>) {
  28. const { renderCounter, source } = this.props;
  29. if (renderCounter !== prevProps.renderCounter || source !== prevProps.source) {
  30. this.setState({ values: this.props.getProcessedValues() });
  31. }
  32. }
  33. render() {
  34. const { orientation, height, width, renderValue } = this.props;
  35. const { values } = this.state;
  36. return (
  37. <VizRepeater height={height} width={width} values={values} orientation={orientation}>
  38. {({ vizHeight, vizWidth, value }) => renderValue(value, vizWidth, vizHeight)}
  39. </VizRepeater>
  40. );
  41. }
  42. }