Async _navigate() unintuitively prevents scrolling or focusing with onMount() or actions #2477
Labels
bug
Something isn't working
p2-nice-to-have
SvelteKit cannot be used by a small number of people, quality of life improvements, etc.
Describe the bug
Since the _navigate() function that is called after clicking an anchor tag is asynchronous, part of it runs after the code inside the
onMount()
oruse:action
of the target route is executed.If one were to use either of those to for example focus an input field on navigation, this would not work, as the default scroll and focus behavior of the router are run later and therefore overwrite the focus/scroll changes made inside the onMount/action.
I think it is fair to classify this as a bug since
this is completely undocumented behavior that works without hiccups in non-sveltekit svelte:
(REPL for reference)
since the _navigate() function is not called when refreshing manually, the onMount/action code works as expected on refresh, possibly causing confusion for why this doesn't work. (Check the reproduction repository to see this behavior in action)
I see two possible solutions to addressing this unexpected behavior:
Document the behavior and tell users to work around this by wrapping the focus/scroll inside setTimeout as async code has priority to whatever is on the eventLoop and therefore focus will only be pushed onto the browsers main thread after _navigate() completes. As you can see in the reproduction, this does work but is not very intuitive. The end user does not now that navigate is async and therefore won't understand why setTimeout is required here.
Fix the behavior. To my surprise, adding the attribute of sveltekit:noscroll to anchor tags did not fix this behavior. I thought this could be addressed by simply adding sveltekit:keepfocus as an attribute and telling users to use either of those modifiers if they want to focus/scroll in their onMount/actions. I will be happy to help with a fix for this, but I currently have no other idea for how to fix this.
Reproduction
https://github.com/Theo-Steiner/onMountFocus
Logs
No response
System Info
Severity
serious, but I can work around it
I assume many people would want to scroll/focus inside onMount / actions. I just stumbled upon this behavior in the first place because people in the discord were struggling with this.
Additional Information
No response
The text was updated successfully, but these errors were encountered: