index.tsx 17 KB

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