utils.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { config } from '@grafana/runtime';
  2. import { TextDimensionMode } from 'app/features/dimensions';
  3. import { getMarkerMaker } from './markers';
  4. import { defaultStyleConfig, StyleConfig, StyleConfigFields, StyleConfigState } from './types';
  5. /** Indicate if the style wants to show text values */
  6. export function styleUsesText(config: StyleConfig): boolean {
  7. const text = config?.text;
  8. if (!text) {
  9. return false;
  10. }
  11. if (text.mode === TextDimensionMode.Fixed && text.fixed?.length) {
  12. return true;
  13. }
  14. if (text.mode === TextDimensionMode.Field && text.field?.length) {
  15. return true;
  16. }
  17. return false;
  18. }
  19. /** Return a distinct list of fields used to dynamically change the style */
  20. export async function getStyleConfigState(cfg?: StyleConfig): Promise<StyleConfigState> {
  21. if (!cfg) {
  22. cfg = defaultStyleConfig;
  23. }
  24. const hasText = styleUsesText(cfg);
  25. const fields: StyleConfigFields = {};
  26. const maker = await getMarkerMaker(cfg.symbol?.fixed, hasText);
  27. const state: StyleConfigState = {
  28. config: cfg, // raw values
  29. hasText,
  30. fields,
  31. base: {
  32. color: config.theme2.visualization.getColorByName(cfg.color?.fixed ?? defaultStyleConfig.color.fixed),
  33. opacity: cfg.opacity ?? defaultStyleConfig.opacity,
  34. lineWidth: cfg.lineWidth ?? 1,
  35. size: cfg.size?.fixed ?? defaultStyleConfig.size.fixed,
  36. rotation: cfg.rotation?.fixed ?? defaultStyleConfig.rotation.fixed, // add ability follow path later
  37. },
  38. maker,
  39. };
  40. if (cfg.color?.field?.length) {
  41. fields.color = cfg.color.field;
  42. }
  43. if (cfg.size?.field?.length) {
  44. fields.size = cfg.size.field;
  45. }
  46. if (cfg.rotation?.field?.length) {
  47. fields.rotation = cfg.rotation.field;
  48. }
  49. if (hasText) {
  50. state.base.text = cfg.text?.fixed;
  51. state.base.textConfig = cfg.textConfig ?? defaultStyleConfig.textConfig;
  52. if (cfg.text?.field?.length) {
  53. fields.text = cfg.text.field;
  54. }
  55. }
  56. // Clear the fields if possible
  57. if (!Object.keys(fields).length) {
  58. state.fields = undefined;
  59. }
  60. return state;
  61. }