dashboard.tsx 19 KB

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