index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. <Tooltip
  271. title={widget.title}
  272. containerDisplayMode="grid"
  273. showOnlyOnOverflow
  274. >
  275. <WidgetTitle>{widget.title}</WidgetTitle>
  276. </Tooltip>
  277. {this.renderContextMenu()}
  278. </WidgetHeader>
  279. {hasSessionDuration && SESSION_DURATION_ALERT}
  280. {isWidgetInvalid ? (
  281. <Fragment>
  282. {renderErrorMessage?.('Widget query condition is invalid.')}
  283. <StyledErrorPanel>
  284. <IconWarning color="gray500" size="lg" />
  285. </StyledErrorPanel>
  286. </Fragment>
  287. ) : noLazyLoad ? (
  288. <WidgetCardChartContainer
  289. location={location}
  290. api={api}
  291. organization={organization}
  292. selection={selection}
  293. widget={widget}
  294. isMobile={isMobile}
  295. renderErrorMessage={renderErrorMessage}
  296. tableItemLimit={tableItemLimit}
  297. windowWidth={windowWidth}
  298. onDataFetched={this.setData}
  299. dashboardFilters={dashboardFilters}
  300. />
  301. ) : (
  302. <LazyLoad once resize height={200}>
  303. <WidgetCardChartContainer
  304. location={location}
  305. api={api}
  306. organization={organization}
  307. selection={selection}
  308. widget={widget}
  309. isMobile={isMobile}
  310. renderErrorMessage={renderErrorMessage}
  311. tableItemLimit={tableItemLimit}
  312. windowWidth={windowWidth}
  313. onDataFetched={this.setData}
  314. dashboardFilters={dashboardFilters}
  315. />
  316. </LazyLoad>
  317. )}
  318. {this.renderToolbar()}
  319. </WidgetCardPanel>
  320. {!organization.features.includes('performance-mep-bannerless-ui') &&
  321. (organization.features.includes('dashboards-mep') ||
  322. organization.features.includes('mep-rollout-flag')) && (
  323. <MEPConsumer>
  324. {metricSettingContext => {
  325. return (
  326. <DashboardsMEPConsumer>
  327. {({isMetricsData}) => {
  328. if (
  329. showStoredAlert &&
  330. isMetricsData === false &&
  331. widget.widgetType === WidgetType.DISCOVER &&
  332. metricSettingContext &&
  333. metricSettingContext.metricSettingState !==
  334. MEPState.transactionsOnly
  335. ) {
  336. if (!widgetContainsErrorFields) {
  337. return (
  338. <StoredDataAlert showIcon>
  339. {tct(
  340. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  341. {
  342. indexedData: (
  343. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  344. ),
  345. }
  346. )}
  347. </StoredDataAlert>
  348. );
  349. }
  350. }
  351. return null;
  352. }}
  353. </DashboardsMEPConsumer>
  354. );
  355. }}
  356. </MEPConsumer>
  357. )}
  358. </React.Fragment>
  359. )}
  360. </ErrorBoundary>
  361. );
  362. }
  363. }
  364. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  365. const ErrorCard = styled(Placeholder)`
  366. display: flex;
  367. align-items: center;
  368. justify-content: center;
  369. background-color: ${p => p.theme.alert.error.backgroundLight};
  370. border: 1px solid ${p => p.theme.alert.error.border};
  371. color: ${p => p.theme.alert.error.textLight};
  372. border-radius: ${p => p.theme.borderRadius};
  373. margin-bottom: ${space(2)};
  374. `;
  375. export const WidgetCardPanel = styled(Panel, {
  376. shouldForwardProp: prop => prop !== 'isDragging',
  377. })<{
  378. isDragging: boolean;
  379. }>`
  380. margin: 0;
  381. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  382. /* If a panel overflows due to a long title stretch its grid sibling */
  383. height: 100%;
  384. min-height: 96px;
  385. display: flex;
  386. flex-direction: column;
  387. `;
  388. const ToolbarPanel = styled('div')`
  389. position: absolute;
  390. top: 0;
  391. left: 0;
  392. z-index: 2;
  393. width: 100%;
  394. height: 100%;
  395. display: flex;
  396. justify-content: flex-end;
  397. align-items: flex-start;
  398. background-color: ${p => p.theme.overlayBackgroundAlpha};
  399. border-radius: calc(${p => p.theme.panelBorderRadius} - 1px);
  400. `;
  401. const IconContainer = styled('div')`
  402. display: flex;
  403. margin: ${space(1)};
  404. touch-action: none;
  405. `;
  406. const GrabbableButton = styled(Button)`
  407. cursor: grab;
  408. `;
  409. const WidgetTitle = styled(HeaderTitle)`
  410. ${p => p.theme.overflowEllipsis};
  411. font-weight: normal;
  412. `;
  413. const WidgetHeader = styled('div')`
  414. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  415. min-height: 36px;
  416. width: 100%;
  417. display: flex;
  418. align-items: center;
  419. justify-content: space-between;
  420. `;
  421. const StoredDataAlert = styled(Alert)`
  422. margin-top: ${space(1)};
  423. margin-bottom: 0;
  424. `;
  425. const StyledErrorPanel = styled(ErrorPanel)`
  426. padding: ${space(2)};
  427. `;