state.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { useCallback, useState } from 'react';
  2. import store from 'app/core/store';
  3. import { QueryEditorMode } from '../../prometheus/querybuilder/shared/types';
  4. import { LokiQuery, LokiQueryType } from '../types';
  5. const queryEditorModeDefaultLocalStorageKey = 'LokiQueryEditorModeDefault';
  6. export function changeEditorMode(query: LokiQuery, editorMode: QueryEditorMode, onChange: (query: LokiQuery) => void) {
  7. // If empty query store new mode as default
  8. if (query.expr === '') {
  9. store.set(queryEditorModeDefaultLocalStorageKey, editorMode);
  10. }
  11. onChange({ ...query, editorMode });
  12. }
  13. export function getDefaultEditorMode(expr: string) {
  14. // If we already have an expression default to code view
  15. if (expr != null && expr !== '') {
  16. return QueryEditorMode.Code;
  17. }
  18. const value = store.get(queryEditorModeDefaultLocalStorageKey) as QueryEditorMode;
  19. switch (value) {
  20. case QueryEditorMode.Builder:
  21. case QueryEditorMode.Code:
  22. case QueryEditorMode.Explain:
  23. return value;
  24. default:
  25. return QueryEditorMode.Builder;
  26. }
  27. }
  28. /**
  29. * Returns query with defaults, and boolean true/false depending on change was required
  30. */
  31. export function getQueryWithDefaults(query: LokiQuery): LokiQuery {
  32. // If no expr (ie new query) then default to builder
  33. let result = query;
  34. if (!query.editorMode) {
  35. result = { ...query, editorMode: getDefaultEditorMode(query.expr) };
  36. }
  37. if (query.expr == null) {
  38. result = { ...result, expr: '' };
  39. }
  40. if (query.queryType == null) {
  41. // Default to range query
  42. result = { ...result, queryType: LokiQueryType.Range };
  43. }
  44. return result;
  45. }
  46. const queryEditorRawQueryLocalStorageKey = 'LokiQueryEditorRawQueryDefault';
  47. function getRawQueryVisibility(): boolean {
  48. const val = store.get(queryEditorRawQueryLocalStorageKey);
  49. return val === undefined ? true : Boolean(parseInt(val, 10));
  50. }
  51. function setRawQueryVisibility(value: boolean) {
  52. store.set(queryEditorRawQueryLocalStorageKey, value ? '1' : '0');
  53. }
  54. /**
  55. * Use and store value of raw query switch in local storage.
  56. * Needs to be a hook with local state to trigger rerenders.
  57. */
  58. export function useRawQuery(): [boolean, (val: boolean) => void] {
  59. const [rawQuery, setRawQuery] = useState(getRawQueryVisibility());
  60. const setter = useCallback((value: boolean) => {
  61. setRawQueryVisibility(value);
  62. setRawQuery(value);
  63. }, []);
  64. return [rawQuery, setter];
  65. }