dashboard.tsx 17 KB

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