mediaWidthRanges function

List<({double end, double width})> mediaWidthRanges(
  1. Iterable<MediaRule> rules,
  2. Breakpoints breakpoints
)

Screen widths that between them meet every combination of rules' width conditions: the first width of each range their bounds cut the widths into (from 0), each with the range's end (exclusive; infinity for the last).

Implementation

List<({double width, double end})> mediaWidthRanges(Iterable<MediaRule> rules, Breakpoints breakpoints) {
  final cuts = <double>{0};
  for (final r in rules) {
    if (r.lowest(breakpoints) case final double lo) cuts.add(lo);
    if (r.maxWidth is num) {
      // max-width: n holds up to n inclusive.
      cuts.add((r.maxWidth as num).toDouble() + 0.5);
    } else if (r.below(breakpoints) case final double hi when hi.isFinite) {
      cuts.add(hi);
    }
  }
  final sorted = cuts.where((c) => c >= 0 && c.isFinite).toList()..sort();
  return [
    for (var i = 0; i < sorted.length; i++) (width: sorted[i], end: i + 1 < sorted.length ? sorted[i + 1] : double.infinity),
  ];
}