chooseRoutes static method

Map<Pattern, String> chooseRoutes(
  1. RouteInformation routeInformation,
  2. Iterable<Pattern> routes
)

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

If routeInformation doesn't match any of the routes, nothing will be selected and BeamerDelegate will declare that the location is NotFound.

Implementation

static Map<Pattern, String> chooseRoutes(
  RouteInformation routeInformation,
  Iterable<Pattern> routes,
) {
  String createMatch(String path, Map<String, String> queryParameters) => Uri(
        path: path == '' ? '/' : path,
        queryParameters: queryParameters.isEmpty ? null : queryParameters,
      ).toString();

  final matched = <Pattern, String>{};
  var overrideNotFound = false;
  final uri = Utils.removeTrailingSlash(routeInformation.uri);

  for (final route in routes) {
    if (route is String) {
      if (uri.path.isEmpty) {
        continue;
      }

      if (route.startsWith('/') && !uri.path.startsWith('/')) {
        continue;
      }

      if (route == '*') {
        matched[route] = createMatch(uri.path, uri.queryParameters);
        overrideNotFound = true;
        continue;
      }

      if (route == '/*' && uri.path == '/') {
        matched[route] = createMatch(uri.path, uri.queryParameters);
        overrideNotFound = true;
        continue;
      }

      final uriPathSegments = uri.pathSegments.toList();
      final routePathSegments = Uri.parse(route).pathSegments;

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

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

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

      if (checksPassed) {
        matched[route] = createMatch(path, uri.queryParameters);
      }
    } else {
      final regexp = Utils.tryCastToRegExp(route);
      if (regexp.hasMatch(uri.toString())) {
        final path = uri.toString();
        matched[regexp] = createMatch(path, uri.queryParameters);
      }
    }
  }

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

  if (overrideNotFound) {
    return matched;
  }

  return isNotFound ? {} : matched;
}