index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. {widget.description && (
  287. <Tooltip
  288. title={widget.description}
  289. containerDisplayMode="grid"
  290. showOnlyOnOverflow
  291. >
  292. <WidgetDescription>{widget.description}</WidgetDescription>
  293. </Tooltip>
  294. )}
  295. <DashboardsMEPConsumer>
  296. {({}) => {
  297. // TODO(Tele-Team): Re-enable this when we have a better way to determine if the data is transaction only
  298. // if (
  299. // isMetricsData === false &&
  300. // widget.widgetType === WidgetType.DISCOVER
  301. // ) {
  302. // return (
  303. // <Tooltip
  304. // containerDisplayMode="inline-flex"
  305. // title={t(
  306. // 'Based on your search criteria, the sampled events available may be limited and may not be representative of all events.'
  307. // )}
  308. // >
  309. // <IconWarning color="warningText" />
  310. // </Tooltip>
  311. // );
  312. // }
  313. return null;
  314. }}
  315. </DashboardsMEPConsumer>
  316. </WidgetHeaderDescription>
  317. {this.renderContextMenu()}
  318. </WidgetHeader>
  319. {hasSessionDuration && SESSION_DURATION_ALERT}
  320. {isWidgetInvalid ? (
  321. <Fragment>
  322. {renderErrorMessage?.('Widget query condition is invalid.')}
  323. <StyledErrorPanel>
  324. <IconWarning color="gray500" size="lg" />
  325. </StyledErrorPanel>
  326. </Fragment>
  327. ) : noLazyLoad ? (
  328. <WidgetCardChartContainer
  329. location={location}
  330. api={api}
  331. organization={organization}
  332. selection={selection}
  333. widget={widget}
  334. isMobile={isMobile}
  335. renderErrorMessage={renderErrorMessage}
  336. tableItemLimit={tableItemLimit}
  337. windowWidth={windowWidth}
  338. onDataFetched={this.setData}
  339. dashboardFilters={dashboardFilters}
  340. />
  341. ) : (
  342. <LazyLoad once resize height={200}>
  343. <WidgetCardChartContainer
  344. location={location}
  345. api={api}
  346. organization={organization}
  347. selection={selection}
  348. widget={widget}
  349. isMobile={isMobile}
  350. renderErrorMessage={renderErrorMessage}
  351. tableItemLimit={tableItemLimit}
  352. windowWidth={windowWidth}
  353. onDataFetched={this.setData}
  354. dashboardFilters={dashboardFilters}
  355. />
  356. </LazyLoad>
  357. )}
  358. {this.renderToolbar()}
  359. </WidgetCardPanel>
  360. </VisuallyCompleteWithData>
  361. {!organization.features.includes('performance-mep-bannerless-ui') &&
  362. (organization.features.includes('dashboards-mep') ||
  363. organization.features.includes('mep-rollout-flag')) && (
  364. <MEPConsumer>
  365. {metricSettingContext => {
  366. return (
  367. <DashboardsMEPConsumer>
  368. {({isMetricsData}) => {
  369. if (
  370. showStoredAlert &&
  371. isMetricsData === false &&
  372. widget.widgetType === WidgetType.DISCOVER &&
  373. metricSettingContext &&
  374. metricSettingContext.metricSettingState !==
  375. MEPState.TRANSACTIONS_ONLY
  376. ) {
  377. if (!widgetContainsErrorFields) {
  378. return (
  379. <StoredDataAlert showIcon>
  380. {tct(
  381. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  382. {
  383. indexedData: (
  384. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  385. ),
  386. }
  387. )}
  388. </StoredDataAlert>
  389. );
  390. }
  391. }
  392. return null;
  393. }}
  394. </DashboardsMEPConsumer>
  395. );
  396. }}
  397. </MEPConsumer>
  398. )}
  399. </React.Fragment>
  400. )}
  401. </ErrorBoundary>
  402. );
  403. }
  404. }
  405. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  406. const ErrorCard = styled(Placeholder)`
  407. display: flex;
  408. align-items: center;
  409. justify-content: center;
  410. background-color: ${p => p.theme.alert.error.backgroundLight};
  411. border: 1px solid ${p => p.theme.alert.error.border};
  412. color: ${p => p.theme.alert.error.textLight};
  413. border-radius: ${p => p.theme.borderRadius};
  414. margin-bottom: ${space(2)};
  415. `;
  416. export const WidgetCardPanel = styled(Panel, {
  417. shouldForwardProp: prop => prop !== 'isDragging',
  418. })<{
  419. isDragging: boolean;
  420. }>`
  421. margin: 0;
  422. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  423. /* If a panel overflows due to a long title stretch its grid sibling */
  424. height: 100%;
  425. min-height: 96px;
  426. display: flex;
  427. flex-direction: column;
  428. `;
  429. const ToolbarPanel = styled('div')`
  430. position: absolute;
  431. top: 0;
  432. left: 0;
  433. z-index: 2;
  434. width: 100%;
  435. height: 100%;
  436. display: flex;
  437. justify-content: flex-end;
  438. align-items: flex-start;
  439. background-color: ${p => p.theme.overlayBackgroundAlpha};
  440. border-radius: calc(${p => p.theme.panelBorderRadius} - 1px);
  441. `;
  442. const IconContainer = styled('div')`
  443. display: flex;
  444. margin: ${space(1)};
  445. touch-action: none;
  446. `;
  447. const GrabbableButton = styled(Button)`
  448. cursor: grab;
  449. `;
  450. const WidgetTitle = styled(HeaderTitle)`
  451. ${p => p.theme.overflowEllipsis};
  452. font-weight: normal;
  453. `;
  454. const WidgetHeader = styled('div')`
  455. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  456. min-height: 36px;
  457. width: 100%;
  458. display: flex;
  459. align-items: center;
  460. justify-content: space-between;
  461. `;
  462. const StoredDataAlert = styled(Alert)`
  463. margin-top: ${space(1)};
  464. margin-bottom: 0;
  465. `;
  466. const StyledErrorPanel = styled(ErrorPanel)`
  467. padding: ${space(2)};
  468. `;
  469. const WidgetHeaderDescription = styled('div')`
  470. display: flex;
  471. flex-direction: column;
  472. gap: ${space(0.5)};
  473. `;
  474. export const WidgetDescription = styled('small')`
  475. ${p => p.theme.overflowEllipsis}
  476. color: ${p => p.theme.gray300};
  477. `;