dashboard.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. import 'react-grid-layout/css/styles.css';
  2. import 'react-resizable/css/styles.css';
  3. import {Component} from 'react';
  4. import type {Layouts} from 'react-grid-layout';
  5. import {Responsive, WidthProvider} from 'react-grid-layout';
  6. import {forceCheck} from 'react-lazyload';
  7. import styled from '@emotion/styled';
  8. import type {Location} from 'history';
  9. import cloneDeep from 'lodash/cloneDeep';
  10. import debounce from 'lodash/debounce';
  11. import isEqual from 'lodash/isEqual';
  12. import {validateWidget} from 'sentry/actionCreators/dashboards';
  13. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  14. import {fetchOrgMembers} from 'sentry/actionCreators/members';
  15. import {loadOrganizationTags} from 'sentry/actionCreators/tags';
  16. import type {Client} from 'sentry/api';
  17. import {Button} from 'sentry/components/button';
  18. import {IconResize} from 'sentry/icons';
  19. import {t} from 'sentry/locale';
  20. import GroupStore from 'sentry/stores/groupStore';
  21. import {space} from 'sentry/styles/space';
  22. import type {PageFilters} from 'sentry/types/core';
  23. import type {InjectedRouter} from 'sentry/types/legacyReactRouter';
  24. import type {Organization} from 'sentry/types/organization';
  25. import {trackAnalytics} from 'sentry/utils/analytics';
  26. import {DatasetSource} from 'sentry/utils/discover/types';
  27. import {hasCustomMetrics} from 'sentry/utils/metrics/features';
  28. import theme from 'sentry/utils/theme';
  29. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  30. import withApi from 'sentry/utils/withApi';
  31. import withPageFilters from 'sentry/utils/withPageFilters';
  32. import {DataSet} from 'sentry/views/dashboards/widgetBuilder/utils';
  33. import AddWidget, {ADD_WIDGET_BUTTON_DRAG_ID} from './addWidget';
  34. import type {Position} from './layoutUtils';
  35. import {
  36. assignDefaultLayout,
  37. assignTempId,
  38. calculateColumnDepths,
  39. constructGridItemKey,
  40. DEFAULT_WIDGET_WIDTH,
  41. enforceWidgetHeightValues,
  42. generateWidgetId,
  43. generateWidgetsAfterCompaction,
  44. getDashboardLayout,
  45. getDefaultWidgetHeight,
  46. getMobileLayout,
  47. getNextAvailablePosition,
  48. isValidLayout,
  49. METRIC_WIDGET_MIN_SIZE,
  50. pickDefinedStoreKeys,
  51. } from './layoutUtils';
  52. import SortableWidget from './sortableWidget';
  53. import type {DashboardDetails, Widget} from './types';
  54. import {DashboardWidgetSource, WidgetType} from './types';
  55. import {connectDashboardCharts, getDashboardFiltersFromURL} from './utils';
  56. import type WidgetLegendSelectionState from './widgetLegendSelectionState';
  57. export const DRAG_HANDLE_CLASS = 'widget-drag';
  58. const DRAG_RESIZE_CLASS = 'widget-resize';
  59. const DESKTOP = 'desktop';
  60. const MOBILE = 'mobile';
  61. export const NUM_DESKTOP_COLS = 6;
  62. const NUM_MOBILE_COLS = 2;
  63. const ROW_HEIGHT = 120;
  64. const WIDGET_MARGINS: [number, number] = [16, 16];
  65. const BOTTOM_MOBILE_VIEW_POSITION = {
  66. x: 0,
  67. y: Number.MAX_SAFE_INTEGER,
  68. };
  69. const MOBILE_BREAKPOINT = parseInt(theme.breakpoints.small, 10);
  70. const BREAKPOINTS = {[MOBILE]: 0, [DESKTOP]: MOBILE_BREAKPOINT};
  71. const COLUMNS = {[MOBILE]: NUM_MOBILE_COLS, [DESKTOP]: NUM_DESKTOP_COLS};
  72. export const DASHBOARD_CHART_GROUP = 'dashboard-group';
  73. type Props = {
  74. api: Client;
  75. dashboard: DashboardDetails;
  76. handleAddCustomWidget: (widget: Widget) => void;
  77. handleUpdateWidgetList: (widgets: Widget[]) => void;
  78. isEditingDashboard: boolean;
  79. location: Location;
  80. /**
  81. * Fired when widgets are added/removed/sorted.
  82. */
  83. onUpdate: (widgets: Widget[]) => void;
  84. organization: Organization;
  85. router: InjectedRouter;
  86. selection: PageFilters;
  87. widgetLegendState: WidgetLegendSelectionState;
  88. widgetLimitReached: boolean;
  89. handleAddMetricWidget?: (layout?: Widget['layout']) => void;
  90. handleChangeSplitDataset?: (widget: Widget, index: number) => void;
  91. isPreview?: boolean;
  92. newWidget?: Widget;
  93. onSetNewWidget?: () => void;
  94. paramDashboardId?: string;
  95. paramTemplateId?: string;
  96. };
  97. type State = {
  98. isMobile: boolean;
  99. layouts: Layouts;
  100. windowWidth: number;
  101. };
  102. class Dashboard extends Component<Props, State> {
  103. constructor(props: Props) {
  104. super(props);
  105. const {dashboard} = props;
  106. const desktopLayout = getDashboardLayout(dashboard.widgets);
  107. this.state = {
  108. isMobile: false,
  109. layouts: {
  110. [DESKTOP]: desktopLayout,
  111. [MOBILE]: getMobileLayout(desktopLayout, dashboard.widgets),
  112. },
  113. windowWidth: window.innerWidth,
  114. };
  115. }
  116. static getDerivedStateFromProps(props, state) {
  117. if (state.isMobile) {
  118. // Don't need to recalculate any layout state from props in the mobile view
  119. // because we want to force different positions (i.e. new widgets added
  120. // at the bottom)
  121. return null;
  122. }
  123. // If the user clicks "Cancel" and the dashboard resets,
  124. // recalculate the layout to revert to the unmodified state
  125. const dashboardLayout = getDashboardLayout(props.dashboard.widgets);
  126. if (
  127. !isEqual(
  128. dashboardLayout.map(pickDefinedStoreKeys),
  129. state.layouts[DESKTOP].map(pickDefinedStoreKeys)
  130. )
  131. ) {
  132. return {
  133. ...state,
  134. layouts: {
  135. [DESKTOP]: dashboardLayout,
  136. [MOBILE]: getMobileLayout(dashboardLayout, props.dashboard.widgets),
  137. },
  138. };
  139. }
  140. return null;
  141. }
  142. componentDidMount() {
  143. const {newWidget} = this.props;
  144. window.addEventListener('resize', this.debouncedHandleResize);
  145. // Always load organization tags on dashboards
  146. this.fetchTags();
  147. if (newWidget) {
  148. this.addNewWidget();
  149. }
  150. // Get member list data for issue widgets
  151. this.fetchMemberList();
  152. connectDashboardCharts(DASHBOARD_CHART_GROUP);
  153. }
  154. componentDidUpdate(prevProps: Props) {
  155. const {selection, newWidget} = this.props;
  156. if (newWidget && newWidget !== prevProps.newWidget) {
  157. this.addNewWidget();
  158. }
  159. if (!isEqual(prevProps.selection.projects, selection.projects)) {
  160. this.fetchMemberList();
  161. }
  162. }
  163. componentWillUnmount() {
  164. window.removeEventListener('resize', this.debouncedHandleResize);
  165. window.clearTimeout(this.forceCheckTimeout);
  166. GroupStore.reset();
  167. }
  168. forceCheckTimeout: number | undefined = undefined;
  169. debouncedHandleResize = debounce(() => {
  170. this.setState({
  171. windowWidth: window.innerWidth,
  172. });
  173. }, 250);
  174. fetchMemberList() {
  175. const {api, selection} = this.props;
  176. // Stores MemberList in MemberListStore for use in modals and sets state for use is child components
  177. fetchOrgMembers(
  178. api,
  179. this.props.organization.slug,
  180. selection.projects?.map(projectId => String(projectId))
  181. );
  182. }
  183. async addNewWidget() {
  184. const {api, organization, newWidget, handleAddCustomWidget, onSetNewWidget} =
  185. this.props;
  186. if (newWidget) {
  187. try {
  188. await validateWidget(api, organization.slug, newWidget);
  189. handleAddCustomWidget(newWidget);
  190. onSetNewWidget?.();
  191. } catch (error) {
  192. // Don't do anything, widget isn't valid
  193. addErrorMessage(error);
  194. }
  195. }
  196. }
  197. fetchTags() {
  198. const {api, organization, selection} = this.props;
  199. loadOrganizationTags(api, organization.slug, selection);
  200. }
  201. handleStartAdd = (dataset?: DataSet) => {
  202. const {organization, router, location, paramDashboardId, handleAddMetricWidget} =
  203. this.props;
  204. if (dataset === DataSet.METRICS) {
  205. handleAddMetricWidget?.({...this.addWidgetLayout, ...METRIC_WIDGET_MIN_SIZE});
  206. return;
  207. }
  208. if (paramDashboardId) {
  209. router.push(
  210. normalizeUrl({
  211. pathname: `/organizations/${organization.slug}/dashboard/${paramDashboardId}/widget/new/`,
  212. query: {
  213. ...location.query,
  214. source: DashboardWidgetSource.DASHBOARDS,
  215. dataset,
  216. },
  217. })
  218. );
  219. return;
  220. }
  221. router.push(
  222. normalizeUrl({
  223. pathname: `/organizations/${organization.slug}/dashboards/new/widget/new/`,
  224. query: {
  225. ...location.query,
  226. source: DashboardWidgetSource.DASHBOARDS,
  227. dataset,
  228. },
  229. })
  230. );
  231. return;
  232. };
  233. handleUpdateComplete = (prevWidget: Widget) => (nextWidget: Widget) => {
  234. const {isEditingDashboard, onUpdate, handleUpdateWidgetList} = this.props;
  235. let nextList = [...this.props.dashboard.widgets];
  236. const updateIndex = nextList.indexOf(prevWidget);
  237. const nextWidgetData = {
  238. ...nextWidget,
  239. tempId: prevWidget.tempId,
  240. };
  241. // Only modify and re-compact if the default height has changed
  242. if (
  243. getDefaultWidgetHeight(prevWidget.displayType) !==
  244. getDefaultWidgetHeight(nextWidget.displayType)
  245. ) {
  246. nextList[updateIndex] = enforceWidgetHeightValues(nextWidgetData);
  247. nextList = generateWidgetsAfterCompaction(nextList);
  248. } else {
  249. nextList[updateIndex] = nextWidgetData;
  250. }
  251. onUpdate(nextList);
  252. if (!isEditingDashboard) {
  253. handleUpdateWidgetList(nextList);
  254. }
  255. };
  256. handleDeleteWidget = (widgetToDelete: Widget) => () => {
  257. const {
  258. organization,
  259. dashboard,
  260. onUpdate,
  261. isEditingDashboard,
  262. handleUpdateWidgetList,
  263. } = this.props;
  264. trackAnalytics('dashboards_views.widget.delete', {
  265. organization,
  266. widget_type: widgetToDelete.displayType,
  267. });
  268. let nextList = dashboard.widgets.filter(widget => widget !== widgetToDelete);
  269. nextList = generateWidgetsAfterCompaction(nextList);
  270. onUpdate(nextList);
  271. if (!isEditingDashboard) {
  272. handleUpdateWidgetList(nextList);
  273. }
  274. };
  275. handleDuplicateWidget = (widget: Widget, index: number) => () => {
  276. const {
  277. organization,
  278. dashboard,
  279. onUpdate,
  280. isEditingDashboard,
  281. handleUpdateWidgetList,
  282. } = this.props;
  283. trackAnalytics('dashboards_views.widget.duplicate', {
  284. organization,
  285. widget_type: widget.displayType,
  286. });
  287. const widgetCopy = cloneDeep(
  288. assignTempId({...widget, id: undefined, tempId: undefined})
  289. );
  290. let nextList = [...dashboard.widgets];
  291. nextList.splice(index, 0, widgetCopy);
  292. nextList = generateWidgetsAfterCompaction(nextList);
  293. onUpdate(nextList);
  294. if (!isEditingDashboard) {
  295. handleUpdateWidgetList(nextList);
  296. }
  297. };
  298. handleChangeSplitDataset = (widget: Widget, index: number) => {
  299. const {dashboard, onUpdate, isEditingDashboard, handleUpdateWidgetList} = this.props;
  300. const widgetCopy = cloneDeep({
  301. ...widget,
  302. id: undefined,
  303. });
  304. const nextList = [...dashboard.widgets];
  305. const nextWidgetData = {
  306. ...widgetCopy,
  307. widgetType: WidgetType.TRANSACTIONS,
  308. datasetSource: DatasetSource.USER,
  309. id: widget.id,
  310. };
  311. nextList[index] = nextWidgetData;
  312. onUpdate(nextList);
  313. if (!isEditingDashboard) {
  314. handleUpdateWidgetList(nextList);
  315. }
  316. };
  317. handleEditWidget = (index: number) => () => {
  318. const {organization, router, location, paramDashboardId} = this.props;
  319. const widget = this.props.dashboard.widgets[index];
  320. trackAnalytics('dashboards_views.widget.edit', {
  321. organization,
  322. widget_type: widget.displayType,
  323. });
  324. if (widget.widgetType === WidgetType.METRICS) {
  325. return;
  326. }
  327. if (paramDashboardId) {
  328. router.push(
  329. normalizeUrl({
  330. pathname: `/organizations/${organization.slug}/dashboard/${paramDashboardId}/widget/${index}/edit/`,
  331. query: {
  332. ...location.query,
  333. source: DashboardWidgetSource.DASHBOARDS,
  334. },
  335. })
  336. );
  337. return;
  338. }
  339. router.push(
  340. normalizeUrl({
  341. pathname: `/organizations/${organization.slug}/dashboards/new/widget/${index}/edit/`,
  342. query: {
  343. ...location.query,
  344. source: DashboardWidgetSource.DASHBOARDS,
  345. },
  346. })
  347. );
  348. return;
  349. };
  350. getWidgetIds() {
  351. return [
  352. ...this.props.dashboard.widgets.map((widget, index): string => {
  353. return generateWidgetId(widget, index);
  354. }),
  355. ADD_WIDGET_BUTTON_DRAG_ID,
  356. ];
  357. }
  358. renderWidget(widget: Widget, index: number) {
  359. const {isMobile, windowWidth} = this.state;
  360. const {isEditingDashboard, widgetLimitReached, isPreview, dashboard, location} =
  361. this.props;
  362. const widgetProps = {
  363. widget,
  364. widgetLegendState: this.props.widgetLegendState,
  365. isEditingDashboard,
  366. widgetLimitReached,
  367. onDelete: this.handleDeleteWidget(widget),
  368. onEdit: this.handleEditWidget(index),
  369. onDuplicate: this.handleDuplicateWidget(widget, index),
  370. onSetTransactionsDataset: () => this.handleChangeSplitDataset(widget, index),
  371. isPreview,
  372. dashboardFilters: getDashboardFiltersFromURL(location) ?? dashboard.filters,
  373. };
  374. const key = constructGridItemKey(widget);
  375. return (
  376. <div key={key} data-grid={widget.layout}>
  377. <SortableWidget
  378. {...widgetProps}
  379. isMobile={isMobile}
  380. windowWidth={windowWidth}
  381. index={String(index)}
  382. />
  383. </div>
  384. );
  385. }
  386. handleLayoutChange = (_, allLayouts: Layouts) => {
  387. const {isMobile} = this.state;
  388. const {dashboard, onUpdate} = this.props;
  389. const isNotAddButton = ({i}) => i !== ADD_WIDGET_BUTTON_DRAG_ID;
  390. const newLayouts = {
  391. [DESKTOP]: allLayouts[DESKTOP].filter(isNotAddButton),
  392. [MOBILE]: allLayouts[MOBILE].filter(isNotAddButton),
  393. };
  394. // Generate a new list of widgets where the layouts are associated
  395. let columnDepths = calculateColumnDepths(newLayouts[DESKTOP]);
  396. const newWidgets = dashboard.widgets.map(widget => {
  397. const gridKey = constructGridItemKey(widget);
  398. let matchingLayout = newLayouts[DESKTOP].find(({i}) => i === gridKey);
  399. if (!matchingLayout) {
  400. const height = getDefaultWidgetHeight(widget.displayType);
  401. const defaultWidgetParams = {
  402. w: DEFAULT_WIDGET_WIDTH,
  403. h: height,
  404. minH: height,
  405. i: gridKey,
  406. };
  407. // Calculate the available position
  408. const [nextPosition, nextColumnDepths] = getNextAvailablePosition(
  409. columnDepths,
  410. height
  411. );
  412. columnDepths = nextColumnDepths;
  413. // Set the position for the desktop layout
  414. matchingLayout = {
  415. ...defaultWidgetParams,
  416. ...nextPosition,
  417. };
  418. if (isMobile) {
  419. // This is a new widget and it's on the mobile page so we keep it at the bottom
  420. const mobileLayout = newLayouts[MOBILE].filter(({i}) => i !== gridKey);
  421. mobileLayout.push({
  422. ...defaultWidgetParams,
  423. ...BOTTOM_MOBILE_VIEW_POSITION,
  424. });
  425. newLayouts[MOBILE] = mobileLayout;
  426. }
  427. }
  428. return {
  429. ...widget,
  430. layout: pickDefinedStoreKeys(matchingLayout),
  431. };
  432. });
  433. this.setState({
  434. layouts: newLayouts,
  435. });
  436. onUpdate(newWidgets);
  437. // Force check lazyLoad elements that might have shifted into view after (re)moving an upper widget
  438. // Unfortunately need to use window.setTimeout since React Grid Layout animates widgets into view when layout changes
  439. // RGL doesn't provide a handler for post animation layout change
  440. window.clearTimeout(this.forceCheckTimeout);
  441. this.forceCheckTimeout = window.setTimeout(forceCheck, 400);
  442. };
  443. handleBreakpointChange = (newBreakpoint: string) => {
  444. const {layouts} = this.state;
  445. const {
  446. dashboard: {widgets},
  447. } = this.props;
  448. if (newBreakpoint === MOBILE) {
  449. this.setState({
  450. isMobile: true,
  451. layouts: {
  452. ...layouts,
  453. [MOBILE]: getMobileLayout(layouts[DESKTOP], widgets),
  454. },
  455. });
  456. return;
  457. }
  458. this.setState({isMobile: false});
  459. };
  460. get addWidgetLayout() {
  461. const {isMobile, layouts} = this.state;
  462. let position: Position = BOTTOM_MOBILE_VIEW_POSITION;
  463. if (!isMobile) {
  464. const columnDepths = calculateColumnDepths(layouts[DESKTOP]);
  465. const [nextPosition] = getNextAvailablePosition(columnDepths, 1);
  466. position = nextPosition;
  467. }
  468. return {
  469. ...position,
  470. w: DEFAULT_WIDGET_WIDTH,
  471. h: 1,
  472. isResizable: false,
  473. };
  474. }
  475. render() {
  476. const {layouts, isMobile} = this.state;
  477. const {isEditingDashboard, dashboard, widgetLimitReached, organization, isPreview} =
  478. this.props;
  479. const {widgets} = dashboard;
  480. const columnDepths = calculateColumnDepths(layouts[DESKTOP]);
  481. const widgetsWithLayout = assignDefaultLayout(widgets, columnDepths);
  482. const canModifyLayout = !isMobile && isEditingDashboard;
  483. const displayInlineAddWidget =
  484. hasCustomMetrics(organization) &&
  485. isValidLayout({...this.addWidgetLayout, i: ADD_WIDGET_BUTTON_DRAG_ID});
  486. return (
  487. <GridLayout
  488. breakpoints={BREAKPOINTS}
  489. cols={COLUMNS}
  490. rowHeight={ROW_HEIGHT}
  491. margin={WIDGET_MARGINS}
  492. draggableHandle={`.${DRAG_HANDLE_CLASS}`}
  493. draggableCancel={`.${DRAG_RESIZE_CLASS}`}
  494. layouts={layouts}
  495. onLayoutChange={this.handleLayoutChange}
  496. onBreakpointChange={this.handleBreakpointChange}
  497. isDraggable={canModifyLayout}
  498. isResizable={canModifyLayout}
  499. resizeHandle={
  500. <ResizeHandle
  501. aria-label={t('Resize Widget')}
  502. data-test-id="custom-resize-handle"
  503. className={DRAG_RESIZE_CLASS}
  504. size="xs"
  505. borderless
  506. icon={<IconResize />}
  507. />
  508. }
  509. useCSSTransforms={false}
  510. isBounded
  511. >
  512. {widgetsWithLayout.map((widget, index) => this.renderWidget(widget, index))}
  513. {(isEditingDashboard || displayInlineAddWidget) &&
  514. !widgetLimitReached &&
  515. !isPreview && (
  516. <AddWidgetWrapper
  517. key={ADD_WIDGET_BUTTON_DRAG_ID}
  518. data-grid={this.addWidgetLayout}
  519. >
  520. <AddWidget onAddWidget={this.handleStartAdd} />
  521. </AddWidgetWrapper>
  522. )}
  523. </GridLayout>
  524. );
  525. }
  526. }
  527. export default withApi(withPageFilters(Dashboard));
  528. // A widget being dragged has a z-index of 3
  529. // Allow the Add Widget tile to show above widgets when moved
  530. const AddWidgetWrapper = styled('div')`
  531. z-index: 5;
  532. background-color: ${p => p.theme.background};
  533. `;
  534. const GridLayout = styled(WidthProvider(Responsive))`
  535. margin: -${space(2)};
  536. .react-grid-item.react-grid-placeholder {
  537. background: ${p => p.theme.purple200};
  538. border-radius: ${p => p.theme.borderRadius};
  539. }
  540. `;
  541. const ResizeHandle = styled(Button)`
  542. position: absolute;
  543. z-index: 2;
  544. bottom: ${space(0.5)};
  545. right: ${space(0.5)};
  546. color: ${p => p.theme.subText};
  547. cursor: nwse-resize;
  548. .react-resizable-hide & {
  549. display: none;
  550. }
  551. `;