orgDashboards.tsx 6.5 KB

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