index.tsx 13 KB

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