url.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { Report } from '../../types';
  2. import { initialState } from '../state/reducers';
  3. import { collectVariables } from './variables';
  4. export const getUrlValues = () => {
  5. if (!window.location.search) {
  6. return null;
  7. }
  8. const urlParams = new URLSearchParams(window.location.search);
  9. return {
  10. timeRange: {
  11. to: urlParams.get('to') || '',
  12. from: urlParams.get('from') || '',
  13. },
  14. dashboard: {
  15. uid: urlParams.get('db-uid'),
  16. id: urlParams.get('db-id'),
  17. name: urlParams.get('db-name'),
  18. },
  19. variables: collectVariables(),
  20. };
  21. };
  22. /**
  23. * Apply values from URL params as form's default, in case a report is created
  24. * from dashboard
  25. * @param report
  26. */
  27. export const applyUrlValues = (report: Report) => {
  28. // Do not apply URL values for edited report
  29. if (report.id) {
  30. return report;
  31. }
  32. const values = getUrlValues();
  33. if (!values) {
  34. return report;
  35. }
  36. const { timeRange, dashboard, variables } = values;
  37. let dashboards = [...initialState.report.dashboards!];
  38. if (timeRange?.from && timeRange?.to) {
  39. dashboards[0] = { ...dashboards[0], timeRange };
  40. }
  41. if (dashboard.name && dashboard.id && dashboard.uid) {
  42. dashboards[0] = {
  43. ...dashboards[0],
  44. dashboard: { uid: dashboard.uid, id: Number(dashboard.id), name: dashboard.name },
  45. };
  46. }
  47. if (variables && Object.keys(variables).length) {
  48. dashboards[0] = { ...dashboards[0], reportVariables: variables };
  49. }
  50. return { ...report, dashboards };
  51. };