From 2f21a51f8e8606fb3fbcee2847f3e48637825015 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Thu, 15 Oct 2026 17:22:19 +0900 Subject: [PATCH 01/17] Try a generic JS callback bridge for Components.Platform events - Add a JS module (src/js/Platform.ts) with one export, createCallback. It returns a function that forwards any number of arguments to a .NET JSCallback. Each argument has a shape that selects what is copied, so an event can cross by value. Ship it as a static web asset, as Server.AutoPause does. - Add JSCallback, , and JSCallbackFactory. - Add CookieStore.SetOnChangeAsync and CookieChangeEvent as the first user. - Add jest, unit, and E2E tests. This is a local trial and not part of the Cookie Store PR. --- package-lock.json | 8 ++ package.json | 1 + .../Platform/src/CookieChangeEvent.cs | 20 ++++ src/Components/Platform/src/CookieStore.cs | 57 ++++++++++- src/Components/Platform/src/JSCallback.cs | 40 ++++++++ .../Platform/src/JSCallbackFactory.cs | 96 +++++++++++++++++++ ...soft.AspNetCore.Components.Platform.csproj | 63 +++++++++++- .../Platform/src/PublicAPI.Unshipped.txt | 7 ++ src/Components/Platform/src/js/Platform.ts | 62 ++++++++++++ .../Platform/src/js/babel.config.js | 6 ++ .../Platform/src/js/dist/.gitignore | 3 + src/Components/Platform/src/js/jest.config.js | 25 +++++ src/Components/Platform/src/js/package.json | 12 +++ .../Platform/src/js/rollup.config.mjs | 18 ++++ .../Platform/src/js/test/Platform.test.ts | 92 ++++++++++++++++++ src/Components/Platform/src/js/tsconfig.json | 4 + .../Platform/test/BrowserJSRuntime.cs | 62 ++++++++++++ .../Platform/test/CookieStoreTest.cs | 66 +++++++++++++ .../Platform/test/JSCallbackTest.cs | 96 +++++++++++++++++++ .../Components/CookieStoreDemo.razor | 30 ++++++ .../Tests/CookieStoreTests.cs | 41 ++++++++ 21 files changed, 807 insertions(+), 2 deletions(-) create mode 100644 src/Components/Platform/src/CookieChangeEvent.cs create mode 100644 src/Components/Platform/src/JSCallback.cs create mode 100644 src/Components/Platform/src/JSCallbackFactory.cs create mode 100644 src/Components/Platform/src/js/Platform.ts create mode 100644 src/Components/Platform/src/js/babel.config.js create mode 100644 src/Components/Platform/src/js/dist/.gitignore create mode 100644 src/Components/Platform/src/js/jest.config.js create mode 100644 src/Components/Platform/src/js/package.json create mode 100644 src/Components/Platform/src/js/rollup.config.mjs create mode 100644 src/Components/Platform/src/js/test/Platform.test.ts create mode 100644 src/Components/Platform/src/js/tsconfig.json create mode 100644 src/Components/Platform/test/BrowserJSRuntime.cs create mode 100644 src/Components/Platform/test/JSCallbackTest.cs 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/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..839bbd1d174a 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -12,13 +12,20 @@ namespace Microsoft.AspNetCore.Components.Platform; /// public sealed class CookieStore : IInternalAsyncDisposal { + // The change event crosses by value, and CookieListItem is a dictionary, so the lists are copied whole. + private const string OnChangeShapes = """[{"changed":null,"deleted":null}]"""; + private readonly IJSRuntime _jsRuntime; + private readonly JSCallbackFactory _callbacks; + private readonly JSCallback _onChange = new(); private Task? _referenceTask; + private Task? _onChangeFunctionTask; private bool _disposed; internal CookieStore(IJSRuntime jsRuntime) { _jsRuntime = jsRuntime; + _callbacks = new JSCallbackFactory(jsRuntime); } /// @@ -168,6 +175,37 @@ public async ValueTask DeleteAsync(CookieStoreDeleteOptions options) await cookieStore.InvokeVoidAsync("delete", options).ConfigureAwait(false); } + /// + /// Sets the handler that is called when cookies visible to the current page change, replacing any previous handler. + /// + /// The handler to call, or to remove the current handler. + /// A representing the completion of the operation. + /// The browser does not provide the Cookie Store API for the current page. + [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieListItem))] + public async ValueTask SetOnChangeAsync(Func? handler) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + // Swap the handler before any await, so the last call wins even if calls overlap. + _onChange.Handler = handler; + + var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + + if (handler is null) + { + await cookieStore.SetValueAsync("onchange", null).ConfigureAwait(false); + return; + } + + if (_onChangeFunctionTask is null || _onChangeFunctionTask.IsFaulted || _onChangeFunctionTask.IsCanceled) + { + _onChangeFunctionTask = _callbacks.CreateAsync(_onChange, OnChangeShapes); + } + + var function = await _onChangeFunctionTask.ConfigureAwait(false); + await cookieStore.SetValueAsync("onchange", function).ConfigureAwait(false); + } + async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() { if (_disposed) @@ -176,12 +214,29 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() } _disposed = true; + _onChange.Handler = null; // 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 cookieStore = referenceTask.Result; + + if (_onChangeFunctionTask is { IsCompletedSuccessfully: true }) + { + try + { + await cookieStore.SetValueAsync("onchange", null).ConfigureAwait(false); + } + catch (JSDisconnectedException) + { + // The page is already gone, so nothing can call the handler. + } + } + + await cookieStore.DisposeAsync().ConfigureAwait(false); } + + await ((IInternalAsyncDisposal)_callbacks).InternalDisposeAsync().ConfigureAwait(false); } private Task GetReferenceAsync() diff --git a/src/Components/Platform/src/JSCallback.cs b/src/Components/Platform/src/JSCallback.cs new file mode 100644 index 000000000000..bd97c208725f --- /dev/null +++ b/src/Components/Platform/src/JSCallback.cs @@ -0,0 +1,40 @@ +// 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; + +// Targets of the functions that JSCallbackFactory creates. 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; +} + +internal sealed class JSCallback< + [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T1, + [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T2> +{ + public Func? Handler { get; set; } + + [JSInvokable] + public Task Invoke(T1 arg1, T2 arg2) => Handler?.Invoke(arg1, arg2) ?? Task.CompletedTask; +} + +internal sealed class JSCallback< + [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T1, + [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T2, + [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T3> +{ + public Func? Handler { get; set; } + + [JSInvokable] + public Task Invoke(T1 arg1, T2 arg2, T3 arg3) => Handler?.Invoke(arg1, arg2, arg3) ?? Task.CompletedTask; +} diff --git a/src/Components/Platform/src/JSCallbackFactory.cs b/src/Components/Platform/src/JSCallbackFactory.cs new file mode 100644 index 000000000000..8742864c799b --- /dev/null +++ b/src/Components/Platform/src/JSCallbackFactory.cs @@ -0,0 +1,96 @@ +// 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 readonly List _targets = []; + private readonly List _functions = []; + private Task? _moduleTask; + private bool _disposed; + + public JSCallbackFactory(IJSRuntime jsRuntime) + { + _jsRuntime = jsRuntime; + } + + /// + /// Creates a JavaScript function that calls . + /// + /// The or other arity to call. + /// + /// A JSON array with one ArgumentShape (see js/Platform.ts) per parameter of . + /// + /// The function. It stays valid until this factory is disposed. + public async Task CreateAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCallback>( + TCallback callback, + string shapesJson) + where TCallback : class + { + ObjectDisposedException.ThrowIf(_disposed, this); + + var module = await GetModuleAsync().ConfigureAwait(false); + var target = DotNetObjectReference.Create(callback); + _targets.Add(target); + + var function = await module.InvokeAsync("createCallback", target, shapesJson).ConfigureAwait(false); + + if (_disposed) + { + await function.DisposeAsync().ConfigureAwait(false); + ObjectDisposedException.ThrowIf(_disposed, this); + } + + _functions.Add(function); + + return function; + } + + async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + + foreach (var function in _functions) + { + await function.DisposeAsync().ConfigureAwait(false); + } + + foreach (var target in _targets) + { + target.Dispose(); + } + + _functions.Clear(); + _targets.Clear(); + + if (_moduleTask is { IsCompletedSuccessfully: true } moduleTask) + { + await moduleTask.Result.DisposeAsync().ConfigureAwait(false); + } + } + + private Task GetModuleAsync() + { + if (_moduleTask is null || _moduleTask.IsFaulted || _moduleTask.IsCanceled) + { + _moduleTask = _jsRuntime.InvokeAsync("import", ModulePath).AsTask(); + } + + return _moduleTask; + } +} diff --git a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj index 75cd97a04839..af4b75923063 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,65 @@ + + + + + + + $(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..b19814cb1a24 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? @@ -37,6 +43,7 @@ Microsoft.AspNetCore.Components.Platform.CookieStore.GetAsync(Microsoft.AspNetCo Microsoft.AspNetCore.Components.Platform.CookieStore.GetAsync(string! name) -> System.Threading.Tasks.ValueTask Microsoft.AspNetCore.Components.Platform.CookieStore.SetAsync(Microsoft.AspNetCore.Components.Platform.CookieInit! options) -> System.Threading.Tasks.ValueTask Microsoft.AspNetCore.Components.Platform.CookieStore.SetAsync(string! name, string! value) -> System.Threading.Tasks.ValueTask +Microsoft.AspNetCore.Components.Platform.CookieStore.SetOnChangeAsync(System.Func? handler) -> System.Threading.Tasks.ValueTask Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.CookieStoreDeleteOptions() -> void Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Domain.get -> string? diff --git a/src/Components/Platform/src/js/Platform.ts b/src/Components/Platform/src/js/Platform.ts new file mode 100644 index 000000000000..c21c6b7a3021 --- /dev/null +++ b/src/Components/Platform/src/js/Platform.ts @@ -0,0 +1,62 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// What one argument sends to .NET. null sends the whole value. An object sends only the named +// properties, each with its own shape, so that a browser object such as an event can be copied. +export type ArgumentShape = null | { [property: string]: ArgumentShape }; + +export interface DotNetObject { + invokeMethodAsync(methodIdentifier: string, ...args: unknown[]): Promise; +} + +interface DotNetGlobal { + createJSObjectReference(jsObject: unknown): unknown; +} + +// Creates a function that calls the Invoke method of the target with one argument per shape. +// Arguments beyond the shapes are dropped. The returned promise settles when the .NET method completes. +export function createCallback(target: DotNetObject, shapesJson: string): (...args: unknown[]) => Promise { + const shapes: ArgumentShape[] = JSON.parse(shapesJson); + + return (...args) => target.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)); + } + + 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 is a browser object whose identity must survive, so it crosses as a reference. +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 (globalThis as unknown as { DotNet: DotNetGlobal }).DotNet.createJSObjectReference(value); +} 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..f159c4ce61a5 --- /dev/null +++ b/src/Components/Platform/src/js/test/Platform.test.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. + +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 createTarget(): DotNetObject & { calls: unknown[][] } { + const calls: unknown[][] = []; + return { + calls, + invokeMethodAsync: (methodIdentifier: string, ...args: unknown[]) => { + calls.push([methodIdentifier, ...args]); + return Promise.resolve('result' as T); + }, + }; +} + +beforeEach(() => { + let nextId = 1; + (globalThis as Record).DotNet = { + createJSObjectReference: () => ({ __jsObjectId: nextId++ }), + }; +}); + +describe('createCallback', () => { + test('forwards every argument that has a shape to Invoke', async () => { + const target = createTarget(); + const callback = createCallback(target, '[null, null, null]'); + + const result = await callback('a', 2, { three: 3 }); + + expect(result).toBe('result'); + expect(target.calls).toEqual([['Invoke', 'a', 2, { three: 3 }]]); + }); + + test('drops arguments beyond the shapes and sends null for missing ones', async () => { + const target = createTarget(); + + await createCallback(target, '[null]')('a', 'b'); + await createCallback(target, '[null, null]')('a'); + + expect(target.calls).toEqual([['Invoke', 'a'], ['Invoke', 'a', undefined]]); + expect(JSON.stringify(target.calls[1])).toBe('["Invoke","a",null]'); + }); + + test('copies only the shaped properties of an event', async () => { + const target = createTarget(); + const event = new Event('change'); + Object.defineProperty(event, 'changed', { get: () => [{ name: 'a', value: '1' }] }); + Object.defineProperty(event, 'deleted', { get: () => [{ name: 'b' }] }); + + await createCallback(target, '[{"changed":null,"deleted":null}]')(event); + + expect(JSON.stringify(target.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 browser objects as references', () => { + const value = toDotNet({ port: new BrowserObject(), ports: [new BrowserObject()] }, null); + + expect(value).toEqual({ port: { __jsObjectId: 1 }, ports: [{ __jsObjectId: 2 }] }); + }); + + 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 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..cde8a03a19f0 --- /dev/null +++ b/src/Components/Platform/test/BrowserJSRuntime.cs @@ -0,0 +1,62 @@ +// 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 long _nextObjectId = 1; + private long _nextCallId = 1; + + public List Calls { get; } = []; + + public IEnumerable CallsTo(string identifier) => Calls.Where(call => call.Identifier == identifier); + + // Calls the Invoke method of the DotNetObjectReference that the last createCallback call received. + public async Task InvokeLastCallbackAsync(string argsJson) + { + var createCallback = CallsTo("createCallback").Last(); + 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)); + + var result = invocationInfo.ResultType == JSCallResultType.JSObjectReference + ? $$"""{"__jsObjectId":{{_nextObjectId++}}}""" + : "null"; + + if (invocationInfo.AsyncHandle != 0) + { + DotNetDispatcher.EndInvokeJS(this, $"[{invocationInfo.AsyncHandle},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); + } +} + +internal sealed record BrowserCall(string Identifier, JSCallType CallType, long TargetInstanceId, string ArgsJson); diff --git a/src/Components/Platform/test/CookieStoreTest.cs b/src/Components/Platform/test/CookieStoreTest.cs index 2f4adad071da..10d534c0409b 100644 --- a/src/Components/Platform/test/CookieStoreTest.cs +++ b/src/Components/Platform/test/CookieStoreTest.cs @@ -4,6 +4,7 @@ #nullable enable #pragma warning disable ASP0040 // Partitioned is experimental. +using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.JSInterop; using Microsoft.JSInterop.Infrastructure; @@ -223,6 +224,71 @@ public async Task ScopeDisposal_DoesNotWaitForPendingAcquisition() Assert.False(jsRuntime.ObjectReference.Disposed); } + [Fact] + public async Task SetOnChangeAsync_AssignsAFunctionThatDeliversTheChangeEvent() + { + var jsRuntime = new BrowserJSRuntime(); + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + CookieChangeEvent? received = null; + + await cookieStore.SetOnChangeAsync(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 assignment = Assert.Single(jsRuntime.CallsTo("onchange")); + Assert.Equal((JSCallType.SetValue, 1, """[{"__jsObjectId":3}]"""), (assignment.CallType, assignment.TargetInstanceId, assignment.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 SetOnChangeAsync_ReplacesAndRemovesTheHandler() + { + var jsRuntime = new BrowserJSRuntime(); + await using var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + var calls = new List(); + + await cookieStore.SetOnChangeAsync(_ => { calls.Add("first"); return Task.CompletedTask; }); + await cookieStore.SetOnChangeAsync(_ => { calls.Add("second"); return Task.CompletedTask; }); + await jsRuntime.InvokeLastCallbackAsync("""[{"changed":[],"deleted":[]}]"""); + await cookieStore.SetOnChangeAsync(null); + var afterRemoval = await jsRuntime.InvokeLastCallbackAsync("""[{"changed":[],"deleted":[]}]"""); + + Assert.Equal(["second"], calls); + Assert.True(afterRemoval.Success); + Assert.Single(jsRuntime.CallsTo("createCallback")); + Assert.Equal( + ["""[{"__jsObjectId":3}]""", """[{"__jsObjectId":3}]""", "[null]"], + jsRuntime.CallsTo("onchange").Select(call => call.ArgsJson)); + } + + [Fact] + public async Task ScopeDisposal_RemovesTheChangeHandler() + { + var jsRuntime = new BrowserJSRuntime(); + var provider = CreateServiceProvider(jsRuntime); + var cookieStore = provider.GetRequiredService().Window.CookieStore; + await cookieStore.SetOnChangeAsync(_ => Task.CompletedTask); + + await provider.DisposeAsync(); + + Assert.Equal("[null]", jsRuntime.CallsTo("onchange").Last().ArgsJson); + Assert.Equal( + ["[1]", "[3]", "[2]"], + jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson)); + await Assert.ThrowsAsync(() => cookieStore.SetOnChangeAsync(null).AsTask()); + } + // A mock IJSRuntime records arguments before serialization, so the tests below check the JSON the browser receives. [Fact] public async Task SetAsync_SendsCookieInitWithoutNullMembers() diff --git a/src/Components/Platform/test/JSCallbackTest.cs b/src/Components/Platform/test/JSCallbackTest.cs new file mode 100644 index 000000000000..f2425e141302 --- /dev/null +++ b/src/Components/Platform/test/JSCallbackTest.cs @@ -0,0 +1,96 @@ +// 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(), "[null,{}]"); + + 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},"[null,{}]"]"""], + jsRuntime.CallsTo("createCallback").Select(call => call.ArgsJson)); + } + + [Fact] + public async Task Invoke_PassesEachArgumentToTheHandler() + { + var jsRuntime = new BrowserJSRuntime(); + var factory = new JSCallbackFactory(jsRuntime); + var callback = new JSCallback(); + (string, int, CookieListItem)? received = null; + callback.Handler = (text, number, cookie) => + { + received = (text, number, cookie); + return Task.CompletedTask; + }; + await factory.CreateAsync(callback, "[null,null,null]"); + + var result = await jsRuntime.InvokeLastCallbackAsync("""["text",42,{"name":"a","value":"1"}]"""); + + Assert.True(result.Success, result.Exception?.ToString()); + Assert.Equal("text", received?.Item1); + Assert.Equal(42, received?.Item2); + Assert.Equal(("a", "1"), (received?.Item3.Name, received?.Item3.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 Disposal_ReleasesFunctionsTargetsAndModule() + { + var jsRuntime = new BrowserJSRuntime(); + var factory = new JSCallbackFactory(jsRuntime); + var callback = new JSCallback { Handler = _ => Task.CompletedTask }; + await factory.CreateAsync(callback, "[null]"); + + await ((IInternalAsyncDisposal)factory).InternalDisposeAsync(); + var result = await jsRuntime.InvokeLastCallbackAsync("""["text"]"""); + + // The module is object 1 and the function is object 2. + Assert.Equal(["[2]", "[1]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson)); + Assert.False(result.Success); + await Assert.ThrowsAsync(() => factory.CreateAsync(callback, "[null]")); + } +} diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor index 9116a5ce61f1..377fcfa0086b 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor +++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor @@ -29,7 +29,12 @@ +
+ + +
+ @code { // A path other than the page path shows that the Path member reaches the browser. @@ -39,6 +44,7 @@ private string value = "initial"; private string result = "No operation has run."; private int runCount; + private string change = "No change has been reported."; private Task SetAsync() => RunAsync("Set", async () => { @@ -151,6 +157,30 @@ runCount++; } + private async Task WatchChangesAsync() + { + await Browser.Window.CookieStore.SetOnChangeAsync(OnCookieChangeAsync); + result = "Watching changes."; + } + + private async Task UnwatchChangesAsync() + { + await Browser.Window.CookieStore.SetOnChangeAsync(null); + result = "Stopped watching changes."; + } + + private Task OnCookieChangeAsync(CookieChangeEvent changeEvent) + { + change = string.Join( + "; ", + [ + .. changeEvent.Changed.Select(cookie => $"Changed: {cookie.Name}={cookie.Value}"), + .. changeEvent.Deleted.Select(cookie => $"Deleted: {cookie.Name}"), + ]); + + return InvokeAsync(StateHasChanged); + } + 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.E2E.Tests/Tests/CookieStoreTests.cs b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs index b348724ea7e5..aedc466687ec 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,47 @@ public async Task CookieStore_ThrowsNotSupportedExceptionWithoutTheBrowserApi() } } + [TestMethod] + public async Task CookieStore_ReportsChangesToTheChangeHandler() + { + 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", "Watching changes."); + + await RunAsync("#set-cookie", $"Set: {name}"); + await Expect(_page.Locator("#cookie-change")).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", $"Deleted: {name}"); + await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync($"Deleted: {name}"); + + await RunAsync("#unwatch-cookie-changes", "Stopped watching changes."); + await SetCookieAndWaitForTheBrowserEventAsync(name); + // A round trip after the browser event lets a late notification arrive before the check. + await RunAsync("#get-cookie", $"Found: {name}=value"); + await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync($"Deleted: {name}"); + await RunAsync("#delete-cookie", $"Deleted: {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}"); From efdb3da60202a9015a3507f548603cbb643b5c8b Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Mon, 19 Oct 2026 15:39:12 +0900 Subject: [PATCH 02/17] Replace SetOnChangeAsync with AddEventListenerAsync and a typed event key - Add EventType. CookieStore.ChangeEvent is the first key, and CookieStore.AddEventListenerAsync takes it. A key of another target does not compile. - Each call adds its own listener and returns an IAsyncDisposable that removes it. Scope disposal removes every listener that is still added. - Log an exception from a listener at Error level, so it does not get lost in the browser console. - The bridge no longer turns an unexpected browser object into a JS object reference that nobody disposes. It sends {"__unsupported": ""}. - Share one JSCallbackFactory per Window. Each listener owns its function and DotNetObjectReference. --- .../Platform/src/BrowserPlatform.cs | 7 +- src/Components/Platform/src/CookieStore.cs | 73 +++++------- src/Components/Platform/src/EventListener.cs | 101 ++++++++++++++++ .../Platform/src/EventListenerCollection.cs | 77 +++++++++++++ src/Components/Platform/src/EventType.cs | 52 +++++++++ .../Platform/src/JSCallbackFactory.cs | 41 +++---- ...soft.AspNetCore.Components.Platform.csproj | 1 + .../Platform/src/PublicAPI.Unshipped.txt | 5 +- src/Components/Platform/src/Window.cs | 16 ++- .../src/WindowCookieStoreExtensions.cs | 2 +- src/Components/Platform/src/js/Platform.ts | 14 ++- .../Platform/src/js/test/Platform.test.ts | 17 ++- .../Platform/test/BrowserJSRuntime.cs | 8 +- .../Platform/test/CookieStoreTest.cs | 109 ++++++++++++++---- .../Platform/test/JSCallbackTest.cs | 17 +-- .../Components/CookieStoreDemo.razor | 46 +++++++- .../Tests/CookieStoreTests.cs | 6 +- 17 files changed, 461 insertions(+), 131 deletions(-) create mode 100644 src/Components/Platform/src/EventListener.cs create mode 100644 src/Components/Platform/src/EventListenerCollection.cs create mode 100644 src/Components/Platform/src/EventType.cs 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/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index 839bbd1d174a..67c63ba54ad7 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -12,22 +12,24 @@ namespace Microsoft.AspNetCore.Components.Platform; ///
public sealed class CookieStore : IInternalAsyncDisposal { - // The change event crosses by value, and CookieListItem is a dictionary, so the lists are copied whole. - private const string OnChangeShapes = """[{"changed":null,"deleted":null}]"""; - private readonly IJSRuntime _jsRuntime; - private readonly JSCallbackFactory _callbacks; - private readonly JSCallback _onChange = new(); + private readonly EventListenerCollection _listeners; private Task? _referenceTask; - private Task? _onChangeFunctionTask; private bool _disposed; - internal CookieStore(IJSRuntime jsRuntime) + internal CookieStore(IJSRuntime jsRuntime, EventListenerCollection listeners) { _jsRuntime = jsRuntime; - _callbacks = new JSCallbackFactory(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. /// @@ -176,34 +178,25 @@ public async ValueTask DeleteAsync(CookieStoreDeleteOptions options) } /// - /// Sets the handler that is called when cookies visible to the current page change, replacing any previous handler. + /// 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. /// - /// The handler to call, or to remove the current handler. - /// A representing the completion of the operation. + /// 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. [DynamicDependency(LinkerFlags.JsonSerialized, typeof(CookieListItem))] - public async ValueTask SetOnChangeAsync(Func? handler) + public async ValueTask AddEventListenerAsync(EventType type, Func listener) { - ObjectDisposedException.ThrowIf(_disposed, this); - - // Swap the handler before any await, so the last call wins even if calls overlap. - _onChange.Handler = handler; + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(listener); var cookieStore = await GetReferenceAsync().ConfigureAwait(false); - if (handler is null) - { - await cookieStore.SetValueAsync("onchange", null).ConfigureAwait(false); - return; - } - - if (_onChangeFunctionTask is null || _onChangeFunctionTask.IsFaulted || _onChangeFunctionTask.IsCanceled) - { - _onChangeFunctionTask = _callbacks.CreateAsync(_onChange, OnChangeShapes); - } - - var function = await _onChangeFunctionTask.ConfigureAwait(false); - await cookieStore.SetValueAsync("onchange", function).ConfigureAwait(false); + return await type.AddListenerAsync(_listeners, cookieStore, this, listener).ConfigureAwait(false); } async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() @@ -214,29 +207,15 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() } _disposed = true; - _onChange.Handler = null; + + // Listeners need the cookie store reference to remove themselves, so they go first. + await ((IInternalAsyncDisposal)_listeners).InternalDisposeAsync().ConfigureAwait(false); // Don't wait for a pending acquisition. It could hold up scope disposal until the JS interop timeout. if (_referenceTask is { IsCompletedSuccessfully: true } referenceTask) { - var cookieStore = referenceTask.Result; - - if (_onChangeFunctionTask is { IsCompletedSuccessfully: true }) - { - try - { - await cookieStore.SetValueAsync("onchange", null).ConfigureAwait(false); - } - catch (JSDisconnectedException) - { - // The page is already gone, so nothing can call the handler. - } - } - - await cookieStore.DisposeAsync().ConfigureAwait(false); + await referenceTask.Result.DisposeAsync().ConfigureAwait(false); } - - await ((IInternalAsyncDisposal)_callbacks).InternalDisposeAsync().ConfigureAwait(false); } private Task GetReferenceAsync() diff --git a/src/Components/Platform/src/EventListener.cs b/src/Components/Platform/src/EventListener.cs new file mode 100644 index 000000000000..341637c997c6 --- /dev/null +++ b/src/Components/Platform/src/EventListener.cs @@ -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. + +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 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 ILogger _logger; + private IJSObjectReference? _function; + private IDisposable? _callbackReference; + private bool _removed; + + public EventListener(EventListenerCollection owner, IJSObjectReference target, string type, Func listener, ILogger logger) + { + _owner = owner; + _target = target; + _type = type; + _listener = listener; + _logger = logger; + } + + public async Task AddAsync(JSCallbackFactory callbacks, string shapesJson) + { + var callback = new JSCallback { Handler = InvokeListenerAsync }; + (_function, _callbackReference) = await callbacks.CreateAsync(callback, shapesJson).ConfigureAwait(false); + + // Disposal can run while the function is being created, and then nothing else releases it. + if (_removed) + { + await ReleaseAsync().ConfigureAwait(false); + throw new ObjectDisposedException(GetType().Name); + } + + await _target.InvokeVoidAsync("addEventListener", _type, _function).ConfigureAwait(false); + } + + public async ValueTask DisposeAsync() + { + if (_removed) + { + return; + } + + _removed = true; + _owner.Remove(this); + + await ReleaseAsync().ConfigureAwait(false); + } + + private async Task InvokeListenerAsync(TEvent value) + { + // A call that left the browser before removal can still arrive. + if (_removed) + { + return; + } + + try + { + await _listener(value); + } + catch (Exception ex) + { + EventListenerCollection.Log.ListenerThrew(_logger, _type, ex); + } + } + + private async ValueTask ReleaseAsync() + { + if (_function is { } function) + { + _function = null; + + try + { + await _target.InvokeVoidAsync("removeEventListener", _type, function).ConfigureAwait(false); + } + catch (JSDisconnectedException) + { + // The page is already gone, so nothing can call the listener. + } + + await function.DisposeAsync().ConfigureAwait(false); + } + + _callbackReference?.Dispose(); + _callbackReference = null; + } +} diff --git a/src/Components/Platform/src/EventListenerCollection.cs b/src/Components/Platform/src/EventListenerCollection.cs new file mode 100644 index 000000000000..f32a639f04e2 --- /dev/null +++ b/src/Components/Platform/src/EventListenerCollection.cs @@ -0,0 +1,77 @@ +// 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 _callbacks; + private readonly ILogger _logger; + private readonly List _listeners = []; + private bool _disposed; + + public EventListenerCollection(JSCallbackFactory callbacks, ILogger logger) + { + _callbacks = callbacks; + _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) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + var eventListener = new EventListener(this, target, type, listener, _logger); + _listeners.Add(eventListener); + + try + { + await eventListener.AddAsync(_callbacks, shapesJson).ConfigureAwait(false); + } + catch + { + await eventListener.DisposeAsync().ConfigureAwait(false); + throw; + } + + 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 listener.DisposeAsync().ConfigureAwait(false); + } + } + + internal static partial class Log + { + [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..fa6be80b59d3 --- /dev/null +++ b/src/Components/Platform/src/EventType.cs @@ -0,0 +1,52 @@ +// 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, Task> _addListenerAsync; + + internal EventType( + string name, + Func, 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) + => _addListenerAsync(listeners, target, owner, listener); +} + +/// +/// 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) => listeners.AddAsync(target, name, shapesJson, listener)); +} diff --git a/src/Components/Platform/src/JSCallbackFactory.cs b/src/Components/Platform/src/JSCallbackFactory.cs index 8742864c799b..5513a526dc01 100644 --- a/src/Components/Platform/src/JSCallbackFactory.cs +++ b/src/Components/Platform/src/JSCallbackFactory.cs @@ -14,8 +14,6 @@ internal sealed class JSCallbackFactory : IInternalAsyncDisposal private const string ModulePath = "./_content/Microsoft.AspNetCore.Components.Platform/Microsoft.AspNetCore.Components.Platform.js"; private readonly IJSRuntime _jsRuntime; - private readonly List _targets = []; - private readonly List _functions = []; private Task? _moduleTask; private bool _disposed; @@ -31,8 +29,11 @@ public JSCallbackFactory(IJSRuntime jsRuntime) /// /// A JSON array with one ArgumentShape (see js/Platform.ts) per parameter of . /// - /// The function. It stays valid until this factory is disposed. - public async Task CreateAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCallback>( + /// + /// 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 Target)> CreateAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCallback>( TCallback callback, string shapesJson) where TCallback : class @@ -41,19 +42,17 @@ public JSCallbackFactory(IJSRuntime jsRuntime) var module = await GetModuleAsync().ConfigureAwait(false); var target = DotNetObjectReference.Create(callback); - _targets.Add(target); - var function = await module.InvokeAsync("createCallback", target, shapesJson).ConfigureAwait(false); - - if (_disposed) + try { - await function.DisposeAsync().ConfigureAwait(false); - ObjectDisposedException.ThrowIf(_disposed, this); + var function = await module.InvokeAsync("createCallback", target, shapesJson).ConfigureAwait(false); + return (function, target); + } + catch + { + target.Dispose(); + throw; } - - _functions.Add(function); - - return function; } async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() @@ -65,19 +64,7 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() _disposed = true; - foreach (var function in _functions) - { - await function.DisposeAsync().ConfigureAwait(false); - } - - foreach (var target in _targets) - { - target.Dispose(); - } - - _functions.Clear(); - _targets.Clear(); - + // Functions created from the module keep working after the module reference is released. if (_moduleTask is { IsCompletedSuccessfully: true } moduleTask) { await moduleTask.Result.DisposeAsync().ConfigureAwait(false); diff --git a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj index af4b75923063..fdab97128a92 100644 --- a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj +++ b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj @@ -13,6 +13,7 @@ + diff --git a/src/Components/Platform/src/PublicAPI.Unshipped.txt b/src/Components/Platform/src/PublicAPI.Unshipped.txt index b19814cb1a24..d2d92afb653d 100644 --- a/src/Components/Platform/src/PublicAPI.Unshipped.txt +++ b/src/Components/Platform/src/PublicAPI.Unshipped.txt @@ -34,6 +34,7 @@ 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.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!> @@ -43,7 +44,6 @@ Microsoft.AspNetCore.Components.Platform.CookieStore.GetAsync(Microsoft.AspNetCo Microsoft.AspNetCore.Components.Platform.CookieStore.GetAsync(string! name) -> System.Threading.Tasks.ValueTask Microsoft.AspNetCore.Components.Platform.CookieStore.SetAsync(Microsoft.AspNetCore.Components.Platform.CookieInit! options) -> System.Threading.Tasks.ValueTask Microsoft.AspNetCore.Components.Platform.CookieStore.SetAsync(string! name, string! value) -> System.Threading.Tasks.ValueTask -Microsoft.AspNetCore.Components.Platform.CookieStore.SetOnChangeAsync(System.Func? handler) -> System.Threading.Tasks.ValueTask Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.CookieStoreDeleteOptions() -> void Microsoft.AspNetCore.Components.Platform.CookieStoreDeleteOptions.Domain.get -> string? @@ -60,6 +60,8 @@ 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.Storage @@ -137,3 +139,4 @@ 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! diff --git a/src/Components/Platform/src/Window.cs b/src/Components/Platform/src/Window.cs index 165635cdad32..66c3b39863d8 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,14 +13,24 @@ namespace Microsoft.AspNetCore.Components.Platform; public sealed class Window : IInternalAsyncDisposal { private readonly IJSRuntime _jsRuntime; + private readonly JSCallbackFactory _callbacks; + private readonly ILogger _eventListenerLogger; private readonly Dictionary<(Type FeatureType, string? Subkey), object> _features = []; private bool _disposed; - internal Window(IJSRuntime jsRuntime) + internal Window(IJSRuntime jsRuntime, ILoggerFactory loggerFactory) { _jsRuntime = jsRuntime; + _callbacks = new JSCallbackFactory(jsRuntime); + _eventListenerLogger = loggerFactory.CreateLogger(); } + /// + /// Creates the collection that a projection uses to add event listeners to its JavaScript object. + /// + internal EventListenerCollection CreateEventListenerCollection() + => new(_callbacks, _eventListenerLogger); + /// /// Gets the projection of type , creating it on first access. /// @@ -85,5 +96,8 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() await disposable.InternalDisposeAsync().ConfigureAwait(false); } } + + // Features remove their listeners first, so the module is no longer needed. + await ((IInternalAsyncDisposal)_callbacks).InternalDisposeAsync().ConfigureAwait(false); } } diff --git a/src/Components/Platform/src/WindowCookieStoreExtensions.cs b/src/Components/Platform/src/WindowCookieStoreExtensions.cs index dc9acdd7e74c..d05fe5999916 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 jsRuntime => new CookieStore(jsRuntime)); + => window.GetOrAddFeature(jsRuntime => new CookieStore(jsRuntime, window.CreateEventListenerCollection())); } } diff --git a/src/Components/Platform/src/js/Platform.ts b/src/Components/Platform/src/js/Platform.ts index c21c6b7a3021..83502aa0a63b 100644 --- a/src/Components/Platform/src/js/Platform.ts +++ b/src/Components/Platform/src/js/Platform.ts @@ -9,10 +9,6 @@ export interface DotNetObject { invokeMethodAsync(methodIdentifier: string, ...args: unknown[]): Promise; } -interface DotNetGlobal { - createJSObjectReference(jsObject: unknown): unknown; -} - // Creates a function that calls the Invoke method of the target with one argument per shape. // Arguments beyond the shapes are dropped. The returned promise settles when the .NET method completes. export function createCallback(target: DotNetObject, shapesJson: string): (...args: unknown[]) => Promise { @@ -43,7 +39,8 @@ export function toDotNet(value: unknown, shape: ArgumentShape): unknown { } // Web IDL dictionaries and sequences arrive as plain objects and arrays, so they are copied. -// Any other object is a browser object whose identity must survive, so it crosses as a reference. +// 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; @@ -58,5 +55,10 @@ export function toTransferable(value: unknown): unknown { return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, toTransferable(item)])); } - return (globalThis as unknown as { DotNet: DotNetGlobal }).DotNet.createJSObjectReference(value); + return { __unsupported: typeNameOf(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/test/Platform.test.ts b/src/Components/Platform/src/js/test/Platform.test.ts index f159c4ce61a5..31b757c48208 100644 --- a/src/Components/Platform/src/js/test/Platform.test.ts +++ b/src/Components/Platform/src/js/test/Platform.test.ts @@ -25,13 +25,6 @@ function createTarget(): DotNetObject & { calls: unknown[][] } { }; } -beforeEach(() => { - let nextId = 1; - (globalThis as Record).DotNet = { - createJSObjectReference: () => ({ __jsObjectId: nextId++ }), - }; -}); - describe('createCallback', () => { test('forwards every argument that has a shape to Invoke', async () => { const target = createTarget(); @@ -72,10 +65,14 @@ describe('toDotNet', () => { expect(toDotNet({ a: [1, { b: true }] }, null)).toEqual({ a: [1, { b: true }] }); }); - test('sends browser objects as references', () => { - const value = toDotNet({ port: new BrowserObject(), ports: [new BrowserObject()] }, null); + 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: { __jsObjectId: 1 }, ports: [{ __jsObjectId: 2 }] }); + expect(value).toEqual({ + port: { __unsupported: 'BrowserObject' }, + dates: [{ __unsupported: 'Date' }], + callback: { __unsupported: 'Function' }, + }); }); test('applies nested shapes and applies a shape to each array item', () => { diff --git a/src/Components/Platform/test/BrowserJSRuntime.cs b/src/Components/Platform/test/BrowserJSRuntime.cs index cde8a03a19f0..17347132450d 100644 --- a/src/Components/Platform/test/BrowserJSRuntime.cs +++ b/src/Components/Platform/test/BrowserJSRuntime.cs @@ -21,9 +21,13 @@ internal sealed class BrowserJSRuntime : JSRuntime public IEnumerable CallsTo(string identifier) => Calls.Where(call => call.Identifier == identifier); // Calls the Invoke method of the DotNetObjectReference that the last createCallback call received. - public async Task InvokeLastCallbackAsync(string argsJson) + 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").Last(); + 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); diff --git a/src/Components/Platform/test/CookieStoreTest.cs b/src/Components/Platform/test/CookieStoreTest.cs index 10d534c0409b..1a9d37e70e31 100644 --- a/src/Components/Platform/test/CookieStoreTest.cs +++ b/src/Components/Platform/test/CookieStoreTest.cs @@ -6,6 +6,7 @@ using System.Text.Json; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Microsoft.JSInterop; using Microsoft.JSInterop.Infrastructure; using Xunit; @@ -225,14 +226,14 @@ public async Task ScopeDisposal_DoesNotWaitForPendingAcquisition() } [Fact] - public async Task SetOnChangeAsync_AssignsAFunctionThatDeliversTheChangeEvent() + 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.SetOnChangeAsync(changeEvent => + await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, changeEvent => { received = changeEvent; return Task.CompletedTask; @@ -243,50 +244,85 @@ await cookieStore.SetOnChangeAsync(changeEvent => // 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 assignment = Assert.Single(jsRuntime.CallsTo("onchange")); - Assert.Equal((JSCallType.SetValue, 1, """[{"__jsObjectId":3}]"""), (assignment.CallType, assignment.TargetInstanceId, assignment.ArgsJson)); + 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 SetOnChangeAsync_ReplacesAndRemovesTheHandler() + 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(); - await cookieStore.SetOnChangeAsync(_ => { calls.Add("first"); return Task.CompletedTask; }); - await cookieStore.SetOnChangeAsync(_ => { calls.Add("second"); return Task.CompletedTask; }); - await jsRuntime.InvokeLastCallbackAsync("""[{"changed":[],"deleted":[]}]"""); - await cookieStore.SetOnChangeAsync(null); - var afterRemoval = await jsRuntime.InvokeLastCallbackAsync("""[{"changed":[],"deleted":[]}]"""); + 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)); + } - Assert.Equal(["second"], calls); - Assert.True(afterRemoval.Success); - Assert.Single(jsRuntime.CallsTo("createCallback")); - Assert.Equal( - ["""[{"__jsObjectId":3}]""", """[{"__jsObjectId":3}]""", "[null]"], - jsRuntime.CallsTo("onchange").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_RemovesTheChangeHandler() + public async Task ScopeDisposal_RemovesListeners() { var jsRuntime = new BrowserJSRuntime(); var provider = CreateServiceProvider(jsRuntime); var cookieStore = provider.GetRequiredService().Window.CookieStore; - await cookieStore.SetOnChangeAsync(_ => Task.CompletedTask); + var listener = await cookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, _ => Task.CompletedTask); await provider.DisposeAsync(); + await listener.DisposeAsync(); - Assert.Equal("[null]", jsRuntime.CallsTo("onchange").Last().ArgsJson); + Assert.Single(jsRuntime.CallsTo("removeEventListener")); Assert.Equal( - ["[1]", "[3]", "[2]"], + ["[3]", "[1]", "[2]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson)); - await Assert.ThrowsAsync(() => cookieStore.SetOnChangeAsync(null).AsTask()); + 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. @@ -409,15 +445,44 @@ 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(); } + private sealed record LogEntry(LogLevel Level, EventId EventId, Exception? Exception); + + private 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() + { + } + } + private static void AssertInvocation(Invocation invocation, string identifier, params object?[] arguments) { Assert.Equal(identifier, invocation.Identifier); diff --git a/src/Components/Platform/test/JSCallbackTest.cs b/src/Components/Platform/test/JSCallbackTest.cs index f2425e141302..2ecc9e6b873a 100644 --- a/src/Components/Platform/test/JSCallbackTest.cs +++ b/src/Components/Platform/test/JSCallbackTest.cs @@ -78,19 +78,22 @@ public async Task Invoke_SucceedsWithoutAHandler() } [Fact] - public async Task Disposal_ReleasesFunctionsTargetsAndModule() + public async Task CreatedFunctions_StayValidUntilTheCallerReleasesThem() { var jsRuntime = new BrowserJSRuntime(); var factory = new JSCallbackFactory(jsRuntime); var callback = new JSCallback { Handler = _ => Task.CompletedTask }; - await factory.CreateAsync(callback, "[null]"); + var (_, target) = await factory.CreateAsync(callback, "[null]"); await ((IInternalAsyncDisposal)factory).InternalDisposeAsync(); - var result = await jsRuntime.InvokeLastCallbackAsync("""["text"]"""); - - // The module is object 1 and the function is object 2. - Assert.Equal(["[2]", "[1]"], jsRuntime.CallsTo("DotNet.disposeJSObjectReferenceById").Select(call => call.ArgsJson)); - Assert.False(result.Success); + var beforeRelease = await jsRuntime.InvokeLastCallbackAsync("""["text"]"""); + target.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]")); } } diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor index 377fcfa0086b..61a681c4df97 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 @@ -31,10 +32,12 @@
+
+ @code { // A path other than the page path shows that the Path member reaches the browser. @@ -45,6 +48,9 @@ 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; + private IAsyncDisposable? secondListener; private Task SetAsync() => RunAsync("Set", async () => { @@ -159,26 +165,58 @@ private async Task WatchChangesAsync() { - await Browser.Window.CookieStore.SetOnChangeAsync(OnCookieChangeAsync); + listener = await Browser.Window.CookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, OnCookieChangeAsync); result = "Watching changes."; } + private async Task WatchChangesWithSecondListenerAsync() + { + secondListener = await Browser.Window.CookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, changeEvent => + { + secondChange = Describe(changeEvent); + StateHasChanged(); + return Task.CompletedTask; + }); + result = "Watching changes with a second listener."; + } + private async Task UnwatchChangesAsync() { - await Browser.Window.CookieStore.SetOnChangeAsync(null); + if (listener is not null) + { + await listener.DisposeAsync(); + } + result = "Stopped watching changes."; } + // The listener runs on the renderer's dispatcher, so StateHasChanged needs no InvokeAsync. private Task OnCookieChangeAsync(CookieChangeEvent changeEvent) { - change = string.Join( + 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}"), ]); - return InvokeAsync(StateHasChanged); + public async ValueTask DisposeAsync() + { + if (listener is not null) + { + await listener.DisposeAsync(); + } + + if (secondListener is not null) + { + await secondListener.DisposeAsync(); + } } private static string Format(CookieListItem? cookie) 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 aedc466687ec..2c9028398275 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs +++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs @@ -157,7 +157,7 @@ public async Task CookieStore_ThrowsNotSupportedExceptionWithoutTheBrowserApi() } [TestMethod] - public async Task CookieStore_ReportsChangesToTheChangeHandler() + public async Task CookieStore_ReportsChangesToEachListener() { foreach (var path in CookieStorePaths) { @@ -167,9 +167,11 @@ public async Task CookieStore_ReportsChangesToTheChangeHandler() await _page.Locator("#cookie-name").FillAsync(name); await _page.Locator("#cookie-value").FillAsync("value"); await RunAsync("#watch-cookie-changes", "Watching changes."); + await RunAsync("#watch-cookie-changes-second", "Watching changes with a second listener."); 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'; }"); @@ -180,8 +182,10 @@ public async Task CookieStore_ReportsChangesToTheChangeHandler() await RunAsync("#delete-cookie", $"Deleted: {name}"); await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync($"Deleted: {name}"); + // Removing one listener leaves the other in place. await RunAsync("#unwatch-cookie-changes", "Stopped watching changes."); 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", $"Found: {name}=value"); await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync($"Deleted: {name}"); From 152741231d23599de3acbc263f242ae0a5dd611e Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Mon, 19 Oct 2026 15:44:48 +0900 Subject: [PATCH 03/17] Add the storage event on Window with AddEventListenerAsync - Add Window.AddEventListenerAsync and the key Window.StorageEvent, a static extension member in WindowWebStorageExtensions. - StorageEvent.StorageArea is the existing LocalStorage or SessionStorage instance. A new { $known: [...] } shape sends the name of the matching global, such as "localStorage", instead of a reference. - An EventType can convert the payload before the listener gets it, so the public event type can refer to existing projections. - The E2E test changes localStorage in a second page of the same browser context, because the event does not fire in the page that made the change. --- src/Components/Platform/src/EventType.cs | 15 ++++++ .../Platform/src/PublicAPI.Unshipped.txt | 14 +++++ src/Components/Platform/src/StorageEvent.cs | 35 +++++++++++++ .../Platform/src/StorageEventPayload.cs | 32 ++++++++++++ src/Components/Platform/src/Window.cs | 45 ++++++++++++++++ .../src/WindowWebStorageExtensions.cs | 14 +++++ src/Components/Platform/src/js/Platform.ts | 29 ++++++++++- .../Platform/src/js/test/Platform.test.ts | 12 +++++ src/Components/Platform/test/PublicApiTest.cs | 1 + src/Components/Platform/test/StorageTest.cs | 52 +++++++++++++++++++ .../Components/StorageDemo.razor | 30 +++++++++++ .../Tests/StorageTests.cs | 24 +++++++++ src/submodules/googletest | 2 +- 13 files changed, 303 insertions(+), 2 deletions(-) create mode 100644 src/Components/Platform/src/StorageEvent.cs create mode 100644 src/Components/Platform/src/StorageEventPayload.cs diff --git a/src/Components/Platform/src/EventType.cs b/src/Components/Platform/src/EventType.cs index fa6be80b59d3..157dcea120ca 100644 --- a/src/Components/Platform/src/EventType.cs +++ b/src/Components/Platform/src/EventType.cs @@ -49,4 +49,19 @@ internal static class EventTypes string shapesJson) where TTarget : class => new(name, (listeners, target, _, listener) => listeners.AddAsync(target, name, shapesJson, listener)); + + /// + /// 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) => + listeners.AddAsync(target, name, shapesJson, payload => listener(convert(owner, payload)))); } diff --git a/src/Components/Platform/src/PublicAPI.Unshipped.txt b/src/Components/Platform/src/PublicAPI.Unshipped.txt index d2d92afb653d..c93d70b73365 100644 --- a/src/Components/Platform/src/PublicAPI.Unshipped.txt +++ b/src/Components/Platform/src/PublicAPI.Unshipped.txt @@ -64,6 +64,18 @@ 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 @@ -130,6 +142,7 @@ 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.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! @@ -140,3 +153,4 @@ Microsoft.AspNetCore.Components.Platform.WindowWebStorageExtensions.extension(Mi 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 66c3b39863d8..edfb19b56c13 100644 --- a/src/Components/Platform/src/Window.cs +++ b/src/Components/Platform/src/Window.cs @@ -15,7 +15,9 @@ public sealed class Window : IInternalAsyncDisposal private readonly IJSRuntime _jsRuntime; private readonly JSCallbackFactory _callbacks; private readonly ILogger _eventListenerLogger; + private readonly EventListenerCollection _listeners; private readonly Dictionary<(Type FeatureType, string? Subkey), object> _features = []; + private Task? _referenceTask; private bool _disposed; internal Window(IJSRuntime jsRuntime, ILoggerFactory loggerFactory) @@ -23,6 +25,27 @@ internal Window(IJSRuntime jsRuntime, ILoggerFactory loggerFactory) _jsRuntime = jsRuntime; _callbacks = new JSCallbackFactory(jsRuntime); _eventListenerLogger = loggerFactory.CreateLogger(); + _listeners = CreateEventListenerCollection(); + } + + /// + /// 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. + /// + /// 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 async ValueTask AddEventListenerAsync(EventType type, Func listener) + { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(listener); + + var window = await GetReferenceAsync().ConfigureAwait(false); + + return await type.AddListenerAsync(_listeners, window, this, listener).ConfigureAwait(false); } /// @@ -31,6 +54,18 @@ internal Window(IJSRuntime jsRuntime, ILoggerFactory loggerFactory) internal EventListenerCollection CreateEventListenerCollection() => new(_callbacks, _eventListenerLogger); + private Task GetReferenceAsync() + { + ObjectDisposedException.ThrowIf(_disposed, this); + + if (_referenceTask is null || _referenceTask.IsFaulted || _referenceTask.IsCanceled) + { + _referenceTask = _jsRuntime.GetValueAsync("window").AsTask(); + } + + return _referenceTask; + } + /// /// Gets the projection of type , creating it on first access. /// @@ -86,6 +121,16 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() } _disposed = true; + + // Listeners need the window reference to remove themselves, so they go first. + await ((IInternalAsyncDisposal)_listeners).InternalDisposeAsync().ConfigureAwait(false); + + // 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(); diff --git a/src/Components/Platform/src/WindowWebStorageExtensions.cs b/src/Components/Platform/src/WindowWebStorageExtensions.cs index 9f03165834e0..d849cad683f4 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 index 83502aa0a63b..e4db9a9bd42e 100644 --- a/src/Components/Platform/src/js/Platform.ts +++ b/src/Components/Platform/src/js/Platform.ts @@ -3,7 +3,12 @@ // What one argument sends to .NET. null sends the whole value. An object sends only the named // properties, each with its own shape, so that a browser object such as an event can be copied. -export type ArgumentShape = null | { [property: string]: ArgumentShape }; +// { $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; @@ -30,6 +35,10 @@ export function toDotNet(value: unknown, shape: ArgumentShape): unknown { 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); @@ -58,6 +67,24 @@ export function toTransferable(value: unknown): unknown { 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/test/Platform.test.ts b/src/Components/Platform/src/js/test/Platform.test.ts index 31b757c48208..b33f8fb8dde4 100644 --- a/src/Components/Platform/src/js/test/Platform.test.ts +++ b/src/Components/Platform/src/js/test/Platform.test.ts @@ -82,6 +82,18 @@ describe('toDotNet', () => { 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/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/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/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.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/submodules/googletest b/src/submodules/googletest index a8380b01a25e..cd8e73f06712 160000 --- a/src/submodules/googletest +++ b/src/submodules/googletest @@ -1 +1 @@ -Subproject commit a8380b01a25ebdb130097b607b3afed2a58d04ba +Subproject commit cd8e73f067129f8489e35c7b51c7a68552b289d2 From 7b0870e86c017816ce656ed5a06e18416d6f67d7 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Thu, 22 Oct 2026 17:39:06 +0900 Subject: [PATCH 04/17] Rename JS callback bridge identifiers for readability Name the JSCallbackFactory parameters and fields callbackFactory, not callbacks, which read as a collection of callbacks. Name the DotNetObjectReference that a created function calls callbackReference, not target, which clashed with the event target in EventListener. --- src/Components/Platform/src/EventListener.cs | 4 ++-- .../Platform/src/EventListenerCollection.cs | 8 +++---- src/Components/Platform/src/JSCallback.cs | 2 +- .../Platform/src/JSCallbackFactory.cs | 10 ++++---- src/Components/Platform/src/Window.cs | 8 +++---- src/Components/Platform/src/js/Platform.ts | 6 ++--- .../Platform/src/js/test/Platform.test.ts | 24 +++++++++---------- .../Platform/test/JSCallbackTest.cs | 4 ++-- 8 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/Components/Platform/src/EventListener.cs b/src/Components/Platform/src/EventListener.cs index 341637c997c6..3f9cdd896f3c 100644 --- a/src/Components/Platform/src/EventListener.cs +++ b/src/Components/Platform/src/EventListener.cs @@ -31,10 +31,10 @@ public EventListener(EventListenerCollection owner, IJSObjectReference target, s _logger = logger; } - public async Task AddAsync(JSCallbackFactory callbacks, string shapesJson) + public async Task AddAsync(JSCallbackFactory callbackFactory, string shapesJson) { var callback = new JSCallback { Handler = InvokeListenerAsync }; - (_function, _callbackReference) = await callbacks.CreateAsync(callback, shapesJson).ConfigureAwait(false); + (_function, _callbackReference) = await callbackFactory.CreateAsync(callback, shapesJson).ConfigureAwait(false); // Disposal can run while the function is being created, and then nothing else releases it. if (_removed) diff --git a/src/Components/Platform/src/EventListenerCollection.cs b/src/Components/Platform/src/EventListenerCollection.cs index f32a639f04e2..9f29c08a277d 100644 --- a/src/Components/Platform/src/EventListenerCollection.cs +++ b/src/Components/Platform/src/EventListenerCollection.cs @@ -13,14 +13,14 @@ namespace Microsoft.AspNetCore.Components.Platform; ///
internal sealed partial class EventListenerCollection : IInternalAsyncDisposal { - private readonly JSCallbackFactory _callbacks; + private readonly JSCallbackFactory _callbackFactory; private readonly ILogger _logger; private readonly List _listeners = []; private bool _disposed; - public EventListenerCollection(JSCallbackFactory callbacks, ILogger logger) + public EventListenerCollection(JSCallbackFactory callbackFactory, ILogger logger) { - _callbacks = callbacks; + _callbackFactory = callbackFactory; _logger = logger; } @@ -41,7 +41,7 @@ public EventListenerCollection(JSCallbackFactory callbacks, ILogger logger) try { - await eventListener.AddAsync(_callbacks, shapesJson).ConfigureAwait(false); + await eventListener.AddAsync(_callbackFactory, shapesJson).ConfigureAwait(false); } catch { diff --git a/src/Components/Platform/src/JSCallback.cs b/src/Components/Platform/src/JSCallback.cs index bd97c208725f..e59961c55c7f 100644 --- a/src/Components/Platform/src/JSCallback.cs +++ b/src/Components/Platform/src/JSCallback.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.Components.Platform; -// Targets of the functions that JSCallbackFactory creates. The browser can call such a function +// 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> diff --git a/src/Components/Platform/src/JSCallbackFactory.cs b/src/Components/Platform/src/JSCallbackFactory.cs index 5513a526dc01..7a361a469b33 100644 --- a/src/Components/Platform/src/JSCallbackFactory.cs +++ b/src/Components/Platform/src/JSCallbackFactory.cs @@ -33,7 +33,7 @@ public JSCallbackFactory(IJSRuntime jsRuntime) /// 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 Target)> CreateAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCallback>( + public async Task<(IJSObjectReference Function, IDisposable CallbackReference)> CreateAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCallback>( TCallback callback, string shapesJson) where TCallback : class @@ -41,16 +41,16 @@ public JSCallbackFactory(IJSRuntime jsRuntime) ObjectDisposedException.ThrowIf(_disposed, this); var module = await GetModuleAsync().ConfigureAwait(false); - var target = DotNetObjectReference.Create(callback); + var callbackReference = DotNetObjectReference.Create(callback); try { - var function = await module.InvokeAsync("createCallback", target, shapesJson).ConfigureAwait(false); - return (function, target); + var function = await module.InvokeAsync("createCallback", callbackReference, shapesJson).ConfigureAwait(false); + return (function, callbackReference); } catch { - target.Dispose(); + callbackReference.Dispose(); throw; } } diff --git a/src/Components/Platform/src/Window.cs b/src/Components/Platform/src/Window.cs index edfb19b56c13..04cb502b5036 100644 --- a/src/Components/Platform/src/Window.cs +++ b/src/Components/Platform/src/Window.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Components.Platform; public sealed class Window : IInternalAsyncDisposal { private readonly IJSRuntime _jsRuntime; - private readonly JSCallbackFactory _callbacks; + private readonly JSCallbackFactory _callbackFactory; private readonly ILogger _eventListenerLogger; private readonly EventListenerCollection _listeners; private readonly Dictionary<(Type FeatureType, string? Subkey), object> _features = []; @@ -23,7 +23,7 @@ public sealed class Window : IInternalAsyncDisposal internal Window(IJSRuntime jsRuntime, ILoggerFactory loggerFactory) { _jsRuntime = jsRuntime; - _callbacks = new JSCallbackFactory(jsRuntime); + _callbackFactory = new JSCallbackFactory(jsRuntime); _eventListenerLogger = loggerFactory.CreateLogger(); _listeners = CreateEventListenerCollection(); } @@ -52,7 +52,7 @@ public async ValueTask AddEventListenerAsync(EventType /// Creates the collection that a projection uses to add event listeners to its JavaScript object. /// internal EventListenerCollection CreateEventListenerCollection() - => new(_callbacks, _eventListenerLogger); + => new(_callbackFactory, _eventListenerLogger); private Task GetReferenceAsync() { @@ -143,6 +143,6 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() } // Features remove their listeners first, so the module is no longer needed. - await ((IInternalAsyncDisposal)_callbacks).InternalDisposeAsync().ConfigureAwait(false); + await ((IInternalAsyncDisposal)_callbackFactory).InternalDisposeAsync().ConfigureAwait(false); } } diff --git a/src/Components/Platform/src/js/Platform.ts b/src/Components/Platform/src/js/Platform.ts index e4db9a9bd42e..dad59fe9ee85 100644 --- a/src/Components/Platform/src/js/Platform.ts +++ b/src/Components/Platform/src/js/Platform.ts @@ -14,12 +14,12 @@ export interface DotNetObject { invokeMethodAsync(methodIdentifier: string, ...args: unknown[]): Promise; } -// Creates a function that calls the Invoke method of the target with one argument per shape. +// Creates a function that calls the 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. -export function createCallback(target: DotNetObject, shapesJson: string): (...args: unknown[]) => Promise { +export function createCallback(callbackReference: DotNetObject, shapesJson: string): (...args: unknown[]) => Promise { const shapes: ArgumentShape[] = JSON.parse(shapesJson); - return (...args) => target.invokeMethodAsync('Invoke', ...shapes.map((shape, index) => toDotNet(args[index], shape))); + return (...args) => callbackReference.invokeMethodAsync('Invoke', ...shapes.map((shape, index) => toDotNet(args[index], shape))); } export function toDotNet(value: unknown, shape: ArgumentShape): unknown { diff --git a/src/Components/Platform/src/js/test/Platform.test.ts b/src/Components/Platform/src/js/test/Platform.test.ts index b33f8fb8dde4..ef8a81fde6e9 100644 --- a/src/Components/Platform/src/js/test/Platform.test.ts +++ b/src/Components/Platform/src/js/test/Platform.test.ts @@ -14,7 +14,7 @@ class BrowserObject { } } -function createTarget(): DotNetObject & { calls: unknown[][] } { +function createCallbackReference(): DotNetObject & { calls: unknown[][] } { const calls: unknown[][] = []; return { calls, @@ -27,34 +27,34 @@ function createTarget(): DotNetObject & { calls: unknown[][] } { describe('createCallback', () => { test('forwards every argument that has a shape to Invoke', async () => { - const target = createTarget(); - const callback = createCallback(target, '[null, null, null]'); + const callbackReference = createCallbackReference(); + const callback = createCallback(callbackReference, '[null, null, null]'); const result = await callback('a', 2, { three: 3 }); expect(result).toBe('result'); - expect(target.calls).toEqual([['Invoke', 'a', 2, { three: 3 }]]); + expect(callbackReference.calls).toEqual([['Invoke', 'a', 2, { three: 3 }]]); }); test('drops arguments beyond the shapes and sends null for missing ones', async () => { - const target = createTarget(); + const callbackReference = createCallbackReference(); - await createCallback(target, '[null]')('a', 'b'); - await createCallback(target, '[null, null]')('a'); + await createCallback(callbackReference, '[null]')('a', 'b'); + await createCallback(callbackReference, '[null, null]')('a'); - expect(target.calls).toEqual([['Invoke', 'a'], ['Invoke', 'a', undefined]]); - expect(JSON.stringify(target.calls[1])).toBe('["Invoke","a",null]'); + 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 target = createTarget(); + 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(target, '[{"changed":null,"deleted":null}]')(event); + await createCallback(callbackReference, '[{"changed":null,"deleted":null}]')(event); - expect(JSON.stringify(target.calls[0])).toBe('["Invoke",{"changed":[{"name":"a","value":"1"}],"deleted":[{"name":"b"}]}]'); + expect(JSON.stringify(callbackReference.calls[0])).toBe('["Invoke",{"changed":[{"name":"a","value":"1"}],"deleted":[{"name":"b"}]}]'); }); }); diff --git a/src/Components/Platform/test/JSCallbackTest.cs b/src/Components/Platform/test/JSCallbackTest.cs index 2ecc9e6b873a..7a5379404744 100644 --- a/src/Components/Platform/test/JSCallbackTest.cs +++ b/src/Components/Platform/test/JSCallbackTest.cs @@ -83,11 +83,11 @@ public async Task CreatedFunctions_StayValidUntilTheCallerReleasesThem() var jsRuntime = new BrowserJSRuntime(); var factory = new JSCallbackFactory(jsRuntime); var callback = new JSCallback { Handler = _ => Task.CompletedTask }; - var (_, target) = await factory.CreateAsync(callback, "[null]"); + var (_, callbackReference) = await factory.CreateAsync(callback, "[null]"); await ((IInternalAsyncDisposal)factory).InternalDisposeAsync(); var beforeRelease = await jsRuntime.InvokeLastCallbackAsync("""["text"]"""); - target.Dispose(); + callbackReference.Dispose(); var afterRelease = await jsRuntime.InvokeLastCallbackAsync("""["text"]"""); // The module is object 1, and the factory releases only the module. From 03fa0b74ecaddae21182131289aec7f794ecb714 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Mon, 26 Oct 2026 16:08:36 +0900 Subject: [PATCH 05/17] Adapt the bridge trial to dotnet/main after the rebase Drop the Logging.Abstractions package reference, which the SDK now prunes (NU1510), and report the event demo steps through the result marker of the Cookie Store page. --- ...osoft.AspNetCore.Components.Platform.csproj | 1 - .../Components/CookieStoreDemo.razor | 18 +++++++++--------- .../Tests/CookieStoreTests.cs | 12 ++++++------ 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj index fdab97128a92..af4b75923063 100644 --- a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj +++ b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj @@ -13,7 +13,6 @@ - diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor index 61a681c4df97..62eeac43860e 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor +++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor @@ -163,13 +163,13 @@ runCount++; } - private async Task WatchChangesAsync() + private Task WatchChangesAsync() => RunAsync("Watch changes", async () => { listener = await Browser.Window.CookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, OnCookieChangeAsync); - result = "Watching changes."; - } + return "added"; + }); - private async Task WatchChangesWithSecondListenerAsync() + private Task WatchChangesWithSecondListenerAsync() => RunAsync("Watch changes with a second listener", async () => { secondListener = await Browser.Window.CookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, changeEvent => { @@ -177,18 +177,18 @@ StateHasChanged(); return Task.CompletedTask; }); - result = "Watching changes with a second listener."; - } + return "added"; + }); - private async Task UnwatchChangesAsync() + private Task UnwatchChangesAsync() => RunAsync("Stop watching changes", async () => { if (listener is not null) { await listener.DisposeAsync(); } - result = "Stopped watching changes."; - } + return "removed"; + }); // The listener runs on the renderer's dispatcher, so StateHasChanged needs no InvokeAsync. private Task OnCookieChangeAsync(CookieChangeEvent changeEvent) 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 2c9028398275..b4eca07a4d82 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs +++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs @@ -166,8 +166,8 @@ public async Task CookieStore_ReportsChangesToEachListener() 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", "Watching changes."); - await RunAsync("#watch-cookie-changes-second", "Watching changes with a second listener."); + 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"); @@ -179,17 +179,17 @@ public async Task CookieStore_ReportsChangesToEachListener() await _page.EvaluateAsync("() => { document.cookie = 'external=; max-age=0'; }"); await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync("Deleted: external"); - await RunAsync("#delete-cookie", $"Deleted: {name}"); + 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", "Stopped watching changes."); + 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", $"Found: {name}=value"); + await RunAsync("#get-cookie", $"Get: Found: {name}=value"); await Expect(_page.Locator("#cookie-change")).ToHaveTextAsync($"Deleted: {name}"); - await RunAsync("#delete-cookie", $"Deleted: {name}"); + await RunAsync("#delete-cookie", $"Delete: {name}"); } } From 65b950b055768267e4fe20c450f4fbb0aa1d68b1 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Mon, 26 Oct 2026 17:30:37 +0900 Subject: [PATCH 06/17] Fix the lifecycle problems found in the event listener review Keep the renderer's synchronization context while adding and removing listeners, because their state is not locked. Release the function and the callback reference even when removeEventListener fails, and let scope disposal continue with the other listeners and log the failure. Release a module that arrives after disposal and stop before createCallback. BrowserJSRuntime can now complete calls on the thread pool and fail or hold a call, which the new EventListenerLifecycleTest relies on. --- src/Components/Platform/src/CookieStore.cs | 7 +- src/Components/Platform/src/EventListener.cs | 46 +++--- .../Platform/src/EventListenerCollection.cs | 22 ++- .../Platform/src/JSCallbackFactory.cs | 22 ++- src/Components/Platform/src/Window.cs | 9 +- .../Platform/test/BrowserJSRuntime.cs | 69 ++++++++- .../Platform/test/CookieStoreTest.cs | 22 --- .../test/EventListenerLifecycleTest.cs | 146 ++++++++++++++++++ .../Platform/test/JSCallbackTest.cs | 17 ++ ...spNetCore.Components.Platform.Tests.csproj | 1 + .../Platform/test/RecordingLoggerFactory.cs | 30 ++++ 11 files changed, 333 insertions(+), 58 deletions(-) create mode 100644 src/Components/Platform/test/EventListenerLifecycleTest.cs create mode 100644 src/Components/Platform/test/RecordingLoggerFactory.cs diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index 67c63ba54ad7..af6543373d20 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -194,9 +194,10 @@ public async ValueTask AddEventListenerAsync(EventType ArgumentNullException.ThrowIfNull(type); ArgumentNullException.ThrowIfNull(listener); - var cookieStore = await GetReferenceAsync().ConfigureAwait(false); + // 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).ConfigureAwait(false); + return await type.AddListenerAsync(_listeners, cookieStore, this, listener); } async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() @@ -209,7 +210,7 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() _disposed = true; // Listeners need the cookie store reference to remove themselves, so they go first. - await ((IInternalAsyncDisposal)_listeners).InternalDisposeAsync().ConfigureAwait(false); + 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 index 3f9cdd896f3c..7bb84fd7f0b8 100644 --- a/src/Components/Platform/src/EventListener.cs +++ b/src/Components/Platform/src/EventListener.cs @@ -34,16 +34,16 @@ public EventListener(EventListenerCollection owner, IJSObjectReference target, s public async Task AddAsync(JSCallbackFactory callbackFactory, string shapesJson) { var callback = new JSCallback { Handler = InvokeListenerAsync }; - (_function, _callbackReference) = await callbackFactory.CreateAsync(callback, shapesJson).ConfigureAwait(false); + (_function, _callbackReference) = await callbackFactory.CreateAsync(callback, shapesJson); // Disposal can run while the function is being created, and then nothing else releases it. if (_removed) { - await ReleaseAsync().ConfigureAwait(false); + await ReleaseAsync(); throw new ObjectDisposedException(GetType().Name); } - await _target.InvokeVoidAsync("addEventListener", _type, _function).ConfigureAwait(false); + await _target.InvokeVoidAsync("addEventListener", _type, _function); } public async ValueTask DisposeAsync() @@ -56,7 +56,7 @@ public async ValueTask DisposeAsync() _removed = true; _owner.Remove(this); - await ReleaseAsync().ConfigureAwait(false); + await ReleaseAsync(); } private async Task InvokeListenerAsync(TEvent value) @@ -79,23 +79,33 @@ private async Task InvokeListenerAsync(TEvent value) private async ValueTask ReleaseAsync() { - if (_function is { } function) - { - _function = null; + var function = _function; + var callbackReference = _callbackReference; + _function = null; + _callbackReference = null; - try - { - await _target.InvokeVoidAsync("removeEventListener", _type, function).ConfigureAwait(false); - } - catch (JSDisconnectedException) + // A failed removal still releases both references, and then reaches the caller. + try + { + if (function is not null) { - // The page is already gone, so nothing can call the listener. + try + { + await _target.InvokeVoidAsync("removeEventListener", _type, function); + } + catch (JSDisconnectedException) + { + // The page is already gone, so nothing can call the listener. + } + finally + { + await function.DisposeAsync(); + } } - - await function.DisposeAsync().ConfigureAwait(false); } - - _callbackReference?.Dispose(); - _callbackReference = null; + finally + { + callbackReference?.Dispose(); + } } } diff --git a/src/Components/Platform/src/EventListenerCollection.cs b/src/Components/Platform/src/EventListenerCollection.cs index 9f29c08a277d..044b9fb326e0 100644 --- a/src/Components/Platform/src/EventListenerCollection.cs +++ b/src/Components/Platform/src/EventListenerCollection.cs @@ -41,11 +41,12 @@ public EventListenerCollection(JSCallbackFactory callbackFactory, ILogger logger try { - await eventListener.AddAsync(_callbackFactory, shapesJson).ConfigureAwait(false); + await eventListener.AddAsync(_callbackFactory, shapesJson); } catch { - await eventListener.DisposeAsync().ConfigureAwait(false); + // The exception of the failed addition is the useful one. + await TryDisposeAsync(eventListener); throw; } @@ -65,12 +66,27 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() foreach (var listener in _listeners.ToArray()) { - await listener.DisposeAsync().ConfigureAwait(false); + await TryDisposeAsync(listener); + } + } + + private 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/JSCallbackFactory.cs b/src/Components/Platform/src/JSCallbackFactory.cs index 7a361a469b33..bd817eb87a64 100644 --- a/src/Components/Platform/src/JSCallbackFactory.cs +++ b/src/Components/Platform/src/JSCallbackFactory.cs @@ -40,12 +40,12 @@ public JSCallbackFactory(IJSRuntime jsRuntime) { ObjectDisposedException.ThrowIf(_disposed, this); - var module = await GetModuleAsync().ConfigureAwait(false); + var module = await GetModuleAsync(); var callbackReference = DotNetObjectReference.Create(callback); try { - var function = await module.InvokeAsync("createCallback", callbackReference, shapesJson).ConfigureAwait(false); + var function = await module.InvokeAsync("createCallback", callbackReference, shapesJson); return (function, callbackReference); } catch @@ -67,7 +67,7 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() // Functions created from the module keep working after the module reference is released. if (_moduleTask is { IsCompletedSuccessfully: true } moduleTask) { - await moduleTask.Result.DisposeAsync().ConfigureAwait(false); + await moduleTask.Result.DisposeAsync(); } } @@ -75,9 +75,23 @@ private Task GetModuleAsync() { if (_moduleTask is null || _moduleTask.IsFaulted || _moduleTask.IsCanceled) { - _moduleTask = _jsRuntime.InvokeAsync("import", ModulePath).AsTask(); + _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/Window.cs b/src/Components/Platform/src/Window.cs index 04cb502b5036..53ef9d9f724a 100644 --- a/src/Components/Platform/src/Window.cs +++ b/src/Components/Platform/src/Window.cs @@ -43,9 +43,10 @@ public async ValueTask AddEventListenerAsync(EventType ArgumentNullException.ThrowIfNull(type); ArgumentNullException.ThrowIfNull(listener); - var window = await GetReferenceAsync().ConfigureAwait(false); + // Adding and removing listeners changes unlocked state, so these awaits keep the renderer's synchronization context. + var window = await GetReferenceAsync(); - return await type.AddListenerAsync(_listeners, window, this, listener).ConfigureAwait(false); + return await type.AddListenerAsync(_listeners, window, this, listener); } /// @@ -123,7 +124,7 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() _disposed = true; // Listeners need the window reference to remove themselves, so they go first. - await ((IInternalAsyncDisposal)_listeners).InternalDisposeAsync().ConfigureAwait(false); + 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) @@ -143,6 +144,6 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() } // Features remove their listeners first, so the module is no longer needed. - await ((IInternalAsyncDisposal)_callbackFactory).InternalDisposeAsync().ConfigureAwait(false); + await ((IInternalAsyncDisposal)_callbackFactory).InternalDisposeAsync(); } } diff --git a/src/Components/Platform/test/BrowserJSRuntime.cs b/src/Components/Platform/test/BrowserJSRuntime.cs index 17347132450d..716f1faafd94 100644 --- a/src/Components/Platform/test/BrowserJSRuntime.cs +++ b/src/Components/Platform/test/BrowserJSRuntime.cs @@ -13,13 +13,36 @@ namespace Microsoft.AspNetCore.Components.Platform.Tests; 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) + { + _identifiersToHold.Remove(identifier); + + foreach (var held in _heldCalls.Where(held => held.Identifier == identifier).ToArray()) + { + _heldCalls.Remove(held); + Complete(held.AsyncHandle, succeeded: true, held.Result); + } + } + // Calls the Invoke method of the DotNetObjectReference that the last createCallback call received. public Task InvokeLastCallbackAsync(string argsJson) => InvokeCallbackAsync(CallsTo("createCallback").Count() - 1, argsJson); @@ -41,16 +64,35 @@ public async Task InvokeCallbackAsync(int index, string protected override void BeginInvokeJS(in JSInvocationInfo invocationInfo) { - Calls.Add(new BrowserCall(invocationInfo.Identifier, invocationInfo.CallType, invocationInfo.TargetInstanceId, invocationInfo.ArgsJson)); + 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 (invocationInfo.AsyncHandle != 0) + if (_identifiersToHold.Contains(invocationInfo.Identifier)) { - DotNetDispatcher.EndInvokeJS(this, $"[{invocationInfo.AsyncHandle},true,{result}]"); + _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) @@ -61,6 +103,25 @@ protected override void EndInvokeDotNet(DotNetInvocationInfo invocationInfo, in _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); +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 1a9d37e70e31..004e3e904551 100644 --- a/src/Components/Platform/test/CookieStoreTest.cs +++ b/src/Components/Platform/test/CookieStoreTest.cs @@ -461,28 +461,6 @@ private static ServiceProvider CreateServiceProvider(IJSRuntime jsRuntime, ILogg return services.BuildServiceProvider(); } - private sealed record LogEntry(LogLevel Level, EventId EventId, Exception? Exception); - - private 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() - { - } - } - private static void AssertInvocation(Invocation invocation, string identifier, params object?[] arguments) { Assert.Equal(identifier, invocation.Identifier); diff --git a/src/Components/Platform/test/EventListenerLifecycleTest.cs b/src/Components/Platform/test/EventListenerLifecycleTest.cs new file mode 100644 index 000000000000..a1f6c5f65756 --- /dev/null +++ b/src/Components/Platform/test/EventListenerLifecycleTest.cs @@ -0,0 +1,146 @@ +// 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)); + } + + 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 index 7a5379404744..063ec4132c9b 100644 --- a/src/Components/Platform/test/JSCallbackTest.cs +++ b/src/Components/Platform/test/JSCallbackTest.cs @@ -96,4 +96,21 @@ public async Task CreatedFunctions_StayValidUntilTheCallerReleasesThem() 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/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() + { + } +} From 0342221992d90c5365d1309d1e0e03a1d8a03f79 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Tue, 27 Oct 2026 14:18:04 +0900 Subject: [PATCH 07/17] Remove event listeners when a CancellationToken is canceled AddEventListenerAsync on Window and CookieStore takes an optional CancellationToken, the .NET form of the signal option of addEventListener. Canceling it removes the listener at any time: before the call nothing is added, during the addition the listener is removed when the addition ends and the call throws OperationCanceledException with the token, and after it the listener is removed as disposing the handle does. A component can then pass a token that it cancels in Dispose, and needs no handle. The token callback posts the removal to the context that added the listener itself. useSynchronizationContext: true would call Send, which blocks forever when Cancel runs on the renderer's own context. The second listener of the Cookie Store demo now uses a token. --- src/Components/Platform/src/CookieStore.cs | 8 +- src/Components/Platform/src/EventListener.cs | 39 +++++- .../Platform/src/EventListenerCollection.cs | 25 +++- src/Components/Platform/src/EventType.cs | 14 +-- .../Platform/src/PublicAPI.Unshipped.txt | 4 +- src/Components/Platform/src/Window.cs | 8 +- .../Platform/test/BrowserJSRuntime.cs | 4 +- .../test/EventListenerLifecycleTest.cs | 119 ++++++++++++++++++ .../Components/CookieStoreDemo.razor | 31 +++-- .../Tests/CookieStoreTests.cs | 8 ++ 10 files changed, 226 insertions(+), 34 deletions(-) diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index af6543373d20..043ad10a5366 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -181,23 +181,27 @@ public async ValueTask DeleteAsync(CookieStoreDeleteOptions options) /// 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. + /// 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) + public async ValueTask AddEventListenerAsync(EventType type, Func listener, CancellationToken cancellationToken = default) { 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); + return await type.AddListenerAsync(_listeners, cookieStore, this, listener, cancellationToken); } async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() diff --git a/src/Components/Platform/src/EventListener.cs b/src/Components/Platform/src/EventListener.cs index 7bb84fd7f0b8..0e8286490f1a 100644 --- a/src/Components/Platform/src/EventListener.cs +++ b/src/Components/Platform/src/EventListener.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Components.Platform; /// -/// One listener added with addEventListener. Disposing it removes the listener. +/// One listener added with addEventListener. Disposing it or canceling its token removes the listener. /// internal sealed class EventListener<[DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] TEvent> : IAsyncDisposable { @@ -17,17 +17,21 @@ internal sealed class EventListener<[DynamicallyAccessedMembers(LinkerFlags.Json 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, ILogger logger) + 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; } @@ -37,15 +41,26 @@ public async Task AddAsync(JSCallbackFactory callbackFactory, string shapesJson) (_function, _callbackReference) = await callbackFactory.CreateAsync(callback, shapesJson); // Disposal can run while the function is being created, and then nothing else releases it. - if (_removed) + 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) @@ -54,15 +69,31 @@ public async ValueTask DisposeAsync() } _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) + if (_removed || _cancellationToken.IsCancellationRequested) { return; } diff --git a/src/Components/Platform/src/EventListenerCollection.cs b/src/Components/Platform/src/EventListenerCollection.cs index 044b9fb326e0..ff0c8b0da2b1 100644 --- a/src/Components/Platform/src/EventListenerCollection.cs +++ b/src/Components/Platform/src/EventListenerCollection.cs @@ -32,24 +32,41 @@ public EventListenerCollection(JSCallbackFactory callbackFactory, ILogger logger IJSObjectReference target, string type, string shapesJson, - Func listener) + Func listener, + CancellationToken cancellationToken) { ObjectDisposedException.ThrowIf(_disposed, this); + cancellationToken.ThrowIfCancellationRequested(); - var eventListener = new EventListener(this, target, type, listener, _logger); + var eventListener = new EventListener(this, target, type, listener, cancellationToken, _logger); _listeners.Add(eventListener); try { await eventListener.AddAsync(_callbackFactory, shapesJson); } - catch + 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(); + } + + eventListener.RemoveWhenCanceled(); return eventListener; } @@ -70,7 +87,7 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() } } - private async ValueTask TryDisposeAsync(IAsyncDisposable listener) + internal async ValueTask TryDisposeAsync(IAsyncDisposable listener) { try { diff --git a/src/Components/Platform/src/EventType.cs b/src/Components/Platform/src/EventType.cs index 157dcea120ca..e098ededadc8 100644 --- a/src/Components/Platform/src/EventType.cs +++ b/src/Components/Platform/src/EventType.cs @@ -14,11 +14,11 @@ namespace Microsoft.AspNetCore.Components.Platform; /// The type of the event object. public sealed class EventType where TTarget : class { - private readonly Func, Task> _addListenerAsync; + private readonly Func, CancellationToken, Task> _addListenerAsync; internal EventType( string name, - Func, Task> addListenerAsync) + Func, CancellationToken, Task> addListenerAsync) { Name = name; _addListenerAsync = addListenerAsync; @@ -29,8 +29,8 @@ internal EventType( /// public string Name { get; } - internal Task AddListenerAsync(EventListenerCollection listeners, IJSObjectReference target, TTarget owner, Func listener) - => _addListenerAsync(listeners, target, owner, listener); + internal Task AddListenerAsync(EventListenerCollection listeners, IJSObjectReference target, TTarget owner, Func listener, CancellationToken cancellationToken) + => _addListenerAsync(listeners, target, owner, listener, cancellationToken); } /// @@ -48,7 +48,7 @@ internal static class EventTypes string name, string shapesJson) where TTarget : class - => new(name, (listeners, target, _, listener) => listeners.AddAsync(target, name, shapesJson, listener)); + => 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, @@ -62,6 +62,6 @@ internal static class EventTypes string shapesJson, Func convert) where TTarget : class - => new(name, (listeners, target, owner, listener) => - listeners.AddAsync(target, name, shapesJson, payload => listener(convert(owner, payload)))); + => 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/PublicAPI.Unshipped.txt b/src/Components/Platform/src/PublicAPI.Unshipped.txt index c93d70b73365..81e8ea305753 100644 --- a/src/Components/Platform/src/PublicAPI.Unshipped.txt +++ b/src/Components/Platform/src/PublicAPI.Unshipped.txt @@ -34,7 +34,7 @@ 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.Tasks.ValueTask +Microsoft.AspNetCore.Components.Platform.CookieStore.AddEventListenerAsync(Microsoft.AspNetCore.Components.Platform.EventType! type, System.Func! listener, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> 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!> @@ -142,7 +142,7 @@ 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.Tasks.ValueTask +Microsoft.AspNetCore.Components.Platform.Window.AddEventListenerAsync(Microsoft.AspNetCore.Components.Platform.EventType! type, System.Func! listener, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> 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! diff --git a/src/Components/Platform/src/Window.cs b/src/Components/Platform/src/Window.cs index 53ef9d9f724a..c4d5241f6ad8 100644 --- a/src/Components/Platform/src/Window.cs +++ b/src/Components/Platform/src/Window.cs @@ -32,21 +32,25 @@ internal Window(IJSRuntime jsRuntime, ILoggerFactory 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. + /// 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 . - public async ValueTask AddEventListenerAsync(EventType type, Func listener) + /// was canceled before the listener was added. + public async ValueTask AddEventListenerAsync(EventType type, Func listener, CancellationToken cancellationToken = default) { 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(); - return await type.AddListenerAsync(_listeners, window, this, listener); + return await type.AddListenerAsync(_listeners, window, this, listener, cancellationToken); } /// diff --git a/src/Components/Platform/test/BrowserJSRuntime.cs b/src/Components/Platform/test/BrowserJSRuntime.cs index 716f1faafd94..b5da1763e786 100644 --- a/src/Components/Platform/test/BrowserJSRuntime.cs +++ b/src/Components/Platform/test/BrowserJSRuntime.cs @@ -32,14 +32,14 @@ internal sealed class BrowserJSRuntime : JSRuntime // Keeps the calls to the identifier pending until ReleaseHeldCalls. public void HoldCallsTo(string identifier) => _identifiersToHold.Add(identifier); - public void ReleaseHeldCalls(string 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: true, held.Result); + Complete(held.AsyncHandle, succeeded, succeeded ? held.Result : $"\"{identifier} failed.\""); } } diff --git a/src/Components/Platform/test/EventListenerLifecycleTest.cs b/src/Components/Platform/test/EventListenerLifecycleTest.cs index a1f6c5f65756..1b8a3c29faf8 100644 --- a/src/Components/Platform/test/EventListenerLifecycleTest.cs +++ b/src/Components/Platform/test/EventListenerLifecycleTest.cs @@ -130,6 +130,125 @@ public async Task ScopeDisposal_DuringTheModuleImport_ReleasesTheModuleThatArriv 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(); diff --git a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor index 62eeac43860e..9185d632d831 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor +++ b/src/Components/Platform/testassets/PlatformTestApp.Client/Components/CookieStoreDemo.razor @@ -34,6 +34,7 @@ + @@ -50,7 +51,8 @@ private string change = "No change has been reported."; private string secondChange = "No change has been reported."; private IAsyncDisposable? listener; - private IAsyncDisposable? secondListener; + // 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 () => { @@ -171,12 +173,15 @@ private Task WatchChangesWithSecondListenerAsync() => RunAsync("Watch changes with a second listener", async () => { - secondListener = await Browser.Window.CookieStore.AddEventListenerAsync(CookieStore.ChangeEvent, changeEvent => - { - secondChange = Describe(changeEvent); - StateHasChanged(); - return Task.CompletedTask; - }); + await Browser.Window.CookieStore.AddEventListenerAsync( + CookieStore.ChangeEvent, + changeEvent => + { + secondChange = Describe(changeEvent); + StateHasChanged(); + return Task.CompletedTask; + }, + secondListenerCancellation.Token); return "added"; }); @@ -190,6 +195,12 @@ 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) { @@ -213,10 +224,8 @@ await listener.DisposeAsync(); } - if (secondListener is not null) - { - await secondListener.DisposeAsync(); - } + secondListenerCancellation.Cancel(); + secondListenerCancellation.Dispose(); } private static string Format(CookieListItem? cookie) 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 b4eca07a4d82..4c8c05405423 100644 --- a/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs +++ b/src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/CookieStoreTests.cs @@ -190,6 +190,14 @@ public async Task CookieStore_ReportsChangesToEachListener() 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}"); } } From 0c4b0ae3df9ace1cd9fffa0c89c6985fce0e0515 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Tue, 27 Oct 2026 15:40:30 +0900 Subject: [PATCH 08/17] Take the CancellationToken in an overload, not as an optional parameter AddEventListenerAsync on Window and CookieStore now has an overload without a token and one with a required token, as the package maps other optional parameters. An optional token would conflict with RS0026 and RS0027 when an overload for AddEventListenerOptions such as once is added later. --- src/Components/Platform/src/CookieStore.cs | 16 +++++++++++++++- .../Platform/src/PublicAPI.Unshipped.txt | 6 ++++-- src/Components/Platform/src/Window.cs | 15 ++++++++++++++- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index 043ad10a5366..2463a7afb6aa 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -177,6 +177,20 @@ 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. + /// + /// 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. @@ -192,7 +206,7 @@ public async ValueTask DeleteAsync(CookieStoreDeleteOptions options) /// 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 = default) + public async ValueTask AddEventListenerAsync(EventType type, Func listener, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(type); ArgumentNullException.ThrowIfNull(listener); diff --git a/src/Components/Platform/src/PublicAPI.Unshipped.txt b/src/Components/Platform/src/PublicAPI.Unshipped.txt index 81e8ea305753..bb506b142a1d 100644 --- a/src/Components/Platform/src/PublicAPI.Unshipped.txt +++ b/src/Components/Platform/src/PublicAPI.Unshipped.txt @@ -34,7 +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 = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +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!> @@ -142,7 +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 = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +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! diff --git a/src/Components/Platform/src/Window.cs b/src/Components/Platform/src/Window.cs index c4d5241f6ad8..6928c8f95b91 100644 --- a/src/Components/Platform/src/Window.cs +++ b/src/Components/Platform/src/Window.cs @@ -28,6 +28,19 @@ internal Window(IJSRuntime jsRuntime, ILoggerFactory loggerFactory) _listeners = CreateEventListenerCollection(); } + /// + /// 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. + /// + /// 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. @@ -41,7 +54,7 @@ internal Window(IJSRuntime jsRuntime, ILoggerFactory loggerFactory) /// 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 = default) + public async ValueTask AddEventListenerAsync(EventType type, Func listener, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(type); ArgumentNullException.ThrowIfNull(listener); From f45eecba3d7fbd32fe5ce2d9b696e7eb2648b69d Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Fri, 6 Nov 2026 12:08:30 +0900 Subject: [PATCH 09/17] Document independent listener registrations and create Window event parts on first use The XML docs of AddEventListenerAsync on Window and CookieStore now say that each call creates its own registration. Window creates the JS callback factory and its listener collection when the first listener is added, so an app that adds no listener pays nothing. --- src/Components/Platform/src/CookieStore.cs | 4 +++ src/Components/Platform/src/Window.cs | 30 +++++++++++++++------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/src/Components/Platform/src/CookieStore.cs b/src/Components/Platform/src/CookieStore.cs index 2463a7afb6aa..7315c498e2c9 100644 --- a/src/Components/Platform/src/CookieStore.cs +++ b/src/Components/Platform/src/CookieStore.cs @@ -181,6 +181,8 @@ public async ValueTask DeleteAsync(CookieStoreDeleteOptions options) /// 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 . @@ -195,6 +197,8 @@ public ValueTask AddEventListenerAsync(EventType removes the listener, as disposing the returned object does. /// /// The type of the event object. diff --git a/src/Components/Platform/src/Window.cs b/src/Components/Platform/src/Window.cs index 6928c8f95b91..d889b3d2425b 100644 --- a/src/Components/Platform/src/Window.cs +++ b/src/Components/Platform/src/Window.cs @@ -13,9 +13,9 @@ namespace Microsoft.AspNetCore.Components.Platform; public sealed class Window : IInternalAsyncDisposal { private readonly IJSRuntime _jsRuntime; - private readonly JSCallbackFactory _callbackFactory; - private readonly ILogger _eventListenerLogger; - private readonly EventListenerCollection _listeners; + private readonly ILoggerFactory _loggerFactory; + private JSCallbackFactory? _callbackFactory; + private EventListenerCollection? _listeners; private readonly Dictionary<(Type FeatureType, string? Subkey), object> _features = []; private Task? _referenceTask; private bool _disposed; @@ -23,15 +23,15 @@ public sealed class Window : IInternalAsyncDisposal internal Window(IJSRuntime jsRuntime, ILoggerFactory loggerFactory) { _jsRuntime = jsRuntime; - _callbackFactory = new JSCallbackFactory(jsRuntime); - _eventListenerLogger = loggerFactory.CreateLogger(); - _listeners = CreateEventListenerCollection(); + _loggerFactory = 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. @@ -45,6 +45,8 @@ public ValueTask AddEventListenerAsync(EventType removes the listener, as disposing the returned object does. /// /// The type of the event object. @@ -63,6 +65,10 @@ public async ValueTask AddEventListenerAsync(EventType // 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); + _listeners ??= CreateEventListenerCollection(); + return await type.AddListenerAsync(_listeners, window, this, listener, cancellationToken); } @@ -70,7 +76,7 @@ public async ValueTask AddEventListenerAsync(EventType /// Creates the collection that a projection uses to add event listeners to its JavaScript object. /// internal EventListenerCollection CreateEventListenerCollection() - => new(_callbackFactory, _eventListenerLogger); + => new(_callbackFactory ??= new JSCallbackFactory(_jsRuntime), _loggerFactory.CreateLogger()); private Task GetReferenceAsync() { @@ -141,7 +147,10 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() _disposed = true; // Listeners need the window reference to remove themselves, so they go first. - await ((IInternalAsyncDisposal)_listeners).InternalDisposeAsync(); + if (_listeners is not null) + { + 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) @@ -161,6 +170,9 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() } // Features remove their listeners first, so the module is no longer needed. - await ((IInternalAsyncDisposal)_callbackFactory).InternalDisposeAsync(); + if (_callbackFactory is not null) + { + await ((IInternalAsyncDisposal)_callbackFactory).InternalDisposeAsync(); + } } } From f24b0a79a6c24ddc595131cb4e11ba29b1848ec2 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Fri, 6 Nov 2026 13:06:35 +0900 Subject: [PATCH 10/17] Keep the Window event parts out of trimmed apps that add no listener Window held them in fields of their own types, so disposal kept the types. Typing the fields as IInternalAsyncDisposal lets the trimmer remove them. --- src/Components/Platform/src/Window.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Components/Platform/src/Window.cs b/src/Components/Platform/src/Window.cs index d889b3d2425b..e81313648c5e 100644 --- a/src/Components/Platform/src/Window.cs +++ b/src/Components/Platform/src/Window.cs @@ -14,8 +14,9 @@ public sealed class Window : IInternalAsyncDisposal { private readonly IJSRuntime _jsRuntime; private readonly ILoggerFactory _loggerFactory; - private JSCallbackFactory? _callbackFactory; - private EventListenerCollection? _listeners; + // Typed as the interface, so that disposal does not keep these types in an app that never adds a listener. + private IInternalAsyncDisposal? _callbackFactory; + private IInternalAsyncDisposal? _listeners; private readonly Dictionary<(Type FeatureType, string? Subkey), object> _features = []; private Task? _referenceTask; private bool _disposed; @@ -67,16 +68,16 @@ public async ValueTask AddEventListenerAsync(EventType // The collection and the module loader are created here, so an app that adds no listener pays nothing. ObjectDisposedException.ThrowIf(_disposed, this); - _listeners ??= CreateEventListenerCollection(); + var listeners = (EventListenerCollection)(_listeners ??= CreateEventListenerCollection()); - return await type.AddListenerAsync(_listeners, window, this, listener, cancellationToken); + return await type.AddListenerAsync(listeners, window, this, listener, cancellationToken); } /// /// Creates the collection that a projection uses to add event listeners to its JavaScript object. /// internal EventListenerCollection CreateEventListenerCollection() - => new(_callbackFactory ??= new JSCallbackFactory(_jsRuntime), _loggerFactory.CreateLogger()); + => new((JSCallbackFactory)(_callbackFactory ??= new JSCallbackFactory(_jsRuntime)), _loggerFactory.CreateLogger()); private Task GetReferenceAsync() { @@ -149,7 +150,7 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() // Listeners need the window reference to remove themselves, so they go first. if (_listeners is not null) { - await ((IInternalAsyncDisposal)_listeners).InternalDisposeAsync(); + await _listeners.InternalDisposeAsync(); } // Don't wait for a pending acquisition. It could hold up scope disposal until the JS interop timeout. @@ -172,7 +173,7 @@ async ValueTask IInternalAsyncDisposal.InternalDisposeAsync() // Features remove their listeners first, so the module is no longer needed. if (_callbackFactory is not null) { - await ((IInternalAsyncDisposal)_callbackFactory).InternalDisposeAsync(); + await _callbackFactory.InternalDisposeAsync(); } } } From 621bf279c3d882d691310044ca814aa4f924c2d5 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Fri, 6 Nov 2026 13:33:40 +0900 Subject: [PATCH 11/17] Test that an any-typed event value reaches a JsonElement through Blazor interop A test-only key for the window message event (made with the internal EventTypes helper, so the test app gets InternalsVisibleTo) shows that nested JSON values and markers for Date and Map arrive in both render modes. --- ...soft.AspNetCore.Components.Platform.csproj | 1 + .../Components/MessageEventDemo.razor | 45 +++++++++++ .../Pages/MessageEventWebAssembly.razor | 4 + .../Tests/MessageEventTests.cs | 78 +++++++++++++++++++ .../Components/Pages/MessageEventServer.razor | 4 + 5 files changed, 132 insertions(+) create mode 100644 src/Components/Platform/testassets/PlatformTestApp.Client/Components/MessageEventDemo.razor create mode 100644 src/Components/Platform/testassets/PlatformTestApp.Client/Pages/MessageEventWebAssembly.razor create mode 100644 src/Components/Platform/testassets/PlatformTestApp.E2E.Tests/Tests/MessageEventTests.cs create mode 100644 src/Components/Platform/testassets/PlatformTestApp/Components/Pages/MessageEventServer.razor diff --git a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj index af4b75923063..77c52da9c39f 100644 --- a/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj +++ b/src/Components/Platform/src/Microsoft.AspNetCore.Components.Platform.csproj @@ -23,6 +23,7 @@ + + + + + From ead6ef6bdafa1090c25f92b72cf95ab31f3b959b Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Fri, 6 Nov 2026 16:30:04 +0900 Subject: [PATCH 13/17] Reject a listener whose addition ends after scope disposal --- src/Components/Platform/src/EventListenerCollection.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Components/Platform/src/EventListenerCollection.cs b/src/Components/Platform/src/EventListenerCollection.cs index ff0c8b0da2b1..2837f4b28f14 100644 --- a/src/Components/Platform/src/EventListenerCollection.cs +++ b/src/Components/Platform/src/EventListenerCollection.cs @@ -66,6 +66,9 @@ public EventListenerCollection(JSCallbackFactory callbackFactory, ILogger logger 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; } From 5d7bae37e02c7704bd0fad8c1af8dc671208aeaa Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Mon, 9 Nov 2026 11:29:25 +0900 Subject: [PATCH 14/17] Remove the unused two- and three-argument JSCallback types --- src/Components/Platform/src/JSCallback.cs | 21 ------------------ .../Platform/test/JSCallbackTest.cs | 22 +++++++++---------- 2 files changed, 10 insertions(+), 33 deletions(-) diff --git a/src/Components/Platform/src/JSCallback.cs b/src/Components/Platform/src/JSCallback.cs index e59961c55c7f..1c495b8af98f 100644 --- a/src/Components/Platform/src/JSCallback.cs +++ b/src/Components/Platform/src/JSCallback.cs @@ -17,24 +17,3 @@ internal sealed class JSCallback<[DynamicallyAccessedMembers(LinkerFlags.JsonSer [JSInvokable] public Task Invoke(T1 arg1) => Handler?.Invoke(arg1) ?? Task.CompletedTask; } - -internal sealed class JSCallback< - [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T1, - [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T2> -{ - public Func? Handler { get; set; } - - [JSInvokable] - public Task Invoke(T1 arg1, T2 arg2) => Handler?.Invoke(arg1, arg2) ?? Task.CompletedTask; -} - -internal sealed class JSCallback< - [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T1, - [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T2, - [DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] T3> -{ - public Func? Handler { get; set; } - - [JSInvokable] - public Task Invoke(T1 arg1, T2 arg2, T3 arg3) => Handler?.Invoke(arg1, arg2, arg3) ?? Task.CompletedTask; -} diff --git a/src/Components/Platform/test/JSCallbackTest.cs b/src/Components/Platform/test/JSCallbackTest.cs index 063ec4132c9b..029bdd200324 100644 --- a/src/Components/Platform/test/JSCallbackTest.cs +++ b/src/Components/Platform/test/JSCallbackTest.cs @@ -17,36 +17,34 @@ public async Task CreateAsync_ImportsTheModuleOnceAndPassesTheShapes() var factory = new JSCallbackFactory(jsRuntime); await factory.CreateAsync(new JSCallback(), "[null]"); - 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},"[null,{}]"]"""], + ["""[{"__dotNetObject":1},"[null]"]""", """[{"__dotNetObject":2},"[{}]"]"""], jsRuntime.CallsTo("createCallback").Select(call => call.ArgsJson)); } [Fact] - public async Task Invoke_PassesEachArgumentToTheHandler() + public async Task Invoke_PassesTheArgumentToTheHandler() { var jsRuntime = new BrowserJSRuntime(); var factory = new JSCallbackFactory(jsRuntime); - var callback = new JSCallback(); - (string, int, CookieListItem)? received = null; - callback.Handler = (text, number, cookie) => + var callback = new JSCallback(); + CookieListItem? received = null; + callback.Handler = cookie => { - received = (text, number, cookie); + received = cookie; return Task.CompletedTask; }; - await factory.CreateAsync(callback, "[null,null,null]"); + await factory.CreateAsync(callback, "[null]"); - var result = await jsRuntime.InvokeLastCallbackAsync("""["text",42,{"name":"a","value":"1"}]"""); + var result = await jsRuntime.InvokeLastCallbackAsync("""[{"name":"a","value":"1"}]"""); Assert.True(result.Success, result.Exception?.ToString()); - Assert.Equal("text", received?.Item1); - Assert.Equal(42, received?.Item2); - Assert.Equal(("a", "1"), (received?.Item3.Name, received?.Item3.Value)); + Assert.Equal(("a", "1"), (received?.Name, received?.Value)); } [Fact] From 470c2ddb9f9687a76ab9ed6712bc51f6ae729364 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Mon, 9 Nov 2026 11:43:21 +0900 Subject: [PATCH 15/17] Restore the googletest submodule pointer to main --- src/submodules/googletest | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/submodules/googletest b/src/submodules/googletest index cd8e73f06712..a8380b01a25e 160000 --- a/src/submodules/googletest +++ b/src/submodules/googletest @@ -1 +1 @@ -Subproject commit cd8e73f067129f8489e35c7b51c7a68552b289d2 +Subproject commit a8380b01a25ebdb130097b607b3afed2a58d04ba From ed515f8e9903273ab6d9ce7deb78c8bc325311ac Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Mon, 9 Nov 2026 11:45:23 +0900 Subject: [PATCH 16/17] Clarify the comments in Platform.ts --- src/Components/Platform/src/js/Platform.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Components/Platform/src/js/Platform.ts b/src/Components/Platform/src/js/Platform.ts index dad59fe9ee85..ff87ca1b8553 100644 --- a/src/Components/Platform/src/js/Platform.ts +++ b/src/Components/Platform/src/js/Platform.ts @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// What one argument sends to .NET. null sends the whole value. An object sends only the named +// 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 }; @@ -14,8 +14,9 @@ export interface DotNetObject { invokeMethodAsync(methodIdentifier: string, ...args: unknown[]): Promise; } -// Creates a function that calls the Invoke method of the callback reference with one argument per shape. +// 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); From be1b24f70637c2aa633546b90f3ea1a851f4d5e9 Mon Sep 17 00:00:00 2001 From: jsakamotoIGJP Date: Mon, 9 Nov 2026 13:32:19 +0900 Subject: [PATCH 17/17] Remove a stale mention of other arities --- src/Components/Platform/src/JSCallbackFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Components/Platform/src/JSCallbackFactory.cs b/src/Components/Platform/src/JSCallbackFactory.cs index bd817eb87a64..676637026518 100644 --- a/src/Components/Platform/src/JSCallbackFactory.cs +++ b/src/Components/Platform/src/JSCallbackFactory.cs @@ -25,7 +25,7 @@ public JSCallbackFactory(IJSRuntime jsRuntime) /// /// Creates a JavaScript function that calls . /// - /// The or other arity to call. + /// The to call. /// /// A JSON array with one ArgumentShape (see js/Platform.ts) per parameter of . ///