index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import {useEffect, useRef, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Query} from 'history';
  4. import debounce from 'lodash/debounce';
  5. import pick from 'lodash/pick';
  6. import {createDashboard} from 'sentry/actionCreators/dashboards';
  7. import {addSuccessMessage} from 'sentry/actionCreators/indicator';
  8. import {openImportDashboardFromFileModal} from 'sentry/actionCreators/modal';
  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 ErrorBoundary from 'sentry/components/errorBoundary';
  15. import FeedbackWidgetButton from 'sentry/components/feedback/widget/feedbackWidgetButton';
  16. import * as Layout from 'sentry/components/layouts/thirds';
  17. import NoProjectMessage from 'sentry/components/noProjectMessage';
  18. import {PageHeadingQuestionTooltip} from 'sentry/components/pageHeadingQuestionTooltip';
  19. import Pagination from 'sentry/components/pagination';
  20. import SearchBar from 'sentry/components/searchBar';
  21. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  22. import Switch from 'sentry/components/switchButton';
  23. import {IconAdd} from 'sentry/icons';
  24. import {t} from 'sentry/locale';
  25. import {space} from 'sentry/styles/space';
  26. import type {SelectValue} from 'sentry/types/core';
  27. import {trackAnalytics} from 'sentry/utils/analytics';
  28. import localStorage from 'sentry/utils/localStorage';
  29. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  30. import {useApiQuery} from 'sentry/utils/queryClient';
  31. import {decodeScalar} from 'sentry/utils/queryString';
  32. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  33. import useApi from 'sentry/utils/useApi';
  34. import {useLocalStorageState} from 'sentry/utils/useLocalStorageState';
  35. import {useLocation} from 'sentry/utils/useLocation';
  36. import {useNavigate} from 'sentry/utils/useNavigate';
  37. import useOrganization from 'sentry/utils/useOrganization';
  38. import {DashboardImportButton} from 'sentry/views/dashboards/manage/dashboardImport';
  39. import {MetricsRemovedAlertsWidgetsAlert} from 'sentry/views/metrics/metricsRemovedAlertsWidgetsAlert';
  40. import RouteError from 'sentry/views/routeError';
  41. import {getDashboardTemplates} from '../data';
  42. import {assignDefaultLayout, getInitialColumnDepths} from '../layoutUtils';
  43. import type {DashboardDetails, DashboardListItem} from '../types';
  44. import DashboardList from './dashboardList';
  45. import {
  46. DASHBOARD_CARD_GRID_PADDING,
  47. DASHBOARD_GRID_DEFAULT_NUM_CARDS,
  48. DASHBOARD_GRID_DEFAULT_NUM_COLUMNS,
  49. DASHBOARD_GRID_DEFAULT_NUM_ROWS,
  50. MINIMUM_DASHBOARD_CARD_WIDTH,
  51. } from './settings';
  52. import TemplateCard from './templateCard';
  53. const SORT_OPTIONS: SelectValue<string>[] = [
  54. {label: t('My Dashboards'), value: 'mydashboards'},
  55. {label: t('Dashboard Name (A-Z)'), value: 'title'},
  56. {label: t('Date Created (Newest)'), value: '-dateCreated'},
  57. {label: t('Date Created (Oldest)'), value: 'dateCreated'},
  58. {label: t('Most Popular'), value: 'mostPopular'},
  59. {label: t('Recently Viewed'), value: 'recentlyViewed'},
  60. ];
  61. const SHOW_TEMPLATES_KEY = 'dashboards-show-templates';
  62. function shouldShowTemplates(): boolean {
  63. const shouldShow = localStorage.getItem(SHOW_TEMPLATES_KEY);
  64. return shouldShow === 'true' || shouldShow === null;
  65. }
  66. function ManageDashboards() {
  67. const organization = useOrganization();
  68. const navigate = useNavigate();
  69. const location = useLocation();
  70. const api = useApi();
  71. const dashboardGridRef = useRef<HTMLDivElement>(null);
  72. const [showTemplates, setShowTemplatesLocal] = useLocalStorageState(
  73. SHOW_TEMPLATES_KEY,
  74. shouldShowTemplates()
  75. );
  76. const [{rowCount, columnCount}, setGridSize] = useState({
  77. rowCount: DASHBOARD_GRID_DEFAULT_NUM_ROWS,
  78. columnCount: DASHBOARD_GRID_DEFAULT_NUM_COLUMNS,
  79. });
  80. const {
  81. data: dashboards,
  82. isLoading,
  83. isError,
  84. error,
  85. getResponseHeader,
  86. refetch: refetchDashboards,
  87. } = useApiQuery<DashboardListItem[]>(
  88. [
  89. `/organizations/${organization.slug}/dashboards/`,
  90. {
  91. query: {
  92. ...pick(location.query, ['cursor', 'query']),
  93. sort: getActiveSort().value,
  94. per_page: rowCount * columnCount,
  95. },
  96. },
  97. ],
  98. {staleTime: 0}
  99. );
  100. const dashboardsPageLinks = getResponseHeader?.('Link') ?? '';
  101. function setRowsAndColumns(containerWidth: number) {
  102. const numWidgetsFitInRow = Math.floor(
  103. containerWidth / (MINIMUM_DASHBOARD_CARD_WIDTH + DASHBOARD_CARD_GRID_PADDING)
  104. );
  105. if (numWidgetsFitInRow >= 3) {
  106. setGridSize({
  107. rowCount: DASHBOARD_GRID_DEFAULT_NUM_ROWS,
  108. columnCount: numWidgetsFitInRow,
  109. });
  110. } else if (numWidgetsFitInRow === 0) {
  111. setGridSize({
  112. rowCount: DASHBOARD_GRID_DEFAULT_NUM_CARDS,
  113. columnCount: 1,
  114. });
  115. } else {
  116. setGridSize({
  117. rowCount: DASHBOARD_GRID_DEFAULT_NUM_CARDS / numWidgetsFitInRow,
  118. columnCount: numWidgetsFitInRow,
  119. });
  120. }
  121. }
  122. useEffect(() => {
  123. const dashboardGridObserver = new ResizeObserver(
  124. debounce(entries => {
  125. entries.forEach(entry => {
  126. const currentWidth = entry.contentRect.width;
  127. setRowsAndColumns(currentWidth);
  128. const paginationObject = parseLinkHeader(dashboardsPageLinks);
  129. if (
  130. dashboards?.length &&
  131. paginationObject.next.results &&
  132. rowCount * columnCount > dashboards.length
  133. ) {
  134. refetchDashboards();
  135. }
  136. });
  137. }, 10)
  138. );
  139. const currentDashboardGrid = dashboardGridRef.current;
  140. if (currentDashboardGrid) {
  141. dashboardGridObserver.observe(currentDashboardGrid);
  142. }
  143. return () => {
  144. if (currentDashboardGrid) {
  145. dashboardGridObserver.unobserve(currentDashboardGrid);
  146. }
  147. };
  148. }, [columnCount, dashboards?.length, dashboardsPageLinks, refetchDashboards, rowCount]);
  149. function getActiveSort() {
  150. const urlSort = decodeScalar(location.query.sort, 'mydashboards');
  151. return SORT_OPTIONS.find(item => item.value === urlSort) || SORT_OPTIONS[0];
  152. }
  153. function handleSearch(query: string) {
  154. trackAnalytics('dashboards_manage.search', {
  155. organization,
  156. });
  157. navigate({
  158. pathname: location.pathname,
  159. query: {...location.query, cursor: undefined, query},
  160. });
  161. }
  162. const handleSortChange = (value: string) => {
  163. trackAnalytics('dashboards_manage.change_sort', {
  164. organization,
  165. sort: value,
  166. });
  167. navigate({
  168. pathname: location.pathname,
  169. query: {
  170. ...location.query,
  171. cursor: undefined,
  172. sort: value,
  173. },
  174. });
  175. };
  176. const toggleTemplates = () => {
  177. trackAnalytics('dashboards_manage.templates.toggle', {
  178. organization,
  179. show_templates: !showTemplates,
  180. });
  181. setShowTemplatesLocal(!showTemplates);
  182. };
  183. function getQuery() {
  184. const {query} = location.query;
  185. return typeof query === 'string' ? query : undefined;
  186. }
  187. function renderTemplates() {
  188. return (
  189. <TemplateContainer>
  190. {getDashboardTemplates(organization).map(dashboard => (
  191. <TemplateCard
  192. title={dashboard.title}
  193. description={dashboard.description}
  194. onPreview={() => onPreview(dashboard.id)}
  195. onAdd={() => onAdd(dashboard)}
  196. key={dashboard.title}
  197. />
  198. ))}
  199. </TemplateContainer>
  200. );
  201. }
  202. function renderActions() {
  203. const activeSort = getActiveSort();
  204. return (
  205. <StyledActions>
  206. <SearchBar
  207. defaultQuery=""
  208. query={getQuery()}
  209. placeholder={t('Search Dashboards')}
  210. onSearch={query => handleSearch(query)}
  211. />
  212. <CompactSelect
  213. triggerProps={{prefix: t('Sort By')}}
  214. value={activeSort.value}
  215. options={SORT_OPTIONS}
  216. onChange={opt => handleSortChange(opt.value)}
  217. position="bottom-end"
  218. />
  219. </StyledActions>
  220. );
  221. }
  222. function renderNoAccess() {
  223. return (
  224. <Layout.Page>
  225. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  226. </Layout.Page>
  227. );
  228. }
  229. function renderDashboards() {
  230. return (
  231. <DashboardList
  232. api={api}
  233. dashboards={dashboards}
  234. organization={organization}
  235. location={location}
  236. onDashboardsChange={() => refetchDashboards()}
  237. isLoading={isLoading}
  238. rowCount={rowCount}
  239. columnCount={columnCount}
  240. />
  241. );
  242. }
  243. function renderPagination() {
  244. return (
  245. <PaginationRow
  246. pageLinks={dashboardsPageLinks}
  247. onCursor={(cursor, path, query, direction) => {
  248. const offset = Number(cursor?.split?.(':')?.[1] ?? 0);
  249. const newQuery: Query & {cursor?: string} = {...query, cursor};
  250. const isPrevious = direction === -1;
  251. if (offset <= 0 && isPrevious) {
  252. delete newQuery.cursor;
  253. }
  254. trackAnalytics('dashboards_manage.paginate', {organization});
  255. navigate({
  256. pathname: path,
  257. query: newQuery,
  258. });
  259. }}
  260. />
  261. );
  262. }
  263. function onCreate() {
  264. trackAnalytics('dashboards_manage.create.start', {
  265. organization,
  266. });
  267. navigate(
  268. normalizeUrl({
  269. pathname: `/organizations/${organization.slug}/dashboards/new/`,
  270. query: location.query,
  271. })
  272. );
  273. }
  274. async function onAdd(dashboard: DashboardDetails) {
  275. trackAnalytics('dashboards_manage.templates.add', {
  276. organization,
  277. dashboard_id: dashboard.id,
  278. dashboard_title: dashboard.title,
  279. was_previewed: false,
  280. });
  281. const newDashboard = await createDashboard(
  282. api,
  283. organization.slug,
  284. {
  285. ...dashboard,
  286. widgets: assignDefaultLayout(dashboard.widgets, getInitialColumnDepths()),
  287. },
  288. true
  289. );
  290. addSuccessMessage(`${dashboard.title} dashboard template successfully added.`);
  291. loadDashboard(newDashboard.id);
  292. }
  293. function loadDashboard(dashboardId: string) {
  294. navigate(
  295. normalizeUrl({
  296. pathname: `/organizations/${organization.slug}/dashboards/${dashboardId}/`,
  297. query: location.query,
  298. })
  299. );
  300. }
  301. function onPreview(dashboardId: string) {
  302. trackAnalytics('dashboards_manage.templates.preview', {
  303. organization,
  304. dashboard_id: dashboardId,
  305. });
  306. navigate(
  307. normalizeUrl({
  308. pathname: `/organizations/${organization.slug}/dashboards/new/${dashboardId}/`,
  309. query: location.query,
  310. })
  311. );
  312. }
  313. return (
  314. <Feature
  315. organization={organization}
  316. features="dashboards-edit"
  317. renderDisabled={renderNoAccess}
  318. >
  319. <SentryDocumentTitle title={t('Dashboards')} orgSlug={organization.slug}>
  320. <ErrorBoundary>
  321. {isError ? (
  322. <Layout.Page withPadding>
  323. <RouteError error={error} />
  324. </Layout.Page>
  325. ) : (
  326. <Layout.Page>
  327. <NoProjectMessage organization={organization}>
  328. <Layout.Header>
  329. <Layout.HeaderContent>
  330. <Layout.Title>
  331. {t('Dashboards')}
  332. <PageHeadingQuestionTooltip
  333. docsUrl="https://docs.sentry.io/product/dashboards/"
  334. title={t(
  335. 'A broad overview of your application’s health where you can navigate through error and performance data across multiple projects.'
  336. )}
  337. />
  338. </Layout.Title>
  339. </Layout.HeaderContent>
  340. <Layout.HeaderActions>
  341. <ButtonBar gap={1.5}>
  342. <TemplateSwitch>
  343. {t('Show Templates')}
  344. <Switch
  345. isActive={showTemplates}
  346. size="lg"
  347. toggle={toggleTemplates}
  348. />
  349. </TemplateSwitch>
  350. <FeedbackWidgetButton />
  351. <DashboardImportButton />
  352. <Button
  353. data-test-id="dashboard-create"
  354. onClick={event => {
  355. event.preventDefault();
  356. onCreate();
  357. }}
  358. size="sm"
  359. priority="primary"
  360. icon={<IconAdd isCircled />}
  361. >
  362. {t('Create Dashboard')}
  363. </Button>
  364. <Feature features="dashboards-import">
  365. <Button
  366. onClick={() => {
  367. openImportDashboardFromFileModal({
  368. organization,
  369. api,
  370. location,
  371. });
  372. }}
  373. size="sm"
  374. priority="primary"
  375. icon={<IconAdd isCircled />}
  376. >
  377. {t('Import Dashboard from JSON')}
  378. </Button>
  379. </Feature>
  380. </ButtonBar>
  381. </Layout.HeaderActions>
  382. </Layout.Header>
  383. <Layout.Body>
  384. <Layout.Main fullWidth>
  385. <MetricsRemovedAlertsWidgetsAlert organization={organization} />
  386. {showTemplates && renderTemplates()}
  387. {renderActions()}
  388. <div ref={dashboardGridRef} id="dashboard-list-container">
  389. {renderDashboards()}
  390. </div>
  391. {renderPagination()}
  392. </Layout.Main>
  393. </Layout.Body>
  394. </NoProjectMessage>
  395. </Layout.Page>
  396. )}
  397. </ErrorBoundary>
  398. </SentryDocumentTitle>
  399. </Feature>
  400. );
  401. }
  402. const StyledActions = styled('div')`
  403. display: grid;
  404. grid-template-columns: auto max-content;
  405. gap: ${space(2)};
  406. margin-bottom: ${space(2)};
  407. @media (max-width: ${p => p.theme.breakpoints.small}) {
  408. grid-template-columns: auto;
  409. }
  410. `;
  411. const TemplateSwitch = styled('label')`
  412. font-weight: ${p => p.theme.fontWeightNormal};
  413. font-size: ${p => p.theme.fontSizeLarge};
  414. display: flex;
  415. align-items: center;
  416. gap: ${space(1)};
  417. width: max-content;
  418. margin: 0;
  419. `;
  420. const TemplateContainer = styled('div')`
  421. display: grid;
  422. gap: ${space(2)};
  423. margin-bottom: ${space(0.5)};
  424. @media (min-width: ${p => p.theme.breakpoints.small}) {
  425. grid-template-columns: repeat(2, minmax(200px, 1fr));
  426. }
  427. @media (min-width: ${p => p.theme.breakpoints.large}) {
  428. grid-template-columns: repeat(4, minmax(200px, 1fr));
  429. }
  430. `;
  431. const PaginationRow = styled(Pagination)`
  432. margin-bottom: ${space(3)};
  433. `;
  434. export default ManageDashboards;