useLokiSyntax.ts 1.8 KB

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