dashboard.tsx 19 KB

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