dashboard.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import 'react-grid-layout/css/styles.css';
  2. import 'react-resizable/css/styles.css';
  3. import {Component} from 'react';
  4. import {Layout, Layouts, Responsive, WidthProvider} from 'react-grid-layout';
  5. import {InjectedRouter} from 'react-router';
  6. import {closestCenter, DndContext} from '@dnd-kit/core';
  7. import {arrayMove, rectSortingStrategy, SortableContext} from '@dnd-kit/sortable';
  8. import styled from '@emotion/styled';
  9. import {Location} from 'history';
  10. import cloneDeep from 'lodash/cloneDeep';
  11. import isEqual from 'lodash/isEqual';
  12. import sortBy from 'lodash/sortBy';
  13. import zip from 'lodash/zip';
  14. import {validateWidget} from 'sentry/actionCreators/dashboards';
  15. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  16. import {openAddDashboardWidgetModal} from 'sentry/actionCreators/modal';
  17. import {loadOrganizationTags} from 'sentry/actionCreators/tags';
  18. import {Client} from 'sentry/api';
  19. import space from 'sentry/styles/space';
  20. import {Organization, PageFilters} from 'sentry/types';
  21. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  22. import {uniqueId} from 'sentry/utils/guid';
  23. import theme from 'sentry/utils/theme';
  24. import withApi from 'sentry/utils/withApi';
  25. import withPageFilters from 'sentry/utils/withPageFilters';
  26. import {DataSet} from './widget/utils';
  27. import AddWidget, {ADD_WIDGET_BUTTON_DRAG_ID} from './addWidget';
  28. import SortableWidget from './sortableWidget';
  29. import {
  30. DashboardDetails,
  31. DashboardWidgetSource,
  32. DisplayType,
  33. Widget,
  34. WidgetType,
  35. } from './types';
  36. export const DRAG_HANDLE_CLASS = 'widget-drag';
  37. const WIDGET_PREFIX = 'grid-item';
  38. const DESKTOP = 'desktop';
  39. const MOBILE = 'mobile';
  40. const NUM_DESKTOP_COLS = 6;
  41. const NUM_MOBILE_COLS = 2;
  42. const ROW_HEIGHT = 120;
  43. const WIDGET_MARGINS: [number, number] = [16, 16];
  44. const ADD_BUTTON_POSITION = {
  45. x: 0,
  46. y: Number.MAX_VALUE,
  47. w: 2,
  48. h: 1,
  49. isResizable: false,
  50. };
  51. const DEFAULT_WIDGET_WIDTH = 2;
  52. const MOBILE_BREAKPOINT = parseInt(theme.breakpoints[0], 10);
  53. const BREAKPOINTS = {[MOBILE]: 0, [DESKTOP]: MOBILE_BREAKPOINT};
  54. const COLUMNS = {[MOBILE]: NUM_MOBILE_COLS, [DESKTOP]: NUM_DESKTOP_COLS};
  55. type Props = {
  56. api: Client;
  57. organization: Organization;
  58. dashboard: DashboardDetails;
  59. selection: PageFilters;
  60. isEditing: boolean;
  61. router: InjectedRouter;
  62. location: Location;
  63. widgetLimitReached: boolean;
  64. /**
  65. * Fired when widgets are added/removed/sorted.
  66. */
  67. onUpdate: (widgets: Widget[]) => void;
  68. onSetWidgetToBeUpdated: (widget: Widget) => void;
  69. handleAddLibraryWidgets: (widgets: Widget[]) => void;
  70. handleAddCustomWidget: (widget: Widget) => void;
  71. layout: Layout[];
  72. onLayoutChange: (layout: Layout[]) => void;
  73. paramDashboardId?: string;
  74. newWidget?: Widget;
  75. };
  76. type State = {
  77. isMobile: boolean;
  78. layouts: Layouts;
  79. };
  80. class Dashboard extends Component<Props, State> {
  81. constructor(props) {
  82. super(props);
  83. const {layout, dashboard, organization} = props;
  84. const isUsingGrid = organization.features.includes('dashboard-grid-layout');
  85. this.state = {
  86. isMobile: false,
  87. layouts: {
  88. [DESKTOP]: isUsingGrid ? layout : [],
  89. [MOBILE]: isUsingGrid ? getMobileLayout(layout, dashboard.widgets) : [],
  90. },
  91. };
  92. }
  93. static getDerivedStateFromProps(props, state) {
  94. if (props.organization.features.includes('dashboard-grid-layout')) {
  95. if (!isEqual(props.layout, state.layouts[DESKTOP])) {
  96. return {
  97. ...state,
  98. layouts: {
  99. [DESKTOP]: props.layout,
  100. [MOBILE]: getMobileLayout(props.layout, props.dashboard.widgets),
  101. },
  102. };
  103. }
  104. }
  105. return null;
  106. }
  107. async componentDidMount() {
  108. const {isEditing} = this.props;
  109. // Load organization tags when in edit mode.
  110. if (isEditing) {
  111. this.fetchTags();
  112. }
  113. this.addNewWidget();
  114. }
  115. async componentDidUpdate(prevProps: Props) {
  116. const {isEditing, newWidget} = this.props;
  117. // Load organization tags when going into edit mode.
  118. // We use tags on the add widget modal.
  119. if (prevProps.isEditing !== isEditing && isEditing) {
  120. this.fetchTags();
  121. }
  122. if (newWidget !== prevProps.newWidget) {
  123. this.addNewWidget();
  124. }
  125. }
  126. async addNewWidget() {
  127. const {api, organization, newWidget, handleAddCustomWidget} = this.props;
  128. if (newWidget) {
  129. try {
  130. await validateWidget(api, organization.slug, newWidget);
  131. handleAddCustomWidget(newWidget);
  132. } catch (error) {
  133. // Don't do anything, widget isn't valid
  134. addErrorMessage(error);
  135. }
  136. }
  137. }
  138. fetchTags() {
  139. const {api, organization, selection} = this.props;
  140. loadOrganizationTags(api, organization.slug, selection);
  141. }
  142. handleStartAdd = () => {
  143. const {
  144. organization,
  145. dashboard,
  146. selection,
  147. handleAddLibraryWidgets,
  148. handleAddCustomWidget,
  149. } = this.props;
  150. trackAdvancedAnalyticsEvent('dashboards_views.add_widget_modal.opened', {
  151. organization,
  152. });
  153. if (organization.features.includes('widget-library')) {
  154. trackAdvancedAnalyticsEvent('dashboards_views.widget_library.opened', {
  155. organization,
  156. });
  157. openAddDashboardWidgetModal({
  158. organization,
  159. dashboard,
  160. selection,
  161. onAddWidget: handleAddCustomWidget,
  162. onAddLibraryWidget: (widgets: Widget[]) => handleAddLibraryWidgets(widgets),
  163. source: DashboardWidgetSource.LIBRARY,
  164. });
  165. return;
  166. }
  167. openAddDashboardWidgetModal({
  168. organization,
  169. dashboard,
  170. selection,
  171. onAddWidget: handleAddCustomWidget,
  172. source: DashboardWidgetSource.DASHBOARDS,
  173. });
  174. };
  175. handleOpenWidgetBuilder = () => {
  176. const {router, paramDashboardId, organization, location} = this.props;
  177. if (paramDashboardId) {
  178. router.push({
  179. pathname: `/organizations/${organization.slug}/dashboard/${paramDashboardId}/widget/new/`,
  180. query: {
  181. ...location.query,
  182. dataSet: DataSet.EVENTS,
  183. },
  184. });
  185. return;
  186. }
  187. router.push({
  188. pathname: `/organizations/${organization.slug}/dashboards/new/widget/new/`,
  189. query: {
  190. ...location.query,
  191. dataSet: DataSet.EVENTS,
  192. },
  193. });
  194. };
  195. handleUpdateComplete = (prevWidget: Widget) => (nextWidget: Widget) => {
  196. const nextList = [...this.props.dashboard.widgets];
  197. const updateIndex = nextList.indexOf(prevWidget);
  198. nextList[updateIndex] = {...nextWidget, tempId: prevWidget.tempId};
  199. this.props.onUpdate(nextList);
  200. };
  201. handleDeleteWidget = (widgetToDelete: Widget) => () => {
  202. const {layouts} = this.state;
  203. const {dashboard, onUpdate, onLayoutChange, organization} = this.props;
  204. const nextList = dashboard.widgets.filter(widget => widget !== widgetToDelete);
  205. onUpdate(nextList);
  206. if (organization.features.includes('dashboard-grid-layout')) {
  207. const newLayout = layouts[DESKTOP].filter(
  208. ({i}) => i !== constructGridItemKey(widgetToDelete)
  209. );
  210. onLayoutChange(newLayout);
  211. }
  212. };
  213. handleDuplicateWidget = (widget: Widget, index: number) => () => {
  214. const {dashboard, handleAddLibraryWidgets} = this.props;
  215. const widgetCopy = cloneDeep(widget);
  216. widgetCopy.id = undefined;
  217. widgetCopy.tempId = undefined;
  218. const nextList = [...dashboard.widgets];
  219. nextList.splice(index, 0, widgetCopy);
  220. handleAddLibraryWidgets(nextList);
  221. };
  222. handleEditWidget = (widget: Widget, index: number) => () => {
  223. const {
  224. organization,
  225. dashboard,
  226. selection,
  227. router,
  228. location,
  229. paramDashboardId,
  230. onSetWidgetToBeUpdated,
  231. handleAddCustomWidget,
  232. } = this.props;
  233. if (organization.features.includes('metrics')) {
  234. onSetWidgetToBeUpdated(widget);
  235. if (paramDashboardId) {
  236. router.push({
  237. pathname: `/organizations/${organization.slug}/dashboard/${paramDashboardId}/widget/${index}/edit/`,
  238. query: {
  239. ...location.query,
  240. dataSet: DataSet.EVENTS,
  241. },
  242. });
  243. return;
  244. }
  245. router.push({
  246. pathname: `/organizations/${organization.slug}/dashboards/new/widget/${index}/edit/`,
  247. query: {
  248. ...location.query,
  249. dataSet: DataSet.EVENTS,
  250. },
  251. });
  252. }
  253. trackAdvancedAnalyticsEvent('dashboards_views.edit_widget_modal.opened', {
  254. organization,
  255. });
  256. const modalProps = {
  257. organization,
  258. widget,
  259. selection,
  260. onAddWidget: handleAddCustomWidget,
  261. onUpdateWidget: this.handleUpdateComplete(widget),
  262. };
  263. openAddDashboardWidgetModal({
  264. ...modalProps,
  265. dashboard,
  266. source: DashboardWidgetSource.DASHBOARDS,
  267. });
  268. };
  269. getWidgetIds() {
  270. return [
  271. ...this.props.dashboard.widgets.map((widget, index): string => {
  272. return generateWidgetId(widget, index);
  273. }),
  274. ADD_WIDGET_BUTTON_DRAG_ID,
  275. ];
  276. }
  277. renderWidget(widget: Widget, index: number) {
  278. const {isMobile} = this.state;
  279. const {isEditing, organization, widgetLimitReached} = this.props;
  280. const widgetProps = {
  281. widget,
  282. isEditing,
  283. widgetLimitReached,
  284. onDelete: this.handleDeleteWidget(widget),
  285. onEdit: this.handleEditWidget(widget, index),
  286. onDuplicate: this.handleDuplicateWidget(widget, index),
  287. };
  288. if (organization.features.includes('dashboard-grid-layout')) {
  289. const key = constructGridItemKey(widget);
  290. const dragId = key;
  291. return (
  292. <GridItem key={key} data-grid={getDefaultPosition(index, widget.displayType)}>
  293. <SortableWidget {...widgetProps} dragId={dragId} hideDragHandle={isMobile} />
  294. </GridItem>
  295. );
  296. }
  297. const key = generateWidgetId(widget, index);
  298. const dragId = key;
  299. return <SortableWidget {...widgetProps} key={key} dragId={dragId} />;
  300. }
  301. handleLayoutChange = (_, allLayouts: Layouts) => {
  302. const {onLayoutChange} = this.props;
  303. const isNotAddButton = ({i}) => i !== ADD_WIDGET_BUTTON_DRAG_ID;
  304. const newLayouts = {
  305. [DESKTOP]: allLayouts[DESKTOP].filter(isNotAddButton),
  306. [MOBILE]: allLayouts[MOBILE].filter(isNotAddButton),
  307. };
  308. this.setState({
  309. layouts: newLayouts,
  310. });
  311. // The desktop layout is the source of truth
  312. onLayoutChange(newLayouts[DESKTOP]);
  313. };
  314. handleBreakpointChange = (newBreakpoint: string) => {
  315. const {layouts} = this.state;
  316. const {
  317. dashboard: {widgets},
  318. } = this.props;
  319. if (newBreakpoint === MOBILE) {
  320. this.setState({
  321. isMobile: true,
  322. layouts: {
  323. ...layouts,
  324. [MOBILE]: getMobileLayout(layouts[DESKTOP], widgets),
  325. },
  326. });
  327. return;
  328. }
  329. this.setState({isMobile: false});
  330. };
  331. renderGridDashboard() {
  332. const {layouts, isMobile} = this.state;
  333. const {isEditing, dashboard, organization, widgetLimitReached} = this.props;
  334. let {widgets} = dashboard;
  335. // Filter out any issue widgets if the user does not have the feature flag
  336. if (!organization.features.includes('issues-in-dashboards')) {
  337. widgets = widgets.filter(({widgetType}) => widgetType !== WidgetType.ISSUE);
  338. }
  339. const canModifyLayout = !isMobile && isEditing;
  340. return (
  341. <GridLayout
  342. breakpoints={BREAKPOINTS}
  343. cols={COLUMNS}
  344. rowHeight={ROW_HEIGHT}
  345. margin={WIDGET_MARGINS}
  346. draggableHandle={`.${DRAG_HANDLE_CLASS}`}
  347. layouts={layouts}
  348. onLayoutChange={this.handleLayoutChange}
  349. onBreakpointChange={this.handleBreakpointChange}
  350. isDraggable={canModifyLayout}
  351. isResizable={canModifyLayout}
  352. isBounded
  353. >
  354. {widgets.map((widget, index) => this.renderWidget(widget, index))}
  355. {isEditing && !!!widgetLimitReached && (
  356. <div key={ADD_WIDGET_BUTTON_DRAG_ID} data-grid={ADD_BUTTON_POSITION}>
  357. <AddWidget
  358. orgFeatures={organization.features}
  359. onAddWidget={this.handleStartAdd}
  360. onOpenWidgetBuilder={this.handleOpenWidgetBuilder}
  361. />
  362. </div>
  363. )}
  364. </GridLayout>
  365. );
  366. }
  367. renderDndDashboard = () => {
  368. const {isEditing, onUpdate, dashboard, organization, widgetLimitReached} = this.props;
  369. let {widgets} = dashboard;
  370. // Filter out any issue widgets if the user does not have the feature flag
  371. if (!organization.features.includes('issues-in-dashboards')) {
  372. widgets = widgets.filter(({widgetType}) => widgetType !== WidgetType.ISSUE);
  373. }
  374. const items = this.getWidgetIds();
  375. return (
  376. <DndContext
  377. collisionDetection={closestCenter}
  378. onDragEnd={({over, active}) => {
  379. const activeDragId = active.id;
  380. const getIndex = items.indexOf.bind(items);
  381. const activeIndex = activeDragId ? getIndex(activeDragId) : -1;
  382. if (over && over.id !== ADD_WIDGET_BUTTON_DRAG_ID) {
  383. const overIndex = getIndex(over.id);
  384. if (activeIndex !== overIndex) {
  385. onUpdate(arrayMove(widgets, activeIndex, overIndex));
  386. }
  387. }
  388. }}
  389. >
  390. <WidgetContainer>
  391. <SortableContext items={items} strategy={rectSortingStrategy}>
  392. {widgets.map((widget, index) => this.renderWidget(widget, index))}
  393. {isEditing && !!!widgetLimitReached && (
  394. <AddWidget
  395. orgFeatures={organization.features}
  396. onAddWidget={this.handleStartAdd}
  397. onOpenWidgetBuilder={this.handleOpenWidgetBuilder}
  398. />
  399. )}
  400. </SortableContext>
  401. </WidgetContainer>
  402. </DndContext>
  403. );
  404. };
  405. render() {
  406. const {organization} = this.props;
  407. if (organization.features.includes('dashboard-grid-layout')) {
  408. return this.renderGridDashboard();
  409. }
  410. return this.renderDndDashboard();
  411. }
  412. }
  413. export default withApi(withPageFilters(Dashboard));
  414. const WidgetContainer = styled('div')`
  415. display: grid;
  416. grid-template-columns: repeat(2, minmax(0, 1fr));
  417. grid-auto-flow: row dense;
  418. grid-gap: ${space(2)};
  419. @media (min-width: ${p => p.theme.breakpoints[1]}) {
  420. grid-template-columns: repeat(4, minmax(0, 1fr));
  421. }
  422. @media (min-width: ${p => p.theme.breakpoints[3]}) {
  423. grid-template-columns: repeat(6, minmax(0, 1fr));
  424. }
  425. @media (min-width: ${p => p.theme.breakpoints[4]}) {
  426. grid-template-columns: repeat(8, minmax(0, 1fr));
  427. }
  428. `;
  429. const GridItem = styled('div')`
  430. .react-resizable-handle {
  431. z-index: 1;
  432. }
  433. `;
  434. // HACK: to stack chart tooltips above other grid items
  435. const GridLayout = styled(WidthProvider(Responsive))`
  436. .react-grid-item:hover {
  437. z-index: 10;
  438. }
  439. `;
  440. function generateWidgetId(widget: Widget, index: number) {
  441. return widget.id ? `${widget.id}-index-${index}` : `index-${index}`;
  442. }
  443. export function constructGridItemKey(widget: Widget) {
  444. return `${WIDGET_PREFIX}-${widget.id ?? widget.tempId}`;
  445. }
  446. export function assignTempId(widget: Widget) {
  447. if (widget.id ?? widget.tempId) {
  448. return widget;
  449. }
  450. return {...widget, tempId: uniqueId()};
  451. }
  452. /**
  453. * Naive positioning for widgets assuming no resizes.
  454. */
  455. function getDefaultPosition(index: number, displayType: DisplayType) {
  456. return {
  457. x: (DEFAULT_WIDGET_WIDTH * index) % NUM_DESKTOP_COLS,
  458. y: Number.MAX_VALUE,
  459. w: DEFAULT_WIDGET_WIDTH,
  460. h: displayType === DisplayType.BIG_NUMBER ? 1 : 2,
  461. minH: displayType === DisplayType.BIG_NUMBER ? 1 : 2,
  462. };
  463. }
  464. function getMobileLayout(desktopLayout: Layout[], widgets: Widget[]) {
  465. if (desktopLayout.length === 0) {
  466. // Initial case where the user has no layout saved, but
  467. // dashboard has widgets
  468. return [];
  469. }
  470. const layoutWidgetPairs = zip(desktopLayout, widgets) as [Layout, Widget][];
  471. // Sort by y and then subsort by x
  472. const sorted = sortBy(layoutWidgetPairs, ['0.y', '0.x']);
  473. const mobileLayout = sorted.map(([layout, widget], index) => ({
  474. ...layout,
  475. x: 0,
  476. y: index * 2,
  477. w: 2,
  478. h: widget.displayType === DisplayType.BIG_NUMBER ? 1 : 2,
  479. }));
  480. return mobileLayout;
  481. }