index.tsx 17 KB

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