1/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package androidx.navigation.testing;
18
19import android.os.Bundle;
20import android.support.annotation.NonNull;
21import android.support.annotation.Nullable;
22import android.support.v4.util.Pair;
23
24import androidx.navigation.NavDestination;
25import androidx.navigation.NavOptions;
26import androidx.navigation.Navigator;
27
28import java.util.ArrayDeque;
29
30/**
31 * A simple Navigator that doesn't actually navigate anywhere, but does dispatch correctly
32 */
33@Navigator.Name("test")
34public class TestNavigator extends Navigator<TestNavigator.Destination> {
35
36    public final ArrayDeque<Pair<Destination, Bundle>> mBackStack = new ArrayDeque<>();
37
38    @NonNull
39    @Override
40    public Destination createDestination() {
41        return new Destination(this);
42    }
43
44    @Override
45    public void navigate(@NonNull Destination destination, @Nullable Bundle args,
46            @Nullable NavOptions navOptions) {
47        if (navOptions != null && navOptions.shouldLaunchSingleTop() && !mBackStack.isEmpty()
48                && mBackStack.peekLast().first.getId() == destination.getId()) {
49            mBackStack.pop();
50            mBackStack.add(new Pair<>(destination, args));
51            dispatchOnNavigatorNavigated(destination.getId(), BACK_STACK_UNCHANGED);
52        } else {
53            mBackStack.add(new Pair<>(destination, args));
54            dispatchOnNavigatorNavigated(destination.getId(), BACK_STACK_DESTINATION_ADDED);
55        }
56    }
57
58    @Override
59    public boolean popBackStack() {
60        boolean popped = mBackStack.pollLast() != null;
61        if (popped) {
62            dispatchOnNavigatorNavigated(mBackStack.isEmpty()
63                            ? 0
64                            : mBackStack.peekLast().first.getId(),
65                    BACK_STACK_DESTINATION_POPPED);
66        }
67        return popped;
68    }
69
70    /**
71     * A simple Test destination
72     */
73    public static class Destination extends NavDestination {
74        /**
75         * NavDestinations should be created via {@link Navigator#createDestination}.
76         */
77        Destination(@NonNull Navigator<? extends NavDestination> navigator) {
78            super(navigator);
79        }
80    }
81}
82