dashboard.tsx 16 KB

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