widgetCard.tsx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import {Fragment, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import {ErrorBoundary} from '@sentry/react';
  4. import type {Location} from 'history';
  5. import ErrorPanel from 'sentry/components/charts/errorPanel';
  6. import {HeaderTitle} from 'sentry/components/charts/styles';
  7. import {EquationFormatter} from 'sentry/components/metrics/equationInput/syntax/formatter';
  8. import TextOverflow from 'sentry/components/textOverflow';
  9. import {IconWarning} from 'sentry/icons';
  10. import {t} from 'sentry/locale';
  11. import {space} from 'sentry/styles/space';
  12. import type {PageFilters} from 'sentry/types/core';
  13. import type {InjectedRouter} from 'sentry/types/legacyReactRouter';
  14. import type {Organization} from 'sentry/types/organization';
  15. import {getFormattedMQL, unescapeMetricsFormula} from 'sentry/utils/metrics';
  16. import {hasMetricsNewInputs} from 'sentry/utils/metrics/features';
  17. import {formatMRIField, MRIToField, parseMRI} from 'sentry/utils/metrics/mri';
  18. import {MetricExpressionType} from 'sentry/utils/metrics/types';
  19. import {useMetricsQuery} from 'sentry/utils/metrics/useMetricsQuery';
  20. import {useVirtualMetricsContext} from 'sentry/utils/metrics/virtualMetricsContext';
  21. import {MetricBigNumberContainer} from 'sentry/views/dashboards/metrics/bigNumber';
  22. import {MetricChartContainer} from 'sentry/views/dashboards/metrics/chart';
  23. import {MetricTableContainer} from 'sentry/views/dashboards/metrics/table';
  24. import type {DashboardMetricsExpression} from 'sentry/views/dashboards/metrics/types';
  25. import {
  26. expressionsToApiQueries,
  27. formatAlias,
  28. getMetricExpressions,
  29. isMetricsEquation,
  30. toMetricDisplayType,
  31. } from 'sentry/views/dashboards/metrics/utils';
  32. import type {DashboardFilters, Widget} from 'sentry/views/dashboards/types';
  33. import {DisplayType} from 'sentry/views/dashboards/types';
  34. import {
  35. WidgetCardContextMenuContainer,
  36. WidgetCardPanel,
  37. WidgetTitleRow,
  38. } from 'sentry/views/dashboards/widgetCard';
  39. import {DashboardsMEPContext} from 'sentry/views/dashboards/widgetCard/dashboardsMEPContext';
  40. import {Toolbar} from 'sentry/views/dashboards/widgetCard/toolbar';
  41. import WidgetCardContextMenu from 'sentry/views/dashboards/widgetCard/widgetCardContextMenu';
  42. import {useMetricsIntervalOptions} from 'sentry/views/metrics/utils/useMetricsIntervalParam';
  43. type Props = {
  44. isEditingDashboard: boolean;
  45. location: Location;
  46. organization: Organization;
  47. router: InjectedRouter;
  48. selection: PageFilters;
  49. widget: Widget;
  50. dashboardFilters?: DashboardFilters;
  51. index?: string;
  52. isMobile?: boolean;
  53. onDelete?: () => void;
  54. onDuplicate?: () => void;
  55. onEdit?: (index: string) => void;
  56. renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
  57. showContextMenu?: boolean;
  58. };
  59. const EMPTY_FN = () => {};
  60. export function getWidgetTitle(expressions: DashboardMetricsExpression[]) {
  61. const filteredExpressions = expressions.filter(query => !query.isQueryOnly);
  62. if (filteredExpressions.length === 1) {
  63. const firstQuery = filteredExpressions[0];
  64. if (isMetricsEquation(firstQuery)) {
  65. return (
  66. <Fragment>
  67. <EquationFormatter equation={unescapeMetricsFormula(firstQuery.formula)} />
  68. </Fragment>
  69. );
  70. }
  71. return formatAlias(firstQuery.alias) ?? getFormattedMQL(firstQuery);
  72. }
  73. return filteredExpressions
  74. .map(q =>
  75. isMetricsEquation(q)
  76. ? formatAlias(q.alias) ?? unescapeMetricsFormula(q.formula)
  77. : formatAlias(q.alias) ?? formatMRIField(MRIToField(q.mri, q.aggregation))
  78. )
  79. .join(', ');
  80. }
  81. export function MetricWidgetCard({
  82. organization,
  83. selection,
  84. widget,
  85. isEditingDashboard,
  86. onDelete,
  87. onDuplicate,
  88. location,
  89. router,
  90. dashboardFilters,
  91. renderErrorMessage,
  92. showContextMenu = true,
  93. }: Props) {
  94. const metricsNewInputs = hasMetricsNewInputs(organization);
  95. const {getVirtualMRIQuery, isLoading: isLoadingVirtualMetrics} =
  96. useVirtualMetricsContext();
  97. const metricExpressions = getMetricExpressions(
  98. widget,
  99. dashboardFilters,
  100. getVirtualMRIQuery
  101. );
  102. const hasSetMetric = useMemo(
  103. () =>
  104. metricExpressions.some(
  105. expression =>
  106. expression.type === MetricExpressionType.QUERY &&
  107. parseMRI(expression.mri)!.type === 's'
  108. ),
  109. [metricExpressions]
  110. );
  111. const widgetMQL = useMemo(
  112. () => (isLoadingVirtualMetrics ? '' : getWidgetTitle(metricExpressions)),
  113. [isLoadingVirtualMetrics, metricExpressions]
  114. );
  115. const metricQueries = useMemo(() => {
  116. const formattedAliasQueries = expressionsToApiQueries(
  117. metricExpressions,
  118. metricsNewInputs
  119. ).map(query => {
  120. if (query.alias) {
  121. return {...query, alias: formatAlias(query.alias)};
  122. }
  123. return query;
  124. });
  125. return [...formattedAliasQueries];
  126. }, [metricExpressions, metricsNewInputs]);
  127. const {interval: validatedInterval} = useMetricsIntervalOptions({
  128. // TODO: Figure out why this can be undefined
  129. interval: widget.interval ?? '',
  130. hasSetMetric,
  131. datetime: selection.datetime,
  132. onIntervalChange: EMPTY_FN,
  133. });
  134. const {
  135. data: timeseriesData,
  136. isPending,
  137. isError,
  138. error,
  139. } = useMetricsQuery(metricQueries, selection, {
  140. interval: validatedInterval,
  141. });
  142. const vizualizationComponent = useMemo(() => {
  143. if (widget.displayType === DisplayType.TABLE) {
  144. return (
  145. <MetricTableContainer
  146. metricQueries={metricQueries}
  147. timeseriesData={timeseriesData}
  148. isLoading={isPending}
  149. />
  150. );
  151. }
  152. if (widget.displayType === DisplayType.BIG_NUMBER) {
  153. return (
  154. <MetricBigNumberContainer timeseriesData={timeseriesData} isLoading={isPending} />
  155. );
  156. }
  157. return (
  158. <MetricChartContainer
  159. timeseriesData={timeseriesData}
  160. isLoading={isPending}
  161. metricQueries={metricQueries}
  162. displayType={toMetricDisplayType(widget.displayType)}
  163. chartHeight={!showContextMenu ? 200 : undefined}
  164. showLegend
  165. />
  166. );
  167. }, [widget.displayType, metricQueries, timeseriesData, isPending, showContextMenu]);
  168. return (
  169. <DashboardsMEPContext.Provider
  170. value={{
  171. isMetricsData: undefined,
  172. setIsMetricsData: () => {},
  173. }}
  174. >
  175. <WidgetCardPanel isDragging={false}>
  176. <WidgetHeaderWrapper>
  177. <WidgetHeaderDescription>
  178. <WidgetTitleRow>
  179. <WidgetTitle>
  180. <TextOverflow>{widget.title || widgetMQL}</TextOverflow>
  181. </WidgetTitle>
  182. </WidgetTitleRow>
  183. </WidgetHeaderDescription>
  184. <ContextMenuWrapper>
  185. {showContextMenu && !isEditingDashboard && (
  186. <WidgetCardContextMenuContainer>
  187. <WidgetCardContextMenu
  188. organization={organization}
  189. widget={widget}
  190. selection={selection}
  191. showContextMenu
  192. isPreview={false}
  193. widgetLimitReached={false}
  194. onEdit={() => {
  195. router.push({
  196. pathname: `${location.pathname}${
  197. location.pathname.endsWith('/') ? '' : '/'
  198. }widget/${widget.id}/`,
  199. query: location.query,
  200. });
  201. }}
  202. router={router}
  203. location={location}
  204. onDelete={onDelete}
  205. onDuplicate={onDuplicate}
  206. title={widget.title || widgetMQL}
  207. />
  208. </WidgetCardContextMenuContainer>
  209. )}
  210. </ContextMenuWrapper>
  211. </WidgetHeaderWrapper>
  212. <ErrorBoundary>
  213. <WidgetCardBody
  214. isError={isError}
  215. timeseriesData={timeseriesData}
  216. renderErrorMessage={renderErrorMessage}
  217. error={error}
  218. >
  219. {vizualizationComponent}
  220. </WidgetCardBody>
  221. </ErrorBoundary>
  222. {isEditingDashboard && <Toolbar onDelete={onDelete} onDuplicate={onDuplicate} />}
  223. </WidgetCardPanel>
  224. </DashboardsMEPContext.Provider>
  225. );
  226. }
  227. function WidgetCardBody({children, isError, timeseriesData, renderErrorMessage, error}) {
  228. if (isError && !timeseriesData) {
  229. const errorMessage =
  230. error?.responseJSON?.detail?.toString() || t('Error while fetching metrics data');
  231. return (
  232. <ErrorWrapper>
  233. {renderErrorMessage?.(errorMessage)}
  234. <ErrorPanel>
  235. <IconWarning color="gray500" size="lg" />
  236. </ErrorPanel>
  237. </ErrorWrapper>
  238. );
  239. }
  240. return children;
  241. }
  242. const WidgetHeaderWrapper = styled('div')`
  243. min-height: 36px;
  244. width: 100%;
  245. display: flex;
  246. align-items: flex-start;
  247. justify-content: space-between;
  248. `;
  249. const ContextMenuWrapper = styled('div')`
  250. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  251. `;
  252. const WidgetHeaderDescription = styled('div')`
  253. ${p => p.theme.overflowEllipsis};
  254. overflow-y: visible;
  255. `;
  256. const WidgetTitle = styled(HeaderTitle)`
  257. padding-left: ${space(3)};
  258. padding-top: ${space(2)};
  259. padding-right: ${space(1)};
  260. ${p => p.theme.overflowEllipsis};
  261. font-weight: ${p => p.theme.fontWeightBold};
  262. `;
  263. const ErrorWrapper = styled('div')`
  264. padding-top: ${space(1)};
  265. `;