dvSsrFirstThemeFromPages function

String? dvSsrFirstThemeFromPages(
  1. List<DVSsrThemePage?> pages, {
  2. Map<String, List<DVLayoutFont>> fonts = const <String, List<DVLayoutFont>>{},
})

dvSsrFirstTheme from each page's dvSsrFirstThemePage, in page order.

Implementation

String? dvSsrFirstThemeFromPages(
  List<DVSsrThemePage?> pages, {
  Map<String, List<DVLayoutFont>> fonts = const <String, List<DVLayoutFont>>{},
}) {
  // By width: each role's painted paragraphs, and each page's column.
  final Map<int, Map<String, List<_Item>>> styles = <int, Map<String, List<_Item>>>{};
  final Map<int, List<double>> lefts = <int, List<double>>{};
  final Map<int, List<double>> gutters = <int, List<double>>{};
  final Map<int, List<double>> tops = <int, List<double>>{};
  final Map<int, Map<String, List<double>>> after = <int, Map<String, List<double>>>{};
  _Layout? styler;
  for (final DVSsrThemePage? page in pages) {
    if (page == null) continue;
    if (styler == null) {
      styler = page._layout;
      if (styler == null) throw StateError('The first page of the SSR-first theme was given without its layout.');
    }
    for (final _ThemeWidth part in page._widths) {
      final int width = part.width;
      for (final (String role, _Item item) in part.styled) {
        styles.putIfAbsent(width, () => <String, List<_Item>>{}).putIfAbsent(role, () => <_Item>[]).add(item);
      }
      final (double, double, double)? column = part.column;
      if (column == null) continue;
      lefts.putIfAbsent(width, () => <double>[]).add(column.$1);
      gutters.putIfAbsent(width, () => <double>[]).add(column.$2);
      tops.putIfAbsent(width, () => <double>[]).add(column.$3);
      for (final (String key, double gap) in part.after) {
        after.putIfAbsent(width, () => <String, List<double>>{}).putIfAbsent(key, () => <double>[]).add(gap);
      }
    }
  }
  if (styler == null || lefts.isEmpty) return null;
  final _Layout layout = styler;

  double median(List<double> values) {
    final List<double> sorted = <double>[...values]..sort();
    return sorted[sorted.length ~/ 2];
  }

  /// The paragraph that says most of [items]' text: the role's usual look.
  _Item usual(List<_Item> items) {
    final Map<String, int> weight = <String, int>{};
    final Map<String, _Item> sample = <String, _Item>{};
    for (final _Item item in items) {
      if (item.runs.isEmpty) continue;
      final String key = '${layout._font(item.runs.first, item.json['lh'])}|${item.runs.first['c']}';
      weight[key] = (weight[key] ?? 0) + item.text.length;
      sample.putIfAbsent(key, () => item);
    }
    String best = sample.keys.first;
    for (final String key in sample.keys) {
      if (weight[key]! > weight[best]!) best = key;
    }
    return sample[best]!;
  }

  final List<int> widths = lefts.keys.toList()..sort();
  final StringBuffer gated = StringBuffer()
    ..write('.dv-fallback:has(>.$dvSsrThemeClass){padding:0}')
    ..write('.$dvSsrThemeClass{box-sizing:border-box;padding-bottom:48px}')
    // `*:is`, not ` :is`: the page minifier takes the space before a colon.
    ..write('.$dvSsrThemeClass *:is(h1,h2,h3,h4,h5,h6,p,li){margin:0 0 16px}');
  final Map<String, String> lastMargin = <String, String>{};
  final Map<String, String> lastLight = <String, String>{};
  final Map<String, String> lastDark = <String, String>{};
  for (int index = 0; index < widths.length; index++) {
    final int width = widths[index];
    final StringBuffer block = StringBuffer();
    final StringBuffer dark = StringBuffer();
    // The column: its left edge and right gutter move linearly to the next
    // captured width, as the layout's boxes do.
    String between(Map<int, List<double>> values) {
      final double here = median(values[width]!);
      if (widths.length < 2) return '${_num(here)}px';
      final int from = index + 1 < widths.length ? index : index - 1;
      final int a = widths[from], b = widths[from + 1];
      return _linear(a.toDouble(), median(values[a]!), b.toDouble(), median(values[b]!));
    }

    block.write('.$dvSsrThemeClass{padding-left:${between(lefts)};padding-right:${between(gutters)};'
        'padding-top:${_num(median(tops[width]!))}px}');
    final Map<String, List<_Item>> roles = styles[width] ?? const <String, List<_Item>>{};
    for (final String role in <String>[..._themeRoles, 'a']) {
      final List<_Item>? items = roles[role];
      if (items == null || items.isEmpty) continue;
      final _Item item = usual(items);
      final Map<String, Object?> run = item.runs.first;
      final String light = <String>[
        'font:${layout._font(run, item.json['lh'])}',
        ...layout._inlineExtras(run),
        if (role == 'a') 'text-decoration:none',
      ].join(';');
      // The space the app leaves after this kind of block at this width.
      final Map<String, List<double>> gapsHere = after[width] ?? const <String, List<double>>{};
      final bool heading = role.startsWith('h') && role != 'li';
      // The lower quartile, so the space where one section ends and the
      // next begins is not read as the space inside a text; below a block,
      // at most one and a half of its lines.
      final double line = (items.isEmpty ? null : usual(items).json['lh'] as num?)?.toDouble() ?? 24;
      String? space(String key, {required bool capped}) {
        final List<double>? gaps = gapsHere[key];
        if (gaps == null) return null;
        final List<double> sorted = <double>[...gaps]..sort();
        final double quartile = sorted[sorted.length ~/ 4];
        return '${_num(math.min(quartile, capped ? line * 1.5 : 96).clamp(0, 96).roundToDouble())}px';
      }

      final String? top = heading ? space('before:$role', capped: false) : null;
      final String? bottom = heading ? space('after:$role', capped: true) : space('same:$role', capped: true);
      if (role != 'a' && (top != null || bottom != null)) {
        final String margin = 'margin:${top ?? '0'} 0 ${bottom ?? '16px'}';
        if (lastMargin[role] != margin) {
          block.write('.$dvSsrThemeClass $role{$margin}');
          lastMargin[role] = margin;
        }
      }
      if (lastLight[role] != light) {
        block.write('.$dvSsrThemeClass $role{$light}');
        lastLight[role] = light;
      }
      final Map<String, Object?>? darkRun = item.dark == null || item.dark!.runs.isEmpty ? null : item.dark!.runs.first;
      final String? darkColour = darkRun == null ? null : _colour(darkRun['c']);
      if (darkColour != null && lastDark[role] != darkColour) {
        dark.write('.$dvSsrThemeClass $role{color:$darkColour}');
        lastDark[role] = darkColour;
      }
    }
    if (dark.isNotEmpty) block.write('@media (prefers-color-scheme:dark){$dark}');
    gated.write(index == 0 ? '$block' : '@media (min-width:${width}px){$block}');
  }
  return '${layout._fontFaces()}'
      '@media screen and (scripting:enabled){html:not([data-dv-app]):not([data-dv-plain]){$gated}}';
}