index.tsx 17 KB

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