index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 {DASHBOARD_CHART_GROUP} from 'sentry/views/dashboards/dashboard';
  41. import {MetricWidgetCard} from 'sentry/views/dashboards/widgetCard/metricWidgetCard';
  42. import {Toolbar} from 'sentry/views/dashboards/widgetCard/toolbar';
  43. import type {DashboardFilters, Widget} from '../types';
  44. import {DisplayType, WidgetType} from '../types';
  45. import {getColoredWidgetIndicator, hasThresholdMaxValue} from '../utils';
  46. import {DEFAULT_RESULTS_LIMIT} from '../widgetBuilder/utils';
  47. import {DashboardsMEPConsumer, DashboardsMEPProvider} from './dashboardsMEPContext';
  48. import WidgetCardChartContainer from './widgetCardChartContainer';
  49. import WidgetCardContextMenu from './widgetCardContextMenu';
  50. const SESSION_DURATION_INGESTION_STOP_DATE = new Date('2023-01-12');
  51. export const SESSION_DURATION_ALERT = (
  52. <PanelAlert type="warning">
  53. {t(
  54. 'session.duration is no longer being recorded as of %s. Data in this widget may be incomplete.',
  55. getFormattedDate(SESSION_DURATION_INGESTION_STOP_DATE, 'MMM D, YYYY')
  56. )}
  57. </PanelAlert>
  58. );
  59. type DraggableProps = Pick<ReturnType<typeof useSortable>, 'attributes' | 'listeners'>;
  60. type Props = WithRouterProps & {
  61. api: Client;
  62. isEditingDashboard: boolean;
  63. location: Location;
  64. organization: Organization;
  65. selection: PageFilters;
  66. widget: Widget;
  67. widgetLimitReached: boolean;
  68. dashboardFilters?: DashboardFilters;
  69. draggableProps?: DraggableProps;
  70. hideToolbar?: boolean;
  71. index?: string;
  72. isEditingWidget?: boolean;
  73. isMobile?: boolean;
  74. isPreview?: boolean;
  75. isWidgetInvalid?: boolean;
  76. noDashboardsMEPProvider?: boolean;
  77. noLazyLoad?: boolean;
  78. onDataFetched?: (results: TableDataWithTitle[]) => void;
  79. onDelete?: () => void;
  80. onDuplicate?: () => void;
  81. onEdit?: () => void;
  82. onUpdate?: (widget: Widget | null) => void;
  83. renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
  84. showContextMenu?: boolean;
  85. showStoredAlert?: boolean;
  86. tableItemLimit?: number;
  87. windowWidth?: number;
  88. };
  89. type State = {
  90. pageLinks?: string;
  91. seriesData?: Series[];
  92. seriesResultsType?: Record<string, AggregationOutputType>;
  93. tableData?: TableDataWithTitle[];
  94. totalIssuesCount?: string;
  95. };
  96. type SearchFilterKey = {key?: {value: string}};
  97. const ERROR_FIELDS = [
  98. 'error.handled',
  99. 'error.unhandled',
  100. 'error.mechanism',
  101. 'error.type',
  102. 'error.value',
  103. ];
  104. class WidgetCard extends Component<Props, State> {
  105. state: State = {};
  106. renderToolbar() {
  107. const {
  108. onEdit,
  109. onDelete,
  110. onDuplicate,
  111. draggableProps,
  112. hideToolbar,
  113. isEditingDashboard,
  114. isMobile,
  115. } = this.props;
  116. if (!isEditingDashboard) {
  117. return null;
  118. }
  119. return (
  120. <Toolbar
  121. onEdit={onEdit}
  122. onDelete={onDelete}
  123. onDuplicate={onDuplicate}
  124. draggableProps={draggableProps}
  125. hideToolbar={hideToolbar}
  126. isMobile={isMobile}
  127. />
  128. );
  129. }
  130. renderContextMenu() {
  131. const {
  132. widget,
  133. selection,
  134. organization,
  135. showContextMenu,
  136. isPreview,
  137. widgetLimitReached,
  138. onEdit,
  139. onDuplicate,
  140. onDelete,
  141. isEditingDashboard,
  142. router,
  143. location,
  144. index,
  145. } = this.props;
  146. const {seriesData, tableData, pageLinks, totalIssuesCount, seriesResultsType} =
  147. this.state;
  148. if (isEditingDashboard) {
  149. return null;
  150. }
  151. return (
  152. <WidgetCardContextMenu
  153. organization={organization}
  154. widget={widget}
  155. selection={selection}
  156. showContextMenu={showContextMenu}
  157. isPreview={isPreview}
  158. widgetLimitReached={widgetLimitReached}
  159. onDuplicate={onDuplicate}
  160. onEdit={onEdit}
  161. onDelete={onDelete}
  162. router={router}
  163. location={location}
  164. index={index}
  165. seriesData={seriesData}
  166. seriesResultsType={seriesResultsType}
  167. tableData={tableData}
  168. pageLinks={pageLinks}
  169. totalIssuesCount={totalIssuesCount}
  170. />
  171. );
  172. }
  173. setData = ({
  174. tableResults,
  175. timeseriesResults,
  176. totalIssuesCount,
  177. pageLinks,
  178. timeseriesResultsTypes,
  179. }: {
  180. pageLinks?: string;
  181. tableResults?: TableDataWithTitle[];
  182. timeseriesResults?: Series[];
  183. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  184. totalIssuesCount?: string;
  185. }) => {
  186. const {onDataFetched} = this.props;
  187. if (onDataFetched && tableResults) {
  188. onDataFetched(tableResults);
  189. }
  190. this.setState({
  191. seriesData: timeseriesResults,
  192. tableData: tableResults,
  193. totalIssuesCount,
  194. pageLinks,
  195. seriesResultsType: timeseriesResultsTypes,
  196. });
  197. };
  198. render() {
  199. const {
  200. api,
  201. organization,
  202. selection,
  203. widget,
  204. isMobile,
  205. renderErrorMessage,
  206. tableItemLimit,
  207. windowWidth,
  208. noLazyLoad,
  209. showStoredAlert,
  210. noDashboardsMEPProvider,
  211. dashboardFilters,
  212. isWidgetInvalid,
  213. location,
  214. } = this.props;
  215. if (widget.displayType === DisplayType.TOP_N) {
  216. const queries = widget.queries.map(query => ({
  217. ...query,
  218. // Use the last aggregate because that's where the y-axis is stored
  219. aggregates: query.aggregates.length
  220. ? [query.aggregates[query.aggregates.length - 1]]
  221. : [],
  222. }));
  223. widget.queries = queries;
  224. widget.limit = DEFAULT_RESULTS_LIMIT;
  225. }
  226. const hasSessionDuration = widget.queries.some(query =>
  227. query.aggregates.some(aggregate => aggregate.includes('session.duration'))
  228. );
  229. function conditionalWrapWithDashboardsMEPProvider(component: React.ReactNode) {
  230. if (noDashboardsMEPProvider) {
  231. return component;
  232. }
  233. return <DashboardsMEPProvider>{component}</DashboardsMEPProvider>;
  234. }
  235. const widgetContainsErrorFields = widget.queries.some(
  236. ({columns, aggregates, conditions}) =>
  237. ERROR_FIELDS.some(
  238. errorField =>
  239. columns.includes(errorField) ||
  240. aggregates.some(aggregate =>
  241. parseFunction(aggregate)?.arguments.includes(errorField)
  242. ) ||
  243. parseSearch(conditions)?.some(
  244. filter => (filter as SearchFilterKey).key?.value === errorField
  245. )
  246. )
  247. );
  248. if (widget.widgetType === WidgetType.METRICS) {
  249. if (hasDDMFeature(organization) && isSupportedDisplayType(widget.displayType)) {
  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. dashboardFilters={dashboardFilters}
  265. renderErrorMessage={renderErrorMessage}
  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. chartGroup={DASHBOARD_CHART_GROUP}
  339. />
  340. ) : (
  341. <LazyLoad once resize height={200}>
  342. <WidgetCardChartContainer
  343. location={location}
  344. api={api}
  345. organization={organization}
  346. selection={selection}
  347. widget={widget}
  348. isMobile={isMobile}
  349. renderErrorMessage={renderErrorMessage}
  350. tableItemLimit={tableItemLimit}
  351. windowWidth={windowWidth}
  352. onDataFetched={this.setData}
  353. dashboardFilters={dashboardFilters}
  354. chartGroup={DASHBOARD_CHART_GROUP}
  355. />
  356. </LazyLoad>
  357. )}
  358. {this.renderToolbar()}
  359. </WidgetCardPanel>
  360. </VisuallyCompleteWithData>
  361. {!organization.features.includes('performance-mep-bannerless-ui') && (
  362. <MEPConsumer>
  363. {metricSettingContext => {
  364. return (
  365. <DashboardsMEPConsumer>
  366. {({isMetricsData}) => {
  367. if (
  368. showStoredAlert &&
  369. isMetricsData === false &&
  370. widget.widgetType === WidgetType.DISCOVER &&
  371. metricSettingContext &&
  372. metricSettingContext.metricSettingState !==
  373. MEPState.TRANSACTIONS_ONLY
  374. ) {
  375. if (!widgetContainsErrorFields) {
  376. return (
  377. <StoredDataAlert showIcon>
  378. {tct(
  379. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  380. {
  381. indexedData: (
  382. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  383. ),
  384. }
  385. )}
  386. </StoredDataAlert>
  387. );
  388. }
  389. }
  390. return null;
  391. }}
  392. </DashboardsMEPConsumer>
  393. );
  394. }}
  395. </MEPConsumer>
  396. )}
  397. </Fragment>
  398. )}
  399. </ErrorBoundary>
  400. );
  401. }
  402. }
  403. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  404. const ErrorCard = styled(Placeholder)`
  405. display: flex;
  406. align-items: center;
  407. justify-content: center;
  408. background-color: ${p => p.theme.alert.error.backgroundLight};
  409. border: 1px solid ${p => p.theme.alert.error.border};
  410. color: ${p => p.theme.alert.error.textLight};
  411. border-radius: ${p => p.theme.borderRadius};
  412. margin-bottom: ${space(2)};
  413. `;
  414. export const WidgetCardPanel = styled(Panel, {
  415. shouldForwardProp: prop => prop !== 'isDragging',
  416. })<{
  417. isDragging: boolean;
  418. }>`
  419. margin: 0;
  420. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  421. /* If a panel overflows due to a long title stretch its grid sibling */
  422. height: 100%;
  423. min-height: 96px;
  424. display: flex;
  425. flex-direction: column;
  426. `;
  427. const StoredDataAlert = styled(Alert)`
  428. margin-top: ${space(1)};
  429. margin-bottom: 0;
  430. `;
  431. const StyledErrorPanel = styled(ErrorPanel)`
  432. padding: ${space(2)};
  433. `;
  434. export const WidgetTitleRow = styled('span')`
  435. display: flex;
  436. align-items: center;
  437. gap: ${space(0.75)};
  438. `;
  439. export const WidgetDescription = styled('small')`
  440. ${p => p.theme.overflowEllipsis}
  441. color: ${p => p.theme.gray300};
  442. `;
  443. const WidgetTitle = styled(HeaderTitle)`
  444. ${p => p.theme.overflowEllipsis};
  445. font-weight: normal;
  446. `;
  447. const WidgetHeaderWrapper = styled('div')`
  448. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  449. min-height: 36px;
  450. width: 100%;
  451. display: flex;
  452. align-items: center;
  453. justify-content: space-between;
  454. `;
  455. const WidgetHeaderDescription = styled('div')`
  456. display: flex;
  457. flex-direction: column;
  458. gap: ${space(0.5)};
  459. `;