-
Notifications
You must be signed in to change notification settings - Fork 633
/
build-view.jsx
378 lines (349 loc) · 13.5 KB
/
build-view.jsx
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
/**
* @license Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
import {h, Fragment} from 'preact';
import _ from '@lhci/utils/src/lodash';
import {useState, useMemo, useCallback, useEffect} from 'preact/hooks';
import {AsyncLoader, combineLoadingStates, combineAsyncData} from '../../components/async-loader';
import {Dropdown} from '../../components/dropdown';
import {
useBuild,
useOptionalBuildById,
useOptionalBuildRepresentativeRuns,
useAncestorBuild,
useProjectBySlug,
} from '../../hooks/use-api-data';
import {BuildHashSelector} from './build-hash-selector';
import {BuildSelectorHeaderSection} from './build-selector-header-section';
import {AuditDetailPane} from './audit-detail/audit-detail-pane';
import {Page} from '../../layout/page';
import {BuildScoreComparison} from './build-score-comparison';
import {AuditGroup} from './audit-list/audit-group';
import './build-view.css';
import {BuildViewLegend} from './build-view-legend';
import clsx from 'clsx';
import {findAuditDiffs, getDiffSeverity} from '@lhci/utils/src/audit-diff-finder';
import {route, Link} from 'preact-router';
import {BuildViewWarnings} from './build-view-warnings';
import {DocumentTitle} from '../../components/document-title';
import {LoadingSpinner} from '../../components/loading-spinner';
/**
* @param {LH.Result} lhr
* @param {LH.Result|undefined} baseLhr
* @param {{percentAbsoluteDeltaThreshold: number}} options
* @return {Array<AuditGroupDef>}
*/
export function computeAuditGroups(lhr, baseLhr, options) {
/** @type {Array<IntermediateAuditGroupDef|undefined>} */
const rawAuditGroups = Object.entries(lhr.categories)
.map(([categoryId, category]) => {
const auditRefsGroupedByGroup = _.groupBy(category.auditRefs, ref => ref.group);
return auditRefsGroupedByGroup.map(auditRefGroup => {
let groupId = auditRefGroup[0].group || '';
let group = lhr.categoryGroups && lhr.categoryGroups[groupId];
if (!group) {
if (auditRefsGroupedByGroup.length !== 1) return;
groupId = `category:${categoryId}`;
group = {title: category.title, description: category.description};
}
const audits = auditRefGroup
.map(ref => ({...lhr.audits[ref.id], id: ref.id}))
.sort((a, b) => (a.score || 0) - (b.score || 0));
return {id: groupId, group: {...group, id: groupId}, audits};
});
})
.reduce((a, b) => a.concat(b));
/** @type {Array<AuditGroupDef>} */
const auditGroups = [];
for (const intermediateGroup of rawAuditGroups) {
if (!intermediateGroup) continue;
const auditPairs = intermediateGroup.audits
.map(audit => {
const baseAudit = baseLhr && baseLhr.audits[audit.id || ''];
const diffs = baseAudit
? findAuditDiffs(baseAudit, audit, {...options, synthesizeItemKeyDiffs: true})
: [];
const maxSeverity = Math.max(...diffs.map(getDiffSeverity), 0);
return {audit, baseAudit, diffs, maxSeverity, group: intermediateGroup.group};
})
.filter(pair => !pair.baseAudit || pair.diffs.length);
const auditGroup = {
id: intermediateGroup.id,
group: intermediateGroup.group,
pairs: auditPairs.sort((a, b) => (a.audit.score || 0) - (b.audit.score || 0)),
};
if (auditGroup.pairs.length) auditGroups.push(auditGroup);
}
return auditGroups;
}
/** @typedef {{id: string, audits: Array<LH.AuditResult>, group: {id: string, title: string}}} IntermediateAuditGroupDef */
/** @typedef {{id: string, pairs: Array<LHCI.AuditPair>, group: {id: string, title: string}}} AuditGroupDef */
/** @param {{selectedUrl: string, selectedAuditId?: string | null, build: LHCI.ServerCommand.Build | null, lhr?: LH.Result, baseLhr?: LH.Result, urls: Array<string>, percentAbsoluteDeltaThreshold: number, setPercentAbsoluteDeltaThreshold: (x: number) => void}} props */
const BuildViewScoreAndUrl = props => {
return (
<div className="build-view__scores-and-url">
<div className="container">
<div className="build-view__dropdowns">
<Dropdown
label="URL"
className="dropdown--url"
value={props.selectedUrl}
setValue={url => {
const to = new URL(window.location.href);
to.searchParams.set('compareUrl', url);
route(`${to.pathname}${to.search}`);
}}
options={props.urls.map(url => ({value: url, label: url}))}
/>
<Dropdown
label="Threshold"
value={props.percentAbsoluteDeltaThreshold.toString()}
setValue={value => {
props.setPercentAbsoluteDeltaThreshold(Number(value));
}}
options={[
{value: '0', label: '0%'},
{value: '0.05', label: '5%'},
{value: '0.1', label: '10%'},
{value: '0.15', label: '15%'},
{value: '0.25', label: '25%'},
]}
/>
</div>
{props.selectedAuditId ? <Fragment /> : <BuildScoreComparison {...props} />}
</div>
</div>
);
};
/** @param {{auditGroups: Array<AuditGroupDef|undefined>, baseLhr?: LH.Result, selectedAuditId: string|null, setSelectedAuditId: (id: string|null) => void, showAsNarrow: boolean}} props */
const AuditGroups = props => {
return (
<div className="build-view__audit-groups">
{props.auditGroups.map(auditGroup => {
if (!auditGroup) return undefined;
return (
<AuditGroup
key={auditGroup.id}
showAsNarrow={props.showAsNarrow}
pairs={auditGroup.pairs}
group={auditGroup.group}
baseLhr={props.baseLhr}
selectedAuditId={props.selectedAuditId}
setSelectedAuditId={props.setSelectedAuditId}
/>
);
})}
</div>
);
};
/** @param {{project: LHCI.ServerCommand.Project, build: LHCI.ServerCommand.Build, ancestorBuild: LHCI.ServerCommand.Build | null, runs: Array<LHCI.ServerCommand.Run>, compareUrl?: string, hasBaseOverride: boolean}} props */
const BuildView_ = props => {
const [percentAbsoluteDeltaThreshold, setDiffThreshold] = useState(0.05);
const [openBuildHash, setOpenBuild] = useState(/** @type {null|'base'|'compare'} */ (null));
const [selectedAuditId, setAuditId] = useState(/** @type {string|null} */ (null));
const [isOpenLhrLinkHovered, setLhrLinkHover] = useState(false);
const selectedUrl = props.compareUrl || (props.runs[0] && props.runs[0].url);
const buildHashSelectorCloseFn = useCallback(() => setOpenBuild(null), [setOpenBuild]);
const compareRuns = props.runs.filter(run => run.buildId === props.build.id);
const availableUrls = [...new Set(compareRuns.map(run => run.url))];
const run = compareRuns.find(run => run.url === selectedUrl);
const ancestorBuildId = props.ancestorBuild && props.ancestorBuild.id;
const baseRuns = props.runs.filter(run => run.buildId === ancestorBuildId);
const baseRun = baseRuns.find(run => run.url === selectedUrl);
/** @type {LH.Result|undefined} */
let lhr;
/** @type {LH.Result|undefined} */
let baseLhr;
/** @type {Error|undefined} */
let lhrError;
try {
lhr = useMemo(() => run && JSON.parse(run.lhr), [run]);
} catch (err) {
lhrError = err;
}
try {
baseLhr = useMemo(() => baseRun && JSON.parse(baseRun.lhr), [baseRun]);
} catch (err) {
lhrError = err;
}
// Attach the LHRs to the window for easy debugging.
useEffect(() => {
// @ts-ignore
window.__LHR__ = lhr;
// @ts-ignore
window.__BASE_LHR__ = baseLhr;
}, [lhr, baseLhr]);
if (!run || !lhr) {
return (
<Fragment>
<h1>No runs for build</h1>
<pre>
{lhrError}
{JSON.stringify(props, null, 2)}
</pre>
</Fragment>
);
}
const auditGroups = computeAuditGroups(lhr, baseLhr, {percentAbsoluteDeltaThreshold});
return (
<Page
headerLeft={
<Link href={`/app/projects/${props.project.slug}`}>
<i className="material-icons">arrow_back</i>
</Link>
}
header={
<Fragment>
<BuildSelectorHeaderSection
build={props.ancestorBuild}
variant="base"
lhr={baseLhr}
isDimmed={openBuildHash === 'compare'}
isOpen={openBuildHash === 'base'}
setLhrLinkHover={setLhrLinkHover}
onClick={() => setOpenBuild(openBuildHash === 'base' ? null : 'base')}
/>
<BuildSelectorHeaderSection
build={props.build}
variant="compare"
lhr={lhr}
isDimmed={openBuildHash === 'base'}
isOpen={openBuildHash === 'compare'}
setLhrLinkHover={setLhrLinkHover}
onClick={() => setOpenBuild(openBuildHash === 'compare' ? null : 'compare')}
/>
</Fragment>
}
headerRight={
<a
href="https://github.com/GoogleChrome/lighthouse-ci"
target="_blank"
rel="noopener noreferrer"
>
<i className="material-icons">info</i>
</a>
}
>
<DocumentTitle title={`Compare "${props.build.commitMessage}"`} />
{(openBuildHash && (
<BuildHashSelector
build={props.build}
ancestorBuild={props.ancestorBuild}
selector={openBuildHash}
lhr={lhr}
baseLhr={baseLhr}
close={buildHashSelectorCloseFn}
/>
)) || <Fragment />}
{(selectedAuditId && (
<AuditDetailPane
selectedAuditId={selectedAuditId}
setSelectedAuditId={setAuditId}
pairs={auditGroups.map(group => group.pairs).reduce((a, b) => a.concat(b))}
baseLhr={baseLhr}
/>
)) || <Fragment />}
{(lhrError && <h1>Error parsing LHR ({lhrError.stack})</h1>) || <Fragment />}
<div
className={clsx('build-view', {
'build-view--with-audit-selection': !!selectedAuditId,
'build-view--with-lhr-link-hover': isOpenLhrLinkHovered,
})}
>
<BuildViewScoreAndUrl
build={props.build}
lhr={lhr}
baseLhr={baseLhr}
selectedUrl={selectedUrl}
selectedAuditId={selectedAuditId}
urls={availableUrls}
percentAbsoluteDeltaThreshold={percentAbsoluteDeltaThreshold}
setPercentAbsoluteDeltaThreshold={setDiffThreshold}
/>
<div className="container">
<BuildViewWarnings
lhr={lhr}
build={props.build}
auditGroups={auditGroups}
baseBuild={props.ancestorBuild}
baseLhr={baseLhr}
hasBaseOverride={props.hasBaseOverride}
/>
{auditGroups.length && baseLhr ? (
<Fragment>
{selectedAuditId ? (
<Fragment />
) : (
<div className="build-view__legend-and-options">
<BuildViewLegend />
</div>
)}
<AuditGroups
showAsNarrow={!!selectedAuditId}
auditGroups={auditGroups}
baseLhr={baseLhr}
selectedAuditId={selectedAuditId}
setSelectedAuditId={setAuditId}
/>
</Fragment>
) : (
<Fragment />
)}
</div>
</div>
</Page>
);
};
/** @param {{projectSlug: string, partialBuildId: string, baseBuild?: string, compareUrl?: string}} props */
export const BuildView = props => {
const projectLoadingData = useProjectBySlug(props.projectSlug);
const projectId = projectLoadingData[1] && projectLoadingData[1].id;
const buildLoadingData = useBuild(projectId, props.partialBuildId);
const buildId = buildLoadingData[1] && buildLoadingData[1].id;
const ancestorBuildData = useAncestorBuild(projectId, buildId);
const baseOverrideOptions = props.baseBuild ? props.baseBuild : null;
const baseOverrideData = useOptionalBuildById(projectId, baseOverrideOptions);
const baseBuildData = props.baseBuild ? baseOverrideData : ancestorBuildData;
const baseBuildId = baseBuildData[1] && baseBuildData[1].id;
const runData = useOptionalBuildRepresentativeRuns(projectId, buildId, null);
const baseRunData = useOptionalBuildRepresentativeRuns(
projectId,
baseBuildId === null ? 'EMPTY_QUERY' : baseBuildId,
null
);
return (
<AsyncLoader
loadingState={combineLoadingStates(
projectLoadingData,
buildLoadingData,
baseBuildData,
runData,
baseRunData
)}
asyncData={combineAsyncData(
projectLoadingData,
buildLoadingData,
baseBuildData,
runData,
baseRunData
)}
renderLoading={() => (
<Page>
<LoadingSpinner />
</Page>
)}
render={([project, build, ancestorBuild, runs, baseRuns]) => (
<BuildView_
project={project}
build={build}
compareUrl={props.compareUrl}
ancestorBuild={ancestorBuild}
runs={runs.concat(baseRuns)}
hasBaseOverride={!!props.baseBuild}
/>
)}
/>
);
};