index.tsx 15 KB

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