dashboard.tsx 15 KB

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