htmlDeclaresPageBackground function

bool htmlDeclaresPageBackground(
  1. String html
)

作者有没有给整页(html / body / :root / *)声明背景。

用它决定深色档要不要接管文字颜色:

  • 作者没管背景 ⇒ 底色是我们按主题换上去的,这一页的配色本来就不保真, 文字颜色也一并由我们定(统一浅灰),否则作者写死的深色字在深底上读不出来 (notes 仓库 outline/17-html.html 的 h2{color:#123}、27-plain.html 的 body{color:#222} 都是这种);
  • 作者管了背景(body{background:#fff} 之类)⇒ 那一页是自洽的白底黑字, 我们只补底色兜底,字色一律不碰 —— 否则就是白底白字。

只看整页选择器:28-sticky.html 的 .topbar{background:#123} 是局部配色, 不能因此认定「作者管了背景」(那样正文就漏修了)。代价也说清:本页里有白底 卡片、而整页背景没声明的页面,卡片里的字会跟着变成浅灰 —— 深色档不谈保真, 这是有意的取舍。

Implementation

bool htmlDeclaresPageBackground(String html) {
  for (final RegExpMatch block
      in RegExp(r'<style\b[^>]*>([\s\S]*?)</style\s*>', caseSensitive: false)
          .allMatches(html)) {
    // 注释里的 `body{background:…}` 不生效,先摘掉
    final String text = block.group(1)!.replaceAll(RegExp(r'/\*[\s\S]*?\*/'), '');
    for (final RegExpMatch rule
        in RegExp(r'([^{}]+)\{([^{}]*)\}').allMatches(text)) {
      if (_isPageSelector(rule.group(1)!) && _declaresBackground(rule.group(2)!)) {
        return true;
      }
    }
  }
  for (final RegExpMatch tag in RegExp(
    r'<(?:html|body)\b[^>]*>',
    caseSensitive: false,
  ).allMatches(html)) {
    final String element = tag.group(0)!;
    // `<body bgcolor="#fff">` 这种上古写法也算作者管了背景
    if (RegExp(r'\sbgcolor\s*=', caseSensitive: false).hasMatch(element)) {
      return true;
    }
    // 内联样式挂的就是整页那一层,本身就是一串声明,不需要选择器
    final RegExpMatch? style = RegExp(
      r'''style\s*=\s*("([^"]*)"|'([^']*)')''',
      caseSensitive: false,
    ).firstMatch(element);
    final String? css = style == null ? null : (style.group(2) ?? style.group(3));
    if (css != null && _declaresBackground(css)) {
      return true;
    }
  }
  return false;
}