index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 {hasDDMExperimentalFeature} 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 (
  249. hasDDMExperimentalFeature(organization) &&
  250. isSupportedDisplayType(widget.displayType)
  251. ) {
  252. return (
  253. <MetricWidgetCard
  254. index={this.props.index}
  255. isEditingWidget={this.props.isEditingWidget}
  256. isEditingDashboard={this.props.isEditingDashboard}
  257. onEdit={this.props.onEdit}
  258. onUpdate={this.props.onUpdate}
  259. onDelete={this.props.onDelete}
  260. onDuplicate={this.props.onDuplicate}
  261. router={this.props.router}
  262. location={this.props.location}
  263. organization={organization}
  264. selection={selection}
  265. widget={widget}
  266. />
  267. );
  268. }
  269. }
  270. return (
  271. <ErrorBoundary
  272. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  273. >
  274. {conditionalWrapWithDashboardsMEPProvider(
  275. <Fragment>
  276. <VisuallyCompleteWithData
  277. id="DashboardList-FirstWidgetCard"
  278. hasData={
  279. ((this.state.tableData?.length || this.state.seriesData?.length) ?? 0) > 0
  280. }
  281. disabled={Number(this.props.index) !== 0}
  282. >
  283. <WidgetCardPanel isDragging={false}>
  284. <WidgetHeaderWrapper>
  285. <WidgetHeaderDescription>
  286. <WidgetTitleRow>
  287. <Tooltip
  288. title={widget.title}
  289. containerDisplayMode="grid"
  290. showOnlyOnOverflow
  291. >
  292. <WidgetTitle>{widget.title}</WidgetTitle>
  293. </Tooltip>
  294. {widget.thresholds &&
  295. hasThresholdMaxValue(widget.thresholds) &&
  296. this.state.tableData &&
  297. organization.features.includes('dashboard-widget-indicators') &&
  298. getColoredWidgetIndicator(
  299. widget.thresholds,
  300. this.state.tableData
  301. )}
  302. <ExtractedMetricsTag queryKey={widget} />
  303. </WidgetTitleRow>
  304. {widget.description && (
  305. <Tooltip
  306. title={widget.description}
  307. containerDisplayMode="grid"
  308. showOnlyOnOverflow
  309. isHoverable
  310. >
  311. <WidgetDescription>{widget.description}</WidgetDescription>
  312. </Tooltip>
  313. )}
  314. </WidgetHeaderDescription>
  315. {this.renderContextMenu()}
  316. </WidgetHeaderWrapper>
  317. {hasSessionDuration && SESSION_DURATION_ALERT}
  318. {isWidgetInvalid ? (
  319. <Fragment>
  320. {renderErrorMessage?.('Widget query condition is invalid.')}
  321. <StyledErrorPanel>
  322. <IconWarning color="gray500" size="lg" />
  323. </StyledErrorPanel>
  324. </Fragment>
  325. ) : noLazyLoad ? (
  326. <WidgetCardChartContainer
  327. location={location}
  328. api={api}
  329. organization={organization}
  330. selection={selection}
  331. widget={widget}
  332. isMobile={isMobile}
  333. renderErrorMessage={renderErrorMessage}
  334. tableItemLimit={tableItemLimit}
  335. windowWidth={windowWidth}
  336. onDataFetched={this.setData}
  337. dashboardFilters={dashboardFilters}
  338. />
  339. ) : (
  340. <LazyLoad once resize height={200}>
  341. <WidgetCardChartContainer
  342. location={location}
  343. api={api}
  344. organization={organization}
  345. selection={selection}
  346. widget={widget}
  347. isMobile={isMobile}
  348. renderErrorMessage={renderErrorMessage}
  349. tableItemLimit={tableItemLimit}
  350. windowWidth={windowWidth}
  351. onDataFetched={this.setData}
  352. dashboardFilters={dashboardFilters}
  353. />
  354. </LazyLoad>
  355. )}
  356. {this.renderToolbar()}
  357. </WidgetCardPanel>
  358. </VisuallyCompleteWithData>
  359. {!organization.features.includes('performance-mep-bannerless-ui') && (
  360. <MEPConsumer>
  361. {metricSettingContext => {
  362. return (
  363. <DashboardsMEPConsumer>
  364. {({isMetricsData}) => {
  365. if (
  366. showStoredAlert &&
  367. isMetricsData === false &&
  368. widget.widgetType === WidgetType.DISCOVER &&
  369. metricSettingContext &&
  370. metricSettingContext.metricSettingState !==
  371. MEPState.TRANSACTIONS_ONLY
  372. ) {
  373. if (!widgetContainsErrorFields) {
  374. return (
  375. <StoredDataAlert showIcon>
  376. {tct(
  377. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  378. {
  379. indexedData: (
  380. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  381. ),
  382. }
  383. )}
  384. </StoredDataAlert>
  385. );
  386. }
  387. }
  388. return null;
  389. }}
  390. </DashboardsMEPConsumer>
  391. );
  392. }}
  393. </MEPConsumer>
  394. )}
  395. </Fragment>
  396. )}
  397. </ErrorBoundary>
  398. );
  399. }
  400. }
  401. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  402. const ErrorCard = styled(Placeholder)`
  403. display: flex;
  404. align-items: center;
  405. justify-content: center;
  406. background-color: ${p => p.theme.alert.error.backgroundLight};
  407. border: 1px solid ${p => p.theme.alert.error.border};
  408. color: ${p => p.theme.alert.error.textLight};
  409. border-radius: ${p => p.theme.borderRadius};
  410. margin-bottom: ${space(2)};
  411. `;
  412. export const WidgetCardPanel = styled(Panel, {
  413. shouldForwardProp: prop => prop !== 'isDragging',
  414. })<{
  415. isDragging: boolean;
  416. }>`
  417. margin: 0;
  418. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  419. /* If a panel overflows due to a long title stretch its grid sibling */
  420. height: 100%;
  421. min-height: 96px;
  422. display: flex;
  423. flex-direction: column;
  424. `;
  425. const StoredDataAlert = styled(Alert)`
  426. margin-top: ${space(1)};
  427. margin-bottom: 0;
  428. `;
  429. const StyledErrorPanel = styled(ErrorPanel)`
  430. padding: ${space(2)};
  431. `;
  432. export const WidgetTitleRow = styled('span')`
  433. display: flex;
  434. align-items: center;
  435. gap: ${space(0.75)};
  436. `;
  437. export const WidgetDescription = styled('small')`
  438. ${p => p.theme.overflowEllipsis}
  439. color: ${p => p.theme.gray300};
  440. `;
  441. const WidgetTitle = styled(HeaderTitle)`
  442. ${p => p.theme.overflowEllipsis};
  443. font-weight: normal;
  444. `;
  445. const WidgetHeaderWrapper = styled('div')`
  446. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  447. min-height: 36px;
  448. width: 100%;
  449. display: flex;
  450. align-items: center;
  451. justify-content: space-between;
  452. `;
  453. const WidgetHeaderDescription = styled('div')`
  454. display: flex;
  455. flex-direction: column;
  456. gap: ${space(0.5)};
  457. `;