-
Notifications
You must be signed in to change notification settings - Fork 10.4k
[Blazor] Allow <FocusOnNavigate>
to work when rendered statically
#57131
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e628615
Support `<FocusOnNavigate>` in SSR, new events
MackinnonBuck 427f2a4
Clean up, add tests
MackinnonBuck cd3bcf7
Simplify handling of multiple selectors
MackinnonBuck fe9f08a
Update `enhancednavigationstart` event
MackinnonBuck 8759ede
Update blazor.*.js
MackinnonBuck 699b9d3
Simlified to wait until streaming completes
MackinnonBuck 8075b2e
Respect `autofocus` on the initial page load
MackinnonBuck File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
import { domFunctions } from '../DomWrapper'; | ||
import { JSEventRegistry } from '../Services/JSEventRegistry'; | ||
import { isForSamePath } from '../Services/NavigationUtils'; | ||
|
||
const customElementName = 'blazor-focus-on-navigate'; | ||
let currentFocusOnNavigateElement: FocusOnNavigateElement | null = null; | ||
let locationOnLastNavigation = location.href; | ||
let allowApplyFocusAfterEnhancedNavigation = false; | ||
|
||
export function enableFocusOnNavigate(jsEventRegistry: JSEventRegistry) { | ||
customElements.define(customElementName, FocusOnNavigateElement); | ||
jsEventRegistry.addEventListener('enhancednavigationstart', onEnhancedNavigationStart); | ||
jsEventRegistry.addEventListener('enhancednavigationend', onEnhancedNavigationEnd); | ||
document.addEventListener('focusin', onFocusIn); | ||
|
||
if (document.readyState === 'loading') { | ||
document.addEventListener('DOMContentLoaded', onInitialPageLoad, { once: true }); | ||
} else { | ||
onInitialPageLoad(); | ||
} | ||
} | ||
|
||
function onInitialPageLoad() { | ||
// On the initial page load, we only want to apply focus if there isn't already | ||
// a focused element. | ||
// See also: https://developer.mozilla.org/docs/Web/API/Document/activeElement#value | ||
if (document.activeElement !== null && document.activeElement !== document.body) { | ||
return; | ||
} | ||
|
||
// If an element on the page is requesting autofocus, but hasn't yet been focused, | ||
// we'll respect that. | ||
if (document.querySelector('[autofocus]')) { | ||
return; | ||
} | ||
|
||
tryApplyFocus(); | ||
} | ||
|
||
function onEnhancedNavigationStart() { | ||
// Only move focus when navigating to a new page. | ||
if (!isForSamePath(locationOnLastNavigation, location.href)) { | ||
allowApplyFocusAfterEnhancedNavigation = true; | ||
} | ||
|
||
locationOnLastNavigation = location.href; | ||
} | ||
|
||
function onEnhancedNavigationEnd() { | ||
if (allowApplyFocusAfterEnhancedNavigation) { | ||
tryApplyFocus(); | ||
} | ||
} | ||
|
||
function onFocusIn() { | ||
// If the user explicitly focuses a different element before a navigation completes, | ||
// don't move focus again. | ||
allowApplyFocusAfterEnhancedNavigation = false; | ||
} | ||
|
||
function tryApplyFocus() { | ||
const selector = currentFocusOnNavigateElement?.getAttribute('selector'); | ||
if (selector) { | ||
domFunctions.focusBySelector(selector); | ||
} | ||
} | ||
|
||
class FocusOnNavigateElement extends HTMLElement { | ||
connectedCallback() { | ||
// eslint-disable-next-line @typescript-eslint/no-this-alias | ||
currentFocusOnNavigateElement = this; | ||
} | ||
|
||
disconnectedCallback() { | ||
if (currentFocusOnNavigateElement === this) { | ||
currentFocusOnNavigateElement = null; | ||
} | ||
} | ||
} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In a previous iteration, I had a slightly more sophisticated implementation that gracefully handled having multiple
<FocusOnNavigate>
components at the same time, which can be later removed from the page in an arbitrary order without breaking things. However, I realized that's unlikely to be a real scenario, because<FocusOnNavigate>
is almost always going to exist in one location (in the router), especially considering it requires aRouteData
parameter that you can only obtain from the<Router>
(unless you construct it yourself, which I don't think is common).This simplified implementation always prioritizes the last-rendered
<blazor-focus-on-navigate>
custom element and assumes that if one already exists, it's going to be disconnected soon because we're in the process of applying updates to the DOM.If others disagree, I'm happy to add the old logic back. It's really not hugely complicated and I'm confident that it works, but it's just more code that apps need to download (and that we need to maintain).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We could choose to throw if we find more than one instance of focus on navigate on the document on the server even if we wanted.
It's not even clear what the behavior is when many of them are available on the page interactively.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TBH I'd be happy with avoiding the need for extra checks/errors and just go with a "first one in the document wins" rule. It would be the same as the HTML
autofocus
attribute:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's fine for me, given that there's defined behavior.
We should also consider interactions between
FocusOnNavigate
andautofocus
now that you mention it.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've updated the implementation to defer to
autofocus
on the initial page load. That is,autofocus
takes precedence overFocusOnNavigate
.That said,
autofocus
is not a replacement forFocusOnNavigate
, because after the first element gets autofocused, no other elements can get autofocused until a full page reload. In other words,autofocus
does not work with enhanced nav.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sounds reasonable.