Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: queued navigate with React Router #19985

Merged
merged 11 commits into from
Sep 30, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ import React, {
useEffect,
useReducer,
useRef,
useState,
type ReactNode
} from "react";
import {
matchRoutes,
useBlocker,
useLocation,
useNavigate
useNavigate,
type NavigateOptions,
} from "react-router-dom";
import type { AgnosticRouteObject } from '@remix-run/router';
import { createPortal } from "react-dom";
Expand Down Expand Up @@ -200,6 +202,61 @@ function portalsReducer(portals: readonly PortalEntry[], action: PortalAction) {
}
}

type NavigateFn = (to: string, opts?: NavigateOptions) => void;
type NavigateArgs = Parameters<NavigateFn>

/**
* A hook providing the `navigate(path: string, opts?: NavigateOptions)` function
* with React Router API that has more consistent history updates. Uses internal
* queue for processing navigate calls.
*/
function useQueuedNavigate(waitReference: React.MutableRefObject<Promise<void> | undefined>): NavigateFn {
const navigate = useNavigate();
const navigateQueue = useRef<NavigateArgs[]>([]).current;
const [navigateQueueLength, setNavigateQueueLength] = useState(0);

const dequeueNavigation = useCallback(() => {
const navigateArgs = navigateQueue.shift();
if (navigateArgs === undefined) {
// Empty queue, do nothing.
return;
}

const blockingNavigate = async () => {
if (waitReference.current) {
await waitReference.current;
waitReference.current = undefined;
}
navigate(...navigateArgs);
setNavigateQueueLength(navigateQueue.length);
}
blockingNavigate();
}, [navigate, setNavigateQueueLength]);

const dequeueNavigationAfterCurrentTask = useCallback(() => {
queueMicrotask(dequeueNavigation);
}, [dequeueNavigation]);

const enqueueNavigation = useCallback((...navigateArgs: NavigateArgs) => {
navigateQueue.push(navigateArgs);
setNavigateQueueLength(navigateQueue.length);
if (navigateQueue.length === 1) {
// The first navigation can be started right after any pending sync
// jobs, which could add more navigations to the queue.
dequeueNavigationAfterCurrentTask();
}
}, [setNavigateQueueLength, dequeueNavigationAfterCurrentTask]);

useEffect(() => () => {
// The Flow component has rendered, but history might not be
// updated yet, as React Router does it asynchronously.
// Use microtask callback for history consistency.
dequeueNavigationAfterCurrentTask();
}, [navigateQueueLength, dequeueNavigationAfterCurrentTask]);

return enqueueNavigation;
}

function Flow() {
const ref = useRef<HTMLOutputElement>(null);
const navigate = useNavigate();
Expand All @@ -211,6 +268,8 @@ function Flow() {
const navigated = useRef<boolean>(false);
const fromAnchor = useRef<boolean>(false);
const containerRef = useRef<RouterContainer | undefined>(undefined);
const roundTrip = useRef<Promise<void> | undefined>(undefined);
const queuedNavigate = useQueuedNavigate(roundTrip);

// portalsReducer function is used as state outside the Flow component.
const [portals, dispatchPortalAction] = useReducer(portalsReducer, []);
Expand Down Expand Up @@ -263,7 +322,7 @@ function Flow() {
const path = '/' + event.detail.url;
navigated.current = !event.detail.callback;
fromAnchor.current = false;
navigate(path, { state: event.detail.state, replace: event.detail.replace});
queuedNavigate(path, { state: event.detail.state, replace: event.detail.replace});
}, [navigate]);

const redirect = useCallback((path: string) => {
Expand Down Expand Up @@ -296,9 +355,13 @@ function Flow() {

useEffect(() => {
if (blocker.state === 'blocked') {
let blockingPromise: any;
roundTrip.current = new Promise<void>((resolve,reject) => blockingPromise = {resolve:resolve,reject:reject});

// Do not skip server round-trip if navigation originates from a click on a link
if (navigated.current && !fromAnchor.current) {
blocker.proceed();
blockingPromise.resolve();
return;
}
fromAnchor.current = false;
Expand All @@ -310,14 +373,16 @@ function Flow() {
// @ts-ignore
if (matched && matched.filter(path => path.route?.element?.type?.name === Flow.name).length != 0) {
containerRef.current?.onBeforeEnter?.call(containerRef?.current,
{pathname,search}, {
{pathname, search}, {
prevent() {
blocker.reset();
blockingPromise.resolve();
navigated.current = false;
},
redirect,
continue() {
blocker.proceed();
blockingPromise.resolve();
}
}, router);
navigated.current = true;
Expand All @@ -333,13 +398,16 @@ function Flow() {
containerRef.current.serverConnected = (cancel) => {
if (cancel) {
blocker.reset();
blockingPromise.resolve();
} else {
blocker.proceed();
blockingPromise.resolve();
}
}
} else {
// permitted navigation: proceed with the blocker
blocker.proceed();
blockingPromise.resolve();
}
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright 2000-2024 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package com.vaadin.flow;

import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.NativeButton;
import com.vaadin.flow.router.Route;

@Route("com.vaadin.flow.BackNavFirstView")
public class BackNavFirstView extends Div {

public BackNavFirstView() {
add(new NativeButton("Navigate", event -> getUI()
.ifPresent(ui -> ui.navigate(BackNavSecondView.class))));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright 2000-2024 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package com.vaadin.flow;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.router.AfterNavigationEvent;
import com.vaadin.flow.router.AfterNavigationObserver;
import com.vaadin.flow.router.Route;

@Route("com.vaadin.flow.BackNavSecondView")
public class BackNavSecondView extends Div implements AfterNavigationObserver {

public BackNavSecondView() {
add("Second view");
}

@Override
public void afterNavigation(AfterNavigationEvent event) {
UI.getCurrent().getPage().getHistory().replaceState(null,
"com.vaadin.flow.BackNavSecondView?param");
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Copyright 2000-2024 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package com.vaadin.flow;

import com.vaadin.flow.component.html.Div;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Copyright 2000-2024 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package com.vaadin.flow;

import com.vaadin.flow.component.html.Div;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Copyright 2000-2024 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package com.vaadin.flow;

import com.vaadin.flow.component.html.Div;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Copyright 2000-2024 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package com.vaadin.flow;

import com.vaadin.flow.component.html.Div;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.vaadin.flow;

import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.TimeoutException;

import com.vaadin.flow.component.html.testbench.NativeButtonElement;
import com.vaadin.flow.component.html.testbench.SpanElement;
import com.vaadin.flow.testutil.ChromeBrowserTest;

public class BackNavIT extends ChromeBrowserTest {

public static final String BACK_NAV_FIRST_VIEW = "/view/com.vaadin.flow.BackNavFirstView";
public static final String BACK_NAV_SECOND_VIEW = "/view/com.vaadin.flow.BackNavSecondView?param";

// Test for https://github.com/vaadin/flow/issues/19839
@Test
public void testBackButtonAfterHistoryStateChange() {
getDriver().get(getTestURL(getRootURL(), BACK_NAV_FIRST_VIEW, null));

try {
waitUntil(arg -> driver.getCurrentUrl()
.endsWith(BACK_NAV_FIRST_VIEW));
} catch (TimeoutException e) {
Assert.fail("URL wasn't updated to expected one: "
+ BACK_NAV_FIRST_VIEW);
}

$(NativeButtonElement.class).first().click();

try {
waitUntil(arg -> driver.getCurrentUrl()
.endsWith(BACK_NAV_SECOND_VIEW));
} catch (TimeoutException e) {
Assert.fail("URL wasn't updated to expected one: "
+ BACK_NAV_SECOND_VIEW);
}

// Navigate back; ensure we get the first URL again
getDriver().navigate().back();
try {
waitUntil(arg -> driver.getCurrentUrl()
.endsWith(BACK_NAV_FIRST_VIEW));
} catch (TimeoutException e) {
Assert.fail("URL wasn't updated to expected one: "
+ BACK_NAV_FIRST_VIEW);
}
}

}
Loading