scalar.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { DataFrame, Field } from '@grafana/data';
  2. import { DimensionSupplier, ScalarDimensionConfig, ScalarDimensionMode } from './types';
  3. import { findField, getLastNotNullFieldValue } from './utils';
  4. //---------------------------------------------------------
  5. // Scalar dimension
  6. //---------------------------------------------------------
  7. export function getScalarDimension(
  8. frame: DataFrame | undefined,
  9. config: ScalarDimensionConfig
  10. ): DimensionSupplier<number> {
  11. return getScalarDimensionForField(findField(frame, config?.field), config);
  12. }
  13. export function getScalarDimensionForField(
  14. field: Field | undefined,
  15. cfg: ScalarDimensionConfig
  16. ): DimensionSupplier<number> {
  17. if (!field) {
  18. const v = cfg.fixed ?? 0;
  19. return {
  20. isAssumed: Boolean(cfg.field?.length) || !cfg.fixed,
  21. fixed: v,
  22. value: () => v,
  23. get: () => v,
  24. };
  25. }
  26. //mod mode as default
  27. let validated = (value: number) => {
  28. return value % cfg.max;
  29. };
  30. //capped mode
  31. if (cfg.mode === ScalarDimensionMode.Clamped) {
  32. validated = (value: number) => {
  33. if (value < cfg.min) {
  34. return cfg.min;
  35. }
  36. if (value > cfg.max) {
  37. return cfg.max;
  38. }
  39. return value;
  40. };
  41. }
  42. const get = (i: number) => {
  43. const v = field.values.get(i);
  44. if (v === null || typeof v !== 'number') {
  45. return 0;
  46. }
  47. return validated(v);
  48. };
  49. return {
  50. field,
  51. get,
  52. value: () => getLastNotNullFieldValue(field),
  53. };
  54. }