Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,13 @@ public static BrowserOptions GetBrowserOptions(HttpContext context)

if (!context.Items.TryGetValue(Key, out var result))
{
// Seed from endpoint metadata if available
var metadataOptions = context.GetEndpoint()?.Metadata.GetMetadata<BrowserOptions>();
var options = metadataOptions ?? new BrowserOptions();
// Seed a request-local copy from endpoint metadata, which is shared across requests
var options = new BrowserOptions();
if (context.GetEndpoint()?.Metadata.GetMetadata<BrowserOptions>() is { } metadataOptions)
{
ConfigureBrowser.MergeInto(options, metadataOptions);
}

context.Items[Key] = options;
return options;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ await _renderer.InitializeStandardComponentServicesAsync(
// streaming SSR batches (inside SendStreamingUpdatesAsync). Otherwise some other code might dispatch to the
// renderer sync context and cause a batch that would get missed.
htmlContent.WriteTo(bufferWriter, HtmlEncoder.Default); // Don't use WriteToAsync, as per the comment above
if (htmlContent != EndpointHtmlRenderer.PrerenderedComponentHtmlContent.Empty)
{
_renderer.EmitBrowserConfigurationForInitialContent(bufferWriter);
}

if (!quiesceTask.IsCompletedSuccessfully)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,15 @@ internal static bool IsProgressivelyEnhancedNavigation(HttpRequest request)
private static readonly string? s_aspnetcoreBrowserTools =
Environment.GetEnvironmentVariable("__ASPNETCORE_BROWSER_TOOLS") is { Length: > 0 } v2 ? v2 : null;

internal void EmitBrowserConfigurationForInitialContent(TextWriter output)
{
if (!_browserConfigurationEmitted)
{
// A later streaming batch can configure the browser before emitting the first interactive component.
WriteBrowserConfiguration(output);
}
}

private void EmitBrowserConfigurationOnce(TextWriter output)
{
if (_browserConfigurationEmitted)
Expand All @@ -442,7 +451,11 @@ private void EmitBrowserConfigurationOnce(TextWriter output)
}

_browserConfigurationEmitted = true;
WriteBrowserConfiguration(output);
}

private void WriteBrowserConfiguration(TextWriter output)
{
var config = BrowserOptions.GetBrowserOptions(_httpContext);

// Apply framework defaults: environment name and tooling env vars
Expand Down
26 changes: 25 additions & 1 deletion src/Components/Endpoints/test/BrowserOptionsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ public void GetBrowserOptions_ReturnsSameInstanceOnSubsequentCalls()
public void GetBrowserOptions_SeedsFromEndpointMetadata()
{
var metadataOptions = new BrowserOptions();
metadataOptions.StaticServer.PreserveDom = true;
metadataOptions.InteractiveWebAssembly.EnvironmentVariables["KEY"] = "value";
var context = new DefaultHttpContext();
context.SetEndpoint(new Endpoint(
requestDelegate: null,
Expand All @@ -100,7 +102,29 @@ public void GetBrowserOptions_SeedsFromEndpointMetadata()

var result = BrowserOptions.GetBrowserOptions(context);

Assert.Same(metadataOptions, result);
Assert.True(result.StaticServer.PreserveDom);
Assert.Equal("value", result.InteractiveWebAssembly.EnvironmentVariables["KEY"]);
}

[Fact]
public void GetBrowserOptions_RequestChangesDoNotAffectEndpointMetadata()
{
var metadataOptions = new BrowserOptions();
var endpoint = new Endpoint(
requestDelegate: null,
metadata: new EndpointMetadataCollection(metadataOptions),
displayName: "Test");
var firstContext = new DefaultHttpContext();
firstContext.SetEndpoint(endpoint);
var pageOptions = new BrowserOptions();
pageOptions.StaticServer.PreserveDom = false;

ConfigureBrowser.MergeInto(BrowserOptions.GetBrowserOptions(firstContext), pageOptions);
var secondContext = new DefaultHttpContext();
secondContext.SetEndpoint(endpoint);

Assert.Null(BrowserOptions.GetBrowserOptions(secondContext).StaticServer.PreserveDom);
Assert.Null(metadataOptions.StaticServer.PreserveDom);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ public async Task Invoker_HandlesHeadRequestAsync()
.Services.AddAntiforgery()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build())
.AddSingleton<IWebHostEnvironment>(new TestWebHostEnvironment())
.AddSingleton<IHostEnvironment>(sp => sp.GetRequiredService<IWebHostEnvironment>())
.BuildServiceProvider();

var invoker = new RazorComponentEndpointInvoker(
Expand Down
115 changes: 103 additions & 12 deletions src/Components/Web.JS/src/Boot.Web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { Blazor } from './GlobalExports';
import { WebStartOptions } from './Platform/WebStartOptions';
import { attachStreamingRenderingListener } from './Rendering/StreamingRendering';
import { resetScrollIfNeeded, ScrollResetSchedule } from './Rendering/Renderer';
import { NavigationEnhancementCallbacks, attachProgressivelyEnhancedNavigationListener } from './Services/NavigationEnhancement';
import { NavigationEnhancementCallbacks, attachProgressivelyEnhancedNavigationListener, updateProgrammaticEnhancedNavigationHandler } from './Services/NavigationEnhancement';
import { WebRootComponentManager } from './Services/WebRootComponentManager';
import { hasProgrammaticEnhancedNavigationHandler, performProgrammaticEnhancedNavigation } from './Services/NavigationUtils';
import { attachComponentDescriptorHandler, registerAllComponentDescriptors } from './Rendering/DomMerging/DomSync';
Expand All @@ -29,10 +29,18 @@ import { resolveOptions, CircuitStartOptions, ReconnectionOptions } from './Plat
import { JSInitializer } from './JSInitializers/JSInitializers';
import { enableFocusOnNavigate } from './Rendering/FocusOnNavigate';
import { WebAssemblyStartOptions } from './Platform/WebAssemblyStartOptions';
import { SsrStartOptions } from './Platform/SsrStartOptions';
import { createBlazorValidation, ensureNovalidateOnForms } from './Validation';

let started = false;
let rootComponentManager: WebRootComponentManager;
let initialOptions: {
logLevel?: LogLevel;
circuitLogLevel?: LogLevel;
circuitInactivityTimeoutMs?: number;
disableDomPreservation?: boolean;
reconnectionRetryIntervalMilliseconds?: ReconnectionOptions['retryIntervalMilliseconds'];
Comment thread
ilonatommy marked this conversation as resolved.
Resolved
};

function boot(options?: Partial<WebStartOptions>) : Promise<void> {
if (started) {
Expand All @@ -41,7 +49,16 @@ function boot(options?: Partial<WebStartOptions>) : Promise<void> {

started = true;
options = options || {};
// Resolved options also contain defaults and values from previous enhanced navigations.
initialOptions = {
logLevel: options.logLevel,
circuitLogLevel: options.circuit?.logLevel,
circuitInactivityTimeoutMs: options.ssr?.circuitInactivityTimeoutMs,
disableDomPreservation: options.ssr?.disableDomPreservation,
reconnectionRetryIntervalMilliseconds: options.circuit?.reconnectionOptions?.retryIntervalMilliseconds,
};
options.logLevel ??= LogLevel.Error;
options.ssr ??= {};
Blazor._internal.isBlazorWeb = true;

// Defined here to avoid inadvertently imported enhanced navigation
Expand All @@ -53,7 +70,7 @@ function boot(options?: Partial<WebStartOptions>) : Promise<void> {
};

const jsEventRegistry = JSEventRegistry.create(Blazor);
rootComponentManager = new WebRootComponentManager(options?.ssr?.circuitInactivityTimeoutMs ?? 2000, jsEventRegistry);
rootComponentManager = new WebRootComponentManager(() => options.ssr, jsEventRegistry);

const navigationEnhancementCallbacks: NavigationEnhancementCallbacks = {
enhancedNavigationStarted: () => {
Expand All @@ -62,6 +79,7 @@ function boot(options?: Partial<WebStartOptions>) : Promise<void> {
beforeDomUpdate: (source) => {
updateOptionsFromBrowserConfiguration(options, source);
},
isDomPreservationDisabled: () => options.ssr?.disableDomPreservation === true,
documentUpdated: () => {
rootComponentManager.onDocumentUpdated();
resetScrollIfNeeded(ScrollResetSchedule.AfterDocumentUpdate);
Expand All @@ -74,11 +92,9 @@ function boot(options?: Partial<WebStartOptions>) : Promise<void> {
};

attachComponentDescriptorHandler(rootComponentManager);
attachStreamingRenderingListener(options?.ssr, navigationEnhancementCallbacks);

if (!options?.ssr?.disableDomPreservation) {
attachProgressivelyEnhancedNavigationListener(navigationEnhancementCallbacks);
}
// Attach navigation first, since defining the streaming element can synchronously process buffered batches.
attachProgressivelyEnhancedNavigationListener(navigationEnhancementCallbacks);
Comment thread
kotlarmilos marked this conversation as resolved.
Resolved
attachStreamingRenderingListener(() => options.ssr, navigationEnhancementCallbacks);

enableFocusOnNavigate(jsEventRegistry);

Expand Down Expand Up @@ -111,7 +127,78 @@ function onInitialDomContentLoaded(options: Partial<WebStartOptions>) {
options.circuit = initialCircuitOptions;
options.webAssembly = options.webAssembly || ({} as WebAssemblyStartOptions);
const logger = new ConsoleLogger(initialCircuitOptions.logLevel);
const initializersPromise = fetchAndInvokeInitializers(options, logger);
const initialSsrOptions = options.ssr || {};
options.ssr = initialSsrOptions;
const initializerSsrProxies = new WeakMap<SsrStartOptions, SsrStartOptions>();
const initializerSsrTargets = new WeakMap<SsrStartOptions, SsrStartOptions>();
const initializerSsrHandler: ProxyHandler<SsrStartOptions> = {
set(target, property, value) {
if (property === 'disableDomPreservation') {
initialOptions.disableDomPreservation = value;
} else if (property === 'circuitInactivityTimeoutMs') {
initialOptions.circuitInactivityTimeoutMs = value;
}
const result = Reflect.set(target, property, value);
if (property === 'disableDomPreservation') {
updateProgrammaticEnhancedNavigationHandler();
}
return result;
},
};
function getInitializerSsrOptions(ssrOptions: SsrStartOptions): SsrStartOptions {
let proxy = initializerSsrProxies.get(ssrOptions);
if (!proxy) {
proxy = new Proxy(ssrOptions, initializerSsrHandler);
initializerSsrProxies.set(ssrOptions, proxy);
initializerSsrTargets.set(proxy, ssrOptions);
}
return proxy;
}
const initializerCircuitOptions = new Proxy(initialCircuitOptions, {
get(target, property, receiver) {
const value = Reflect.get(target, property, receiver);
return property === 'reconnectionOptions' && value
? new Proxy(value, {
set(reconnectionTarget, reconnectionProperty, reconnectionValue) {
if (reconnectionProperty === 'retryIntervalMilliseconds') {
initialOptions.reconnectionRetryIntervalMilliseconds = reconnectionValue;
}
return Reflect.set(reconnectionTarget, reconnectionProperty, reconnectionValue);
},
})
: value;
},
set(target, property, value) {
if (property === 'logLevel') {
initialOptions.circuitLogLevel = value;
} else if (property === 'reconnectionOptions' && value?.retryIntervalMilliseconds !== undefined) {
initialOptions.reconnectionRetryIntervalMilliseconds = value.retryIntervalMilliseconds;
}
return Reflect.set(target, property, value);
},
});
const initializerOptions = new Proxy(options, {
get(target, property, receiver) {
if (property === 'ssr' && target.ssr) {
return getInitializerSsrOptions(target.ssr);
}
return property === 'circuit' && target.circuit === initialCircuitOptions
? initializerCircuitOptions
: Reflect.get(target, property, receiver);
},
set(target, property, value, receiver) {
if (property === 'ssr') {
value = initializerSsrTargets.get(value) ?? value;
initialOptions.disableDomPreservation = value?.disableDomPreservation;
initialOptions.circuitInactivityTimeoutMs = value?.circuitInactivityTimeoutMs;
const result = Reflect.set(target, property, value, receiver);
updateProgrammaticEnhancedNavigationHandler();
return result;
}
return Reflect.set(target, property, value, receiver);
},
});
const initializersPromise = fetchAndInvokeInitializers(initializerOptions, logger);
setCircuitOptions(resolveConfiguredOptions(initializersPromise, initialCircuitOptions));
setWebAssemblyOptions(resolveConfiguredOptions(initializersPromise, options.webAssembly));

Expand All @@ -126,17 +213,20 @@ function updateOptionsFromBrowserConfiguration(options: Partial<WebStartOptions>
const browserConfig = discoverBrowserConfiguration(source);
if (browserConfig) {
if (browserConfig.logLevel !== undefined) {
options.logLevel = browserConfig.logLevel;
options.logLevel = initialOptions.logLevel ?? browserConfig.logLevel;
options.circuit ??= {} as CircuitStartOptions;
options.circuit.logLevel = initialOptions.circuitLogLevel ?? browserConfig.logLevel;
Comment thread
ilonatommy marked this conversation as resolved.
Resolved
}

// SSR options
if (browserConfig.ssr) {
options.ssr = options.ssr || {};
if (browserConfig.ssr.disableDomPreservation !== undefined) {
options.ssr.disableDomPreservation = browserConfig.ssr.disableDomPreservation;
options.ssr.disableDomPreservation = initialOptions.disableDomPreservation ?? browserConfig.ssr.disableDomPreservation;
Comment thread
kotlarmilos marked this conversation as resolved.
Resolved
updateProgrammaticEnhancedNavigationHandler();
}
if (browserConfig.ssr.circuitInactivityTimeoutMs !== undefined) {
options.ssr.circuitInactivityTimeoutMs = browserConfig.ssr.circuitInactivityTimeoutMs;
options.ssr.circuitInactivityTimeoutMs = initialOptions.circuitInactivityTimeoutMs ?? browserConfig.ssr.circuitInactivityTimeoutMs;
}
}

Expand All @@ -151,7 +241,7 @@ function updateOptionsFromBrowserConfiguration(options: Partial<WebStartOptions>
reconnOpts.maxRetries = browserConfig.server.reconnectionMaxRetries;
}
if (browserConfig.server.reconnectionRetryIntervalMilliseconds !== undefined) {
reconnOpts.retryIntervalMilliseconds = browserConfig.server.reconnectionRetryIntervalMilliseconds;
reconnOpts.retryIntervalMilliseconds = initialOptions.reconnectionRetryIntervalMilliseconds ?? browserConfig.server.reconnectionRetryIntervalMilliseconds;
Comment thread
kotlarmilos marked this conversation as resolved.
Resolved
Comment thread
kotlarmilos marked this conversation as resolved.
Resolved
}
if (browserConfig.server.reconnectionDialogId !== undefined) {
reconnOpts.dialogId = browserConfig.server.reconnectionDialogId;
Expand All @@ -170,6 +260,7 @@ function updateOptionsFromBrowserConfiguration(options: Partial<WebStartOptions>
if (browserConfig.webAssembly) {
rootComponentManager.setWebAssemblyOptions({
environmentName: browserConfig.webAssembly.environmentName ?? '',
applicationCulture: browserConfig.webAssembly.applicationCulture,
environmentVariables: browserConfig.webAssembly.environmentVariables ?? {},
});
}
Expand Down
3 changes: 3 additions & 0 deletions src/Components/Web.JS/src/Boot.WebAssembly.Common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ export function loadWebAssemblyPlatformIfNotStarted(serverOptions: WebAssemblySe
if (!finalOptions.environment) {
finalOptions.environment = serverOptions?.environmentName ?? undefined;
}
if (!finalOptions.applicationCulture) {
finalOptions.applicationCulture = serverOptions?.applicationCulture;
}
const existingConfig = options?.configureRuntime;
finalOptions.configureRuntime = (config) => {
existingConfig?.(config);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ class ReconnectionProcess {
}
};

timeoutId = setTimeout(step, intervalMs);
timeoutId = setTimeout(step, Math.min(totalTimeMs, intervalMs));

document.addEventListener('visibilitychange', stepIfDocumentIsVisible);
await new Promise<void>(resolve => resolveTimerPromise = resolve);
Expand Down
17 changes: 9 additions & 8 deletions src/Components/Web.JS/src/Rendering/DomMerging/DomSync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function registerAllComponentDescriptors(root: Node) {

export { preprocessAndSynchronizeDomContent as synchronizeDomContent };

function preprocessAndSynchronizeDomContent(destination: CommentBoundedRange | Node, newContent: Node) {
function preprocessAndSynchronizeDomContent(destination: CommentBoundedRange | Node, newContent: Node, preserveExisting = true) {
// Strip any WebAssembly metadata comments from the new content before building
// the logical tree, so they don't end up as orphaned nodes in the logical children array
discoverWebAssemblyOptions(newContent);
Expand All @@ -47,10 +47,10 @@ function preprocessAndSynchronizeDomContent(destination: CommentBoundedRange | N
upgradeComponentCommentsToLogicalRootComments(newContent);

// Then, synchronize the preprocessed DOM content
synchronizeDomContentCore(destination, newContent);
synchronizeDomContentCore(destination, newContent, preserveExisting);
}

function synchronizeDomContentCore(destination: CommentBoundedRange | Node, newContent: Node) {
function synchronizeDomContentCore(destination: CommentBoundedRange | Node, newContent: Node, preserveExisting = true) {
// Determine the destination's parent node, i.e., the node containing the children
// we intend to synchronize. This might sometimes be a logical parent.
let destinationParent: Node;
Expand Down Expand Up @@ -88,11 +88,12 @@ function synchronizeDomContentCore(destination: CommentBoundedRange | Node, newC
}

// Run the diff
const editScript = computeEditScript(
originalNodesForDiff,
newNodesForDiff,
domNodeComparer
);
const editScript = preserveExisting
? computeEditScript(originalNodesForDiff, newNodesForDiff, domNodeComparer)
: {
skipCount: 0,
edits: [...Array<Operation>(originalNodesForDiff.length).fill(Operation.Delete), ...Array<Operation>(newNodesForDiff.length).fill(Operation.Insert)],
};

let destinationWalker: EditWalker;
let sourceWalker: EditWalker;
Expand Down
Loading
Loading