utils.tsx 21 KB

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