diff --git a/eng/Npm.Workspace.nodeproj b/eng/Npm.Workspace.nodeproj
index 6085da589820..127fda7643ca 100644
--- a/eng/Npm.Workspace.nodeproj
+++ b/eng/Npm.Workspace.nodeproj
@@ -114,6 +114,11 @@
+
+
+
+
+
diff --git a/package-lock.json b/package-lock.json
index c1c7e5842bc4..1e65386a0113 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -19,6 +19,7 @@
"src/Components/WebAssembly/Authentication.Msal/src/Interop",
"src/Components/CustomElements/src/js",
"src/Components/Server.AutoPause/src/js",
+ "src/Components/Platform/src/js",
"src/ProjectTemplates/test/Templates.Tests"
],
"devDependencies": {
@@ -2773,6 +2774,10 @@
"resolved": "src/SignalR/clients/ts/FunctionalTests",
"link": true
},
+ "node_modules/@microsoft/microsoft.aspnetcore.components.platform": {
+ "resolved": "src/Components/Platform/src/js",
+ "link": true
+ },
"node_modules/@microsoft/microsoft.aspnetcore.components.server.autopause": {
"resolved": "src/Components/Server.AutoPause/src/js",
"link": true
@@ -18398,6 +18403,9 @@
"version": "1.0.0",
"license": "MIT"
},
+ "src/Components/Platform/src/js": {
+ "name": "@microsoft/microsoft.aspnetcore.components.platform"
+ },
"src/Components/Server.AutoPause/src/js": {
"name": "@microsoft/microsoft.aspnetcore.components.server.autopause"
},
diff --git a/package.json b/package.json
index 86dc85959218..dfddc334a2ea 100644
--- a/package.json
+++ b/package.json
@@ -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",
"src/ProjectTemplates/test/Templates.Tests"
],
"scripts": {
diff --git a/src/Components/Platform/src/BrowserPlatform.cs b/src/Components/Platform/src/BrowserPlatform.cs
index cb32e163f974..e9c6c097686b 100644
--- a/src/Components/Platform/src/BrowserPlatform.cs
+++ b/src/Components/Platform/src/BrowserPlatform.cs
@@ -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; }
diff --git a/src/Components/Platform/src/CookieChangeEvent.cs b/src/Components/Platform/src/CookieChangeEvent.cs
new file mode 100644
index 000000000000..b0b5d6cf1b81
--- /dev/null
+++ b/src/Components/Platform/src/CookieChangeEvent.cs
@@ -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;
+
+///
+/// Represents a change to the cookies visible to the current page.
+///
+public sealed class CookieChangeEvent
+{
+ ///
+ /// Gets the cookies that were created or changed.
+ ///
+ public IReadOnlyList Changed { get; init; } = [];
+
+ ///
+ /// Gets the cookies that were deleted. Their is .
+ ///
+ public IReadOnlyList Deleted { get; init; } = [];
+}
diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs
index 1071e802672d..7315c498e2c9 100644
--- a/src/Components/Platform/src/CookieStore.cs
+++ b/src/Components/Platform/src/CookieStore.cs
@@ -13,14 +13,23 @@ namespace Microsoft.AspNetCore.Components.Platform;
public sealed class CookieStore : IInternalAsyncDisposal
{
private readonly IJSRuntime _jsRuntime;
+ private readonly EventListenerCollection _listeners;
private Task? _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.
+ ///
+ /// Gets the event that fires when cookies visible to the current page change.
+ ///
+ public static EventType ChangeEvent { get; }
+ = EventTypes.Create("change", """[{"changed":null,"deleted":null}]""");
+
///
/// Gets the first cookie with the specified name.
///
@@ -168,6 +177,51 @@ public async ValueTask DeleteAsync(CookieStoreDeleteOptions options)
await cookieStore.InvokeVoidAsync("delete", options).ConfigureAwait(false);
}
+ ///
+ /// 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.
+ ///
+ /// The type of the event object.
+ /// The event to listen for, such as .
+ /// The function to call with each event.
+ /// An object that removes the listener when disposed.
+ /// or is .
+ /// The browser does not provide the Cookie Store API for the current page.
+ public ValueTask AddEventListenerAsync(EventType type, Func listener)
+ => AddEventListenerAsync(type, listener, CancellationToken.None);
+
+ ///
+ /// 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 removes the listener, as disposing the returned object does.
+ ///
+ /// The type of the event object.
+ /// The event to listen for, such as .
+ /// The function to call with each event.
+ /// The token that removes the listener when canceled.
+ /// An object that removes the listener when disposed.
+ /// or is .
+ /// was canceled before the listener was added.
+ /// The browser does not provide the Cookie Store API for the current page.
+ [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieListItem))]
+ public async ValueTask AddEventListenerAsync(EventType type, Func 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();
+
+ return await type.AddListenerAsync(_listeners, cookieStore, this, listener, cancellationToken);
+ }
+
async ValueTask IInternalAsyncDisposal.InternalDisposeAsync()
{
if (_disposed)
@@ -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)
{
diff --git a/src/Components/Platform/src/EventListener.cs b/src/Components/Platform/src/EventListener.cs
new file mode 100644
index 000000000000..0e8286490f1a
--- /dev/null
+++ b/src/Components/Platform/src/EventListener.cs
@@ -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;
+
+///
+/// One listener added with addEventListener. Disposing it or canceling its token removes the listener.
+///
+internal sealed class EventListener<[DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] TEvent> : IAsyncDisposable
+{
+ private readonly EventListenerCollection _owner;
+ private readonly IJSObjectReference _target;
+ private readonly string _type;
+ private readonly Func _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 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 { 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);
+ }
+
+ ///
+ /// Removes the listener when its token is canceled. Call it once the listener is added.
+ ///
+ 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)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)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();
+ }
+ }
+}
diff --git a/src/Components/Platform/src/EventListenerCollection.cs b/src/Components/Platform/src/EventListenerCollection.cs
new file mode 100644
index 000000000000..2837f4b28f14
--- /dev/null
+++ b/src/Components/Platform/src/EventListenerCollection.cs
@@ -0,0 +1,113 @@
+// 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;
+
+///
+/// Tracks the listeners added to one event target, so that scope disposal can remove them all.
+///
+internal sealed partial class EventListenerCollection : IInternalAsyncDisposal
+{
+ private readonly JSCallbackFactory _callbackFactory;
+ private readonly ILogger _logger;
+ private readonly List _listeners = [];
+ private bool _disposed;
+
+ public EventListenerCollection(JSCallbackFactory callbackFactory, ILogger logger)
+ {
+ _callbackFactory = callbackFactory;
+ _logger = logger;
+ }
+
+ ///
+ /// Adds a listener for to .
+ ///
+ /// The handle that removes the listener when disposed.
+ public async Task AddAsync<[DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] TEvent>(
+ IJSObjectReference target,
+ string type,
+ string shapesJson,
+ Func listener,
+ CancellationToken cancellationToken)
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var eventListener = new EventListener(this, target, type, listener, cancellationToken, _logger);
+ _listeners.Add(eventListener);
+
+ try
+ {
+ await eventListener.AddAsync(_callbackFactory, shapesJson);
+ }
+ catch (Exception ex)
+ {
+ // The exception of the failed addition is the useful one.
+ await TryDisposeAsync(eventListener);
+
+ // Decided by the token, not by the error, as for other canceled browser operations.
+ if (cancellationToken.IsCancellationRequested && ex is not OperationCanceledException)
+ {
+ throw new OperationCanceledException(ex.Message, ex, cancellationToken);
+ }
+
+ throw;
+ }
+
+ // The token can be canceled while addEventListener is on its way.
+ if (cancellationToken.IsCancellationRequested)
+ {
+ await TryDisposeAsync(eventListener);
+ cancellationToken.ThrowIfCancellationRequested();
+ }
+
+ // Scope disposal can run while addEventListener is on its way, and it has already removed this listener.
+ ObjectDisposedException.ThrowIf(_disposed, this);
+
+ eventListener.RemoveWhenCanceled();
+ return eventListener;
+ }
+
+ internal void Remove(IAsyncDisposable listener) => _listeners.Remove(listener);
+
+ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+
+ foreach (var listener in _listeners.ToArray())
+ {
+ await TryDisposeAsync(listener);
+ }
+ }
+
+ internal async ValueTask TryDisposeAsync(IAsyncDisposable listener)
+ {
+ try
+ {
+ await listener.DisposeAsync();
+ }
+ catch (Exception ex)
+ {
+ Log.ListenerRemovalFailed(_logger, ex);
+ }
+ }
+
+ internal static partial class Log
+ {
+ [LoggerMessage(2, LogLevel.Warning, "A listener could not be removed from its event target.", EventName = "ListenerRemovalFailed")]
+ public static partial void ListenerRemovalFailed(ILogger logger, Exception exception);
+
+ [LoggerMessage(1, LogLevel.Error, "A listener for the '{EventType}' event threw an exception.", EventName = "ListenerThrew")]
+ public static partial void ListenerThrew(ILogger logger, string eventType, Exception exception);
+ }
+}
diff --git a/src/Components/Platform/src/EventType.cs b/src/Components/Platform/src/EventType.cs
new file mode 100644
index 000000000000..e098ededadc8
--- /dev/null
+++ b/src/Components/Platform/src/EventType.cs
@@ -0,0 +1,67 @@
+// 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.JSInterop;
+
+namespace Microsoft.AspNetCore.Components.Platform;
+
+///
+/// Identifies an event that a fires, and the type of the event object that listeners receive.
+///
+/// The type of the object that fires the event.
+/// The type of the event object.
+public sealed class EventType where TTarget : class
+{
+ private readonly Func, CancellationToken, Task> _addListenerAsync;
+
+ internal EventType(
+ string name,
+ Func, CancellationToken, Task> addListenerAsync)
+ {
+ Name = name;
+ _addListenerAsync = addListenerAsync;
+ }
+
+ ///
+ /// Gets the name of the event, such as "change".
+ ///
+ public string Name { get; }
+
+ internal Task AddListenerAsync(EventListenerCollection listeners, IJSObjectReference target, TTarget owner, Func listener, CancellationToken cancellationToken)
+ => _addListenerAsync(listeners, target, owner, listener, cancellationToken);
+}
+
+///
+/// Creates instances. The event object types are known here,
+/// so the public methods that add listeners need no trimming annotations.
+///
+internal static class EventTypes
+{
+ ///
+ /// Creates an event whose object crosses to .NET as itself.
+ ///
+ /// The JavaScript event name.
+ /// The ArgumentShape list (see js/Platform.ts) that copies the event object.
+ public static EventType Create(
+ string name,
+ string shapesJson)
+ where TTarget : class
+ => new(name, (listeners, target, _, listener, cancellationToken) => listeners.AddAsync(target, name, shapesJson, listener, cancellationToken));
+
+ ///
+ /// Creates an event whose object crosses to .NET as and is then converted,
+ /// for members such as storageArea that refer to an existing projection.
+ ///
+ /// The JavaScript event name.
+ /// The ArgumentShape list (see js/Platform.ts) that copies the event object.
+ /// The function that creates the event object from the target and the payload.
+ public static EventType Create(
+ string name,
+ string shapesJson,
+ Func convert)
+ where TTarget : class
+ => new(name, (listeners, target, owner, listener, cancellationToken) =>
+ listeners.AddAsync(target, name, shapesJson, payload => listener(convert(owner, payload)), cancellationToken));
+}
diff --git a/src/Components/Platform/src/FeatureContext.cs b/src/Components/Platform/src/FeatureContext.cs
index 70603951a01c..dfbf601c321d 100644
--- a/src/Components/Platform/src/FeatureContext.cs
+++ b/src/Components/Platform/src/FeatureContext.cs
@@ -1,6 +1,7 @@
// 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.JSInterop;
namespace Microsoft.AspNetCore.Components.Platform;
@@ -8,15 +9,30 @@ namespace Microsoft.AspNetCore.Components.Platform;
///
/// Provides what a projection needs when it is created, shared by all projections of the scope.
///
-internal sealed class FeatureContext
+internal sealed class FeatureContext : IInternalAsyncDisposal
{
- public FeatureContext(IJSRuntime jsRuntime)
+ private readonly ILoggerFactory _loggerFactory;
+ // Typed as the interface, so that disposal does not keep the type in an app that never adds a listener.
+ private IInternalAsyncDisposal? _callbackFactory;
+
+ public FeatureContext(IJSRuntime jsRuntime, ILoggerFactory loggerFactory)
{
JSRuntime = jsRuntime;
+ _loggerFactory = loggerFactory;
}
///
/// Gets the JS runtime of the scope.
///
public IJSRuntime JSRuntime { get; }
+
+ ///
+ /// Creates the collection that a projection uses to add event listeners to its JavaScript object.
+ ///
+ public EventListenerCollection CreateEventListenerCollection()
+ => new((JSCallbackFactory)(_callbackFactory ??= new JSCallbackFactory(JSRuntime)), _loggerFactory.CreateLogger());
+
+ // Window calls this last, after every listener that needs the module is removed.
+ ValueTask IInternalAsyncDisposal.InternalDisposeAsync()
+ => _callbackFactory?.InternalDisposeAsync() ?? ValueTask.CompletedTask;
}
diff --git a/src/Components/Platform/src/JSCallback.cs b/src/Components/Platform/src/JSCallback.cs
new file mode 100644
index 000000000000..1c495b8af98f
--- /dev/null
+++ b/src/Components/Platform/src/JSCallback.cs
@@ -0,0 +1,19 @@
+// 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.JSInterop;
+
+namespace Microsoft.AspNetCore.Components.Platform;
+
+// Objects that the functions created by JSCallbackFactory call. The browser can call such a function
+// before a handler is set or after it is removed, so a missing handler is not an error.
+
+internal sealed class JSCallback<[DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T1>
+{
+ public Func? Handler { get; set; }
+
+ [JSInvokable]
+ public Task Invoke(T1 arg1) => Handler?.Invoke(arg1) ?? Task.CompletedTask;
+}
diff --git a/src/Components/Platform/src/JSCallbackFactory.cs b/src/Components/Platform/src/JSCallbackFactory.cs
new file mode 100644
index 000000000000..676637026518
--- /dev/null
+++ b/src/Components/Platform/src/JSCallbackFactory.cs
@@ -0,0 +1,97 @@
+// 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.JSInterop;
+
+namespace Microsoft.AspNetCore.Components.Platform;
+
+///
+/// Creates JavaScript functions that call a through the JavaScript module of this package.
+///
+internal sealed class JSCallbackFactory : IInternalAsyncDisposal
+{
+ private const string ModulePath = "./_content/Microsoft.AspNetCore.Components.Platform/Microsoft.AspNetCore.Components.Platform.js";
+
+ private readonly IJSRuntime _jsRuntime;
+ private Task? _moduleTask;
+ private bool _disposed;
+
+ public JSCallbackFactory(IJSRuntime jsRuntime)
+ {
+ _jsRuntime = jsRuntime;
+ }
+
+ ///
+ /// Creates a JavaScript function that calls .
+ ///
+ /// The to call.
+ ///
+ /// A JSON array with one ArgumentShape (see js/Platform.ts) per parameter of .
+ ///
+ ///
+ /// The function, and the reference that lets JavaScript reach .
+ /// The caller owns both and releases them when the function is no longer used.
+ ///
+ public async Task<(IJSObjectReference Function, IDisposable CallbackReference)> CreateAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCallback>(
+ TCallback callback,
+ string shapesJson)
+ where TCallback : class
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+
+ var module = await GetModuleAsync();
+ var callbackReference = DotNetObjectReference.Create(callback);
+
+ try
+ {
+ var function = await module.InvokeAsync("createCallback", callbackReference, shapesJson);
+ return (function, callbackReference);
+ }
+ catch
+ {
+ callbackReference.Dispose();
+ throw;
+ }
+ }
+
+ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+
+ // Functions created from the module keep working after the module reference is released.
+ if (_moduleTask is { IsCompletedSuccessfully: true } moduleTask)
+ {
+ await moduleTask.Result.DisposeAsync();
+ }
+ }
+
+ private Task GetModuleAsync()
+ {
+ if (_moduleTask is null || _moduleTask.IsFaulted || _moduleTask.IsCanceled)
+ {
+ _moduleTask = ImportModuleAsync();
+ }
+
+ return _moduleTask;
+ }
+
+ private async Task ImportModuleAsync()
+ {
+ var module = await _jsRuntime.InvokeAsync("import", ModulePath);
+
+ // Disposal does not wait for the import, so nothing else releases a module that arrives after it.
+ if (_disposed)
+ {
+ await module.DisposeAsync();
+ throw new ObjectDisposedException(GetType().Name);
+ }
+
+ return module;
+ }
+}
diff --git a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj
index 75cd97a04839..77c52da9c39f 100644
--- a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj
+++ b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj
@@ -1,4 +1,4 @@
-
+$(DefaultNetCoreTargetFramework)
@@ -21,4 +21,66 @@
+
+
+
+
+
+
+
+ $(MSBuildThisFileDirectory)js\
+
+ IncludeCompileJsOutput;
+ $(ResolveStaticWebAssetsInputsDependsOn)
+
+
+
+
+
+ <_JsBuildOutput Include="$(InteropWorkingDir)dist\$(Configuration)\**" Exclude="$(InteropWorkingDir)dist\.gitignore" />
+ <_JsBuildOutput>
+ %(_JsBuildOutput.RecursiveDir)%(Filename)%(Extension)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ <_JsBuildOutput Include="$(InteropWorkingDir)dist\$(Configuration)\**" Exclude="$(InteropWorkingDir)dist\.gitignore" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Components/Platform/src/PublicAPI.Unshipped.txt b/src/Components/Platform/src/PublicAPI.Unshipped.txt
index 3c16643c5e2a..bb506b142a1d 100644
--- a/src/Components/Platform/src/PublicAPI.Unshipped.txt
+++ b/src/Components/Platform/src/PublicAPI.Unshipped.txt
@@ -1,4 +1,10 @@
#nullable enable
+Microsoft.AspNetCore.Components.Platform.CookieChangeEvent
+Microsoft.AspNetCore.Components.Platform.CookieChangeEvent.Changed.get -> System.Collections.Generic.IReadOnlyList!
+Microsoft.AspNetCore.Components.Platform.CookieChangeEvent.Changed.init -> void
+Microsoft.AspNetCore.Components.Platform.CookieChangeEvent.CookieChangeEvent() -> void
+Microsoft.AspNetCore.Components.Platform.CookieChangeEvent.Deleted.get -> System.Collections.Generic.IReadOnlyList!
+Microsoft.AspNetCore.Components.Platform.CookieChangeEvent.Deleted.init -> void
Microsoft.AspNetCore.Components.Platform.CookieInit
Microsoft.AspNetCore.Components.Platform.CookieInit.CookieInit() -> void
Microsoft.AspNetCore.Components.Platform.CookieInit.Domain.get -> string?
@@ -28,6 +34,8 @@ Microsoft.AspNetCore.Components.Platform.CookieSameSite.Lax = 1 -> Microsoft.Asp
Microsoft.AspNetCore.Components.Platform.CookieSameSite.None = 2 -> Microsoft.AspNetCore.Components.Platform.CookieSameSite
Microsoft.AspNetCore.Components.Platform.CookieSameSite.Strict = 0 -> Microsoft.AspNetCore.Components.Platform.CookieSameSite
Microsoft.AspNetCore.Components.Platform.CookieStore
+Microsoft.AspNetCore.Components.Platform.CookieStore.AddEventListenerAsync(Microsoft.AspNetCore.Components.Platform.EventType! type, System.Func! listener, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask
+Microsoft.AspNetCore.Components.Platform.CookieStore.AddEventListenerAsync(Microsoft.AspNetCore.Components.Platform.EventType! type, System.Func! listener) -> System.Threading.Tasks.ValueTask
Microsoft.AspNetCore.Components.Platform.CookieStore.DeleteAsync(Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions! options) -> System.Threading.Tasks.ValueTask
Microsoft.AspNetCore.Components.Platform.CookieStore.DeleteAsync(string! name) -> System.Threading.Tasks.ValueTask
Microsoft.AspNetCore.Components.Platform.CookieStore.GetAllAsync() -> System.Threading.Tasks.ValueTask!>
@@ -53,8 +61,22 @@ Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions.Name.get -> strin
Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions.Name.set -> void
Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions.Url.get -> string?
Microsoft.AspNetCore.Components.Platform.CookieStoreGetOptions.Url.set -> void
+Microsoft.AspNetCore.Components.Platform.EventType
+Microsoft.AspNetCore.Components.Platform.EventType.Name.get -> string!
Microsoft.AspNetCore.Components.Platform.IBrowserPlatform
Microsoft.AspNetCore.Components.Platform.IBrowserPlatform.Window.get -> Microsoft.AspNetCore.Components.Platform.Window!
+Microsoft.AspNetCore.Components.Platform.StorageEvent
+Microsoft.AspNetCore.Components.Platform.StorageEvent.Key.get -> string?
+Microsoft.AspNetCore.Components.Platform.StorageEvent.Key.init -> void
+Microsoft.AspNetCore.Components.Platform.StorageEvent.NewValue.get -> string?
+Microsoft.AspNetCore.Components.Platform.StorageEvent.NewValue.init -> void
+Microsoft.AspNetCore.Components.Platform.StorageEvent.OldValue.get -> string?
+Microsoft.AspNetCore.Components.Platform.StorageEvent.OldValue.init -> void
+Microsoft.AspNetCore.Components.Platform.StorageEvent.StorageArea.get -> Microsoft.AspNetCore.Components.Platform.Storage?
+Microsoft.AspNetCore.Components.Platform.StorageEvent.StorageArea.init -> void
+Microsoft.AspNetCore.Components.Platform.StorageEvent.StorageEvent() -> void
+Microsoft.AspNetCore.Components.Platform.StorageEvent.Url.get -> string!
+Microsoft.AspNetCore.Components.Platform.StorageEvent.Url.init -> void
Microsoft.AspNetCore.Components.Platform.Storage
Microsoft.AspNetCore.Components.Platform.Storage.ClearAsync() -> System.Threading.Tasks.ValueTask
Microsoft.AspNetCore.Components.Platform.Storage.GetItemAsync(string! key) -> System.Threading.Tasks.ValueTask
@@ -121,6 +143,8 @@ Microsoft.AspNetCore.Components.Platform.WindowUrlExtensions
Microsoft.AspNetCore.Components.Platform.WindowUrlExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!)
Microsoft.AspNetCore.Components.Platform.WindowUrlExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!).Url.get -> Microsoft.AspNetCore.Components.Platform.UrlConstructor!
Microsoft.AspNetCore.Components.Platform.WindowUrlExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!).UrlSearchParams.get -> Microsoft.AspNetCore.Components.Platform.UrlSearchParamsConstructor!
+Microsoft.AspNetCore.Components.Platform.Window.AddEventListenerAsync(Microsoft.AspNetCore.Components.Platform.EventType! type, System.Func! listener, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask
+Microsoft.AspNetCore.Components.Platform.Window.AddEventListenerAsync(Microsoft.AspNetCore.Components.Platform.EventType! type, System.Func! listener) -> System.Threading.Tasks.ValueTask
Microsoft.AspNetCore.Components.Platform.WindowCookieStoreExtensions
Microsoft.AspNetCore.Components.Platform.WindowCookieStoreExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!)
Microsoft.AspNetCore.Components.Platform.WindowCookieStoreExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!).CookieStore.get -> Microsoft.AspNetCore.Components.Platform.CookieStore!
@@ -130,3 +154,5 @@ Microsoft.AspNetCore.Components.Platform.WindowWebStorageExtensions.extension(Mi
Microsoft.AspNetCore.Components.Platform.WindowWebStorageExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!).SessionStorage.get -> Microsoft.AspNetCore.Components.Platform.Storage!
Microsoft.Extensions.DependencyInjection.BrowserPlatformServiceCollectionExtensions
static Microsoft.Extensions.DependencyInjection.BrowserPlatformServiceCollectionExtensions.AddBrowserPlatform(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
+static Microsoft.AspNetCore.Components.Platform.CookieStore.ChangeEvent.get -> Microsoft.AspNetCore.Components.Platform.EventType!
+static Microsoft.AspNetCore.Components.Platform.WindowWebStorageExtensions.extension(Microsoft.AspNetCore.Components.Platform.Window!).StorageEvent.get -> Microsoft.AspNetCore.Components.Platform.EventType!
diff --git a/src/Components/Platform/src/StorageEvent.cs b/src/Components/Platform/src/StorageEvent.cs
new file mode 100644
index 000000000000..8667ee48740c
--- /dev/null
+++ b/src/Components/Platform/src/StorageEvent.cs
@@ -0,0 +1,35 @@
+// 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;
+
+///
+/// Represents a change to local or session storage made by another page of the same origin.
+///
+public sealed class StorageEvent
+{
+ ///
+ /// Gets the key of the changed item, or if the storage was cleared.
+ ///
+ public string? Key { get; init; }
+
+ ///
+ /// Gets the previous value of the item, or if the item was added or the storage was cleared.
+ ///
+ public string? OldValue { get; init; }
+
+ ///
+ /// Gets the new value of the item, or if the item was removed or the storage was cleared.
+ ///
+ public string? NewValue { get; init; }
+
+ ///
+ /// Gets the URL of the page whose storage changed.
+ ///
+ public string Url { get; init; } = string.Empty;
+
+ ///
+ /// Gets the storage that changed. It is the same instance as Window.LocalStorage or Window.SessionStorage.
+ ///
+ public Storage? StorageArea { get; init; }
+}
diff --git a/src/Components/Platform/src/StorageEventPayload.cs b/src/Components/Platform/src/StorageEventPayload.cs
new file mode 100644
index 000000000000..436a86cdd7e8
--- /dev/null
+++ b/src/Components/Platform/src/StorageEventPayload.cs
@@ -0,0 +1,32 @@
+// 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;
+
+// The storage event as it crosses from JavaScript. StorageArea holds the name of the global, not a reference.
+internal sealed class StorageEventPayload
+{
+ public string? Key { get; init; }
+
+ public string? OldValue { get; init; }
+
+ public string? NewValue { get; init; }
+
+ public string Url { get; init; } = string.Empty;
+
+ public string? StorageArea { get; init; }
+
+ public StorageEvent ToStorageEvent(Window window) => new()
+ {
+ Key = Key,
+ OldValue = OldValue,
+ NewValue = NewValue,
+ Url = Url,
+ StorageArea = StorageArea switch
+ {
+ "localStorage" => window.LocalStorage,
+ "sessionStorage" => window.SessionStorage,
+ _ => null,
+ },
+ };
+}
diff --git a/src/Components/Platform/src/Window.cs b/src/Components/Platform/src/Window.cs
index 0b880934b84c..7b0d38f02315 100644
--- a/src/Components/Platform/src/Window.cs
+++ b/src/Components/Platform/src/Window.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
+using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
namespace Microsoft.AspNetCore.Components.Platform;
@@ -12,12 +13,73 @@ namespace Microsoft.AspNetCore.Components.Platform;
public sealed class Window : IInternalAsyncDisposal
{
private readonly FeatureContext _context;
+ // Typed as the interface, so that disposal does not keep the type in an app that never adds a listener.
+ private IInternalAsyncDisposal? _listeners;
private readonly Dictionary<(Type FeatureType, string? Subkey), object> _features = [];
+ private Task? _referenceTask;
private bool _disposed;
- internal Window(IJSRuntime jsRuntime)
+ internal Window(IJSRuntime jsRuntime, ILoggerFactory loggerFactory)
{
- _context = new FeatureContext(jsRuntime);
+ _context = new FeatureContext(jsRuntime, loggerFactory);
+ }
+
+ ///
+ /// Adds a listener that is called each time the specified event fires on the window.
+ /// 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.
+ ///
+ /// The type of the event object.
+ /// The event to listen for, such as Window.StorageEvent.
+ /// The function to call with each event.
+ /// An object that removes the listener when disposed.
+ /// or is .
+ public ValueTask AddEventListenerAsync(EventType type, Func listener)
+ => AddEventListenerAsync(type, listener, CancellationToken.None);
+
+ ///
+ /// Adds a listener that is called each time the specified event fires on the window.
+ /// 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 removes the listener, as disposing the returned object does.
+ ///
+ /// The type of the event object.
+ /// The event to listen for, such as Window.StorageEvent.
+ /// The function to call with each event.
+ /// The token that removes the listener when canceled.
+ /// An object that removes the listener when disposed.
+ /// or is .
+ /// was canceled before the listener was added.
+ public async ValueTask AddEventListenerAsync(EventType type, Func 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 window = await GetReferenceAsync();
+
+ // The collection and the module loader are created here, so an app that adds no listener pays nothing.
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ var listeners = (EventListenerCollection)(_listeners ??= _context.CreateEventListenerCollection());
+
+ return await type.AddListenerAsync(listeners, window, this, listener, cancellationToken);
+ }
+
+ private Task GetReferenceAsync()
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+
+ if (_referenceTask is null || _referenceTask.IsFaulted || _referenceTask.IsCanceled)
+ {
+ _referenceTask = _context.JSRuntime.GetValueAsync("window").AsTask();
+ }
+
+ return _referenceTask;
}
///
@@ -75,6 +137,19 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync()
}
_disposed = true;
+
+ // Listeners need the window reference to remove themselves, so they go first.
+ if (_listeners is not null)
+ {
+ await _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)
+ {
+ await referenceTask.Result.DisposeAsync().ConfigureAwait(false);
+ }
+
var features = _features.Values.ToArray();
_features.Clear();
@@ -85,5 +160,8 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync()
await disposable.InternalDisposeAsync().ConfigureAwait(false);
}
}
+
+ // Features remove their listeners first, so the module is no longer needed.
+ await ((IInternalAsyncDisposal)_context).InternalDisposeAsync();
}
}
diff --git a/src/Components/Platform/src/WindowCookieStoreExtensions.cs b/src/Components/Platform/src/WindowCookieStoreExtensions.cs
index 8fd6f2e8f656..0af7ad060cbb 100644
--- a/src/Components/Platform/src/WindowCookieStoreExtensions.cs
+++ b/src/Components/Platform/src/WindowCookieStoreExtensions.cs
@@ -14,6 +14,6 @@ public static class WindowCookieStoreExtensions
/// Gets the cookie store of the current page.
///
public CookieStore CookieStore
- => window.GetOrAddFeature(static context => new CookieStore(context.JSRuntime));
+ => window.GetOrAddFeature(static context => new CookieStore(context.JSRuntime, context.CreateEventListenerCollection()));
}
}
diff --git a/src/Components/Platform/src/WindowWebStorageExtensions.cs b/src/Components/Platform/src/WindowWebStorageExtensions.cs
index 2c51070c67bf..7b0a80430f57 100644
--- a/src/Components/Platform/src/WindowWebStorageExtensions.cs
+++ b/src/Components/Platform/src/WindowWebStorageExtensions.cs
@@ -8,6 +8,20 @@ namespace Microsoft.AspNetCore.Components.Platform;
///
public static class WindowWebStorageExtensions
{
+ private static readonly EventType _storageEvent = EventTypes.Create(
+ "storage",
+ """[{"key":null,"oldValue":null,"newValue":null,"url":null,"storageArea":{"$known":["localStorage","sessionStorage"]}}]""",
+ static (window, payload) => payload.ToStorageEvent(window));
+
+ extension(Window)
+ {
+ ///
+ /// Gets the event that fires when another page of the same origin changes local or session storage.
+ /// It does not fire for changes that the current page makes.
+ ///
+ public static EventType StorageEvent => _storageEvent;
+ }
+
extension(Window window)
{
///
diff --git a/src/Components/Platform/src/js/Platform.ts b/src/Components/Platform/src/js/Platform.ts
new file mode 100644
index 000000000000..ff87ca1b8553
--- /dev/null
+++ b/src/Components/Platform/src/js/Platform.ts
@@ -0,0 +1,92 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+// Specifies which data from one argument is sent to .NET. When null, the whole value is sent. An object sends only the named
+// properties, each with its own shape, so that a browser object such as an event can be copied.
+// { $known: [...] } sends the name of the global that is the value, such as "localStorage".
+export type ArgumentShape = null | KnownObjectShape | { [property: string]: ArgumentShape };
+
+interface KnownObjectShape {
+ $known: string[];
+}
+
+export interface DotNetObject {
+ invokeMethodAsync(methodIdentifier: string, ...args: unknown[]): Promise;
+}
+
+// Creates a JS function that calls the .NET Invoke method of the callback reference with one argument per shape.
+// Arguments beyond the shapes are dropped. The returned promise settles when the .NET method completes.
+// E.g. [{ key: null }, null] + [{ key: "theme", oldValue: "light" }, "hello", 123] → Invoke({ key: "theme" }, "hello")
+export function createCallback(callbackReference: DotNetObject, shapesJson: string): (...args: unknown[]) => Promise {
+ const shapes: ArgumentShape[] = JSON.parse(shapesJson);
+
+ return (...args) => callbackReference.invokeMethodAsync('Invoke', ...shapes.map((shape, index) => toDotNet(args[index], shape)));
+}
+
+export function toDotNet(value: unknown, shape: ArgumentShape): unknown {
+ if (shape === null) {
+ return toTransferable(value);
+ }
+
+ if (value === null || value === undefined) {
+ return null;
+ }
+
+ if (Array.isArray(value)) {
+ return value.map(item => toDotNet(item, shape));
+ }
+
+ if (isKnownObjectShape(shape)) {
+ return toKnownName(value, shape.$known);
+ }
+
+ const copy: Record = {};
+ for (const [name, propertyShape] of Object.entries(shape)) {
+ copy[name] = toDotNet((value as Record)[name], propertyShape);
+ }
+
+ return copy;
+}
+
+// Web IDL dictionaries and sequences arrive as plain objects and arrays, so they are copied.
+// Any other object needs a shape that says how to send it. Without one it becomes a marker with its type name,
+// because a reference created here would have no owner to dispose it.
+export function toTransferable(value: unknown): unknown {
+ if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {
+ return value;
+ }
+
+ if (Array.isArray(value)) {
+ return value.map(toTransferable);
+ }
+
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype === Object.prototype || prototype === null) {
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, toTransferable(item)]));
+ }
+
+ return { __unsupported: typeNameOf(value) };
+}
+
+function isKnownObjectShape(shape: Exclude): shape is KnownObjectShape {
+ return Array.isArray((shape as Partial).$known);
+}
+
+function toKnownName(value: unknown, names: string[]): unknown {
+ for (const name of names) {
+ try {
+ if ((globalThis as Record)[name] === value) {
+ return name;
+ }
+ } catch {
+ // Reading a global such as localStorage throws when the browser blocks it, so it cannot be the value.
+ }
+ }
+
+ return toTransferable(value);
+}
+
+function typeNameOf(value: object): string {
+ return (value as { constructor?: { name?: string } }).constructor?.name
+ || Object.prototype.toString.call(value).slice('[object '.length, -1);
+}
diff --git a/src/Components/Platform/src/js/babel.config.js b/src/Components/Platform/src/js/babel.config.js
new file mode 100644
index 000000000000..8165fe455772
--- /dev/null
+++ b/src/Components/Platform/src/js/babel.config.js
@@ -0,0 +1,6 @@
+module.exports = {
+ presets: [
+ ['@babel/preset-env', { targets: { node: 'current' } }],
+ '@babel/preset-typescript',
+ ],
+};
diff --git a/src/Components/Platform/src/js/dist/.gitignore b/src/Components/Platform/src/js/dist/.gitignore
new file mode 100644
index 000000000000..c5ae7fff992d
--- /dev/null
+++ b/src/Components/Platform/src/js/dist/.gitignore
@@ -0,0 +1,3 @@
+**/*.js
+**/*.js.map
+**/*.txt
\ No newline at end of file
diff --git a/src/Components/Platform/src/js/jest.config.js b/src/Components/Platform/src/js/jest.config.js
new file mode 100644
index 000000000000..1781a7d41667
--- /dev/null
+++ b/src/Components/Platform/src/js/jest.config.js
@@ -0,0 +1,25 @@
+/*
+ * For a detailed explanation regarding each configuration property, visit:
+ * https://jestjs.io/docs/configuration
+ */
+
+const path = require('path');
+
+const ROOT_DIR = path.resolve(__dirname, '..', '..', '..', '..', '..');
+
+/** @type {import('jest').Config} */
+
+module.exports = {
+ roots: [''],
+ testMatch: ['**/test/**/*.test.ts'],
+ moduleFileExtensions: ['js', 'ts'],
+ transform: {
+ '^.+\\.(js|ts)$': 'babel-jest',
+ },
+ moduleDirectories: ['node_modules'],
+ testEnvironment: 'jsdom',
+ reporters: [
+ 'default',
+ [path.resolve(ROOT_DIR, 'node_modules', 'jest-junit', 'index.js'), { 'outputDirectory': path.resolve(ROOT_DIR, 'artifacts', 'log'), 'outputName': `${process.platform}` + '.components-platform.junit.xml' }]
+ ],
+};
diff --git a/src/Components/Platform/src/js/package.json b/src/Components/Platform/src/js/package.json
new file mode 100644
index 000000000000..840477b25135
--- /dev/null
+++ b/src/Components/Platform/src/js/package.json
@@ -0,0 +1,12 @@
+{
+ "private": true,
+ "name": "@microsoft/microsoft.aspnetcore.components.platform",
+ "scripts": {
+ "clean": "rimraf ./dist/Debug ./dist/Release",
+ "prebuild": "npm run clean",
+ "build": "npm run build:debug && npm run build:production",
+ "build:debug": "rollup -c --environment development --forceExit",
+ "build:production": "rollup -c --environment production --forceExit",
+ "test": "jest"
+ }
+}
diff --git a/src/Components/Platform/src/js/rollup.config.mjs b/src/Components/Platform/src/js/rollup.config.mjs
new file mode 100644
index 000000000000..8f789202144e
--- /dev/null
+++ b/src/Components/Platform/src/js/rollup.config.mjs
@@ -0,0 +1,18 @@
+import path from 'path';
+import { fileURLToPath } from 'url';
+import createBaseConfig from '../../../Shared.JS/rollup.config.mjs';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+// The .NET side imports the bundle as an ES module, so it must not end in .lib.module.js,
+// which Blazor would load as a JS initializer.
+export default createBaseConfig({
+ inputOutputMap: {
+ 'Microsoft.AspNetCore.Components.Platform': './Platform.ts',
+ },
+ dir: __dirname,
+ updateConfig: (config, _environment, _output, _input) => {
+ config.output.format = 'es';
+ }
+});
diff --git a/src/Components/Platform/src/js/test/Platform.test.ts b/src/Components/Platform/src/js/test/Platform.test.ts
new file mode 100644
index 000000000000..ef8a81fde6e9
--- /dev/null
+++ b/src/Components/Platform/src/js/test/Platform.test.ts
@@ -0,0 +1,101 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+import { createCallback, DotNetObject, toDotNet } from '../Platform';
+
+// Browser objects such as events expose their members as getters on the prototype.
+class BrowserObject {
+ get name(): string {
+ return 'browser';
+ }
+
+ get child(): BrowserObject | null {
+ return null;
+ }
+}
+
+function createCallbackReference(): DotNetObject & { calls: unknown[][] } {
+ const calls: unknown[][] = [];
+ return {
+ calls,
+ invokeMethodAsync: (methodIdentifier: string, ...args: unknown[]) => {
+ calls.push([methodIdentifier, ...args]);
+ return Promise.resolve('result' as T);
+ },
+ };
+}
+
+describe('createCallback', () => {
+ test('forwards every argument that has a shape to Invoke', async () => {
+ const callbackReference = createCallbackReference();
+ const callback = createCallback(callbackReference, '[null, null, null]');
+
+ const result = await callback('a', 2, { three: 3 });
+
+ expect(result).toBe('result');
+ expect(callbackReference.calls).toEqual([['Invoke', 'a', 2, { three: 3 }]]);
+ });
+
+ test('drops arguments beyond the shapes and sends null for missing ones', async () => {
+ const callbackReference = createCallbackReference();
+
+ await createCallback(callbackReference, '[null]')('a', 'b');
+ await createCallback(callbackReference, '[null, null]')('a');
+
+ expect(callbackReference.calls).toEqual([['Invoke', 'a'], ['Invoke', 'a', undefined]]);
+ expect(JSON.stringify(callbackReference.calls[1])).toBe('["Invoke","a",null]');
+ });
+
+ test('copies only the shaped properties of an event', async () => {
+ const callbackReference = createCallbackReference();
+ const event = new Event('change');
+ Object.defineProperty(event, 'changed', { get: () => [{ name: 'a', value: '1' }] });
+ Object.defineProperty(event, 'deleted', { get: () => [{ name: 'b' }] });
+
+ await createCallback(callbackReference, '[{"changed":null,"deleted":null}]')(event);
+
+ expect(JSON.stringify(callbackReference.calls[0])).toBe('["Invoke",{"changed":[{"name":"a","value":"1"}],"deleted":[{"name":"b"}]}]');
+ });
+});
+
+describe('toDotNet', () => {
+ test('copies primitives, plain objects, and arrays', () => {
+ expect(toDotNet(null, null)).toBeNull();
+ expect(toDotNet('text', null)).toBe('text');
+ expect(toDotNet({ a: [1, { b: true }] }, null)).toEqual({ a: [1, { b: true }] });
+ });
+
+ test('sends a marker with the type name for objects that are not plain', () => {
+ const value = toDotNet({ port: new BrowserObject(), dates: [new Date(0)], callback: () => 1 }, null);
+
+ expect(value).toEqual({
+ port: { __unsupported: 'BrowserObject' },
+ dates: [{ __unsupported: 'Date' }],
+ callback: { __unsupported: 'Function' },
+ });
+ });
+
+ test('applies nested shapes and applies a shape to each array item', () => {
+ const shape = { name: null, child: { name: null } };
+
+ expect(toDotNet(new BrowserObject(), shape)).toEqual({ name: 'browser', child: null });
+ expect(toDotNet([new BrowserObject()], { name: null })).toEqual([{ name: 'browser' }]);
+ });
+
+ test('sends the name of a known global', () => {
+ const area = new BrowserObject();
+ const otherArea = new BrowserObject();
+ (globalThis as Record).knownArea = area;
+ const shape = { $known: ['missingArea', 'knownArea'] };
+
+ expect(toDotNet(area, shape)).toBe('knownArea');
+ expect(toDotNet(null, shape)).toBeNull();
+ expect(toDotNet(otherArea, shape)).toEqual({ __unsupported: 'BrowserObject' });
+ expect(toDotNet({ storageArea: area }, { storageArea: shape })).toEqual({ storageArea: 'knownArea' });
+ });
+
+ test('sends an empty object for an empty shape', () => {
+ expect(toDotNet(new BrowserObject(), {})).toEqual({});
+ expect(toDotNet(undefined, {})).toBeNull();
+ });
+});
diff --git a/src/Components/Platform/src/js/tsconfig.json b/src/Components/Platform/src/js/tsconfig.json
new file mode 100644
index 000000000000..3533776aa768
--- /dev/null
+++ b/src/Components/Platform/src/js/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "../../../Shared.JS/tsconfig.json",
+ "exclude": ["test", "dist", "node_modules"]
+}
diff --git a/src/Components/Platform/test/BrowserJSRuntime.cs b/src/Components/Platform/test/BrowserJSRuntime.cs
new file mode 100644
index 000000000000..b5da1763e786
--- /dev/null
+++ b/src/Components/Platform/test/BrowserJSRuntime.cs
@@ -0,0 +1,127 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#nullable enable
+
+using System.Text.Json;
+using Microsoft.JSInterop;
+using Microsoft.JSInterop.Infrastructure;
+
+namespace Microsoft.AspNetCore.Components.Platform.Tests;
+
+// Runs the real JSRuntime serializer and dispatcher, and plays the browser side of each call.
+internal sealed class BrowserJSRuntime : JSRuntime
+{
+ private readonly Dictionary> _pendingDotNetCalls = [];
+ private readonly HashSet _identifiersToFail = [];
+ private readonly HashSet _identifiersToHold = [];
+ private readonly List<(string Identifier, long AsyncHandle, string Result)> _heldCalls = [];
+ private long _nextObjectId = 1;
+ private long _nextCallId = 1;
+
+ public List Calls { get; } = [];
+
+ // Completes calls from a thread pool thread, as a transport that does not use the renderer's dispatcher does.
+ public bool CompleteOnThreadPool { get; init; }
+
+ public IEnumerable CallsTo(string identifier) => Calls.Where(call => call.Identifier == identifier);
+
+ // Makes the next call to the identifier fail, as a browser exception or a timeout would.
+ public void FailNextCallTo(string identifier) => _identifiersToFail.Add(identifier);
+
+ // Keeps the calls to the identifier pending until ReleaseHeldCalls.
+ public void HoldCallsTo(string identifier) => _identifiersToHold.Add(identifier);
+
+ public void ReleaseHeldCalls(string identifier, bool succeeded = true)
+ {
+ _identifiersToHold.Remove(identifier);
+
+ foreach (var held in _heldCalls.Where(held => held.Identifier == identifier).ToArray())
+ {
+ _heldCalls.Remove(held);
+ Complete(held.AsyncHandle, succeeded, succeeded ? held.Result : $"\"{identifier} failed.\"");
+ }
+ }
+
+ // Calls the Invoke method of the DotNetObjectReference that the last createCallback call received.
+ public Task InvokeLastCallbackAsync(string argsJson)
+ => InvokeCallbackAsync(CallsTo("createCallback").Count() - 1, argsJson);
+
+ // Calls the Invoke method of the DotNetObjectReference that the createCallback call at the index received.
+ public async Task InvokeCallbackAsync(int index, string argsJson)
+ {
+ var createCallback = CallsTo("createCallback").ElementAt(index);
+ using var args = JsonDocument.Parse(createCallback.ArgsJson);
+ var dotNetObjectId = args.RootElement[0].GetProperty("__dotNetObject").GetInt64();
+ var callId = (_nextCallId++).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ var completion = new TaskCompletionSource();
+ _pendingDotNetCalls[callId] = completion;
+
+ DotNetDispatcher.BeginInvokeDotNet(this, new DotNetInvocationInfo(null, "Invoke", dotNetObjectId, callId), argsJson);
+
+ return await completion.Task;
+ }
+
+ protected override void BeginInvokeJS(in JSInvocationInfo invocationInfo)
+ {
+ Calls.Add(new BrowserCall(
+ invocationInfo.Identifier,
+ invocationInfo.CallType,
+ invocationInfo.TargetInstanceId,
+ invocationInfo.ArgsJson,
+ SynchronizationContext.Current));
+
+ if (invocationInfo.AsyncHandle == 0)
+ {
+ return;
+ }
+
+ if (_identifiersToFail.Remove(invocationInfo.Identifier))
+ {
+ Complete(invocationInfo.AsyncHandle, succeeded: false, $"\"{invocationInfo.Identifier} failed.\"");
+ return;
+ }
+
+ var result = invocationInfo.ResultType == JSCallResultType.JSObjectReference
+ ? $$"""{"__jsObjectId":{{_nextObjectId++}}}"""
+ : "null";
+
+ if (_identifiersToHold.Contains(invocationInfo.Identifier))
+ {
+ _heldCalls.Add((invocationInfo.Identifier, invocationInfo.AsyncHandle, result));
+ return;
+ }
+
+ Complete(invocationInfo.AsyncHandle, succeeded: true, result);
+ }
+
+ protected override void BeginInvokeJS(long taskId, string identifier, string? argsJson, JSCallResultType resultType, long targetInstanceId)
+ => throw new NotSupportedException();
+
+ protected override void EndInvokeDotNet(DotNetInvocationInfo invocationInfo, in DotNetInvocationResult invocationResult)
+ {
+ _pendingDotNetCalls.Remove(invocationInfo.CallId!, out var completion);
+ completion!.SetResult(invocationResult);
+ }
+
+ private void Complete(long asyncHandle, bool succeeded, string result)
+ {
+ var json = $"[{asyncHandle},{(succeeded ? "true" : "false")},{result}]";
+
+ if (CompleteOnThreadPool)
+ {
+ ThreadPool.QueueUserWorkItem(_ => DotNetDispatcher.EndInvokeJS(this, json));
+ }
+ else
+ {
+ DotNetDispatcher.EndInvokeJS(this, json);
+ }
+ }
+}
+
+internal sealed record BrowserCall(
+ string Identifier,
+ JSCallType CallType,
+ long TargetInstanceId,
+ string ArgsJson,
+ SynchronizationContext? Context);
diff --git a/src/Components/Platform/test/CookieStoreTest.cs b/src/Components/Platform/test/CookieStoreTest.cs
index 2f4adad071da..004e3e904551 100644
--- a/src/Components/Platform/test/CookieStoreTest.cs
+++ b/src/Components/Platform/test/CookieStoreTest.cs
@@ -4,7 +4,9 @@
#nullable enable
#pragma warning disable ASP0040 // Partitioned is experimental.
+using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using Microsoft.JSInterop.Infrastructure;
using Xunit;
@@ -223,6 +225,106 @@ public async Task ScopeDisposal_DoesNotWaitForPendingAcquisition()
Assert.False(jsRuntime.ObjectReference.Disposed);
}
+ [Fact]
+ public async Task AddEventListenerAsync_AddsAFunctionThatDeliversTheChangeEvent()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ CookieChangeEvent? received = null;
+
+ await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, changeEvent =>
+ {
+ received = changeEvent;
+ return Task.CompletedTask;
+ });
+ var result = await jsRuntime.InvokeLastCallbackAsync(
+ """[{"changed":[{"name":"a","value":"1"}],"deleted":[{"name":"b"}]}]""");
+
+ // The cookie store is object 1, the module is object 2, and the function is object 3.
+ using var createCallbackArgs = JsonDocument.Parse(Assert.Single(jsRuntime.CallsTo("createCallback")).ArgsJson);
+ Assert.Equal("""[{"changed":null,"deleted":null}]""", createCallbackArgs.RootElement[1].GetString());
+ var addition = Assert.Single(jsRuntime.CallsTo("addEventListener"));
+ Assert.Equal((JSCallType.FunctionCall, 1, """["change",{"__jsObjectId":3}]"""), (addition.CallType, addition.TargetInstanceId, addition.ArgsJson));
+ Assert.True(result.Success, result.Exception?.ToString());
+ Assert.Equal(("a", "1"), (Assert.Single(received!.Changed).Name, received.Changed[0].Value));
+ Assert.Equal(("b", null), (Assert.Single(received.Deleted).Name, received.Deleted[0].Value));
+ }
+
+ [Fact]
+ public async Task AddEventListenerAsync_KeepsListenersIndependent()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ var calls = new List();
+
+ var first = await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => { calls.Add("first"); return Task.CompletedTask; });
+ await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => { calls.Add("second"); return Task.CompletedTask; });
+ await jsRuntime.InvokeCallbackAsync(0, EmptyChange);
+ await jsRuntime.InvokeCallbackAsync(1, EmptyChange);
+ await first.DisposeAsync();
+ await first.DisposeAsync();
+ var afterRemoval = await jsRuntime.InvokeCallbackAsync(0, EmptyChange);
+ await jsRuntime.InvokeCallbackAsync(1, EmptyChange);
+
+ // The module is object 2, and the functions are objects 3 and 4.
+ Assert.Equal(["first", "second", "second"], calls);
+ Assert.False(afterRemoval.Success);
+ Assert.Single(jsRuntime.CallsTo("import"));
+ var removal = Assert.Single(jsRuntime.CallsTo("removeEventListener"));
+ Assert.Equal((1, """["change",{"__jsObjectId":3}]"""), (removal.TargetInstanceId, removal.ArgsJson));
+ Assert.Equal(["[3]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ }
+
+ [Fact]
+ public async Task AddEventListenerAsync_LogsAnExceptionFromTheListener()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var loggerFactory = new RecordingLoggerFactory();
+ await using var provider = CreateServiceProvider(jsRuntime, loggerFactory);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+
+ await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => throw new InvalidOperationException("Listener failed."));
+ var result = await jsRuntime.InvokeLastCallbackAsync(EmptyChange);
+
+ Assert.True(result.Success, result.Exception?.ToString());
+ var entry = Assert.Single(loggerFactory.Entries);
+ Assert.Equal((LogLevel.Error, "ListenerThrew"), (entry.Level, entry.EventId.Name));
+ Assert.Equal("Listener failed.", Assert.IsType(entry.Exception).Message);
+ }
+
+ [Fact]
+ public async Task AddEventListenerAsync_ThrowsForNullArguments()
+ {
+ await using var provider = CreateServiceProvider(new BrowserJSRuntime());
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+
+ await Assert.ThrowsAsync(
+ () => cookieStore.AddEventListenerAsync(null!, _ => Task.CompletedTask).AsTask());
+ await Assert.ThrowsAsync(
+ () => cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, null!).AsTask());
+ }
+
+ [Fact]
+ public async Task ScopeDisposal_RemovesListeners()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ var listener = await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask);
+
+ await provider.DisposeAsync();
+ await listener.DisposeAsync();
+
+ Assert.Single(jsRuntime.CallsTo("removeEventListener"));
+ Assert.Equal(
+ ["[3]", "[1]", "[2]"],
+ jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ await Assert.ThrowsAsync(
+ () => cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask).AsTask());
+ }
+
// A mock IJSRuntime records arguments before serialization, so the tests below check the JSON the browser receives.
[Fact]
public async Task SetAsync_SendsCookieInitWithoutNullMembers()
@@ -343,12 +445,19 @@ public async Task GetAsync_ReadsTheCookieOrNull()
Assert.Null(missing);
}
- private static ServiceProvider CreateServiceProvider(IJSRuntime jsRuntime)
+ private const string EmptyChange = """[{"changed":[],"deleted":[]}]""";
+
+ private static ServiceProvider CreateServiceProvider(IJSRuntime jsRuntime, ILoggerFactory? loggerFactory = null)
{
var services = new ServiceCollection();
services.AddSingleton(jsRuntime);
services.AddBrowserPlatform();
+ if (loggerFactory is not null)
+ {
+ services.AddSingleton(loggerFactory);
+ }
+
return services.BuildServiceProvider();
}
diff --git a/src/Components/Platform/test/EventListenerLifecycleTest.cs b/src/Components/Platform/test/EventListenerLifecycleTest.cs
new file mode 100644
index 000000000000..1b8a3c29faf8
--- /dev/null
+++ b/src/Components/Platform/test/EventListenerLifecycleTest.cs
@@ -0,0 +1,265 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#nullable enable
+
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Microsoft.JSInterop;
+using Xunit;
+
+namespace Microsoft.AspNetCore.Components.Platform.Tests;
+
+public class EventListenerLifecycleTest
+{
+ private const string EmptyChange = """[{"changed":[],"deleted":[]}]""";
+
+ [Fact]
+ public async Task WindowAddEventListenerAsync_StaysOnTheRendererSynchronizationContext()
+ {
+ var jsRuntime = new BrowserJSRuntime { CompleteOnThreadPool = true };
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var window = provider.GetRequiredService().Window;
+ var dispatcher = Dispatcher.CreateDefault();
+ var context = await dispatcher.InvokeAsync(() => SynchronizationContext.Current);
+
+ await dispatcher.InvokeAsync(async () => await window.AddEventListenerAsync(Window.StorageEvent, _ => Task.CompletedTask));
+
+ Assert.NotNull(context);
+ Assert.Equal(["window", "import", "createCallback", "addEventListener"], jsRuntime.Calls.Select(call => call.Identifier));
+ Assert.All(jsRuntime.Calls, call => Assert.Same(context, call.Context));
+ }
+
+ [Fact]
+ public async Task CookieStoreAddEventListenerAsync_StaysOnTheRendererSynchronizationContext()
+ {
+ var jsRuntime = new BrowserJSRuntime { CompleteOnThreadPool = true };
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ var dispatcher = Dispatcher.CreateDefault();
+ var context = await dispatcher.InvokeAsync(() => SynchronizationContext.Current);
+
+ await dispatcher.InvokeAsync(async () => await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask));
+
+ Assert.NotNull(context);
+ Assert.Equal(["cookieStore", "import", "createCallback", "addEventListener"], jsRuntime.Calls.Select(call => call.Identifier));
+ Assert.All(jsRuntime.Calls, call => Assert.Same(context, call.Context));
+ }
+
+ [Fact]
+ public async Task ScopeDisposal_RemovesTheOtherListenersWhenOneRemovalFails()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var loggerFactory = new RecordingLoggerFactory();
+ var provider = CreateServiceProvider(jsRuntime, loggerFactory);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask);
+ await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask);
+ jsRuntime.FailNextCallTo("removeEventListener");
+
+ await provider.DisposeAsync();
+
+ // The cookie store is object 1, the module is object 2, and the functions are objects 3 and 4.
+ Assert.Equal(2, jsRuntime.CallsTo("removeEventListener").Count());
+ Assert.Equal(
+ ["[3]", "[4]", "[1]", "[2]"],
+ jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ Assert.False((await jsRuntime.InvokeCallbackAsync(0, EmptyChange)).Success);
+ Assert.False((await jsRuntime.InvokeCallbackAsync(1, EmptyChange)).Success);
+ var entry = Assert.Single(loggerFactory.Entries);
+ Assert.Equal((LogLevel.Warning, "ListenerRemovalFailed"), (entry.Level, entry.EventId.Name));
+ Assert.Contains("removeEventListener", Assert.IsType(entry.Exception).Message);
+ }
+
+ [Fact]
+ public async Task DisposeAsync_ReleasesTheFunctionAndTheCallbackWhenTheRemovalFails()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ var listener = await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask);
+ jsRuntime.FailNextCallTo("removeEventListener");
+
+ var exception = await Assert.ThrowsAsync(() => listener.DisposeAsync().AsTask());
+ await listener.DisposeAsync();
+
+ // The function is object 3.
+ Assert.Contains("removeEventListener", exception.Message);
+ Assert.Single(jsRuntime.CallsTo("removeEventListener"));
+ Assert.Equal(["[3]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ Assert.False((await jsRuntime.InvokeLastCallbackAsync(EmptyChange)).Success);
+ }
+
+ [Fact]
+ public async Task AddEventListenerAsync_ThrowsTheOriginalExceptionWhenTheCleanupAlsoFails()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var loggerFactory = new RecordingLoggerFactory();
+ await using var provider = CreateServiceProvider(jsRuntime, loggerFactory);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ jsRuntime.FailNextCallTo("addEventListener");
+ jsRuntime.FailNextCallTo("removeEventListener");
+
+ var exception = await Assert.ThrowsAsync(
+ () => cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask).AsTask());
+
+ // The function is object 3.
+ Assert.Contains("addEventListener", exception.Message);
+ Assert.Equal(["[3]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ Assert.False((await jsRuntime.InvokeLastCallbackAsync(EmptyChange)).Success);
+ var entry = Assert.Single(loggerFactory.Entries);
+ Assert.Equal("ListenerRemovalFailed", entry.EventId.Name);
+ }
+
+ [Fact]
+ public async Task ScopeDisposal_DuringTheModuleImport_ReleasesTheModuleThatArrivesLater()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ jsRuntime.HoldCallsTo("import");
+
+ var adding = cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask).AsTask();
+ await provider.DisposeAsync();
+ jsRuntime.ReleaseHeldCalls("import");
+
+ // The cookie store is object 1, and the module is object 2.
+ await Assert.ThrowsAsync(() => adding);
+ Assert.Empty(jsRuntime.CallsTo("createCallback"));
+ Assert.Empty(jsRuntime.CallsTo("addEventListener"));
+ Assert.Equal(["[1]", "[2]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ }
+
+ [Fact]
+ public async Task AddEventListenerAsync_WithACanceledToken_ThrowsWithoutCallingTheBrowser()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var window = provider.GetRequiredService().Window;
+ using var cts = new CancellationTokenSource();
+ cts.Cancel();
+
+ var exception = await Assert.ThrowsAnyAsync(
+ () => window.AddEventListenerAsync(Window.StorageEvent, _ => Task.CompletedTask, cts.Token).AsTask());
+
+ Assert.Equal(cts.Token, exception.CancellationToken);
+ Assert.Empty(jsRuntime.Calls);
+ }
+
+ [Fact]
+ public async Task CancelingTheToken_StopsTheListenerAndRemovesItOnTheRendererSynchronizationContext()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ var dispatcher = Dispatcher.CreateDefault();
+ var context = await dispatcher.InvokeAsync(() => SynchronizationContext.Current);
+ using var cts = new CancellationTokenSource();
+ var calls = 0;
+ await dispatcher.InvokeAsync(async () => await cookieStore.AddEventListenerAsync(
+ CookieStore.ChangeEvent,
+ _ => { calls++; return Task.CompletedTask; },
+ cts.Token));
+
+ // A component cancels on the renderer's context, which the removal is posted back to.
+ await dispatcher.InvokeAsync(() => cts.Cancel()).WaitAsync(TimeSpan.FromSeconds(10));
+ await jsRuntime.InvokeLastCallbackAsync(EmptyChange);
+ await WaitForAsync(dispatcher, () => jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Any());
+
+ // The function is object 3.
+ Assert.Equal(0, calls);
+ Assert.Same(context, Assert.Single(jsRuntime.CallsTo("removeEventListener")).Context);
+ Assert.Equal(["[3]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ }
+
+ [Fact]
+ public async Task CancelingTheTokenDuringTheModuleImport_ReleasesTheFunctionAndThrows()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ using var cts = new CancellationTokenSource();
+ jsRuntime.HoldCallsTo("import");
+
+ var adding = cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask, cts.Token).AsTask();
+ cts.Cancel();
+ jsRuntime.ReleaseHeldCalls("import");
+
+ // The function is object 3.
+ var exception = await Assert.ThrowsAnyAsync(() => adding);
+ Assert.Equal(cts.Token, exception.CancellationToken);
+ Assert.Empty(jsRuntime.CallsTo("addEventListener"));
+ Assert.Equal(["[3]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ Assert.False((await jsRuntime.InvokeLastCallbackAsync(EmptyChange)).Success);
+ }
+
+ [Fact]
+ public async Task CancelingTheTokenDuringAddEventListener_RemovesTheListenerAndThrows()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ using var cts = new CancellationTokenSource();
+ var calls = 0;
+ jsRuntime.HoldCallsTo("addEventListener");
+
+ var adding = cookieStore.AddEventListenerAsync(
+ CookieStore.ChangeEvent,
+ _ => { calls++; return Task.CompletedTask; },
+ cts.Token).AsTask();
+ cts.Cancel();
+ // An event that the browser sends before the removal reaches it.
+ await jsRuntime.InvokeLastCallbackAsync(EmptyChange);
+ jsRuntime.ReleaseHeldCalls("addEventListener");
+
+ // The function is object 3.
+ var exception = await Assert.ThrowsAnyAsync(() => adding);
+ Assert.Equal(cts.Token, exception.CancellationToken);
+ Assert.Equal(0, calls);
+ Assert.Single(jsRuntime.CallsTo("removeEventListener"));
+ Assert.Equal(["[3]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ Assert.False((await jsRuntime.InvokeLastCallbackAsync(EmptyChange)).Success);
+ }
+
+ [Fact]
+ public async Task AddEventListenerAsync_ReportsTheCancellationWhenTheAdditionFailsAfterIt()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var cookieStore = provider.GetRequiredService().Window.CookieStore;
+ using var cts = new CancellationTokenSource();
+ jsRuntime.HoldCallsTo("addEventListener");
+
+ var adding = cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask, cts.Token).AsTask();
+ cts.Cancel();
+ jsRuntime.ReleaseHeldCalls("addEventListener", succeeded: false);
+
+ var exception = await Assert.ThrowsAnyAsync(() => adding);
+ Assert.Equal(cts.Token, exception.CancellationToken);
+ Assert.Contains("addEventListener", Assert.IsType(exception.InnerException).Message);
+ }
+
+ private static async Task WaitForAsync(Dispatcher dispatcher, Func condition)
+ {
+ var timeout = Task.Delay(TimeSpan.FromSeconds(10));
+ while (!await dispatcher.InvokeAsync(condition))
+ {
+ Assert.False(timeout.IsCompleted, "The condition was not met in time.");
+ await Task.Delay(10);
+ }
+ }
+
+ private static ServiceProvider CreateServiceProvider(IJSRuntime jsRuntime, ILoggerFactory? loggerFactory = null)
+ {
+ var services = new ServiceCollection();
+ services.AddSingleton(jsRuntime);
+ services.AddBrowserPlatform();
+
+ if (loggerFactory is not null)
+ {
+ services.AddSingleton(loggerFactory);
+ }
+
+ return services.BuildServiceProvider();
+ }
+}
diff --git a/src/Components/Platform/test/JSCallbackTest.cs b/src/Components/Platform/test/JSCallbackTest.cs
new file mode 100644
index 000000000000..029bdd200324
--- /dev/null
+++ b/src/Components/Platform/test/JSCallbackTest.cs
@@ -0,0 +1,114 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#nullable enable
+
+using Microsoft.JSInterop;
+using Xunit;
+
+namespace Microsoft.AspNetCore.Components.Platform.Tests;
+
+public class JSCallbackTest
+{
+ [Fact]
+ public async Task CreateAsync_ImportsTheModuleOnceAndPassesTheShapes()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var factory = new JSCallbackFactory(jsRuntime);
+
+ await factory.CreateAsync(new JSCallback(), "[null]");
+ await factory.CreateAsync(new JSCallback(), "[{}]");
+
+ Assert.Equal(
+ ["""["./_content/Microsoft.AspNetCore.Components.Platform/Microsoft.AspNetCore.Components.Platform.js"]"""],
+ jsRuntime.CallsTo("import").Select(call => call.ArgsJson));
+ Assert.Equal(
+ ["""[{"__dotNetObject":1},"[null]"]""", """[{"__dotNetObject":2},"[{}]"]"""],
+ jsRuntime.CallsTo("createCallback").Select(call => call.ArgsJson));
+ }
+
+ [Fact]
+ public async Task Invoke_PassesTheArgumentToTheHandler()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var factory = new JSCallbackFactory(jsRuntime);
+ var callback = new JSCallback();
+ CookieListItem? received = null;
+ callback.Handler = cookie =>
+ {
+ received = cookie;
+ return Task.CompletedTask;
+ };
+ await factory.CreateAsync(callback, "[null]");
+
+ var result = await jsRuntime.InvokeLastCallbackAsync("""[{"name":"a","value":"1"}]""");
+
+ Assert.True(result.Success, result.Exception?.ToString());
+ Assert.Equal(("a", "1"), (received?.Name, received?.Value));
+ }
+
+ [Fact]
+ public async Task Invoke_WaitsForTheHandler()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var factory = new JSCallbackFactory(jsRuntime);
+ var handlerCompletion = new TaskCompletionSource();
+ var callback = new JSCallback { Handler = _ => handlerCompletion.Task };
+ await factory.CreateAsync(callback, "[null]");
+
+ var invocation = jsRuntime.InvokeLastCallbackAsync("""["text"]""");
+ Assert.False(invocation.IsCompleted);
+ handlerCompletion.SetResult();
+
+ Assert.True((await invocation).Success);
+ }
+
+ [Fact]
+ public async Task Invoke_SucceedsWithoutAHandler()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var factory = new JSCallbackFactory(jsRuntime);
+ await factory.CreateAsync(new JSCallback(), "[null]");
+
+ var result = await jsRuntime.InvokeLastCallbackAsync("""["text"]""");
+
+ Assert.True(result.Success);
+ }
+
+ [Fact]
+ public async Task CreatedFunctions_StayValidUntilTheCallerReleasesThem()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var factory = new JSCallbackFactory(jsRuntime);
+ var callback = new JSCallback { Handler = _ => Task.CompletedTask };
+ var (_, callbackReference) = await factory.CreateAsync(callback, "[null]");
+
+ await ((IInternalAsyncDisposal)factory).InternalDisposeAsync();
+ var beforeRelease = await jsRuntime.InvokeLastCallbackAsync("""["text"]""");
+ callbackReference.Dispose();
+ var afterRelease = await jsRuntime.InvokeLastCallbackAsync("""["text"]""");
+
+ // The module is object 1, and the factory releases only the module.
+ Assert.Equal(["[1]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ Assert.True(beforeRelease.Success);
+ Assert.False(afterRelease.Success);
+ await Assert.ThrowsAsync(() => factory.CreateAsync(callback, "[null]"));
+ }
+
+ [Fact]
+ public async Task CreateAsync_ReleasesTheModuleThatArrivesAfterDisposal()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var factory = new JSCallbackFactory(jsRuntime);
+ jsRuntime.HoldCallsTo("import");
+
+ var creation = factory.CreateAsync(new JSCallback(), "[null]");
+ await ((IInternalAsyncDisposal)factory).InternalDisposeAsync();
+ jsRuntime.ReleaseHeldCalls("import");
+
+ // The module is object 1.
+ await Assert.ThrowsAsync(() => creation);
+ Assert.Empty(jsRuntime.CallsTo("createCallback"));
+ Assert.Equal(["[1]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ }
+}
diff --git a/src/Components/Platform/test/Microsoft.AspNetCore.Components.Platform.Tests.csproj b/src/Components/Platform/test/Microsoft.AspNetCore.Components.Platform.Tests.csproj
index d88ba18b0083..499cf83f316a 100644
--- a/src/Components/Platform/test/Microsoft.AspNetCore.Components.Platform.Tests.csproj
+++ b/src/Components/Platform/test/Microsoft.AspNetCore.Components.Platform.Tests.csproj
@@ -7,6 +7,7 @@
+
diff --git a/src/Components/Platform/test/PublicApiTest.cs b/src/Components/Platform/test/PublicApiTest.cs
index e76bece60946..7a86c3be4ee0 100644
--- a/src/Components/Platform/test/PublicApiTest.cs
+++ b/src/Components/Platform/test/PublicApiTest.cs
@@ -49,6 +49,7 @@ public void LiveBrowserObjectMethods_AreAsynchronous()
typeof(CookieStore),
typeof(Url),
typeof(UrlSearchParams),
+ typeof(Window),
];
var synchronousMethods = liveBrowserObjectTypes
diff --git a/src/Components/Platform/test/RecordingLoggerFactory.cs b/src/Components/Platform/test/RecordingLoggerFactory.cs
new file mode 100644
index 000000000000..ad13f3ee23ad
--- /dev/null
+++ b/src/Components/Platform/test/RecordingLoggerFactory.cs
@@ -0,0 +1,30 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+#nullable enable
+
+using Microsoft.Extensions.Logging;
+
+namespace Microsoft.AspNetCore.Components.Platform.Tests;
+
+internal sealed record LogEntry(LogLevel Level, EventId EventId, Exception? Exception);
+
+internal sealed class RecordingLoggerFactory : ILoggerFactory, ILogger
+{
+ public List Entries { get; } = [];
+
+ public ILogger CreateLogger(string categoryName) => this;
+
+ public void AddProvider(ILoggerProvider provider) => throw new NotSupportedException();
+
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => true;
+
+ public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)
+ => Entries.Add(new LogEntry(logLevel, eventId, exception));
+
+ public void Dispose()
+ {
+ }
+}
diff --git a/src/Components/Platform/test/StorageTest.cs b/src/Components/Platform/test/StorageTest.cs
index 21808dbda4ff..c1d2527c0e68 100644
--- a/src/Components/Platform/test/StorageTest.cs
+++ b/src/Components/Platform/test/StorageTest.cs
@@ -3,8 +3,10 @@
#nullable enable
+using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.JSInterop;
+using Microsoft.JSInterop.Infrastructure;
using Xunit;
namespace Microsoft.AspNetCore.Components.Platform.Tests;
@@ -141,6 +143,56 @@ public async Task ScopeDisposal_BeforeUseDoesNotAcquireReference()
Assert.Equal(0, jsRuntime.GetValueCallCount);
}
+ [Fact]
+ public async Task StorageEvent_DeliversTheExistingStorageAsTheStorageArea()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ await using var provider = CreateServiceProvider(jsRuntime);
+ var window = provider.GetRequiredService().Window;
+ var received = new List();
+
+ await window.AddEventListenerAsync(Window.StorageEvent, storageEvent =>
+ {
+ received.Add(storageEvent);
+ return Task.CompletedTask;
+ });
+ await jsRuntime.InvokeLastCallbackAsync(
+ """[{"key":"k","oldValue":null,"newValue":"v","url":"https://localhost/","storageArea":"localStorage"}]""");
+ await jsRuntime.InvokeLastCallbackAsync(
+ """[{"key":null,"oldValue":null,"newValue":null,"url":"https://localhost/","storageArea":"sessionStorage"}]""");
+
+ // The window is object 1, the module is object 2, and the function is object 3.
+ Assert.Equal(JSCallType.GetValue, Assert.Single(jsRuntime.CallsTo("window")).CallType);
+ using var createCallbackArgs = JsonDocument.Parse(Assert.Single(jsRuntime.CallsTo("createCallback")).ArgsJson);
+ Assert.Contains("""
+ "storageArea":{"$known":["localStorage","sessionStorage"]}
+ """, createCallbackArgs.RootElement[1].GetString());
+ var addition = Assert.Single(jsRuntime.CallsTo("addEventListener"));
+ Assert.Equal((1, """["storage",{"__jsObjectId":3}]"""), (addition.TargetInstanceId, addition.ArgsJson));
+ Assert.Equal(("k", null, "v", "https://localhost/"), (received[0].Key, received[0].OldValue, received[0].NewValue, received[0].Url));
+ Assert.Same(window.LocalStorage, received[0].StorageArea);
+ Assert.Null(received[1].Key);
+ Assert.Same(window.SessionStorage, received[1].StorageArea);
+ }
+
+ [Fact]
+ public async Task ScopeDisposal_RemovesWindowListeners()
+ {
+ var jsRuntime = new BrowserJSRuntime();
+ var provider = CreateServiceProvider(jsRuntime);
+ var window = provider.GetRequiredService().Window;
+ await window.AddEventListenerAsync(Window.StorageEvent, _ => Task.CompletedTask);
+
+ await provider.DisposeAsync();
+
+ Assert.Equal(1, Assert.Single(jsRuntime.CallsTo("removeEventListener")).TargetInstanceId);
+ Assert.Equal(
+ ["[3]", "[1]", "[2]"],
+ jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson));
+ await Assert.ThrowsAsync(
+ () => window.AddEventListenerAsync(Window.StorageEvent, _ => Task.CompletedTask).AsTask());
+ }
+
private static ServiceProvider CreateServiceProvider(IJSRuntime jsRuntime)
{
var services = new ServiceCollection();
diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor
index 9116a5ce61f1..9185d632d831 100644
--- a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor
+++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor
@@ -1,3 +1,4 @@
+@implements IAsyncDisposable
@using Microsoft.JSInterop
@inject Microsoft.AspNetCore.Components.Platform.IBrowserPlatform Browser
@inject NavigationManager Navigation
@@ -29,7 +30,15 @@
+
+
+
+
+
+
@result
+
@change
+
@secondChange
@code {
// A path other than the page path shows that the Path member reaches the browser.
@@ -39,6 +48,11 @@
private string value = "initial";
private string result = "No operation has run.";
private int runCount;
+ private string change = "No change has been reported.";
+ private string secondChange = "No change has been reported.";
+ private IAsyncDisposable? listener;
+ // The second listener is removed by its token, so the component keeps no handle for it.
+ private readonly CancellationTokenSource secondListenerCancellation = new();
private Task SetAsync() => RunAsync("Set", async () =>
{
@@ -151,6 +165,69 @@
runCount++;
}
+ private Task WatchChangesAsync() => RunAsync("Watch changes", async () =>
+ {
+ listener = await Browser.Window.CookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, OnCookieChangeAsync);
+ return "added";
+ });
+
+ private Task WatchChangesWithSecondListenerAsync() => RunAsync("Watch changes with a second listener", async () =>
+ {
+ await Browser.Window.CookieStore.AddEventListenerAsync(
+ CookieStore.ChangeEvent,
+ changeEvent =>
+ {
+ secondChange = Describe(changeEvent);
+ StateHasChanged();
+ return Task.CompletedTask;
+ },
+ secondListenerCancellation.Token);
+ return "added";
+ });
+
+ private Task UnwatchChangesAsync() => RunAsync("Stop watching changes", async () =>
+ {
+ if (listener is not null)
+ {
+ await listener.DisposeAsync();
+ }
+
+ return "removed";
+ });
+
+ private Task CancelSecondListenerAsync() => RunAsync("Cancel the second listener", () =>
+ {
+ secondListenerCancellation.Cancel();
+ return Task.FromResult("canceled");
+ });
+
+ // The listener runs on the renderer's dispatcher, so StateHasChanged needs no InvokeAsync.
+ private Task OnCookieChangeAsync(CookieChangeEvent changeEvent)
+ {
+ change = Describe(changeEvent);
+ StateHasChanged();
+ return Task.CompletedTask;
+ }
+
+ private static string Describe(CookieChangeEvent changeEvent)
+ => string.Join(
+ "; ",
+ [
+ .. changeEvent.Changed.Select(cookie => $"Changed: {cookie.Name}={cookie.Value}"),
+ .. changeEvent.Deleted.Select(cookie => $"Deleted: {cookie.Name}"),
+ ]);
+
+ public async ValueTask DisposeAsync()
+ {
+ if (listener is not null)
+ {
+ await listener.DisposeAsync();
+ }
+
+ secondListenerCancellation.Cancel();
+ secondListenerCancellation.Dispose();
+ }
+
private static string Format(CookieListItem? cookie)
=> cookie is null ? "Cookie is missing." : $"Found: {cookie.Name}={cookie.Value}";
diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/MessageEventDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/MessageEventDemo.razor
new file mode 100644
index 000000000000..7c2d9394dadd
--- /dev/null
+++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/MessageEventDemo.razor
@@ -0,0 +1,45 @@
+@using System.Text.Json
+@implements IAsyncDisposable
+@inject IBrowserPlatform Browser
+
+
Message event data
+
+
+
@result
+
+@code {
+ // A test-only key built with the internal helper. Its shape copies "data", which can hold any value, whole.
+ private static readonly EventType MessageEvent =
+ EventTypes.Create("message", """[{"data":null}]""");
+
+ private string result = "No message has been reported.";
+ private int run;
+ private IAsyncDisposable? listener;
+
+ private async Task ListenAsync()
+ {
+ listener = await Browser.Window.AddEventListenerAsync(MessageEvent, OnMessageAsync);
+ result = "Listening.";
+ }
+
+ private Task OnMessageAsync(MessageData e)
+ {
+ result = e.Data.GetRawText();
+ run++;
+ StateHasChanged();
+ return Task.CompletedTask;
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ if (listener is not null)
+ {
+ await listener.DisposeAsync();
+ }
+ }
+
+ public sealed class MessageData
+ {
+ public JsonElement Data { get; set; }
+ }
+}
diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/StorageDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/StorageDemo.razor
index a31c04e7e15d..13c90735e32d 100644
--- a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/StorageDemo.razor
+++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/StorageDemo.razor
@@ -1,3 +1,4 @@
+@implements IAsyncDisposable
@inject Microsoft.AspNetCore.Components.Platform.IBrowserPlatform Browser
Web Storage
@@ -7,12 +8,16 @@
+
@result
+
@storageEvent
@code {
private const string StorageKey = "components-platform-e2e";
private string value = "initial";
private string result = "No operation has run.";
+ private string storageEvent = "No storage event has been reported.";
+ private IAsyncDisposable? listener;
private async Task SaveAsync()
{
@@ -32,4 +37,29 @@
value = string.Empty;
result = "Value removed.";
}
+
+ private async Task WatchAsync()
+ {
+ listener = await Browser.Window.AddEventListenerAsync(Window.StorageEvent, OnStorageAsync);
+ result = "Watching storage events.";
+ }
+
+ private Task OnStorageAsync(StorageEvent e)
+ {
+ // Comparing with the existing projections shows that StorageArea keeps their identity.
+ var area = e.StorageArea == Browser.Window.LocalStorage ? "localStorage"
+ : e.StorageArea == Browser.Window.SessionStorage ? "sessionStorage"
+ : "unknown storage";
+ storageEvent = $"{e.Key}: {e.OldValue ?? "(none)"} -> {e.NewValue ?? "(none)"} in {area}";
+ StateHasChanged();
+ return Task.CompletedTask;
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ if (listener is not null)
+ {
+ await listener.DisposeAsync();
+ }
+ }
}
diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Pages/MessageEventWebAssembly.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Pages/MessageEventWebAssembly.razor
new file mode 100644
index 000000000000..0b52d0678fd9
--- /dev/null
+++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Pages/MessageEventWebAssembly.razor
@@ -0,0 +1,4 @@
+@page "/message-event-wasm"
+@rendermode InteractiveWebAssembly
+
+
diff --git a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs
index b348724ea7e5..4c8c05405423 100644
--- a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs
+++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs
@@ -156,6 +156,59 @@ public async Task CookieStore_ThrowsNotSupportedExceptionWithoutTheBrowserApi()
}
}
+ [TestMethod]
+ public async Task CookieStore_ReportsChangesToEachListener()
+ {
+ foreach (var path in CookieStorePaths)
+ {
+ await NavigateAsync(path, "#set-cookie");
+
+ var name = path == "/cookiestore-server" ? "server-watched" : "wasm-watched";
+ await _page.Locator("#cookie-name").FillAsync(name);
+ await _page.Locator("#cookie-value").FillAsync("value");
+ await RunAsync("#watch-cookie-changes", "Watch changes: added");
+ await RunAsync("#watch-cookie-changes-second", "Watch changes with a second listener: added");
+
+ await RunAsync("#set-cookie", $"Set: {name}");
+ await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync($"Changed: {name}=value");
+ await Expect(_page.Locator("#cookie-change-second")).ToHaveTextAsync($"Changed: {name}=value");
+
+ // A change that does not come from .NET is reported too.
+ await _page.EvaluateAsync("() => { document.cookie = 'external=1'; }");
+ await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync("Changed: external=1");
+ await _page.EvaluateAsync("() => { document.cookie = 'external=; max-age=0'; }");
+ await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync("Deleted: external");
+
+ await RunAsync("#delete-cookie", $"Delete: {name}");
+ await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync($"Deleted: {name}");
+
+ // Removing one listener leaves the other in place.
+ await RunAsync("#unwatch-cookie-changes", "Stop watching changes: removed");
+ await SetCookieAndWaitForTheBrowserEventAsync(name);
+ await Expect(_page.Locator("#cookie-change-second")).ToHaveTextAsync($"Changed: {name}=value");
+ // A round trip after the browser event lets a late notification arrive before the check.
+ await RunAsync("#get-cookie", $"Get: Found: {name}=value");
+ await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync($"Deleted: {name}");
+ await RunAsync("#delete-cookie", $"Delete: {name}");
+ await Expect(_page.Locator("#cookie-change-second")).ToHaveTextAsync($"Deleted: {name}");
+
+ // Canceling the token removes the second listener.
+ await RunAsync("#cancel-second-cookie-watch", "Cancel the second listener: canceled");
+ await SetCookieAndWaitForTheBrowserEventAsync(name);
+ await RunAsync("#get-cookie", $"Get: Found: {name}=value");
+ await Expect(_page.Locator("#cookie-change-second")).ToHaveTextAsync($"Deleted: {name}");
+ await RunAsync("#delete-cookie", $"Delete: {name}");
+ }
+ }
+
+ private async Task SetCookieAndWaitForTheBrowserEventAsync(string name)
+ {
+ var browserEvent = _page.EvaluateAsync(
+ "() => new Promise(resolve => cookieStore.addEventListener('change', resolve, { once: true }))");
+ await RunAsync("#set-cookie", $"Set: {name}");
+ await browserEvent;
+ }
+
private async Task NavigateAsync(string path, string interactiveSelector)
{
await _page.GotoAsync($"{_server.TestUrl}{path}");
diff --git a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/MessageEventTests.cs b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/MessageEventTests.cs
new file mode 100644
index 000000000000..e95c3d10fdef
--- /dev/null
+++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/MessageEventTests.cs
@@ -0,0 +1,78 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Globalization;
+using Microsoft.AspNetCore.Components.Testing.Infrastructure;
+using Microsoft.AspNetCore.Components.Testing.Playwright;
+using Microsoft.Playwright;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using PlatformTestApp.Components;
+using PlatformTestApp.E2E.Tests.Fixtures;
+
+namespace PlatformTestApp.E2E.Tests.Tests;
+
+[UITest]
+public partial class MessageEventTests : BrowserTest
+{
+ private static readonly string[] MessagePaths = ["/message-event-server", "/message-event-wasm"];
+
+ private ServerInstance _server = null!;
+ private IPage _page = null!;
+
+ protected override async Task InitializeCoreAsync()
+ {
+ await base.InitializeCoreAsync();
+ _server = await StartServerAsync(TestRoot.Servers);
+ var context = await NewContext(new BrowserNewContextOptions().WithServerRouting(_server));
+ _page = await context.NewPageAsync();
+ }
+
+ [TestMethod]
+ public async Task MessageEvent_DeliversAnyJsonValueAsJsonElement()
+ {
+ foreach (var path in MessagePaths)
+ {
+ await StartListeningAsync(path);
+
+ await PostAndExpectAsync("\"text\"", "\"text\"");
+ await PostAndExpectAsync("42", "42");
+ await PostAndExpectAsync("true", "true");
+ await PostAndExpectAsync("null", "null");
+ await PostAndExpectAsync(
+ """{ name: "日本語", list: [1, 2.5, "x", null, true], nested: { a: { b: [{ c: 1 }] } } }""",
+ """{"name":"日本語","list":[1,2.5,"x",null,true],"nested":{"a":{"b":[{"c":1}]}}}""");
+ }
+ }
+
+ [TestMethod]
+ public async Task MessageEvent_DeliversMarkersForValuesThatAreNotJson()
+ {
+ foreach (var path in MessagePaths)
+ {
+ await StartListeningAsync(path);
+
+ await PostAndExpectAsync(
+ "{ when: new Date(0), map: new Map([[1, 2]]), list: [new Date(0)], text: 'kept' }",
+ """{"when":{"__unsupported":"Date"},"map":{"__unsupported":"Map"},"list":[{"__unsupported":"Date"}],"text":"kept"}""");
+ }
+ }
+
+ private async Task StartListeningAsync(string path)
+ {
+ await _page.GotoAsync($"{_server.TestUrl}{path}");
+ await _page.WaitForInteractiveAsync("#listen-message");
+ await _page.Locator("#listen-message").ClickAsync();
+ await Expect(_page.Locator("#message-result")).ToHaveTextAsync("Listening.");
+ }
+
+ // The message event reaches the page asynchronously, so the test waits for the run counter to go up by one.
+ private async Task PostAndExpectAsync(string messageExpression, string expectedJson)
+ {
+ var run = int.Parse(await _page.Locator("#message-result").GetAttributeAsync("data-run") ?? "0", CultureInfo.InvariantCulture);
+
+ await _page.EvaluateAsync($"window.postMessage({messageExpression}, '*')");
+
+ await Expect(_page.Locator("#message-result")).ToHaveAttributeAsync("data-run", (run + 1).ToString(CultureInfo.InvariantCulture));
+ await Expect(_page.Locator("#message-result")).ToHaveTextAsync(expectedJson);
+ }
+}
diff --git a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/StorageTests.cs b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/StorageTests.cs
index 07447c1efc82..65e553088c1e 100644
--- a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/StorageTests.cs
+++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/StorageTests.cs
@@ -62,6 +62,30 @@ public async Task Url_WorksInBothRenderModes()
}
}
+ [TestMethod]
+ public async Task WebStorage_ReportsChangesFromAnotherPage()
+ {
+ foreach (var path in StoragePaths)
+ {
+ await NavigateAsync(path, "#watch-storage");
+ await _page.Locator("#watch-storage").ClickAsync();
+ await Expect(_page.Locator("#storage-result")).ToHaveTextAsync("Watching storage events.");
+
+ // The storage event fires only in other pages of the same origin.
+ var otherPage = await _page.Context.NewPageAsync();
+ await otherPage.GotoAsync($"{_server.TestUrl}{path}");
+
+ var value = path == "/storage-server" ? "server-event" : "wasm-event";
+ await otherPage.EvaluateAsync("value => localStorage.setItem('components-platform-e2e', value)", value);
+ await Expect(_page.Locator("#storage-event")).ToHaveTextAsync($"components-platform-e2e: (none) -> {value} in localStorage");
+
+ await otherPage.EvaluateAsync("() => localStorage.removeItem('components-platform-e2e')");
+ await Expect(_page.Locator("#storage-event")).ToHaveTextAsync($"components-platform-e2e: {value} -> (none) in localStorage");
+
+ await otherPage.CloseAsync();
+ }
+ }
+
private async Task NavigateAsync(string path, string interactiveSelector)
{
await _page.GotoAsync($"{_server.TestUrl}{path}");
diff --git a/src/Components/Platform/testassets/PlatformTestApp/Components/Pages/MessageEventServer.razor b/src/Components/Platform/testassets/PlatformTestApp/Components/Pages/MessageEventServer.razor
new file mode 100644
index 000000000000..855310d4dd58
--- /dev/null
+++ b/src/Components/Platform/testassets/PlatformTestApp/Components/Pages/MessageEventServer.razor
@@ -0,0 +1,4 @@
+@page "/message-event-server"
+@rendermode InteractiveServer
+
+