index.tsx 17 KB

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