index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. isEditing: boolean;
  43. location: Location;
  44. organization: Organization;
  45. selection: PageFilters;
  46. widget: Widget;
  47. widgetLimitReached: boolean;
  48. dashboardFilters?: DashboardFilters;
  49. draggableProps?: DraggableProps;
  50. hideToolbar?: boolean;
  51. index?: string;
  52. isMobile?: boolean;
  53. isPreview?: boolean;
  54. isWidgetInvalid?: boolean;
  55. noDashboardsMEPProvider?: boolean;
  56. noLazyLoad?: boolean;
  57. onDelete?: () => void;
  58. onDuplicate?: () => void;
  59. onEdit?: () => void;
  60. renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
  61. showContextMenu?: boolean;
  62. showStoredAlert?: boolean;
  63. showWidgetViewerButton?: 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. showWidgetViewerButton,
  151. router,
  152. location,
  153. index,
  154. } = this.props;
  155. const {seriesData, tableData, pageLinks, totalIssuesCount, seriesResultsType} =
  156. this.state;
  157. if (isEditing) {
  158. return null;
  159. }
  160. return (
  161. <WidgetCardContextMenu
  162. organization={organization}
  163. widget={widget}
  164. selection={selection}
  165. showContextMenu={showContextMenu}
  166. isPreview={isPreview}
  167. widgetLimitReached={widgetLimitReached}
  168. onDuplicate={onDuplicate}
  169. onEdit={onEdit}
  170. onDelete={onDelete}
  171. showWidgetViewerButton={showWidgetViewerButton}
  172. router={router}
  173. location={location}
  174. index={index}
  175. seriesData={seriesData}
  176. seriesResultsType={seriesResultsType}
  177. tableData={tableData}
  178. pageLinks={pageLinks}
  179. totalIssuesCount={totalIssuesCount}
  180. />
  181. );
  182. }
  183. setData = ({
  184. tableResults,
  185. timeseriesResults,
  186. totalIssuesCount,
  187. pageLinks,
  188. timeseriesResultsTypes,
  189. }: {
  190. pageLinks?: string;
  191. tableResults?: TableDataWithTitle[];
  192. timeseriesResults?: Series[];
  193. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  194. totalIssuesCount?: string;
  195. }) => {
  196. this.setState({
  197. seriesData: timeseriesResults,
  198. tableData: tableResults,
  199. totalIssuesCount,
  200. pageLinks,
  201. seriesResultsType: timeseriesResultsTypes,
  202. });
  203. };
  204. render() {
  205. const {
  206. api,
  207. organization,
  208. selection,
  209. widget,
  210. isMobile,
  211. renderErrorMessage,
  212. tableItemLimit,
  213. windowWidth,
  214. noLazyLoad,
  215. showStoredAlert,
  216. noDashboardsMEPProvider,
  217. dashboardFilters,
  218. isWidgetInvalid,
  219. } = this.props;
  220. if (widget.displayType === DisplayType.TOP_N) {
  221. const queries = widget.queries.map(query => ({
  222. ...query,
  223. // Use the last aggregate because that's where the y-axis is stored
  224. aggregates: query.aggregates.length
  225. ? [query.aggregates[query.aggregates.length - 1]]
  226. : [],
  227. }));
  228. widget.queries = queries;
  229. widget.limit = DEFAULT_RESULTS_LIMIT;
  230. }
  231. function conditionalWrapWithDashboardsMEPProvider(component: React.ReactNode) {
  232. if (noDashboardsMEPProvider) {
  233. return component;
  234. }
  235. return <DashboardsMEPProvider>{component}</DashboardsMEPProvider>;
  236. }
  237. const widgetContainsErrorFields = widget.queries.some(
  238. ({columns, aggregates, conditions}) =>
  239. ERROR_FIELDS.some(
  240. errorField =>
  241. columns.includes(errorField) ||
  242. aggregates.some(aggregate =>
  243. parseFunction(aggregate)?.arguments.includes(errorField)
  244. ) ||
  245. parseSearch(conditions)?.some(
  246. filter => (filter as SearchFilterKey).key?.value === errorField
  247. )
  248. )
  249. );
  250. return (
  251. <ErrorBoundary
  252. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  253. >
  254. {conditionalWrapWithDashboardsMEPProvider(
  255. <React.Fragment>
  256. <WidgetCardPanel isDragging={false}>
  257. <WidgetHeader>
  258. <Tooltip
  259. title={widget.title}
  260. containerDisplayMode="grid"
  261. showOnlyOnOverflow
  262. >
  263. <WidgetTitle>{widget.title}</WidgetTitle>
  264. </Tooltip>
  265. {this.renderContextMenu()}
  266. </WidgetHeader>
  267. {isWidgetInvalid ? (
  268. <Fragment>
  269. {renderErrorMessage?.('Widget query condition is invalid.')}
  270. <StyledErrorPanel>
  271. <IconWarning color="gray500" size="lg" />
  272. </StyledErrorPanel>
  273. </Fragment>
  274. ) : noLazyLoad ? (
  275. <WidgetCardChartContainer
  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. api={api}
  291. organization={organization}
  292. selection={selection}
  293. widget={widget}
  294. isMobile={isMobile}
  295. renderErrorMessage={renderErrorMessage}
  296. tableItemLimit={tableItemLimit}
  297. windowWidth={windowWidth}
  298. onDataFetched={this.setData}
  299. dashboardFilters={dashboardFilters}
  300. />
  301. </LazyLoad>
  302. )}
  303. {this.renderToolbar()}
  304. </WidgetCardPanel>
  305. {!organization.features.includes('performance-mep-bannerless-ui') &&
  306. (organization.features.includes('dashboards-mep') ||
  307. organization.features.includes('mep-rollout-flag')) && (
  308. <MEPConsumer>
  309. {metricSettingContext => {
  310. return (
  311. <DashboardsMEPConsumer>
  312. {({isMetricsData}) => {
  313. if (
  314. showStoredAlert &&
  315. isMetricsData === false &&
  316. widget.widgetType === WidgetType.DISCOVER &&
  317. metricSettingContext &&
  318. metricSettingContext.metricSettingState !==
  319. MEPState.transactionsOnly
  320. ) {
  321. if (!widgetContainsErrorFields) {
  322. return (
  323. <StoredDataAlert showIcon>
  324. {tct(
  325. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  326. {
  327. indexedData: (
  328. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  329. ),
  330. }
  331. )}
  332. </StoredDataAlert>
  333. );
  334. }
  335. }
  336. return null;
  337. }}
  338. </DashboardsMEPConsumer>
  339. );
  340. }}
  341. </MEPConsumer>
  342. )}
  343. </React.Fragment>
  344. )}
  345. </ErrorBoundary>
  346. );
  347. }
  348. }
  349. export default withApi(withOrganization(withPageFilters(withRouter(WidgetCard))));
  350. const ErrorCard = styled(Placeholder)`
  351. display: flex;
  352. align-items: center;
  353. justify-content: center;
  354. background-color: ${p => p.theme.alert.error.backgroundLight};
  355. border: 1px solid ${p => p.theme.alert.error.border};
  356. color: ${p => p.theme.alert.error.textLight};
  357. border-radius: ${p => p.theme.borderRadius};
  358. margin-bottom: ${space(2)};
  359. `;
  360. export const WidgetCardPanel = styled(Panel, {
  361. shouldForwardProp: prop => prop !== 'isDragging',
  362. })<{
  363. isDragging: boolean;
  364. }>`
  365. margin: 0;
  366. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  367. /* If a panel overflows due to a long title stretch its grid sibling */
  368. height: 100%;
  369. min-height: 96px;
  370. display: flex;
  371. flex-direction: column;
  372. `;
  373. const ToolbarPanel = styled('div')`
  374. position: absolute;
  375. top: 0;
  376. left: 0;
  377. z-index: 2;
  378. width: 100%;
  379. height: 100%;
  380. display: flex;
  381. justify-content: flex-end;
  382. align-items: flex-start;
  383. background-color: ${p => p.theme.overlayBackgroundAlpha};
  384. border-radius: ${p => p.theme.borderRadius};
  385. `;
  386. const IconContainer = styled('div')`
  387. display: flex;
  388. margin: ${space(1)};
  389. touch-action: none;
  390. `;
  391. const GrabbableButton = styled(Button)`
  392. cursor: grab;
  393. `;
  394. const WidgetTitle = styled(HeaderTitle)`
  395. ${p => p.theme.overflowEllipsis};
  396. font-weight: normal;
  397. `;
  398. const WidgetHeader = styled('div')`
  399. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  400. min-height: 36px;
  401. width: 100%;
  402. display: flex;
  403. align-items: center;
  404. justify-content: space-between;
  405. `;
  406. const StoredDataAlert = styled(Alert)`
  407. margin-top: ${space(1)};
  408. margin-bottom: 0;
  409. `;
  410. const StyledErrorPanel = styled(ErrorPanel)`
  411. padding: ${space(2)};
  412. `;