optimize method

  1. @override
void optimize()
override

Optimizes this text node by merging it with adjacent nodes if they share the same style.

Implementation

@override
void optimize() {
  if (this is EmbedNode) {
    // Embed nodes cannot be merged with text nor other embeds (in fact,
    // there could be no two adjacent embeds on the same line since an
    // embed occupies an entire line).
    return;
  }

  // This is a text node and it can only be merged with other text nodes.

  TextNode node = this as TextNode;
  if (!node.isFirst && node.previous is TextNode) {
    TextNode mergeWith = node.previous as TextNode;
    if (mergeWith.style == node.style) {
      final combinedValue = mergeWith.value + node.value;
      mergeWith._value = combinedValue;
      node.unlink();
      node = mergeWith;
    }
  }
  if (!node.isLast && node.next is TextNode) {
    TextNode mergeWith = node.next as TextNode;
    if (mergeWith.style == node.style) {
      final combinedValue = node.value + mergeWith.value;
      node._value = combinedValue;
      mergeWith.unlink();
    }
  }
}