injectStyleIntoHtml function

String injectStyleIntoHtml(
  1. String html,
  2. String css
)

把 css 作为一段 <style> 注入 html。

位置:紧随 <head> 开始标签 → 没有 head 就紧随 <!doctype> → 两者都没有才前置。

⚠️ 绝不能插到 doctype 之前:doctype 前出现任何内容都会让浏览器退回怪异模式 (quirks mode),盒模型随之改变,整页变形 —— 这就是后面那两段 fallback 存在的理由。

插在文档靠前是有意的:作者自己的样式在后面、优先级更高,我们只做兜底 (页面自己声明了底色就让它保持自己的底色)。样式表内也一样, 所以 html,body{background} 这种兜底规则会被作者后面的声明覆盖。

唯一的例外是链接下划线(htmlPreviewCss 产出的 CSS 里带 !important): 底色是「作者没表态时替他兜底」,而链接下划线是「作者表态了也必须改」—— 因为在 墨水屏上「下划线」是认出链接的唯一线索,作者那句 text-decoration:none 正是 「靠颜色区分」的写法。!important 挡的是同 / 更高特异性的作者规则(普通 a 本来就压得过,见 htmlPreviewCss 的注释)。这个不对称是有意的,别当疏漏「统一」掉。

Implementation

String injectStyleIntoHtml(String html, String css) {
  final String style = '<style>$css</style>';
  final RegExpMatch? head = RegExp(
    r'<head[^>]*>',
    caseSensitive: false,
  ).firstMatch(html);
  if (head != null) {
    return html.replaceRange(head.end, head.end, style);
  }
  final RegExpMatch? doctype = RegExp(
    r'<!doctype[^>]*>',
    caseSensitive: false,
  ).firstMatch(html);
  if (doctype != null) {
    return html.replaceRange(doctype.end, doctype.end, style);
  }
  return style + html;
}