index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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 DateTime from 'sentry/components/dateTime';
  14. import ErrorBoundary from 'sentry/components/errorBoundary';
  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 {statsPeriodToDays} from 'sentry/utils/dates';
  26. import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  27. import {parseFunction} from 'sentry/utils/discover/fields';
  28. import withApi from 'sentry/utils/withApi';
  29. import withOrganization from 'sentry/utils/withOrganization';
  30. import withPageFilters from 'sentry/utils/withPageFilters';
  31. import {DRAG_HANDLE_CLASS} from '../dashboard';
  32. import {DashboardFilters, DisplayType, Widget, WidgetType} from '../types';
  33. import {isCustomMeasurementWidget} from '../utils';
  34. import {DEFAULT_RESULTS_LIMIT} from '../widgetBuilder/utils';
  35. import {DashboardsMEPConsumer, DashboardsMEPProvider} from './dashboardsMEPContext';
  36. import WidgetCardChartContainer from './widgetCardChartContainer';
  37. import WidgetCardContextMenu from './widgetCardContextMenu';
  38. type DraggableProps = Pick<ReturnType<typeof useSortable>, 'attributes' | 'listeners'>;
  39. type Props = WithRouterProps & {
  40. api: Client;
  41. currentWidgetDragging: boolean;
  42. isEditing: boolean;
  43. isSorting: 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. 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. tableData?: TableDataWithTitle[];
  71. totalIssuesCount?: string;
  72. };
  73. type SearchFilterKey = {key?: {value: string}};
  74. const METRICS_BACKED_SESSIONS_START_DATE = new Date('2022-04-12');
  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} = 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. tableData={tableData}
  176. pageLinks={pageLinks}
  177. totalIssuesCount={totalIssuesCount}
  178. />
  179. );
  180. }
  181. setData = ({
  182. tableResults,
  183. timeseriesResults,
  184. totalIssuesCount,
  185. pageLinks,
  186. }: {
  187. pageLinks?: string;
  188. tableResults?: TableDataWithTitle[];
  189. timeseriesResults?: Series[];
  190. totalIssuesCount?: string;
  191. }) => {
  192. this.setState({
  193. seriesData: timeseriesResults,
  194. tableData: tableResults,
  195. totalIssuesCount,
  196. pageLinks,
  197. });
  198. };
  199. render() {
  200. const {
  201. api,
  202. organization,
  203. selection,
  204. widget,
  205. isMobile,
  206. renderErrorMessage,
  207. tableItemLimit,
  208. windowWidth,
  209. noLazyLoad,
  210. showStoredAlert,
  211. noDashboardsMEPProvider,
  212. dashboardFilters,
  213. } = this.props;
  214. const {start, period} = selection.datetime;
  215. let showIncompleteDataAlert: boolean = false;
  216. if (widget.widgetType === WidgetType.RELEASE && showStoredAlert) {
  217. if (start) {
  218. let startDate: Date | undefined = undefined;
  219. if (typeof start === 'string') {
  220. startDate = new Date(start);
  221. } else {
  222. startDate = start;
  223. }
  224. showIncompleteDataAlert = startDate < METRICS_BACKED_SESSIONS_START_DATE;
  225. } else if (period) {
  226. const periodInDays = statsPeriodToDays(period);
  227. const current = new Date();
  228. const prior = new Date(new Date().setDate(current.getDate() - periodInDays));
  229. showIncompleteDataAlert = prior < METRICS_BACKED_SESSIONS_START_DATE;
  230. }
  231. }
  232. if (widget.displayType === DisplayType.TOP_N) {
  233. const queries = widget.queries.map(query => ({
  234. ...query,
  235. // Use the last aggregate because that's where the y-axis is stored
  236. aggregates: query.aggregates.length
  237. ? [query.aggregates[query.aggregates.length - 1]]
  238. : [],
  239. }));
  240. widget.queries = queries;
  241. widget.limit = DEFAULT_RESULTS_LIMIT;
  242. }
  243. function conditionalWrapWithDashboardsMEPProvider(component: React.ReactNode) {
  244. if (noDashboardsMEPProvider) {
  245. return component;
  246. }
  247. return <DashboardsMEPProvider>{component}</DashboardsMEPProvider>;
  248. }
  249. const widgetContainsErrorFields = widget.queries.some(
  250. ({columns, aggregates, conditions}) =>
  251. ERROR_FIELDS.some(
  252. errorField =>
  253. columns.includes(errorField) ||
  254. aggregates.some(aggregate =>
  255. parseFunction(aggregate)?.arguments.includes(errorField)
  256. ) ||
  257. parseSearch(conditions)?.some(
  258. filter => (filter as SearchFilterKey).key?.value === errorField
  259. )
  260. )
  261. );
  262. return (
  263. <ErrorBoundary
  264. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  265. >
  266. {conditionalWrapWithDashboardsMEPProvider(
  267. <React.Fragment>
  268. <WidgetCardPanel isDragging={false}>
  269. <WidgetHeader>
  270. <Tooltip
  271. title={widget.title}
  272. containerDisplayMode="grid"
  273. showOnlyOnOverflow
  274. >
  275. <WidgetTitle>{widget.title}</WidgetTitle>
  276. </Tooltip>
  277. {this.renderContextMenu()}
  278. </WidgetHeader>
  279. {noLazyLoad ? (
  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. ) : (
  293. <LazyLoad once resize height={200}>
  294. <WidgetCardChartContainer
  295. api={api}
  296. organization={organization}
  297. selection={selection}
  298. widget={widget}
  299. isMobile={isMobile}
  300. renderErrorMessage={renderErrorMessage}
  301. tableItemLimit={tableItemLimit}
  302. windowWidth={windowWidth}
  303. onDataFetched={this.setData}
  304. dashboardFilters={dashboardFilters}
  305. />
  306. </LazyLoad>
  307. )}
  308. {this.renderToolbar()}
  309. </WidgetCardPanel>
  310. <Feature organization={organization} features={['dashboards-mep']}>
  311. <DashboardsMEPConsumer>
  312. {({isMetricsData}) => {
  313. if (
  314. showStoredAlert &&
  315. isMetricsData === false &&
  316. widget.widgetType === WidgetType.DISCOVER
  317. ) {
  318. if (isCustomMeasurementWidget(widget)) {
  319. return (
  320. <StoredDataAlert showIcon type="error">
  321. {tct(
  322. '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.',
  323. {
  324. customPerformanceMetrics: (
  325. <ExternalLink href="https://docs.sentry.io/" />
  326. ), // TODO(dashboards): Update the docs URL
  327. here: <ExternalLink href="https://docs.sentry.io/" />, // TODO(dashboards): Update the docs URL
  328. }
  329. )}
  330. </StoredDataAlert>
  331. );
  332. }
  333. if (!widgetContainsErrorFields) {
  334. return (
  335. <StoredDataAlert showIcon>
  336. {tct(
  337. "Your selection is only applicable to [storedData: stored event data]. We've automatically adjusted your results.",
  338. {
  339. storedData: <ExternalLink href="https://docs.sentry.io/" />, // TODO(dashboards): Update the docs URL
  340. }
  341. )}
  342. </StoredDataAlert>
  343. );
  344. }
  345. }
  346. return null;
  347. }}
  348. </DashboardsMEPConsumer>
  349. </Feature>
  350. <Feature organization={organization} features={['dashboards-releases']}>
  351. {showIncompleteDataAlert && (
  352. <StoredDataAlert showIcon>
  353. {tct(
  354. 'Releases data is only available from [date]. Data may be incomplete as a result.',
  355. {
  356. date: (
  357. <DateTime date={METRICS_BACKED_SESSIONS_START_DATE} dateOnly />
  358. ),
  359. }
  360. )}
  361. </StoredDataAlert>
  362. )}
  363. </Feature>
  364. </React.Fragment>
  365. )}
  366. </ErrorBoundary>
  367. );
  368. }
  369. }
  370. export default withApi(withOrganization(withPageFilters(withRouter(WidgetCard))));
  371. const ErrorCard = styled(Placeholder)`
  372. display: flex;
  373. align-items: center;
  374. justify-content: center;
  375. background-color: ${p => p.theme.alert.error.backgroundLight};
  376. border: 1px solid ${p => p.theme.alert.error.border};
  377. color: ${p => p.theme.alert.error.textLight};
  378. border-radius: ${p => p.theme.borderRadius};
  379. margin-bottom: ${space(2)};
  380. `;
  381. export const WidgetCardPanel = styled(Panel, {
  382. shouldForwardProp: prop => prop !== 'isDragging',
  383. })<{
  384. isDragging: boolean;
  385. }>`
  386. margin: 0;
  387. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  388. /* If a panel overflows due to a long title stretch its grid sibling */
  389. height: 100%;
  390. min-height: 96px;
  391. display: flex;
  392. flex-direction: column;
  393. `;
  394. const ToolbarPanel = styled('div')`
  395. position: absolute;
  396. top: 0;
  397. left: 0;
  398. z-index: 2;
  399. width: 100%;
  400. height: 100%;
  401. display: flex;
  402. justify-content: flex-end;
  403. align-items: flex-start;
  404. background-color: ${p => p.theme.overlayBackgroundAlpha};
  405. border-radius: ${p => p.theme.borderRadius};
  406. `;
  407. const IconContainer = styled('div')`
  408. display: flex;
  409. margin: ${space(1)};
  410. touch-action: none;
  411. `;
  412. const GrabbableButton = styled(Button)`
  413. cursor: grab;
  414. `;
  415. const WidgetTitle = styled(HeaderTitle)`
  416. ${p => p.theme.overflowEllipsis};
  417. font-weight: normal;
  418. `;
  419. const WidgetHeader = styled('div')`
  420. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  421. min-height: 36px;
  422. width: 100%;
  423. display: flex;
  424. align-items: center;
  425. justify-content: space-between;
  426. `;
  427. const StoredDataAlert = styled(Alert)`
  428. margin-top: ${space(1)};
  429. margin-bottom: 0;
  430. `;