index.tsx 17 KB

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