Skip to content

Commit

Permalink
Merge with main
Browse files Browse the repository at this point in the history
  • Loading branch information
Florian Gilde committed Dec 17, 2024
2 parents 49d2e44 + bcc0421 commit 78998f5
Show file tree
Hide file tree
Showing 21 changed files with 197 additions and 110 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -190,5 +190,5 @@ void Submit(DialogResult result)
/// <summary>
/// Cancels the dialog
/// </summary>
void Cancel() => MudDialog.CloseAnimatedIf();
void Cancel() => MudDialog.CloseAnimatedIf(JsRuntime);
}
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@
return
@<MudExPropertyEdit @ref="@Ref" DisableFieldFallback="@DisableFieldFallback"
RenderKey="@RenderKey"
AutoFocus="@HasAutoFocus(property)"
ReadOnlyOverwrite="@ReadOnlyOverwrite"
StoreAndReadValueFromUrl="@StoreAndReadValueFromUrl"
ShowPathAsTitle="@ShowPathAsTitleForEachProperty"
Expand Down
83 changes: 49 additions & 34 deletions MudBlazor.Extensions/Components/ObjectEdit/MudExObjectEdit.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using Nextended.Core.Extensions;
using Nextended.Core.Helper;
using Nextended.Core.Scopes;
using TagLib;
using IComponent = Microsoft.AspNetCore.Components.IComponent;

namespace MudBlazor.Extensions.Components.ObjectEdit;
Expand Down Expand Up @@ -51,17 +52,17 @@ public partial class MudExObjectEdit<T>
/// Returns true if we have a registration for the current object that then uses the registered component
/// </summary>
protected bool HasRegistrationForWholeObject => RenderWithType != null;

/// <summary>
/// Is true if currently is an internal Bulk running. Like reset or clear etc.
/// </summary>
protected bool IsInternalLoading;

/// <summary>
/// ToolBarContent
/// </summary>
protected virtual RenderFragment InternalToolBarContent => null;

/// <summary>
/// Is true if the value is a primitive type
/// </summary>
Expand Down Expand Up @@ -149,7 +150,7 @@ public T Value
/// <summary>
/// If this setting is true, after import all properties are set instead of full value assignment
/// </summary>
[Obsolete("This will hopefully be removed in future versions. Only use it if you have problems with the import or restore feature")]
[Obsolete("This will hopefully be removed in future versions. Only use it if you have problems with the import or restore feature")]
[Parameter] public bool SetPropertiesAfterImport { get; set; }

/// <summary>
Expand Down Expand Up @@ -466,7 +467,7 @@ public bool SearchActive
/// The behaviour how registered Meta and configured meta should applied
/// </summary>
[Parameter] public RegisteredConfigurationBehaviour ConfigureBehaviourForRegisteredConfigurations { get; set; } = RegisteredConfigurationBehaviour.ExecutedBefore;

/**
* If this setting is true a manual passed MetaInformation will also re configured
*/
Expand All @@ -476,7 +477,7 @@ public bool SearchActive
/// Error message to display
/// </summary>
[Parameter] public string ErrorMessage { get; set; }

/// <summary>
/// Set this to handle Reset on your own
/// </summary>
Expand Down Expand Up @@ -507,7 +508,7 @@ public bool SearchActive
public MudExPropertyEdit Ref { set => Editors.Add(value); }

internal static bool IsPrimitive() => MudExObjectEditHelper.HandleAsPrimitive(typeof(T));

#region Overrides

/// <inheritdoc/>
Expand All @@ -522,7 +523,7 @@ protected override async Task OnParametersSetAsync()
CancelText = TryLocalize("Cancel"),
YesText = TryLocalize("Reset")
};

}

/// <inheritdoc/>
Expand Down Expand Up @@ -709,7 +710,7 @@ protected virtual async Task OnPropertyChange(ObjectEditPropertyMeta property)
{
if (!IsRendered)
return;

if (AutoSaveRestoreState)
_ = Task.Run(SaveState);

Expand Down Expand Up @@ -746,12 +747,13 @@ private bool IsInFilter(ObjectEditPropertyMeta propertyMeta)
// No filters, nothing to filter against, so return true
return !allFilters.Any() ||
// Loop through each filter in allFilters
(from filter in allFilters where !string.IsNullOrWhiteSpace(filter)
select propertyMeta.Settings.LabelFor(LocalizerToUse).Contains(filter, StringComparison.InvariantCultureIgnoreCase)
|| propertyMeta.Settings.DescriptionFor(LocalizerToUse).Contains(filter, StringComparison.InvariantCultureIgnoreCase)
|| propertyMeta.PropertyInfo.Name.Contains(filter, StringComparison.InvariantCultureIgnoreCase)
|| (propertyMeta.Value?.ToString()?.Contains(filter, StringComparison.InvariantCultureIgnoreCase) == true)
|| (propertyMeta.GroupInfo?.Name?.Contains(filter, StringComparison.InvariantCultureIgnoreCase) == true)
(from filter in allFilters
where !string.IsNullOrWhiteSpace(filter)
select propertyMeta.Settings.LabelFor(LocalizerToUse).Contains(filter, StringComparison.InvariantCultureIgnoreCase)
|| propertyMeta.Settings.DescriptionFor(LocalizerToUse).Contains(filter, StringComparison.InvariantCultureIgnoreCase)
|| propertyMeta.PropertyInfo.Name.Contains(filter, StringComparison.InvariantCultureIgnoreCase)
|| (propertyMeta.Value?.ToString()?.Contains(filter, StringComparison.InvariantCultureIgnoreCase) == true)
|| (propertyMeta.GroupInfo?.Name?.Contains(filter, StringComparison.InvariantCultureIgnoreCase) == true)
|| (propertyMeta.RenderData?.Attributes.Values.OfType<string>().Any(x => x.Contains(filter, StringComparison.InvariantCultureIgnoreCase)) == true))
.Any(matchesCurrentFilter => matchesCurrentFilter);
}
Expand All @@ -761,7 +763,7 @@ select propertyMeta.Settings.LabelFor(LocalizerToUse).Contains(filter, StringCom
private bool ShouldAddGrid(IEnumerable<ObjectEditPropertyMeta> meta) => WrapInMudGrid ?? ContainsMudItemInWrapper(meta);
private string CssClassName => GroupingStyle == GroupingStyle.Flat ? $"mud-ex-object-edit-group-flat {(!GroupsCollapsible ? "mud-ex-hide-expand-btn" : "")}" : string.Empty;


private List<IGrouping<string, ObjectEditPropertyMeta>> DefaultGroupedMetaPropertyInfos() // Here we filter ignore directly
=> MetaInformation?.AllProperties?.EmptyIfNull()
.Where(m => m.ShouldRender() && IsInFilter(m) && (!AutoHideDisabledFields || m.Settings.IsEditable))
Expand All @@ -774,8 +776,8 @@ private List<IGrouping<string, ObjectEditPropertyMeta>> AllGroupedMetaPropertyIn
.GroupBy(m => !DisableGrouping ? m.GroupInfo?.Name : string.Empty)
.ToList();

private List<IGrouping<string, ObjectEditPropertyMeta>> GroupedMetaPropertyInfos()

private List<IGrouping<string, ObjectEditPropertyMeta>> GroupedMetaPropertyInfos()
=> !RenderIgnoredReferences ? DefaultGroupedMetaPropertyInfos() : AllGroupedMetaPropertyInfos();


Expand Down Expand Up @@ -818,23 +820,23 @@ protected virtual async Task CreateMetaIfNotExists(bool? reconfigure = null)
if (c != null)
await Task.Run(() => c.Invoke(ConfigureMetaBase(MetaInformation)));
else
await Task.Run(() => ConfigureMetaBase(MetaInformation));
await Task.Run(() => ConfigureMetaBase(MetaInformation));

if (ConfigService != null && ConfigureBehaviourForRegisteredConfigurations == RegisteredConfigurationBehaviour.ExecutedAfter)
await ConfigService.ConfigureAsync(MetaInformation);
UpdateConditions();

UpdateConditions();
}
}

private async Task OnResetClick(MouseEventArgs arg)
{
if (GlobalResetSettings.RequiresConfirmation && DialogService != null && !(await ShowConfirmationBox()))
return;
await Reset();
CallStateHasChanged();
}

private async Task<bool> ShowConfirmationBox()
{
ResetConfirmationDialogOptions ??= new DialogOptionsEx
Expand Down Expand Up @@ -936,18 +938,18 @@ private IDictionary<string, object> GetAttributesForPrimitive()

return res;
}

private IDictionary<string, object> GetCompatibleParameters(Type componentType)
{
var res = ComponentRenderHelper.GetCompatibleParameters(this, componentType)
.Where(p => IsOverwritten(p.Key)).ToDictionary(p => p.Key, p => p.Value);

foreach (var parameter in UserAttributes.Where(parameter => ComponentRenderHelper.IsValidParameter(componentType, parameter.Key, parameter.Value)))
{
res.AddOrUpdate(parameter.Key, parameter.Value);
}

if(ReadOnlyOverwrite.HasValue)
if (ReadOnlyOverwrite.HasValue)
res.AddOrUpdate(nameof(MudBaseInput<object>.ReadOnly), ReadOnlyOverwrite.Value);
res.AddOrUpdate(nameof(Value), Value);
res.AddOrUpdate(nameof(ValueChanged), RuntimeHelpers.TypeCheck(
Expand All @@ -974,8 +976,8 @@ protected async Task Export()
{
var exported = new ExportData<T> { Value = Value, Json = await ToJsonAsync() };
await BeforeExport.InvokeAsync(exported);
if(exported.Cancel)

if (exported.Cancel)
return;

IsInternalLoading = true;
Expand Down Expand Up @@ -1012,7 +1014,7 @@ public Task<string> ToJsonAsync()
public string ToJson()
{
var ignored = MetaInformation.Properties().Where(p => p.Settings.IgnoreOnExport).Select(m => m.PropertyName).ToArray();

var json = JsonConvert.SerializeObject(Value, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Expand Down Expand Up @@ -1067,7 +1069,7 @@ private async Task Import(InputFileChangeEventArgs e)
{
var buffer = new byte[e.File.Size];
await e.File.OpenReadStream(e.File.Size).ReadAsync(buffer);

var toImport = new ImportData<T> { Json = Encoding.UTF8.GetString(buffer), Value = Value };
await BeforeImport.InvokeAsync(toImport);
if (toImport.Cancel || await ShouldCancelImportAsync(toImport.Json, e.File.Name))
Expand All @@ -1078,7 +1080,7 @@ private async Task Import(InputFileChangeEventArgs e)

await LoadFromJson(toImport.Json, RemoveIgnoredFromImport);
await ImportSuccessUi();
await AfterImport.InvokeAsync(new ImportedData<T> {Json = toImport.Json, Value = Value});
await AfterImport.InvokeAsync(new ImportedData<T> { Json = toImport.Json, Value = Value });
}
catch (Exception ex)
{
Expand Down Expand Up @@ -1117,7 +1119,7 @@ public Task LoadFromJson(string json, bool removeIgnoredImports)
SetValueAfterImport(JsonConvert.DeserializeObject<T>(json));
return;
}

var obj = JsonConvert.DeserializeObject(json, Value.GetType());
var notIgnored = obj.ToFlatDictionary().Where(kvp => !ignored.Contains(kvp.Key) && !ignored.Any(path => PropertyHelper.IsPropertyPathSubPropertyOf(kvp.Key, path))).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Expand All @@ -1134,7 +1136,7 @@ public Task LoadFromJson(string json, bool removeIgnoredImports)
}
private void SetValueAfterImport(T value)
{
if(SetPropertiesAfterImport)
if (SetPropertiesAfterImport)
SetEditorValueProperties(value);
else
Value = value;
Expand Down Expand Up @@ -1177,4 +1179,17 @@ private IDictionary<string, object> GetPropertiesWithPaths(object obj, string cu

return result;
}

bool _defaultFocus = true;
private bool HasAutoFocus(ObjectEditPropertyMeta property)
{
var isConfigured = MetaInformation.AllProperties.Any(p => p?.Settings?.AutoFocus == true);
if (isConfigured)
return property?.Settings?.AutoFocus == true;
var res = _defaultFocus;
_defaultFocus = false;
if (res)
property.WithDefaultFocus();
return res;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.JSInterop;
using MudBlazor.Extensions.Components.ObjectEdit.Options;
using MudBlazor.Extensions.Core;
using MudBlazor.Extensions.Helper;
Expand Down Expand Up @@ -129,7 +130,7 @@ protected override async Task OnSubmit(EditContext ctx)
await base.OnSubmit(ctx);
if (CustomSubmit == null || string.IsNullOrWhiteSpace(_errorMessage = await CustomSubmit.Invoke(Value, this)))
{
MudDialog.CloseAnimatedIf(DialogResult.Ok(Value));
MudDialog.CloseAnimatedIf(DialogResult.Ok(Value), JsRuntime);
}
}
finally
Expand All @@ -145,6 +146,6 @@ protected override async Task OnSubmit(EditContext ctx)
protected override async Task Cancel()
{
await base.Cancel();
MudDialog.CancelAnimatedIf();
MudDialog.CancelAnimatedIf(JsRuntime);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,15 @@ public static ObjectEditPropertyMeta RenderWith(this ObjectEditPropertyMeta meta
public static ObjectEditPropertyMeta AsReadOnly(this ObjectEditPropertyMeta meta, bool isReadOnly = true)
=> meta?.SetProperties(p => p.Settings.IsEditable = !isReadOnly, p => p?.RenderData?.AddAttributes(true, new KeyValuePair<string, object>(nameof(MudBaseInput<string>.ReadOnly), isReadOnly)));

///<summary>
/// Marks an ObjectEditPropertyMeta to have Auto focus
/// <param name="meta">The ObjectEditPropertyMeta instance to modify.</param>
/// <returns>The modified ObjectEditPropertyMeta instance.</returns>
///</summary>
public static ObjectEditPropertyMeta WithDefaultFocus(this ObjectEditPropertyMeta meta)
=> meta?.SetProperties(p => p.Settings.AutoFocus = true, p => p?.RenderData?.AddAttributes(true, new KeyValuePair<string, object>(nameof(MudBaseInput<string>.AutoFocus), true)));


///<summary>
/// Disables the underline for an ObjectEditPropertyMeta.
/// <param name="meta">The ObjectEditPropertyMeta instance to modify.</param>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
//Todo we need to have value changed or something to raise also this PropertyValueChanged
result = @<MudTextField ReadOnly="@(!PropertyMeta.Settings.IsEditable)"
For="@(CreateFieldForExpression<string>())"
AutoFocus="@AutoFocus"
HelperText="@(PropertyMeta.Settings.DescriptionFor(Localizer))"
Label="@(PropertyMeta.Settings.LabelFor(Localizer))"
@bind-Value="PropertyMeta.As<string>(true).Value">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ namespace MudBlazor.Extensions.Components.ObjectEdit;
/// </summary>
public partial class MudExPropertyEdit
{
private bool? _autoFocus;

/// <summary>
/// Editor should be focused on load
/// </summary>
[Parameter]
public bool AutoFocus
{
get => _autoFocus ?? PropertyMeta.Settings.AutoFocus;
set => _autoFocus = value;
}

/// <summary>
/// If this is set all properties will be readonly depending on the value otherwise the property settings for meta configuration will be used
Expand Down Expand Up @@ -87,6 +98,7 @@ public DynamicComponent Editor
private bool _urlSetDone;

private DynamicComponent _editor;

//private Expression<Func<TPropertyType>> CreateFieldForExpression<TPropertyType>()
// => Check.TryCatch<Expression<Func<TPropertyType>>, Exception>(() => Expression.Lambda<Func<TPropertyType>>(Expression.Property(Expression.Constant(PropertyMeta.ReferenceHolder, PropertyMeta.ReferenceHolder.GetType()), PropertyMeta.PropertyInfo)));

Expand Down Expand Up @@ -159,6 +171,7 @@ private IDictionary<string, object> GetPreparedAttributes()
.TrySetAttributeIfAllowed(nameof(Style), () => Style)
.TrySetAttributeIfAllowed(nameof(Localizer), Localizer)
.TrySetAttributeIfAllowed(nameof(RenderKey), RenderKey)
.TrySetAttributeIfAllowed(nameof(AutoFocus), AutoFocus)
.TrySetAttributeIfAllowed(nameof(MudBaseInput<string>.ReadOnly), () => !PropertyMeta.Settings.IsEditable);

if (ReadOnlyOverwrite.HasValue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,12 @@ public ObjectEditPropertyMetaSettings(ObjectEditPropertyMeta owner)
/// Determines if the property is editable.
/// </summary>
public bool IsEditable { get; set; }


/// <summary>
/// Should have Auto focus.
/// </summary>
public bool AutoFocus { get; set; }

/// <summary>
/// Determines if the property is ignored.
/// </summary>
Expand Down
4 changes: 4 additions & 0 deletions MudBlazor.Extensions/Docs/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
## Change Log
- 2.1.0 > MudExObject now supports default focused element within the meta configuration with `meta.Property(m => m.LastName).WithDefaultFocus()`
- 2.1.0 > MudExObject edit now has AutoFocus for first input field if no other focus is configured
- 2.1.0 > Provide a Middleware again without deprecated UseMudExtensions now you should use `app.Use(MudExWebApp.MudExMiddleware);`
- 2.1.0 > Fix another bug with dialog that only occurs on webassembly projects hosted in a .net8 runtime
- 2.0.9 > Fix bug with dialog animations on server side rendered projects #112
- 2.0.8 > Ensure dialog initial relative state if configured
- 2.0.8 > Fix Remove Item Bug in Collection editor
Expand Down
Loading

0 comments on commit 78998f5

Please sign in to comment.