dashboard.tsx 17 KB

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