useLokiSyntax.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { useState, useEffect } from 'react';
  2. // @ts-ignore
  3. import Prism from 'prismjs';
  4. import { DataSourceStatus } from '@grafana/ui/src/types/datasource';
  5. import LokiLanguageProvider from 'app/plugins/datasource/loki/language_provider';
  6. import { useLokiLabels } from 'app/plugins/datasource/loki/components/useLokiLabels';
  7. import { CascaderOption } from 'app/plugins/datasource/loki/components/LokiQueryFieldForm';
  8. import { useRefMounted } from 'app/core/hooks/useRefMounted';
  9. const PRISM_SYNTAX = 'promql';
  10. /**
  11. *
  12. * @param languageProvider
  13. * @description Initializes given language provider, exposes Loki syntax and enables loading label option values
  14. */
  15. export const useLokiSyntax = (languageProvider: LokiLanguageProvider, datasourceStatus: DataSourceStatus) => {
  16. const mounted = useRefMounted();
  17. // State
  18. const [languageProviderInitialized, setLanguageProviderInitilized] = useState(false);
  19. const [syntax, setSyntax] = useState(null);
  20. /**
  21. * Holds information about currently selected option from rc-cascader to perform effect
  22. * that loads option values not fetched yet. Based on that useLokiLabels hook decides whether or not
  23. * the option requires additional data fetching
  24. */
  25. const [activeOption, setActiveOption] = useState<CascaderOption[]>();
  26. const { logLabelOptions, setLogLabelOptions, refreshLabels } = useLokiLabels(
  27. languageProvider,
  28. languageProviderInitialized,
  29. activeOption,
  30. datasourceStatus
  31. );
  32. // Async
  33. const initializeLanguageProvider = async () => {
  34. await languageProvider.start();
  35. Prism.languages[PRISM_SYNTAX] = languageProvider.getSyntax();
  36. if (mounted.current) {
  37. setLogLabelOptions(languageProvider.logLabelOptions);
  38. setSyntax(languageProvider.getSyntax());
  39. setLanguageProviderInitilized(true);
  40. }
  41. };
  42. // Effects
  43. useEffect(() => {
  44. initializeLanguageProvider();
  45. }, []);
  46. return {
  47. isSyntaxReady: languageProviderInitialized,
  48. syntax,
  49. logLabelOptions,
  50. setActiveOption,
  51. refreshLabels,
  52. };
  53. };