widget.tsx 9.2 KB

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