dashboard.tsx 18 KB

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