dashboard.tsx 16 KB

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