text.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { DataFrame, Field, FieldType, formattedValueToString } from '@grafana/data';
  2. import { DimensionSupplier, TextDimensionConfig, TextDimensionMode } from './types';
  3. import { findField, getLastNotNullFieldValue } from './utils';
  4. //---------------------------------------------------------
  5. // Resource dimension
  6. //---------------------------------------------------------
  7. export function getTextDimension(frame: DataFrame | undefined, config: TextDimensionConfig): DimensionSupplier<string> {
  8. const field = config.field ? findField(frame, config.field) : frame?.fields.find((f) => f.type === FieldType.string);
  9. return getTextDimensionForField(field, config);
  10. }
  11. export function getTextDimensionForField(
  12. field: Field | undefined,
  13. config: TextDimensionConfig
  14. ): DimensionSupplier<string> {
  15. let v = config.fixed;
  16. const mode = config.mode ?? TextDimensionMode.Fixed;
  17. if (mode === TextDimensionMode.Fixed) {
  18. return {
  19. isAssumed: !Boolean(v),
  20. fixed: v,
  21. value: () => v,
  22. get: (i) => v,
  23. };
  24. }
  25. if (mode === TextDimensionMode.Template) {
  26. const disp = (v: any) => {
  27. return `TEMPLATE[${config.fixed} // ${v}]`;
  28. };
  29. if (!field) {
  30. v = disp('');
  31. return {
  32. isAssumed: true,
  33. fixed: v,
  34. value: () => v,
  35. get: (i) => v,
  36. };
  37. }
  38. return {
  39. field,
  40. get: (i) => disp(field.values.get(i)),
  41. value: () => disp(getLastNotNullFieldValue(field)),
  42. };
  43. }
  44. if (!field) {
  45. return {
  46. isAssumed: true,
  47. fixed: v,
  48. value: () => v,
  49. get: (i) => v,
  50. };
  51. }
  52. let disp = (v: any) => formattedValueToString(field.display!(v));
  53. return {
  54. field,
  55. get: (i) => disp(field.values.get(i)),
  56. value: () => disp(getLastNotNullFieldValue(field)),
  57. };
  58. }