Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
@@ -0,0 +1,81 @@
@namespace Bit.BlazorUI
@inherits BitComponentBase

<div @ref="@RootElement" @attributes="HtmlAttributes"
id="@_Id"
style="@StyleBuilder.Value"
class="@ClassBuilder.Value"
dir="@Dir?.ToString().ToLower()">

@if (LabelTemplate is not null)
{
@LabelTemplate
}
else if (HideLabel is false)
{
<button @onclick="Browse"
type="button"
class="bit-fin-lbl">
@(Label ?? "Browse")
</button>
}

<input @ref="_inputRef"
@onchange="HandleOnChange"
type="file"
id="@InputId"
class="bit-fin-fi"
multiple="@Multiple"
disabled="@(IsEnabled is false)"
aria-labelledby="@(Label.HasValue() ? Label : null)"
accept="@(Accept ?? string.Join(",", AllowedExtensions))" />

@if (Files is not null && HideFileList is false)
{
<div class="bit-fin-fl">
@for (var i = 0; i < Files.Count; i++)
{
var index = i;
var file = Files[index];
file.Index = index;

if (HideFileList is false)
{
if (FileViewTemplate is not null)
{
@FileViewTemplate(file)
}
else
{
<div class="bit-fin-itm @GetFileElClass(file.IsValid)">
<div class="bit-fin-fic">
<div title="@file.Name" class="bit-fin-fnc">
<div class="bit-fin-fn">
@file.Name
</div>
</div>
<div class="bit-fin-fsc">
<span class="bit-fin-fs">
@FileSizeHumanizer.Humanize(file.Size)
</span>
</div>
@if (file.IsValid is false)
{
<div class="bit-fin-us">
@file.Message
</div>
}
</div>
@if (ShowRemoveButton)
{
<div class="bit-fin-usi" @onclick="() => RemoveFile(file)">
<i title="remove" class="bit-icon bit-icon--Delete" aria-hidden="true" />
</div>
}
</div>
}
}
}
</div>
}
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
namespace Bit.BlazorUI;

/// <summary>
/// BitFileInput component wraps the HTML file input element(s) and allows file selection. The selected files can be accessed from the C# context for further processing.
/// </summary>
public partial class BitFileInput : BitComponentBase
{
private ElementReference _inputRef;
private List<BitFileInputInfo> _files = [];
private IJSObjectReference _dropZoneRef = default!;



[Inject] private IJSRuntime _js { get; set; } = default!;



/// <summary>
/// The value of the accept attribute of the input element.
/// </summary>
[Parameter] public string? Accept { get; set; }

/// <summary>
/// Filters files by extension.
/// </summary>
[Parameter] public IReadOnlyCollection<string> AllowedExtensions { get; set; } = ["*"];

/// <summary>
/// Enables the append mode that adds any additional selected file(s) to the current file list.
/// </summary>
[Parameter] public bool Append { get; set; }

/// <summary>
/// Automatically resets the file input before starting to browse for files.
/// </summary>
[Parameter] public bool AutoReset { get; set; }

/// <summary>
/// Hides the file list section of the file input.
/// </summary>
[Parameter] public bool HideFileList { get; set; }

/// <summary>
/// Hides the label of the file input.
/// </summary>
[Parameter] public bool HideLabel { get; set; }

/// <summary>
/// The text of select file button.
/// </summary>
[Parameter] public string? Label { get; set; }

/// <summary>
/// A custom razor template for select button.
/// </summary>
[Parameter] public RenderFragment? LabelTemplate { get; set; }

/// <summary>
/// Specifies the maximum allowed file size in bytes (0 for unlimited).
/// </summary>
[Parameter] public long MaxSize { get; set; }

/// <summary>
/// Specifies the message for the failed validation due to exceeding the maximum size.
/// </summary>
[Parameter] public string? MaxSizeErrorMessage { get; set; }

/// <summary>
/// Enables multi-file selection.
/// </summary>
[Parameter] public bool Multiple { get; set; }

/// <summary>
/// Specifies the message for the failed validation due to the allowed extensions.
/// </summary>
[Parameter] public string? NotAllowedExtensionErrorMessage { get; set; }

/// <summary>
/// Callback for when file or files selection changes.
/// </summary>
[Parameter] public EventCallback<BitFileInputInfo[]> OnChange { get; set; }

/// <summary>
/// Shows the remove button for each selected file.
/// </summary>
[Parameter] public bool ShowRemoveButton { get; set; }

/// <summary>
/// The custom file view template.
/// </summary>
[Parameter] public RenderFragment<BitFileInputInfo>? FileViewTemplate { get; set; }



/// <summary>
/// A list of all of the selected files.
/// </summary>
public IReadOnlyList<BitFileInputInfo> Files => _files;

/// <summary>
/// The id of the file input element.
/// </summary>
public string? InputId { get; private set; }



/// <summary>
/// Opens a file selection dialog.
/// </summary>
public async Task Browse()
{
if (IsEnabled is false) return;

if (AutoReset)
{
await Reset();
}

await _js.BitFileInputBrowse(_inputRef);
}

/// <summary>
/// Resets the file input.
/// </summary>
public async Task Reset()
{
_files.Clear();

await _js.BitFileInputReset(UniqueId, _inputRef);

StateHasChanged();
}

/// <summary>
/// Removes a file from the selected files list.
/// </summary>
/// <param name="fileInfo">
/// null => all files | else => specific file
/// </param>
public void RemoveFile(BitFileInputInfo? fileInfo = null)
{
if (_files.Any() is false) return;

if (fileInfo is null)
{
_files.Clear();
}
else
{
_files.Remove(fileInfo);
}

StateHasChanged();
}



protected override string RootElementClass => "bit-fin";

protected override Task OnInitializedAsync()
{
InputId = $"FileInput-{UniqueId}-input";

return base.OnInitializedAsync();
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender is false) return;

_dropZoneRef = await _js.BitFileInputSetupDragDrop(RootElement, _inputRef);
}



private bool IsFileTypeNotAllowed(BitFileInputInfo file)
{
if (Accept.HasNoValue()) return false;

var fileSections = file.Name.Split('.');
var extension = $".{fileSections?.Last()}";

return AllowedExtensions.Count > 0 &&
AllowedExtensions.All(ext => ext != "*") &&
AllowedExtensions.All(ext => ext != extension);
}

private async Task HandleOnChange()
{
if (Append is false)
{
_files.Clear();
}

if (IsDisposed) return;

var newFiles = await _js.BitFileInputSetup(UniqueId, _inputRef, Append);

foreach (var file in newFiles)
{
// Validate file size
if (MaxSize > 0 && file.Size > MaxSize)
{
file.IsValid = false;
file.Message = MaxSizeErrorMessage ?? "The file size is larger than the max size";
}
// Validate file extension
else if (IsFileTypeNotAllowed(file))
{
file.IsValid = false;
file.Message = NotAllowedExtensionErrorMessage ?? "The file type is not allowed";
}
}

_files.AddRange(newFiles);

await OnChange.InvokeAsync([.. _files]);
}

private string GetFileElClass(bool isValid)
{
return isValid ? $"bit-fin-vld" : $"bit-fin-inv";
}



protected override async ValueTask DisposeAsync(bool disposing)
{
if (IsDisposed || disposing is false) return;

await base.DisposeAsync(disposing);

if (_dropZoneRef is not null)
{
try
{
await _dropZoneRef.InvokeVoidAsync("dispose");
await _dropZoneRef.DisposeAsync();
}
catch (JSDisconnectedException) { } // we can ignore this exception here
catch (JSException ex)
{
// it seems it's safe to just ignore this exception here.
// otherwise it will blow up the MAUI app in a page refresh for example.
Console.WriteLine(ex.Message);
}
}

try
{
await _js.BitFileInputClear(UniqueId);
}
catch (JSDisconnectedException) { } // we can ignore this exception here
}
}
Loading
Loading