utils.tsx 21 KB

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