index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import {browserHistory, InjectedRouter} from 'react-router';
  2. import styled from '@emotion/styled';
  3. import {Location} from 'history';
  4. import pick from 'lodash/pick';
  5. import {createDashboard} from 'sentry/actionCreators/dashboards';
  6. import {addSuccessMessage} from 'sentry/actionCreators/indicator';
  7. import {openImportDashboardFromFileModal} from 'sentry/actionCreators/modal';
  8. import {Client} from 'sentry/api';
  9. import Feature from 'sentry/components/acl/feature';
  10. import {Alert} from 'sentry/components/alert';
  11. import {Button} from 'sentry/components/button';
  12. import ButtonBar from 'sentry/components/buttonBar';
  13. import {CompactSelect} from 'sentry/components/compactSelect';
  14. import * as Layout from 'sentry/components/layouts/thirds';
  15. import LoadingIndicator from 'sentry/components/loadingIndicator';
  16. import NoProjectMessage from 'sentry/components/noProjectMessage';
  17. import {PageHeadingQuestionTooltip} from 'sentry/components/pageHeadingQuestionTooltip';
  18. import SearchBar from 'sentry/components/searchBar';
  19. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  20. import Switch from 'sentry/components/switchButton';
  21. import {IconAdd, IconDownload} from 'sentry/icons';
  22. import {t} from 'sentry/locale';
  23. import {space} from 'sentry/styles/space';
  24. import {Organization, SelectValue} from 'sentry/types';
  25. import {trackAnalytics} from 'sentry/utils/analytics';
  26. import {hasDashboardImportFeature} from 'sentry/utils/metrics/features';
  27. import {decodeScalar} from 'sentry/utils/queryString';
  28. import withApi from 'sentry/utils/withApi';
  29. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  30. import withOrganization from 'sentry/utils/withOrganization';
  31. import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
  32. import {openDashboardImport} from '../../ddm/dashboardImportModal';
  33. import {DASHBOARDS_TEMPLATES} from '../data';
  34. import {assignDefaultLayout, getInitialColumnDepths} from '../layoutUtils';
  35. import {DashboardDetails, DashboardListItem} from '../types';
  36. import DashboardList from './dashboardList';
  37. import TemplateCard from './templateCard';
  38. import {setShowTemplates, shouldShowTemplates} from './utils';
  39. const SORT_OPTIONS: SelectValue<string>[] = [
  40. {label: t('My Dashboards'), value: 'mydashboards'},
  41. {label: t('Dashboard Name (A-Z)'), value: 'title'},
  42. {label: t('Date Created (Newest)'), value: '-dateCreated'},
  43. {label: t('Date Created (Oldest)'), value: 'dateCreated'},
  44. {label: t('Most Popular'), value: 'mostPopular'},
  45. {label: t('Recently Viewed'), value: 'recentlyViewed'},
  46. ];
  47. type Props = {
  48. api: Client;
  49. location: Location;
  50. organization: Organization;
  51. router: InjectedRouter;
  52. } & DeprecatedAsyncView['props'];
  53. type State = {
  54. dashboards: DashboardListItem[] | null;
  55. dashboardsPageLinks: string;
  56. showTemplates: boolean;
  57. } & DeprecatedAsyncView['state'];
  58. class ManageDashboards extends DeprecatedAsyncView<Props, State> {
  59. getDefaultState() {
  60. return {
  61. ...super.getDefaultState(),
  62. showTemplates: shouldShowTemplates(),
  63. };
  64. }
  65. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  66. const {organization, location} = this.props;
  67. const endpoints: ReturnType<DeprecatedAsyncView['getEndpoints']> = [
  68. [
  69. 'dashboards',
  70. `/organizations/${organization.slug}/dashboards/`,
  71. {
  72. query: {
  73. ...pick(location.query, ['cursor', 'query']),
  74. sort: this.getActiveSort().value,
  75. per_page: '9',
  76. },
  77. },
  78. ],
  79. ];
  80. return endpoints;
  81. }
  82. getActiveSort() {
  83. const {location} = this.props;
  84. const urlSort = decodeScalar(location.query.sort, 'mydashboards');
  85. return SORT_OPTIONS.find(item => item.value === urlSort) || SORT_OPTIONS[0];
  86. }
  87. onDashboardsChange() {
  88. this.reloadData();
  89. }
  90. handleSearch(query: string) {
  91. const {location, router, organization} = this.props;
  92. trackAnalytics('dashboards_manage.search', {
  93. organization,
  94. });
  95. router.push({
  96. pathname: location.pathname,
  97. query: {...location.query, cursor: undefined, query},
  98. });
  99. }
  100. handleSortChange = (value: string) => {
  101. const {location, organization} = this.props;
  102. trackAnalytics('dashboards_manage.change_sort', {
  103. organization,
  104. sort: value,
  105. });
  106. browserHistory.push({
  107. pathname: location.pathname,
  108. query: {
  109. ...location.query,
  110. cursor: undefined,
  111. sort: value,
  112. },
  113. });
  114. };
  115. toggleTemplates = () => {
  116. const {showTemplates} = this.state;
  117. const {organization} = this.props;
  118. trackAnalytics('dashboards_manage.templates.toggle', {
  119. organization,
  120. show_templates: !showTemplates,
  121. });
  122. this.setState({showTemplates: !showTemplates}, () => {
  123. setShowTemplates(!showTemplates);
  124. });
  125. };
  126. getQuery() {
  127. const {query} = this.props.location.query;
  128. return typeof query === 'string' ? query : undefined;
  129. }
  130. renderTemplates() {
  131. return (
  132. <TemplateContainer>
  133. {DASHBOARDS_TEMPLATES.map(dashboard => (
  134. <TemplateCard
  135. title={dashboard.title}
  136. description={dashboard.description}
  137. onPreview={() => this.onPreview(dashboard.id)}
  138. onAdd={() => this.onAdd(dashboard)}
  139. key={dashboard.title}
  140. />
  141. ))}
  142. </TemplateContainer>
  143. );
  144. }
  145. renderActions() {
  146. const activeSort = this.getActiveSort();
  147. return (
  148. <StyledActions>
  149. <SearchBar
  150. defaultQuery=""
  151. query={this.getQuery()}
  152. placeholder={t('Search Dashboards')}
  153. onSearch={query => this.handleSearch(query)}
  154. />
  155. <CompactSelect
  156. triggerProps={{prefix: t('Sort By')}}
  157. value={activeSort.value}
  158. options={SORT_OPTIONS}
  159. onChange={opt => this.handleSortChange(opt.value)}
  160. position="bottom-end"
  161. />
  162. </StyledActions>
  163. );
  164. }
  165. renderNoAccess() {
  166. return (
  167. <Layout.Page>
  168. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  169. </Layout.Page>
  170. );
  171. }
  172. renderDashboards() {
  173. const {dashboards, dashboardsPageLinks} = this.state;
  174. const {organization, location, api} = this.props;
  175. return (
  176. <DashboardList
  177. api={api}
  178. dashboards={dashboards}
  179. organization={organization}
  180. pageLinks={dashboardsPageLinks}
  181. location={location}
  182. onDashboardsChange={() => this.onDashboardsChange()}
  183. />
  184. );
  185. }
  186. getTitle() {
  187. return t('Dashboards');
  188. }
  189. onCreate() {
  190. const {organization, location} = this.props;
  191. trackAnalytics('dashboards_manage.create.start', {
  192. organization,
  193. });
  194. browserHistory.push(
  195. normalizeUrl({
  196. pathname: `/organizations/${organization.slug}/dashboards/new/`,
  197. query: location.query,
  198. })
  199. );
  200. }
  201. async onAdd(dashboard: DashboardDetails) {
  202. const {organization, api} = this.props;
  203. trackAnalytics('dashboards_manage.templates.add', {
  204. organization,
  205. dashboard_id: dashboard.id,
  206. dashboard_title: dashboard.title,
  207. was_previewed: false,
  208. });
  209. const newDashboard = await createDashboard(
  210. api,
  211. organization.slug,
  212. {
  213. ...dashboard,
  214. widgets: assignDefaultLayout(dashboard.widgets, getInitialColumnDepths()),
  215. },
  216. true
  217. );
  218. addSuccessMessage(`${dashboard.title} dashboard template successfully added.`);
  219. this.loadDashboard(newDashboard.id);
  220. }
  221. loadDashboard(dashboardId: string) {
  222. const {organization, location} = this.props;
  223. browserHistory.push(
  224. normalizeUrl({
  225. pathname: `/organizations/${organization.slug}/dashboards/${dashboardId}/`,
  226. query: location.query,
  227. })
  228. );
  229. }
  230. onPreview(dashboardId: string) {
  231. const {organization, location} = this.props;
  232. trackAnalytics('dashboards_manage.templates.preview', {
  233. organization,
  234. dashboard_id: dashboardId,
  235. });
  236. browserHistory.push(
  237. normalizeUrl({
  238. pathname: `/organizations/${organization.slug}/dashboards/new/${dashboardId}/`,
  239. query: location.query,
  240. })
  241. );
  242. }
  243. renderLoading() {
  244. return (
  245. <Layout.Page withPadding>
  246. <LoadingIndicator />
  247. </Layout.Page>
  248. );
  249. }
  250. renderBody() {
  251. const {showTemplates} = this.state;
  252. const {organization, api, location} = this.props;
  253. return (
  254. <Feature
  255. organization={organization}
  256. features="dashboards-edit"
  257. renderDisabled={this.renderNoAccess}
  258. >
  259. <SentryDocumentTitle title={t('Dashboards')} orgSlug={organization.slug}>
  260. <Layout.Page>
  261. <NoProjectMessage organization={organization}>
  262. <Layout.Header>
  263. <Layout.HeaderContent>
  264. <Layout.Title>
  265. {t('Dashboards')}
  266. <PageHeadingQuestionTooltip
  267. docsUrl="https://docs.sentry.io/product/dashboards/"
  268. title={t(
  269. 'A broad overview of your application’s health where you can navigate through error and performance data across multiple projects.'
  270. )}
  271. />
  272. </Layout.Title>
  273. </Layout.HeaderContent>
  274. <Layout.HeaderActions>
  275. <ButtonBar gap={1.5}>
  276. <TemplateSwitch>
  277. {t('Show Templates')}
  278. <Switch
  279. isActive={showTemplates}
  280. size="lg"
  281. toggle={this.toggleTemplates}
  282. />
  283. </TemplateSwitch>
  284. {hasDashboardImportFeature(organization) && (
  285. <Button
  286. onClick={() => {
  287. openDashboardImport(organization);
  288. }}
  289. size="sm"
  290. icon={<IconDownload />}
  291. >
  292. {t('Import Dashboard')}
  293. </Button>
  294. )}
  295. <Button
  296. data-test-id="dashboard-create"
  297. onClick={event => {
  298. event.preventDefault();
  299. this.onCreate();
  300. }}
  301. size="sm"
  302. priority="primary"
  303. icon={<IconAdd isCircled />}
  304. >
  305. {t('Create Dashboard')}
  306. </Button>
  307. <Feature features="dashboards-import">
  308. <Button
  309. onClick={() => {
  310. openImportDashboardFromFileModal({
  311. organization,
  312. api,
  313. location,
  314. });
  315. }}
  316. size="sm"
  317. priority="primary"
  318. icon={<IconAdd isCircled />}
  319. >
  320. {t('Import Dashboard from JSON')}
  321. </Button>
  322. </Feature>
  323. </ButtonBar>
  324. </Layout.HeaderActions>
  325. </Layout.Header>
  326. <Layout.Body>
  327. <Layout.Main fullWidth>
  328. {showTemplates && this.renderTemplates()}
  329. {this.renderActions()}
  330. {this.renderDashboards()}
  331. </Layout.Main>
  332. </Layout.Body>
  333. </NoProjectMessage>
  334. </Layout.Page>
  335. </SentryDocumentTitle>
  336. </Feature>
  337. );
  338. }
  339. }
  340. const StyledActions = styled('div')`
  341. display: grid;
  342. grid-template-columns: auto max-content;
  343. gap: ${space(2)};
  344. margin-bottom: ${space(2)};
  345. @media (max-width: ${p => p.theme.breakpoints.small}) {
  346. grid-template-columns: auto;
  347. }
  348. `;
  349. const TemplateSwitch = styled('label')`
  350. font-weight: normal;
  351. font-size: ${p => p.theme.fontSizeLarge};
  352. display: flex;
  353. align-items: center;
  354. gap: ${space(1)};
  355. width: max-content;
  356. margin: 0;
  357. `;
  358. const TemplateContainer = styled('div')`
  359. display: grid;
  360. gap: ${space(2)};
  361. margin-bottom: ${space(0.5)};
  362. @media (min-width: ${p => p.theme.breakpoints.small}) {
  363. grid-template-columns: repeat(2, minmax(200px, 1fr));
  364. }
  365. @media (min-width: ${p => p.theme.breakpoints.large}) {
  366. grid-template-columns: repeat(4, minmax(200px, 1fr));
  367. }
  368. `;
  369. export default withApi(withOrganization(ManageDashboards));