apply method

  1. @override
void apply(
  1. MarkupRenderObject root
)
override

Implementation

@override
void apply(MarkupRenderObject root) {
  final (html, head, body) = createDocumentStructure(root);

  String? keyFor(MarkupRenderObject n) {
    return switch (n) {
      MarkupRenderObject(id: String id) when id.isNotEmpty => id,
      MarkupRenderObject(tag: "title" || "base") => '__${n.tag}',
      MarkupRenderObject(tag: "meta", attributes: {'name': String name}) => '__meta:$name',
      _ => null,
    };
  }

  for (final MapEntry(:key, :value) in entries.entries) {
    var target = switch (key) {
      'html' => html,
      'head' => head,
      'body' => body,
      _ => throw StateError('Unknown target $key'),
    };

    if (value.attributes.isNotEmpty) {
      (target.attributes ??= {}).addAll(value.attributes);
    }

    if (value.children.isNotEmpty) {
      target.children.insertBefore(target.createChildRenderObject()..updateText(r'<!--$-->', true));

      List<MarkupRenderObject> nodes = [];
      Map<String, (int, int)> indices = {};

      for (var e in value.children) {
        e.$1.remove();
        for (var n in e.$1) {
          var key = keyFor(n);
          if (key == null) {
            nodes.add(n);
            continue;
          }
          var index = indices[key];
          if (index == null) {
            nodes.add(n);
            indices[key] = (nodes.length - 1, e.$2);
          }
          if (index != null && e.$2 >= index.$2) {
            nodes[index.$1] = n;
          }
        }
      }

      for (var n in nodes) {
        target.children.insertBefore(n);
      }

      target.children.insertBefore(target.createChildRenderObject()..updateText(r'<!--/-->', true));
    }
  }
}