Awesome Reviewers

When implementing event-driven UI behaviors that must remain correct under timing issues and dynamic DOM updates, design the logic as an algorithm with explicit invariants and ownership of state transitions.

Apply this pattern: 1) Define an invariant (what must remain true) and enforce it from reliable signals.

Minimal example (anchor-based stabilization sketch):

type Anchor = { element: Element; offsetTop: number };

function findAnchor(viewport: HTMLDivElement, content: HTMLDivElement): Anchor | null {
  // Descend through wrappers regardless of structure; pick the deepest child
  // whose bottom edge crosses the viewport top (or the first child below if in a gap).
  // Return element + its offsetTop relative to viewport.
  return null;
}

function restoreAnchorScroll(viewport: HTMLDivElement, content: HTMLDivElement, anchor: Anchor) {
  const elRect = anchor.element.getBoundingClientRect();
  const viewportRect = viewport.getBoundingClientRect();
  const currentOffset = elRect.top - viewportRect.top;
  const delta = currentOffset - anchor.offsetTop;
  viewport.scrollTop += delta; // clamp as needed
}

// On resize/content mutation:
// - recompute anchor only when appropriate
// - restore scrollTop to keep invariant

Coding standard takeaway: UI “correctness” should be expressed as invariants + ownership + measurement-based anchoring, not as ad-hoc event handling and one-off deltas.