index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 Tooltip from 'sentry/components/tooltip';
  19. import {IconCopy, IconDelete, IconEdit, IconGrabbable} 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 {statsPeriodToDays} from 'sentry/utils/dates';
  25. import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  26. import withApi from 'sentry/utils/withApi';
  27. import withOrganization from 'sentry/utils/withOrganization';
  28. import withPageFilters from 'sentry/utils/withPageFilters';
  29. import {DRAG_HANDLE_CLASS} from '../dashboard';
  30. import {DisplayType, Widget, WidgetType} from '../types';
  31. import {isCustomMeasurementWidget} from '../utils';
  32. import {DEFAULT_RESULTS_LIMIT} from '../widgetBuilder/utils';
  33. import {DashboardsMEPConsumer, DashboardsMEPProvider} from './dashboardsMEPContext';
  34. import WidgetCardChartContainer from './widgetCardChartContainer';
  35. import WidgetCardContextMenu from './widgetCardContextMenu';
  36. type DraggableProps = Pick<ReturnType<typeof useSortable>, 'attributes' | 'listeners'>;
  37. type Props = WithRouterProps & {
  38. api: Client;
  39. currentWidgetDragging: boolean;
  40. isEditing: boolean;
  41. isSorting: boolean;
  42. location: Location;
  43. organization: Organization;
  44. selection: PageFilters;
  45. widget: Widget;
  46. widgetLimitReached: boolean;
  47. draggableProps?: DraggableProps;
  48. hideToolbar?: boolean;
  49. index?: string;
  50. isMobile?: boolean;
  51. isPreview?: boolean;
  52. noDashboardsMEPProvider?: boolean;
  53. noLazyLoad?: boolean;
  54. onDelete?: () => void;
  55. onDuplicate?: () => void;
  56. onEdit?: () => void;
  57. renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
  58. showContextMenu?: boolean;
  59. showStoredAlert?: boolean;
  60. showWidgetViewerButton?: boolean;
  61. tableItemLimit?: number;
  62. windowWidth?: number;
  63. };
  64. type State = {
  65. pageLinks?: string;
  66. seriesData?: Series[];
  67. tableData?: TableDataWithTitle[];
  68. totalIssuesCount?: string;
  69. };
  70. const METRICS_BACKED_SESSIONS_START_DATE = new Date('2022-04-12');
  71. class WidgetCard extends Component<Props, State> {
  72. state: State = {};
  73. renderToolbar() {
  74. const {
  75. onEdit,
  76. onDelete,
  77. onDuplicate,
  78. draggableProps,
  79. hideToolbar,
  80. isEditing,
  81. isMobile,
  82. } = this.props;
  83. if (!isEditing) {
  84. return null;
  85. }
  86. return (
  87. <ToolbarPanel>
  88. <IconContainer style={{visibility: hideToolbar ? 'hidden' : 'visible'}}>
  89. {!isMobile && (
  90. <GrabbableButton
  91. size="xs"
  92. aria-label={t('Drag Widget')}
  93. icon={<IconGrabbable />}
  94. borderless
  95. className={DRAG_HANDLE_CLASS}
  96. {...draggableProps?.listeners}
  97. {...draggableProps?.attributes}
  98. />
  99. )}
  100. <Button
  101. data-test-id="widget-edit"
  102. aria-label={t('Edit Widget')}
  103. size="xs"
  104. borderless
  105. onClick={onEdit}
  106. icon={<IconEdit />}
  107. />
  108. <Button
  109. aria-label={t('Duplicate Widget')}
  110. size="xs"
  111. borderless
  112. onClick={onDuplicate}
  113. icon={<IconCopy />}
  114. />
  115. <Button
  116. data-test-id="widget-delete"
  117. aria-label={t('Delete Widget')}
  118. borderless
  119. size="xs"
  120. onClick={onDelete}
  121. icon={<IconDelete />}
  122. />
  123. </IconContainer>
  124. </ToolbarPanel>
  125. );
  126. }
  127. renderContextMenu() {
  128. const {
  129. widget,
  130. selection,
  131. organization,
  132. showContextMenu,
  133. isPreview,
  134. widgetLimitReached,
  135. onEdit,
  136. onDuplicate,
  137. onDelete,
  138. isEditing,
  139. showWidgetViewerButton,
  140. router,
  141. location,
  142. index,
  143. } = this.props;
  144. const {seriesData, tableData, pageLinks, totalIssuesCount} = this.state;
  145. if (isEditing) {
  146. return null;
  147. }
  148. return (
  149. <WidgetCardContextMenu
  150. organization={organization}
  151. widget={widget}
  152. selection={selection}
  153. showContextMenu={showContextMenu}
  154. isPreview={isPreview}
  155. widgetLimitReached={widgetLimitReached}
  156. onDuplicate={onDuplicate}
  157. onEdit={onEdit}
  158. onDelete={onDelete}
  159. showWidgetViewerButton={showWidgetViewerButton}
  160. router={router}
  161. location={location}
  162. index={index}
  163. seriesData={seriesData}
  164. tableData={tableData}
  165. pageLinks={pageLinks}
  166. totalIssuesCount={totalIssuesCount}
  167. />
  168. );
  169. }
  170. setData = ({
  171. tableResults,
  172. timeseriesResults,
  173. totalIssuesCount,
  174. pageLinks,
  175. }: {
  176. pageLinks?: string;
  177. tableResults?: TableDataWithTitle[];
  178. timeseriesResults?: Series[];
  179. totalIssuesCount?: string;
  180. }) => {
  181. this.setState({
  182. seriesData: timeseriesResults,
  183. tableData: tableResults,
  184. totalIssuesCount,
  185. pageLinks,
  186. });
  187. };
  188. render() {
  189. const {
  190. api,
  191. organization,
  192. selection,
  193. widget,
  194. isMobile,
  195. renderErrorMessage,
  196. tableItemLimit,
  197. windowWidth,
  198. noLazyLoad,
  199. showStoredAlert,
  200. noDashboardsMEPProvider,
  201. } = this.props;
  202. const {start, period} = selection.datetime;
  203. let showIncompleteDataAlert: boolean = false;
  204. if (widget.widgetType === WidgetType.RELEASE && showStoredAlert) {
  205. if (start) {
  206. let startDate: Date | undefined = undefined;
  207. if (typeof start === 'string') {
  208. startDate = new Date(start);
  209. } else {
  210. startDate = start;
  211. }
  212. showIncompleteDataAlert = startDate < METRICS_BACKED_SESSIONS_START_DATE;
  213. } else if (period) {
  214. const periodInDays = statsPeriodToDays(period);
  215. const current = new Date();
  216. const prior = new Date(new Date().setDate(current.getDate() - periodInDays));
  217. showIncompleteDataAlert = prior < METRICS_BACKED_SESSIONS_START_DATE;
  218. }
  219. }
  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. return (
  238. <ErrorBoundary
  239. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  240. >
  241. {conditionalWrapWithDashboardsMEPProvider(
  242. <React.Fragment>
  243. <WidgetCardPanel isDragging={false}>
  244. <WidgetHeader>
  245. <Tooltip
  246. title={widget.title}
  247. containerDisplayMode="grid"
  248. showOnlyOnOverflow
  249. >
  250. <WidgetTitle>{widget.title}</WidgetTitle>
  251. </Tooltip>
  252. {this.renderContextMenu()}
  253. </WidgetHeader>
  254. {noLazyLoad ? (
  255. <WidgetCardChartContainer
  256. api={api}
  257. organization={organization}
  258. selection={selection}
  259. widget={widget}
  260. isMobile={isMobile}
  261. renderErrorMessage={renderErrorMessage}
  262. tableItemLimit={tableItemLimit}
  263. windowWidth={windowWidth}
  264. onDataFetched={this.setData}
  265. />
  266. ) : (
  267. <LazyLoad once resize height={200}>
  268. <WidgetCardChartContainer
  269. api={api}
  270. organization={organization}
  271. selection={selection}
  272. widget={widget}
  273. isMobile={isMobile}
  274. renderErrorMessage={renderErrorMessage}
  275. tableItemLimit={tableItemLimit}
  276. windowWidth={windowWidth}
  277. onDataFetched={this.setData}
  278. />
  279. </LazyLoad>
  280. )}
  281. {this.renderToolbar()}
  282. </WidgetCardPanel>
  283. <Feature organization={organization} features={['dashboards-mep']}>
  284. <DashboardsMEPConsumer>
  285. {({isMetricsData}) => {
  286. if (
  287. showStoredAlert &&
  288. isMetricsData === false &&
  289. widget.widgetType === WidgetType.DISCOVER
  290. ) {
  291. if (isCustomMeasurementWidget(widget)) {
  292. return (
  293. <StoredDataAlert showIcon type="error">
  294. {tct(
  295. '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.',
  296. {
  297. customPerformanceMetrics: (
  298. <ExternalLink href="https://docs.sentry.io/" />
  299. ), // TODO(dashboards): Update the docs URL
  300. here: <ExternalLink href="https://docs.sentry.io/" />, // TODO(dashboards): Update the docs URL
  301. }
  302. )}
  303. </StoredDataAlert>
  304. );
  305. }
  306. return (
  307. <StoredDataAlert showIcon>
  308. {tct(
  309. "Your selection is only applicable to [storedData: stored event data]. We've automatically adjusted your results.",
  310. {
  311. storedData: <ExternalLink href="https://docs.sentry.io/" />, // TODO(dashboards): Update the docs URL
  312. }
  313. )}
  314. </StoredDataAlert>
  315. );
  316. }
  317. return null;
  318. }}
  319. </DashboardsMEPConsumer>
  320. </Feature>
  321. <Feature organization={organization} features={['dashboards-releases']}>
  322. {showIncompleteDataAlert && (
  323. <StoredDataAlert showIcon>
  324. {tct(
  325. 'Releases data is only available from [date]. Data may be incomplete as a result.',
  326. {
  327. date: (
  328. <DateTime date={METRICS_BACKED_SESSIONS_START_DATE} dateOnly />
  329. ),
  330. }
  331. )}
  332. </StoredDataAlert>
  333. )}
  334. </Feature>
  335. </React.Fragment>
  336. )}
  337. </ErrorBoundary>
  338. );
  339. }
  340. }
  341. export default withApi(withOrganization(withPageFilters(withRouter(WidgetCard))));
  342. const ErrorCard = styled(Placeholder)`
  343. display: flex;
  344. align-items: center;
  345. justify-content: center;
  346. background-color: ${p => p.theme.alert.error.backgroundLight};
  347. border: 1px solid ${p => p.theme.alert.error.border};
  348. color: ${p => p.theme.alert.error.textLight};
  349. border-radius: ${p => p.theme.borderRadius};
  350. margin-bottom: ${space(2)};
  351. `;
  352. export const WidgetCardPanel = styled(Panel, {
  353. shouldForwardProp: prop => prop !== 'isDragging',
  354. })<{
  355. isDragging: boolean;
  356. }>`
  357. margin: 0;
  358. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  359. /* If a panel overflows due to a long title stretch its grid sibling */
  360. height: 100%;
  361. min-height: 96px;
  362. display: flex;
  363. flex-direction: column;
  364. `;
  365. const ToolbarPanel = styled('div')`
  366. position: absolute;
  367. top: 0;
  368. left: 0;
  369. z-index: 2;
  370. width: 100%;
  371. height: 100%;
  372. display: flex;
  373. justify-content: flex-end;
  374. align-items: flex-start;
  375. background-color: ${p => p.theme.overlayBackgroundAlpha};
  376. border-radius: ${p => p.theme.borderRadius};
  377. `;
  378. const IconContainer = styled('div')`
  379. display: flex;
  380. margin: ${space(1)};
  381. touch-action: none;
  382. `;
  383. const GrabbableButton = styled(Button)`
  384. cursor: grab;
  385. `;
  386. const WidgetTitle = styled(HeaderTitle)`
  387. ${p => p.theme.overflowEllipsis};
  388. font-weight: normal;
  389. `;
  390. const WidgetHeader = styled('div')`
  391. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  392. min-height: 36px;
  393. width: 100%;
  394. display: flex;
  395. align-items: center;
  396. justify-content: space-between;
  397. `;
  398. const StoredDataAlert = styled(Alert)`
  399. margin-top: ${space(1)};
  400. margin-bottom: 0;
  401. `;