index.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. import {Fragment} from 'react';
  2. import {forceCheck} from 'react-lazyload';
  3. import {RouteComponentProps} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import pick from 'lodash/pick';
  6. import {fetchTagValues} from 'app/actionCreators/tags';
  7. import Feature from 'app/components/acl/feature';
  8. import Alert from 'app/components/alert';
  9. import {GuideAnchor} from 'app/components/assistant/guideAnchor';
  10. import EmptyStateWarning from 'app/components/emptyStateWarning';
  11. import LightWeightNoProjectMessage from 'app/components/lightWeightNoProjectMessage';
  12. import ExternalLink from 'app/components/links/externalLink';
  13. import LoadingIndicator from 'app/components/loadingIndicator';
  14. import GlobalSelectionHeader from 'app/components/organizations/globalSelectionHeader';
  15. import {getRelativeSummary} from 'app/components/organizations/timeRangeSelector/utils';
  16. import PageHeading from 'app/components/pageHeading';
  17. import Pagination from 'app/components/pagination';
  18. import SearchBar from 'app/components/searchBar';
  19. import SmartSearchBar from 'app/components/smartSearchBar';
  20. import {DEFAULT_STATS_PERIOD, RELEASE_ADOPTION_STAGES} from 'app/constants';
  21. import {ALL_ACCESS_PROJECTS} from 'app/constants/globalSelectionHeader';
  22. import {desktop, mobile, PlatformKey, releaseHealth} from 'app/data/platformCategories';
  23. import {IconInfo} from 'app/icons';
  24. import {t} from 'app/locale';
  25. import {PageContent, PageHeader} from 'app/styles/organization';
  26. import space from 'app/styles/space';
  27. import {
  28. GlobalSelection,
  29. Organization,
  30. Project,
  31. Release,
  32. ReleaseStatus,
  33. SessionApiResponse,
  34. Tag,
  35. } from 'app/types';
  36. import {trackAnalyticsEvent} from 'app/utils/analytics';
  37. import Projects from 'app/utils/projects';
  38. import routeTitleGen from 'app/utils/routeTitle';
  39. import withGlobalSelection from 'app/utils/withGlobalSelection';
  40. import withOrganization from 'app/utils/withOrganization';
  41. import AsyncView from 'app/views/asyncView';
  42. import ReleaseArchivedNotice from '../detail/overview/releaseArchivedNotice';
  43. import ReleaseHealthRequest from '../utils/releaseHealthRequest';
  44. import ReleaseAdoptionChart from './releaseAdoptionChart';
  45. import ReleaseCard from './releaseCard';
  46. import ReleaseDisplayOptions from './releaseDisplayOptions';
  47. import ReleaseListSortOptions from './releaseListSortOptions';
  48. import ReleaseListStatusOptions from './releaseListStatusOptions';
  49. import ReleasePromo from './releasePromo';
  50. import {DisplayOption, SortOption, StatusOption} from './utils';
  51. const supportedTags = {
  52. 'release.version': {
  53. key: 'release.version',
  54. name: 'release.version',
  55. },
  56. 'release.build': {
  57. key: 'release.build',
  58. name: 'release.build',
  59. },
  60. 'release.package': {
  61. key: 'release.package',
  62. name: 'release.package',
  63. },
  64. 'release.stage': {
  65. key: 'release.stage',
  66. name: 'release.stage',
  67. predefined: true,
  68. values: RELEASE_ADOPTION_STAGES,
  69. },
  70. release: {
  71. key: 'release',
  72. name: 'release',
  73. },
  74. };
  75. export const isProjectMobileForReleases = (projectPlatform: PlatformKey) =>
  76. (
  77. [...mobile, ...desktop, 'java-android', 'cocoa-objc', 'cocoa-swift'] as string[]
  78. ).includes(projectPlatform);
  79. type RouteParams = {
  80. orgId: string;
  81. };
  82. type Props = RouteComponentProps<RouteParams, {}> & {
  83. organization: Organization;
  84. selection: GlobalSelection;
  85. };
  86. type State = {
  87. releases: Release[];
  88. hasSessions: boolean | null;
  89. } & AsyncView['state'];
  90. class ReleasesList extends AsyncView<Props, State> {
  91. shouldReload = true;
  92. shouldRenderBadRequests = true;
  93. getTitle() {
  94. return routeTitleGen(t('Releases'), this.props.organization.slug, false);
  95. }
  96. getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
  97. const {organization, location} = this.props;
  98. const {statsPeriod} = location.query;
  99. const activeSort = this.getSort();
  100. const activeStatus = this.getStatus();
  101. const query = {
  102. ...pick(location.query, ['project', 'environment', 'cursor', 'query', 'sort']),
  103. summaryStatsPeriod: statsPeriod,
  104. per_page: 20,
  105. flatten: activeSort === SortOption.DATE ? 0 : 1,
  106. adoptionStages: 1,
  107. status:
  108. activeStatus === StatusOption.ARCHIVED
  109. ? ReleaseStatus.Archived
  110. : ReleaseStatus.Active,
  111. };
  112. const endpoints: ReturnType<AsyncView['getEndpoints']> = [
  113. [
  114. 'releases',
  115. `/organizations/${organization.slug}/releases/`,
  116. {query},
  117. {disableEntireQuery: true},
  118. ],
  119. ];
  120. return endpoints;
  121. }
  122. componentDidMount() {
  123. if (this.props.location.query.project) {
  124. this.fetchSessionsExistence();
  125. }
  126. }
  127. componentDidUpdate(prevProps: Props, prevState: State) {
  128. super.componentDidUpdate(prevProps, prevState);
  129. if (prevProps.location.query.project !== this.props.location.query.project) {
  130. this.fetchSessionsExistence();
  131. }
  132. if (prevState.releases !== this.state.releases) {
  133. /**
  134. * Manually trigger checking for elements in viewport.
  135. * Helpful when LazyLoad components enter the viewport without resize or scroll events,
  136. * https://github.com/twobin/react-lazyload#forcecheck
  137. *
  138. * HealthStatsCharts are being rendered only when they are scrolled into viewport.
  139. * This is how we re-check them without scrolling once releases change as this view
  140. * uses shouldReload=true and there is no reloading happening.
  141. */
  142. forceCheck();
  143. }
  144. }
  145. getQuery() {
  146. const {query} = this.props.location.query;
  147. return typeof query === 'string' ? query : undefined;
  148. }
  149. getSort(): SortOption {
  150. const {sort} = this.props.location.query;
  151. switch (sort) {
  152. case SortOption.CRASH_FREE_USERS:
  153. return SortOption.CRASH_FREE_USERS;
  154. case SortOption.CRASH_FREE_SESSIONS:
  155. return SortOption.CRASH_FREE_SESSIONS;
  156. case SortOption.SESSIONS:
  157. return SortOption.SESSIONS;
  158. case SortOption.USERS_24_HOURS:
  159. return SortOption.USERS_24_HOURS;
  160. case SortOption.SESSIONS_24_HOURS:
  161. return SortOption.SESSIONS_24_HOURS;
  162. case SortOption.BUILD:
  163. return SortOption.BUILD;
  164. case SortOption.SEMVER:
  165. return SortOption.SEMVER;
  166. case SortOption.ADOPTION:
  167. return SortOption.ADOPTION;
  168. default:
  169. return SortOption.DATE;
  170. }
  171. }
  172. getDisplay(): DisplayOption {
  173. const {display} = this.props.location.query;
  174. switch (display) {
  175. case DisplayOption.USERS:
  176. return DisplayOption.USERS;
  177. default:
  178. return DisplayOption.SESSIONS;
  179. }
  180. }
  181. getStatus(): StatusOption {
  182. const {status} = this.props.location.query;
  183. switch (status) {
  184. case StatusOption.ARCHIVED:
  185. return StatusOption.ARCHIVED;
  186. default:
  187. return StatusOption.ACTIVE;
  188. }
  189. }
  190. getSelectedProject(): Project | undefined {
  191. const {selection, organization} = this.props;
  192. const selectedProjectId =
  193. selection.projects && selection.projects.length === 1 && selection.projects[0];
  194. return organization.projects?.find(p => p.id === `${selectedProjectId}`);
  195. }
  196. async fetchSessionsExistence() {
  197. const {organization, location} = this.props;
  198. const projectId = location.query.project;
  199. if (!projectId) {
  200. return;
  201. }
  202. this.setState({
  203. hasSessions: null,
  204. });
  205. try {
  206. const response: SessionApiResponse = await this.api.requestPromise(
  207. `/organizations/${organization.slug}/sessions/`,
  208. {
  209. query: {
  210. project: projectId,
  211. field: 'sum(session)',
  212. statsPeriod: '90d',
  213. interval: '1d',
  214. },
  215. }
  216. );
  217. this.setState({
  218. hasSessions: response.groups[0].totals['sum(session)'] > 0,
  219. });
  220. } catch {
  221. // do nothing
  222. }
  223. }
  224. handleSearch = (query: string) => {
  225. const {location, router} = this.props;
  226. router.push({
  227. ...location,
  228. query: {...location.query, cursor: undefined, query},
  229. });
  230. };
  231. handleSortBy = (sort: string) => {
  232. const {location, router} = this.props;
  233. router.push({
  234. ...location,
  235. query: {...location.query, cursor: undefined, sort},
  236. });
  237. };
  238. handleDisplay = (display: string) => {
  239. const {location, router} = this.props;
  240. let sort = location.query.sort;
  241. if (sort === SortOption.USERS_24_HOURS && display === DisplayOption.SESSIONS)
  242. sort = SortOption.SESSIONS_24_HOURS;
  243. else if (sort === SortOption.SESSIONS_24_HOURS && display === DisplayOption.USERS)
  244. sort = SortOption.USERS_24_HOURS;
  245. else if (sort === SortOption.CRASH_FREE_USERS && display === DisplayOption.SESSIONS)
  246. sort = SortOption.CRASH_FREE_SESSIONS;
  247. else if (sort === SortOption.CRASH_FREE_SESSIONS && display === DisplayOption.USERS)
  248. sort = SortOption.CRASH_FREE_USERS;
  249. router.push({
  250. ...location,
  251. query: {...location.query, cursor: undefined, display, sort},
  252. });
  253. };
  254. handleStatus = (status: string) => {
  255. const {location, router} = this.props;
  256. router.push({
  257. ...location,
  258. query: {...location.query, cursor: undefined, status},
  259. });
  260. };
  261. trackAddReleaseHealth = () => {
  262. const {organization, selection} = this.props;
  263. if (organization.id && selection.projects[0]) {
  264. trackAnalyticsEvent({
  265. eventKey: `releases_list.click_add_release_health`,
  266. eventName: `Releases List: Click Add Release Health`,
  267. organization_id: parseInt(organization.id, 10),
  268. project_id: selection.projects[0],
  269. });
  270. }
  271. };
  272. tagValueLoader = (key: string, search: string) => {
  273. const {location, organization} = this.props;
  274. const {project: projectId} = location.query;
  275. return fetchTagValues(
  276. this.api,
  277. organization.slug,
  278. key,
  279. search,
  280. projectId ? [projectId] : null,
  281. location.query
  282. );
  283. };
  284. getTagValues = async (tag: Tag, currentQuery: string): Promise<string[]> => {
  285. const values = await this.tagValueLoader(tag.key, currentQuery);
  286. return values.map(({value}) => value);
  287. };
  288. shouldShowLoadingIndicator() {
  289. const {loading, releases, reloading} = this.state;
  290. return (loading && !reloading) || (loading && !releases?.length);
  291. }
  292. renderLoading() {
  293. return this.renderBody();
  294. }
  295. renderError() {
  296. return this.renderBody();
  297. }
  298. renderEmptyMessage() {
  299. const {location, organization, selection} = this.props;
  300. const {statsPeriod} = location.query;
  301. const searchQuery = this.getQuery();
  302. const activeSort = this.getSort();
  303. const activeStatus = this.getStatus();
  304. if (searchQuery && searchQuery.length) {
  305. return (
  306. <EmptyStateWarning small>{`${t(
  307. 'There are no releases that match'
  308. )}: '${searchQuery}'.`}</EmptyStateWarning>
  309. );
  310. }
  311. if (activeSort === SortOption.USERS_24_HOURS) {
  312. return (
  313. <EmptyStateWarning small>
  314. {t('There are no releases with active user data (users in the last 24 hours).')}
  315. </EmptyStateWarning>
  316. );
  317. }
  318. if (activeSort === SortOption.SESSIONS_24_HOURS) {
  319. return (
  320. <EmptyStateWarning small>
  321. {t(
  322. 'There are no releases with active session data (sessions in the last 24 hours).'
  323. )}
  324. </EmptyStateWarning>
  325. );
  326. }
  327. if (activeSort === SortOption.BUILD || activeSort === SortOption.SEMVER) {
  328. return (
  329. <EmptyStateWarning small>
  330. {t('There are no releases with semantic versioning.')}
  331. </EmptyStateWarning>
  332. );
  333. }
  334. if (activeSort !== SortOption.DATE) {
  335. const relativePeriod = getRelativeSummary(
  336. statsPeriod || DEFAULT_STATS_PERIOD
  337. ).toLowerCase();
  338. return (
  339. <EmptyStateWarning small>
  340. {`${t('There are no releases with data in the')} ${relativePeriod}.`}
  341. </EmptyStateWarning>
  342. );
  343. }
  344. if (activeStatus === StatusOption.ARCHIVED) {
  345. return (
  346. <EmptyStateWarning small>
  347. {t('There are no archived releases.')}
  348. </EmptyStateWarning>
  349. );
  350. }
  351. return (
  352. <ReleasePromo
  353. organization={organization}
  354. projectId={selection.projects.filter(p => p !== ALL_ACCESS_PROJECTS)[0]}
  355. />
  356. );
  357. }
  358. renderHealthCta() {
  359. const {organization} = this.props;
  360. const {hasSessions, releases} = this.state;
  361. const selectedProject = this.getSelectedProject();
  362. if (!selectedProject || hasSessions !== false || !releases?.length) {
  363. return null;
  364. }
  365. return (
  366. <Projects orgId={organization.slug} slugs={[selectedProject.slug]}>
  367. {({projects, initiallyLoaded, fetchError}) => {
  368. const project = projects && projects.length === 1 && projects[0];
  369. const projectCanHaveReleases =
  370. project && project.platform && releaseHealth.includes(project.platform);
  371. if (!initiallyLoaded || fetchError || !projectCanHaveReleases) {
  372. return null;
  373. }
  374. return (
  375. <Alert type="info" icon={<IconInfo size="md" />}>
  376. <AlertText>
  377. <div>
  378. {t(
  379. 'To track user adoption, crash rates, session data and more, add Release Health to your current setup.'
  380. )}
  381. </div>
  382. <ExternalLink
  383. href="https://docs.sentry.io/product/releases/health/setup/"
  384. onClick={this.trackAddReleaseHealth}
  385. >
  386. {t('Add Release Health')}
  387. </ExternalLink>
  388. </AlertText>
  389. </Alert>
  390. );
  391. }}
  392. </Projects>
  393. );
  394. }
  395. renderInnerBody(activeDisplay: DisplayOption) {
  396. const {location, selection, organization, router} = this.props;
  397. const {hasSessions, releases, reloading, releasesPageLinks} = this.state;
  398. if (this.shouldShowLoadingIndicator()) {
  399. return <LoadingIndicator />;
  400. }
  401. if (!releases?.length) {
  402. return this.renderEmptyMessage();
  403. }
  404. return (
  405. <ReleaseHealthRequest
  406. releases={releases.map(({version}) => version)}
  407. organization={organization}
  408. selection={selection}
  409. location={location}
  410. display={[this.getDisplay()]}
  411. releasesReloading={reloading}
  412. healthStatsPeriod={location.query.healthStatsPeriod}
  413. >
  414. {({isHealthLoading, getHealthData}) => {
  415. const singleProjectSelected =
  416. selection.projects?.length === 1 &&
  417. selection.projects[0] !== ALL_ACCESS_PROJECTS;
  418. const selectedProject = this.getSelectedProject();
  419. const isMobileProject =
  420. selectedProject?.platform &&
  421. isProjectMobileForReleases(selectedProject.platform);
  422. return (
  423. <Fragment>
  424. {singleProjectSelected && hasSessions && isMobileProject && (
  425. <Feature features={['organizations:release-adoption-chart']}>
  426. <ReleaseAdoptionChart
  427. organization={organization}
  428. selection={selection}
  429. location={location}
  430. router={router}
  431. activeDisplay={activeDisplay}
  432. />
  433. </Feature>
  434. )}
  435. {releases.map((release, index) => (
  436. <ReleaseCard
  437. key={`${release.version}-${release.projects[0].slug}`}
  438. activeDisplay={activeDisplay}
  439. release={release}
  440. organization={organization}
  441. location={location}
  442. selection={selection}
  443. reloading={reloading}
  444. showHealthPlaceholders={isHealthLoading}
  445. isTopRelease={index === 0}
  446. getHealthData={getHealthData}
  447. />
  448. ))}
  449. <Pagination pageLinks={releasesPageLinks} />
  450. </Fragment>
  451. );
  452. }}
  453. </ReleaseHealthRequest>
  454. );
  455. }
  456. renderBody() {
  457. const {organization} = this.props;
  458. const {releases, reloading, error} = this.state;
  459. const activeSort = this.getSort();
  460. const activeStatus = this.getStatus();
  461. const activeDisplay = this.getDisplay();
  462. const hasSemver = organization.features.includes('semver');
  463. return (
  464. <GlobalSelectionHeader
  465. showAbsolute={false}
  466. timeRangeHint={t(
  467. 'Changing this date range will recalculate the release metrics.'
  468. )}
  469. >
  470. <PageContent>
  471. <LightWeightNoProjectMessage organization={organization}>
  472. <PageHeader>
  473. <PageHeading>{t('Releases')}</PageHeading>
  474. </PageHeader>
  475. {this.renderHealthCta()}
  476. <SortAndFilterWrapper>
  477. {hasSemver ? (
  478. <GuideAnchor target="releases_search" position="bottom">
  479. <SmartSearchBar
  480. searchSource="releases"
  481. query={this.getQuery()}
  482. placeholder={t('Search by release version')}
  483. maxSearchItems={5}
  484. hasRecentSearches={false}
  485. supportedTags={supportedTags}
  486. onSearch={this.handleSearch}
  487. onGetTagValues={this.getTagValues}
  488. />
  489. </GuideAnchor>
  490. ) : (
  491. <SearchBar
  492. placeholder={t('Search')}
  493. onSearch={this.handleSearch}
  494. query={this.getQuery()}
  495. />
  496. )}
  497. <DropdownsWrapper>
  498. <ReleaseListStatusOptions
  499. selected={activeStatus}
  500. onSelect={this.handleStatus}
  501. />
  502. <ReleaseListSortOptions
  503. selected={activeSort}
  504. selectedDisplay={activeDisplay}
  505. onSelect={this.handleSortBy}
  506. organization={organization}
  507. />
  508. <ReleaseDisplayOptions
  509. selected={activeDisplay}
  510. onSelect={this.handleDisplay}
  511. />
  512. </DropdownsWrapper>
  513. </SortAndFilterWrapper>
  514. {!reloading &&
  515. activeStatus === StatusOption.ARCHIVED &&
  516. !!releases?.length && <ReleaseArchivedNotice multi />}
  517. {error
  518. ? super.renderError(new Error('Unable to load all required endpoints'))
  519. : this.renderInnerBody(activeDisplay)}
  520. </LightWeightNoProjectMessage>
  521. </PageContent>
  522. </GlobalSelectionHeader>
  523. );
  524. }
  525. }
  526. const AlertText = styled('div')`
  527. display: flex;
  528. align-items: flex-start;
  529. justify-content: flex-start;
  530. gap: ${space(2)};
  531. > *:nth-child(1) {
  532. flex: 1;
  533. }
  534. flex-direction: column;
  535. @media (min-width: ${p => p.theme.breakpoints[1]}) {
  536. flex-direction: row;
  537. }
  538. `;
  539. const SortAndFilterWrapper = styled('div')`
  540. display: flex;
  541. flex-direction: column;
  542. justify-content: stretch;
  543. margin-bottom: ${space(2)};
  544. > *:nth-child(1) {
  545. flex: 1;
  546. }
  547. /* Below this width search bar needs its own row no to wrap placeholder text
  548. * Above this width search bar and controls can be on the same row */
  549. @media (min-width: ${p => p.theme.breakpoints[2]}) {
  550. flex-direction: row;
  551. }
  552. `;
  553. const DropdownsWrapper = styled('div')`
  554. display: flex;
  555. flex-direction: column;
  556. & > * {
  557. margin-top: ${space(2)};
  558. }
  559. /* At the narrower widths wrapper is on its own in a row
  560. * Expand the dropdown controls to fill the empty space */
  561. & button {
  562. width: 100%;
  563. }
  564. /* At narrower widths space bar needs a separate row
  565. * Divide space evenly when 3 dropdowns are in their own row */
  566. @media (min-width: ${p => p.theme.breakpoints[0]}) {
  567. margin-top: ${space(2)};
  568. & > * {
  569. margin-top: ${space(0)};
  570. margin-left: ${space(2)};
  571. }
  572. & > *:nth-child(1) {
  573. margin-left: ${space(0)};
  574. }
  575. display: grid;
  576. grid-template-columns: 1fr 1fr 1fr;
  577. }
  578. /* At wider widths everything is in 1 row
  579. * Auto space dropdowns when they are in the same row with search bar */
  580. @media (min-width: ${p => p.theme.breakpoints[2]}) {
  581. margin-top: ${space(0)};
  582. & > * {
  583. margin-left: ${space(2)} !important;
  584. }
  585. display: grid;
  586. grid-template-columns: auto auto auto;
  587. }
  588. `;
  589. export default withOrganization(withGlobalSelection(ReleasesList));
  590. export {ReleasesList};