index.tsx 21 KB

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