dashboard.tsx 19 KB

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