dashboard.tsx 15 KB

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