sveltejs / kit

web development, streamlined
https://svelte.dev/docs/kit
MIT License
18.76k stars 1.95k forks source link

pushState/replaceState don't trigger beforeNavigate #11776

Open samal-rasmussen opened 9 months ago

samal-rasmussen commented 9 months ago

Describe the bug

I just started using pushState/replaceState and realized that they don't trigger beforeNavigate, and so I cannot ask the user to confirm before navigating away from a modal form.

I have a rather big webapp that will need to have complex forms in modals. Users definitely want to be asked for confirmation before losing complex form state.

Reproduction

This modal will ask for confirmation when clicking the cancel button, but not on pressing back in the browser: https://stackblitz.com/edit/sveltejs-kit-template-default-fsoasb?file=src%2Froutes%2FModal.svelte

There's a beforeNavigate that should be showing the confirmation, but it isn't called.

Logs

No response

System Info

Forked the newest Sveltekit Stackblitz.

Severity

serious, but I can work around it

That is that for now I can live with only showing a confirmation when pressing the close button in the ui.

Additional Information

No response

eltigerchino commented 5 months ago

pushState and replaceState do not perform an actual navigation (shallow navigation) as it does not change the underlying route. The only things that do change are:

In comparison, (real navigations) using goto on the client, redirect in a load function, clicking on a link, will change these:

samal-rasmussen commented 5 months ago

So there's no way to intercept a shallow navigation back and show a confirmation dialog before doing the back navigation? Shouldn't this be possible?

AndreasHald commented 2 weeks ago

+1 experiencing this issue aswel only workaround i found was doing something like this

<svelte:window
    on:popstate={(e) => {
        if (form_is_tainted) {
            history.pushState(null, '', window.location.href);
        }
    }} />

which is discouraged becasue it interferes with svelte kit router

AndreasHald commented 2 weeks ago

@eltigerchino can you see any reason why letting beforeNavigate fire would be an issue? I can't really come up with a reason myself. In that case should this not be considered a bug? since the documentation for shallow routing literally suggests using it as a model that can be dismissed with the back button.

If there is a good reason why beforeNavigate would be a problematic solution could something akin to beforeShallowNavigate and similar hooks be a solution?