dashboard.tsx 18 KB

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