dashboard.tsx 19 KB

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