You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AllProjects.tsx 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. import styled from '@emotion/styled';
  21. import { Spinner } from '@sonarsource/echoes-react';
  22. import {
  23. LAYOUT_FOOTER_HEIGHT,
  24. LargeCenteredLayout,
  25. PageContentFontWrapper,
  26. themeBorder,
  27. themeColor,
  28. } from 'design-system';
  29. import { keyBy, mapValues, omitBy, pick } from 'lodash';
  30. import * as React from 'react';
  31. import { Helmet } from 'react-helmet-async';
  32. import { useSearchParams } from 'react-router-dom';
  33. import { searchProjects } from '../../../api/components';
  34. import withAppStateContext from '../../../app/components/app-state/withAppStateContext';
  35. import withCurrentUserContext from '../../../app/components/current-user/withCurrentUserContext';
  36. import A11ySkipTarget from '../../../components/a11y/A11ySkipTarget';
  37. import ScreenPositionHelper from '../../../components/common/ScreenPositionHelper';
  38. import Suggestions from '../../../components/embed-docs-modal/Suggestions';
  39. import { Location, Router, withRouter } from '../../../components/hoc/withRouter';
  40. import '../../../components/search-navigator.css';
  41. import handleRequiredAuthentication from '../../../helpers/handleRequiredAuthentication';
  42. import { translate } from '../../../helpers/l10n';
  43. import { addSideBarClass, removeSideBarClass } from '../../../helpers/pages';
  44. import { get, save } from '../../../helpers/storage';
  45. import { isDefined } from '../../../helpers/types';
  46. import { AppState } from '../../../types/appstate';
  47. import { ComponentQualifier } from '../../../types/component';
  48. import { MetricKey } from '../../../types/metrics';
  49. import { RawQuery } from '../../../types/types';
  50. import { CurrentUser, isLoggedIn } from '../../../types/users';
  51. import { Query, hasFilterParams, parseUrlQuery } from '../query';
  52. import '../styles.css';
  53. import { Facets, Project } from '../types';
  54. import { SORTING_SWITCH, convertToQueryData, fetchProjects, parseSorting } from '../utils';
  55. import PageHeader from './PageHeader';
  56. import PageSidebar from './PageSidebar';
  57. import ProjectsList from './ProjectsList';
  58. interface Props {
  59. appState: AppState;
  60. currentUser: CurrentUser;
  61. isFavorite: boolean;
  62. location: Location;
  63. router: Router;
  64. }
  65. interface State {
  66. facets?: Facets;
  67. loading: boolean;
  68. pageIndex?: number;
  69. projects?: Project[];
  70. query: Query;
  71. total?: number;
  72. }
  73. export const LS_PROJECTS_SORT = 'sonarqube.projects.sort';
  74. export const LS_PROJECTS_VIEW = 'sonarqube.projects.view';
  75. export class AllProjects extends React.PureComponent<Props, State> {
  76. mounted = false;
  77. constructor(props: Props) {
  78. super(props);
  79. this.state = { loading: true, query: {} };
  80. }
  81. componentDidMount() {
  82. this.mounted = true;
  83. if (this.props.isFavorite && !isLoggedIn(this.props.currentUser)) {
  84. handleRequiredAuthentication();
  85. return;
  86. }
  87. this.handleQueryChange();
  88. addSideBarClass();
  89. }
  90. componentDidUpdate(prevProps: Props) {
  91. if (prevProps.location.query !== this.props.location.query) {
  92. this.handleQueryChange();
  93. }
  94. }
  95. componentWillUnmount() {
  96. this.mounted = false;
  97. removeSideBarClass();
  98. }
  99. fetchMoreProjects = () => {
  100. const { isFavorite } = this.props;
  101. const { pageIndex, projects, query } = this.state;
  102. if (pageIndex && projects && Object.keys(query).length !== 0) {
  103. this.setState({ loading: true });
  104. fetchProjects({ isFavorite, query, pageIndex: pageIndex + 1 }).then((response) => {
  105. if (this.mounted) {
  106. this.setState({
  107. loading: false,
  108. pageIndex: pageIndex + 1,
  109. projects: [...projects, ...response.projects],
  110. });
  111. }
  112. }, this.stopLoading);
  113. }
  114. };
  115. getSort = () => this.state.query.sort ?? 'name';
  116. getView = () => this.state.query.view ?? 'overall';
  117. handleClearAll = () => {
  118. const { pathname, query } = this.props.location;
  119. const queryWithoutFilters = pick(query, ['view', 'sort']);
  120. this.props.router.push({ pathname, query: queryWithoutFilters });
  121. };
  122. handleFavorite = (key: string, isFavorite: boolean) => {
  123. this.setState(({ projects }) => {
  124. if (!projects) {
  125. return null;
  126. }
  127. return {
  128. projects: projects.map((p) => (p.key === key ? { ...p, isFavorite } : p)),
  129. };
  130. });
  131. };
  132. handlePerspectiveChange = ({ view }: { view?: string }) => {
  133. const query: {
  134. view: string | undefined;
  135. sort?: string;
  136. } = {
  137. view: view === 'overall' ? undefined : view,
  138. };
  139. if (this.state.query.view === 'leak' || view === 'leak') {
  140. if (isDefined(this.state.query.sort)) {
  141. const sort = parseSorting(this.state.query.sort);
  142. if (isDefined(SORTING_SWITCH[sort.sortValue])) {
  143. query.sort = (sort.sortDesc ? '-' : '') + SORTING_SWITCH[sort.sortValue];
  144. }
  145. }
  146. this.props.router.push({ pathname: this.props.location.pathname, query });
  147. } else {
  148. this.updateLocationQuery(query);
  149. }
  150. save(LS_PROJECTS_SORT, query.sort);
  151. save(LS_PROJECTS_VIEW, query.view);
  152. };
  153. handleQueryChange() {
  154. const { isFavorite } = this.props;
  155. const queryRaw = this.props.location.query;
  156. const query = parseUrlQuery(queryRaw);
  157. this.setState({ loading: true, query });
  158. fetchProjects({ isFavorite, query }).then((response) => {
  159. // We ignore the request if the query changed since the time it was initiated
  160. // If that happened, another query will be initiated anyway
  161. if (this.mounted && queryRaw === this.props.location.query) {
  162. this.setState({
  163. facets: response.facets,
  164. loading: false,
  165. pageIndex: 1,
  166. projects: response.projects,
  167. total: response.total,
  168. });
  169. }
  170. }, this.stopLoading);
  171. }
  172. handleSortChange = (sort: string, desc: boolean) => {
  173. const asString = (desc ? '-' : '') + sort;
  174. this.updateLocationQuery({ sort: asString });
  175. save(LS_PROJECTS_SORT, asString);
  176. };
  177. loadSearchResultCount = (property: string, values: string[]) => {
  178. const { isFavorite } = this.props;
  179. const { query = {} } = this.state;
  180. const data = convertToQueryData({ ...query, [property]: values }, isFavorite, {
  181. ps: 1,
  182. facets: property,
  183. });
  184. return searchProjects(data).then(({ facets }) => {
  185. const values = facets.find((facet) => facet.property === property)?.values ?? [];
  186. return mapValues(keyBy(values, 'val'), 'count');
  187. });
  188. };
  189. stopLoading = () => {
  190. if (this.mounted) {
  191. this.setState({ loading: false });
  192. }
  193. };
  194. updateLocationQuery = (newQuery: RawQuery) => {
  195. const query = omitBy({ ...this.props.location.query, ...newQuery }, (x) => !x);
  196. this.props.router.push({ pathname: this.props.location.pathname, query });
  197. };
  198. renderSide = () => (
  199. <SideBarStyle>
  200. <ScreenPositionHelper className="sw-z-filterbar">
  201. {({ top }) => (
  202. <section
  203. aria-label={translate('filters')}
  204. className="sw-overflow-y-auto project-filters-list"
  205. style={{ height: `calc((100vh - ${top}px) - ${LAYOUT_FOOTER_HEIGHT}px)` }}
  206. >
  207. <div className="sw-w-[300px] lg:sw-w-[390px]">
  208. <A11ySkipTarget
  209. anchor="projects_filters"
  210. label={translate('projects.skip_to_filters')}
  211. weight={10}
  212. />
  213. <PageSidebar
  214. applicationsEnabled={this.props.appState.qualifiers.includes(
  215. ComponentQualifier.Application,
  216. )}
  217. facets={this.state.facets}
  218. loadSearchResultCount={this.loadSearchResultCount}
  219. onClearAll={this.handleClearAll}
  220. onQueryChange={this.updateLocationQuery}
  221. query={this.state.query}
  222. view={this.getView()}
  223. />
  224. </div>
  225. </section>
  226. )}
  227. </ScreenPositionHelper>
  228. </SideBarStyle>
  229. );
  230. renderHeader = () => (
  231. <PageHeaderWrapper className="sw-w-full">
  232. <PageHeader
  233. currentUser={this.props.currentUser}
  234. onPerspectiveChange={this.handlePerspectiveChange}
  235. onQueryChange={this.updateLocationQuery}
  236. onSortChange={this.handleSortChange}
  237. query={this.state.query}
  238. selectedSort={this.getSort()}
  239. total={this.state.total}
  240. view={this.getView()}
  241. />
  242. </PageHeaderWrapper>
  243. );
  244. renderMain = () => {
  245. if (this.state.loading && this.state.projects === undefined) {
  246. return <Spinner />;
  247. }
  248. return (
  249. <div className="it__layout-page-main-inner it__projects-list sw-h-full">
  250. {this.state.projects && (
  251. <ProjectsList
  252. cardType={this.getView()}
  253. currentUser={this.props.currentUser}
  254. handleFavorite={this.handleFavorite}
  255. isFavorite={this.props.isFavorite}
  256. isFiltered={hasFilterParams(this.state.query)}
  257. loading={this.state.loading}
  258. loadMore={this.fetchMoreProjects}
  259. projects={this.state.projects}
  260. query={this.state.query}
  261. total={this.state.total}
  262. />
  263. )}
  264. </div>
  265. );
  266. };
  267. render() {
  268. return (
  269. <StyledWrapper id="projects-page">
  270. <Suggestions suggestions={MetricKey.projects} />
  271. <Helmet defer={false} title={translate('projects.page')} />
  272. <h1 className="sw-sr-only">{translate('projects.page')}</h1>
  273. <LargeCenteredLayout>
  274. <PageContentFontWrapper className="sw-flex sw-w-full sw-body-md">
  275. {this.renderSide()}
  276. <div
  277. role="main"
  278. className="sw-flex sw-flex-col sw-box-border sw-min-w-0 sw-pl-12 sw-pt-6 sw-flex-1"
  279. >
  280. <A11ySkipTarget anchor="projects_main" />
  281. <h2 className="sw-sr-only">{translate('list_of_projects')}</h2>
  282. {this.renderHeader()}
  283. {this.renderMain()}
  284. </div>
  285. </PageContentFontWrapper>
  286. </LargeCenteredLayout>
  287. </StyledWrapper>
  288. );
  289. }
  290. }
  291. function getStorageOptions() {
  292. const options: {
  293. sort?: string;
  294. view?: string;
  295. } = {};
  296. if (get(LS_PROJECTS_SORT) !== null) {
  297. options.sort = get(LS_PROJECTS_SORT) ?? undefined;
  298. }
  299. if (get(LS_PROJECTS_VIEW) !== null) {
  300. options.view = get(LS_PROJECTS_VIEW) ?? undefined;
  301. }
  302. return options;
  303. }
  304. function SetSearchParamsWrapper(props: Readonly<Props>) {
  305. const [searchParams, setSearchParams] = useSearchParams();
  306. const savedOptions = getStorageOptions();
  307. React.useEffect(
  308. () => {
  309. const hasViewParams = searchParams.get('sort') ?? searchParams.get('view');
  310. const hasSavedOptions = savedOptions.sort ?? savedOptions.view;
  311. if (!isDefined(hasViewParams) && isDefined(hasSavedOptions)) {
  312. setSearchParams(savedOptions);
  313. }
  314. },
  315. // eslint-disable-next-line react-hooks/exhaustive-deps
  316. [
  317. /* Run once on mount only */
  318. ],
  319. );
  320. return <AllProjects {...props} />;
  321. }
  322. export default withRouter(withCurrentUserContext(withAppStateContext(SetSearchParamsWrapper)));
  323. const StyledWrapper = styled.div`
  324. background-color: ${themeColor('backgroundPrimary')};
  325. `;
  326. const SideBarStyle = styled.div`
  327. border-left: ${themeBorder('default', 'filterbarBorder')};
  328. border-right: ${themeBorder('default', 'filterbarBorder')};
  329. background-color: ${themeColor('backgroundSecondary')};
  330. `;
  331. const PageHeaderWrapper = styled.div`
  332. height: 7.5rem;
  333. border-bottom: ${themeBorder('default', 'filterbarBorder')};
  334. `;