chooseRoutes static method

Map<dynamic, String> chooseRoutes(
  1. BeamState state,
  2. Iterable routes
)

Chooses all the routes that "sub-match" state.uri to stack their pages.

If none of the routes matches state.uri, nothing will be selected and BeamerDelegate will declare that the location is NotFound.

Implementation

static Map<dynamic, String> chooseRoutes(
    BeamState state, Iterable<dynamic> routes) {
  var matched = <dynamic, String>{};
  bool overrideNotFound = false;
  for (var route in routes) {
    if (route is String) {
      final uriPathSegments = List.from(state.uri.pathSegments);
      final routePathSegments = Uri.parse(route).pathSegments;

      if (uriPathSegments.length < routePathSegments.length) {
        continue;
      }

      var checksPassed = true;
      var path = '';
      for (int i = 0; i < routePathSegments.length; i++) {
        path += '/${uriPathSegments[i]}';

        if (routePathSegments[i] == '*') {
          overrideNotFound = true;
          continue;
        }
        if (routePathSegments[i].startsWith(':')) {
          continue;
        }
        if (routePathSegments[i] != uriPathSegments[i]) {
          checksPassed = false;
          break;
        }
      }

      if (checksPassed) {
        matched[route] = Uri(
          path: path == '' ? '/' : path,
          queryParameters:
              state.queryParameters.isEmpty ? null : state.queryParameters,
        ).toString();
      }
    } else {
      final regexp = Utils.tryCastToRegExp(route);
      if (regexp.hasMatch(state.uri.toString())) {
        final path = state.uri.toString();
        matched[regexp] = Uri(
          path: path == '' ? '/' : path,
          queryParameters:
              state.queryParameters.isEmpty ? null : state.queryParameters,
        ).toString();
      }
    }
  }

  bool isNotFound = true;
  matched.forEach((key, value) {
    if (Utils.urisMatch(key, state.uri)) {
      isNotFound = false;
    }
  });

  if (overrideNotFound) {
    return matched;
  }

  return isNotFound ? {} : matched;
}