index.tsx 17 KB

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