Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
2f21a51
Try a generic JS callback bridge for Components.Platform events
jsakamotoIGJP Oct 15, 2026
efdb3da
Replace SetOnChangeAsync with AddEventListenerAsync and a typed event…
jsakamotoIGJP Oct 19, 2026
1527412
Add the storage event on Window with AddEventListenerAsync
jsakamotoIGJP Oct 19, 2026
7b0870e
Rename JS callback bridge identifiers for readability
jsakamotoIGJP Oct 22, 2026
03fa0b7
Adapt the bridge trial to dotnet/main after the rebase
jsakamotoIGJP Oct 26, 2026
65b950b
Fix the lifecycle problems found in the event listener review
jsakamotoIGJP Oct 26, 2026
0342221
Remove event listeners when a CancellationToken is canceled
jsakamotoIGJP Oct 27, 2026
0c4b0ae
Take the CancellationToken in an overload, not as an optional parameter
jsakamotoIGJP Oct 27, 2026
f45eecb
Document independent listener registrations and create Window event p…
jsakamotoIGJP Nov 6, 2026
f24b0a7
Keep the Window event parts out of trimmed apps that add no listener
jsakamotoIGJP Nov 6, 2026
621bf27
Test that an any-typed event value reaches a JsonElement through Blaz…
jsakamotoIGJP Nov 6, 2026
d4324bc
Track the Platform JS bundles as npm build outputs
jsakamotoIGJP Nov 6, 2026
ead6ef6
Reject a listener whose addition ends after scope disposal
jsakamotoIGJP Nov 6, 2026
5d7bae3
Remove the unused two- and three-argument JSCallback types
jsakamotoIGJP Nov 9, 2026
d614612
Merge remote-tracking branch 'dotnet/main' into components-platform-j…
jsakamotoIGJP Nov 9, 2026
470c2dd
Restore the googletest submodule pointer to main
jsakamotoIGJP Nov 9, 2026
ed515f8
Clarify the comments in Platform.ts
jsakamotoIGJP Nov 9, 2026
be1b24f
Remove a stale mention of other arities
jsakamotoIGJP Nov 9, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions eng/Npm.Workspace.nodeproj
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,11 @@
<NpmBuildOutputFiles Include="$(NpmWorkspaceRoot)\src\Components\CustomElements\src\js\dist\Debug\Microsoft.AspNetCore.Components.CustomElements.lib.module.js.map" />
<NpmBuildOutputFiles Include="$(NpmWorkspaceRoot)\src\Components\CustomElements\src\js\dist\Release\Microsoft.AspNetCore.Components.CustomElements.lib.module.js" />

<!-- Components Platform outputs -->
<NpmBuildOutputFiles Include="$(NpmWorkspaceRoot)\src\Components\Platform\src\js\dist\Debug\Microsoft.AspNetCore.Components.Platform.js" />
<NpmBuildOutputFiles Include="$(NpmWorkspaceRoot)\src\Components\Platform\src\js\dist\Debug\Microsoft.AspNetCore.Components.Platform.js.map" />
<NpmBuildOutputFiles Include="$(NpmWorkspaceRoot)\src\Components\Platform\src\js\dist\Release\Microsoft.AspNetCore.Components.Platform.js" />

<!-- FunctionalTests outputs -->
<NpmBuildOutputFiles Include="$(NpmWorkspaceRoot)\src\SignalR\clients\ts\FunctionalTests\wwwroot\dist\signalr-functional-tests.js" />
<NpmBuildOutputFiles Include="$(NpmWorkspaceRoot)\src\SignalR\clients\ts\FunctionalTests\wwwroot\dist\signalr-functional-tests.js.map" />
Expand Down
8 changes: 8 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"src/Components/WebAssembly/Authentication.Msal/src/Interop",
"src/Components/CustomElements/src/js",
"src/Components/Server.AutoPause/src/js",
"src/Components/Platform/src/js",
Comment thread
jsakamotoIGJP marked this conversation as resolved.
Resolved
"src/ProjectTemplates/test/Templates.Tests"
],
"scripts": {
Expand Down
7 changes: 5 additions & 2 deletions src/Components/Platform/src/BrowserPlatform.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace Microsoft.AspNetCore.Components.Platform;

internal sealed class BrowserPlatform : IBrowserPlatform, IAsyncDisposable
{
public BrowserPlatform(Microsoft.JSInterop.IJSRuntime jsRuntime)
public BrowserPlatform(Microsoft.JSInterop.IJSRuntime jsRuntime, ILoggerFactory? loggerFactory = null)
{
Window = new Window(jsRuntime);
Window = new Window(jsRuntime, loggerFactory ?? NullLoggerFactory.Instance);
}

public Window Window { get; }
Expand Down
20 changes: 20 additions & 0 deletions src/Components/Platform/src/CookieChangeEvent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components.Platform;

/// <summary>
/// Represents a change to the cookies visible to the current page.
/// </summary>
public sealed class CookieChangeEvent
{
/// <summary>
/// Gets the cookies that were created or changed.
/// </summary>
public IReadOnlyList<CookieListItem> Changed { get; init; } = [];

/// <summary>
/// Gets the cookies that were deleted. Their <see cref="CookieListItem.Value"/> is <see langword="null"/>.
/// </summary>
public IReadOnlyList<CookieListItem> Deleted { get; init; } = [];
}
59 changes: 58 additions & 1 deletion src/Components/Platform/src/CookieStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,23 @@ namespace Microsoft.AspNetCore.Components.Platform;
public sealed class CookieStore : IInternalAsyncDisposal
{
private readonly IJSRuntime _jsRuntime;
private readonly EventListenerCollection _listeners;
private Task<IJSObjectReference>? _referenceTask;
private bool _disposed;

internal CookieStore(IJSRuntime jsRuntime)
internal CookieStore(IJSRuntime jsRuntime, EventListenerCollection listeners)
{
_jsRuntime = jsRuntime;
_listeners = listeners;
}

// CookieListItem is a dictionary, so the lists are copied whole.
/// <summary>
/// Gets the event that fires when cookies visible to the current page change.
/// </summary>
public static EventType<CookieStore, CookieChangeEvent> ChangeEvent { get; }
= EventTypes.Create<CookieStore, CookieChangeEvent>("change", """[{"changed":null,"deleted":null}]""");

/// <summary>
/// Gets the first cookie with the specified name.
/// </summary>
Expand Down Expand Up @@ -168,6 +177,51 @@ public async ValueTask DeleteAsync(CookieStoreDeleteOptions options)
await cookieStore.InvokeVoidAsync("delete", options).ConfigureAwait(false);
}

/// <summary>
/// Adds a listener that is called each time the specified event fires on the cookie store.
/// Other listeners, including those added by JavaScript code of the page, are not affected.
/// An exception thrown by the listener is logged and does not remove the listener.
/// Each call creates an independent registration, even for the same listener;
/// disposing the returned object removes only that registration.
/// </summary>
/// <typeparam name="TEvent">The type of the event object.</typeparam>
/// <param name="type">The event to listen for, such as <see cref="ChangeEvent"/>.</param>
/// <param name="listener">The function to call with each event.</param>
/// <returns>An object that removes the listener when disposed.</returns>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="listener"/> is <see langword="null"/>.</exception>
/// <exception cref="NotSupportedException">The browser does not provide the Cookie Store API for the current page.</exception>
public ValueTask<IAsyncDisposable> AddEventListenerAsync<TEvent>(EventType<CookieStore, TEvent> type, Func<TEvent, Task> listener)
=> AddEventListenerAsync(type, listener, CancellationToken.None);

/// <summary>
/// Adds a listener that is called each time the specified event fires on the cookie store.
/// Other listeners, including those added by JavaScript code of the page, are not affected.
/// An exception thrown by the listener is logged and does not remove the listener.
/// Each call creates an independent registration, even for the same listener;
/// disposing the returned object removes only that registration.
/// Canceling <paramref name="cancellationToken"/> removes the listener, as disposing the returned object does.
/// </summary>
/// <typeparam name="TEvent">The type of the event object.</typeparam>
/// <param name="type">The event to listen for, such as <see cref="ChangeEvent"/>.</param>
/// <param name="listener">The function to call with each event.</param>
/// <param name="cancellationToken">The token that removes the listener when canceled.</param>
/// <returns>An object that removes the listener when disposed.</returns>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="listener"/> is <see langword="null"/>.</exception>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled before the listener was added.</exception>
/// <exception cref="NotSupportedException">The browser does not provide the Cookie Store API for the current page.</exception>
[DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieListItem))]
public async ValueTask<IAsyncDisposable> AddEventListenerAsync<TEvent>(EventType<CookieStore, TEvent> type, Func<TEvent, Task> listener, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(type);
ArgumentNullException.ThrowIfNull(listener);
cancellationToken.ThrowIfCancellationRequested();

// Adding and removing listeners changes unlocked state, so these awaits keep the renderer's synchronization context.
var cookieStore = await GetReferenceAsync();
Comment thread
jsakamotoIGJP marked this conversation as resolved.
Resolved

return await type.AddListenerAsync(_listeners, cookieStore, this, listener, cancellationToken);
}

async ValueTask IInternalAsyncDisposal.InternalDisposeAsync()
{
if (_disposed)
Expand All @@ -177,6 +231,9 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync()

_disposed = true;

// Listeners need the cookie store reference to remove themselves, so they go first.
await ((IInternalAsyncDisposal)_listeners).InternalDisposeAsync();

// Don't wait for a pending acquisition. It could hold up scope disposal until the JS interop timeout.
if (_referenceTask is { IsCompletedSuccessfully: true } referenceTask)
{
Expand Down
142 changes: 142 additions & 0 deletions src/Components/Platform/src/EventListener.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;

namespace Microsoft.AspNetCore.Components.Platform;

/// <summary>
/// One listener added with <c>addEventListener</c>. Disposing it or canceling its token removes the listener.
/// </summary>
internal sealed class EventListener<[DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] TEvent> : IAsyncDisposable
{
private readonly EventListenerCollection _owner;
private readonly IJSObjectReference _target;
private readonly string _type;
private readonly Func<TEvent, Task> _listener;
private readonly CancellationToken _cancellationToken;
private readonly ILogger _logger;
private IJSObjectReference? _function;
private IDisposable? _callbackReference;
private SynchronizationContext? _synchronizationContext;
private CancellationTokenRegistration _cancellationRegistration;
private bool _removed;

public EventListener(EventListenerCollection owner, IJSObjectReference target, string type, Func<TEvent, Task> listener, CancellationToken cancellationToken, ILogger logger)
{
_owner = owner;
_target = target;
_type = type;
_listener = listener;
_cancellationToken = cancellationToken;
_logger = logger;
}

public async Task AddAsync(JSCallbackFactory callbackFactory, string shapesJson)
{
var callback = new JSCallback<TEvent> { Handler = InvokeListenerAsync };
(_function, _callbackReference) = await callbackFactory.CreateAsync(callback, shapesJson);

// Disposal can run while the function is being created, and then nothing else releases it.
if (_removed || _cancellationToken.IsCancellationRequested)
{
await ReleaseAsync();
_cancellationToken.ThrowIfCancellationRequested();
throw new ObjectDisposedException(GetType().Name);
}

await _target.InvokeVoidAsync("addEventListener", _type, _function);
}

/// <summary>
/// Removes the listener when its token is canceled. Call it once the listener is added.
/// </summary>
public void RemoveWhenCanceled()
{
// Not useSynchronizationContext: its Send blocks forever when Cancel runs on Blazor's renderer context.
_synchronizationContext = SynchronizationContext.Current;
_cancellationRegistration = _cancellationToken.Register(static state => ((EventListener<TEvent>)state!).OnCanceled(), this);
}

public async ValueTask DisposeAsync()
{
if (_removed)
{
return;
}

_removed = true;
_cancellationRegistration.Dispose();
_owner.Remove(this);

await ReleaseAsync();
}

private void OnCanceled()
{
// Removal changes unlocked state, so it runs on the context that added the listener.
if (_synchronizationContext is { } context)
{
context.Post(static state => _ = ((EventListener<TEvent>)state!).RemoveAfterCancellationAsync(), this);
}
else
{
_ = RemoveAfterCancellationAsync();
}
}

private async Task RemoveAfterCancellationAsync() => await _owner.TryDisposeAsync(this);

private async Task InvokeListenerAsync(TEvent value)
{
// A call that left the browser before removal can still arrive.
if (_removed || _cancellationToken.IsCancellationRequested)
{
return;
}

try
{
await _listener(value);
}
catch (Exception ex)
{
EventListenerCollection.Log.ListenerThrew(_logger, _type, ex);
}
}

private async ValueTask ReleaseAsync()
{
var function = _function;
var callbackReference = _callbackReference;
_function = null;
_callbackReference = null;

// A failed removal still releases both references, and then reaches the caller.
try
{
if (function is not null)
{
try
{
await _target.InvokeVoidAsync("removeEventListener", _type, function);
}
catch (JSDisconnectedException)
{
// The page is already gone, so nothing can call the listener.
}
finally
{
await function.DisposeAsync();
}
}
}
finally
{
callbackReference?.Dispose();
}
}
}
Loading
Loading