index.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 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 {getColoredWidgetIndicator, hasThresholdMaxValue} from '../utils';
  40. import {DEFAULT_RESULTS_LIMIT} from '../widgetBuilder/utils';
  41. import {DashboardsMEPConsumer, DashboardsMEPProvider} from './dashboardsMEPContext';
  42. import WidgetCardChartContainer from './widgetCardChartContainer';
  43. import WidgetCardContextMenu from './widgetCardContextMenu';
  44. const SESSION_DURATION_INGESTION_STOP_DATE = new Date('2023-01-12');
  45. export const SESSION_DURATION_ALERT = (
  46. <PanelAlert type="warning">
  47. {t(
  48. 'session.duration is no longer being recorded as of %s. Data in this widget may be incomplete.',
  49. getFormattedDate(SESSION_DURATION_INGESTION_STOP_DATE, 'MMM D, YYYY')
  50. )}
  51. </PanelAlert>
  52. );
  53. type DraggableProps = Pick<ReturnType<typeof useSortable>, 'attributes' | 'listeners'>;
  54. type Props = WithRouterProps & {
  55. api: Client;
  56. isEditing: boolean;
  57. location: Location;
  58. organization: Organization;
  59. selection: PageFilters;
  60. widget: Widget;
  61. widgetLimitReached: boolean;
  62. dashboardFilters?: DashboardFilters;
  63. draggableProps?: DraggableProps;
  64. hideToolbar?: boolean;
  65. index?: string;
  66. isMobile?: boolean;
  67. isPreview?: boolean;
  68. isWidgetInvalid?: boolean;
  69. noDashboardsMEPProvider?: boolean;
  70. noLazyLoad?: boolean;
  71. onDataFetched?: (results: TableDataWithTitle[]) => void;
  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. const {onDataFetched} = this.props;
  209. if (onDataFetched && tableResults) {
  210. onDataFetched(tableResults);
  211. }
  212. this.setState({
  213. seriesData: timeseriesResults,
  214. tableData: tableResults,
  215. totalIssuesCount,
  216. pageLinks,
  217. seriesResultsType: timeseriesResultsTypes,
  218. });
  219. };
  220. render() {
  221. const {
  222. api,
  223. organization,
  224. selection,
  225. widget,
  226. isMobile,
  227. renderErrorMessage,
  228. tableItemLimit,
  229. windowWidth,
  230. noLazyLoad,
  231. showStoredAlert,
  232. noDashboardsMEPProvider,
  233. dashboardFilters,
  234. isWidgetInvalid,
  235. location,
  236. } = this.props;
  237. if (widget.displayType === DisplayType.TOP_N) {
  238. const queries = widget.queries.map(query => ({
  239. ...query,
  240. // Use the last aggregate because that's where the y-axis is stored
  241. aggregates: query.aggregates.length
  242. ? [query.aggregates[query.aggregates.length - 1]]
  243. : [],
  244. }));
  245. widget.queries = queries;
  246. widget.limit = DEFAULT_RESULTS_LIMIT;
  247. }
  248. const hasSessionDuration = widget.queries.some(query =>
  249. query.aggregates.some(aggregate => aggregate.includes('session.duration'))
  250. );
  251. function conditionalWrapWithDashboardsMEPProvider(component: React.ReactNode) {
  252. if (noDashboardsMEPProvider) {
  253. return component;
  254. }
  255. return <DashboardsMEPProvider>{component}</DashboardsMEPProvider>;
  256. }
  257. const widgetContainsErrorFields = widget.queries.some(
  258. ({columns, aggregates, conditions}) =>
  259. ERROR_FIELDS.some(
  260. errorField =>
  261. columns.includes(errorField) ||
  262. aggregates.some(
  263. aggregate => parseFunction(aggregate)?.arguments.includes(errorField)
  264. ) ||
  265. parseSearch(conditions)?.some(
  266. filter => (filter as SearchFilterKey).key?.value === errorField
  267. )
  268. )
  269. );
  270. return (
  271. <ErrorBoundary
  272. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  273. >
  274. {conditionalWrapWithDashboardsMEPProvider(
  275. <Fragment>
  276. <VisuallyCompleteWithData
  277. id="DashboardList-FirstWidgetCard"
  278. hasData={
  279. ((this.state.tableData?.length || this.state.seriesData?.length) ?? 0) > 0
  280. }
  281. disabled={Number(this.props.index) !== 0}
  282. >
  283. <WidgetCardPanel isDragging={false}>
  284. <WidgetHeader>
  285. <WidgetHeaderDescription>
  286. <WidgetTitleRow>
  287. <Tooltip
  288. title={widget.title}
  289. containerDisplayMode="grid"
  290. showOnlyOnOverflow
  291. >
  292. <WidgetTitle>{widget.title}</WidgetTitle>
  293. </Tooltip>
  294. {widget.thresholds &&
  295. hasThresholdMaxValue(widget.thresholds) &&
  296. this.state.tableData &&
  297. organization.features.includes('dashboard-widget-indicators') &&
  298. getColoredWidgetIndicator(
  299. widget.thresholds,
  300. this.state.tableData
  301. )}
  302. </WidgetTitleRow>
  303. {widget.description && (
  304. <Tooltip
  305. title={widget.description}
  306. containerDisplayMode="grid"
  307. showOnlyOnOverflow
  308. >
  309. <WidgetDescription>{widget.description}</WidgetDescription>
  310. </Tooltip>
  311. )}
  312. <DashboardsMEPConsumer>
  313. {({}) => {
  314. // TODO(Tele-Team): Re-enable this when we have a better way to determine if the data is transaction only
  315. // if (
  316. // isMetricsData === false &&
  317. // widget.widgetType === WidgetType.DISCOVER
  318. // ) {
  319. // return (
  320. // <Tooltip
  321. // containerDisplayMode="inline-flex"
  322. // title={t(
  323. // 'Based on your search criteria, the sampled events available may be limited and may not be representative of all events.'
  324. // )}
  325. // >
  326. // <IconWarning color="warningText" />
  327. // </Tooltip>
  328. // );
  329. // }
  330. return null;
  331. }}
  332. </DashboardsMEPConsumer>
  333. </WidgetHeaderDescription>
  334. {this.renderContextMenu()}
  335. </WidgetHeader>
  336. {hasSessionDuration && SESSION_DURATION_ALERT}
  337. {isWidgetInvalid ? (
  338. <Fragment>
  339. {renderErrorMessage?.('Widget query condition is invalid.')}
  340. <StyledErrorPanel>
  341. <IconWarning color="gray500" size="lg" />
  342. </StyledErrorPanel>
  343. </Fragment>
  344. ) : noLazyLoad ? (
  345. <WidgetCardChartContainer
  346. location={location}
  347. api={api}
  348. organization={organization}
  349. selection={selection}
  350. widget={widget}
  351. isMobile={isMobile}
  352. renderErrorMessage={renderErrorMessage}
  353. tableItemLimit={tableItemLimit}
  354. windowWidth={windowWidth}
  355. onDataFetched={this.setData}
  356. dashboardFilters={dashboardFilters}
  357. />
  358. ) : (
  359. <LazyLoad once resize height={200}>
  360. <WidgetCardChartContainer
  361. location={location}
  362. api={api}
  363. organization={organization}
  364. selection={selection}
  365. widget={widget}
  366. isMobile={isMobile}
  367. renderErrorMessage={renderErrorMessage}
  368. tableItemLimit={tableItemLimit}
  369. windowWidth={windowWidth}
  370. onDataFetched={this.setData}
  371. dashboardFilters={dashboardFilters}
  372. />
  373. </LazyLoad>
  374. )}
  375. {this.renderToolbar()}
  376. </WidgetCardPanel>
  377. </VisuallyCompleteWithData>
  378. {!organization.features.includes('performance-mep-bannerless-ui') && (
  379. <MEPConsumer>
  380. {metricSettingContext => {
  381. return (
  382. <DashboardsMEPConsumer>
  383. {({isMetricsData}) => {
  384. if (
  385. showStoredAlert &&
  386. isMetricsData === false &&
  387. widget.widgetType === WidgetType.DISCOVER &&
  388. metricSettingContext &&
  389. metricSettingContext.metricSettingState !==
  390. MEPState.TRANSACTIONS_ONLY
  391. ) {
  392. if (!widgetContainsErrorFields) {
  393. return (
  394. <StoredDataAlert showIcon>
  395. {tct(
  396. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  397. {
  398. indexedData: (
  399. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  400. ),
  401. }
  402. )}
  403. </StoredDataAlert>
  404. );
  405. }
  406. }
  407. return null;
  408. }}
  409. </DashboardsMEPConsumer>
  410. );
  411. }}
  412. </MEPConsumer>
  413. )}
  414. </Fragment>
  415. )}
  416. </ErrorBoundary>
  417. );
  418. }
  419. }
  420. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  421. const ErrorCard = styled(Placeholder)`
  422. display: flex;
  423. align-items: center;
  424. justify-content: center;
  425. background-color: ${p => p.theme.alert.error.backgroundLight};
  426. border: 1px solid ${p => p.theme.alert.error.border};
  427. color: ${p => p.theme.alert.error.textLight};
  428. border-radius: ${p => p.theme.borderRadius};
  429. margin-bottom: ${space(2)};
  430. `;
  431. export const WidgetCardPanel = styled(Panel, {
  432. shouldForwardProp: prop => prop !== 'isDragging',
  433. })<{
  434. isDragging: boolean;
  435. }>`
  436. margin: 0;
  437. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  438. /* If a panel overflows due to a long title stretch its grid sibling */
  439. height: 100%;
  440. min-height: 96px;
  441. display: flex;
  442. flex-direction: column;
  443. `;
  444. const ToolbarPanel = styled('div')`
  445. position: absolute;
  446. top: 0;
  447. left: 0;
  448. z-index: 2;
  449. width: 100%;
  450. height: 100%;
  451. display: flex;
  452. justify-content: flex-end;
  453. align-items: flex-start;
  454. background-color: ${p => p.theme.overlayBackgroundAlpha};
  455. border-radius: calc(${p => p.theme.panelBorderRadius} - 1px);
  456. `;
  457. const IconContainer = styled('div')`
  458. display: flex;
  459. margin: ${space(1)};
  460. touch-action: none;
  461. `;
  462. const GrabbableButton = styled(Button)`
  463. cursor: grab;
  464. `;
  465. const WidgetTitle = styled(HeaderTitle)`
  466. ${p => p.theme.overflowEllipsis};
  467. font-weight: normal;
  468. `;
  469. const WidgetHeader = styled('div')`
  470. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  471. min-height: 36px;
  472. width: 100%;
  473. display: flex;
  474. align-items: center;
  475. justify-content: space-between;
  476. `;
  477. const StoredDataAlert = styled(Alert)`
  478. margin-top: ${space(1)};
  479. margin-bottom: 0;
  480. `;
  481. const StyledErrorPanel = styled(ErrorPanel)`
  482. padding: ${space(2)};
  483. `;
  484. const WidgetHeaderDescription = styled('div')`
  485. display: flex;
  486. flex-direction: column;
  487. gap: ${space(0.5)};
  488. `;
  489. const WidgetTitleRow = styled('span')`
  490. display: flex;
  491. align-items: center;
  492. gap: ${space(0.75)};
  493. `;
  494. export const WidgetDescription = styled('small')`
  495. ${p => p.theme.overflowEllipsis}
  496. color: ${p => p.theme.gray300};
  497. `;