splitAt method
Splits this leaf node at index
and returns new node.
If this is the last node in its list and index
equals this node's
length then this method returns null
as there is nothing left to split.
If there is another leaf node after this one and index
equals this
node's length then the next leaf node is returned.
If index
equals to 0
then this node itself is returned unchanged.
In case a new node is actually split from this one, it inherits this node's style.
Implementation
LeafNode? splitAt(int index) {
assert(index >= 0 && index <= length);
if (index == 0) return this;
if (index == length && isLast) return null;
if (index == length && !isLast) return next as LeafNode?;
if (this is TextNode) {
final text = _value as String;
_value = text.substring(0, index);
final split = LeafNode(text.substring(index));
split.applyStyle(style);
insertAfter(split);
return split;
} else {
// This is an EmbedNode which cannot be split and has length of 1.
// Technically this branch is unreachable because we've already checked
// edge scenarios when index is either at 0 (start) or 1 (end) of this
// node above, e.g. for embed nodes:
// * calling splitAt(0) returns the embed node itself;
// * calling splitAt(1) depends on whether this node is the last one:
// - if last then `null` is returned as there is nothing to split
// - otherwise next node is returned
throw StateError('Unreachable.');
}
}