dashboard.tsx 17 KB

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