orgDashboards.tsx 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import {browserHistory} from 'react-router';
  2. import {Location} from 'history';
  3. import isEmpty from 'lodash/isEmpty';
  4. import isEqual from 'lodash/isEqual';
  5. import {Client} from 'sentry/api';
  6. import AsyncComponent from 'sentry/components/asyncComponent';
  7. import NotFound from 'sentry/components/errors/notFound';
  8. import * as Layout from 'sentry/components/layouts/thirds';
  9. import LoadingIndicator from 'sentry/components/loadingIndicator';
  10. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  11. import {t} from 'sentry/locale';
  12. import {Organization} from 'sentry/types';
  13. import withRouteAnalytics, {
  14. WithRouteAnalyticsProps,
  15. } from 'sentry/utils/routeAnalytics/withRouteAnalytics';
  16. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  17. import {assignTempId} from './layoutUtils';
  18. import {DashboardDetails, DashboardListItem} from './types';
  19. import {hasSavedPageFilters} from './utils';
  20. type OrgDashboardsChildrenProps = {
  21. dashboard: DashboardDetails | null;
  22. dashboards: DashboardListItem[];
  23. error: boolean;
  24. onDashboardUpdate: (updatedDashboard: DashboardDetails) => void;
  25. };
  26. type Props = WithRouteAnalyticsProps & {
  27. api: Client;
  28. children: (props: OrgDashboardsChildrenProps) => React.ReactNode;
  29. location: Location;
  30. organization: Organization;
  31. params: {orgId: string; dashboardId?: string};
  32. };
  33. type State = {
  34. // endpoint response
  35. dashboards: DashboardListItem[] | null;
  36. /**
  37. * The currently selected dashboard.
  38. */
  39. selectedDashboard: DashboardDetails | null;
  40. } & AsyncComponent['state'];
  41. class OrgDashboards extends AsyncComponent<Props, State> {
  42. state: State = {
  43. // AsyncComponent state
  44. loading: true,
  45. reloading: false,
  46. error: false,
  47. errors: {},
  48. dashboards: [],
  49. selectedDashboard: null,
  50. };
  51. componentDidUpdate(prevProps: Props) {
  52. if (!isEqual(prevProps.params.dashboardId, this.props.params.dashboardId)) {
  53. this.remountComponent();
  54. }
  55. }
  56. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  57. const {organization, params} = this.props;
  58. const url = `/organizations/${organization.slug}/dashboards/`;
  59. const endpoints: ReturnType<AsyncComponent['getEndpoints']> = [['dashboards', url]];
  60. if (params.dashboardId) {
  61. endpoints.push(['selectedDashboard', `${url}${params.dashboardId}/`]);
  62. this.props.setEventNames('dashboards2.view', 'Dashboards2: View dashboard');
  63. this.props.setRouteAnalyticsParams({
  64. dashboard_id: params.dashboardId,
  65. });
  66. }
  67. return endpoints;
  68. }
  69. onDashboardUpdate(updatedDashboard: DashboardDetails) {
  70. this.setState({selectedDashboard: updatedDashboard});
  71. }
  72. getDashboards(): DashboardListItem[] {
  73. const {dashboards} = this.state;
  74. return Array.isArray(dashboards) ? dashboards : [];
  75. }
  76. onRequestSuccess({stateKey, data}) {
  77. const {params, organization, location} = this.props;
  78. if (params.dashboardId || stateKey === 'selectedDashboard') {
  79. const queryParamFilters = new Set([
  80. 'project',
  81. 'environment',
  82. 'statsPeriod',
  83. 'start',
  84. 'end',
  85. 'utc',
  86. 'release',
  87. ]);
  88. if (
  89. stateKey === 'selectedDashboard' &&
  90. // Only redirect if there are saved filters and none of the filters
  91. // appear in the query params
  92. hasSavedPageFilters(data) &&
  93. isEmpty(
  94. Object.keys(location.query).filter(unsavedQueryParam =>
  95. queryParamFilters.has(unsavedQueryParam)
  96. )
  97. )
  98. ) {
  99. browserHistory.replace({
  100. ...location,
  101. query: {
  102. ...location.query,
  103. project: data.projects,
  104. environment: data.environment,
  105. statsPeriod: data.period,
  106. start: data.start,
  107. end: data.end,
  108. utc: data.utc,
  109. },
  110. });
  111. }
  112. return;
  113. }
  114. // If we don't have a selected dashboard, and one isn't going to arrive
  115. // we can redirect to the first dashboard in the list.
  116. const dashboardId = data.length ? data[0].id : 'default-overview';
  117. browserHistory.replace(
  118. normalizeUrl({
  119. pathname: `/organizations/${organization.slug}/dashboard/${dashboardId}/`,
  120. query: {
  121. ...location.query,
  122. },
  123. })
  124. );
  125. }
  126. renderLoading() {
  127. return (
  128. <Layout.Page withPadding>
  129. <LoadingIndicator />
  130. </Layout.Page>
  131. );
  132. }
  133. renderBody() {
  134. const {children} = this.props;
  135. const {selectedDashboard, error} = this.state;
  136. let dashboard = selectedDashboard;
  137. // Ensure there are always tempIds for grid layout
  138. // This is needed because there are cases where the dashboard
  139. // renders before the onRequestSuccess setState is processed
  140. // and will caused stacked widgets because of missing tempIds
  141. dashboard = selectedDashboard
  142. ? {
  143. ...selectedDashboard,
  144. widgets: selectedDashboard.widgets.map(assignTempId),
  145. }
  146. : null;
  147. return children({
  148. error,
  149. dashboard,
  150. dashboards: this.getDashboards(),
  151. onDashboardUpdate: (updatedDashboard: DashboardDetails) =>
  152. this.onDashboardUpdate(updatedDashboard),
  153. });
  154. }
  155. renderError(error: Error) {
  156. const notFound = Object.values(this.state.errors).find(
  157. resp => resp && resp.status === 404
  158. );
  159. if (notFound) {
  160. return <NotFound />;
  161. }
  162. return super.renderError(error, true);
  163. }
  164. renderComponent() {
  165. const {organization, location} = this.props;
  166. const {loading, selectedDashboard} = this.state;
  167. if (!organization.features.includes('dashboards-basic')) {
  168. // Redirect to Dashboards v1
  169. browserHistory.replace(
  170. normalizeUrl({
  171. pathname: `/organizations/${organization.slug}/dashboards/`,
  172. query: {
  173. ...location.query,
  174. },
  175. })
  176. );
  177. return null;
  178. }
  179. if (
  180. loading &&
  181. selectedDashboard &&
  182. hasSavedPageFilters(selectedDashboard) &&
  183. isEmpty(location.query)
  184. ) {
  185. // Block dashboard from rendering if the dashboard has filters and
  186. // the URL does not contain filters yet. The filters can either match the
  187. // saved filters, or can be different (i.e. sharing an unsaved state)
  188. return this.renderLoading();
  189. }
  190. return (
  191. <SentryDocumentTitle title={t('Dashboards')} orgSlug={organization.slug}>
  192. {super.renderComponent() as React.ReactChild}
  193. </SentryDocumentTitle>
  194. );
  195. }
  196. }
  197. export default withRouteAnalytics(OrgDashboards);