dashboard.tsx 15 KB

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