utils.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. import {browserHistory} from 'react-router';
  2. import {Location, Query} from 'history';
  3. import cloneDeep from 'lodash/cloneDeep';
  4. import isEmpty from 'lodash/isEmpty';
  5. import isEqual from 'lodash/isEqual';
  6. import pick from 'lodash/pick';
  7. import trimStart from 'lodash/trimStart';
  8. import * as qs from 'query-string';
  9. import WidgetArea from 'sentry-images/dashboard/widget-area.svg';
  10. import WidgetBar from 'sentry-images/dashboard/widget-bar.svg';
  11. import WidgetBigNumber from 'sentry-images/dashboard/widget-big-number.svg';
  12. import WidgetLine from 'sentry-images/dashboard/widget-line-1.svg';
  13. import WidgetTable from 'sentry-images/dashboard/widget-table.svg';
  14. import {parseArithmetic} from 'sentry/components/arithmeticInput/parser';
  15. import {
  16. Fidelity,
  17. getDiffInMinutes,
  18. getInterval,
  19. SIX_HOURS,
  20. TWENTY_FOUR_HOURS,
  21. } from 'sentry/components/charts/utils';
  22. import CircleIndicator from 'sentry/components/circleIndicator';
  23. import {normalizeDateTimeString} from 'sentry/components/organizations/pageFilters/parse';
  24. import {parseSearch, Token} from 'sentry/components/searchSyntax/parser';
  25. import {MRI, Organization, PageFilters} from 'sentry/types';
  26. import {defined} from 'sentry/utils';
  27. import {getUtcDateString, parsePeriodToHours} from 'sentry/utils/dates';
  28. import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  29. import EventView from 'sentry/utils/discover/eventView';
  30. import {DURATION_UNITS} from 'sentry/utils/discover/fieldRenderers';
  31. import {
  32. getAggregateAlias,
  33. getAggregateArg,
  34. getColumnsAndAggregates,
  35. isEquation,
  36. isMeasurement,
  37. RATE_UNIT_MULTIPLIERS,
  38. RateUnits,
  39. stripEquationPrefix,
  40. } from 'sentry/utils/discover/fields';
  41. import {DiscoverDatasets, DisplayModes} from 'sentry/utils/discover/types';
  42. import {getMeasurements} from 'sentry/utils/measurements/measurements';
  43. import {
  44. getDdmUrl,
  45. getMetricDisplayType,
  46. MetricWidgetQueryParams,
  47. } from 'sentry/utils/metrics';
  48. import {parseField} from 'sentry/utils/metrics/mri';
  49. import {decodeList} from 'sentry/utils/queryString';
  50. import theme from 'sentry/utils/theme';
  51. import {
  52. DashboardDetails,
  53. DashboardFilterKeys,
  54. DashboardFilters,
  55. DisplayType,
  56. Widget,
  57. WidgetQuery,
  58. WidgetType,
  59. } from 'sentry/views/dashboards/types';
  60. import ThresholdsHoverWrapper from './widgetBuilder/buildSteps/thresholdsStep/thresholdsHoverWrapper';
  61. import {
  62. ThresholdMaxKeys,
  63. ThresholdsConfig,
  64. } from './widgetBuilder/buildSteps/thresholdsStep/thresholdsStep';
  65. export type ValidationError = {
  66. [key: string]: string | string[] | ValidationError[] | ValidationError;
  67. };
  68. export type FlatValidationError = {
  69. [key: string]: string | FlatValidationError[] | FlatValidationError;
  70. };
  71. export function cloneDashboard(dashboard: DashboardDetails): DashboardDetails {
  72. return cloneDeep(dashboard);
  73. }
  74. export function eventViewFromWidget(
  75. title: string,
  76. query: WidgetQuery,
  77. selection: PageFilters
  78. ): EventView {
  79. const {start, end, period: statsPeriod} = selection.datetime;
  80. const {projects, environments} = selection;
  81. // World Map requires an additional column (geo.country_code) to display in discover when navigating from the widget
  82. const fields = [...query.columns, ...query.aggregates];
  83. const conditions = query.conditions;
  84. const {orderby} = query;
  85. // Need to convert orderby to aggregate alias because eventView still uses aggregate alias format
  86. const aggregateAliasOrderBy = orderby
  87. ? `${orderby.startsWith('-') ? '-' : ''}${getAggregateAlias(trimStart(orderby, '-'))}`
  88. : orderby;
  89. return EventView.fromSavedQuery({
  90. id: undefined,
  91. name: title,
  92. version: 2,
  93. fields,
  94. query: conditions,
  95. orderby: aggregateAliasOrderBy,
  96. projects,
  97. range: statsPeriod ?? undefined,
  98. start: start ? getUtcDateString(start) : undefined,
  99. end: end ? getUtcDateString(end) : undefined,
  100. environment: environments,
  101. });
  102. }
  103. export function getThresholdUnitSelectOptions(
  104. dataType: string
  105. ): {label: string; value: string}[] {
  106. if (dataType === 'duration') {
  107. return Object.keys(DURATION_UNITS)
  108. .map(unit => ({label: unit, value: unit}))
  109. .slice(2);
  110. }
  111. if (dataType === 'rate') {
  112. return Object.values(RateUnits).map(unit => ({
  113. label: `/${unit.split('/')[1]}`,
  114. value: unit,
  115. }));
  116. }
  117. return [];
  118. }
  119. export function hasThresholdMaxValue(thresholdsConfig: ThresholdsConfig): boolean {
  120. return Object.keys(thresholdsConfig.max_values).length > 0;
  121. }
  122. function normalizeUnit(value: number, unit: string, dataType: string): number {
  123. const multiplier =
  124. dataType === 'rate'
  125. ? RATE_UNIT_MULTIPLIERS[unit]
  126. : dataType === 'duration'
  127. ? DURATION_UNITS[unit]
  128. : 1;
  129. return value * multiplier;
  130. }
  131. export function getColoredWidgetIndicator(
  132. thresholds: ThresholdsConfig,
  133. tableData: TableDataWithTitle[]
  134. ): React.ReactNode {
  135. const tableMeta = {...tableData[0].meta};
  136. const fields = Object.keys(tableMeta);
  137. const field = fields[0];
  138. const dataType = tableMeta[field];
  139. const dataUnit = tableMeta.units?.[field];
  140. const dataRow = tableData[0].data[0];
  141. if (!dataRow) {
  142. return null;
  143. }
  144. const data = Number(dataRow[field]);
  145. const normalizedData = dataUnit ? normalizeUnit(data, dataUnit, dataType) : data;
  146. const {max_values} = thresholds;
  147. let color = theme.red300;
  148. const yellowMax = max_values[ThresholdMaxKeys.MAX_2];
  149. const normalizedYellowMax =
  150. thresholds.unit && yellowMax
  151. ? normalizeUnit(yellowMax, thresholds.unit, dataType)
  152. : yellowMax;
  153. if (normalizedYellowMax && normalizedData <= normalizedYellowMax) {
  154. color = theme.yellow300;
  155. }
  156. const greenMax = max_values[ThresholdMaxKeys.MAX_1];
  157. const normalizedGreenMax =
  158. thresholds.unit && greenMax
  159. ? normalizeUnit(greenMax, thresholds.unit, dataType)
  160. : greenMax;
  161. if (normalizedGreenMax && normalizedData <= normalizedGreenMax) {
  162. color = theme.green300;
  163. }
  164. return (
  165. <ThresholdsHoverWrapper thresholds={thresholds} tableData={tableData}>
  166. <CircleIndicator color={color} size={12} />
  167. </ThresholdsHoverWrapper>
  168. );
  169. }
  170. function coerceStringToArray(value?: string | string[] | null) {
  171. return typeof value === 'string' ? [value] : value;
  172. }
  173. export function constructWidgetFromQuery(query?: Query): Widget | undefined {
  174. if (query) {
  175. const queryNames = coerceStringToArray(query.queryNames);
  176. const queryConditions = coerceStringToArray(query.queryConditions);
  177. const queryFields = coerceStringToArray(query.queryFields);
  178. const queries: WidgetQuery[] = [];
  179. if (
  180. queryConditions &&
  181. queryNames &&
  182. queryFields &&
  183. typeof query.queryOrderby === 'string'
  184. ) {
  185. const {columns, aggregates} = getColumnsAndAggregates(queryFields);
  186. queryConditions.forEach((condition, index) => {
  187. queries.push({
  188. name: queryNames[index],
  189. conditions: condition,
  190. fields: queryFields,
  191. columns,
  192. aggregates,
  193. orderby: query.queryOrderby as string,
  194. });
  195. });
  196. }
  197. if (query.title && query.displayType && query.interval && queries.length > 0) {
  198. const newWidget: Widget = {
  199. ...(pick(query, ['title', 'displayType', 'interval']) as {
  200. displayType: DisplayType;
  201. interval: string;
  202. title: string;
  203. }),
  204. widgetType: WidgetType.DISCOVER,
  205. queries,
  206. };
  207. return newWidget;
  208. }
  209. }
  210. return undefined;
  211. }
  212. export function miniWidget(displayType: DisplayType): string {
  213. switch (displayType) {
  214. case DisplayType.BAR:
  215. return WidgetBar;
  216. case DisplayType.AREA:
  217. case DisplayType.TOP_N:
  218. return WidgetArea;
  219. case DisplayType.BIG_NUMBER:
  220. return WidgetBigNumber;
  221. case DisplayType.TABLE:
  222. return WidgetTable;
  223. case DisplayType.LINE:
  224. default:
  225. return WidgetLine;
  226. }
  227. }
  228. export function getWidgetInterval(
  229. displayType: DisplayType,
  230. datetimeObj: Partial<PageFilters['datetime']>,
  231. widgetInterval?: string,
  232. fidelity?: Fidelity
  233. ): string {
  234. // Don't fetch more than 66 bins as we're plotting on a small area.
  235. const MAX_BIN_COUNT = 66;
  236. // Bars charts are daily totals to aligned with discover. It also makes them
  237. // usefully different from line/area charts until we expose the interval control, or remove it.
  238. let interval = displayType === 'bar' ? '1d' : widgetInterval;
  239. if (!interval) {
  240. // Default to 5 minutes
  241. interval = '5m';
  242. }
  243. const desiredPeriod = parsePeriodToHours(interval);
  244. const selectedRange = getDiffInMinutes(datetimeObj);
  245. if (fidelity) {
  246. // Primarily to support lower fidelity for Release Health widgets
  247. // the sort on releases and hit the metrics API endpoint.
  248. interval = getInterval(datetimeObj, fidelity);
  249. if (selectedRange > SIX_HOURS && selectedRange <= TWENTY_FOUR_HOURS) {
  250. interval = '1h';
  251. }
  252. return displayType === 'bar' ? '1d' : interval;
  253. }
  254. // selectedRange is in minutes, desiredPeriod is in hours
  255. // convert desiredPeriod to minutes
  256. if (selectedRange / (desiredPeriod * 60) > MAX_BIN_COUNT) {
  257. const highInterval = getInterval(datetimeObj, 'high');
  258. // Only return high fidelity interval if desired interval is higher fidelity
  259. if (desiredPeriod < parsePeriodToHours(highInterval)) {
  260. return highInterval;
  261. }
  262. }
  263. return interval;
  264. }
  265. export function getFieldsFromEquations(fields: string[]): string[] {
  266. // Gather all fields and functions used in equations and prepend them to the provided fields
  267. const termsSet: Set<string> = new Set();
  268. fields.filter(isEquation).forEach(field => {
  269. const parsed = parseArithmetic(stripEquationPrefix(field)).tc;
  270. parsed.fields.forEach(({term}) => termsSet.add(term as string));
  271. parsed.functions.forEach(({term}) => termsSet.add(term as string));
  272. });
  273. return Array.from(termsSet);
  274. }
  275. export function getWidgetDiscoverUrl(
  276. widget: Widget,
  277. selection: PageFilters,
  278. organization: Organization,
  279. index: number = 0,
  280. isMetricsData: boolean = false
  281. ) {
  282. const eventView = eventViewFromWidget(widget.title, widget.queries[index], selection);
  283. const discoverLocation = eventView.getResultsViewUrlTarget(organization.slug);
  284. // Pull a max of 3 valid Y-Axis from the widget
  285. const yAxisOptions = eventView.getYAxisOptions().map(({value}) => value);
  286. discoverLocation.query.yAxis = [
  287. ...new Set(
  288. widget.queries[0].aggregates.filter(aggregate => yAxisOptions.includes(aggregate))
  289. ),
  290. ].slice(0, 3);
  291. // Visualization specific transforms
  292. switch (widget.displayType) {
  293. case DisplayType.BAR:
  294. discoverLocation.query.display = DisplayModes.BAR;
  295. break;
  296. case DisplayType.TOP_N:
  297. discoverLocation.query.display = DisplayModes.TOP5;
  298. // Last field is used as the yAxis
  299. const aggregates = widget.queries[0].aggregates;
  300. discoverLocation.query.yAxis = aggregates[aggregates.length - 1];
  301. if (aggregates.slice(0, -1).includes(aggregates[aggregates.length - 1])) {
  302. discoverLocation.query.field = aggregates.slice(0, -1);
  303. }
  304. break;
  305. default:
  306. break;
  307. }
  308. // Equation fields need to have their terms explicitly selected as columns in the discover table
  309. const fields = discoverLocation.query.field;
  310. const query = widget.queries[0];
  311. const queryFields = defined(query.fields)
  312. ? query.fields
  313. : [...query.columns, ...query.aggregates];
  314. const equationFields = getFieldsFromEquations(queryFields);
  315. // Updates fields by adding any individual terms from equation fields as a column
  316. equationFields.forEach(term => {
  317. if (Array.isArray(fields) && !fields.includes(term)) {
  318. fields.unshift(term);
  319. }
  320. });
  321. if (isMetricsData) {
  322. discoverLocation.query.fromMetric = 'true';
  323. }
  324. // Construct and return the discover url
  325. const discoverPath = `${discoverLocation.pathname}?${qs.stringify({
  326. ...discoverLocation.query,
  327. })}`;
  328. return discoverPath;
  329. }
  330. export function getWidgetIssueUrl(
  331. widget: Widget,
  332. selection: PageFilters,
  333. organization: Organization
  334. ) {
  335. const {start, end, utc, period} = selection.datetime;
  336. const datetime =
  337. start && end
  338. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  339. : {statsPeriod: period};
  340. const issuesLocation = `/organizations/${organization.slug}/issues/?${qs.stringify({
  341. query: widget.queries?.[0]?.conditions,
  342. sort: widget.queries?.[0]?.orderby,
  343. ...datetime,
  344. project: selection.projects,
  345. environment: selection.environments,
  346. })}`;
  347. return issuesLocation;
  348. }
  349. export function getWidgetReleasesUrl(
  350. _widget: Widget,
  351. selection: PageFilters,
  352. organization: Organization
  353. ) {
  354. const {start, end, utc, period} = selection.datetime;
  355. const datetime =
  356. start && end
  357. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  358. : {statsPeriod: period};
  359. const releasesLocation = `/organizations/${organization.slug}/releases/?${qs.stringify({
  360. ...datetime,
  361. project: selection.projects,
  362. environment: selection.environments,
  363. })}`;
  364. return releasesLocation;
  365. }
  366. export function getWidgetDDMUrl(
  367. _widget: Widget,
  368. selection: PageFilters,
  369. organization: Organization
  370. ) {
  371. const {start, end, utc, period} = selection.datetime;
  372. const datetime =
  373. start && end
  374. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  375. : {statsPeriod: period};
  376. // ensures that My Projects selection is properly handled
  377. const project = selection.projects.length ? selection.projects : [0];
  378. const ddmLocation = getDdmUrl(organization.slug, {
  379. ...datetime,
  380. project,
  381. environment: selection.environments,
  382. widgets: _widget.queries.map(query => {
  383. const {mri: mri, op} = parseField(query.aggregates[0]) ?? {mri: '', op: ''};
  384. return {
  385. mri: mri as MRI,
  386. op,
  387. groupBy: query.columns,
  388. query: query.conditions ?? '',
  389. displayType: getMetricDisplayType(_widget.displayType),
  390. } satisfies MetricWidgetQueryParams;
  391. }),
  392. });
  393. return ddmLocation;
  394. }
  395. export function flattenErrors(
  396. data: ValidationError | string,
  397. update: FlatValidationError
  398. ): FlatValidationError {
  399. if (typeof data === 'string') {
  400. update.error = data;
  401. } else {
  402. Object.keys(data).forEach((key: string) => {
  403. const value = data[key];
  404. if (typeof value === 'string') {
  405. update[key] = value;
  406. return;
  407. }
  408. // Recurse into nested objects.
  409. if (Array.isArray(value) && typeof value[0] === 'string') {
  410. update[key] = value[0];
  411. return;
  412. }
  413. if (Array.isArray(value) && typeof value[0] === 'object') {
  414. (value as ValidationError[]).map(item => flattenErrors(item, update));
  415. } else {
  416. flattenErrors(value as ValidationError, update);
  417. }
  418. });
  419. }
  420. return update;
  421. }
  422. export function getDashboardsMEPQueryParams(isMEPEnabled: boolean) {
  423. return isMEPEnabled
  424. ? {
  425. dataset: DiscoverDatasets.METRICS_ENHANCED,
  426. }
  427. : {};
  428. }
  429. export function getNumEquations(possibleEquations: string[]) {
  430. return possibleEquations.filter(isEquation).length;
  431. }
  432. const DEFINED_MEASUREMENTS = new Set(Object.keys(getMeasurements()));
  433. export function isCustomMeasurement(field: string) {
  434. return !DEFINED_MEASUREMENTS.has(field) && isMeasurement(field);
  435. }
  436. export function isCustomMeasurementWidget(widget: Widget) {
  437. return (
  438. widget.widgetType === WidgetType.DISCOVER &&
  439. widget.queries.some(({aggregates, columns, fields}) => {
  440. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  441. // Should be ok to use getAggregateArg. getAggregateArg only returns the first arg
  442. // but there aren't any custom measurement aggregates that use custom measurements
  443. // outside of the first arg.
  444. const aggregateArg = getAggregateArg(aggregate);
  445. if (aggregateArg) {
  446. acc.push(aggregateArg);
  447. }
  448. return acc;
  449. }, []);
  450. return [...aggregateArgs, ...columns, ...(fields ?? [])].some(field =>
  451. isCustomMeasurement(field)
  452. );
  453. })
  454. );
  455. }
  456. export function getCustomMeasurementQueryParams() {
  457. return {
  458. dataset: 'metrics',
  459. };
  460. }
  461. export function isWidgetUsingTransactionName(widget: Widget) {
  462. return (
  463. widget.widgetType === WidgetType.DISCOVER &&
  464. widget.queries.some(({aggregates, columns, fields, conditions}) => {
  465. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  466. const aggregateArg = getAggregateArg(aggregate);
  467. if (aggregateArg) {
  468. acc.push(aggregateArg);
  469. }
  470. return acc;
  471. }, []);
  472. const transactionSelected = [...aggregateArgs, ...columns, ...(fields ?? [])].some(
  473. field => field === 'transaction'
  474. );
  475. const transactionUsedInFilter = parseSearch(conditions)?.some(
  476. parsedCondition =>
  477. parsedCondition.type === Token.FILTER &&
  478. parsedCondition.key?.text === 'transaction'
  479. );
  480. return transactionSelected || transactionUsedInFilter;
  481. })
  482. );
  483. }
  484. export function hasSavedPageFilters(dashboard: DashboardDetails) {
  485. return !(
  486. isEmpty(dashboard.projects) &&
  487. dashboard.environment === undefined &&
  488. dashboard.start === undefined &&
  489. dashboard.end === undefined &&
  490. dashboard.period === undefined
  491. );
  492. }
  493. export function hasUnsavedFilterChanges(
  494. initialDashboard: DashboardDetails,
  495. location: Location
  496. ) {
  497. // Use Sets to compare the filter fields that are arrays
  498. type Filters = {
  499. end?: string;
  500. environment?: Set<string>;
  501. period?: string;
  502. projects?: Set<number>;
  503. release?: Set<string>;
  504. start?: string;
  505. utc?: boolean;
  506. };
  507. const savedFilters: Filters = {
  508. projects: new Set(initialDashboard.projects),
  509. environment: new Set(initialDashboard.environment),
  510. period: initialDashboard.period,
  511. start: normalizeDateTimeString(initialDashboard.start),
  512. end: normalizeDateTimeString(initialDashboard.end),
  513. utc: initialDashboard.utc,
  514. };
  515. let currentFilters = {
  516. ...getCurrentPageFilters(location),
  517. } as unknown as Filters;
  518. currentFilters = {
  519. ...currentFilters,
  520. projects: new Set(currentFilters.projects),
  521. environment: new Set(currentFilters.environment),
  522. };
  523. if (defined(location.query?.release)) {
  524. // Release is only included in the comparison if it exists in the query
  525. // params, otherwise the dashboard should be using its saved state
  526. savedFilters.release = new Set(initialDashboard.filters?.release);
  527. currentFilters.release = new Set(location.query?.release);
  528. }
  529. return !isEqual(savedFilters, currentFilters);
  530. }
  531. export function getSavedFiltersAsPageFilters(dashboard: DashboardDetails): PageFilters {
  532. return {
  533. datetime: {
  534. end: dashboard.end || null,
  535. period: dashboard.period || null,
  536. start: dashboard.start || null,
  537. utc: null,
  538. },
  539. environments: dashboard.environment || [],
  540. projects: dashboard.projects || [],
  541. };
  542. }
  543. export function getSavedPageFilters(dashboard: DashboardDetails) {
  544. return {
  545. project: dashboard.projects,
  546. environment: dashboard.environment,
  547. statsPeriod: dashboard.period,
  548. start: normalizeDateTimeString(dashboard.start),
  549. end: normalizeDateTimeString(dashboard.end),
  550. utc: dashboard.utc,
  551. };
  552. }
  553. export function resetPageFilters(dashboard: DashboardDetails, location: Location) {
  554. browserHistory.replace({
  555. ...location,
  556. query: getSavedPageFilters(dashboard),
  557. });
  558. }
  559. export function getCurrentPageFilters(
  560. location: Location
  561. ): Pick<
  562. DashboardDetails,
  563. 'projects' | 'environment' | 'period' | 'start' | 'end' | 'utc'
  564. > {
  565. const {project, environment, statsPeriod, start, end, utc} = location.query ?? {};
  566. return {
  567. // Ensure projects and environment are sent as arrays, or undefined in the request
  568. // location.query will return a string if there's only one value
  569. projects:
  570. project === undefined || project === null
  571. ? []
  572. : typeof project === 'string'
  573. ? [Number(project)]
  574. : project.map(Number),
  575. environment:
  576. typeof environment === 'string' ? [environment] : environment ?? undefined,
  577. period: statsPeriod as string | undefined,
  578. start: defined(start) ? normalizeDateTimeString(start as string) : undefined,
  579. end: defined(end) ? normalizeDateTimeString(end as string) : undefined,
  580. utc: defined(utc) ? utc === 'true' : undefined,
  581. };
  582. }
  583. export function getDashboardFiltersFromURL(location: Location): DashboardFilters | null {
  584. const dashboardFilters: DashboardFilters = {};
  585. Object.values(DashboardFilterKeys).forEach(key => {
  586. if (defined(location.query?.[key])) {
  587. dashboardFilters[key] = decodeList(location.query?.[key]);
  588. }
  589. });
  590. return !isEmpty(dashboardFilters) ? dashboardFilters : null;
  591. }
  592. export function dashboardFiltersToString(
  593. dashboardFilters: DashboardFilters | null | undefined
  594. ): string {
  595. let dashboardFilterConditions = '';
  596. if (dashboardFilters) {
  597. for (const [key, activeFilters] of Object.entries(dashboardFilters)) {
  598. if (activeFilters.length === 1) {
  599. dashboardFilterConditions += `${key}:"${activeFilters[0]}" `;
  600. } else if (activeFilters.length > 1) {
  601. dashboardFilterConditions += `${key}:[${activeFilters
  602. .map(f => `"${f}"`)
  603. .join(',')}] `;
  604. }
  605. }
  606. }
  607. return dashboardFilterConditions;
  608. }