Deliver each drop to the zone under the cursor

This commit is contained in:
Thorsten Sommer committed 2026-09-10 11:32:08 +02:00
1 parent d741a6e06d
commit 14066a93fb
40 files changed
+446 -394

No files matched your search

@@ -3,7 +3,7 @@
@if (this.UseSmallForm)
{
<MudStack Spacing="0">
<div @onmouseenter="@this.OnMouseEnter" @onmouseleave="@this.OnMouseLeave">
<div data-drop-zone-id="@this.dropZoneId">
@if (this.isDraggingOver)
{
<MudBadge
@@ -82,7 +82,7 @@ else
{
<MediaTranscriptionStatus Owner="@this.EffectiveImportOwner" TargetId="@this.EffectiveMediaImportTarget.TargetId"/>
}
<div @onmouseenter="@this.OnMouseEnter" @onmouseleave="@this.OnMouseLeave">
<div data-drop-zone-id="@this.dropZoneId">
<MudPaper Height="20em" Outlined="true" Class="@this.dragClass" Style="overflow-y: auto;">
@foreach (var fileAttachment in this.DocumentPaths)
{
@@ -24,18 +24,6 @@ public partial class AttachDocuments : MSGComponentBase
[Parameter]
public string Name { get; set; } = string.Empty;
/// <summary>
/// On which layer to register the drop area. Higher layers have priority over lower layers.
/// </summary>
[Parameter]
public int Layer { get; set; }
/// <summary>
/// When true, pause catching dropped files. Default is false.
/// </summary>
[Parameter]
public bool PauseCatchingDrops { get; set; }
[Parameter]
public HashSet<FileAttachment> DocumentPaths { get; set; } = [];
@@ -46,11 +34,23 @@ public partial class AttachDocuments : MSGComponentBase
public Func<HashSet<FileAttachment>, Task> OnChange { get; set; } = _ => Task.CompletedTask;
/// <summary>
/// Catch all documents that are hovered over the AI Studio window and not only over the drop zone.
/// Makes this component the default target of its area, meaning of its page, assistant, or
/// dialog: it then also takes the drops which land anywhere in that area without hitting a zone
/// of their own.
/// </summary>
/// <remarks>
/// Only one zone per area can hold that role, and if several ask for it, the first one in the
/// markup gets it.
/// </remarks>
[Parameter]
public bool CatchAllDocuments { get; set; }
/// <summary>
/// The area this component lives in, if it lives in one at all.
/// </summary>
[CascadingParameter]
private DropZoneScopeState? Scope { get; set; }
[Parameter]
public bool UseSmallForm { get; set; }
@@ -105,8 +105,9 @@ public partial class AttachDocuments : MSGComponentBase
private const Placement TOOLBAR_TOOLTIP_PLACEMENT = Placement.Top;
private static readonly string DROP_FILES_HERE_TEXT = TB("Drop files here to attach them.");
private uint numDropAreasAboveThis;
private bool isComponentHovered;
private readonly string dropZoneId = $"attach-documents-{Guid.NewGuid():N}";
private bool isDefaultZone;
private bool isDraggingOver;
private bool isFileDialogOpen;
private MediaImportOwner EffectiveImportOwner => this.OwnerChat is not null
@@ -122,10 +123,9 @@ public partial class AttachDocuments : MSGComponentBase
protected override async Task OnInitializedAsync()
{
this.MediaTranscriptionService.StateChanged += this.OnMediaImportStateChanged;
this.ApplyFilters([], [ Event.TAURI_EVENT_RECEIVED, Event.REGISTER_FILE_DROP_AREA, Event.UNREGISTER_FILE_DROP_AREA ]);
this.ApplyFilters([], [ Event.HIGHLIGHT_DROP_ZONE, Event.PATHS_DROPPED ]);
this.ClaimDefaultZoneRole();
// Register this drop area:
await this.MessageBus.SendMessage(this, Event.REGISTER_FILE_DROP_AREA, this.Layer);
await base.OnInitializedAsync();
}
@@ -223,93 +223,37 @@ public partial class AttachDocuments : MSGComponentBase
{
this.MediaTranscriptionService.StateChanged -= this.OnMediaImportStateChanged;
// Release the drop area. Without this, drop areas below this one would count this component
// forever and would stop catching dropped files:
this.MessageBus.SendMessage(this, Event.UNREGISTER_FILE_DROP_AREA, this.Layer).Observe($"{nameof(AttachDocuments)}: releasing the drop area");
// Hand the role of the default target back to the area:
if (this.isDefaultZone)
this.Scope?.ReleaseDefaultZone(this);
base.DisposeResources();
}
protected override async Task ProcessIncomingMessage<T>(ComponentBase? sendingComponent, Event triggeredEvent, T? data) where T : default
{
if (this.IsUnavailable && triggeredEvent == Event.TAURI_EVENT_RECEIVED)
return;
switch (triggeredEvent)
{
case Event.REGISTER_FILE_DROP_AREA when sendingComponent != this:
{
if(data is int layer && layer > this.Layer)
{
this.numDropAreasAboveThis++;
this.PauseCatchingDrops = true;
}
case Event.HIGHLIGHT_DROP_ZONE when data is DropZoneHighlight highlight:
this.ApplyHighlight(this.IsThisZone(highlight.ZoneId));
break;
}
case Event.UNREGISTER_FILE_DROP_AREA when sendingComponent != this:
{
if(data is int layer && layer > this.Layer)
{
if(this.numDropAreasAboveThis > 0)
this.numDropAreasAboveThis--;
case Event.PATHS_DROPPED when data is DroppedPaths dropped:
// Whoever the drop was meant for, the drag is over and no zone stays highlighted:
this.ApplyHighlight(false);
if(this.numDropAreasAboveThis is 0)
this.PauseCatchingDrops = false;
}
break;
}
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.FILE_DROP_HOVERED }:
if(this.PauseCatchingDrops)
if (!this.IsThisZone(dropped.ZoneId))
return;
if(!this.isComponentHovered && !this.CatchAllDocuments)
if (this.IsUnavailable)
{
this.Logger.LogDebug("Attach documents component '{Name}' is not hovered, ignoring file drop hovered event.", this.Name);
this.Logger.LogDebug("The attachment zone '{Name}' is unavailable and swallowed {Count} dropped path(s).", this.Name, dropped.Paths.Count);
return;
}
this.isDraggingOver = true;
this.SetDragClass();
this.StateHasChanged();
break;
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.FILE_DROP_CANCELED }:
if(this.PauseCatchingDrops)
return;
this.isDraggingOver = false;
this.StateHasChanged();
break;
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.WINDOW_NOT_FOCUSED }:
if(this.PauseCatchingDrops)
return;
this.isDraggingOver = false;
this.isComponentHovered = false;
this.ClearDragClass();
this.StateHasChanged();
break;
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.FILE_DROP_DROPPED, Payload: var paths }:
if(this.PauseCatchingDrops)
return;
if(!this.isComponentHovered && !this.CatchAllDocuments)
{
this.Logger.LogDebug("Attach documents component '{Name}' is not hovered, ignoring file drop dropped event.", this.Name);
return;
}
await this.AddFileBatchAsync(paths);
await this.AddFileBatchAsync(dropped.Paths);
await this.DocumentPathsChanged.InvokeAsync(this.DocumentPaths);
await this.OnChange(this.DocumentPaths);
this.isDraggingOver = false;
this.ClearDragClass();
this.StateHasChanged();
break;
}
@@ -317,6 +261,48 @@ public partial class AttachDocuments : MSGComponentBase
#endregion
/// <summary>
/// Asks the area for the role of its default target, if this component wants it.
/// </summary>
private void ClaimDefaultZoneRole()
{
if (!this.CatchAllDocuments || this.Scope is null)
return;
this.isDefaultZone = this.Scope.TryBecomeDefaultZone(this);
if (!this.isDefaultZone)
this.Logger.LogDebug("The attachment zone '{Name}' asked to be the default target of its area, which another zone already is. It now takes only the drops aimed at itself.", this.Name);
}
/// <summary>
/// Decides whether the named zone is this one.
/// </summary>
/// <remarks>
/// The area counts as this zone as long as this zone is its default target. That is the whole
/// mechanism behind dropping anywhere in the chat and still landing on the composer.
/// </remarks>
/// <param name="zoneId">The ID the hit test reported, or null when it hit nothing.</param>
private bool IsThisZone(string? zoneId) => zoneId is not null && (zoneId == this.dropZoneId || (this.isDefaultZone && zoneId == this.Scope?.ScopeId));
/// <summary>
/// Highlights the zone, or takes the highlight away.
/// </summary>
/// <remarks>
/// The comparison is not for tidiness: a throttled drag-over event arrives about ten times per
/// second, and without it every one of them would render every zone on the page anew. In the
/// small form the highlight also swaps the markup, so this keeps the composer from flickering.
/// </remarks>
private void ApplyHighlight(bool shouldBeHighlighted)
{
var highlighted = shouldBeHighlighted && !this.IsUnavailable;
if (highlighted == this.isDraggingOver)
return;
this.isDraggingOver = highlighted;
this.dragClass = highlighted ? $"{DEFAULT_DRAG_CLASS} mud-border-primary border-4" : DEFAULT_DRAG_CLASS;
this.StateHasChanged();
}
private const string DEFAULT_DRAG_CLASS = "relative rounded-lg border-2 border-dashed pa-4 mt-4 mud-width-full mud-height-full";
private string dragClass = DEFAULT_DRAG_CLASS;
@@ -370,32 +356,6 @@ public partial class AttachDocuments : MSGComponentBase
await this.OnChange(this.DocumentPaths);
}
private void SetDragClass() => this.dragClass = $"{DEFAULT_DRAG_CLASS} mud-border-primary border-4";
private void ClearDragClass() => this.dragClass = DEFAULT_DRAG_CLASS;
private void OnMouseEnter(EventArgs _)
{
if(this.IsUnavailable || this.PauseCatchingDrops)
return;
this.Logger.LogDebug("Attach documents component '{Name}' is hovered.", this.Name);
this.isComponentHovered = true;
this.SetDragClass();
this.StateHasChanged();
}
private void OnMouseLeave(EventArgs _)
{
if(this.IsUnavailable || this.PauseCatchingDrops)
return;
this.Logger.LogDebug("Attach documents component '{Name}' is no longer hovered.", this.Name);
this.isComponentHovered = false;
this.ClearDragClass();
this.StateHasChanged();
}
private async Task RemoveDocument(FileAttachment fileAttachment)
{
if (this.IsUnavailable)
@@ -104,7 +104,7 @@
</MudTooltip>
}
<AttachDocuments Name="File Attachments" Layer="@DropLayers.PAGES" DocumentPaths="@this.ComposerState.FileAttachments" DocumentPathsChanged="@this.ComposerAttachmentsChanged" CatchAllDocuments="true" UseSmallForm="true" ShowMediaStatus="false" Provider="@this.Provider" OwnerChat="@this.ChatThread" EnsureOwnerChatAsync="@this.EnsureMediaImportChatAsync" Disabled="@this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner)"/>
<AttachDocuments Name="File Attachments" DocumentPaths="@this.ComposerState.FileAttachments" DocumentPathsChanged="@this.ComposerAttachmentsChanged" CatchAllDocuments="true" UseSmallForm="true" ShowMediaStatus="false" Provider="@this.Provider" OwnerChat="@this.ChatThread" EnsureOwnerChatAsync="@this.EnsureMediaImportChatAsync" Disabled="@this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner)"/>
<MudDivider Vertical="true" Style="height: 24px; align-self: center;"/>
@@ -0,0 +1,8 @@
@* One element, and the content immediately inside it. Layouts hang child selectors on this
element, for instance app.css does on .inner-scrolling-context, so an extra level here would
break them. The cascading value renders no element of its own. *@
<div class="@this.Class" style="@this.Style" data-drop-zone-id="@this.EffectiveState.ScopeId">
<CascadingValue Value="@this.EffectiveState" IsFixed="@true">
@this.ChildContent
</CascadingValue>
</div>
@@ -0,0 +1,57 @@
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
/// <summary>
/// Marks an area whose drops end up at its default target when they hit no specific zone.
/// </summary>
/// <remarks>
/// <para>
/// This is how the habitual behaviour survives the move to hit testing: a file dropped anywhere in
/// the chat, in an assistant, or in a dialog still arrives where it used to, while a file dropped
/// on a specific zone now arrives exactly there. No code decides between the two -- the browser
/// does, because the specific zone lies deeper in the DOM than the area around it, and the hit test
/// resolves from the inside out.
/// </para>
/// <para>
/// The component replaces an existing element rather than adding one: it takes the class and the
/// style of the element it stands in for. Where the areas already had a wrapper, which is the case
/// for every page and every assistant, nothing about the layout changes.
/// </para>
/// </remarks>
public partial class DropZoneScope : ComponentBase
{
/// <summary>
/// The content of the area.
/// </summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>
/// The CSS classes of the element this scope renders.
/// </summary>
[Parameter]
public string Class { get; set; } = string.Empty;
/// <summary>
/// The inline style of the element this scope renders.
/// </summary>
[Parameter]
public string Style { get; set; } = string.Empty;
/// <summary>
/// The state to cascade, for hosts which want to be the default target of their own area.
/// </summary>
/// <remarks>
/// A host cannot read what it cascades itself, so a page which is its own drop target has to own
/// the state instead. The plugins page is such a case: it accepts an archive anywhere on it and
/// has no inner zone to hand the role to. Everybody else leaves this alone and lets the scope
/// keep its own state.
/// </remarks>
[Parameter]
public DropZoneScopeState? State { get; set; }
private readonly DropZoneScopeState ownState = new($"drop-zone-scope-{Guid.NewGuid():N}");
private DropZoneScopeState EffectiveState => this.State ?? this.ownState;
}
@@ -1,6 +1,6 @@
@inherits MSGComponentBase
<div @onmouseenter="@this.OnMouseEnter" @onmouseleave="@this.OnMouseLeave">
<div data-drop-zone-id="@this.dropZoneId">
<MudPaper Outlined="@true" Class="@this.dragClass">
@this.ChildContent
</MudPaper>
@@ -1,5 +1,3 @@
using AIStudio.Tools.Rust;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
@@ -28,22 +26,13 @@ public partial class PathDropZone : MSGComponentBase
public EventCallback<List<string>> OnPathsDropped { get; set; }
/// <summary>
/// On which layer to register the drop area. Higher layers have priority over lower layers.
/// </summary>
[Parameter]
public int Layer { get; set; } = DropLayers.ROOT;
/// <summary>
/// Catch all documents that are hovered over the AI Studio window and not only over the drop zone.
/// Makes this zone the default target of its area, meaning of its page, assistant, or dialog.
/// </summary>
/// <remarks>
/// Practically every zone needs this today. Hovering is detected through mouse events, and no
/// webview delivers those while a native drag is in progress, so a zone without this flag
/// hardly ever catches anything. The consequence is that two zones of the same layer cannot be
/// told apart: the one carrying this flag takes every drop, including the ones meant for the
/// other. A page may therefore hold only one zone per layer. Lifting that limit needs the
/// cursor position, which the runtime receives from Tauri and currently discards in
/// app_window.rs.
/// A drop aimed at this zone arrives here in any case. What this flag decides is the fate of the
/// drops aimed anywhere else in the surrounding area which hit no zone of their own: with the
/// flag, they arrive here as well. Only one zone per area can hold that role, and if several ask
/// for it, the first one in the markup gets it.
/// </remarks>
[Parameter]
public bool CatchAllDocuments { get; set; }
@@ -52,127 +41,118 @@ public partial class PathDropZone : MSGComponentBase
/// When true, the zone ignores drops and is not highlighted.
/// </summary>
/// <remarks>
/// The drop area stays registered nevertheless. Releasing it during the lifetime of the
/// component would lower the count of every zone below this one, and those zones would then
/// catch files while this one is still on screen.
/// It keeps its ID in the DOM nevertheless and therefore swallows the drops aimed at it. That is
/// what the pointer says: it rests on a switched-off field, so nothing happens. Letting the drop
/// fall through to the area behind it would deliver the files somewhere else entirely.
/// </remarks>
[Parameter]
public bool Disabled { get; set; }
/// <summary>
/// The area this zone lives in, if it lives in one at all.
/// </summary>
[CascadingParameter]
private DropZoneScopeState? Scope { get; set; }
[Inject]
private ILogger<PathDropZone> Logger { get; init; } = null!;
private const string DEFAULT_DRAG_CLASS = "relative rounded-lg border-2 border-dashed pa-3 mb-3 mud-width-full";
private readonly string dropZoneId = $"path-drop-zone-{Guid.NewGuid():N}";
private string dragClass = DEFAULT_DRAG_CLASS;
private uint numDropAreasAboveThis;
private bool isComponentHovered;
private bool isDefaultZone;
private bool isHighlighted;
#region Overrides of MSGComponentBase
protected override async Task OnInitializedAsync()
{
this.ApplyFilters([], [ Event.TAURI_EVENT_RECEIVED, Event.REGISTER_FILE_DROP_AREA, Event.UNREGISTER_FILE_DROP_AREA ]);
await this.MessageBus.SendMessage(this, Event.REGISTER_FILE_DROP_AREA, this.Layer);
this.ApplyFilters([], [ Event.HIGHLIGHT_DROP_ZONE, Event.PATHS_DROPPED ]);
this.ClaimDefaultZoneRole();
await base.OnInitializedAsync();
}
/// <summary>
/// Releases the drop area.
/// Hands the role of the default target back to the area.
/// </summary>
protected override void DisposeResources()
{
// Without this, drop areas below this one would count this component forever and would
// stop catching dropped files:
this.MessageBus.SendMessage(this, Event.UNREGISTER_FILE_DROP_AREA, this.Layer).Observe($"{nameof(PathDropZone)}: releasing the drop area");
if (this.isDefaultZone)
this.Scope?.ReleaseDefaultZone(this);
base.DisposeResources();
}
protected override async Task ProcessIncomingMessage<T>(ComponentBase? sendingComponent, Event triggeredEvent, T? data) where T : default
{
// A disabled zone takes no files. It keeps track of the zones above it, though, because
// those come and go while this one is disabled:
if (this.Disabled && triggeredEvent == Event.TAURI_EVENT_RECEIVED)
return;
switch (triggeredEvent)
{
case Event.REGISTER_FILE_DROP_AREA when sendingComponent != this:
{
if(data is int layer && layer > this.Layer)
case Event.HIGHLIGHT_DROP_ZONE when data is DropZoneHighlight highlight:
this.ApplyHighlight(this.IsThisZone(highlight.ZoneId));
break;
case Event.PATHS_DROPPED when data is DroppedPaths dropped:
// Whoever the drop was meant for, the drag is over and no zone stays highlighted:
this.ApplyHighlight(false);
if (!this.IsThisZone(dropped.ZoneId))
return;
if (this.Disabled)
{
this.numDropAreasAboveThis++;
this.ClearDragClass();
this.Logger.LogDebug("The path drop zone '{ZoneId}' is disabled and swallowed {Count} dropped path(s).", this.dropZoneId, dropped.Paths.Count);
return;
}
break;
}
case Event.UNREGISTER_FILE_DROP_AREA when sendingComponent != this:
{
if(data is int layer && layer > this.Layer && this.numDropAreasAboveThis > 0)
this.numDropAreasAboveThis--;
break;
}
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.FILE_DROP_HOVERED }:
if(!this.CanCatchDroppedPath())
return;
this.SetDragClass();
this.StateHasChanged();
break;
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.FILE_DROP_CANCELED }:
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.WINDOW_NOT_FOCUSED }:
this.isComponentHovered = false;
this.ClearDragClass();
this.StateHasChanged();
break;
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.FILE_DROP_DROPPED, Payload: var paths }:
if(!this.CanCatchDroppedPath())
return;
this.Logger.LogDebug("The path drop zone on layer {Layer} caught {Count} path(s).", this.Layer, paths.Count);
await this.OnPathsDropped.InvokeAsync(paths);
this.ClearDragClass();
this.StateHasChanged();
this.Logger.LogDebug("The path drop zone '{ZoneId}' caught {Count} path(s).", this.dropZoneId, dropped.Paths.Count);
await this.OnPathsDropped.InvokeAsync(dropped.Paths);
break;
}
}
#endregion
private bool CanCatchDroppedPath() => this.numDropAreasAboveThis is 0 && (this.isComponentHovered || this.CatchAllDocuments);
private void SetDragClass() => this.dragClass = $"{DEFAULT_DRAG_CLASS} mud-border-primary border-2";
private void ClearDragClass() => this.dragClass = DEFAULT_DRAG_CLASS;
private void OnMouseEnter(EventArgs _)
/// <summary>
/// Asks the area for the role of its default target, if this zone wants it.
/// </summary>
private void ClaimDefaultZoneRole()
{
if(this.Disabled || this.numDropAreasAboveThis > 0)
if (!this.CatchAllDocuments || this.Scope is null)
return;
// A native drag delivers no DOM events at all, mouse events included. This fires before a
// drag begins, while the pointer still moves freely, which makes it a hint about where the
// user is aiming rather than a reliable signal. See the remarks on CatchAllDocuments:
this.isComponentHovered = true;
this.SetDragClass();
this.StateHasChanged();
this.isDefaultZone = this.Scope.TryBecomeDefaultZone(this);
if (!this.isDefaultZone)
this.Logger.LogDebug("The path drop zone '{ZoneId}' asked to be the default target of its area, which another zone already is. It now takes only the drops aimed at itself.", this.dropZoneId);
}
private void OnMouseLeave(EventArgs _)
/// <summary>
/// Decides whether the named zone is this one.
/// </summary>
/// <remarks>
/// The area counts as this zone as long as this zone is its default target. That is the whole
/// mechanism behind dropping anywhere in a page and still landing here.
/// </remarks>
/// <param name="zoneId">The ID the hit test reported, or null when it hit nothing.</param>
private bool IsThisZone(string? zoneId) => zoneId is not null && (zoneId == this.dropZoneId || (this.isDefaultZone && zoneId == this.Scope?.ScopeId));
/// <summary>
/// Highlights the zone, or takes the highlight away.
/// </summary>
/// <remarks>
/// The comparison is not for tidiness: a throttled drag-over event arrives about ten times per
/// second, and without it every one of them would render every zone on the page anew.
/// </remarks>
private void ApplyHighlight(bool shouldBeHighlighted)
{
if(this.Disabled)
var highlighted = shouldBeHighlighted && !this.Disabled;
if (highlighted == this.isHighlighted)
return;
this.isComponentHovered = false;
this.ClearDragClass();
this.isHighlighted = highlighted;
this.dragClass = highlighted ? $"{DEFAULT_DRAG_CLASS} mud-border-primary border-2" : DEFAULT_DRAG_CLASS;
this.StateHasChanged();
}
}
@@ -2,7 +2,7 @@
@if (this.EnableDragDrop)
{
<div @onmouseenter="@this.OnMouseEnter" @onmouseleave="@this.OnMouseLeave">
<div data-drop-zone-id="@this.dropZoneId">
<MudPaper Outlined="true" Class="@this.dragClass">
<MudStack Row="true" AlignItems="AlignItems.Center" StretchItems="StretchItems.None" Wrap="Wrap.Wrap">
@if (this.ShowAttachedDocumentState && this.hasLoadedFileContent)
@@ -46,17 +46,23 @@ public partial class ReadFileContent : MSGComponentBase
public bool EnableDragDrop { get; set; }
/// <summary>
/// On which layer to register the drop area. Higher layers have priority over lower layers.
/// </summary>
[Parameter]
public int Layer { get; set; }
/// <summary>
/// Catch all documents that are hovered over the AI Studio window and not only over the drop zone.
/// Makes this component the default target of its area, meaning of its page, assistant, or
/// dialog: it then also takes the drops which land anywhere in that area without hitting a zone
/// of their own.
/// </summary>
/// <remarks>
/// Only one zone per area can hold that role, and if several ask for it, the first one in the
/// markup gets it. The flag has no effect without drag and drop being enabled.
/// </remarks>
[Parameter]
public bool CatchAllDocuments { get; set; }
/// <summary>
/// The area this component lives in, if it lives in one at all.
/// </summary>
[CascadingParameter]
private DropZoneScopeState? Scope { get; set; }
/// <summary>
/// Optionally restricts the file types offered by the native file picker
/// and accepted by this component.
@@ -81,10 +87,12 @@ public partial class ReadFileContent : MSGComponentBase
private const string DEFAULT_DRAG_CLASS = "relative rounded-lg border-2 border-dashed pa-3 mb-3 mud-width-full";
private readonly string dropZoneId = $"read-file-content-{Guid.NewGuid():N}";
private string ButtonText => string.IsNullOrWhiteSpace(this.Text) ? T("Use file content as input") : this.Text;
private string dragClass = DEFAULT_DRAG_CLASS;
private uint numDropAreasAboveThis;
private bool isComponentHovered;
private bool isDefaultZone;
private bool isHighlighted;
private bool isFileDialogOpen;
private bool hasLoadedFileContent;
private string loadedFileName = string.Empty;
@@ -120,8 +128,8 @@ public partial class ReadFileContent : MSGComponentBase
this.MediaTranscriptionService.StateChanged += this.OnMediaImportStateChanged;
if (this.EnableDragDrop)
{
this.ApplyFilters([], [ Event.TAURI_EVENT_RECEIVED, Event.REGISTER_FILE_DROP_AREA, Event.UNREGISTER_FILE_DROP_AREA ]);
await this.MessageBus.SendMessage(this, Event.REGISTER_FILE_DROP_AREA, this.Layer);
this.ApplyFilters([], [ Event.HIGHLIGHT_DROP_ZONE, Event.PATHS_DROPPED ]);
this.ClaimDefaultZoneRole();
}
await base.OnInitializedAsync();
@@ -192,10 +200,9 @@ public partial class ReadFileContent : MSGComponentBase
{
this.MediaTranscriptionService.StateChanged -= this.OnMediaImportStateChanged;
// Release the drop area. Without this, drop areas below this one would count this component
// forever and would stop catching dropped files:
if (this.EnableDragDrop)
this.MessageBus.SendMessage(this, Event.UNREGISTER_FILE_DROP_AREA, this.Layer).Observe($"{nameof(ReadFileContent)}: releasing the drop area");
// Hand the role of the default target back to the area:
if (this.isDefaultZone)
this.Scope?.ReleaseDefaultZone(this);
base.DisposeResources();
}
@@ -205,57 +212,73 @@ public partial class ReadFileContent : MSGComponentBase
if (!this.EnableDragDrop)
return;
if (this.IsUnavailable && triggeredEvent == Event.TAURI_EVENT_RECEIVED)
return;
switch (triggeredEvent)
{
case Event.REGISTER_FILE_DROP_AREA when sendingComponent != this:
{
if(data is int layer && layer > this.Layer)
case Event.HIGHLIGHT_DROP_ZONE when data is DropZoneHighlight highlight:
this.ApplyHighlight(this.IsThisZone(highlight.ZoneId));
break;
case Event.PATHS_DROPPED when data is DroppedPaths dropped:
// Whoever the drop was meant for, the drag is over and no zone stays highlighted:
this.ApplyHighlight(false);
if (!this.IsThisZone(dropped.ZoneId))
return;
if (this.IsUnavailable)
{
this.numDropAreasAboveThis++;
this.ClearDragClass();
this.Logger.LogDebug("The file zone '{ZoneId}' is unavailable and swallowed {Count} dropped path(s).", this.dropZoneId, dropped.Paths.Count);
return;
}
break;
}
case Event.UNREGISTER_FILE_DROP_AREA when sendingComponent != this:
{
if(data is int layer && layer > this.Layer && this.numDropAreasAboveThis > 0)
this.numDropAreasAboveThis--;
break;
}
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.FILE_DROP_HOVERED }:
if(!this.CanCatchDroppedFile())
return;
this.SetDragClass();
this.StateHasChanged();
break;
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.FILE_DROP_CANCELED }:
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.WINDOW_NOT_FOCUSED }:
this.isComponentHovered = false;
this.ClearDragClass();
this.StateHasChanged();
break;
case Event.TAURI_EVENT_RECEIVED when data is TauriEvent { EventType: TauriEventType.FILE_DROP_DROPPED, Payload: var paths }:
if(!this.CanCatchDroppedFile())
return;
await this.LoadFirstValidFile(paths);
this.ClearDragClass();
await this.LoadFirstValidFile(dropped.Paths);
this.StateHasChanged();
break;
}
}
#endregion
/// <summary>
/// Asks the area for the role of its default target, if this component wants it.
/// </summary>
private void ClaimDefaultZoneRole()
{
if (!this.CatchAllDocuments || this.Scope is null)
return;
this.isDefaultZone = this.Scope.TryBecomeDefaultZone(this);
if (!this.isDefaultZone)
this.Logger.LogDebug("The file zone '{ZoneId}' asked to be the default target of its area, which another zone already is. It now takes only the drops aimed at itself.", this.dropZoneId);
}
/// <summary>
/// Decides whether the named zone is this one.
/// </summary>
/// <remarks>
/// The area counts as this zone as long as this zone is its default target. That is the whole
/// mechanism behind dropping anywhere in an assistant and still landing here.
/// </remarks>
/// <param name="zoneId">The ID the hit test reported, or null when it hit nothing.</param>
private bool IsThisZone(string? zoneId) => zoneId is not null && (zoneId == this.dropZoneId || (this.isDefaultZone && zoneId == this.Scope?.ScopeId));
/// <summary>
/// Highlights the zone, or takes the highlight away.
/// </summary>
/// <remarks>
/// The comparison is not for tidiness: a throttled drag-over event arrives about ten times per
/// second, and without it every one of them would render every zone on the page anew.
/// </remarks>
private void ApplyHighlight(bool shouldBeHighlighted)
{
var highlighted = shouldBeHighlighted && !this.IsUnavailable;
if (highlighted == this.isHighlighted)
return;
this.isHighlighted = highlighted;
this.dragClass = highlighted ? $"{DEFAULT_DRAG_CLASS} mud-border-primary border-2" : DEFAULT_DRAG_CLASS;
this.StateHasChanged();
}
private async Task SelectFile()
{
@@ -417,31 +440,4 @@ public partial class ReadFileContent : MSGComponentBase
return string.Format(this.T("Attached file '{0}'."), this.loadedFileName);
}
private bool CanCatchDroppedFile() => this.numDropAreasAboveThis is 0 && (this.isComponentHovered || this.CatchAllDocuments);
private void SetDragClass() => this.dragClass = $"{DEFAULT_DRAG_CLASS} mud-border-primary border-2";
private void ClearDragClass() => this.dragClass = DEFAULT_DRAG_CLASS;
private void OnMouseEnter(EventArgs _)
{
if(this.IsUnavailable || this.numDropAreasAboveThis > 0)
return;
this.Logger.LogDebug("Read file content component is hovered.");
this.isComponentHovered = true;
this.SetDragClass();
this.StateHasChanged();
}
private void OnMouseLeave(EventArgs _)
{
if(this.IsUnavailable)
return;
this.Logger.LogDebug("Read file content component is no longer hovered.");
this.isComponentHovered = false;
this.ClearDragClass();
this.StateHasChanged();
}
}
@@ -2,7 +2,7 @@
@if (this.EnableDragDrop)
{
<PathDropZone Layer="@this.Layer" CatchAllDocuments="@this.CatchAllDocuments" Disabled="@this.Disabled" OnPathsDropped="@this.PathsDropped">
<PathDropZone CatchAllDocuments="@this.CatchAllDocuments" Disabled="@this.Disabled" OnPathsDropped="@this.PathsDropped">
@this.Picker
<MudText Typo="Typo.body2">
@T("You can also drag & drop the folder here.")
@@ -34,13 +34,9 @@ public partial class SelectDirectory : MSGComponentBase
public bool EnableDragDrop { get; set; }
/// <summary>
/// On which layer to register the drop area. Higher layers have priority over lower layers.
/// </summary>
[Parameter]
public int Layer { get; set; } = DropLayers.ROOT;
/// <summary>
/// Catch all documents that are hovered over the AI Studio window and not only over the drop zone.
/// Makes this component the default target of its area, meaning of its page, assistant, or
/// dialog: it then also takes the drops which land anywhere in that area without hitting a zone
/// of their own.
/// </summary>
[Parameter]
public bool CatchAllDocuments { get; set; }
@@ -2,7 +2,7 @@
@if (this.EnableDragDrop)
{
<PathDropZone Layer="@this.Layer" CatchAllDocuments="@this.CatchAllDocuments" Disabled="@this.Disabled" OnPathsDropped="@this.PathsDropped">
<PathDropZone CatchAllDocuments="@this.CatchAllDocuments" Disabled="@this.Disabled" OnPathsDropped="@this.PathsDropped">
@this.Picker
<MudText Typo="Typo.body2">
@T("You can also drag & drop the file here.")
@@ -38,13 +38,9 @@ public partial class SelectFile : MSGComponentBase
public bool EnableDragDrop { get; set; }
/// <summary>
/// On which layer to register the drop area. Higher layers have priority over lower layers.
/// </summary>
[Parameter]
public int Layer { get; set; } = DropLayers.ROOT;
/// <summary>
/// Catch all documents that are hovered over the AI Studio window and not only over the drop zone.
/// Makes this component the default target of its area, meaning of its page, assistant, or
/// dialog: it then also takes the drops which land anywhere in that area without hitting a zone
/// of their own.
/// </summary>
[Parameter]
public bool CatchAllDocuments { get; set; }