completefrontend

Predict the outputMedium

What is this layout shift's score?

A card on the tea shop's page moved between two frames in a laptop window 800 by 600 CSS pixels wide and tall. The code takes the card's rectangle before and after, as getBoundingClientRect() gives them, and works out the impact fraction, the distance fraction, and the score the way the Layout Instability spec defines them. What does it log?

The code
// The tea of the day's card in a laptop window, 800 by 600 CSS pixels, in two frames one after the other.
// Rectangles are in the viewport's coordinates, as getBoundingClientRect() gives them.
const viewport = { width: 800, height: 600 };
const before = { x: 100, y: 400, width: 300, height: 300 };
const after = { x: 160, y: 480, width: 300, height: 300 };
 
// The part of a rectangle inside the viewport.
function visible({ x, y, width, height }) {
  const left = Math.max(x, 0);
  const top = Math.max(y, 0);
  const right = Math.min(x + width, viewport.width);
  const bottom = Math.min(y + height, viewport.height);
  return { width: Math.max(0, right - left), height: Math.max(0, bottom - top), left, top };
}
 
const a = visible(before);
const b = visible(after);
const overlapWidth = Math.max(0, Math.min(a.left + a.width, b.left + b.width) - Math.max(a.left, b.left));
const overlapHeight = Math.max(0, Math.min(a.top + a.height, b.top + b.height) - Math.max(a.top, b.top));
 
// Impact: the old and new visible areas together, the overlap counted once, over the viewport's area.
const covered = a.width * a.height + b.width * b.height - overlapWidth * overlapHeight;
const impactFraction = covered / (viewport.width * viewport.height);
 
// Distance: the larger of the two moves, over the viewport's larger side.
const moved = Math.max(Math.abs(after.x - before.x), Math.abs(after.y - before.y));
const distanceFraction = Math.min(moved / Math.max(viewport.width, viewport.height), 1);
 
console.log("Impact fraction: " + impactFraction);
console.log("Distance fraction: " + distanceFraction);
console.log("Score: " + (impactFraction * distanceFraction).toFixed(4));

Practice it in the editor, with tests

The answer

Work out every line it logs, in order. Then check.

Checking your sign-in…