index.tsx 13 KB

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