getScreenContext method

ScreenContext getScreenContext(
  1. String? currentRoute
)

Get or rebuild the screen context for the current route.

Implementation

ScreenContext getScreenContext(String? currentRoute) {
  if (currentRoute != null && !_screenDirty) {
    final entry = _screenCache[currentRoute];
    if (entry != null && !entry.isExpired(screenTtl)) {
      // Move to end (most recently used).
      _screenCache.remove(currentRoute);
      _screenCache[currentRoute] = entry;
      AiLogger.log(
        'Screen cache HIT for route "$currentRoute"',
        tag: 'Cache',
      );
      _wasDirty = false;
      return entry.value;
    }
  }

  // Rebuild.
  _wasDirty = true;
  AiLogger.log(
    'Screen cache MISS for route "$currentRoute" — rebuilding',
    tag: 'Cache',
  );
  final context = onCaptureScreen?.call() ?? ScreenContext.empty();
  if (currentRoute != null) {
    _screenCache[currentRoute] = _CacheEntry(context);
    // Evict LRU if over capacity.
    while (_screenCache.length > _maxScreenEntries) {
      final evicted = _screenCache.keys.first;
      _screenCache.remove(evicted);
      AiLogger.log('Screen cache evicted LRU entry "$evicted"', tag: 'Cache');
    }
    // Store in progressive knowledge.
    AiNavigatorObserver.cacheScreenKnowledge(currentRoute, context);
  }
  _screenDirty = false;
  return context;
}