-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindings.js
More file actions
364 lines (338 loc) · 14.2 KB
/
Copy pathfindings.js
File metadata and controls
364 lines (338 loc) · 14.2 KB
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
/**
* Finding rules: turn a recorded transition into actionable diagnostics.
*
* Each rule is a pure function `(record) => Finding[]`, so the whole ruleset is
* testable without a browser. `analyze()` runs them all and sorts by severity.
*
* Every rule id also appears in the README's rule table and maps to a
* "Learn more" article, so ids are part of the public surface: renaming one is
* a breaking change for the docs.
*/
import { findDuplicateNames, snapshotViewportRatio, diffRects } from './pseudo-tree.js';
/** @typedef {'error'|'warning'|'info'} Severity */
/**
* @typedef {object} Finding
* @property {string} rule
* @property {Severity} severity
* @property {string} title
* @property {string} detail
* @property {string} fix
* @property {string} [learnMore] documentation URL
* @property {string[]} [names] affected view-transition-name values
*/
const DOCS = Object.freeze({
underTheHood:
'https://www.css-scroll-driven.com/core-animation-fundamentals-browser-mechanics/how-view-transition-works-under-the-hood/',
sameVsCross:
'https://www.css-scroll-driven.com/core-animation-fundamentals-browser-mechanics/how-view-transition-works-under-the-hood/same-document-vs-cross-document-view-transitions/',
vsFlip:
'https://www.css-scroll-driven.com/core-animation-fundamentals-browser-mechanics/how-view-transition-works-under-the-hood/view-transition-api-vs-flip-technique-comparison/',
spaPageSwap:
'https://www.css-scroll-driven.com/scroll-driven-view-transition-implementation-patterns/spa-page-swap-animations/',
crossRouteMorphing:
'https://www.css-scroll-driven.com/scroll-driven-view-transition-implementation-patterns/cross-route-element-morphing/',
detectSupport:
'https://www.css-scroll-driven.com/scroll-driven-view-transition-implementation-patterns/view-transition-browser-support-matrix/detecting-view-transition-support-supports-javascript/',
inpImpact:
'https://www.css-scroll-driven.com/animation-performance-profiling-optimization/core-web-vitals-scroll-view-transitions/view-transitions-inp-impact/',
mainThreadJank:
'https://www.css-scroll-driven.com/animation-performance-profiling-optimization/profiling-scroll-animations-devtools/diagnosing-main-thread-jank-performance-panel/',
reducedMotion:
'https://www.css-scroll-driven.com/accessibility-inclusive-motion-standards/vestibular-safe-motion-design/reduced-motion-view-transition-variants/',
});
export { DOCS };
/** Thresholds, exported so the tests and the README quote the same numbers. */
export const THRESHOLDS = Object.freeze({
/** A DOM-update callback longer than this stalls the transition visibly. */
callbackWarnMs: 50,
/** Past this the transition reads as a freeze and will hurt INP. */
callbackErrorMs: 150,
/** Snapshot area vs. viewport area beyond which rasterisation gets costly. */
snapshotRatio: 2,
/** Groups beyond which the compositor is juggling a lot of layers. */
groupCountWarn: 20,
});
/**
* Properties that cannot be animated on the compositor. Animating these on a
* view-transition pseudo-element forces layout/paint on every frame, which is
* exactly what the API's snapshot approach is meant to avoid.
*/
export const NON_COMPOSITED_PROPERTIES = Object.freeze([
'width',
'height',
'top',
'left',
'right',
'bottom',
'margin',
'margin-top',
'margin-left',
'margin-right',
'margin-bottom',
'padding',
'clip-path',
'border-radius',
'box-shadow',
'filter',
'background-color',
'font-size',
]);
const nonCompositedSet = new Set(NON_COMPOSITED_PROPERTIES);
/**
* @param {string} property
* @returns {boolean}
*/
export function isNonComposited(property) {
if (typeof property !== 'string') return false;
const normalized = property.trim().toLowerCase();
if (normalized === '' || normalized === 'all') return normalized === 'all';
return nonCompositedSet.has(normalized);
}
const finding = (rule, severity, title, detail, fix, learnMore, names) => ({
rule,
severity,
title,
detail,
fix,
learnMore,
...(names && names.length ? { names } : {}),
});
/* ------------------------------------------------------------------ rules */
/** Two live elements share a `view-transition-name`: the browser aborts. */
function ruleDuplicateNames(record) {
const duplicates = findDuplicateNames(record.nameUsages ?? []);
if (duplicates.length === 0) return [];
const names = duplicates.map((d) => d.name);
return [
finding(
'duplicate-view-transition-name',
'error',
'Duplicate view-transition-name',
`${duplicates
.map((d) => `"${d.name}" is used by ${d.count} elements in the ${d.phase} state`)
.join('; ')}. A name must be unique per document state — the browser skips the whole transition when it is not.`,
'Give each element a unique name, or set `view-transition-name: none` on all but the one you actually want to morph. Generating names from a stable record id (e.g. `--card-${id}`) is the usual fix for lists.',
DOCS.crossRouteMorphing,
names,
),
];
}
/** The transition never animated — skipped, aborted, or the callback threw. */
function ruleSkipped(record) {
if (!record.skipped && !record.error) return [];
const reason = record.error
? `the DOM-update callback rejected (${record.error})`
: (record.skipReason ?? 'skipTransition() was called or the transition was aborted');
return [
finding(
'transition-skipped',
'warning',
'Transition was skipped',
`No animation ran because ${reason}. The DOM still updated — skipping only drops the visual effect.`,
'Check for an explicit skipTransition() call, a second startViewTransition() interrupting this one, a hidden document, or a throwing update callback. Await `finished` and log the rejection to find it.',
DOCS.underTheHood,
),
];
}
/** The developer callback blocked the transition for too long. */
function ruleLongCallback(record) {
const ms = record.callbackMs;
if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < THRESHOLDS.callbackWarnMs) return [];
const severity = ms >= THRESHOLDS.callbackErrorMs ? 'error' : 'warning';
return [
finding(
'long-update-callback',
severity,
'Slow DOM-update callback',
`The update callback took ${ms.toFixed(1)} ms (budget ${THRESHOLDS.callbackWarnMs} ms). The page is frozen on the old snapshot for this entire time, and the delay counts toward INP for the interaction that triggered it.`,
'Move data fetching outside the callback — await it first, then call startViewTransition with a callback that only swaps already-prepared DOM. Avoid forced synchronous layout inside the callback.',
DOCS.inpImpact,
),
];
}
/** Pseudo-element animations that force layout or paint every frame. */
function ruleNonCompositedProperties(record) {
/** @type {Map<string, Set<string>>} */
const byProperty = new Map();
for (const group of record.groups ?? []) {
for (const animation of group.animations ?? []) {
if (!isNonComposited(animation.property)) continue;
const key = animation.property.trim().toLowerCase();
if (!byProperty.has(key)) byProperty.set(key, new Set());
byProperty.get(key).add(group.name);
}
}
if (byProperty.size === 0) return [];
const properties = [...byProperty.keys()].sort();
const names = [...new Set([...byProperty.values()].flatMap((s) => [...s]))].sort();
const isAll = properties.includes('all');
return [
finding(
'non-composited-animation',
'warning',
'Non-compositor-friendly animation',
isAll
? 'A `transition: all` on a view-transition pseudo-element animates layout-affecting properties. Every frame is recalculated on the main thread.'
: `Animating ${properties.map((p) => `\`${p}\``).join(', ')} on the view-transition pseudo-elements forces layout or paint each frame instead of running on the compositor.`,
'Animate `transform` and `opacity` only. Size changes are better expressed by letting the default group animation interpolate width/height while the image pair cross-fades, or by scaling with `transform: scale()`.',
DOCS.mainThreadJank,
names,
),
];
}
/** Snapshots much bigger than the viewport are expensive to rasterise. */
function ruleOversizedSnapshots(record) {
const viewport = record.viewport;
const offenders = [];
for (const group of record.groups ?? []) {
const ratio = snapshotViewportRatio(group, viewport ?? {});
if (ratio > THRESHOLDS.snapshotRatio) {
offenders.push({ name: group.name, ratio });
}
}
if (offenders.length === 0) return [];
return [
finding(
'oversized-snapshot',
'warning',
'Oversized snapshot',
`${offenders
.map((o) => `"${o.name}" covers ~${o.ratio.toFixed(1)}× the viewport area`)
.join('; ')}. Each snapshot is rasterised into a texture, so very large groups cost memory and can be clipped by the compositor's maximum texture size.`,
'Name a smaller element. Tag the visible card rather than a tall scrolling container, and avoid putting a name on `html`, `body`, or a full-page wrapper unless you want the whole-page cross-fade.',
DOCS.underTheHood,
offenders.map((o) => o.name),
),
];
}
/** No reduced-motion escape hatch was found in the page's stylesheets. */
function ruleReducedMotion(record) {
if (record.hasReducedMotionQuery) return [];
if ((record.groups ?? []).length === 0 && !record.animated) return [];
return [
finding(
'missing-reduced-motion',
'info',
'No prefers-reduced-motion handling',
'No `@media (prefers-reduced-motion: reduce)` rule targeting the view-transition pseudo-elements was found. Users who ask for reduced motion still get the full sliding and scaling animation, which can trigger vestibular symptoms.',
'Add a reduced-motion block that replaces movement with a short cross-fade, or disables the pseudo-element animations entirely with `animation: none`. Keep the transition itself — just drop the motion.',
DOCS.reducedMotion,
),
];
}
/** A large group count means a lot of simultaneous compositor layers. */
function ruleTooManyGroups(record) {
const groups = record.groups ?? [];
if (groups.length <= THRESHOLDS.groupCountWarn) return [];
return [
finding(
'too-many-groups',
'info',
'High group count',
`${groups.length} named groups were captured (soft limit ${THRESHOLDS.groupCountWarn}). Every group produces four pseudo-elements and at least one snapshot texture.`,
'Name only the elements that need to morph independently. Containers that just fade can share the default root cross-fade instead of carrying their own name.',
DOCS.spaPageSwap,
groups.slice(THRESHOLDS.groupCountWarn).map((g) => g.name),
),
];
}
/** A group that moves *and* resizes a lot is where morphing usually breaks. */
function ruleLargeGeometryJump(record) {
const offenders = [];
for (const group of record.groups ?? []) {
const delta = group.delta ?? diffRects(group.old, group.new);
if (!delta || !delta.moved || !delta.resized) continue;
const scaled =
(delta.scaleX !== null && (delta.scaleX > 3 || delta.scaleX < 1 / 3)) ||
(delta.scaleY !== null && (delta.scaleY > 3 || delta.scaleY < 1 / 3));
if (scaled) offenders.push(group.name);
}
if (offenders.length === 0) return [];
return [
finding(
'extreme-scale-change',
'info',
'Extreme scale change',
`${offenders.map((n) => `"${n}"`).join(', ')} changes size by more than 3× while also moving. The default cross-fade stretches the old snapshot across that whole range, which usually looks smeared.`,
'Set an explicit `object-fit`/`object-position` on the old and new pseudo-elements, or stagger the size and position changes with a custom keyframe animation on the group.',
DOCS.vsFlip,
offenders,
),
];
}
/** Cross-document transitions have their own opt-in requirements. */
function ruleCrossDocumentSetup(record) {
if (record.kind !== 'cross-document') return [];
if (record.hasViewTransitionRule !== false) return [];
return [
finding(
'cross-document-not-opted-in',
'warning',
'Cross-document transition without @view-transition',
'A `pageswap`/`pagereveal` event fired but no `@view-transition { navigation: auto; }` rule was found in the page stylesheets. Both the outgoing and incoming document must opt in, and both must be same-origin.',
'Add `@view-transition { navigation: auto; }` to the stylesheets of every page in the flow. The rule is required on both sides of the navigation, not just the destination.',
DOCS.sameVsCross,
),
];
}
const RULES = [
ruleDuplicateNames,
ruleSkipped,
ruleLongCallback,
ruleNonCompositedProperties,
ruleOversizedSnapshots,
ruleTooManyGroups,
ruleLargeGeometryJump,
ruleReducedMotion,
ruleCrossDocumentSetup,
];
const SEVERITY_ORDER = { error: 0, warning: 1, info: 2 };
/**
* Run every rule against a record.
*
* Rules never throw: a malformed record from a page we don't control must
* degrade to "no findings", not break the panel.
*
* @param {object} record
* @returns {Finding[]}
*/
export function analyze(record) {
if (record === null || typeof record !== 'object') return [];
const out = [];
for (const rule of RULES) {
try {
out.push(...rule(record));
} catch {
// A single broken rule must not hide the others.
}
}
return out.sort(
(a, b) =>
SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] || a.rule.localeCompare(b.rule),
);
}
/**
* Count findings by severity, for the timeline list badges.
*
* @param {Finding[]} findings
* @returns {{error: number, warning: number, info: number}}
*/
export function severityCounts(findings) {
const counts = { error: 0, warning: 0, info: 0 };
for (const f of Array.isArray(findings) ? findings : []) {
if (f && f.severity in counts) counts[f.severity] += 1;
}
return counts;
}
/** All rule ids, so the README table and the tests can assert coverage. */
export const RULE_IDS = Object.freeze([
'duplicate-view-transition-name',
'transition-skipped',
'long-update-callback',
'non-composited-animation',
'oversized-snapshot',
'too-many-groups',
'extreme-scale-change',
'missing-reduced-motion',
'cross-document-not-opted-in',
]);