mirror of
https://github.com/AlexMacocian/TrailBlazr.git
synced 2026-07-15 15:20:00 +00:00
Add project files.
This commit is contained in:
+137
@@ -0,0 +1,137 @@
|
||||
[*.cs]
|
||||
|
||||
# CA2254: Template should be a static expression
|
||||
dotnet_diagnostic.CA2254.severity = none
|
||||
csharp_indent_labels = one_less_than_current
|
||||
csharp_using_directive_placement = outside_namespace:error
|
||||
csharp_prefer_simple_using_statement = true:error
|
||||
csharp_prefer_braces = true:silent
|
||||
csharp_style_namespace_declarations = file_scoped:error
|
||||
csharp_style_prefer_method_group_conversion = true:suggestion
|
||||
csharp_style_expression_bodied_methods = false:silent
|
||||
csharp_style_expression_bodied_constructors = false:silent
|
||||
csharp_style_expression_bodied_operators = false:silent
|
||||
csharp_style_expression_bodied_properties = true:silent
|
||||
csharp_style_expression_bodied_indexers = true:silent
|
||||
csharp_style_expression_bodied_accessors = true:silent
|
||||
csharp_style_expression_bodied_lambdas = true:silent
|
||||
csharp_style_expression_bodied_local_functions = false:silent
|
||||
csharp_indent_braces = false
|
||||
insert_final_newline = true
|
||||
csharp_space_around_binary_operators = before_and_after
|
||||
csharp_style_throw_expression = true:suggestion
|
||||
csharp_style_prefer_null_check_over_type_check = true:suggestion
|
||||
csharp_prefer_simple_default_expression = true:suggestion
|
||||
csharp_style_prefer_local_over_anonymous_function = true:error
|
||||
csharp_style_prefer_index_operator = true:suggestion
|
||||
csharp_style_prefer_range_operator = true:suggestion
|
||||
csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
|
||||
csharp_style_prefer_tuple_swap = true:suggestion
|
||||
csharp_style_inlined_variable_declaration = true:suggestion
|
||||
csharp_style_deconstructed_variable_declaration = true:error
|
||||
csharp_style_unused_value_assignment_preference = discard_variable:error
|
||||
csharp_style_unused_value_expression_statement_preference = discard_variable:silent
|
||||
csharp_prefer_static_local_function = true:suggestion
|
||||
csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent
|
||||
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent
|
||||
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:suggestion
|
||||
csharp_style_conditional_delegate_call = true:suggestion
|
||||
csharp_style_prefer_parameter_null_checking = true:suggestion
|
||||
csharp_style_prefer_switch_expression = true:suggestion
|
||||
csharp_style_prefer_pattern_matching = true:silent
|
||||
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
|
||||
csharp_style_prefer_not_pattern = true:suggestion
|
||||
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
|
||||
csharp_style_prefer_extended_property_pattern = true:suggestion
|
||||
csharp_style_var_for_built_in_types = false:silent
|
||||
csharp_style_var_when_type_is_apparent = false:silent
|
||||
csharp_style_var_elsewhere = false:silent
|
||||
csharp_style_prefer_top_level_statements = true:suggestion
|
||||
csharp_style_prefer_utf8_string_literals = true:suggestion
|
||||
csharp_style_prefer_readonly_struct = true:suggestion
|
||||
|
||||
[*.{cs,vb}]
|
||||
#### Naming styles ####
|
||||
|
||||
# Naming rules
|
||||
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.severity = error
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
|
||||
|
||||
dotnet_naming_rule.types_should_be_pascal_case.severity = error
|
||||
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
|
||||
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
|
||||
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = error
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
|
||||
|
||||
# Symbol specifications
|
||||
|
||||
dotnet_naming_symbols.interface.applicable_kinds = interface
|
||||
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.interface.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
|
||||
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.types.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
|
||||
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.non_field_members.required_modifiers =
|
||||
|
||||
# Naming styles
|
||||
|
||||
dotnet_naming_style.begins_with_i.required_prefix = I
|
||||
dotnet_naming_style.begins_with_i.required_suffix =
|
||||
dotnet_naming_style.begins_with_i.word_separator =
|
||||
dotnet_naming_style.begins_with_i.capitalization = pascal_case
|
||||
|
||||
dotnet_naming_style.pascal_case.required_prefix =
|
||||
dotnet_naming_style.pascal_case.required_suffix =
|
||||
dotnet_naming_style.pascal_case.word_separator =
|
||||
dotnet_naming_style.pascal_case.capitalization = pascal_case
|
||||
|
||||
dotnet_naming_style.pascal_case.required_prefix =
|
||||
dotnet_naming_style.pascal_case.required_suffix =
|
||||
dotnet_naming_style.pascal_case.word_separator =
|
||||
dotnet_naming_style.pascal_case.capitalization = pascal_case
|
||||
dotnet_style_operator_placement_when_wrapping = beginning_of_line
|
||||
tab_width = 4
|
||||
indent_size = 4
|
||||
end_of_line = crlf
|
||||
dotnet_style_coalesce_expression = true:suggestion
|
||||
dotnet_style_null_propagation = true:suggestion
|
||||
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error
|
||||
dotnet_style_prefer_auto_properties = true:error
|
||||
dotnet_style_object_initializer = true:suggestion
|
||||
dotnet_style_collection_initializer = true:suggestion
|
||||
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
|
||||
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
|
||||
dotnet_style_prefer_conditional_expression_over_return = true:silent
|
||||
dotnet_style_explicit_tuple_names = true:suggestion
|
||||
dotnet_style_prefer_inferred_tuple_names = true:suggestion
|
||||
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
|
||||
dotnet_style_prefer_compound_assignment = true:suggestion
|
||||
dotnet_style_prefer_simplified_interpolation = true:suggestion
|
||||
dotnet_style_namespace_match_folder = true:suggestion
|
||||
dotnet_style_readonly_field = true:suggestion
|
||||
dotnet_style_predefined_type_for_locals_parameters_members = true:silent
|
||||
dotnet_style_predefined_type_for_member_access = true:silent
|
||||
dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
|
||||
dotnet_style_allow_multiple_blank_lines_experimental = true:silent
|
||||
dotnet_style_allow_statement_immediately_after_block_experimental = false:suggestion
|
||||
dotnet_code_quality_unused_parameters = all:error
|
||||
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:suggestion
|
||||
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:suggestion
|
||||
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:suggestion
|
||||
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:suggestion
|
||||
dotnet_style_qualification_for_field = true:error
|
||||
dotnet_style_qualification_for_property = true:error
|
||||
dotnet_style_qualification_for_method = true:error
|
||||
dotnet_style_qualification_for_event = true:error
|
||||
dotnet_diagnostic.CA1000.severity = error
|
||||
|
||||
[*.vb]
|
||||
dotnet_diagnostic.CA1047.severity = error
|
||||
@@ -0,0 +1,16 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions" # See documentation for possible values
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: "nuget"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
@@ -0,0 +1,43 @@
|
||||
name: TrailBlazr CD Pipeline
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
environment: Default
|
||||
strategy:
|
||||
matrix:
|
||||
targetplatform: [x64]
|
||||
|
||||
runs-on: windows-latest
|
||||
|
||||
env:
|
||||
Configuration: Release
|
||||
Actions_Allow_Unsecure_Commands: true
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install .NET Core
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '9.x'
|
||||
|
||||
- name: Setup MSBuild.exe
|
||||
uses: microsoft/setup-msbuild@v2.0.0
|
||||
|
||||
- name: Build TrailBlazr project
|
||||
run: dotnet build TrailBlazr -c $env:Configuration
|
||||
|
||||
- name: Package TrailBlazr
|
||||
run: dotnet pack -c Release -o . TrailBlazr\TrailBlazr.csproj
|
||||
|
||||
- name: Publish
|
||||
run: dotnet nuget push *.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
|
||||
@@ -0,0 +1,46 @@
|
||||
name: TrailBlazr CI Pipeline
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
- release/*
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
strategy:
|
||||
matrix:
|
||||
targetplatform: [x64]
|
||||
|
||||
runs-on: windows-latest
|
||||
|
||||
env:
|
||||
Configuration: Debug
|
||||
Actions_Allow_Unsecure_Commands: true
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install .NET Core
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '9.x'
|
||||
|
||||
- name: Setup MSBuild.exe
|
||||
uses: microsoft/setup-msbuild@v2.0.0
|
||||
|
||||
- name: Build TrailBlazr project
|
||||
run: dotnet build TrailBlazr -c $env:Configuration
|
||||
|
||||
- name: Build TrailBlazr.Tests project
|
||||
run: dotnet build TrailBlazr.Tests -c $env:Configuration
|
||||
|
||||
- name: Run tests
|
||||
run: dotnet test TrailBlazr.Tests -c $env:Configuration --verbosity normal
|
||||
@@ -0,0 +1,9 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>0.1.0</Version>
|
||||
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Components" Version="9.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.7" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,165 @@
|
||||
# TrailBlazr
|
||||
|
||||
[](https://github.com/your-username/TrailBlazr/actions/workflows/ci.yaml)
|
||||
[](https://www.nuget.org/packages/TrailBlazr/)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
||||
TrailBlazr is a powerful library for Blazor that enables compile-correct view management with linked ViewModels through the MVVM pattern. It provides a seamless navigation system using a view container component and view manager, making it easy to build maintainable Blazor applications with strong typing and separation of concerns.
|
||||
|
||||
## Features
|
||||
|
||||
- 🔗 **Strongly-typed View-ViewModel binding** - Compile-time safety for view-viewmodel relationships
|
||||
- 🧭 **Navigation management** - Centralized view navigation through `IViewManager`
|
||||
- 🏗️ **MVVM pattern support** - Clean separation of concerns with ViewModels
|
||||
- 📦 **Dependency injection integration** - Seamless integration with .NET DI container
|
||||
- 🎯 **Dynamic view rendering** - Efficient view switching with `ViewContainer` component
|
||||
- ⚡ **Minimal setup** - Easy configuration with extension methods
|
||||
|
||||
## Installation
|
||||
|
||||
Install TrailBlazr via NuGet Package Manager:
|
||||
|
||||
```bash
|
||||
dotnet add package TrailBlazr
|
||||
```
|
||||
|
||||
Or via Package Manager Console:
|
||||
|
||||
```powershell
|
||||
Install-Package TrailBlazr
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Register TrailBlazr services
|
||||
|
||||
In your `Program.cs` or startup configuration:
|
||||
|
||||
```csharp
|
||||
using TrailBlazr.Extensions;
|
||||
|
||||
// Add TrailBlazr services
|
||||
builder.Services.AddTrailBlazr();
|
||||
|
||||
// Register your views and viewmodels
|
||||
builder.Services.RegisterView<HomeView, HomeViewModel>();
|
||||
builder.Services.RegisterView<UserProfileView, UserProfileViewModel>();
|
||||
|
||||
var app = builder.Build();
|
||||
```
|
||||
|
||||
### 2. Create a ViewModel
|
||||
|
||||
```csharp
|
||||
using TrailBlazr.ViewModels;
|
||||
|
||||
public class HomeViewModel : ViewModelBase<HomeViewModel, HomeView>
|
||||
{
|
||||
public string Title { get; set; } = "Welcome to TrailBlazr!";
|
||||
public string Message { get; set; } = "Navigate with confidence.";
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Create a View
|
||||
|
||||
```razor
|
||||
@using TrailBlazr.Views
|
||||
@inherits ViewBase<HomeView, HomeViewModel>
|
||||
|
||||
<div class="home-container">
|
||||
<h1>@ViewModel.Title</h1>
|
||||
<p>@ViewModel.Message</p>
|
||||
|
||||
<button @onclick="() => NavigateToProfile()">
|
||||
Go to Profile
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Inject]
|
||||
private IViewManager ViewManager { get; set; }
|
||||
|
||||
private void NavigateToProfile()
|
||||
{
|
||||
this.ViewManager.ShowView<UserProfileView, UserProfileViewModel>();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Add ViewContainer to your layout
|
||||
|
||||
```razor
|
||||
@using TrailBlazr.Components
|
||||
|
||||
<div class="main-content">
|
||||
<ViewContainer />
|
||||
</div>
|
||||
```
|
||||
|
||||
### 5. Navigate between views
|
||||
|
||||
Inject `IViewManager` anywhere in your application to navigate:
|
||||
|
||||
```csharp
|
||||
[Inject]
|
||||
private IViewManager ViewManager { get; set; }
|
||||
|
||||
// Navigate to a view with optional data context
|
||||
ViewManager.ShowView<UserProfileView, UserProfileViewModel>(userData);
|
||||
|
||||
// Or navigate by type
|
||||
ViewManager.ShowView(typeof(HomeView), someData);
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### ViewBase<TView, TViewModel>
|
||||
|
||||
Base class for all views that provides:
|
||||
- Strong typing between view and viewmodel
|
||||
- Automatic viewmodel injection
|
||||
- Access to `ViewManager` for navigation
|
||||
|
||||
### ViewModelBase<TViewModel, TView>
|
||||
|
||||
Base class for all viewmodels that provides:
|
||||
- Strong typing between viewmodel and view
|
||||
- Foundation for implementing business logic
|
||||
- Inherits from `INotifyPropertyChanged` for data binding
|
||||
|
||||
### IViewManager
|
||||
|
||||
Central service for managing view navigation:
|
||||
- `ShowView<TView, TViewModel>(object? dataContext)` - Navigate with strong typing
|
||||
- `ShowView(Type viewType, object? dataContext)` - Navigate by type
|
||||
- `ShowViewRequested` event - Subscribe to navigation events
|
||||
|
||||
### ViewContainer
|
||||
|
||||
Blazor component that hosts and renders the current view:
|
||||
- Automatically updates when navigation occurs
|
||||
- Supports dynamic component rendering
|
||||
- Passes data context to views
|
||||
|
||||
## Architecture
|
||||
|
||||
TrailBlazr follows the MVVM (Model-View-ViewModel) pattern:
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
|
||||
│ View │◄──►│ ViewModel │◄──►│ Model │
|
||||
│ (Razor) │ │ (C# Class) │ │ (Data) │
|
||||
└─────────────────┘ └──────────────────┘ └─────────────────┘
|
||||
▲ ▲
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────────────────┐ ┌──────────────────┐
|
||||
│ ViewContainer │◄──►│ ViewManager │
|
||||
│ (Component) │ │ (Service) │
|
||||
└─────────────────┘ └──────────────────┘
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
- .NET 9.0 or later
|
||||
- Blazor Hybrid or Blazor Server/WebAssembly
|
||||
@@ -0,0 +1 @@
|
||||
[assembly: Parallelize(Scope = ExecutionScope.MethodLevel)]
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="MSTest.Sdk/3.6.4">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseVSTest>true</UseVSTest>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,17 @@
|
||||
<Solution>
|
||||
<Configurations>
|
||||
<Platform Name="Any CPU" />
|
||||
<Platform Name="x64" />
|
||||
<Platform Name="x86" />
|
||||
</Configurations>
|
||||
<Folder Name="/Solution Items/">
|
||||
<File Path=".editorconfig" />
|
||||
<File Path=".github/workflows/cd.yaml" />
|
||||
<File Path=".github/workflows/ci.yaml" />
|
||||
<File Path="Directory.Build.props" />
|
||||
<File Path="Directory.Packages.props" />
|
||||
<File Path="README.md" />
|
||||
</Folder>
|
||||
<Project Path="TrailBlazr.Tests/TrailBlazr.Tests.csproj" />
|
||||
<Project Path="TrailBlazr/TrailBlazr.csproj" />
|
||||
</Solution>
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
<h1>Loading...</h1>
|
||||
|
||||
@code {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<DynamicComponent Type="@this.CurrentViewType" Parameters="@this.CurrentParameters" />
|
||||
|
||||
@using TrailBlazr.Models
|
||||
@using TrailBlazr.Services
|
||||
@code {
|
||||
[Inject]
|
||||
protected IViewManager? ViewManager { get; set; }
|
||||
|
||||
protected Type CurrentViewType { get; set; } = typeof(EmptyComponent);
|
||||
|
||||
protected Dictionary<string, object> CurrentParameters { get; set; } = [];
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
if (this.ViewManager is null)
|
||||
{
|
||||
throw new InvalidOperationException("ViewManager is not initialized.");
|
||||
}
|
||||
|
||||
this.ViewManager.ShowViewRequested += this.UpdateCurrentView;
|
||||
}
|
||||
|
||||
private void UpdateCurrentView(object? _, ViewRequest request)
|
||||
{
|
||||
this.CurrentParameters = new Dictionary<string, object>() { { "DataContext", request.DataContext ?? new object() } };
|
||||
this.CurrentViewType = request.ViewType;
|
||||
this.StateHasChanged();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using TrailBlazr.Models;
|
||||
using TrailBlazr.Services;
|
||||
using TrailBlazr.ViewModels;
|
||||
using TrailBlazr.Views;
|
||||
|
||||
namespace TrailBlazr.Extensions;
|
||||
public static class ServiceCollectionExtensions
|
||||
{
|
||||
public static IServiceCollection AddTrailBlazr(this IServiceCollection services)
|
||||
{
|
||||
_ = services ?? throw new ArgumentNullException(nameof(services));
|
||||
|
||||
services.AddSingleton<IViewManager, ViewManager>();
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection RegisterView<TView, TViewModel>(this IServiceCollection services, bool isSingleton = false)
|
||||
where TView : ViewBase<TView, TViewModel>
|
||||
where TViewModel : ViewModelBase<TViewModel, TView>
|
||||
{
|
||||
_ = services ?? throw new ArgumentNullException(nameof(services));
|
||||
if (isSingleton)
|
||||
{
|
||||
services.AddSingleton<TView>();
|
||||
services.AddSingleton<TViewModel>();
|
||||
}
|
||||
else
|
||||
{
|
||||
services.AddScoped<TView>();
|
||||
services.AddScoped<TViewModel>();
|
||||
}
|
||||
|
||||
services.AddSingleton<ViewRegistration>(new ViewRegistration<TView, TViewModel>());
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace TrailBlazr.Models;
|
||||
|
||||
public abstract class ViewRegistration(Type viewType, Type viewModelType)
|
||||
{
|
||||
public Type ViewType { get; } = viewType ?? throw new ArgumentNullException(nameof(viewType));
|
||||
public Type ViewModelType { get; } = viewModelType ?? throw new ArgumentNullException(nameof(viewModelType));
|
||||
}
|
||||
|
||||
public sealed class ViewRegistration<TView, TViewModel>() : ViewRegistration(typeof(TView), typeof(TViewModel))
|
||||
where TView : Views.ViewBase<TView, TViewModel>
|
||||
where TViewModel : ViewModels.ViewModelBase<TViewModel, TView>
|
||||
{
|
||||
public override string ToString() => $"({this.ViewType.Name} - {this.ViewModelType.Name})";
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace TrailBlazr.Models;
|
||||
public sealed record ViewRequest(Type ViewType, Type ViewModelType, object? DataContext)
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using TrailBlazr.Models;
|
||||
using TrailBlazr.ViewModels;
|
||||
using TrailBlazr.Views;
|
||||
|
||||
namespace TrailBlazr.Services;
|
||||
public interface IViewManager
|
||||
{
|
||||
event EventHandler<ViewRequest>? ShowViewRequested;
|
||||
|
||||
void ShowView<TView, TViewModel>(object? dataContext = null)
|
||||
where TView : ViewBase<TView, TViewModel>
|
||||
where TViewModel : ViewModelBase<TViewModel, TView>;
|
||||
|
||||
void ShowView(Type viewType, object? dataContext = null);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using TrailBlazr.Models;
|
||||
using TrailBlazr.ViewModels;
|
||||
using TrailBlazr.Views;
|
||||
|
||||
namespace TrailBlazr.Services;
|
||||
public sealed class ViewManager(
|
||||
IEnumerable<ViewRegistration> viewRegistrations) : IViewManager
|
||||
{
|
||||
private readonly List<ViewRegistration> viewRegistrations = [.. viewRegistrations];
|
||||
|
||||
public event EventHandler<ViewRequest>? ShowViewRequested;
|
||||
|
||||
public void ShowView<TView, TViewModel>(object? dataContext = null)
|
||||
where TView : ViewBase<TView, TViewModel>
|
||||
where TViewModel : ViewModelBase<TViewModel, TView>
|
||||
{
|
||||
var viewType = typeof(TView);
|
||||
this.ShowViewInner(viewType, dataContext);
|
||||
}
|
||||
|
||||
public void ShowView(Type viewType, object? dataContext = null)
|
||||
{
|
||||
this.ShowViewInner(viewType, dataContext);
|
||||
}
|
||||
|
||||
private void ShowViewInner(Type viewType, object? dataContext = null)
|
||||
{
|
||||
if (this.viewRegistrations.FirstOrDefault(r => r.ViewType == viewType) is not ViewRegistration registration)
|
||||
{
|
||||
throw new InvalidOperationException("View type not registered: " + viewType.FullName);
|
||||
}
|
||||
|
||||
var viewRequest = new ViewRequest(registration.ViewType, registration.ViewModelType, dataContext);
|
||||
this.ShowViewRequested?.Invoke(this, viewRequest);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Razor">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Authors>Alexandru Macocian</Authors>
|
||||
<Description>Framework for hosting MVVM views in Blazor.</Description>
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.ComponentModel;
|
||||
using TrailBlazr.Views;
|
||||
|
||||
namespace TrailBlazr.ViewModels;
|
||||
|
||||
public abstract class ViewModelBase<TViewModel, TView> : INotifyPropertyChanged
|
||||
where TViewModel : ViewModelBase<TViewModel, TView>
|
||||
where TView : ViewBase<TView, TViewModel>
|
||||
{
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
public object? DataContext
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
field = value;
|
||||
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(this.DataContext)));
|
||||
}
|
||||
}
|
||||
|
||||
protected TView? View
|
||||
{
|
||||
get => field;
|
||||
private set
|
||||
{
|
||||
field = value;
|
||||
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(this.View)));
|
||||
}
|
||||
}
|
||||
|
||||
internal void SetView(TView view)
|
||||
{
|
||||
this.View = view ?? throw new ArgumentNullException(nameof(view));
|
||||
}
|
||||
|
||||
public void RefreshView()
|
||||
{
|
||||
this.View?.RefreshView();
|
||||
}
|
||||
|
||||
public virtual ValueTask Initialize(CancellationToken cancellationToken) => ValueTask.CompletedTask;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.ComponentModel;
|
||||
using TrailBlazr.ViewModels;
|
||||
|
||||
namespace TrailBlazr.Views;
|
||||
public abstract class ViewBase<TView, TViewModel> : ComponentBase, INotifyPropertyChanged
|
||||
where TView : ViewBase<TView, TViewModel>
|
||||
where TViewModel : ViewModelBase<TViewModel, TView>
|
||||
{
|
||||
public readonly static TimeSpan InitializationTimeout = TimeSpan.FromSeconds(5);
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
[Inject]
|
||||
public TViewModel ViewModel { get; set; } = default!;
|
||||
[Inject]
|
||||
protected ILogger<TView> Logger { get; set; } = default!;
|
||||
[Parameter]
|
||||
public object? DataContext
|
||||
{
|
||||
get => field;
|
||||
set
|
||||
{
|
||||
field = value;
|
||||
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(this.DataContext)));
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
await base.OnAfterRenderAsync(firstRender);
|
||||
if (!firstRender)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this is not TView view)
|
||||
{
|
||||
throw new InvalidOperationException($"View is not of type {typeof(TView).Name}. Actual type: {this.GetType().Name}");
|
||||
}
|
||||
|
||||
this.ViewModel.SetView(view);
|
||||
using var initializationCts = new CancellationTokenSource(InitializationTimeout);
|
||||
_ = this.ViewModel ?? throw new InvalidOperationException("Cannot initialize ViewModel. ViewModel is null");
|
||||
try
|
||||
{
|
||||
await this.ViewModel.Initialize(initializationCts.Token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.Logger?.LogError(ex, "Failed to initialize ViewModel {ViewModelType}", typeof(TViewModel).Name);
|
||||
}
|
||||
}
|
||||
|
||||
internal void RefreshView()
|
||||
{
|
||||
this.StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user