cleanupStackTrackedScopesExcept static method

void cleanupStackTrackedScopesExcept(
  1. String keepScopeName
)

Clean up only scopes that are tracked in the scope stack This preserves manually created scopes that aren't part of navigation

Implementation

static void cleanupStackTrackedScopesExcept(String keepScopeName) {
  final stackScopes = ZenScopeStackTracker.getCurrentStack();
  final scopesToCleanup =
      stackScopes.where((scopeName) => scopeName != keepScopeName).toList();

  if (ZenConfig.enableDebugLogs && scopesToCleanup.isNotEmpty) {
    ZenLogger.logDebug(
        '๐Ÿงน Cleaning up stack-tracked scopes: ${scopesToCleanup.join(', ')}');
  }

  for (final scopeName in scopesToCleanup) {
    final scope =
        _persistentScopes[scopeName] ?? _autoDisposeScopes[scopeName];
    if (scope != null && !scope.isDisposed) {
      if (ZenConfig.enableDebugLogs) {
        ZenLogger.logDebug('๐Ÿ—‘๏ธ Disposing stack-tracked scope: $scopeName');
      }
      scope.dispose();

      // Remove from tracking maps ONLY after disposal to preserve hierarchy during disposal
      _persistentScopes.remove(scopeName);
      _autoDisposeScopes.remove(scopeName);
      _removeScopeFromTracking(scopeName);
    }
  }
}