index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. import {Component, Fragment} from 'react';
  2. import LazyLoad from 'react-lazyload';
  3. import type {WithRouterProps} from 'react-router';
  4. import type {useSortable} from '@dnd-kit/sortable';
  5. import styled from '@emotion/styled';
  6. import type {Location} from 'history';
  7. import type {Client} from 'sentry/api';
  8. import {Alert} from 'sentry/components/alert';
  9. import ErrorPanel from 'sentry/components/charts/errorPanel';
  10. import {HeaderTitle} from 'sentry/components/charts/styles';
  11. import ErrorBoundary from 'sentry/components/errorBoundary';
  12. import ExternalLink from 'sentry/components/links/externalLink';
  13. import Panel from 'sentry/components/panels/panel';
  14. import PanelAlert from 'sentry/components/panels/panelAlert';
  15. import Placeholder from 'sentry/components/placeholder';
  16. import {parseSearch} from 'sentry/components/searchSyntax/parser';
  17. import {Tooltip} from 'sentry/components/tooltip';
  18. import {IconWarning} from 'sentry/icons';
  19. import {t, tct} from 'sentry/locale';
  20. import {space} from 'sentry/styles/space';
  21. import type {Organization, PageFilters} from 'sentry/types';
  22. import type {Series} from 'sentry/types/echarts';
  23. import {getFormattedDate} from 'sentry/utils/dates';
  24. import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  25. import type {AggregationOutputType} from 'sentry/utils/discover/fields';
  26. import {parseFunction} from 'sentry/utils/discover/fields';
  27. import {isSupportedDisplayType} from 'sentry/utils/metrics';
  28. import {hasDDMFeature} from 'sentry/utils/metrics/features';
  29. import {ExtractedMetricsTag} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
  30. import {
  31. MEPConsumer,
  32. MEPState,
  33. } from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  34. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  35. import withApi from 'sentry/utils/withApi';
  36. import withOrganization from 'sentry/utils/withOrganization';
  37. import withPageFilters from 'sentry/utils/withPageFilters';
  38. // eslint-disable-next-line no-restricted-imports
  39. import withSentryRouter from 'sentry/utils/withSentryRouter';
  40. import {MetricWidgetCard} from 'sentry/views/dashboards/widgetCard/metricWidgetCard';
  41. import {Toolbar} from 'sentry/views/dashboards/widgetCard/toolbar';
  42. import type {DashboardFilters, Widget} from '../types';
  43. import {DisplayType, WidgetType} from '../types';
  44. import {getColoredWidgetIndicator, hasThresholdMaxValue} from '../utils';
  45. import {DEFAULT_RESULTS_LIMIT} from '../widgetBuilder/utils';
  46. import {DashboardsMEPConsumer, DashboardsMEPProvider} from './dashboardsMEPContext';
  47. import WidgetCardChartContainer from './widgetCardChartContainer';
  48. import WidgetCardContextMenu from './widgetCardContextMenu';
  49. const SESSION_DURATION_INGESTION_STOP_DATE = new Date('2023-01-12');
  50. export const SESSION_DURATION_ALERT = (
  51. <PanelAlert type="warning">
  52. {t(
  53. 'session.duration is no longer being recorded as of %s. Data in this widget may be incomplete.',
  54. getFormattedDate(SESSION_DURATION_INGESTION_STOP_DATE, 'MMM D, YYYY')
  55. )}
  56. </PanelAlert>
  57. );
  58. type DraggableProps = Pick<ReturnType<typeof useSortable>, 'attributes' | 'listeners'>;
  59. type Props = WithRouterProps & {
  60. api: Client;
  61. isEditingDashboard: boolean;
  62. location: Location;
  63. organization: Organization;
  64. selection: PageFilters;
  65. widget: Widget;
  66. widgetLimitReached: boolean;
  67. dashboardFilters?: DashboardFilters;
  68. draggableProps?: DraggableProps;
  69. hideToolbar?: boolean;
  70. index?: string;
  71. isEditingWidget?: boolean;
  72. isMobile?: boolean;
  73. isPreview?: boolean;
  74. isWidgetInvalid?: boolean;
  75. noDashboardsMEPProvider?: boolean;
  76. noLazyLoad?: boolean;
  77. onDataFetched?: (results: TableDataWithTitle[]) => void;
  78. onDelete?: () => void;
  79. onDuplicate?: () => void;
  80. onEdit?: () => void;
  81. onUpdate?: (widget: Widget | null) => void;
  82. renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
  83. showContextMenu?: boolean;
  84. showStoredAlert?: boolean;
  85. tableItemLimit?: number;
  86. windowWidth?: number;
  87. };
  88. type State = {
  89. pageLinks?: string;
  90. seriesData?: Series[];
  91. seriesResultsType?: Record<string, AggregationOutputType>;
  92. tableData?: TableDataWithTitle[];
  93. totalIssuesCount?: string;
  94. };
  95. type SearchFilterKey = {key?: {value: string}};
  96. const ERROR_FIELDS = [
  97. 'error.handled',
  98. 'error.unhandled',
  99. 'error.mechanism',
  100. 'error.type',
  101. 'error.value',
  102. ];
  103. class WidgetCard extends Component<Props, State> {
  104. state: State = {};
  105. renderToolbar() {
  106. const {
  107. onEdit,
  108. onDelete,
  109. onDuplicate,
  110. draggableProps,
  111. hideToolbar,
  112. isEditingDashboard,
  113. isMobile,
  114. } = this.props;
  115. if (!isEditingDashboard) {
  116. return null;
  117. }
  118. return (
  119. <Toolbar
  120. onEdit={onEdit}
  121. onDelete={onDelete}
  122. onDuplicate={onDuplicate}
  123. draggableProps={draggableProps}
  124. hideToolbar={hideToolbar}
  125. isMobile={isMobile}
  126. />
  127. );
  128. }
  129. renderContextMenu() {
  130. const {
  131. widget,
  132. selection,
  133. organization,
  134. showContextMenu,
  135. isPreview,
  136. widgetLimitReached,
  137. onEdit,
  138. onDuplicate,
  139. onDelete,
  140. isEditingDashboard,
  141. router,
  142. location,
  143. index,
  144. } = this.props;
  145. const {seriesData, tableData, pageLinks, totalIssuesCount, seriesResultsType} =
  146. this.state;
  147. if (isEditingDashboard) {
  148. return null;
  149. }
  150. return (
  151. <WidgetCardContextMenu
  152. organization={organization}
  153. widget={widget}
  154. selection={selection}
  155. showContextMenu={showContextMenu}
  156. isPreview={isPreview}
  157. widgetLimitReached={widgetLimitReached}
  158. onDuplicate={onDuplicate}
  159. onEdit={onEdit}
  160. onDelete={onDelete}
  161. router={router}
  162. location={location}
  163. index={index}
  164. seriesData={seriesData}
  165. seriesResultsType={seriesResultsType}
  166. tableData={tableData}
  167. pageLinks={pageLinks}
  168. totalIssuesCount={totalIssuesCount}
  169. />
  170. );
  171. }
  172. setData = ({
  173. tableResults,
  174. timeseriesResults,
  175. totalIssuesCount,
  176. pageLinks,
  177. timeseriesResultsTypes,
  178. }: {
  179. pageLinks?: string;
  180. tableResults?: TableDataWithTitle[];
  181. timeseriesResults?: Series[];
  182. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  183. totalIssuesCount?: string;
  184. }) => {
  185. const {onDataFetched} = this.props;
  186. if (onDataFetched && tableResults) {
  187. onDataFetched(tableResults);
  188. }
  189. this.setState({
  190. seriesData: timeseriesResults,
  191. tableData: tableResults,
  192. totalIssuesCount,
  193. pageLinks,
  194. seriesResultsType: timeseriesResultsTypes,
  195. });
  196. };
  197. render() {
  198. const {
  199. api,
  200. organization,
  201. selection,
  202. widget,
  203. isMobile,
  204. renderErrorMessage,
  205. tableItemLimit,
  206. windowWidth,
  207. noLazyLoad,
  208. showStoredAlert,
  209. noDashboardsMEPProvider,
  210. dashboardFilters,
  211. isWidgetInvalid,
  212. location,
  213. } = this.props;
  214. if (widget.displayType === DisplayType.TOP_N) {
  215. const queries = widget.queries.map(query => ({
  216. ...query,
  217. // Use the last aggregate because that's where the y-axis is stored
  218. aggregates: query.aggregates.length
  219. ? [query.aggregates[query.aggregates.length - 1]]
  220. : [],
  221. }));
  222. widget.queries = queries;
  223. widget.limit = DEFAULT_RESULTS_LIMIT;
  224. }
  225. const hasSessionDuration = widget.queries.some(query =>
  226. query.aggregates.some(aggregate => aggregate.includes('session.duration'))
  227. );
  228. function conditionalWrapWithDashboardsMEPProvider(component: React.ReactNode) {
  229. if (noDashboardsMEPProvider) {
  230. return component;
  231. }
  232. return <DashboardsMEPProvider>{component}</DashboardsMEPProvider>;
  233. }
  234. const widgetContainsErrorFields = widget.queries.some(
  235. ({columns, aggregates, conditions}) =>
  236. ERROR_FIELDS.some(
  237. errorField =>
  238. columns.includes(errorField) ||
  239. aggregates.some(aggregate =>
  240. parseFunction(aggregate)?.arguments.includes(errorField)
  241. ) ||
  242. parseSearch(conditions)?.some(
  243. filter => (filter as SearchFilterKey).key?.value === errorField
  244. )
  245. )
  246. );
  247. if (widget.widgetType === WidgetType.METRICS) {
  248. if (hasDDMFeature(organization) && isSupportedDisplayType(widget.displayType)) {
  249. return (
  250. <MetricWidgetCard
  251. index={this.props.index}
  252. isEditingWidget={this.props.isEditingWidget}
  253. isEditingDashboard={this.props.isEditingDashboard}
  254. onEdit={this.props.onEdit}
  255. onUpdate={this.props.onUpdate}
  256. onDelete={this.props.onDelete}
  257. onDuplicate={this.props.onDuplicate}
  258. router={this.props.router}
  259. location={this.props.location}
  260. organization={organization}
  261. selection={selection}
  262. widget={widget}
  263. />
  264. );
  265. }
  266. }
  267. return (
  268. <ErrorBoundary
  269. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  270. >
  271. {conditionalWrapWithDashboardsMEPProvider(
  272. <Fragment>
  273. <VisuallyCompleteWithData
  274. id="DashboardList-FirstWidgetCard"
  275. hasData={
  276. ((this.state.tableData?.length || this.state.seriesData?.length) ?? 0) > 0
  277. }
  278. disabled={Number(this.props.index) !== 0}
  279. >
  280. <WidgetCardPanel isDragging={false}>
  281. <WidgetHeaderWrapper>
  282. <WidgetHeaderDescription>
  283. <WidgetTitleRow>
  284. <Tooltip
  285. title={widget.title}
  286. containerDisplayMode="grid"
  287. showOnlyOnOverflow
  288. >
  289. <WidgetTitle>{widget.title}</WidgetTitle>
  290. </Tooltip>
  291. {widget.thresholds &&
  292. hasThresholdMaxValue(widget.thresholds) &&
  293. this.state.tableData &&
  294. organization.features.includes('dashboard-widget-indicators') &&
  295. getColoredWidgetIndicator(
  296. widget.thresholds,
  297. this.state.tableData
  298. )}
  299. <ExtractedMetricsTag queryKey={widget} />
  300. </WidgetTitleRow>
  301. {widget.description && (
  302. <Tooltip
  303. title={widget.description}
  304. containerDisplayMode="grid"
  305. showOnlyOnOverflow
  306. isHoverable
  307. >
  308. <WidgetDescription>{widget.description}</WidgetDescription>
  309. </Tooltip>
  310. )}
  311. </WidgetHeaderDescription>
  312. {this.renderContextMenu()}
  313. </WidgetHeaderWrapper>
  314. {hasSessionDuration && SESSION_DURATION_ALERT}
  315. {isWidgetInvalid ? (
  316. <Fragment>
  317. {renderErrorMessage?.('Widget query condition is invalid.')}
  318. <StyledErrorPanel>
  319. <IconWarning color="gray500" size="lg" />
  320. </StyledErrorPanel>
  321. </Fragment>
  322. ) : noLazyLoad ? (
  323. <WidgetCardChartContainer
  324. location={location}
  325. api={api}
  326. organization={organization}
  327. selection={selection}
  328. widget={widget}
  329. isMobile={isMobile}
  330. renderErrorMessage={renderErrorMessage}
  331. tableItemLimit={tableItemLimit}
  332. windowWidth={windowWidth}
  333. onDataFetched={this.setData}
  334. dashboardFilters={dashboardFilters}
  335. />
  336. ) : (
  337. <LazyLoad once resize height={200}>
  338. <WidgetCardChartContainer
  339. location={location}
  340. api={api}
  341. organization={organization}
  342. selection={selection}
  343. widget={widget}
  344. isMobile={isMobile}
  345. renderErrorMessage={renderErrorMessage}
  346. tableItemLimit={tableItemLimit}
  347. windowWidth={windowWidth}
  348. onDataFetched={this.setData}
  349. dashboardFilters={dashboardFilters}
  350. />
  351. </LazyLoad>
  352. )}
  353. {this.renderToolbar()}
  354. </WidgetCardPanel>
  355. </VisuallyCompleteWithData>
  356. {!organization.features.includes('performance-mep-bannerless-ui') && (
  357. <MEPConsumer>
  358. {metricSettingContext => {
  359. return (
  360. <DashboardsMEPConsumer>
  361. {({isMetricsData}) => {
  362. if (
  363. showStoredAlert &&
  364. isMetricsData === false &&
  365. widget.widgetType === WidgetType.DISCOVER &&
  366. metricSettingContext &&
  367. metricSettingContext.metricSettingState !==
  368. MEPState.TRANSACTIONS_ONLY
  369. ) {
  370. if (!widgetContainsErrorFields) {
  371. return (
  372. <StoredDataAlert showIcon>
  373. {tct(
  374. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  375. {
  376. indexedData: (
  377. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  378. ),
  379. }
  380. )}
  381. </StoredDataAlert>
  382. );
  383. }
  384. }
  385. return null;
  386. }}
  387. </DashboardsMEPConsumer>
  388. );
  389. }}
  390. </MEPConsumer>
  391. )}
  392. </Fragment>
  393. )}
  394. </ErrorBoundary>
  395. );
  396. }
  397. }
  398. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  399. const ErrorCard = styled(Placeholder)`
  400. display: flex;
  401. align-items: center;
  402. justify-content: center;
  403. background-color: ${p => p.theme.alert.error.backgroundLight};
  404. border: 1px solid ${p => p.theme.alert.error.border};
  405. color: ${p => p.theme.alert.error.textLight};
  406. border-radius: ${p => p.theme.borderRadius};
  407. margin-bottom: ${space(2)};
  408. `;
  409. export const WidgetCardPanel = styled(Panel, {
  410. shouldForwardProp: prop => prop !== 'isDragging',
  411. })<{
  412. isDragging: boolean;
  413. }>`
  414. margin: 0;
  415. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  416. /* If a panel overflows due to a long title stretch its grid sibling */
  417. height: 100%;
  418. min-height: 96px;
  419. display: flex;
  420. flex-direction: column;
  421. `;
  422. const StoredDataAlert = styled(Alert)`
  423. margin-top: ${space(1)};
  424. margin-bottom: 0;
  425. `;
  426. const StyledErrorPanel = styled(ErrorPanel)`
  427. padding: ${space(2)};
  428. `;
  429. export const WidgetTitleRow = styled('span')`
  430. display: flex;
  431. align-items: center;
  432. gap: ${space(0.75)};
  433. `;
  434. export const WidgetDescription = styled('small')`
  435. ${p => p.theme.overflowEllipsis}
  436. color: ${p => p.theme.gray300};
  437. `;
  438. const WidgetTitle = styled(HeaderTitle)`
  439. ${p => p.theme.overflowEllipsis};
  440. font-weight: normal;
  441. `;
  442. const WidgetHeaderWrapper = styled('div')`
  443. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  444. min-height: 36px;
  445. width: 100%;
  446. display: flex;
  447. align-items: center;
  448. justify-content: space-between;
  449. `;
  450. const WidgetHeaderDescription = styled('div')`
  451. display: flex;
  452. flex-direction: column;
  453. gap: ${space(0.5)};
  454. `;