dashboard.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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} = this.props;
  296. const widgetProps = {
  297. widget,
  298. isEditingDashboard,
  299. widgetLimitReached,
  300. onDelete: this.handleDeleteWidget(widget),
  301. onEdit: this.handleEditWidget(index),
  302. onDuplicate: this.handleDuplicateWidget(widget, index),
  303. isPreview,
  304. dashboardFilters: getDashboardFiltersFromURL(location) ?? dashboard.filters,
  305. };
  306. const key = constructGridItemKey(widget);
  307. return (
  308. <div key={key} data-grid={widget.layout}>
  309. <SortableWidget
  310. {...widgetProps}
  311. isMobile={isMobile}
  312. windowWidth={windowWidth}
  313. index={String(index)}
  314. />
  315. </div>
  316. );
  317. }
  318. handleLayoutChange = (_, allLayouts: Layouts) => {
  319. const {isMobile} = this.state;
  320. const {dashboard, onUpdate} = this.props;
  321. const isNotAddButton = ({i}) => i !== ADD_WIDGET_BUTTON_DRAG_ID;
  322. const newLayouts = {
  323. [DESKTOP]: allLayouts[DESKTOP].filter(isNotAddButton),
  324. [MOBILE]: allLayouts[MOBILE].filter(isNotAddButton),
  325. };
  326. // Generate a new list of widgets where the layouts are associated
  327. let columnDepths = calculateColumnDepths(newLayouts[DESKTOP]);
  328. const newWidgets = dashboard.widgets.map(widget => {
  329. const gridKey = constructGridItemKey(widget);
  330. let matchingLayout = newLayouts[DESKTOP].find(({i}) => i === gridKey);
  331. if (!matchingLayout) {
  332. const height = getDefaultWidgetHeight(widget.displayType);
  333. const defaultWidgetParams = {
  334. w: DEFAULT_WIDGET_WIDTH,
  335. h: height,
  336. minH: height,
  337. i: gridKey,
  338. };
  339. // Calculate the available position
  340. const [nextPosition, nextColumnDepths] = getNextAvailablePosition(
  341. columnDepths,
  342. height
  343. );
  344. columnDepths = nextColumnDepths;
  345. // Set the position for the desktop layout
  346. matchingLayout = {
  347. ...defaultWidgetParams,
  348. ...nextPosition,
  349. };
  350. if (isMobile) {
  351. // This is a new widget and it's on the mobile page so we keep it at the bottom
  352. const mobileLayout = newLayouts[MOBILE].filter(({i}) => i !== gridKey);
  353. mobileLayout.push({
  354. ...defaultWidgetParams,
  355. ...BOTTOM_MOBILE_VIEW_POSITION,
  356. });
  357. newLayouts[MOBILE] = mobileLayout;
  358. }
  359. }
  360. return {
  361. ...widget,
  362. layout: pickDefinedStoreKeys(matchingLayout),
  363. };
  364. });
  365. this.setState({
  366. layouts: newLayouts,
  367. });
  368. onUpdate(newWidgets);
  369. // Force check lazyLoad elements that might have shifted into view after (re)moving an upper widget
  370. // Unfortunately need to use window.setTimeout since React Grid Layout animates widgets into view when layout changes
  371. // RGL doesn't provide a handler for post animation layout change
  372. window.clearTimeout(this.forceCheckTimeout);
  373. this.forceCheckTimeout = window.setTimeout(forceCheck, 400);
  374. };
  375. handleBreakpointChange = (newBreakpoint: string) => {
  376. const {layouts} = this.state;
  377. const {
  378. dashboard: {widgets},
  379. } = this.props;
  380. if (newBreakpoint === MOBILE) {
  381. this.setState({
  382. isMobile: true,
  383. layouts: {
  384. ...layouts,
  385. [MOBILE]: getMobileLayout(layouts[DESKTOP], widgets),
  386. },
  387. });
  388. return;
  389. }
  390. this.setState({isMobile: false});
  391. };
  392. get addWidgetLayout() {
  393. const {isMobile, layouts} = this.state;
  394. let position: Position = BOTTOM_MOBILE_VIEW_POSITION;
  395. if (!isMobile) {
  396. const columnDepths = calculateColumnDepths(layouts[DESKTOP]);
  397. const [nextPosition] = getNextAvailablePosition(columnDepths, 1);
  398. position = nextPosition;
  399. }
  400. return {
  401. ...position,
  402. w: DEFAULT_WIDGET_WIDTH,
  403. h: 1,
  404. isResizable: false,
  405. };
  406. }
  407. render() {
  408. const {layouts, isMobile} = this.state;
  409. const {isEditingDashboard, dashboard, widgetLimitReached, organization} = this.props;
  410. let {widgets} = dashboard;
  411. // Filter out any issue/release widgets if the user does not have the feature flag
  412. widgets = widgets.filter(({widgetType}) => {
  413. if (widgetType === WidgetType.RELEASE) {
  414. return organization.features.includes('dashboards-rh-widget');
  415. }
  416. return true;
  417. });
  418. const columnDepths = calculateColumnDepths(layouts[DESKTOP]);
  419. const widgetsWithLayout = assignDefaultLayout(widgets, columnDepths);
  420. const canModifyLayout = !isMobile && isEditingDashboard;
  421. return (
  422. <GridLayout
  423. breakpoints={BREAKPOINTS}
  424. cols={COLUMNS}
  425. rowHeight={ROW_HEIGHT}
  426. margin={WIDGET_MARGINS}
  427. draggableHandle={`.${DRAG_HANDLE_CLASS}`}
  428. draggableCancel={`.${DRAG_RESIZE_CLASS}`}
  429. layouts={layouts}
  430. onLayoutChange={this.handleLayoutChange}
  431. onBreakpointChange={this.handleBreakpointChange}
  432. isDraggable={canModifyLayout}
  433. isResizable={canModifyLayout}
  434. resizeHandle={
  435. <ResizeHandle
  436. aria-label={t('Resize Widget')}
  437. data-test-id="custom-resize-handle"
  438. className={DRAG_RESIZE_CLASS}
  439. size="xs"
  440. borderless
  441. icon={<IconResize />}
  442. />
  443. }
  444. useCSSTransforms={false}
  445. isBounded
  446. >
  447. {widgetsWithLayout.map((widget, index) => this.renderWidget(widget, index))}
  448. {(isEditingDashboard || hasDDMExperimentalFeature(organization)) &&
  449. !widgetLimitReached && (
  450. <AddWidgetWrapper
  451. key={ADD_WIDGET_BUTTON_DRAG_ID}
  452. data-grid={this.addWidgetLayout}
  453. >
  454. <AddWidget onAddWidget={this.handleStartAdd} />
  455. </AddWidgetWrapper>
  456. )}
  457. </GridLayout>
  458. );
  459. }
  460. }
  461. export default withApi(withPageFilters(Dashboard));
  462. // A widget being dragged has a z-index of 3
  463. // Allow the Add Widget tile to show above widgets when moved
  464. const AddWidgetWrapper = styled('div')`
  465. z-index: 5;
  466. background-color: ${p => p.theme.background};
  467. `;
  468. const GridLayout = styled(WidthProvider(Responsive))`
  469. margin: -${space(2)};
  470. .react-grid-item.react-grid-placeholder {
  471. background: ${p => p.theme.purple200};
  472. border-radius: ${p => p.theme.borderRadius};
  473. }
  474. `;
  475. const ResizeHandle = styled(Button)`
  476. position: absolute;
  477. z-index: 2;
  478. bottom: ${space(0.5)};
  479. right: ${space(0.5)};
  480. color: ${p => p.theme.subText};
  481. cursor: nwse-resize;
  482. .react-resizable-hide & {
  483. display: none;
  484. }
  485. `;