-
Notifications
You must be signed in to change notification settings - Fork 240
Initial support for razor isolation files (cs, css, js) #12981
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ToddGrun
merged 13 commits into
dotnet:main
from
ToddGrun:dev/toddgrun/RazorIsolationFiles
Apr 2, 2026
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
3f9eced
Initial support for razor isolation files (cs, css, js)
ToddGrun 1baa75b
Address some of the easy feedback
ToddGrun 86a52b9
Add LSP server endpoint for isolation file creation
ToddGrun 028fb60
Simplify VS-side command handlers to delegate to LSP endpoint
ToddGrun 8d8323f
Add unit tests for RemoteAddIsolationFileService
ToddGrun 065812d
Rename from Isolation => Nested
ToddGrun 6b60202
Change menu text to something like "Add Weather.razor.css"
ToddGrun 7d4a1c1
Fix two failing tests
ToddGrun 2abc423
Address most of the easy PR comments
ToddGrun df12c46
Convert CohostAddNestedFileEndpoint to document-scoped endpoint pattern
ToddGrun 4a2283f
Embrace AssertWorkspaceEditAsync
ToddGrun 24e4422
Change NestedFileKind to a struct
ToddGrun db1eb22
Add a test for TryGetNamespace failing (or returning an empty namespace)
ToddGrun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/NestedFiles/NestedFileKind.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| namespace Microsoft.CodeAnalysis.Razor.NestedFiles; | ||
|
|
||
| /// <summary> | ||
| /// Specifies which type of nested file to create for a Razor component. | ||
| /// </summary> | ||
| internal enum NestedFileKind | ||
| { | ||
| CSharp, | ||
| Css, | ||
| JavaScript, | ||
| } |
35 changes: 35 additions & 0 deletions
35
...r/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/NestedFiles/AddNestedFileParams.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. | ||
|
|
||
| using System; | ||
| using System.Text.Json.Serialization; | ||
| using Microsoft.CodeAnalysis.Razor.NestedFiles; | ||
|
|
||
| namespace Microsoft.CodeAnalysis.Razor.Protocol.NestedFiles; | ||
|
|
||
| /// <summary> | ||
| /// Parameters for the razor/addNestedFile endpoint. | ||
| /// </summary> | ||
| internal sealed class AddNestedFileParams : ITextDocumentParams | ||
| { | ||
| /// <summary> | ||
| /// The text document identifier for the Razor file (.razor or .cshtml) to create a nested file for. | ||
| /// </summary> | ||
| [JsonPropertyName("textDocument")] | ||
| public required TextDocumentIdentifier TextDocument { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// The kind of nested file to create. | ||
| /// </summary> | ||
| [JsonPropertyName("fileKind")] | ||
| public required NestedFileKind FileKind { get; set; } | ||
|
|
||
| public static AddNestedFileParams Create(Uri razorFileUri, NestedFileKind fileKind) | ||
| { | ||
| return new AddNestedFileParams | ||
| { | ||
| TextDocument = new TextDocumentIdentifier { DocumentUri = new(razorFileUri) }, | ||
| FileKind = fileKind | ||
| }; | ||
| } | ||
| } |
23 changes: 23 additions & 0 deletions
23
src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Remote/IRemoteAddNestedFileService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.CodeAnalysis.ExternalAccess.Razor; | ||
| using Microsoft.CodeAnalysis.Razor.NestedFiles; | ||
|
|
||
| namespace Microsoft.CodeAnalysis.Razor.Remote; | ||
|
|
||
| internal interface IRemoteAddNestedFileService : IRemoteJsonService | ||
| { | ||
| /// <summary> | ||
| /// Gets an edit to create a nested file (CSS, C# code-behind, or JavaScript) for a Razor file. | ||
| /// Returns a <see cref="WorkspaceEdit"/> containing CreateFile + TextDocumentEdit operations, | ||
| /// or null if the operation could not be completed. | ||
| /// </summary> | ||
| ValueTask<WorkspaceEdit?> GetNewNestedFileWorkspaceEditAsync( | ||
| JsonSerializableRazorPinnedSolutionInfoWrapper solutionInfo, | ||
| JsonSerializableDocumentId documentId, | ||
| NestedFileKind fileKind, | ||
| CancellationToken cancellationToken); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
167 changes: 167 additions & 0 deletions
167
src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/NestedFiles/RemoteAddNestedFileService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.IO; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.AspNetCore.Razor.Language; | ||
| using Microsoft.AspNetCore.Razor.PooledObjects; | ||
| using Microsoft.CodeAnalysis.ExternalAccess.Razor; | ||
| using Microsoft.CodeAnalysis.Razor.CodeActions; | ||
| using Microsoft.CodeAnalysis.Razor.Logging; | ||
| using Microsoft.CodeAnalysis.Razor.NestedFiles; | ||
| using Microsoft.CodeAnalysis.Razor.Remote; | ||
| using Microsoft.CodeAnalysis.Razor.Workspaces; | ||
| using Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem; | ||
|
|
||
| namespace Microsoft.CodeAnalysis.Remote.Razor; | ||
|
|
||
| internal sealed class RemoteAddNestedFileService(in ServiceArgs args) | ||
| : RazorDocumentServiceBase(in args), IRemoteAddNestedFileService | ||
| { | ||
| internal sealed class Factory : FactoryBase<IRemoteAddNestedFileService> | ||
| { | ||
| protected override IRemoteAddNestedFileService CreateService(in ServiceArgs args) | ||
| => new RemoteAddNestedFileService(in args); | ||
| } | ||
|
|
||
| private readonly IRoslynCodeActionHelpers _roslynCodeActionHelpers = | ||
| args.ExportProvider.GetExportedValue<IRoslynCodeActionHelpers>(); | ||
|
|
||
| private readonly LanguageServerFeatureOptions _languageServerFeatureOptions = | ||
| args.ExportProvider.GetExportedValue<LanguageServerFeatureOptions>(); | ||
|
|
||
| public ValueTask<WorkspaceEdit?> GetNewNestedFileWorkspaceEditAsync( | ||
| JsonSerializableRazorPinnedSolutionInfoWrapper solutionInfo, | ||
| JsonSerializableDocumentId documentId, | ||
| NestedFileKind fileKind, | ||
| CancellationToken cancellationToken) | ||
| => RunServiceAsync( | ||
| solutionInfo, | ||
| documentId, | ||
| context => GetNewNestedFileWorkspaceEditAsync(context, fileKind, cancellationToken), | ||
| cancellationToken); | ||
|
|
||
| private async ValueTask<WorkspaceEdit?> GetNewNestedFileWorkspaceEditAsync( | ||
| RemoteDocumentContext context, | ||
| NestedFileKind fileKind, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var razorFilePath = context.FilePath; | ||
| if (GetNestedFilePath(razorFilePath, fileKind) is not string nestedFilePath) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| var nestedFileUri = LspFactory.CreateFilePathUri(nestedFilePath, _languageServerFeatureOptions); | ||
|
|
||
| var content = await GenerateContentAsync( | ||
| fileKind, context, razorFilePath, nestedFileUri, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| var nestedFileDocumentIdentifier = new OptionalVersionedTextDocumentIdentifier | ||
| { | ||
| DocumentUri = new DocumentUri(nestedFileUri) | ||
| }; | ||
|
|
||
| var documentChanges = new SumType<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>[] | ||
| { | ||
| new CreateFile { DocumentUri = nestedFileDocumentIdentifier.DocumentUri }, | ||
| new TextDocumentEdit | ||
| { | ||
| TextDocument = nestedFileDocumentIdentifier, | ||
| Edits = [LspFactory.CreateTextEdit(position: (0, 0), content)] | ||
| } | ||
| }; | ||
|
|
||
| return new WorkspaceEdit | ||
| { | ||
| DocumentChanges = documentChanges, | ||
| }; | ||
| } | ||
|
|
||
| private static string? GetNestedFilePath(string razorFilePath, NestedFileKind fileKind) | ||
| { | ||
| return fileKind switch | ||
| { | ||
| NestedFileKind.Css => razorFilePath + ".css", | ||
| NestedFileKind.CSharp => razorFilePath + ".cs", | ||
| NestedFileKind.JavaScript => razorFilePath + ".js", | ||
| _ => null | ||
| }; | ||
| } | ||
|
|
||
| private async Task<string> GenerateContentAsync( | ||
| NestedFileKind fileKind, | ||
| RemoteDocumentContext documentContext, | ||
| string razorFilePath, | ||
| Uri nestedFileUri, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| return fileKind switch | ||
| { | ||
| NestedFileKind.CSharp => await GenerateCSharpContentAsync( | ||
| documentContext, razorFilePath, nestedFileUri, cancellationToken).ConfigureAwait(false), | ||
| NestedFileKind.Css => GenerateCssContent(razorFilePath), | ||
| NestedFileKind.JavaScript => GenerateJavaScriptContent(razorFilePath), | ||
| _ => string.Empty | ||
| }; | ||
| } | ||
|
|
||
| private static string GenerateCssContent(string razorFilePath) | ||
| { | ||
| var componentName = Path.GetFileNameWithoutExtension(razorFilePath); | ||
| var fileType = FileKinds.GetFileKindFromPath(razorFilePath).IsLegacy() ? "view" : "component"; | ||
| return $"/* CSS for {componentName} {fileType} */\r\n"; | ||
| } | ||
|
|
||
| private static string GenerateJavaScriptContent(string razorFilePath) | ||
| { | ||
| var componentName = Path.GetFileNameWithoutExtension(razorFilePath); | ||
| var fileType = FileKinds.GetFileKindFromPath(razorFilePath).IsLegacy() ? "view" : "component"; | ||
| return $"// JavaScript for {componentName} {fileType}\r\n"; | ||
| } | ||
|
|
||
| private async Task<string> GenerateCSharpContentAsync( | ||
| RemoteDocumentContext documentContext, | ||
| string razorFilePath, | ||
| Uri nestedFileUri, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var codeDocument = await documentContext.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false); | ||
| var className = Path.GetFileNameWithoutExtension(razorFilePath); | ||
|
|
||
| // Use the Razor compiler's namespace resolution which handles @namespace directives, | ||
| // _Imports.razor, and SDK-provided root namespace | ||
| if (!codeDocument.TryGetNamespace(fallbackToRootNamespace: true, out var ns) || ns.IsNullOrEmpty()) | ||
| { | ||
| Logger.LogWarning($"Could not determine namespace for: {razorFilePath}"); | ||
| ns = "Unknown"; | ||
| } | ||
|
|
||
| var content = GenerateCodeBehindClass(className, ns); | ||
|
|
||
| // Format via Roslyn (handles file-scoped namespaces, indentation, etc.) | ||
| content = await _roslynCodeActionHelpers.GetFormattedNewFileContentsAsync( | ||
| documentContext.Snapshot.Project, | ||
| nestedFileUri, | ||
| content, | ||
| cancellationToken).ConfigureAwait(false); | ||
|
|
||
| return content; | ||
| } | ||
|
|
||
| private static string GenerateCodeBehindClass(string className, string namespaceName) | ||
| { | ||
| using var _ = StringBuilderPool.GetPooledObject(out var builder); | ||
|
|
||
| builder.AppendLine($"namespace {namespaceName}"); | ||
| builder.AppendLine("{"); | ||
| builder.AppendLine($"public partial class {className}"); | ||
| builder.AppendLine("{"); | ||
| builder.AppendLine("}"); | ||
| builder.AppendLine("}"); | ||
|
|
||
| return builder.ToString(); | ||
| } | ||
| } | ||
80 changes: 80 additions & 0 deletions
80
....VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostAddNestedFileEndpoint.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Composition; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.AspNetCore.Razor; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.ExternalAccess.Razor; | ||
| using Microsoft.CodeAnalysis.ExternalAccess.Razor.Cohost; | ||
| using Microsoft.CodeAnalysis.Razor.Cohost; | ||
| using Microsoft.CodeAnalysis.Razor.Logging; | ||
| using Microsoft.CodeAnalysis.Razor.Protocol.NestedFiles; | ||
| using Microsoft.CodeAnalysis.Razor.Remote; | ||
|
|
||
| namespace Microsoft.VisualStudio.Razor.LanguageClient.Cohost; | ||
|
|
||
| #pragma warning disable RS0030 // Do not use banned APIs | ||
| [Shared] | ||
| [CohostEndpoint(RazorLSPConstants.AddNestedFileName)] | ||
| [ExportCohostStatelessLspService(typeof(CohostAddNestedFileEndpoint))] | ||
| [method: ImportingConstructor] | ||
| #pragma warning restore RS0030 // Do not use banned APIs | ||
| internal sealed class CohostAddNestedFileEndpoint( | ||
| IRemoteServiceInvoker remoteServiceInvoker, | ||
| IIncompatibleProjectService incompatibleProjectService, | ||
| ILoggerFactory loggerFactory) | ||
| : AbstractCohostDocumentEndpoint<AddNestedFileParams, VoidResult>(incompatibleProjectService) | ||
| { | ||
| private readonly IRemoteServiceInvoker _remoteServiceInvoker = remoteServiceInvoker; | ||
| private readonly ILogger _logger = loggerFactory.GetOrCreateLogger<CohostAddNestedFileEndpoint>(); | ||
|
|
||
| protected override bool MutatesSolutionState => false; | ||
|
|
||
| protected override bool RequiresLSPSolution => true; | ||
|
|
||
| protected override RazorTextDocumentIdentifier? GetRazorTextDocumentIdentifier(AddNestedFileParams request) | ||
| => request.TextDocument.ToRazorTextDocumentIdentifier(); | ||
|
|
||
| protected override Task<VoidResult> HandleRequestAsync( | ||
| AddNestedFileParams request, | ||
| TextDocument razorDocument, | ||
| CancellationToken cancellationToken) | ||
| => Assumed.Unreachable<Task<VoidResult>>(); | ||
|
|
||
| protected override async Task<VoidResult> HandleRequestAsync( | ||
| AddNestedFileParams request, | ||
| RazorCohostRequestContext context, | ||
| TextDocument razorDocument, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var workspaceEdit = await _remoteServiceInvoker.TryInvokeAsync<IRemoteAddNestedFileService, WorkspaceEdit?>( | ||
| razorDocument.Project.Solution, | ||
| (service, solutionInfo, ct) => service.GetNewNestedFileWorkspaceEditAsync( | ||
| solutionInfo, | ||
| razorDocument.Id, | ||
| request.FileKind, | ||
| ct), | ||
| cancellationToken).ConfigureAwait(false); | ||
|
|
||
| if (workspaceEdit is null) | ||
| { | ||
| _logger.LogWarning($"Remote service returned no edit for addNestedFile."); | ||
| return new(); | ||
| } | ||
|
|
||
| var razorCohostClientLanguageServerManager = context.GetRequiredService<IRazorClientLanguageServerManager>(); | ||
| var response = await razorCohostClientLanguageServerManager.SendRequestAsync<ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse>( | ||
| Methods.WorkspaceApplyEditName, | ||
| new ApplyWorkspaceEditParams { Edit = workspaceEdit }, | ||
| cancellationToken).ConfigureAwait(false); | ||
|
|
||
| if (!response.Applied) | ||
| { | ||
| _logger.LogWarning($"Failed to apply workspace edit for addNestedFile: {response.FailureReason}"); | ||
| } | ||
|
|
||
| return new(); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think if you pass
inGlobalNamespace: truetoCreateProjectAndRazorDocumentin a test, we should get coverage of this. Might be worth it just for regression prevention. If it's not that simple, I wouldn't worry.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It was that easy, and it actually behaved differently than I was expecting. Good catch!