diff --git a/docs/BlazorComponentsGuidance.md b/docs/BlazorComponentsGuidance.md index 4db137cec498..581c3008a042 100644 --- a/docs/BlazorComponentsGuidance.md +++ b/docs/BlazorComponentsGuidance.md @@ -71,6 +71,7 @@ validation guidance rather than defining a separate architecture. - Preserve Blazor's inbound route precedence: compare segments from left to right; for simple segments, literal segments precede constrained parameters, unconstrained parameters, constrained catch-all parameters, and unconstrained catch-all parameters. Optionality is not a precedence tie-breaker: `/users/{id}` and `/users/{id?}` must be rejected as ambiguous rather than preferring the required parameter. Supplemental implementation/test references: [`RoutePrecedence.ComputeInbound`](../src/Http/Routing/src/Template/RoutePrecedence.cs) and [`RouteTableFactoryTests.ThrowsForOptionalParametersAndNonOptionalParameters`](../src/Components/Components/test/Routing/RouteTableFactoryTests.cs). - Preserve exclusions for download and non-navigation links, real page loads for external replace-history navigation, and server/client `NavigationManager` synchronization. - Enhanced form and navigation tests should use explicit promises, per-test storage IDs, and isolated hooks instead of timeouts or shared ambient state. +- Enhanced-navigation click interception stays on document so native document-level stopPropagation does not disable it. The shared renderer-listener registration hook keeps it after every renderer's click delegate, including active-listener re-registration. Reordering during a managed click is postponed until the navigation listener runs so it is not skipped for that click; keep static SSR navigation working after interactive circuits are disposed. ### JS interop, browser APIs, and serialization diff --git a/src/Components/Web.JS/src/Rendering/Events/EventDelegator.ts b/src/Components/Web.JS/src/Rendering/Events/EventDelegator.ts index b0fd5e7fe793..38ed55725346 100644 --- a/src/Components/Web.JS/src/Rendering/Events/EventDelegator.ts +++ b/src/Components/Web.JS/src/Rendering/Events/EventDelegator.ts @@ -4,6 +4,7 @@ import { EventFieldInfo } from './EventFieldInfo'; import { eventNameAliasRegisteredCallbacks, getBrowserEventName, getEventNameAliases, getEventTypeOptions } from './EventTypes'; import { isRendererAttached, dispatchEvent } from '../WebRendererInteropMethods'; +import { dispatchGlobalEvent, notifyGlobalListenerAdded } from './EventDelegatorListeners'; const nonBubblingEvents = toLookup([ 'abort', @@ -74,7 +75,8 @@ export class EventDelegator { constructor(private browserRendererId: number) { const eventDelegatorId = ++EventDelegator.nextEventDelegatorId; this.eventsCollectionKey = `_blazorEvents_${eventDelegatorId}`; - this.eventInfoStore = new EventInfoStore(this.onGlobalEvent.bind(this)); + const globalListener = this.onGlobalEvent.bind(this); + this.eventInfoStore = new EventInfoStore(event => dispatchGlobalEvent(event, globalListener)); } public setListener(element: Element, eventName: string, eventHandlerId: number, renderingComponentId: number): void { @@ -294,6 +296,7 @@ class EventInfoStore { // We preserve the non-bubbling behavior by only dispatching such events to the targeted element. const useCapture = Object.prototype.hasOwnProperty.call(nonBubblingEvents, eventName); document.addEventListener(eventName, this.globalListener, useCapture); + notifyGlobalListenerAdded(eventName); } } @@ -314,6 +317,7 @@ class EventInfoStore { // We preserve the non-bubbling behavior by only dispatching such events to the targeted element. const useCapture = Object.prototype.hasOwnProperty.call(nonBubblingEvents, eventName); document.addEventListener(eventName, this.globalListener, { capture: useCapture, passive: false }); + notifyGlobalListenerAdded(eventName); } public update(oldEventHandlerId: number, newEventHandlerId: number) { diff --git a/src/Components/Web.JS/src/Rendering/Events/EventDelegatorListeners.ts b/src/Components/Web.JS/src/Rendering/Events/EventDelegatorListeners.ts new file mode 100644 index 000000000000..5195a1927a1f --- /dev/null +++ b/src/Components/Web.JS/src/Rendering/Events/EventDelegatorListeners.ts @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +let clickListenerRegisteredCallback: ((isDispatchingClick: boolean) => void) | undefined; +let clickDispatchDepth = 0; + +export function setClickListenerRegisteredCallback(callback: typeof clickListenerRegisteredCallback): void { + clickListenerRegisteredCallback = callback; +} + +export function notifyGlobalListenerAdded(eventName: string): void { + if (eventName === 'click') { + clickListenerRegisteredCallback?.(clickDispatchDepth > 0); + } +} + +export function dispatchGlobalEvent(event: Event, listener: EventListener): void { + if (event.type !== 'click') { + listener(event); + return; + } + + clickDispatchDepth++; + try { + listener(event); + } finally { + clickDispatchDepth--; + } +} diff --git a/src/Components/Web.JS/src/Services/NavigationEnhancement.ts b/src/Components/Web.JS/src/Services/NavigationEnhancement.ts index 7bd29bee95bb..416385f6ccda 100644 --- a/src/Components/Web.JS/src/Services/NavigationEnhancement.ts +++ b/src/Components/Web.JS/src/Services/NavigationEnhancement.ts @@ -4,6 +4,7 @@ import { synchronizeDomContent } from '../Rendering/DomMerging/DomSync'; import { attachProgrammaticEnhancedNavigationHandler, handleClickForNavigationInterception, hasInteractiveRouter, isForSamePath, notifyEnhancedNavigationListeners, performScrollToElementOnTheSamePage, isSamePageWithHash } from './NavigationUtils'; import { scheduleScrollReset, ScrollResetSchedule } from '../Rendering/Renderer'; +import { setClickListenerRegisteredCallback } from '../Rendering/Events/EventDelegatorListeners'; /* In effect, we have two separate client-side navigation mechanisms: @@ -37,6 +38,7 @@ const acceptHeader = 'text/html; blazor-enhanced-nav=on'; let currentEnhancedNavigationAbortController: AbortController | null; let navigationEnhancementCallbacks: NavigationEnhancementCallbacks; let performingEnhancedPageLoad: boolean; +let clickListenerReorderPending = false; // This gets initialized to the current URL when we load. // After that, it gets updated every time we successfully complete a navigation. @@ -59,6 +61,7 @@ export function hasNeverStartedAnyEnhancedPageLoad() { export function attachProgressivelyEnhancedNavigationListener(callbacks: NavigationEnhancementCallbacks) { navigationEnhancementCallbacks = callbacks; + setClickListenerRegisteredCallback(onClickListenerRegistered); document.addEventListener('click', onDocumentClick); document.addEventListener('submit', onDocumentSubmit); window.addEventListener('popstate', onPopState); @@ -67,6 +70,8 @@ export function attachProgressivelyEnhancedNavigationListener(callbacks: Navigat } export function detachProgressivelyEnhancedNavigationListener() { + setClickListenerRegisteredCallback(undefined); + clickListenerReorderPending = false; document.removeEventListener('click', onDocumentClick); document.removeEventListener('submit', onDocumentSubmit); window.removeEventListener('popstate', onPopState); @@ -88,7 +93,23 @@ function performProgrammaticEnhancedNavigation(absoluteInternalHref: string, rep performEnhancedPageLoad(absoluteInternalHref, /* interceptedLink */ false); } +function onClickListenerRegistered(isDispatchingClick: boolean) { + // Removing a listener during dispatch skips it for that click. Let it run before reordering. + if (isDispatchingClick) { + clickListenerReorderPending = true; + return; + } + + clickListenerReorderPending = false; + document.removeEventListener('click', onDocumentClick); + document.addEventListener('click', onDocumentClick); +} + function onDocumentClick(event: MouseEvent) { + if (clickListenerReorderPending) { + onClickListenerRegistered(false); + } + if (hasInteractiveRouter()) { return; } diff --git a/src/Components/test/E2ETest/ServerRenderingTests/EnhancedNavigationTest.cs b/src/Components/test/E2ETest/ServerRenderingTests/EnhancedNavigationTest.cs index ce1d985c6a81..9e75cb579726 100644 --- a/src/Components/test/E2ETest/ServerRenderingTests/EnhancedNavigationTest.cs +++ b/src/Components/test/E2ETest/ServerRenderingTests/EnhancedNavigationTest.cs @@ -730,6 +730,271 @@ public void CanReceiveNullParameterValueOnEnhancedNavigation(string renderMode) Assert.DoesNotContain(logs, log => log.Message.Contains("Error")); } + [Theory] + [InlineData("server", true)] + [InlineData("server", false)] + [InlineData("wasm", true)] + [InlineData("wasm", false)] + [InlineData("auto", true)] + [InlineData("auto", false)] + [InlineData("mixed", true)] + [InlineData("mixed", false)] + public void PreventDefaultIsRespectedWithEnhancedNavigation(string mode, bool prerender) + { + Navigate($"{ServerPathBase}/nav/prevent-default/{mode}?prerender={prerender}"); + var originalUrl = Browser.Url; + var originalDocument = Browser.Exists(By.TagName("html")); + var ids = mode == "mixed" ? new[] { "server", "wasm", "auto" } : new[] { mode }; + + foreach (var id in ids) + { + AssertPreventDefaultLinksAreInteractive(id); + } + + foreach (var id in ids) + { + var count = 1; + foreach (var link in new[] { "original", "route", "fragment", "conditional", "no-enhance", "nested-target", "ancestor", "stop", "async" }) + { + AssertPreventDefaultClick($"{link}-{id}", id, ++count, originalUrl); + } + } + + var firstId = ids[0]; + Browser.Exists(By.Id($"prevent-{firstId}")).Click(); + Browser.Equal("False", () => Browser.Exists(By.Id($"prevention-{firstId}")).Text); + Browser.Exists(By.Id($"prevent-{firstId}")).Click(); + Browser.Equal("True", () => Browser.Exists(By.Id($"prevention-{firstId}")).Text); + AssertPreventDefaultClick($"conditional-{firstId}", firstId, 11, originalUrl); + + Browser.Exists(By.Id($"ordinary-fragment-{firstId}")).Click(); + Browser.Equal($"{originalUrl}#target-{firstId}", () => Browser.Url); + Browser.Exists(By.Id($"ordinary-{firstId}")).Click(); + Browser.Equal("Other", () => Browser.Exists(By.TagName("h1")).Text); + Assert.False(originalDocument.IsStale()); + } + + [Theory] + [InlineData("server", true)] + [InlineData("server", false)] + [InlineData("wasm", true)] + [InlineData("wasm", false)] + public void PreventDefaultIsRespectedAfterAnotherRendererStarts(string firstMode, bool prerender) + { + Navigate($"{ServerPathBase}/nav/prevent-default/{firstMode}?prerender={prerender}"); + AssertPreventDefaultLinksAreInteractive(firstMode); + + Browser.Exists(By.Id("mixed-links")).Click(); + var counts = new[] { "server", "wasm", "auto" }.ToDictionary(id => id, AssertPreventDefaultLinksAreInteractive); + + var originalUrl = Browser.Url; + foreach (var id in new[] { "server", "wasm", "auto" }) + { + AssertPreventDefaultClick($"original-{id}", id, counts[id] + 1, originalUrl); + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void PreventDefaultIsRespectedWithColdAndWarmAuto(bool prerender) + { + Navigate($"{ServerPathBase}/nav"); + ((IJavaScriptExecutor)Browser).ExecuteScript(""" + localStorage.removeItem('blazor-resource-hash:Components.WasmMinimal'); + sessionStorage.setItem('block-load-boot-resource', 'true'); + """); + + var url = $"{ServerPathBase}/nav/prevent-default/auto?prerender={prerender}"; + Navigate(url); + AssertPreventDefaultLinksAreInteractive("auto"); + Browser.Equal("Server", () => Browser.Exists(By.Id("runtime-auto")).Text); + var originalUrl = Browser.Url; + AssertPreventDefaultClick("original-auto", "auto", 2, originalUrl); + + ((IJavaScriptExecutor)Browser).ExecuteScript("window.unblockLoadBootResource()"); + Browser.Exists(By.Id("unblocked-wasm")); + + Navigate(url); + AssertPreventDefaultLinksAreInteractive("auto"); + Browser.Equal("WebAssembly", () => Browser.Exists(By.Id("runtime-auto")).Text); + AssertPreventDefaultClick("original-auto", "auto", 2, originalUrl); + } + + [Fact] + public void EnhancedNavigationWorksAfterInteractiveServerCircuitIsDisposed() + { + Navigate($"{ServerPathBase}/nav/prevent-default/server"); + AssertPreventDefaultLinksAreInteractive("server"); + var originalDocument = Browser.Exists(By.TagName("html")); + Browser.Manage().Logs.GetLog(LogType.Browser); + + Browser.Exists(By.Id("ordinary-server")).Click(); + Browser.Equal("Other", () => Browser.Exists(By.TagName("h1")).Text); + Assert.False(originalDocument.IsStale()); + Browser.True(() => Browser.Manage().Logs.GetLog(LogType.Browser).Any(log => log.Message.Contains("Connection disconnected."))); + + Browser.Exists(By.TagName("nav")).FindElement(By.LinkText("Home")).Click(); + Browser.Equal("Hello", () => Browser.Exists(By.TagName("h1")).Text); + Assert.False(originalDocument.IsStale()); + } + + [Theory] + [InlineData("static", true)] + [InlineData("server", true)] + [InlineData("server", false)] + [InlineData("wasm", true)] + [InlineData("wasm", false)] + [InlineData("auto", true)] + [InlineData("auto", false)] + [InlineData("mixed", true)] + [InlineData("mixed", false)] + public void EnhancedNavigationWorksWithDocumentStopPropagation(string mode, bool prerender) + { + Navigate($"{ServerPathBase}/nav/prevent-default/{mode}?prerender={prerender}"); + var originalDocument = Browser.Exists(By.TagName("html")); + var ids = mode == "mixed" ? new[] { "server", "wasm", "auto" } : mode == "static" ? Array.Empty() : new[] { mode }; + var counts = ids.ToDictionary(id => id, AssertPreventDefaultLinksAreInteractive); + var originalUrl = Browser.Url; + + InstallDocumentClickProbe(stopPropagation: true); + try + { + foreach (var id in ids) + { + AssertPreventDefaultClick($"original-{id}", id, counts[id] + 1, originalUrl); + } + + Browser.Exists(By.Id("static-ordinary")).Click(); + Browser.Equal("Other", () => Browser.Exists(By.TagName("h1")).Text); + Assert.False(originalDocument.IsStale()); + } + finally + { + RemoveDocumentClickProbe(); + } + } + + [Theory] + [InlineData("server", true)] + [InlineData("server", false)] + [InlineData("wasm", true)] + [InlineData("wasm", false)] + [InlineData("auto", true)] + [InlineData("auto", false)] + [InlineData("mixed", true)] + [InlineData("mixed", false)] + public void PreventDefaultIsRespectedAfterClickListenerIsReregistered(string mode, bool prerender) + { + Navigate($"{ServerPathBase}/nav/prevent-default/{mode}?prerender={prerender}"); + var ids = mode == "mixed" ? new[] { "server", "wasm", "auto" } : new[] { mode }; + var counts = ids.ToDictionary(id => id, AssertPreventDefaultLinksAreInteractive); + var originalUrl = Browser.Url; + + InstallDocumentClickProbe(stopPropagation: true); + try + { + foreach (var id in ids) + { + Browser.Exists(By.Id($"reveal-{id}")).Click(); + Browser.Exists(By.Id($"late-{id}")); + AssertPreventDefaultClick($"late-{id}", id, counts[id] + 1, originalUrl); + AssertPreventDefaultClick($"original-{id}", id, counts[id] + 2, originalUrl); + } + + Assert.True((bool)((IJavaScriptExecutor)Browser).ExecuteScript("return window.documentClickProbe.registrations > 0")); + } + finally + { + RemoveDocumentClickProbe(); + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void EnhancedNavigationWorksWhenClickRegistersAnotherListener(bool prerender) + { + Navigate($"{ServerPathBase}/nav/prevent-default/wasm?prerender={prerender}"); + AssertPreventDefaultLinksAreInteractive("wasm"); + Browser.Equal("WebAssembly", () => Browser.Exists(By.Id("runtime-wasm")).Text); + var originalDocument = Browser.Exists(By.TagName("html")); + + InstallDocumentClickProbe(stopPropagation: false); + try + { + Browser.Exists(By.Id("register-and-navigate-wasm")).Click(); + Browser.Equal("Other", () => Browser.Exists(By.TagName("h1")).Text); + Assert.False(originalDocument.IsStale()); + Assert.True((bool)((IJavaScriptExecutor)Browser).ExecuteScript("return window.documentClickProbe.reentrantRegistrations > 0")); + } + finally + { + RemoveDocumentClickProbe(); + } + } + + private void InstallDocumentClickProbe(bool stopPropagation) + { + // WebDriver cannot install native document listeners or observe their registration. + ((IJavaScriptExecutor)Browser).ExecuteScript(""" + const probe = window.documentClickProbe = { + add: document.addEventListener, + registrations: 0, + reentrantRegistrations: 0, + }; + probe.capture = event => probe.event = event; + probe.stop = event => { + if (arguments[0] && event.target instanceof Element && event.target.closest('a')) { + event.stopPropagation(); + } + }; + document.addEventListener('click', probe.capture, true); + document.addEventListener('click', probe.stop); + document.addEventListener = function(type, listener, options) { + if (type === 'click') { + probe.registrations++; + if (probe.event?.eventPhase === Event.BUBBLING_PHASE) { + probe.reentrantRegistrations++; + } + } + return probe.add.call(this, type, listener, options); + }; + """, stopPropagation); + } + + private void RemoveDocumentClickProbe() + { + ((IJavaScriptExecutor)Browser).ExecuteScript(""" + const probe = window.documentClickProbe; + if (probe) { + document.removeEventListener('click', probe.capture, true); + document.removeEventListener('click', probe.stop); + document.addEventListener = probe.add; + delete window.documentClickProbe; + } + """); + } + + private int AssertPreventDefaultLinksAreInteractive(string id) + { + Browser.Equal("True", () => Browser.Exists(By.Id($"interactive-{id}")).Text); + var expectedCount = int.Parse(Browser.Exists(By.Id($"count-{id}")).Text, CultureInfo.InvariantCulture) + 1; + Browser.Exists(By.Id($"increment-{id}")).Click(); + Browser.Equal(expectedCount.ToString(CultureInfo.InvariantCulture), () => Browser.Exists(By.Id($"count-{id}")).Text); + + return expectedCount; + } + + private void AssertPreventDefaultClick(string linkId, string id, int expectedCount, string originalUrl) + { + Browser.Exists(By.Id(linkId)).Click(); + var expectedText = expectedCount.ToString(CultureInfo.InvariantCulture); + Browser.True(() => Browser.Url != originalUrl || Browser.FindElements(By.Id($"count-{id}")).Any(element => element.Text == expectedText)); + Assert.Equal(originalUrl, Browser.Url); + Browser.Equal(expectedText, () => Browser.Exists(By.Id($"count-{id}")).Text); + } + [Fact] public void CanUpdateHrefOnLinkTagWithIntegrity() { diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/EnhancedNav/PageWithPreventDefaultLinks.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/EnhancedNav/PageWithPreventDefaultLinks.razor new file mode 100644 index 000000000000..247ece1bd11c --- /dev/null +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/EnhancedNav/PageWithPreventDefaultLinks.razor @@ -0,0 +1,32 @@ +@page "/nav/prevent-default/{mode}" +@inject NavigationManager Navigation + +Prevent default links + +

Prevent default links

+ +Server links +WebAssembly links +Mixed links +Static ordinary link + +@if (Mode is "server" or "mixed") +{ + +} +@if (Mode is "wasm" or "mixed") +{ + +} +@if (Mode is "auto" or "mixed") +{ + +} + +@code { + [Parameter] + public string Mode { get; set; } = default!; + + [SupplyParameterFromQuery] + public bool Prerender { get; set; } = true; +} diff --git a/src/Components/test/testassets/TestContentPackage/PreventDefaultLinks.razor b/src/Components/test/testassets/TestContentPackage/PreventDefaultLinks.razor new file mode 100644 index 000000000000..b06c5a72496a --- /dev/null +++ b/src/Components/test/testassets/TestContentPackage/PreventDefaultLinks.razor @@ -0,0 +1,63 @@ +
+

@RendererInfo.IsInteractive

+

@RendererInfo.Name

+

@_count

+ + +

@_preventDefault

+ Original reproduction + Prevent route navigation + Prevent fragment navigation + Conditional prevention + Without enhanced navigation + Ordinary navigation + Ordinary fragment + + Nested click target + + + + Async handler +

Fragment target

+ + Render during navigation + @if (_showLateLink) + { + Late prevented link + } +
+ +@code { + [Parameter] + public string Id { get; set; } = default!; + + [Parameter] + public string ReturnUrl { get; set; } = default!; + + private int _count; + private bool _preventDefault = true; + private bool _showLateLink; + + private void ShowLateLink() + { + _showLateLink = true; + } + + private void Increment() + { + _count++; + } + + private async Task IncrementAsync() + { + await Task.Yield(); + _count++; + } +}