This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-android-15-predictive-back-insets-sync

Capacitor 7 Android 15 Predictive Back & WindowInsets Synchronization Protocol

Enforces edge-to-edge layout invariants and Viewport synchronization for Capacitor 7 running on Android 15 (API 35+). Prevents WebView compositor clipping, frame drops, and touch-target misalignment during predictive back gestures, software keyboard (IME) animations, and dynamic display cutout transitions.

Prohibited Anti-Pattern: Unsynchronized CSS Viewport and Native Inset Polling During Predictive Back and IME Transitions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Android 15 Predictive Back & WindowInsets Synchronization Protocol - Enforces edge-to-edge layout invariants and Viewport synchronization for Capacitor 7 running on Android 15 (API 35+). Prevents WebView compositor clipping, frame drops, and touch-target misalignment during predictive back gestures, software keyboard (IME) animations, and dynamic display cutout transitions.
globs: android/app/src/main/java/**/*.java, android/app/src/main/res/values/styles.xml, android/app/src/main/res/values-v35/styles.xml, src/**/*.{ts,tsx,css,scss}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-android-15-predictive-back-insets-sync"
---

# Capacitor 7 Android 15 Predictive Back & WindowInsets Synchronization Protocol

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized CSS Viewport and Native Inset Polling During Predictive Back and IME Transitions

## System Constraints
You are a Principal Mobile Architect enforcing Android 15 edge-to-edge rendering and predictive back invariants for Capacitor 7 hybrid applications. You must ensure the native Android ViewTree correctly propagates WindowInsetsCompat (specifically IME, systemBars, and displayCutout) into the Chromium compositor, while synchronizing Web Viewport CSS environment variables and hardware-accelerated transforms to eliminate visual jank and touch misalignment.

## Strict Guidelines
- Engineers MUST ALWAYS enable edge-to-edge explicitly via WindowCompat.setDecorFitsSystemWindows(window, false) in MainActivity and configure android:windowOptOutEdgeToEdgeEnforcement to false in styles.xml for API 35.
- Engineers MUST ALWAYS bind an OnApplyWindowInsetsListener to the Capacitor BridgeWebView that translates WindowInsetsCompat into direct CSS custom property updates via evaluateJavascript rather than relying on delayed window resize events.
- Engineers MUST NOT rely solely on CSS env(safe-area-inset-*) without fallback polyfills synchronized with native OnBackAnimationCallback progress events.
- Components NEVER use 100vh or 100% height on root layout containers without pairing with dvh (Dynamic Viewport Height) or custom inset variables (--safe-area-inset-bottom, --ime-inset-bottom).
- Native code MUST consume OnBackInvokedDispatcher with PRIORITY_DEFAULT or PRIORITY_OVERLAY and emit normalized progress events (0.0 to 1.0) to the Capacitor bridge to drive CSS scale/translate transforms.
- Engineers MUST NOT disable hardware acceleration on the BridgeWebView or its ancestor FrameLayout during predictive back gesture interception.

## Bad vs Good Implementations
### Android 15 Native Edge-to-Edge & Predictive Back Synchronization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to configure WindowCompat edge-to-edge constraints, causing Android 15 to enforce default letterboxing or synthetic insets. Fails to register BackAnimationCallback, causing the WebView to freeze during system gestures.
```java
// Anti-pattern: Legacy window adjustments and unhandled Android 15 insets
package com.example.app;

import android.os.Bundle;
import com.getcapacitor.BridgeActivity;

public class MainActivity extends BridgeActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Deprecated flags break Android 15 predictive back and force letterboxing
        getWindow().setFlags(1024, 1024);
    }
}
```

#### Production Standard (Correct)
> **Standard**: Implements modern edge-to-edge compatibility via WindowCompat, dynamically injects density-normalized safe area dimensions into the WebView via evaluateJavascript, and streams predictive back animation milestones into DOM custom events.
```java
package com.example.app;

import android.os.Build;
import android.os.Bundle;
import android.window.BackAnimationCallback;
import android.window.BackEvent;
import android.window.OnBackInvokedDispatcher;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import com.getcapacitor.BridgeActivity;

public class MainActivity extends BridgeActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);

        ViewCompat.setOnApplyWindowInsetsListener(getBridge().getWebView(), (view, windowInsets) -> {
            int imeHeight = windowInsets.getInsets(WindowInsetsCompat.Type.ime()).bottom;
            int navHeight = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()).bottom;
            int topInset = windowInsets.getInsets(WindowInsetsCompat.Type.statusBars()).top;
            
            float density = getResources().getDisplayMetrics().density;
            String js = String.format(
                "document.documentElement.style.setProperty('--ime-height', '%fpx');" +
                "document.documentElement.style.setProperty('--status-bar-height', '%fpx');" +
                "document.documentElement.style.setProperty('--nav-bar-height', '%fpx');",
                imeHeight / density, topInset / density, navHeight / density
            );
            getBridge().getWebView().evaluateJavascript(js, null);
            return WindowInsetsCompat.CONSUMED;
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            getOnBackInvokedDispatcher().registerOnBackInvokedCallback(
                OnBackInvokedDispatcher.PRIORITY_DEFAULT,
                new BackAnimationCallback() {
                    @Override
                    public void onBackProgressed(@NonNull BackEvent backEvent) {
                        getBridge().getWebView().evaluateJavascript(
                            "window.dispatchEvent(new CustomEvent('predictiveBack', { detail: { progress: " + backEvent.getProgress() + " } }));",
                            null
                        );
                    }
                    @Override
                    public void onBackInvoked() {
                        getBridge().getWebView().evaluateJavascript("window.dispatchEvent(new Event('backInvoked'));", null);
                    }
                }
            );
        }
    }
}
```

### TypeScript Layout Controller with Predictive Back Interpolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using 100vh creates overflow defects when the Android 15 IME appears, and hardcoded paddings cause overlaps under status bars or notches. Lacks predictive back frame transformation.
```typescript
// Anti-pattern: Static viewport assumptions and unresponsive back navigation
import React, { useEffect } from 'react';

export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  return (
    <div style={{ height: '100vh', width: '100vw', paddingTop: '20px' }}>
      {children}
    </div>
  );
};
```

#### Production Standard (Correct)
> **Standard**: Uses dynamic viewport units (100dvh) combined with CSS properties derived from WindowInsetsCompat. Subscribes to native predictive back events to apply hardware-accelerated scale transforms matching Android 15 system aesthetics.
```typescript
import React, { useEffect, useState } from 'react';

interface PredictiveBackDetail {
  progress: number;
}

export const EdgeToEdgeLayout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [backProgress, setBackProgress] = useState<number>(0);

  useEffect(() => {
    const handleProgress = (event: Event) => {
      const customEvent = event as CustomEvent<PredictiveBackDetail>;
      setBackProgress(customEvent.detail.progress);
    };

    const handleInvoked = () => {
      setBackProgress(0);
    };

    window.addEventListener('predictiveBack', handleProgress);
    window.addEventListener('backInvoked', handleInvoked);

    return () => {
      window.removeEventListener('predictiveBack', handleProgress);
      window.removeEventListener('backInvoked', handleInvoked);
    };
  }, []);

  const scale = 1 - backProgress * 0.08;
  const borderRadius = `${backProgress * 16}px`;

  return (
    <div
      style={{
        boxSizing: 'border-box',
        minHeight: '100dvh',
        width: '100vw',
        paddingTop: 'var(--status-bar-height, env(safe-area-inset-top, 0px))',
        paddingBottom: 'calc(var(--ime-height, 0px) + var(--nav-bar-height, env(safe-area-inset-bottom, 0px)))',
        transform: `scale(${scale})`,
        transformOrigin: 'center center',
        borderRadius,
        overflow: 'hidden',
        transition: backProgress === 0 ? 'transform 200ms ease-out, border-radius 200ms ease-out' : 'none',
        willChange: 'transform, border-radius'
      }}
    >
      {children}
    </div>
  );
};
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Android 15 Predictive Back & WindowInsets Synchronization Protocol

Capacitor 7 Android 15 Predictive Back & WindowInsets Synchronization Protocol defines an industrial-grade behavioral standard for mobile engineering. Enforces edge-to-edge layout invariants and Viewport synchronization for Capacitor 7 running on Android 15 (API 35+). Prevents WebView compositor clipping, frame drops, and touch-target misalignment during predictive back gestures, software keyboard (IME) animations, and dynamic display cutout transitions. 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: Unsynchronized CSS Viewport and Native Inset Polling During Predictive Back and IME Transitions 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 DriftUnsynchronized CSS Viewport and Native Inset Polling During Predictive Back and IME TransitionsCritical
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 enable edge-to-edge explicitly via WindowCompat.setDecorFitsSystemWindows(window, false) in MainActivity and configure android

Engineers MUST ALWAYS enable edge-to-edge explicitly via WindowCompat.setDecorFitsSystemWindows(window, false) in MainActivity and configure android:windowOptOutEdgeToEdgeEnforcement to false in styles.xml for API 35.

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 ALWAYS bind an OnApplyWindowInsetsListener to the Capacitor BridgeWebView that translates WindowInsetsCompat into direct CSS custom property updates via evaluateJavascript rather than relying on delayed window resize events.

Engineers MUST ALWAYS bind an OnApplyWindowInsetsListener to the Capacitor BridgeWebView that translates WindowInsetsCompat into direct CSS custom property updates via evaluateJavascript rather than relying on delayed window resize events.

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 NOT rely solely on CSS env(safe-area-inset-*) without fallback polyfills synchronized with native OnBackAnimationCallback progress events.

Engineers MUST NOT rely solely on CSS env(safe-area-inset-*) without fallback polyfills synchronized with native OnBackAnimationCallback progress events.

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

Components NEVER use 100vh or 100% height on root layout containers without pairing with dvh (Dynamic Viewport Height) or custom inset variables (--safe-area-inset-bottom, --ime-inset-bottom).

Components NEVER use 100vh or 100% height on root layout containers without pairing with dvh (Dynamic Viewport Height) or custom inset variables (--safe-area-inset-bottom, --ime-inset-bottom).

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

Native code MUST consume OnBackInvokedDispatcher with PRIORITY_DEFAULT or PRIORITY_OVERLAY and emit normalized progress events (0.0 to 1.0) to the Capacitor bridge to drive CSS scale/translate transforms.

Native code MUST consume OnBackInvokedDispatcher with PRIORITY_DEFAULT or PRIORITY_OVERLAY and emit normalized progress events (0.0 to 1.0) to the Capacitor bridge to drive CSS scale/translate transforms.

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

Engineers MUST NOT disable hardware acceleration on the BridgeWebView or its ancestor FrameLayout during predictive back gesture interception.

Engineers MUST NOT disable hardware acceleration on the BridgeWebView or its ancestor FrameLayout during predictive back gesture interception.

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 Capacitor 7 Android 15 Predictive Back & WindowInsets Synchronization Protocol critical for AI coding assistants?

Enforces edge-to-edge layout invariants and Viewport synchronization for Capacitor 7 running on Android 15 (API 35+). Prevents WebView compositor clipping, frame drops, and touch-target misalignment during predictive back gestures, software keyboard (IME) animations, and dynamic display cutout transitions. 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 (Unsynchronized CSS Viewport and Native Inset Polling During Predictive Back and IME Transitions) 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 MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor