index.tsx 17 KB

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