index.tsx 16 KB

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