dashboard.tsx 18 KB

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