grafana/public/app/plugins/datasource/loki/components/useLokiSyntax.ts
Dominik Prokop c2e9daad1e
feat(Explore): make sure Loki labels are up to date (#16131)
* Migrated loki syntax and labels logic to useLokiSyntax hook

* Enable loki labels  refresh after specified interval has passed

* Enable periodic loki labels refresh when labels selector is opened

* Fix prettier

* Add react-hooks-testing-library and disable lib check on typecheck

* Add tests for loki syntax/label hooks

* Move tsc's skipLibCheck option to tsconfig for webpack to pick it up

* Set log labels refresh marker variable when log labels fetch start

* Fix prettier issues

* Fix type on activeOption in useLokiLabel hook

* Typo fixes and types in useLokiSyntax hook test fixes

* Make sure effect's setState is not performed on unmounted component

* Extract logic for checking if is component mounted to a separate hook
2019-03-25 12:08:28 +01:00

58 lines
1.8 KiB
TypeScript

import { useState, useEffect } from 'react';
import LokiLanguageProvider from 'app/plugins/datasource/loki/language_provider';
import Prism from 'prismjs';
import { useLokiLabels } from 'app/plugins/datasource/loki/components/useLokiLabels';
import { CascaderOption } from 'app/plugins/datasource/loki/components/LokiQueryFieldForm';
import { useRefMounted } from 'app/core/hooks/useRefMounted';
const PRISM_SYNTAX = 'promql';
/**
*
* @param languageProvider
* @description Initializes given language provider, exposes Loki syntax and enables loading label option values
*/
export const useLokiSyntax = (languageProvider: LokiLanguageProvider) => {
const mounted = useRefMounted();
// State
const [languageProviderInitialized, setLanguageProviderInitilized] = useState(false);
const [syntax, setSyntax] = useState(null);
/**
* Holds information about currently selected option from rc-cascader to perform effect
* that loads option values not fetched yet. Based on that useLokiLabels hook decides whether or not
* the option requires additional data fetching
*/
const [activeOption, setActiveOption] = useState<CascaderOption[]>();
const { logLabelOptions, setLogLabelOptions, refreshLabels } = useLokiLabels(
languageProvider,
languageProviderInitialized,
activeOption
);
// Async
const initializeLanguageProvider = async () => {
await languageProvider.start();
Prism.languages[PRISM_SYNTAX] = languageProvider.getSyntax();
if (mounted.current) {
setLogLabelOptions(languageProvider.logLabelOptions);
setSyntax(languageProvider.getSyntax());
setLanguageProviderInitilized(true);
}
};
// Effects
useEffect(() => {
initializeLanguageProvider();
}, []);
return {
isSyntaxReady: languageProviderInitialized,
syntax,
logLabelOptions,
setActiveOption,
refreshLabels,
};
};