index.tsx 13 KB

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