dashboard.tsx 18 KB

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