calculateNodeDirection function

TextDirection calculateNodeDirection({
  1. required Node node,
  2. required TextDirection layoutDirection,
  3. String? defaultTextDirection,
  4. TextDirection? lastDirection,
})

Calculate the text direction of a node.

Implementation

// If the textDirection attribute is not set, we will use defaultTextDirection if
// it has a value (defaultTextDirection != null). If not will use layoutDirection.
// If the textDirection is ltr or rtl we will apply that.
// If the textDirection is auto we go by these priorities:
// 1. Determine the direction by first character with strong directionality
// 2. lastDirection which is the node last determined direction
// 3. previous line direction
// 4. defaultTextDirection
// 5. layoutDirection
// We will move from first priority when for example the node text is empty or
// it only has characters without strong directionality e.g. '@'.
TextDirection calculateNodeDirection({
  required Node node,
  required TextDirection layoutDirection,
  String? defaultTextDirection,
  TextDirection? lastDirection,
}) {
  // if the block component has a text direction attribute which is not auto,
  // use it
  final value = node.direction(defaultTextDirection);
  if (value != null && value != blockComponentTextDirectionAuto) {
    final direction = value.toTextDirection();
    if (direction != null) {
      return direction;
    }
  }

  if (value == blockComponentTextDirectionAuto) {
    if (lastDirection != null) {
      defaultTextDirection = lastDirection.name;
    } else {
      defaultTextDirection =
          _getDirectionFromPreviousOrParentNode(node, defaultTextDirection)
                  ?.name ??
              defaultTextDirection;
    }
  }

  // if the value is null or the text is null or empty,
  // use the default text direction
  final text = node.delta?.toPlainText();
  if (value == null || text == null || text.isEmpty) {
    return defaultTextDirection?.toTextDirection() ?? layoutDirection;
  }

  // if the value is auto and the text isn't null or empty,
  // calculate the text direction by the text
  return _determineTextDirection(text) ??
      defaultTextDirection?.toTextDirection() ??
      layoutDirection;
}