dashboard.tsx 19 KB

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