1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
|
/*
* SonarQube
* Copyright (C) 2009-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import { CenteredLayout, Spinner } from 'design-system';
import { differenceBy } from 'lodash';
import * as React from 'react';
import { createPortal } from 'react-dom';
import { Helmet } from 'react-helmet-async';
import { Outlet } from 'react-router-dom';
import { useLocation, useRouter } from '~sonar-aligned/components/hoc/withRouter';
import { validateProjectAlmBinding } from '../../api/alm-settings';
import { getTasksForComponent } from '../../api/ce';
import { getComponentData } from '../../api/components';
import { getComponentNavigation } from '../../api/navigation';
import { translateWithParameters } from '../../helpers/l10n';
import { HttpStatus } from '../../helpers/request';
import { getPortfolioUrl, getProjectUrl, getPullRequestUrl } from '../../helpers/urls';
import { useBranchesQuery } from '../../queries/branch';
import { ProjectAlmBindingConfigurationErrors } from '../../types/alm-settings';
import { Branch } from '../../types/branch-like';
import { ComponentQualifier, isFile, isPortfolioLike } from '../../types/component';
import { Feature } from '../../types/features';
import { Task, TaskStatuses, TaskTypes } from '../../types/tasks';
import { Component } from '../../types/types';
import handleRequiredAuthorization from '../utils/handleRequiredAuthorization';
import ComponentContainerNotFound from './ComponentContainerNotFound';
import withAvailableFeatures, {
WithAvailableFeaturesProps,
} from './available-features/withAvailableFeatures';
import { ComponentContext } from './componentContext/ComponentContext';
import ComponentNav from './nav/component/ComponentNav';
const FETCH_STATUS_WAIT_TIME = 3000;
function ComponentContainer({ hasFeature }: Readonly<WithAvailableFeaturesProps>) {
const watchStatusTimer = React.useRef<number>();
const portalAnchor = React.useRef<Element | null>(null);
const oldTasksInProgress = React.useRef<Task[]>();
const oldCurrentTask = React.useRef<Task>();
const {
query: { id: key, branch, pullRequest, fixedInPullRequest },
pathname,
} = useLocation();
const router = useRouter();
const [component, setComponent] = React.useState<Component>();
const [currentTask, setCurrentTask] = React.useState<Task>();
const [tasksInProgress, setTasksInProgress] = React.useState<Task[]>();
const [projectBindingErrors, setProjectBindingErrors] =
React.useState<ProjectAlmBindingConfigurationErrors>();
const [loading, setLoading] = React.useState(true);
const [isPending, setIsPending] = React.useState(false);
const { data: { branchLike } = {}, isFetching } = useBranchesQuery(
fixedInPullRequest ? component : undefined,
);
const isInTutorials = pathname.includes('tutorials');
const fetchComponent = React.useCallback(
async (branchName?: string) => {
// Only show loader if we're changing components
if (component?.key !== key) {
setLoading(true);
}
let componentWithQualifier;
const targetBranch = branch ?? branchName;
try {
const [nav, { component }] = await Promise.all([
getComponentNavigation({ component: key, branch: targetBranch, pullRequest }),
getComponentData({ component: key, branch: targetBranch, pullRequest }),
]);
componentWithQualifier = addQualifier({ ...nav, ...component });
} catch (e) {
if (e instanceof Response && e.status === HttpStatus.Forbidden) {
handleRequiredAuthorization();
}
} finally {
setComponent(componentWithQualifier);
setLoading(false);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[key, branch, pullRequest],
);
const fetchStatus = React.useCallback(
async (componentKey: string) => {
try {
const { current, queue } = await getTasksForComponent(componentKey);
const newCurrentTask = getCurrentTask(current, branch, pullRequest, isInTutorials);
const pendingTasks = getReportRelatedPendingTasks(
queue,
branch,
pullRequest,
isInTutorials,
);
const newTasksInProgress = getInProgressTasks(pendingTasks);
const isPending = pendingTasks.some((task) => task.status === TaskStatuses.Pending);
setIsPending(isPending);
setCurrentTask(newCurrentTask);
setTasksInProgress(newTasksInProgress);
} catch {
// noop
}
},
[branch, isInTutorials, pullRequest],
);
const fetchProjectBindingErrors = React.useCallback(
async (component: Component) => {
if (
component.qualifier === ComponentQualifier.Project &&
component.analysisDate === undefined &&
hasFeature(Feature.BranchSupport)
) {
try {
const projectBindingErrors = await validateProjectAlmBinding(component.key);
setProjectBindingErrors(projectBindingErrors);
} catch {
// noop
}
}
},
[hasFeature],
);
const handleComponentChange = React.useCallback(
(changes: Partial<Component>) => {
if (!component) {
return;
}
setComponent({ ...component, ...changes });
},
[component],
);
React.useEffect(() => {
if (key) {
fetchComponent();
}
}, [key, fetchComponent]);
// Fetch status and errors when component has changed
React.useEffect(() => {
if (component) {
fetchStatus(component.key);
fetchProjectBindingErrors(component);
}
}, [component, fetchStatus, fetchProjectBindingErrors]);
// Refetch status when tasks in progress/current task have changed
// Or refetch component based on computeHasUpdatedTasks
React.useEffect(() => {
// Stop here if tasks are not fetched yet
if (!tasksInProgress) {
return;
}
const tasks = tasksInProgress ?? [];
const hasUpdatedTasks = computeHasUpdatedTasks(
oldTasksInProgress.current,
tasks,
oldCurrentTask.current,
currentTask,
component,
);
if (isInTutorials && hasUpdatedTasks) {
const { branch: branchName, pullRequest: pullRequestKey } = currentTask ?? tasks[0];
const url =
pullRequestKey !== undefined
? getPullRequestUrl(key, pullRequestKey)
: getProjectUrl(key, branchName);
router.replace(url);
}
if (needsAnotherCheck(hasUpdatedTasks, component, tasks)) {
// Refresh the status as long as there are tasks in progress or no analysis
window.clearTimeout(watchStatusTimer.current);
watchStatusTimer.current = window.setTimeout(() => {
fetchStatus(component?.key ?? '');
}, FETCH_STATUS_WAIT_TIME);
} else if (hasUpdatedTasks) {
fetchComponent();
}
oldCurrentTask.current = currentTask;
oldTasksInProgress.current = tasks;
}, [
component,
currentTask,
fetchComponent,
fetchStatus,
isInTutorials,
key,
router,
tasksInProgress,
]);
// Refetch component when a new branch is analyzed
React.useEffect(() => {
if (branchLike?.analysisDate && !component?.analysisDate) {
fetchComponent();
}
}, [branchLike, component, fetchComponent]);
// Refetch component when target branch for fixing pull request is fetched
React.useEffect(() => {
const branch = branchLike as Branch;
if (fixedInPullRequest && !isFetching && branch && component?.branch !== branch.name) {
fetchComponent(branch.name);
}
}, [fetchComponent, component, branchLike, fixedInPullRequest, isFetching]);
// Redirects
React.useEffect(() => {
/*
* There used to be a redirect from /dashboard to /portfolio which caused issues.
* Links should be fixed to not rely on this redirect, but:
* This is a fail-safe in case there are still some faulty links remaining.
*/
if (pathname.includes('dashboard') && component && isPortfolioLike(component.qualifier)) {
router.replace(getPortfolioUrl(component.key));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [component]);
// Set portal anchor on mount
React.useEffect(() => {
portalAnchor.current = document.querySelector('#component-nav-portal');
}, []);
const isInProgress = tasksInProgress && tasksInProgress.length > 0;
const componentProviderProps = React.useMemo(
() => ({
component,
currentTask,
isInProgress,
isPending,
onComponentChange: handleComponentChange,
fetchComponent,
}),
[component, currentTask, isInProgress, isPending, handleComponentChange, fetchComponent],
);
// Show not found component when, after loading:
// - component is not found
// - target branch is not found (for pull requests fixing issues in a branch)
if (!loading && (!component || (fixedInPullRequest && !isFetching && !branchLike))) {
return <ComponentContainerNotFound isPortfolioLike={pathname.includes('portfolio')} />;
}
return (
<div>
<Helmet
defer={false}
titleTemplate={translateWithParameters(
'page_title.template.with_instance',
component?.name ?? '',
)}
/>
{component &&
!isFile(component.qualifier) &&
portalAnchor.current &&
/* Use a portal to fix positioning until we can fully review the layout */
createPortal(
<ComponentNav
component={component}
isInProgress={isInProgress}
isPending={isPending}
projectBindingErrors={projectBindingErrors}
/>,
portalAnchor.current,
)}
{loading ? (
<CenteredLayout>
<Spinner className="sw-mt-10" />
</CenteredLayout>
) : (
<ComponentContext.Provider value={componentProviderProps}>
<Outlet />
</ComponentContext.Provider>
)}
</div>
);
}
function addQualifier(component: Component) {
return {
...component,
qualifier: component.breadcrumbs[component.breadcrumbs.length - 1].qualifier,
};
}
function needsAnotherCheck(
hasUpdatedTasks: boolean,
component: Component | undefined,
newTasksInProgress: Task[],
) {
return (
!hasUpdatedTasks && component && (newTasksInProgress.length > 0 || !component.analysisDate)
);
}
export function isSameBranch(
task: Pick<Task, 'branch' | 'pullRequest'>,
branch?: string,
pullRequest?: string,
) {
if (!branch?.length && !pullRequest?.length) {
return !task.branch && !task.pullRequest;
}
if (pullRequest?.length) {
return pullRequest === task.pullRequest;
}
return branch === task.branch;
}
function getCurrentTask(
current?: Task,
branch?: string,
pullRequest?: string,
canBeDifferentBranchLike = false,
) {
if (!current || !isReportRelatedTask(current)) {
return undefined;
}
return current.status === TaskStatuses.Failed ||
canBeDifferentBranchLike ||
isSameBranch(current, branch, pullRequest)
? current
: undefined;
}
function getReportRelatedPendingTasks(
pendingTasks: Task[],
branch?: string,
pullRequest?: string,
canBeDifferentBranchLike = false,
) {
return pendingTasks.filter(
(task) =>
isReportRelatedTask(task) &&
(canBeDifferentBranchLike || isSameBranch(task, branch, pullRequest)),
);
}
function getInProgressTasks(pendingTasks: Task[]) {
return pendingTasks.filter((task) => task.status === TaskStatuses.InProgress);
}
function isReportRelatedTask(task: Task) {
return [TaskTypes.AppRefresh, TaskTypes.Report, TaskTypes.ViewRefresh].includes(task.type);
}
function computeHasUpdatedTasks(
tasksInProgress: Task[] | undefined,
newTasksInProgress: Task[],
currentTask: Task | undefined,
newCurrentTask: Task | undefined,
component: Component | undefined,
) {
const progressHasChanged = Boolean(
tasksInProgress &&
(newTasksInProgress.length !== tasksInProgress.length ||
differenceBy(newTasksInProgress, tasksInProgress, 'id').length > 0),
);
const currentTaskHasChanged = Boolean(
(!currentTask && newCurrentTask) ||
(currentTask && newCurrentTask && currentTask.id !== newCurrentTask.id),
);
if (progressHasChanged) {
return true;
} else if (currentTaskHasChanged && component) {
// We return true if:
// - there was no prior analysis date (means this is an empty project, and
// a new analysis came in)
// - OR, there was a prior analysis date (non-empty project) AND there were
// some tasks in progress before
return (
Boolean(!component.analysisDate) || Boolean(component.analysisDate && tasksInProgress?.length)
);
}
return false;
}
export default withAvailableFeatures(ComponentContainer);
|