widget.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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 {MetricsApiResponse, PageFilters} from 'sentry/types';
  17. import {
  18. defaultMetricDisplayType,
  19. getSeriesName,
  20. MetricDisplayType,
  21. MetricsQuery,
  22. parseMRI,
  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 {MetricWidgetContextMenu} from 'sentry/views/ddm/contextMenu';
  31. import {QueryBuilder} from 'sentry/views/ddm/queryBuilder';
  32. import {SummaryTable} from 'sentry/views/ddm/summaryTable';
  33. import {DEFAULT_SORT_STATE, MIN_WIDGET_WIDTH} from './constants';
  34. type SortState = {
  35. name: 'name' | 'avg' | 'min' | 'max' | 'sum';
  36. order: 'asc' | 'desc';
  37. };
  38. const emptyWidget = {
  39. mri: '',
  40. op: undefined,
  41. query: '',
  42. groupBy: [],
  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. export function MetricWidget({
  96. widget,
  97. datetime,
  98. projects,
  99. environments,
  100. }: {
  101. datetime: PageFilters['datetime'];
  102. environments: PageFilters['environments'];
  103. projects: PageFilters['projects'];
  104. widget: MetricWidgetProps;
  105. }) {
  106. return (
  107. <MetricWidgetPanel key={widget.position}>
  108. <PanelBody>
  109. <MetricWidgetHeader>
  110. <QueryBuilder
  111. metricsQuery={{
  112. mri: widget.mri,
  113. query: widget.query,
  114. op: widget.op,
  115. groupBy: widget.groupBy,
  116. }}
  117. projects={projects}
  118. displayType={widget.displayType}
  119. onChange={widget.onChange}
  120. powerUserMode={widget.powerUserMode}
  121. />
  122. <MetricWidgetContextMenu
  123. metricsQuery={{
  124. mri: widget.mri,
  125. query: widget.query,
  126. op: widget.op,
  127. groupBy: widget.groupBy,
  128. projects,
  129. datetime,
  130. environments,
  131. }}
  132. displayType={widget.displayType}
  133. />
  134. </MetricWidgetHeader>
  135. {widget.mri ? (
  136. <MetricWidgetBody
  137. datetime={datetime}
  138. projects={projects}
  139. environments={environments}
  140. {...widget}
  141. />
  142. ) : (
  143. <StyledMetricWidgetBody>
  144. <EmptyMessage
  145. icon={<IconSearch size="xxl" />}
  146. title={t('Nothing to show!')}
  147. description={t('Choose a metric to display data.')}
  148. />
  149. </StyledMetricWidgetBody>
  150. )}
  151. </PanelBody>
  152. </MetricWidgetPanel>
  153. );
  154. }
  155. const MetricWidgetHeader = styled('div')`
  156. display: flex;
  157. justify-content: space-between;
  158. margin-bottom: ${space(1)};
  159. `;
  160. function MetricWidgetBody({
  161. onChange,
  162. displayType,
  163. focusedSeries,
  164. sort,
  165. ...metricsQuery
  166. }: MetricWidgetProps & PageFilters) {
  167. const {mri, op, query, groupBy, projects, environments, datetime} = metricsQuery;
  168. const {data, isLoading, isError, error, onZoom} = useMetricsDataZoom({
  169. mri,
  170. op,
  171. query,
  172. groupBy,
  173. projects,
  174. environments,
  175. datetime,
  176. });
  177. const [dataToBeRendered, setDataToBeRendered] = useState<
  178. MetricsApiResponse | undefined
  179. >(undefined);
  180. const [hoveredLegend, setHoveredLegend] = useState('');
  181. useEffect(() => {
  182. if (data) {
  183. setDataToBeRendered(data);
  184. }
  185. }, [data]);
  186. const toggleSeriesVisibility = useCallback(
  187. (seriesName: string) => {
  188. setHoveredLegend('');
  189. onChange({
  190. focusedSeries: focusedSeries === seriesName ? undefined : seriesName,
  191. });
  192. },
  193. [focusedSeries, onChange]
  194. );
  195. if (!dataToBeRendered || isError) {
  196. return (
  197. <StyledMetricWidgetBody>
  198. {isLoading && <LoadingIndicator />}
  199. {isError && (
  200. <Alert type="error">
  201. {error?.responseJSON?.detail || t('Error while fetching metrics data')}
  202. </Alert>
  203. )}
  204. </StyledMetricWidgetBody>
  205. );
  206. }
  207. const chartSeries = getChartSeries(dataToBeRendered, {
  208. focusedSeries,
  209. hoveredLegend,
  210. groupBy: metricsQuery.groupBy,
  211. });
  212. return (
  213. <StyledMetricWidgetBody>
  214. <TransparentLoadingMask visible={isLoading} />
  215. <MetricChart
  216. series={chartSeries}
  217. displayType={displayType}
  218. operation={metricsQuery.op}
  219. projects={metricsQuery.projects}
  220. environments={metricsQuery.environments}
  221. {...normalizeChartTimeParams(dataToBeRendered)}
  222. onZoom={onZoom}
  223. />
  224. {metricsQuery.showSummaryTable && (
  225. <SummaryTable
  226. series={chartSeries}
  227. onSortChange={newSort => {
  228. onChange({sort: newSort});
  229. }}
  230. sort={sort}
  231. operation={metricsQuery.op}
  232. onRowClick={toggleSeriesVisibility}
  233. setHoveredLegend={focusedSeries ? undefined : setHoveredLegend}
  234. />
  235. )}
  236. </StyledMetricWidgetBody>
  237. );
  238. }
  239. function getChartSeries(
  240. data: MetricsApiResponse,
  241. {focusedSeries, groupBy, hoveredLegend}
  242. ) {
  243. // this assumes that all series have the same unit
  244. const parsed = parseMRI(Object.keys(data.groups[0]?.series ?? {})[0]);
  245. const unit = parsed?.unit ?? '';
  246. const series = data.groups.map(g => {
  247. return {
  248. values: Object.values(g.series)[0],
  249. name: getSeriesName(g, data.groups.length === 1, groupBy),
  250. transaction: g.by.transaction,
  251. release: g.by.release,
  252. };
  253. });
  254. const colors = theme.charts.getColorPalette(series.length);
  255. return series
  256. .sort((a, b) => a.name?.localeCompare(b.name))
  257. .map((item, i) => ({
  258. seriesName: item.name,
  259. unit,
  260. color: colorFn(colors[i])
  261. .alpha(hoveredLegend && hoveredLegend !== item.name ? 0.1 : 1)
  262. .string(),
  263. hidden: focusedSeries && focusedSeries !== item.name,
  264. data: item.values.map((value, index) => ({
  265. name: moment(data.intervals[index]).valueOf(),
  266. value,
  267. })),
  268. transaction: item.transaction as string | undefined,
  269. release: item.release as string | undefined,
  270. emphasis: {
  271. focus: 'series',
  272. } as LineSeriesOption['emphasis'],
  273. })) as Series[];
  274. }
  275. function normalizeChartTimeParams(data: MetricsApiResponse) {
  276. const {
  277. start,
  278. end,
  279. utc: utcString,
  280. statsPeriod,
  281. } = normalizeDateTimeParams(data, {
  282. allowEmptyPeriod: true,
  283. allowAbsoluteDatetime: true,
  284. allowAbsolutePageDatetime: true,
  285. });
  286. const utc = utcString === 'true';
  287. if (start && end) {
  288. return utc
  289. ? {
  290. start: moment.utc(start).format(),
  291. end: moment.utc(end).format(),
  292. utc,
  293. }
  294. : {
  295. start: moment(start).utc().format(),
  296. end: moment(end).utc().format(),
  297. utc,
  298. };
  299. }
  300. return {
  301. period: statsPeriod ?? '90d',
  302. };
  303. }
  304. export type Series = {
  305. color: string;
  306. data: {name: number; value: number}[];
  307. seriesName: string;
  308. unit: string;
  309. hidden?: boolean;
  310. release?: string;
  311. transaction?: string;
  312. };
  313. const MetricWidgetPanel = styled(Panel)`
  314. padding-bottom: 0;
  315. margin-bottom: 0;
  316. min-width: ${MIN_WIDGET_WIDTH}px;
  317. `;
  318. const StyledMetricWidgetBody = styled('div')`
  319. padding: ${space(1)};
  320. display: flex;
  321. flex-direction: column;
  322. justify-content: center;
  323. `;