index.tsx 16 KB

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