widget.tsx 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import {useCallback, useEffect, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import colorFn from 'color';
  4. import type {LineSeriesOption} from 'echarts';
  5. import moment from 'moment';
  6. import Alert from 'sentry/components/alert';
  7. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  8. import EmptyMessage from 'sentry/components/emptyMessage';
  9. import LoadingIndicator from 'sentry/components/loadingIndicator';
  10. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  11. import Panel from 'sentry/components/panels/panel';
  12. import PanelBody from 'sentry/components/panels/panelBody';
  13. import {IconSearch} from 'sentry/icons';
  14. import {t} from 'sentry/locale';
  15. import {space} from 'sentry/styles/space';
  16. import {PageFilters} from 'sentry/types';
  17. import {
  18. defaultMetricDisplayType,
  19. getUnitFromMRI,
  20. MetricDisplayType,
  21. MetricsData,
  22. MetricsQuery,
  23. updateQuery,
  24. useMetricsDataZoom,
  25. } from 'sentry/utils/metrics';
  26. import {decodeList} from 'sentry/utils/queryString';
  27. import theme from 'sentry/utils/theme';
  28. import useRouter from 'sentry/utils/useRouter';
  29. import {MetricChart} from 'sentry/views/ddm/chart';
  30. import {QueryBuilder} from 'sentry/views/ddm/queryBuilder';
  31. import {SummaryTable} from 'sentry/views/ddm/summaryTable';
  32. import {DEFAULT_SORT_STATE, MIN_WIDGET_WIDTH} from './constants';
  33. type SortState = {
  34. name: 'name' | 'avg' | 'min' | 'max' | 'sum';
  35. order: 'asc' | 'desc';
  36. };
  37. const emptyWidget = {
  38. mri: '',
  39. op: undefined,
  40. query: '',
  41. groupBy: [],
  42. displayType: defaultMetricDisplayType,
  43. sort: DEFAULT_SORT_STATE,
  44. };
  45. export type MetricWidgetDisplayConfig = {
  46. displayType: MetricDisplayType;
  47. onChange: (data: Partial<MetricWidgetProps>) => void;
  48. position: number;
  49. sort: SortState;
  50. focusedSeries?: string;
  51. powerUserMode?: boolean;
  52. showSummaryTable?: boolean;
  53. };
  54. export type MetricWidgetProps = Pick<MetricsQuery, 'mri' | 'op' | 'query' | 'groupBy'> &
  55. MetricWidgetDisplayConfig;
  56. export function useMetricWidgets() {
  57. const router = useRouter();
  58. const currentWidgets = JSON.parse(
  59. router.location.query.widgets ?? JSON.stringify([emptyWidget])
  60. );
  61. const widgets: MetricWidgetProps[] = currentWidgets.map(
  62. (widget: MetricWidgetProps, i) => {
  63. return {
  64. mri: widget.mri,
  65. op: widget.op,
  66. query: widget.query,
  67. groupBy: decodeList(widget.groupBy),
  68. displayType: widget.displayType ?? defaultMetricDisplayType,
  69. focusedSeries: widget.focusedSeries,
  70. showSummaryTable: widget.showSummaryTable ?? true, // temporary default
  71. position: widget.position ?? i,
  72. powerUserMode: widget.powerUserMode,
  73. sort: widget.sort ?? DEFAULT_SORT_STATE,
  74. };
  75. }
  76. );
  77. const onChange = (position: number, data: Partial<MetricWidgetProps>) => {
  78. currentWidgets[position] = {...currentWidgets[position], ...data};
  79. updateQuery(router, {
  80. widgets: JSON.stringify(currentWidgets),
  81. });
  82. };
  83. const addWidget = () => {
  84. currentWidgets.push({...emptyWidget, position: currentWidgets.length});
  85. updateQuery(router, {
  86. widgets: JSON.stringify(currentWidgets),
  87. });
  88. };
  89. return {
  90. widgets,
  91. onChange,
  92. addWidget,
  93. };
  94. }
  95. // TODO(ddm): reuse from types/metrics.tsx
  96. type Group = {
  97. by: Record<string, unknown>;
  98. series: Record<string, number[]>;
  99. totals: Record<string, number>;
  100. };
  101. export function MetricWidget({
  102. widget,
  103. datetime,
  104. projects,
  105. environments,
  106. }: {
  107. datetime: PageFilters['datetime'];
  108. environments: PageFilters['environments'];
  109. projects: PageFilters['projects'];
  110. widget: MetricWidgetProps;
  111. }) {
  112. return (
  113. <MetricWidgetPanel key={widget.position}>
  114. <PanelBody>
  115. <QueryBuilder
  116. metricsQuery={{
  117. mri: widget.mri,
  118. query: widget.query,
  119. op: widget.op,
  120. groupBy: widget.groupBy,
  121. }}
  122. projects={projects}
  123. displayType={widget.displayType}
  124. onChange={widget.onChange}
  125. powerUserMode={widget.powerUserMode}
  126. />
  127. {widget.mri ? (
  128. <MetricWidgetBody
  129. datetime={datetime}
  130. projects={projects}
  131. environments={environments}
  132. {...widget}
  133. />
  134. ) : (
  135. <StyledMetricWidgetBody>
  136. <EmptyMessage
  137. icon={<IconSearch size="xxl" />}
  138. title={t('Nothing to show!')}
  139. description={t('Choose a metric to display data.')}
  140. />
  141. </StyledMetricWidgetBody>
  142. )}
  143. </PanelBody>
  144. </MetricWidgetPanel>
  145. );
  146. }
  147. function MetricWidgetBody({
  148. onChange,
  149. displayType,
  150. focusedSeries,
  151. sort,
  152. ...metricsQuery
  153. }: MetricWidgetProps & PageFilters) {
  154. const {mri, op, query, groupBy, projects, environments, datetime} = metricsQuery;
  155. const {data, isLoading, isError, error, onZoom} = useMetricsDataZoom({
  156. mri,
  157. op,
  158. query,
  159. groupBy,
  160. projects,
  161. environments,
  162. datetime,
  163. });
  164. const [dataToBeRendered, setDataToBeRendered] = useState<MetricsData | undefined>(
  165. undefined
  166. );
  167. const [hoveredLegend, setHoveredLegend] = useState('');
  168. useEffect(() => {
  169. if (data) {
  170. setDataToBeRendered(data);
  171. }
  172. }, [data]);
  173. const toggleSeriesVisibility = useCallback(
  174. (seriesName: string) => {
  175. setHoveredLegend('');
  176. onChange({
  177. focusedSeries: focusedSeries === seriesName ? undefined : seriesName,
  178. });
  179. },
  180. [focusedSeries, onChange]
  181. );
  182. if (!dataToBeRendered || isError) {
  183. return (
  184. <StyledMetricWidgetBody>
  185. {isLoading && <LoadingIndicator />}
  186. {isError && (
  187. <Alert type="error">
  188. {error?.responseJSON?.detail || t('Error while fetching metrics data')}
  189. </Alert>
  190. )}
  191. </StyledMetricWidgetBody>
  192. );
  193. }
  194. const chartSeries = getChartSeries(dataToBeRendered, {
  195. focusedSeries,
  196. hoveredLegend,
  197. groupBy: metricsQuery.groupBy,
  198. });
  199. return (
  200. <StyledMetricWidgetBody>
  201. <TransparentLoadingMask visible={isLoading} />
  202. <MetricChart
  203. series={chartSeries}
  204. displayType={displayType}
  205. operation={metricsQuery.op}
  206. projects={metricsQuery.projects}
  207. environments={metricsQuery.environments}
  208. {...normalizeChartTimeParams(dataToBeRendered)}
  209. onZoom={onZoom}
  210. />
  211. {metricsQuery.showSummaryTable && (
  212. <SummaryTable
  213. series={chartSeries}
  214. onSortChange={newSort => {
  215. onChange({sort: newSort});
  216. }}
  217. sort={sort}
  218. operation={metricsQuery.op}
  219. onRowClick={toggleSeriesVisibility}
  220. setHoveredLegend={focusedSeries ? undefined : setHoveredLegend}
  221. />
  222. )}
  223. </StyledMetricWidgetBody>
  224. );
  225. }
  226. function getChartSeries(data: MetricsData, {focusedSeries, groupBy, hoveredLegend}) {
  227. const unit = getUnitFromMRI(Object.keys(data.groups[0]?.series ?? {})[0]); // this assumes that all series have the same unit
  228. const series = data.groups.map(g => {
  229. return {
  230. values: Object.values(g.series)[0],
  231. name: getSeriesName(g, data.groups.length === 1, groupBy),
  232. transaction: g.by.transaction,
  233. release: g.by.release,
  234. };
  235. });
  236. const colors = theme.charts.getColorPalette(series.length);
  237. return series
  238. .sort((a, b) => a.name?.localeCompare(b.name))
  239. .map((item, i) => ({
  240. seriesName: item.name,
  241. unit,
  242. color: colorFn(colors[i])
  243. .alpha(hoveredLegend && hoveredLegend !== item.name ? 0.1 : 1)
  244. .string(),
  245. hidden: focusedSeries && focusedSeries !== item.name,
  246. data: item.values.map((value, index) => ({
  247. name: moment(data.intervals[index]).valueOf(),
  248. value,
  249. })),
  250. transaction: item.transaction as string | undefined,
  251. release: item.release as string | undefined,
  252. emphasis: {
  253. focus: 'series',
  254. } as LineSeriesOption['emphasis'],
  255. })) as Series[];
  256. }
  257. function getSeriesName(
  258. group: Group,
  259. isOnlyGroup = false,
  260. groupBy: MetricsQuery['groupBy']
  261. ) {
  262. if (isOnlyGroup && !groupBy?.length) {
  263. return Object.keys(group.series)?.[0] ?? '(none)';
  264. }
  265. return Object.entries(group.by)
  266. .map(([key, value]) => `${key}:${String(value).length ? value : t('none')}`)
  267. .join(', ');
  268. }
  269. function normalizeChartTimeParams(data: MetricsData) {
  270. const {
  271. start,
  272. end,
  273. utc: utcString,
  274. statsPeriod,
  275. } = normalizeDateTimeParams(data, {
  276. allowEmptyPeriod: true,
  277. allowAbsoluteDatetime: true,
  278. allowAbsolutePageDatetime: true,
  279. });
  280. const utc = utcString === 'true';
  281. if (start && end) {
  282. return utc
  283. ? {
  284. start: moment.utc(start).format(),
  285. end: moment.utc(end).format(),
  286. utc,
  287. }
  288. : {
  289. start: moment(start).utc().format(),
  290. end: moment(end).utc().format(),
  291. utc,
  292. };
  293. }
  294. return {
  295. period: statsPeriod ?? '90d',
  296. };
  297. }
  298. export type Series = {
  299. color: string;
  300. data: {name: number; value: number}[];
  301. seriesName: string;
  302. unit: string;
  303. hidden?: boolean;
  304. release?: string;
  305. transaction?: string;
  306. };
  307. const MetricWidgetPanel = styled(Panel)`
  308. padding-bottom: 0;
  309. margin-bottom: 0;
  310. min-width: ${MIN_WIDGET_WIDTH};
  311. `;
  312. const StyledMetricWidgetBody = styled('div')`
  313. padding: ${space(1)};
  314. display: flex;
  315. flex-direction: column;
  316. justify-content: center;
  317. `;