index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. dashboardFilters={dashboardFilters}
  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. `;