index.tsx 17 KB

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