inlineAssetsIntoDocument function

Future inlineAssetsIntoDocument(
  1. Document doc,
  2. Directory? assetDirectory
)

Replaces link and script tags within a doc with the static contents they would otherwise trigger an HTTP request to.

Powers both inlineAssets and inlineAssetsFromVirtualDirectory.

Implementation

Future inlineAssetsIntoDocument(
    html.Document doc, Directory? assetDirectory) async {
  var linksWithRel = doc.head
          ?.getElementsByTagName('link')
          .where((link) => link.attributes['rel'] == 'stylesheet') ??
      <html.Element>[];

  for (var link in linksWithRel) {
    if (link.attributes.containsKey('data-no-inline')) {
      link.attributes.remove('data-no-inline');
    } else {
      var uri = Uri.parse(link.attributes['href']!);

      if (uri.scheme.isEmpty) {
        var styleFile = assetDirectory!.childFile(uri.path);

        if (await styleFile.exists()) {
          var style = html.Element.tag('style')
            ..innerHtml = await styleFile.readAsString();
          link.replaceWith(style);
        }
      }
    }
  }

  var scripts = doc
      .getElementsByTagName('script')
      .where((script) => script.attributes.containsKey('src'));

  for (var script in scripts) {
    if (script.attributes.containsKey('data-no-inline')) {
      script.attributes.remove('data-no-inline');
    } else {
      var uri = Uri.parse(script.attributes['src']!);

      if (uri.scheme.isEmpty) {
        var scriptFile = assetDirectory!.childFile(uri.path);
        if (await scriptFile.exists()) {
          script.attributes.remove('src');
          script.innerHtml = await scriptFile.readAsString();
        }
      }
    }
  }
}