dashboard.tsx 18 KB

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