forked from flutter/packages
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfiguration.dart
More file actions
863 lines (794 loc) · 27.7 KB
/
configuration.dart
File metadata and controls
863 lines (794 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'logging.dart';
import 'match.dart';
import 'misc/constants.dart';
import 'misc/errors.dart';
import 'path_utils.dart';
import 'route.dart';
import 'router.dart' show GoRouter, OnEnter, RoutingConfig;
import 'state.dart';
/// The signature of the redirect callback.
typedef GoRouterRedirect =
FutureOr<String?> Function(BuildContext context, GoRouterState state);
typedef _NamedPath = ({String path, bool caseSensitive});
/// The route configuration for GoRouter configured by the app.
class RouteConfiguration {
/// Constructs a [RouteConfiguration].
RouteConfiguration(
this._routingConfig, {
required this.navigatorKey,
this.extraCodec,
this.router,
}) {
_onRoutingTableChanged();
_routingConfig.addListener(_onRoutingTableChanged);
}
static bool _debugCheckPath(List<RouteBase> routes, bool isTopLevel) {
for (final route in routes) {
late bool subRouteIsTopLevel;
if (route is GoRoute) {
if (route.path != '/') {
assert(
!route.path.endsWith('/'),
'route path may not end with "/" except for the top "/" route. Found: $route',
);
}
subRouteIsTopLevel = false;
} else if (route is ShellRouteBase) {
subRouteIsTopLevel = isTopLevel;
}
_debugCheckPath(route.routes, subRouteIsTopLevel);
}
return true;
}
// Check that each parentNavigatorKey refers to either a ShellRoute's
// navigatorKey or the root navigator key.
static bool _debugCheckParentNavigatorKeys(
List<RouteBase> routes,
List<GlobalKey<NavigatorState>> allowedKeys,
) {
for (final route in routes) {
if (route is GoRoute) {
final GlobalKey<NavigatorState>? parentKey = route.parentNavigatorKey;
if (parentKey != null) {
// Verify that the root navigator or a ShellRoute ancestor has a
// matching navigator key.
assert(
allowedKeys.contains(parentKey),
'parentNavigatorKey $parentKey must refer to'
" an ancestor ShellRoute's navigatorKey or GoRouter's"
' navigatorKey',
);
_debugCheckParentNavigatorKeys(
route.routes,
<GlobalKey<NavigatorState>>[
// Once a parentNavigatorKey is used, only that navigator key
// or keys above it can be used.
...allowedKeys.sublist(0, allowedKeys.indexOf(parentKey) + 1),
],
);
} else {
_debugCheckParentNavigatorKeys(
route.routes,
<GlobalKey<NavigatorState>>[...allowedKeys],
);
}
} else if (route is ShellRoute) {
_debugCheckParentNavigatorKeys(
route.routes,
<GlobalKey<NavigatorState>>[...allowedKeys, route.navigatorKey],
);
} else if (route is StatefulShellRoute) {
for (final StatefulShellBranch branch in route.branches) {
assert(
!allowedKeys.contains(branch.navigatorKey),
'StatefulShellBranch must not reuse an ancestor navigatorKey '
'(${branch.navigatorKey})',
);
_debugCheckParentNavigatorKeys(
branch.routes,
<GlobalKey<NavigatorState>>[...allowedKeys, branch.navigatorKey],
);
}
}
}
return true;
}
static bool _debugVerifyNoDuplicatePathParameter(
List<RouteBase> routes,
Map<String, GoRoute> usedPathParams,
) {
for (final route in routes) {
if (route is! GoRoute) {
continue;
}
for (final String pathParam in route.pathParameters) {
if (usedPathParams.containsKey(pathParam)) {
final sameRoute = usedPathParams[pathParam] == route;
throw GoError(
"duplicate path parameter, '$pathParam' found in ${sameRoute ? '$route' : '${usedPathParams[pathParam]}, and $route'}",
);
}
usedPathParams[pathParam] = route;
}
_debugVerifyNoDuplicatePathParameter(route.routes, usedPathParams);
route.pathParameters.forEach(usedPathParams.remove);
}
return true;
}
// Check to see that the configured initialLocation of StatefulShellBranches
// points to a descendant route of the route branch.
bool _debugCheckStatefulShellBranchDefaultLocations(List<RouteBase> routes) {
for (final route in routes) {
if (route is StatefulShellRoute) {
for (final StatefulShellBranch branch in route.branches) {
if (branch.initialLocation == null) {
// Recursively search for the first GoRoute descendant. Will
// throw assertion error if not found.
final GoRoute? defaultGoRoute = branch.defaultRoute;
final String? initialLocation = defaultGoRoute != null
? locationForRoute(defaultGoRoute)
: null;
assert(
initialLocation != null,
'The default location of a StatefulShellBranch must be '
'derivable from GoRoute descendant',
);
assert(
defaultGoRoute!.pathParameters.isEmpty,
'The default location of a StatefulShellBranch cannot be '
'a parameterized route',
);
} else {
final RouteMatchList matchList = findMatch(
Uri.parse(branch.initialLocation!),
);
assert(
!matchList.isError,
'initialLocation (${matchList.uri}) of StatefulShellBranch must '
'be a valid location',
);
final List<RouteBase> matchRoutes = matchList.routes;
final int shellIndex = matchRoutes.indexOf(route);
var matchFound = false;
if (shellIndex >= 0 && (shellIndex + 1) < matchRoutes.length) {
final RouteBase branchRoot = matchRoutes[shellIndex + 1];
matchFound = branch.routes.contains(branchRoot);
}
assert(
matchFound,
'The initialLocation (${branch.initialLocation}) of '
'StatefulShellBranch must match a descendant route of the '
'branch',
);
}
}
}
_debugCheckStatefulShellBranchDefaultLocations(route.routes);
}
return true;
}
/// The match used when there is an error during parsing.
static RouteMatchList _errorRouteMatchList(
Uri uri,
GoException exception, {
Object? extra,
}) {
return RouteMatchList(
matches: const <RouteMatch>[],
extra: extra,
error: exception,
uri: uri,
pathParameters: const <String, String>{},
);
}
void _onRoutingTableChanged() {
final RoutingConfig routingTable = _routingConfig.value;
assert(_debugCheckPath(routingTable.routes, true));
assert(
_debugVerifyNoDuplicatePathParameter(
routingTable.routes,
<String, GoRoute>{},
),
);
assert(
_debugCheckParentNavigatorKeys(
routingTable.routes,
<GlobalKey<NavigatorState>>[navigatorKey],
),
);
assert(_debugCheckStatefulShellBranchDefaultLocations(routingTable.routes));
_nameToPath.clear();
_cacheNameToPath('', routingTable.routes);
log(debugKnownRoutes());
}
/// Builds a [GoRouterState] suitable for top level callback such as
/// `GoRouter.redirect` or `GoRouter.onException`.
GoRouterState buildTopLevelGoRouterState(RouteMatchList matchList) {
return GoRouterState(
this,
uri: matchList.uri,
// No name available at the top level trim the query params off the
// sub-location to match route.redirect
fullPath: matchList.fullPath,
pathParameters: matchList.pathParameters,
matchedLocation: matchList.uri.path,
extra: matchList.extra,
pageKey: const ValueKey<String>('topLevel'),
topRoute: matchList.lastOrNull?.route,
error: matchList.error,
);
}
/// The routing table.
final ValueListenable<RoutingConfig> _routingConfig;
/// The list of top level routes used by [GoRouterDelegate].
List<RouteBase> get routes => _routingConfig.value.routes;
/// Legacy top level page redirect.
///
/// This is handled via [applyTopLegacyRedirect] inside [redirect].
GoRouterRedirect get topRedirect => _routingConfig.value.redirect;
/// Top level page on enter.
OnEnter? get topOnEnter => _routingConfig.value.onEnter;
/// The limit for the number of consecutive redirects.
int get redirectLimit => _routingConfig.value.redirectLimit;
/// Normalizes a URI by ensuring it has a valid path and removing trailing slashes.
static Uri normalizeUri(Uri uri) {
if (uri.hasEmptyPath) {
return uri.replace(path: '/');
} else if (uri.path.length > 1 && uri.path.endsWith('/')) {
return uri.replace(path: uri.path.substring(0, uri.path.length - 1));
}
return uri;
}
/// The global key for top level navigator.
final GlobalKey<NavigatorState> navigatorKey;
/// The codec used to encode and decode extra into a serializable format.
///
/// When navigating using [GoRouter.go] or [GoRouter.push], one can provide
/// an `extra` parameter along with it. If the extra contains complex data,
/// consider provide a codec for serializing and deserializing the extra data.
///
/// See also:
/// * [Navigation](https://pub.dev/documentation/go_router/latest/topics/Navigation-topic.html)
/// topic.
/// * [extra_codec](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/extra_codec.dart)
/// example.
/// * [topOnEnter] for navigation interception.
/// * [topRedirect] for legacy redirections.
final Codec<Object?, Object?>? extraCodec;
/// The GoRouter instance that owns this configuration.
///
/// This is used to provide access to the router during redirects.
final GoRouter? router;
final Map<String, _NamedPath> _nameToPath = <String, _NamedPath>{};
/// Looks up the url location by a [GoRoute]'s name.
String namedLocation(
String name, {
Map<String, String> pathParameters = const <String, String>{},
Map<String, dynamic> queryParameters = const <String, dynamic>{},
String? fragment,
}) {
assert(() {
log(
'getting location for name: '
'"$name"'
'${pathParameters.isEmpty ? '' : ', pathParameters: $pathParameters'}'
'${queryParameters.isEmpty ? '' : ', queryParameters: $queryParameters'}'
'${fragment != null ? ', fragment: $fragment' : ''}',
);
return true;
}());
assert(_nameToPath.containsKey(name), 'unknown route name: $name');
final _NamedPath path = _nameToPath[name]!;
assert(() {
// Check that all required params are present
final paramNames = <String>[];
patternToRegExp(path.path, paramNames, caseSensitive: path.caseSensitive);
for (final paramName in paramNames) {
assert(
pathParameters.containsKey(paramName),
'missing param "$paramName" for $path',
);
}
// Check that there are no extra params
for (final String key in pathParameters.keys) {
assert(paramNames.contains(key), 'unknown param "$key" for $path');
}
return true;
}());
final encodedParams = <String, String>{
for (final MapEntry<String, String> param in pathParameters.entries)
param.key: Uri.encodeComponent(param.value),
};
final String location = patternToPath(path.path, encodedParams);
return Uri(
path: location,
queryParameters: queryParameters.isEmpty ? null : queryParameters,
fragment: fragment,
).toString();
}
/// Finds the routes that matched the given URL.
RouteMatchList findMatch(Uri uri, {Object? extra}) {
final pathParameters = <String, String>{};
final List<RouteMatchBase> matches = _getLocRouteMatches(
uri,
pathParameters,
);
if (matches.isEmpty) {
return _errorRouteMatchList(
uri,
GoException('no routes for location: $uri'),
extra: extra,
);
}
return RouteMatchList(
matches: matches,
uri: uri,
pathParameters: pathParameters,
extra: extra,
);
}
/// Reparse the input RouteMatchList
RouteMatchList reparse(RouteMatchList matchList) {
RouteMatchList result = findMatch(matchList.uri, extra: matchList.extra);
for (final ImperativeRouteMatch imperativeMatch
in matchList.matches.whereType<ImperativeRouteMatch>()) {
final match = ImperativeRouteMatch(
pageKey: imperativeMatch.pageKey,
matches: findMatch(
imperativeMatch.matches.uri,
extra: imperativeMatch.matches.extra,
),
completer: imperativeMatch.completer,
);
result = result.push(match);
}
return result;
}
List<RouteMatchBase> _getLocRouteMatches(
Uri uri,
Map<String, String> pathParameters,
) {
for (final RouteBase route in _routingConfig.value.routes) {
final List<RouteMatchBase> result = RouteMatchBase.match(
rootNavigatorKey: navigatorKey,
route: route,
uri: uri,
pathParameters: pathParameters,
);
if (result.isNotEmpty) {
return result;
}
}
return const <RouteMatchBase>[];
}
/// Processes all redirects (top-level and route-level) and returns the
/// final [RouteMatchList].
///
/// Top-level redirects are evaluated first via [applyTopLegacyRedirect],
/// then route-level redirects run on the resulting match list. If a
/// route-level redirect changes the location, this method recurses —
/// re-evaluating top-level redirects on the new location naturally.
FutureOr<RouteMatchList> redirect(
BuildContext context,
FutureOr<RouteMatchList> prevMatchListFuture, {
required List<RouteMatchList> redirectHistory,
}) {
FutureOr<RouteMatchList> processRedirect(RouteMatchList prevMatchList) {
// Step 1: Apply top-level redirect first (self-recursive for chains).
final FutureOr<RouteMatchList> afterTopLevel = applyTopLegacyRedirect(
context,
prevMatchList,
redirectHistory: redirectHistory,
);
// Step 2: Then apply route-level redirects on the post-top-level result.
if (afterTopLevel is RouteMatchList) {
return _processRouteLevelRedirects(
context,
afterTopLevel,
redirectHistory,
);
}
return afterTopLevel.then<RouteMatchList>((RouteMatchList ml) {
if (!context.mounted) {
return ml;
}
return _processRouteLevelRedirects(context, ml, redirectHistory);
});
}
if (prevMatchListFuture is RouteMatchList) {
return processRedirect(prevMatchListFuture);
}
return prevMatchListFuture.then<RouteMatchList>(processRedirect);
}
/// Processes route-level redirects on [matchList].
///
/// If a route-level redirect changes the location, recurses back into
/// [redirect] which will re-evaluate top-level redirects on the new path.
FutureOr<RouteMatchList> _processRouteLevelRedirects(
BuildContext context,
RouteMatchList matchList,
List<RouteMatchList> redirectHistory,
) {
final prevLocation = matchList.uri.toString();
FutureOr<RouteMatchList> processRouteLevelRedirect(
String? routeRedirectLocation,
) {
if (routeRedirectLocation != null &&
routeRedirectLocation != prevLocation) {
final RouteMatchList newMatch = _getNewMatches(
routeRedirectLocation,
matchList.uri,
redirectHistory,
);
if (newMatch.isError) {
return newMatch;
}
// Recurse into redirect — top-level will be re-evaluated at the
// top of the next cycle.
return redirect(
context,
newMatch,
redirectHistory: redirectHistory,
);
}
return matchList;
}
final routeMatches = <RouteMatchBase>[];
matchList.visitRouteMatches((RouteMatchBase match) {
if (match.route.redirect != null) {
routeMatches.add(match);
}
return true;
});
try {
final FutureOr<String?> routeLevelRedirectResult =
_getRouteLevelRedirect(context, matchList, routeMatches, 0);
if (routeLevelRedirectResult is String?) {
return processRouteLevelRedirect(routeLevelRedirectResult);
}
return routeLevelRedirectResult
.then<RouteMatchList>(processRouteLevelRedirect)
.catchError((Object error) {
final GoException goException = error is GoException
? error
: GoException('Exception during route redirect: $error');
return _errorRouteMatchList(
matchList.uri,
goException,
extra: matchList.extra,
);
});
} catch (exception) {
final GoException goException = exception is GoException
? exception
: GoException('Exception during route redirect: $exception');
return _errorRouteMatchList(
matchList.uri,
goException,
extra: matchList.extra,
);
}
}
/// Applies the legacy top-level redirect to [prevMatchList] and returns the
/// resulting matches.
///
/// Returns [prevMatchList] when no redirect happens.
///
/// Shares [redirectHistory] with later route-level redirects for proper loop detection.
///
/// Recursively re-evaluates the top-level redirect when it produces a new
/// location, so that top-level redirect chains (e.g. `/` → `/a` → `/b`) are
/// fully resolved. Loop detection and redirect limit are enforced via the
/// shared [redirectHistory].
FutureOr<RouteMatchList> applyTopLegacyRedirect(
BuildContext context,
RouteMatchList prevMatchList, {
required List<RouteMatchList> redirectHistory,
}) {
final prevLocation = prevMatchList.uri.toString();
FutureOr<RouteMatchList> done(String? topLocation) {
if (topLocation != null && topLocation != prevLocation) {
final RouteMatchList newMatch = _getNewMatches(
topLocation,
prevMatchList.uri,
redirectHistory,
);
if (newMatch.isError) {
return newMatch;
}
// Recursively re-evaluate the top-level redirect on the new location.
return applyTopLegacyRedirect(
context,
newMatch,
redirectHistory: redirectHistory,
);
}
return prevMatchList;
}
try {
final FutureOr<String?> res = _runInRouterZone(() {
return _routingConfig.value.redirect(
context,
buildTopLevelGoRouterState(prevMatchList),
);
});
if (res is String?) {
return done(res);
}
return res.then<RouteMatchList>(done).catchError((Object error) {
final GoException goException = error is GoException
? error
: GoException('Exception during redirect: $error');
return _errorRouteMatchList(
prevMatchList.uri,
goException,
extra: prevMatchList.extra,
);
});
} catch (exception) {
final GoException goException = exception is GoException
? exception
: GoException('Exception during redirect: $exception');
return _errorRouteMatchList(
prevMatchList.uri,
goException,
extra: prevMatchList.extra,
);
}
}
FutureOr<String?> _getRouteLevelRedirect(
BuildContext context,
RouteMatchList matchList,
List<RouteMatchBase> routeMatches,
int currentCheckIndex,
) {
if (currentCheckIndex >= routeMatches.length) {
return null;
}
final RouteMatchBase match = routeMatches[currentCheckIndex];
FutureOr<String?> processRouteRedirect(String? newLocation) =>
newLocation ??
_getRouteLevelRedirect(
context,
matchList,
routeMatches,
currentCheckIndex + 1,
);
final RouteBase route = match.route;
try {
final FutureOr<String?> routeRedirectResult = _runInRouterZone(() {
return route.redirect!.call(context, match.buildState(this, matchList));
});
if (routeRedirectResult is String?) {
return processRouteRedirect(routeRedirectResult);
}
return routeRedirectResult.then<String?>(processRouteRedirect).catchError(
(Object error) {
// Convert any exception during async route redirect to a GoException
final GoException goException = error is GoException
? error
: GoException('Exception during route redirect: $error');
// Throw the GoException to be caught by the redirect handling chain
throw goException;
},
);
} catch (exception) {
// Convert any exception during route redirect to a GoException
final GoException goException = exception is GoException
? exception
: GoException('Exception during route redirect: $exception');
// Throw the GoException to be caught by the redirect handling chain
throw goException;
}
}
RouteMatchList _getNewMatches(
String newLocation,
Uri previousLocation,
List<RouteMatchList> redirectHistory,
) {
try {
// Normalize the URI to avoid trailing slash inconsistencies
final Uri uri = normalizeUri(Uri.parse(newLocation));
final RouteMatchList newMatch = findMatch(uri);
// Only add successful matches to redirect history
if (!newMatch.isError) {
_addRedirect(redirectHistory, newMatch);
}
return newMatch;
} catch (exception) {
final GoException goException = exception is GoException
? exception
: GoException('Exception during redirect: $exception');
log('Redirection exception: ${goException.message}');
return _errorRouteMatchList(previousLocation, goException);
}
}
/// Adds the redirect to [redirects] if it is valid.
///
/// Throws if a loop is detected or the redirection limit is reached.
void _addRedirect(List<RouteMatchList> redirects, RouteMatchList newMatch) {
if (redirects.contains(newMatch)) {
throw GoException(
'redirect loop detected ${_formatRedirectionHistory(<RouteMatchList>[...redirects, newMatch])}',
);
}
// Check limit before adding (redirects should only contain actual redirects, not the initial location)
if (redirects.length >= _routingConfig.value.redirectLimit) {
throw GoException(
'too many redirects ${_formatRedirectionHistory(<RouteMatchList>[...redirects, newMatch])}',
);
}
redirects.add(newMatch);
log('redirecting to $newMatch');
}
String _formatRedirectionHistory(List<RouteMatchList> redirections) {
return redirections
.map<String>(
(RouteMatchList routeMatches) => routeMatches.uri.toString(),
)
.join(' => ');
}
/// Runs the given function in a Zone with the router context for redirects.
T _runInRouterZone<T>(T Function() callback) {
if (router == null) {
return callback();
}
T? result;
var errorOccurred = false;
runZonedGuarded<void>(
() {
result = callback();
},
(Object error, StackTrace stack) {
errorOccurred = true;
// Convert any exception during redirect to a GoException and rethrow
final GoException goException = error is GoException
? error
: GoException('Exception during redirect: $error');
throw goException;
},
zoneValues: <Object?, Object?>{currentRouterKey: router},
);
if (errorOccurred) {
// This should not be reached since we rethrow in the error handler
throw GoException('Unexpected error in router zone');
}
return result as T;
}
/// Get the location for the provided route.
///
/// Builds the absolute path for the route, by concatenating the paths of the
/// route and all its ancestors.
String? locationForRoute(RouteBase route) =>
fullPathForRoute(route, '', _routingConfig.value.routes);
@override
String toString() {
return 'RouterConfiguration: ${_routingConfig.value.routes}';
}
/// Returns the full path of [routes].
///
/// Each path is indented based depth of the hierarchy, and its `name`
/// is also appended if not null
@visibleForTesting
String debugKnownRoutes() {
final sb = StringBuffer();
sb.writeln('Full paths for routes:');
_debugFullPathsFor(
_routingConfig.value.routes,
'',
const <_DecorationType>[],
sb,
);
if (_nameToPath.isNotEmpty) {
sb.writeln('known full paths for route names:');
for (final MapEntry<String, _NamedPath> e in _nameToPath.entries) {
sb.writeln(
' ${e.key} => ${e.value.path}${e.value.caseSensitive ? '' : ' (case-insensitive)'}',
);
}
}
return sb.toString();
}
void _debugFullPathsFor(
List<RouteBase> routes,
String parentFullpath,
List<_DecorationType> parentDecoration,
StringBuffer sb,
) {
for (final (int index, RouteBase route) in routes.indexed) {
final List<_DecorationType> decoration = _getDecoration(
parentDecoration,
index,
routes.length,
);
final String decorationString = decoration
.map((_DecorationType e) => e.toString())
.join();
var path = parentFullpath;
if (route is GoRoute) {
path = concatenatePaths(parentFullpath, route.path);
final String? screenName = route.builder?.runtimeType
.toString()
.split('=> ')
.last;
sb.writeln(
'$decorationString$path '
'${screenName == null ? '' : '($screenName)'}',
);
} else if (route is ShellRouteBase) {
sb.writeln('$decorationString (ShellRoute)');
}
_debugFullPathsFor(route.routes, path, decoration, sb);
}
}
List<_DecorationType> _getDecoration(
List<_DecorationType> parentDecoration,
int index,
int length,
) {
final Iterable<_DecorationType> newDecoration = parentDecoration.map((
_DecorationType e,
) {
switch (e) {
// swap
case _DecorationType.branch:
return _DecorationType.parentBranch;
case _DecorationType.leaf:
return _DecorationType.none;
// no swap
case _DecorationType.parentBranch:
return _DecorationType.parentBranch;
case _DecorationType.none:
return _DecorationType.none;
}
});
if (index == length - 1) {
return <_DecorationType>[...newDecoration, _DecorationType.leaf];
} else {
return <_DecorationType>[...newDecoration, _DecorationType.branch];
}
}
void _cacheNameToPath(String parentFullPath, List<RouteBase> childRoutes) {
for (final route in childRoutes) {
if (route is GoRoute) {
final String fullPath = concatenatePaths(parentFullPath, route.path);
if (route.name != null) {
final String name = route.name!;
assert(
!_nameToPath.containsKey(name),
'duplication fullpaths for name '
'"$name":${_nameToPath[name]!.path}, $fullPath',
);
_nameToPath[name] = (
path: fullPath,
caseSensitive: route.caseSensitive,
);
}
if (route.routes.isNotEmpty) {
_cacheNameToPath(fullPath, route.routes);
}
} else if (route is ShellRouteBase) {
if (route.routes.isNotEmpty) {
_cacheNameToPath(parentFullPath, route.routes);
}
}
}
}
}
enum _DecorationType {
parentBranch('│ '),
branch('├─'),
leaf('└─'),
none(' ');
const _DecorationType(this.value);
final String value;
@override
String toString() => value;
}