# Ask the guards in a router

A module can keep the user from the rest of the app with a guard, or from the routes that ask for a condition, and it declares the guard as data of the router role. [Guards of routes](https://doc.saymyframe.com/concepts/guards.md) and [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md) describe what the user then sees. This page is for a module that [provides the router role](https://doc.saymyframe.com/extending/role-provider.md#a-provider-that-renders-its-data): what it calls, when, and what it does with each answer.

## The class of the role

In an app with guards, the template of the role generates `routeGuards`, `redirectOf()`, `flowIsOver()`, `guardChanges` and the class `GuardedNavigation`, with the classes of its answers, in `lib/core/router/app_router.dart`. The class decides what a router does about the guards and keeps what the gates make it remember. A router creates it once, asks it at two times and does what it answers:

1. The router creates one `GuardedNavigation<L>`, where `L` is how it knows a location that it can show as `go()` does, such as a URI. It gives the class its location `/`, the screen that the app starts on, as `start`, and a function from an `AppLocation` of the navigation to its own location as `locationOf`.
2. Before it shows a location, it calls `asked`.
3. Each time `guardChanges` notifies, it calls `changed`.

Routers that ask alike and do what they are answered show the user the same pages at the same time.

## Before a location shows

```dart
WhenAsked<L>? asked(String? route, L location, {required Iterable<String?> onTopOf})
```

The router calls it for the location the app starts on, for each location that `go()`, `push()` or `replace()` of the navigation is asked to show, and for each location that the platform gives it, if it takes any.

| Argument | What the router gives |
| --- | --- |
| `route` | The full name of the route of the location, or `null` for a location that is no route of a module: one that no route matches, and `/`. |
| `location` | The location, as the router knows it. |
| `onTopOf` | The full names of the routes of the pages that the user can get back to at that time, the same pages that it tells `changed` of. It gives none while it has no page, and none for a location from the platform, which takes the place of the stack. |

The router does what the answer says:

| Answer | What the router does |
| --- | --- |
| `null` | It shows the location. |
| `ShowInstead(location)` | It shows that location in place of the other, as `go()` to it does. The location is the target of a gate, or `/` for a location in a flow that is over. It takes the whole stack, whichever page the other location was asked from, and such a `push()` completes with `null` at once. |
| `ShowOver(location, flow: routes)` | It shows the location over the page on top, as `push()` of it does, so the user can go back from it. The location is the target of a guard that stands for a condition, or a page of the flow of such a guard that was itself asked for with no pages, and `flow` has the full names of the routes of that flow. The router keeps the request waiting, and a `push()` that waits does not complete. |
| `ShowNothing()` | It shows nothing and leaves its pages as they are, since the flow of the guard is open already. Such a `push()` completes with `null` at once. |

Unless the answer is `null`, or a `ShowOver` of the location itself, the router does not build the screen of the location, and the listeners of the screen do not hear of it. A request that waits is asked about again before its location shows.

- The target of a gate also takes the stacks of every branch of the main navigation, so that each branch is back on its destination when the user comes to it again. The location `/` for a flow that is over hides nothing from the user. The router shows it as its `go()` to that location does, and whether the branches that are not selected keep their pages then is up to the router.
- Asked with no pages, as for a location from the platform, a router that gets `ShowOver` first shows `/` in place of the stack and then the location of the answer over it. The listeners of the screen hear only of that location.
- The class keeps no request. Asked again about a location that it answered `ShowOver` for, with a page of the flow among `onTopOf`, it answers `ShowNothing` for a location that the guard keeps the user from, and `null` for a page of the flow.

### The answer depends on the pages

The routes of the flow of a guard that stands for a condition show while the condition does not hold. What `asked` answers for one of them depends on `onTopOf`:

| A page of such a flow is asked for | The answer |
| --- | --- |
| On a page | `null`. The page shows as the code of the app asked: over that page for `push()`, and in place of the stack for `go()`. |
| With no pages, as by a link | `ShowOver` of the location itself, with its query, and of the flow. The page opens over `/`, back leads to `/`, and once the condition holds the router closes the flow. A route below the target then has `/` alone below it. |

So a router never asks with no pages about a location that it shows over a page, nor about a location that it goes to for a request that it asked about with the pages. Asked so about the target that it shows for a `ShowOver`, the class answers `ShowOver` again, and the router would open the target without end.

A router whose redirect runs for each location that it goes to, with no pages, keeps the calls of its own navigation from the class. A router that cannot rule such a call out should fail loudly when it happens, as `go_router` does with a `StateError`, and not open the target again and again. Such a redirect may still run again for the location that it answered with, that of a `ShowInstead` or `/`: the location takes the place of the stack, and the class answers for it as for any other.

While a gate with the same flow does not allow, the flow is the gate's, and its page takes the place of the stack.

## The request that waits

The request that waits is the one that the router got `ShowOver` for: the location, and whether `go()`, `push()`, `replace()` or the platform asked for it. The router keeps it, not the class, since only the router can complete a `push()`.

It keeps one request. When it gets `ShowOver` while a request waits, it drops the earlier one, and a `push()` that waited completes with `null`.

The request waits while a page of a route of the `flow` of the answer is among the pages that the user can get back to, so it is still there after a `push()` or a `replace()` inside the flow. It ends in one of three ways:

| What ends it | What the router does |
| --- | --- |
| `changed` answers `ClosePages` without `dropsRequest`, and no page of the flow is left once the router closed the pages. | It makes the request again as it was made, on top of the pages that are left, and asks the class about it again. `push()` shows the location over the page that the flow was opened from, and the first `push()` completes with the value of that page. `go()` shows it in place of the stack, `replace()` in place of the page that the flow was opened from, and a location from the platform as `go()` to it. |
| `changed` answers `ClosePages` with `dropsRequest`. | It drops the request, and does not make it on the page below. The pages that close reach below the flow, so the page that the request was made on closes too, as one that asks for another condition, which stopped holding. |
| The last page of the flow leaves in any other way: the user goes back from it, or a location takes the place of the stack. | It drops the request, and a `push()` that waited completes with `null`. |

When the router makes the request again, the class may answer with the target of another guard, as for a route that asks for two conditions.

For a page of the flow that a link asked for, the request that waits is the page itself. Asked about again once the flow closes, it is answered with `/`, where the user is then.

The target of a gate takes the place of the stack, and the request goes with the pages of its flow. When that target is a page of the same flow, as for a gate and a guard of a condition with one flow, the request waits on until the target leaves.

## When a guard changes

```dart
WhenChanged<L>? changed(Iterable<({String? route, L location, bool pushed})> pages)
```

Each time `guardChanges` notifies, the router calls it with the pages that the user can get back to, the one on top first: those of its root navigator and, in place of the main navigation, those of its selected branch. It leaves out the pages of the other branches. A guard may notify though what it allows did not change.

Each page comes with the full name of its route or `null`, with its location, and with `pushed`: whether the router can close the page on its own and leave the pages below it as they are. That is `true` for a page that `push()` showed, and for a page that `replace()` showed in place of such a page. Whether a page that `replace()` showed in place of another page is one is up to the router.

A router that has no page yet, as before it shows the location that the app starts on, has none to tell of and shows nothing then. It asks about its first location when it shows it.

| Answer | What the router does |
| --- | --- |
| `null` | It leaves everything as it is: the stack stays, the listeners of the screen hear nothing, and each `push()` still completes with the value of its page. |
| `ShowInstead(location)` | It shows the location in place of its whole stack, as for that answer of `asked`, and the target of a gate in place of the stacks of every branch too. That holds whenever the gate allows again: also in the turn in which it stopped allowing, and while the transition to its target is on its way. |
| `ClosePages(pages, dropsRequest: ...)` | It closes that many pages on top, each of which it told of as `pushed`, and leaves the pages below them as they are. Each `push()` that showed one of them completes with `null`, at once or when the frame is over. Then it drops the request that waits, with `dropsRequest`, or else makes it again, if no page of its flow is left. |

What `ClosePages` asks of a router:

- The pages leave at once, whatever the navigator shows over them, such as a dialog. That includes a page that a `push()` of the same turn showed and that the navigator has not built yet.
- The listeners of the screen hear of the page that the user ends on. They do not hear of the page below the closed ones when the request shows another page over it, since the user never saw that page come back.
- Until the navigator builds again, it may still have the route of a page that the router closed. The code of a screen that closes its own page in that time, or the back button of the system, closes that route and no page of the router, and the router does not fail. The `push()` of such a page may complete with the value that the page closed with.
- `ShowOver` and `ClosePages` leave the main navigation and its branches as they are, since no route of the main navigation asks for a condition.

With `ShowInstead` from `changed`, two things are up to the router: whether the listeners of the screen hear of a target that no frame showed, and whether the `push()` of a page that the answer takes out of the stack completes, as when `go()` replaces the stack.

## Without a page, and on the error screen

A router may have no page to push over or to replace: before it shows its first location, or on an error screen that took the place of its stack. It may then take each request as `go()` to its location, which takes the place of the stack as a location from the platform does. It asks about the location once, with no pages, and such a `push()` completes with `null` at once. The target of a guard that stands for a condition then opens over the location `/`, in place of the error screen too.

On its error screen, a router still shows the location that `push()` or `replace()` asks for, and the listeners of the screen hear of it once; see [Provide a role](https://doc.saymyframe.com/extending/role-provider.md#a-provider-that-renders-its-data).

## With go_router

`go_router` knows a location by its URI. It creates the class with its location `/` and with the path of an `AppLocation`:

```dart title="lib/core/router/app_router_factory.dart"
  final GuardedNavigation<String> _guards = GuardedNavigation(
    start: '/',
    locationOf: (location) => location.path,
  );
```

`go()`, `push()` and `replace()` ask once, before they hand a location to go_router, with the routes of the pages that the user can get back to. For `ShowOver` the router pushes the target and keeps the request: how to make it again, and how to end it without showing its location, which for a `push()` completes its future with `null`.

```dart title="lib/core/router/app_router_factory.dart"
    final answer = _guards.asked(
      location.routeName,
      location.path,
      onTopOf: [for (final page in _pages) page.route],
    );
    switch (answer) {
      case null:
        return false;
      case ShowInstead(location: final shown):
        _own(() => config.go(shown));
        drop?.call();
      case ShowNothing():
        drop?.call();
      case ShowOver(location: final target, :final flow):
        _open(target, flow, again: again, drop: drop);
    }
    return true;
```

The top-level `redirect` of go_router runs inside each call of go_router, and asks with no pages. So the router counts the calls that it makes itself, with `_own`: those with a location that it asked about, or that the class answered, or with pages that are shown already, a refresh of go_router among them. Within them the `redirect` asks nothing:

```dart title="lib/core/router/app_router_factory.dart"
  R _own<R>(R Function() navigate) {
    _asking++;
    try {
      return navigate();
    } finally {
      _asking--;
    }
  }
```

What is left for the `redirect` are the locations that go_router parses on its own: the one the app starts on, those of the platform, and that of a branch of the main navigation that the user selects. Such a location takes the place of the stack, so the router gives no pages. A redirect can only send go_router to another location. So for `ShowOver` the router sends it to `/` and pushes the location of the answer in a microtask, once the parse is over. When the page on top is that location already, as for a second link to a page of a flow, the router puts that page back over `/` and pushes no new one, so the page keeps its state:

```dart title="lib/core/router/app_router_factory.dart"
  String? _redirect(String? route, String location) {
    if (_asking > 0) return null;
    switch (_guards.asked(route, location, onTopOf: const [])) {
      case null || ShowNothing():
        return null;
      case ShowInstead(location: final shown):
        return shown;
      case ShowOver(location: final target, :final flow):
        _muted = true;
        final onTop = config.routerDelegate.currentConfiguration.lastOrNull;
        final kept =
            onTop is ImperativeRouteMatch && '${onTop.matches.uri}' == target
            ? onTop
            : null;
        void open() {
          if (_opening != open) return;
          _opening = null;
          _muted = false;
          _open(target, flow, again: () => config.go(location), kept: kept);
          if (_opening == null) return;
          _opening = null;
          throw StateError(
            'The redirect of go_router asked the guards about $target, '
            'which the router pushes itself, and would open it without '
            'end: it must ask nothing within a call of the router.',
          );
        }
        _opening = open;
        scheduleMicrotask(open);
        return _guards.start;
    }
  }
```

The push of the target is a call of the router's own, so the `redirect` is not asked about it. If it ever were, the class would answer to open the target again, without end, and the router throws a `StateError` then.

While go_router has no page of a route, before its first location and on its error screen, the router asks the class nothing itself. `go()`, `push()` and `replace()` give go_router the location as `go()` does, and the `redirect` asks about it, with no pages.

The router listens to `guardChanges` itself and tells the class of its pages:

```dart title="lib/core/router/app_router_factory.dart"
  void _guardsChanged() {
    final pages = _pages;
    if (pages.isEmpty) return;
    switch (_guards.changed(pages)) {
      case null:
        break;
      case ShowInstead(:final location):
        _own(() => config.go(location));
      case ClosePages(pages: final count, :final dropsRequest):
        _close(count, dropsRequest: dropsRequest);
    }
  }
```

It does not hand `guardChanges` to go_router as its `refreshListenable`: a refresh asks only about the location below the pushed pages, and gives each of those pages a new completer. To close pages, it takes them out of the pages of go_router with one `restore()` and completes their pushes once the frame is over. `pop()` would close what the navigator shows on top, such as a dialog over the page.

An app without guards has none of these names in `app_router.dart`, so a provider renders this code only when `routerRole.facadeOf(input).guards` is not empty. `go_router` gives its brick the variable `guards` for it, as [its render hook](https://doc.saymyframe.com/extending/role-provider.md#a-provider-that-renders-its-data) shows. [`go_router`](https://doc.saymyframe.com/modules/go-router.md#guards) describes the rest of what the module does.

## What is checked

The rule `router.guards_asked` of the contract harness checks that, in an app with guards, the files of the provider create a `GuardedNavigation`, read `guardChanges`, and name the answers `ShowOver` and `ClosePages`. It asks for both answers in every app with guards, also in one whose guards are all gates. So neither a router that knows nothing of the guards nor one that shows every answer in place of its stack can be in an app with a module that needs them.

Whether the router does what the class answers, only a running app shows. SMF's CI checks that in running apps, with every provider of the router role that SMF has. It also runs the same tests on routers with a known bug, such as one whose `replace()` leaves the stack as it is, or one that drops the request that waits when the pages of the flow close, and each must fail on its bug. [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time) lists these tests.
