This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: view-transitions-l2-cross-document-guardrail

View Transitions API Level 2 Cross-Document Coordination & Containment Standard

Enforces strict pseudo-element allocation budgets, explicit viewport containment, and declarative lifecycle coordination across cross-document (MPA) navigations. Prevents GPU memory saturation, compositing thrashing, and sub-16ms frame drops caused by unbounded view-transition-name registration and unconstrained off-screen texture snapshots.

Prohibited Anti-Pattern: Unbounded Pseudo-Element Allocation and Uncontained Full-Document Snapshots Inducing Compositor Stalls During Cross-Document Navigation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: View Transitions API Level 2 Cross-Document Coordination & Containment Standard - Enforces strict pseudo-element allocation budgets, explicit viewport containment, and declarative lifecycle coordination across cross-document (MPA) navigations. Prevents GPU memory saturation, compositing thrashing, and sub-16ms frame drops caused by unbounded view-transition-name registration and unconstrained off-screen texture snapshots.
globs: src/**/*.{ts,tsx,js,jsx,css,scss,html}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/view-transitions-l2-cross-document-guardrail"
---

# View Transitions API Level 2 Cross-Document Coordination & Containment Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unbounded Pseudo-Element Allocation and Uncontained Full-Document Snapshots Inducing Compositor Stalls During Cross-Document Navigation

## System Constraints
You are a Principal Frontend Architect enforcing CSS View Transitions Module Level 2 standards for Cross-Document navigations. Cross-document view transitions incur significant GPU rasterization and compositor memory overhead if transition names are assigned without strict bounding budgets. You must ensure that developers strictly limit concurrent active transition identifiers, enforce strict layout/paint containment on target nodes, guard against off-screen capture overhead using IntersectionObserver checks, and orchestrate `pageswap` and `pagereveal` lifecycle events to prevent main-thread jank and aborted rendering states.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict CSS containment (`contain: layout paint` or `contain: strict`) on every element assigned a non-none `view-transition-name`.
- Engineers MUST NOT statically assign unique `view-transition-name` identifiers to repeated collection items or lists in global stylesheets, as this causes catastrophic GPU texture explosion during navigation capture.
- Engineers MUST dynamically limit concurrent active `view-transition-name` bindings to a maximum budget of 8 visible viewport elements during `pageswap` execution.
- Code MUST qualify cross-document transitions in CSS using `@view-transition { navigation: auto; }` paired with explicit selector scoping via `@media (prefers-reduced-motion: no-preference)`.
- Code MUST leverage CSS View Transitions Level 2 `view-transition-class` attributes to consolidate shared keyframe animations across pseudo-element pairs rather than duplicating pseudo-rules.
- Services MUST abort or skip transitions using `event.viewTransition.skipTransition()` in the `pageswap` handler if the target URL is cross-origin, matches an excluded route pattern, or if navigation payload exceeds latency budgets.
- Components NEVER attach `view-transition-name` to off-screen or virtualized elements outside the active viewport during the `pageswap` snapshot cycle.
- Transitions MUST animate solely hardware-accelerated compositor properties (`transform`, `opacity`, `filter`), explicitly forbidding geometry animations (`width`, `height`, `top`, `margin`) inside `::view-transition-group(*)`.

## Bad vs Good Implementations
### Cross-Document Navigation Transition Management via pageswap and pagereveal

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Assigning view-transition-name unconditionally to all list elements forces the browser engine to snapshot textures for hundreds of elements (even off-screen). This saturates the compositor memory and breaks the 16ms frame budget. Animating geometry properties like height inside pseudo-elements causes main-thread layout thrashing during capture.
```typescript
// BAD: Global unconstrained view-transition assignment capturing out-of-viewport elements
// Leads to unbounded texture memory allocation and 100ms+ compositor freezes

window.addEventListener('pageswap', (event: any) => {
  // Invariant Violation: Capturing entire dynamic card list unconditionally
  const cards = document.querySelectorAll('.card');
  cards.forEach((card, index) => {
    (card as HTMLElement).style.viewTransitionName = `card-${index}`;
  });
});

// Bad CSS:
// @view-transition { navigation: auto; }
// ::view-transition-group(*) {
//   animation-duration: 0.5s;
//   height: auto; /* Forces main-thread reflow on every frame */
// }
```

#### Production Standard (Correct)
> **Standard**: Restricts active view transition elements to an explicit budget (<= 6) using viewport-bounding detection. Implements strict layout and paint containment on participating nodes. Skips cross-origin or untrusted targets, and handles promise rejection during interrupted transitions without leaving lingering styles.
```typescript
// GOOD: Strict containment budget with IntersectionObserver bounding and lifecycle guards

const MAX_TRANSITION_BUDGET = 6;

interface PageSwapEvent extends Event {
  activation?: { entry: NavigationHistoryEntry };
  viewTransition?: {
    skipTransition: () => void;
    types?: Set<string>;
  };
}

interface PageRevealEvent extends Event {
  viewTransition?: {
    ready: Promise<void>;
    finished: Promise<void>;
    types?: Set<string>;
  };
}

export function setupCrossDocumentCoordination(): void {
  if (!('onpageswap' in window)) return;

  window.addEventListener('pageswap', (event: Event) => {
    const swapEvent = event as PageSwapEvent;
    if (!swapEvent.viewTransition) return;

    const targetUrl = swapEvent.activation?.entry?.url;
    if (!targetUrl || !targetUrl.startsWith(window.location.origin)) {
      swapEvent.viewTransition.skipTransition();
      return;
    }

    // Enforce budget: only promote elements visible within the viewport
    const candidates = Array.from(document.querySelectorAll<HTMLElement>('[data-transition-target]'));
    const viewportHeight = window.innerHeight;
    let allocated = 0;

    for (const el of candidates) {
      const rect = el.getBoundingClientRect();
      const isVisible = rect.top < viewportHeight && rect.bottom > 0;

      if (isVisible && allocated < MAX_TRANSITION_BUDGET) {
        const name = el.dataset.transitionTarget;
        if (name) {
          el.style.contain = 'layout paint';
          el.style.viewTransitionName = name;
          allocated++;
        }
      } else {
        el.style.viewTransitionName = 'none';
      }
    }
  });

  window.addEventListener('pagereveal', (event: Event) => {
    const revealEvent = event as PageRevealEvent;
    if (!revealEvent.viewTransition) return;

    revealEvent.viewTransition.ready.catch(() => {
      // Graceful fallback for interrupted navigations
      document.querySelectorAll<HTMLElement>('[data-transition-target]').forEach((el) => {
        el.style.viewTransitionName = 'none';
      });
    });
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: View Transitions API Level 2 Cross-Document Coordination & Containment Standard

View Transitions API Level 2 Cross-Document Coordination & Containment Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict pseudo-element allocation budgets, explicit viewport containment, and declarative lifecycle coordination across cross-document (MPA) navigations. Prevents GPU memory saturation, compositing thrashing, and sub-16ms frame drops caused by unbounded view-transition-name registration and unconstrained off-screen texture snapshots. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded Pseudo-Element Allocation and Uncontained Full-Document Snapshots Inducing Compositor Stalls During Cross-Document Navigation Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded Pseudo-Element Allocation and Uncontained Full-Document Snapshots Inducing Compositor Stalls During Cross-Document NavigationCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS enforce strict CSS containment (`contain

Engineers MUST ALWAYS enforce strict CSS containment (`contain: layout paint` or `contain: strict`) on every element assigned a non-none `view-transition-name`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT statically assign unique `view-transition-name` identifiers to repeated collection items or lists in global stylesheets, as this causes catastrophic GPU texture explosion during navigation capture.

Engineers MUST NOT statically assign unique `view-transition-name` identifiers to repeated collection items or lists in global stylesheets, as this causes catastrophic GPU texture explosion during navigation capture.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST dynamically limit concurrent active `view-transition-name` bindings to a maximum budget of 8 visible viewport elements during `pageswap` execution.

Engineers MUST dynamically limit concurrent active `view-transition-name` bindings to a maximum budget of 8 visible viewport elements during `pageswap` execution.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code MUST qualify cross-document transitions in CSS using `@view-transition { navigation

Code MUST qualify cross-document transitions in CSS using `@view-transition { navigation: auto; }` paired with explicit selector scoping via `@media (prefers-reduced-motion: no-preference)`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Code MUST leverage CSS View Transitions Level 2 `view-transition-class` attributes to consolidate shared keyframe animations across pseudo-element pairs rather than duplicating pseudo-rules.

Code MUST leverage CSS View Transitions Level 2 `view-transition-class` attributes to consolidate shared keyframe animations across pseudo-element pairs rather than duplicating pseudo-rules.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Services MUST abort or skip transitions using `event.viewTransition.skipTransition()` in the `pageswap` handler if the target URL is cross-origin, matches an excluded route pattern, or if navigation payload exceeds latency budgets.

Services MUST abort or skip transitions using `event.viewTransition.skipTransition()` in the `pageswap` handler if the target URL is cross-origin, matches an excluded route pattern, or if navigation payload exceeds latency budgets.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
7

Components NEVER attach `view-transition-name` to off-screen or virtualized elements outside the active viewport during the `pageswap` snapshot cycle.

Components NEVER attach `view-transition-name` to off-screen or virtualized elements outside the active viewport during the `pageswap` snapshot cycle.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
8

Transitions MUST animate solely hardware-accelerated compositor properties (`transform`, `opacity`, `filter`), explicitly forbidding geometry animations (`width`, `height`, `top`, `margin`) inside `

Transitions MUST animate solely hardware-accelerated compositor properties (`transform`, `opacity`, `filter`), explicitly forbidding geometry animations (`width`, `height`, `top`, `margin`) inside `::view-transition-group(*)`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is View Transitions API Level 2 Cross-Document Coordination & Containment Standard critical for AI coding assistants?

Enforces strict pseudo-element allocation budgets, explicit viewport containment, and declarative lifecycle coordination across cross-document (MPA) navigations. Prevents GPU memory saturation, compositing thrashing, and sub-16ms frame drops caused by unbounded view-transition-name registration and unconstrained off-screen texture snapshots. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded Pseudo-Element Allocation and Uncontained Full-Document Snapshots Inducing Compositor Stalls During Cross-Document Navigation) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

View