calcAnchorTabIndex static method

int calcAnchorTabIndex({
  1. required ObserveModel observeModel,
  2. required List<int> tabIndexs,
  3. required int currentTabIndex,
})

Calculate the anchor tab index.

Implementation

static int calcAnchorTabIndex({
  required ObserveModel observeModel,
  required List<int> tabIndexs,
  required int currentTabIndex,
}) {
  if (currentTabIndex >= tabIndexs.length) {
    return currentTabIndex;
  }
  if (observeModel is ListViewObserveModel) {
    final topIndex = observeModel.firstChild?.index ?? 0;
    final index = tabIndexs.indexOf(topIndex);
    if (isValidListIndex(index)) {
      return index;
    }
    var targetTabIndex = currentTabIndex - 1;
    if (targetTabIndex < 0 || targetTabIndex >= tabIndexs.length) {
      return currentTabIndex;
    }
    var curIndex = tabIndexs[currentTabIndex];
    var lastIndex = tabIndexs[currentTabIndex - 1];
    if (curIndex > topIndex && lastIndex < topIndex) {
      final lastTabIndex = tabIndexs.indexOf(lastIndex);
      if (isValidListIndex(lastTabIndex)) {
        return lastTabIndex;
      }
    }
  } else if (observeModel is GridViewObserveModel) {
    final firstGroupChildList = observeModel.firstGroupChildList;
    if (firstGroupChildList.isEmpty) {
      return currentTabIndex;
    }
    // Record the child with the shortest distance from the bottom.
    GridViewObserveDisplayingChildModel mainChildModel =
        firstGroupChildList.first;
    for (var firstGroupChildModel in firstGroupChildList) {
      final index = tabIndexs.indexOf(firstGroupChildModel.index);
      if (isValidListIndex(index)) {
        // Found the target index from tabIndexs, return directly.
        return index;
      }
      if (mainChildModel.trailingMarginToViewport <
          firstGroupChildModel.trailingMarginToViewport) {
        mainChildModel = firstGroupChildModel;
      }
    }
    // Target index not found from tabIndexs.
    var targetTabIndex = currentTabIndex - 1;
    if (targetTabIndex < 0 || targetTabIndex >= tabIndexs.length) {
      return currentTabIndex;
    }
    var curIndex = tabIndexs[currentTabIndex];
    final firstGroupIndexList =
        firstGroupChildList.map((e) => e.index).toList();
    final minOffset = mainChildModel.layoutOffset;
    final maxOffset =
        mainChildModel.layoutOffset + mainChildModel.mainAxisSize;
    final displayingChildModelList =
        observeModel.displayingChildModelList.where((e) {
      return !firstGroupIndexList.contains(e.index) &&
          e.layoutOffset >= minOffset &&
          e.layoutOffset <= maxOffset;
    }).toList();
    // If the indexes of all the children currently being displayed are
    // greater than curIndex, keep using currentTabIndex.
    // Otherwise, using targetTabIndex.
    for (var model in displayingChildModelList) {
      if (model.index <= curIndex) {
        return targetTabIndex;
      }
    }
  }
  return currentTabIndex;
}