Added plugin events

This commit is contained in:
2025-02-02 19:06:41 +01:00
parent 4cfeaab652
commit 13e9af892c
28 changed files with 415 additions and 87 deletions

View File

@@ -6,6 +6,8 @@
@using HopFrame.Core.Services
@using HopFrame.Web.Models
@using HopFrame.Web.Helpers
@using HopFrame.Web.Plugins
@using HopFrame.Web.Plugins.Events
<FluentDialogBody>
@foreach (var property in Content.Config.Properties.Where(prop => !prop.IsListingProperty).OrderBy(prop => prop.Order)) {
@@ -169,6 +171,7 @@
@inject IHopFrameAuthHandler Handler
@inject IToastService Toasts
@inject IServiceProvider Provider
@inject IPluginOrchestrator PluginOrchestrator
@code {
[Parameter]
@@ -374,6 +377,14 @@
if (value is null && property.IsRequired)
errorList.Add($"{property.Name} is required");
var eventResult = await PluginOrchestrator.DispatchEvent(new ValidationEvent(this) {
Errors = errorList,
Property = property,
Table = Content.Config
});
if (eventResult.IsCanceled) return false;
}
StateHasChanged();

View File

@@ -4,9 +4,11 @@
@implements IDisposable
@using HopFrame.Core.Config
@using HopFrame.Core.Events
@using HopFrame.Core.Callbacks
@using HopFrame.Core.Services
@using HopFrame.Web.Models
@using HopFrame.Web.Plugins
@using HopFrame.Web.Plugins.Events
@using Microsoft.JSInterop
@using Microsoft.EntityFrameworkCore
@@ -118,7 +120,8 @@
@inject IJSRuntime Js
@inject IDialogService Dialogs
@inject IHopFrameAuthHandler Handler
@inject IEventEmitter Emitter
@inject ICallbackEmitter Emitter
@inject IPluginOrchestrator PluginOrchestrator
@code {
@@ -199,11 +202,28 @@
_searchCancel = new();
await Task.Delay(500, _searchCancel.Token);
var eventResult = await PluginOrchestrator.DispatchEvent(new SearchEvent(this) {
SearchTerm = _searchTerm,
Table = _config!
});
if (eventResult.IsCanceled) return;
_searchTerm = eventResult.SearchTerm;
await Reload();
}
private async Task Reload() {
_loading = true;
var eventResult = await PluginOrchestrator.DispatchEvent(new ReloadEvent(this) {
Table = _config!
});
if (eventResult.IsCanceled) {
_loading = false;
return;
}
if (!string.IsNullOrEmpty(_searchTerm)) {
(var query, _totalPages) = await _manager!.Search(_searchTerm, 0, PerPage);
_currentlyDisplayedModels = query.ToArray();
@@ -215,6 +235,15 @@
}
private async Task ChangePage(int page) {
var eventResult = await PluginOrchestrator.DispatchEvent(new PageChangeEvent(this) {
CurrentPage = _currentPage,
NewPage = page,
TotalPages = _totalPages,
Table = _config!
});
if (eventResult.IsCanceled) return;
page = eventResult.NewPage;
if (page < 0 || page > _totalPages - 1) return;
_currentPage = page;
await Reload();
@@ -225,13 +254,19 @@
Navigator.NavigateTo("/admin", true);
return;
}
var eventResult = await PluginOrchestrator.DispatchEvent(new DeleteEntryEvent(this) {
Entity = element,
Table = _config!
});
if (eventResult.IsCanceled) return;
var dialog = await Dialogs.ShowConfirmationAsync("Do you really want to delete this entry?");
var result = await dialog.Result;
if (result.Cancelled) return;
await _manager!.DeleteItem(element);
await Emitter.DispatchEvent(EventTypes.DeleteEntry(_config!), element);
await Emitter.DispatchCallback(CallbackTypes.DeleteEntry(_config!), element);
await Reload();
}
@@ -240,6 +275,22 @@
Navigator.NavigateTo("/admin", true);
return;
}
HopFrameTablePageEventArgs eventArgs;
if (element is null) {
eventArgs = new CreateEntryEvent(this) {
Table = _config!
};
}
else {
eventArgs = new UpdateEntryEvent(this) {
Table = _config!,
Entity = element
};
}
var eventResult = await PluginOrchestrator.DispatchEvent(eventArgs);
if (eventResult.IsCanceled) return;
var panel = await Dialogs.ShowPanelAsync<HopFrameEditor>(new EditorDialogData(_config!, element), new DialogParameters {
TrapFocus = false
@@ -251,17 +302,25 @@
if (element is null) {
await _manager!.AddItem(data!.CurrentObject!);
await Emitter.DispatchEvent(EventTypes.CreateEntry(_config!), data.CurrentObject!);
await Emitter.DispatchCallback(CallbackTypes.CreateEntry(_config!), data.CurrentObject!);
}
else {
await _manager!.EditItem(data!.CurrentObject!);
await Emitter.DispatchEvent(EventTypes.UpdateEntry(_config!), data.CurrentObject!);
await Emitter.DispatchCallback(CallbackTypes.UpdateEntry(_config!), data.CurrentObject!);
}
await Reload();
}
private void SelectItem(object item, bool selected) {
var eventResult = PluginOrchestrator.DispatchEvent(new SelectEntryEvent(this) {
Entity = item,
Selected = selected,
Table = _config!
}).Result;
if (eventResult.IsCanceled) return;
selected = eventResult.Selected;
if (!selected)
DialogData!.SelectedObjects.Remove(item);
else DialogData!.SelectedObjects.Add(item);

View File

@@ -1,6 +1,10 @@
using HopFrame.Core.Config;
using System.Reflection;
using HopFrame.Core.Config;
using HopFrame.Web.Components.Layout;
using HopFrame.Web.Models;
using HopFrame.Web.Plugins;
using HopFrame.Web.Plugins.Annotations;
using HopFrame.Web.Plugins.Internal;
namespace HopFrame.Web;
@@ -28,5 +32,23 @@ public static class HopFrameConfiguratorExtensions {
configuratorDelegate.Invoke(viewConfigurator);
return configurator;
}
public static HopFrameConfigurator AddPlugin<TPlugin>(this HopFrameConfigurator configurator) where TPlugin : HopFramePlugin {
PluginOrchestrator.RegisterPlugin(configurator.ServiceCollection, typeof(TPlugin));
var methods = typeof(TPlugin).GetMethods()
.Where(method => method.IsStatic)
.Where(method => method.GetCustomAttributes(true)
.Any(attr => attr is PluginConfiguratorAttribute))
.Where(method => method.GetParameters().Length < 2);
foreach (var method in methods) {
if (method.GetParameters().Length > 0)
method.Invoke(null, [configurator]);
else method.Invoke(null, []);
}
return configurator;
}
}

View File

@@ -0,0 +1,4 @@
namespace HopFrame.Web.Plugins.Annotations;
[AttributeUsage(AttributeTargets.Method)]
public class EventHandlerAttribute : Attribute;

View File

@@ -0,0 +1,8 @@
namespace HopFrame.Web.Plugins.Annotations;
/// <summary>
/// Configures the method as a plugin configurator, so the method gets called, when the plugin is registered.
/// Only works on static methods
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class PluginConfiguratorAttribute : Attribute;

View File

@@ -0,0 +1,18 @@
using HopFrame.Web.Components.Pages;
namespace HopFrame.Web.Plugins.Events;
public sealed class DeleteEntryEvent(HopFrameTablePage sender) : HopFrameTablePageEventArgs(sender) {
public required object Entity { get; init; }
}
public sealed class CreateEntryEvent(HopFrameTablePage sender) : HopFrameTablePageEventArgs(sender);
public sealed class UpdateEntryEvent(HopFrameTablePage sender) : HopFrameTablePageEventArgs(sender) {
public required object Entity { get; init; }
}
public sealed class SelectEntryEvent(HopFrameTablePage sender) : HopFrameTablePageEventArgs(sender) {
public required object Entity { get; init; }
public required bool Selected { get; set; }
}

View File

@@ -0,0 +1,27 @@
using HopFrame.Core.Config;
using HopFrame.Web.Components.Dialogs;
using HopFrame.Web.Components.Pages;
namespace HopFrame.Web.Plugins.Events;
public abstract class HopFrameEventArgs(object internalSender) {
internal object InternalSender { get; } = internalSender;
public bool IsCanceled { get; protected set; }
public void SetCancelled(bool canceled) => IsCanceled = canceled;
}
public abstract class HopFrameEventArgs<TSender>(TSender sender) : HopFrameEventArgs(sender) where TSender : class {
public TSender Sender => (TSender)InternalSender;
}
public abstract class HopFrameTablePageEventArgs(HopFrameTablePage sender)
: HopFrameEventArgs<HopFrameTablePage>(sender) {
public required TableConfig Table { get; init; }
}
public abstract class HopFrameEditorEventArgs(HopFrameEditor sender)
: HopFrameEventArgs<HopFrameEditor>(sender) {
public required TableConfig Table { get; init; }
}

View File

@@ -0,0 +1,9 @@
using HopFrame.Web.Components.Pages;
namespace HopFrame.Web.Plugins.Events;
public sealed class PageChangeEvent(HopFrameTablePage sender) : HopFrameTablePageEventArgs(sender) {
public required int CurrentPage { get; init; }
public required int TotalPages { get; init; }
public required int NewPage { get; set; }
}

View File

@@ -0,0 +1,9 @@
using System.Reflection;
namespace HopFrame.Web.Plugins.Events;
internal sealed class PluginEventContainer {
public required MethodInfo Handler { get; init; }
public required Type EventType { get; init; }
public required bool IsAwaitable { get; init; }
}

View File

@@ -0,0 +1,7 @@
using HopFrame.Web.Components.Pages;
namespace HopFrame.Web.Plugins.Events;
public sealed class ReloadEvent(HopFrameTablePage sender) : HopFrameTablePageEventArgs(sender) {
}

View File

@@ -0,0 +1,7 @@
using HopFrame.Web.Components.Pages;
namespace HopFrame.Web.Plugins.Events;
public sealed class SearchEvent(HopFrameTablePage sender) : HopFrameTablePageEventArgs(sender) {
public required string SearchTerm { get; set; }
}

View File

@@ -0,0 +1,9 @@
using HopFrame.Core.Config;
using HopFrame.Web.Components.Dialogs;
namespace HopFrame.Web.Plugins.Events;
public sealed class ValidationEvent(HopFrameEditor sender) : HopFrameEditorEventArgs(sender) {
public required IList<string> Errors { get; init; }
public required PropertyConfig Property { get; init; }
}

View File

@@ -0,0 +1,7 @@
namespace HopFrame.Web.Plugins;
public abstract class HopFramePlugin {
}

View File

@@ -0,0 +1,5 @@
namespace HopFrame.Web.Plugins;
public interface IPluginOrchestrator {
public Task<TEvent> DispatchEvent<TEvent>(TEvent @event, CancellationToken ct = new());
}

View File

@@ -0,0 +1,46 @@
using HopFrame.Web.Plugins.Annotations;
using HopFrame.Web.Plugins.Events;
using Microsoft.Extensions.DependencyInjection;
namespace HopFrame.Web.Plugins.Internal;
internal sealed class PluginOrchestrator(IServiceProvider services) : IPluginOrchestrator {
public static void RegisterPlugin(IServiceCollection collection, Type plugin) {
var methods = plugin.GetMethods()
.Where(method => method.GetCustomAttributes(true)
.Any(attr => attr is EventHandlerAttribute));
foreach (var method in methods) {
var awaitable = method.ReturnType.IsAssignableFrom(typeof(Task));
var eventType = method
.GetParameters()
.FirstOrDefault(param => param.ParameterType.IsAssignableTo(typeof(HopFrameEventArgs)))?.ParameterType;
if (eventType is null) continue;
var container = new PluginEventContainer {
EventType = eventType,
IsAwaitable = awaitable,
Handler = method
};
collection.AddSingleton(container);
collection.AddScoped(plugin);
}
}
public async Task<TEvent> DispatchEvent<TEvent>(TEvent @event, CancellationToken ct = new()) {
var eventContainers = services.GetRequiredService<IEnumerable<PluginEventContainer>>()
.Where(container => container.EventType == typeof(TEvent));
foreach (var container in eventContainers) {
var plugin = services.GetRequiredService(container.Handler.DeclaringType!);
var result = container.Handler.Invoke(plugin, [@event]);
if (container.IsAwaitable)
await (Task)result!;
}
return @event;
}
}

View File

@@ -1,8 +1,10 @@
using HopFrame.Core;
using HopFrame.Core.Config;
using HopFrame.Core.Events;
using HopFrame.Core.Callbacks;
using HopFrame.Web.Components;
using HopFrame.Web.Components.Pages;
using HopFrame.Web.Plugins;
using HopFrame.Web.Plugins.Internal;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.FluentUI.AspNetCore.Components;
using Microsoft.AspNetCore.Builder;
@@ -21,7 +23,7 @@ public static class ServiceCollectionExtensions {
/// <returns>The same service collection that is passed in</returns>
public static IServiceCollection AddHopFrame(this IServiceCollection services, Action<HopFrameConfigurator> configurator, LibraryConfiguration? fluentUiLibraryConfiguration = null, bool addRazorComponents = true) {
var config = new HopFrameConfig();
configurator.Invoke(new HopFrameConfigurator(config));
configurator.Invoke(new HopFrameConfigurator(config, services));
return AddHopFrame(services, config, fluentUiLibraryConfiguration, addRazorComponents);
}
@@ -38,6 +40,8 @@ public static class ServiceCollectionExtensions {
services.AddHopFrameServices();
services.AddFluentUIComponents(fluentUiLibraryConfiguration);
services.AddScoped<IPluginOrchestrator, PluginOrchestrator>();
if (addRazorComponents) {
services.AddRazorComponents()
.AddInteractiveServerComponents();