ResponsiveData.fromMediaQuery constructor

ResponsiveData.fromMediaQuery(
  1. MediaQueryData? media,
  2. ScalifyConfig cfg
)

Factory to compute ResponsiveData from MediaQueryData.

Implementation

factory ResponsiveData.fromMediaQuery(
    MediaQueryData? media, ScalifyConfig cfg) {
  if (media == null) return ResponsiveData.identity;

  final width = media.size.width;
  final height = media.size.height;

  if (width == 0 || height == 0) return ResponsiveData.identity;

  // ScreenType Logic
  ScreenType type;
  if (width < cfg.mobileBreakpoint) {
    type =
        (width < cfg.watchBreakpoint) ? ScreenType.watch : ScreenType.mobile;
  } else if (width < cfg.smallDesktopBreakpoint) {
    type = (width < cfg.tabletBreakpoint)
        ? ScreenType.tablet
        : ScreenType.smallDesktop;
  } else {
    type = (width < cfg.desktopBreakpoint)
        ? ScreenType.desktop
        : ScreenType.largeDesktop;
  }

  // Scale Logic
  double designWidth = cfg.designWidth;
  double designHeight = cfg.designHeight;

  if (cfg.autoSwapDimensions) {
    final bool isLandscape = width > height;
    if (isLandscape) {
      designWidth = cfg.designHeight;
      designHeight = cfg.designWidth;
    }
  }

  double calculatedScaleWidth = width / designWidth;
  if (width > cfg.memoryProtectionThreshold) {
    final thresholdScale = cfg.memoryProtectionThreshold / designWidth;
    final excessWidth = width - cfg.memoryProtectionThreshold;
    calculatedScaleWidth = thresholdScale +
        ((excessWidth / designWidth) * cfg.highResScaleFactor);
  }

  final double finalScaleWidth =
      calculatedScaleWidth.clamp(cfg.minScale, cfg.maxScale);
  final double finalScaleHeight =
      (height / designHeight).clamp(cfg.minScale, cfg.maxScale);

  // Combine width/height scaling into a single stable scaleFactor.
  // We use the minimum to avoid overstretching UI on one axis while the other is small.
  final double finalCombined = math.min(finalScaleWidth, finalScaleHeight);

  // Use standard text scale factor
  final double systemTextScaleFactor = media.textScaler.scale(1.0);

  return ResponsiveData._(
    size: Size(width, height),
    textScaleFactor: systemTextScaleFactor,
    screenType: type,
    config: cfg,
    scaleWidth: finalScaleWidth,
    scaleHeight: finalScaleHeight,
    scaleFactor: finalCombined,
    scaleWidthId: (finalScaleWidth * 1000).round(),
    scaleHeightId: (finalScaleHeight * 1000).round(),
    scaleFactorId: (finalCombined * 1000).round(),
    textScaleFactorId: (systemTextScaleFactor * 100).round(),
  );
}