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 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 {hasDDMFeature} 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 (widget.widgetType === WidgetType.METRICS && hasDDMFeature(organization)) {
  277. this.handleStartEditMetricWidget(index);
  278. return;
  279. }
  280. if (paramDashboardId) {
  281. router.push(
  282. normalizeUrl({
  283. pathname: `/organizations/${organization.slug}/dashboard/${paramDashboardId}/widget/${index}/edit/`,
  284. query: {
  285. ...location.query,
  286. source: DashboardWidgetSource.DASHBOARDS,
  287. },
  288. })
  289. );
  290. return;
  291. }
  292. router.push(
  293. normalizeUrl({
  294. pathname: `/organizations/${organization.slug}/dashboards/new/widget/${index}/edit/`,
  295. query: {
  296. ...location.query,
  297. source: DashboardWidgetSource.DASHBOARDS,
  298. },
  299. })
  300. );
  301. return;
  302. };
  303. handleStartEditMetricWidget = (index: number) => {
  304. this.props.onStartEditMetricWidget?.(index);
  305. };
  306. onUpdate = (widget: Widget, index: number) => (newWidget: Widget | null) => {
  307. if (widget.widgetType === WidgetType.METRICS) {
  308. this.handleEndEditMetricWidget(widget, index)(newWidget);
  309. return;
  310. }
  311. };
  312. handleEndEditMetricWidget =
  313. (widget: Widget, index: number) => (newWidget: Widget | null) => {
  314. const widgets = [...this.props.dashboard.widgets];
  315. if (newWidget) {
  316. widgets[index] = {...widget, ...newWidget};
  317. }
  318. this.props.onEndEditMetricWidget?.(widgets, !newWidget);
  319. };
  320. getWidgetIds() {
  321. return [
  322. ...this.props.dashboard.widgets.map((widget, index): string => {
  323. return generateWidgetId(widget, index);
  324. }),
  325. ADD_WIDGET_BUTTON_DRAG_ID,
  326. ];
  327. }
  328. renderWidget(widget: Widget, index: number) {
  329. const {isMobile, windowWidth} = this.state;
  330. const {
  331. isEditingDashboard,
  332. editingWidgetIndex,
  333. widgetLimitReached,
  334. isPreview,
  335. dashboard,
  336. location,
  337. } = this.props;
  338. const isEditingWidget = editingWidgetIndex === index;
  339. const widgetProps = {
  340. widget,
  341. isEditingDashboard,
  342. widgetLimitReached,
  343. onDelete: this.handleDeleteWidget(widget),
  344. onEdit: this.handleEditWidget(index),
  345. onDuplicate: this.handleDuplicateWidget(widget, index),
  346. onUpdate: this.onUpdate(widget, index),
  347. isPreview,
  348. isEditingWidget,
  349. dashboardFilters: getDashboardFiltersFromURL(location) ?? dashboard.filters,
  350. };
  351. const key = constructGridItemKey(widget);
  352. // inline edited widgets span full width
  353. if (isEditingWidget) {
  354. return (
  355. <WidgetWidthWrapper key={key} data-grid={widget.layout}>
  356. <SortableWidget
  357. {...widgetProps}
  358. isMobile={isMobile}
  359. windowWidth={windowWidth}
  360. index={String(index)}
  361. />
  362. </WidgetWidthWrapper>
  363. );
  364. }
  365. return (
  366. <div key={key} data-grid={widget.layout}>
  367. <SortableWidget
  368. {...widgetProps}
  369. isMobile={isMobile}
  370. windowWidth={windowWidth}
  371. index={String(index)}
  372. />
  373. </div>
  374. );
  375. }
  376. handleLayoutChange = (_, allLayouts: Layouts) => {
  377. const {isMobile} = this.state;
  378. const {dashboard, onUpdate} = this.props;
  379. const isNotAddButton = ({i}) => i !== ADD_WIDGET_BUTTON_DRAG_ID;
  380. const newLayouts = {
  381. [DESKTOP]: allLayouts[DESKTOP].filter(isNotAddButton),
  382. [MOBILE]: allLayouts[MOBILE].filter(isNotAddButton),
  383. };
  384. // Generate a new list of widgets where the layouts are associated
  385. let columnDepths = calculateColumnDepths(newLayouts[DESKTOP]);
  386. const newWidgets = dashboard.widgets.map(widget => {
  387. const gridKey = constructGridItemKey(widget);
  388. let matchingLayout = newLayouts[DESKTOP].find(({i}) => i === gridKey);
  389. if (!matchingLayout) {
  390. const height = getDefaultWidgetHeight(widget.displayType);
  391. const defaultWidgetParams = {
  392. w: DEFAULT_WIDGET_WIDTH,
  393. h: height,
  394. minH: height,
  395. i: gridKey,
  396. };
  397. // Calculate the available position
  398. const [nextPosition, nextColumnDepths] = getNextAvailablePosition(
  399. columnDepths,
  400. height
  401. );
  402. columnDepths = nextColumnDepths;
  403. // Set the position for the desktop layout
  404. matchingLayout = {
  405. ...defaultWidgetParams,
  406. ...nextPosition,
  407. };
  408. if (isMobile) {
  409. // This is a new widget and it's on the mobile page so we keep it at the bottom
  410. const mobileLayout = newLayouts[MOBILE].filter(({i}) => i !== gridKey);
  411. mobileLayout.push({
  412. ...defaultWidgetParams,
  413. ...BOTTOM_MOBILE_VIEW_POSITION,
  414. });
  415. newLayouts[MOBILE] = mobileLayout;
  416. }
  417. }
  418. return {
  419. ...widget,
  420. layout: pickDefinedStoreKeys(matchingLayout),
  421. };
  422. });
  423. this.setState({
  424. layouts: newLayouts,
  425. });
  426. onUpdate(newWidgets);
  427. // Force check lazyLoad elements that might have shifted into view after (re)moving an upper widget
  428. // Unfortunately need to use window.setTimeout since React Grid Layout animates widgets into view when layout changes
  429. // RGL doesn't provide a handler for post animation layout change
  430. window.clearTimeout(this.forceCheckTimeout);
  431. this.forceCheckTimeout = window.setTimeout(forceCheck, 400);
  432. };
  433. handleBreakpointChange = (newBreakpoint: string) => {
  434. const {layouts} = this.state;
  435. const {
  436. dashboard: {widgets},
  437. } = this.props;
  438. if (newBreakpoint === MOBILE) {
  439. this.setState({
  440. isMobile: true,
  441. layouts: {
  442. ...layouts,
  443. [MOBILE]: getMobileLayout(layouts[DESKTOP], widgets),
  444. },
  445. });
  446. return;
  447. }
  448. this.setState({isMobile: false});
  449. };
  450. get addWidgetLayout() {
  451. const {isMobile, layouts} = this.state;
  452. let position: Position = BOTTOM_MOBILE_VIEW_POSITION;
  453. if (!isMobile) {
  454. const columnDepths = calculateColumnDepths(layouts[DESKTOP]);
  455. const [nextPosition] = getNextAvailablePosition(columnDepths, 1);
  456. position = nextPosition;
  457. }
  458. return {
  459. ...position,
  460. w: DEFAULT_WIDGET_WIDTH,
  461. h: 1,
  462. isResizable: false,
  463. };
  464. }
  465. render() {
  466. const {layouts, isMobile} = this.state;
  467. const {isEditingDashboard, dashboard, widgetLimitReached, organization} = this.props;
  468. let {widgets} = dashboard;
  469. // Filter out any issue/release widgets if the user does not have the feature flag
  470. widgets = widgets.filter(({widgetType}) => {
  471. if (widgetType === WidgetType.RELEASE) {
  472. return organization.features.includes('dashboards-rh-widget');
  473. }
  474. return true;
  475. });
  476. const columnDepths = calculateColumnDepths(layouts[DESKTOP]);
  477. const widgetsWithLayout = assignDefaultLayout(widgets, columnDepths);
  478. const canModifyLayout = !isMobile && isEditingDashboard;
  479. const displayInlineAddWidget =
  480. hasDDMFeature(organization) &&
  481. isValidLayout({...this.addWidgetLayout, i: ADD_WIDGET_BUTTON_DRAG_ID});
  482. return (
  483. <GridLayout
  484. breakpoints={BREAKPOINTS}
  485. cols={COLUMNS}
  486. rowHeight={ROW_HEIGHT}
  487. margin={WIDGET_MARGINS}
  488. draggableHandle={`.${DRAG_HANDLE_CLASS}`}
  489. draggableCancel={`.${DRAG_RESIZE_CLASS}`}
  490. layouts={layouts}
  491. onLayoutChange={this.handleLayoutChange}
  492. onBreakpointChange={this.handleBreakpointChange}
  493. isDraggable={canModifyLayout}
  494. isResizable={canModifyLayout}
  495. resizeHandle={
  496. <ResizeHandle
  497. aria-label={t('Resize Widget')}
  498. data-test-id="custom-resize-handle"
  499. className={DRAG_RESIZE_CLASS}
  500. size="xs"
  501. borderless
  502. icon={<IconResize />}
  503. />
  504. }
  505. useCSSTransforms={false}
  506. isBounded
  507. >
  508. {widgetsWithLayout.map((widget, index) => this.renderWidget(widget, index))}
  509. {(isEditingDashboard || displayInlineAddWidget) && !widgetLimitReached && (
  510. <AddWidgetWrapper
  511. key={ADD_WIDGET_BUTTON_DRAG_ID}
  512. data-grid={this.addWidgetLayout}
  513. >
  514. <AddWidget onAddWidget={this.handleStartAdd} />
  515. </AddWidgetWrapper>
  516. )}
  517. </GridLayout>
  518. );
  519. }
  520. }
  521. export default withApi(withPageFilters(Dashboard));
  522. // A widget being dragged has a z-index of 3
  523. // Allow the Add Widget tile to show above widgets when moved
  524. const AddWidgetWrapper = styled('div')`
  525. z-index: 5;
  526. background-color: ${p => p.theme.background};
  527. `;
  528. const GridLayout = styled(WidthProvider(Responsive))`
  529. margin: -${space(2)};
  530. .react-grid-item.react-grid-placeholder {
  531. background: ${p => p.theme.purple200};
  532. border-radius: ${p => p.theme.borderRadius};
  533. }
  534. `;
  535. const ResizeHandle = styled(Button)`
  536. position: absolute;
  537. z-index: 2;
  538. bottom: ${space(0.5)};
  539. right: ${space(0.5)};
  540. color: ${p => p.theme.subText};
  541. cursor: nwse-resize;
  542. .react-resizable-hide & {
  543. display: none;
  544. }
  545. `;
  546. const WidgetWidthWrapper = styled('div')`
  547. position: absolute;
  548. /* react-grid-layout adds left, right and width so we need to override */
  549. left: 16px !important;
  550. right: 16px !important;
  551. width: auto !important;
  552. /* minimal working z-index */
  553. z-index: 6;
  554. `;