index.tsx 11 KB

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