index.tsx 16 KB

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