Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add context menu and duplicate option to web app (#2293)
Leendert de Borstf43f6bdc3163
diff --git a/apps/server/AliasVault.Client/Main/Components/Items/ItemCard.razor b/apps/server/AliasVault.Client/Main/Components/Items/ItemCard.razorindex 54de3d97c..12b6ffe95 100644--- a/apps/server/AliasVault.Client/Main/Components/Items/ItemCard.razor+++ b/apps/server/AliasVault.Client/Main/Components/Items/ItemCard.razor@@ -3,8 +3,12 @@@inject NavigationManager NavigationManager@* ItemCard component - displays an item in a card format with appropriate icon and information *@-<div @onclick="ShowDetails" class="credential-card overflow-hidden p-4 space-y-2 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700+<div @onclick="ShowDetails" @oncontextmenu="OpenContextMenu" @oncontextmenu:preventDefault="true"+ class="credential-card relative group p-4 space-y-2 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700dark:bg-gray-800 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors duration-200">+ <div class="absolute top-2 right-2">+ <ItemContextMenu @ref="_contextMenu" ItemId="@Obj.Id" ItemName="@Obj.Service" OnMutated="OnMutated" />+ </div><div class="px-4 py-2 text-gray-400 rounded text-center flex flex-col items-center"><div class="mb-2"><ItemIcon@@ -61,6 +65,22 @@[Parameter]public bool ShowFolderPath { get; set; }+ /// <summary>+ /// Gets or sets the callback raised after the item was mutated via the context menu (duplicated or deleted).+ /// </summary>+ [Parameter]+ public EventCallback OnMutated { get; set; }++ private ItemContextMenu? _contextMenu;++ /// <summary>+ /// Opens the item context menu at the right-click position on the card.+ /// </summary>+ private void OpenContextMenu(MouseEventArgs e)+ {+ _contextMenu?.Open(e);+ }+/// <summary>/// Gets the display text for the item, showing username by default,/// falling back to email. For credit cards, shows cardholder name or masked number.diff --git a/apps/server/AliasVault.Client/Main/Components/Items/ItemContextMenu.razor b/apps/server/AliasVault.Client/Main/Components/Items/ItemContextMenu.razornew file mode 100644index 000000000..e59503a48--- /dev/null+++ b/apps/server/AliasVault.Client/Main/Components/Items/ItemContextMenu.razor@@ -0,0 +1,229 @@+@using Microsoft.Extensions.Localization+@inject IStringLocalizerFactory LocalizerFactory+@inject NavigationManager NavigationManager+@inject ItemService ItemService+@inject GlobalNotificationService GlobalNotificationService+@inject Config Config++<div class="relative" @onclick:stopPropagation="true">+ <button type="button" id="@($"itemMenuBtn-{InstanceId}")" @onclick="ToggleMenu"+ aria-label="@Localizer["ItemOptionsLabel"]" aria-haspopup="menu"+ class="px-0.5 py-1 rounded text-gray-400 transition-opacity @(IsOpen ? "opacity-100" : "opacity-0") group-hover:opacity-100 group-focus-within:opacity-100 focus:opacity-100 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500">+ <svg class="w-2 h-4" viewBox="0 0 12 24" fill="currentColor" aria-hidden="true">+ <circle cx="6" cy="5" r="2" />+ <circle cx="6" cy="12" r="2" />+ <circle cx="6" cy="19" r="2" />+ </svg>+ </button>++ @if (IsOpen)+ {+ <ClickOutsideHandler OnClose="CloseMenu" ContentId="@($"itemMenu-{InstanceId},itemMenuBtn-{InstanceId}")">+ <div id="@($"itemMenu-{InstanceId}")" role="menu" style="@MenuStyle"+ class="@(HasCursorPosition ? "fixed" : "absolute right-0 top-full mt-1") z-50 w-40 py-1 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 dark:bg-gray-700">+ <button type="button" role="menuitem" @onclick="EditItem"+ class="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600">+ @Localizer["EditMenuItem"]+ </button>+ <button type="button" role="menuitem" @onclick="DuplicateItem"+ class="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600">+ @Localizer["DuplicateMenuItem"]+ </button>+ <button type="button" role="menuitem" @onclick="OpenDeleteModal"+ class="w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-600">+ @Localizer["DeleteMenuItem"]+ </button>+ </div>+ </ClickOutsideHandler>+ }++ @if (ShowDeleteModal)+ {+ <FormModal+ IsOpen="ShowDeleteModal"+ Title="@DeleteLocalizer["DeleteItemTitle"]"+ IconBackgroundClass="bg-red-100 dark:bg-red-900/30"+ ConfirmText="@DeleteLocalizer["YesImSureButton"]"+ CancelText="@DeleteLocalizer["NoCancelButton"]"+ ConfirmButtonClass="bg-red-600 hover:bg-red-700"+ IsLoading="IsDeleting"+ OnConfirm="ConfirmDelete"+ OnClose="CancelDelete">+ <Icon>+ <svg class="h-6 w-6 text-red-600 dark:text-red-400" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">+ <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />+ </svg>+ </Icon>+ <ChildContent>+ <p class="text-sm text-gray-500 dark:text-gray-400 mb-3">+ @string.Format(DeleteLocalizer["DeleteItemDescription"].Value, Config.TrashRetentionDays)+ </p>+ <div class="bg-gray-50 dark:bg-gray-700/50 rounded-md p-3">+ <p class="text-sm font-medium text-gray-900 dark:text-white break-all">@(ItemName ?? string.Empty)</p>+ </div>+ </ChildContent>+ </FormModal>+ }+</div>++@code {+ /// <summary>+ /// Gets or sets the id of the item this menu operates on.+ /// </summary>+ [Parameter]+ public Guid ItemId { get; set; }++ /// <summary>+ /// Gets or sets the display name of the item, shown in the delete confirmation.+ /// </summary>+ [Parameter]+ public string? ItemName { get; set; }++ /// <summary>+ /// Gets or sets the callback raised after the item was duplicated or deleted so the parent can refresh its list.+ /// </summary>+ [Parameter]+ public EventCallback OnMutated { get; set; }++ private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Items.ItemContextMenu", "AliasVault.Client");+ private IStringLocalizer ViewLocalizer => LocalizerFactory.Create("Pages.Main.Items.View", "AliasVault.Client");+ private IStringLocalizer DeleteLocalizer => LocalizerFactory.Create("Pages.Main.Items.Delete", "AliasVault.Client");++ private string InstanceId { get; } = Guid.NewGuid().ToString("N")[..8];+ private bool IsOpen { get; set; }+ private bool ShowDeleteModal { get; set; }+ private bool IsDeleting { get; set; }+ private bool IsDuplicating { get; set; }+ private double MenuX { get; set; }+ private double MenuY { get; set; }++ private bool HasCursorPosition => MenuX > 0 || MenuY > 0;++ /// <summary>+ /// Inline style that places the menu at the cursor.+ /// </summary>+ private string MenuStyle => HasCursorPosition+ ? FormattableString.Invariant($"left: min({(int)MenuX}px, calc(100vw - 170px)); top: min({(int)MenuY}px, calc(100vh - 140px));")+ : string.Empty;++ /// <summary>+ /// Opens the menu at the given mouse position. Used by parent components on right-click of the row/card.+ /// </summary>+ public void Open(MouseEventArgs e)+ {+ MenuX = e.ClientX;+ MenuY = e.ClientY;+ IsOpen = true;+ StateHasChanged();+ }++ /// <summary>+ /// Toggles the menu visibility from the trigger button, opening at the click position.+ /// </summary>+ private void ToggleMenu(MouseEventArgs e)+ {+ if (IsOpen)+ {+ CloseMenu();+ return;+ }++ Open(e);+ }++ /// <summary>+ /// Closes the menu.+ /// </summary>+ private void CloseMenu()+ {+ IsOpen = false;+ StateHasChanged();+ }++ /// <summary>+ /// Navigates to the edit page for this item.+ /// </summary>+ private void EditItem()+ {+ NavigationManager.NavigateTo($"/items/{ItemId}/edit");+ }++ /// <summary>+ /// Duplicates the item (including fields, TOTP codes, attachments and tags) and notifies the parent.+ /// </summary>+ private async Task DuplicateItem()+ {+ IsOpen = false;++ if (IsDuplicating)+ {+ return;+ }++ IsDuplicating = true;++ try+ {+ var newItemId = await ItemService.DuplicateEntryAsync(ItemId);+ if (newItemId == Guid.Empty)+ {+ GlobalNotificationService.AddErrorMessage(ViewLocalizer["DuplicateErrorMessage"], true);+ return;+ }++ GlobalNotificationService.AddSuccessMessage(ViewLocalizer["DuplicateSuccessMessage"], true);+ await OnMutated.InvokeAsync();+ }+ finally+ {+ IsDuplicating = false;+ }+ }++ /// <summary>+ /// Opens the delete confirmation modal.+ /// </summary>+ private void OpenDeleteModal()+ {+ IsOpen = false;+ ShowDeleteModal = true;+ }++ /// <summary>+ /// Closes the delete confirmation modal without deleting.+ /// </summary>+ private void CancelDelete()+ {+ if (IsDeleting)+ {+ return;+ }++ ShowDeleteModal = false;+ }++ /// <summary>+ /// Moves the item to the trash and notifies the parent.+ /// </summary>+ private async Task ConfirmDelete()+ {+ if (IsDeleting)+ {+ return;+ }++ IsDeleting = true;++ try+ {+ await ItemService.TrashItemInBackgroundAsync(ItemId);+ GlobalNotificationService.AddSuccessMessage(DeleteLocalizer["DeleteSuccessMessage"], true);+ ShowDeleteModal = false;+ await OnMutated.InvokeAsync();+ }+ finally+ {+ IsDeleting = false;+ }+ }+}diff --git a/apps/server/AliasVault.Client/Main/Components/Items/ItemsTable.razor b/apps/server/AliasVault.Client/Main/Components/Items/ItemsTable.razorindex f4e60909b..2287f1fea 100644--- a/apps/server/AliasVault.Client/Main/Components/Items/ItemsTable.razor+++ b/apps/server/AliasVault.Client/Main/Components/Items/ItemsTable.razor@@ -5,7 +5,7 @@<SortableTable Columns="@_tableColumns" SortColumn="@SortColumn" SortDirection="@CurrentSortDirection" OnSortChanged="HandleSortChanged">@foreach (var credential in Credentials){- <SortableTableRow @key="credential.Id" Class="cursor-pointer" OnClick="@(() => NavigateToCredential(credential.Id))">+ <SortableTableRow @key="credential.Id" Class="cursor-pointer group" OnClick="@(() => NavigateToCredential(credential.Id))" OnContextMenu="@((MouseEventArgs e) => OpenRowMenu(credential.Id, e))"><SortableTableColumn Padding="false"><div class="flex items-center space-x-2 py-2 pl-2"><ItemIcon@@ -20,6 +20,11 @@<SortableTableColumn Padding="false">@credential.Username</SortableTableColumn><SortableTableColumn Padding="false">@credential.Email</SortableTableColumn><SortableTableColumn Padding="false">@credential.CreatedAt.ToString("yyyy-MM-dd")</SortableTableColumn>+ <SortableTableColumn Padding="false">+ <div class="flex justify-end pr-2">+ <ItemContextMenu @ref="_rowMenus[credential.Id]" ItemId="@credential.Id" ItemName="@credential.Service" OnMutated="OnMutated" />+ </div>+ </SortableTableColumn></SortableTableRow>}</SortableTable>@@ -50,6 +55,12 @@[Parameter]public EventCallback<(string Column, SortDirection Direction)> OnTableSortChanged { get; set; }+ /// <summary>+ /// Gets or sets the callback raised after an item was mutated via the row context menu (duplicated or deleted).+ /// </summary>+ [Parameter]+ public EventCallback OnMutated { get; set; }+/// <summary>/// Gets or sets the columns to show in the table./// </summary>@@ -57,9 +68,15 @@new TableColumn { Title = "Service", PropertyName = "Service" },new TableColumn { Title = "Username", PropertyName = "Username" },new TableColumn { Title = "Email", PropertyName = "Email" },- new TableColumn { Title = "Created", PropertyName = "CreatedAt" }+ new TableColumn { Title = "Created", PropertyName = "CreatedAt" },+ new TableColumn { Title = string.Empty, Sortable = false }];+ /// <summary>+ /// Context menu component references per row, used to open the menu via right-click.+ /// </summary>+ private readonly Dictionary<Guid, ItemContextMenu> _rowMenus = new();+/// <summary>/// Handles the sort changed event from the table header click./// Notifies the parent component to apply sorting on all items.@@ -78,4 +95,17 @@{NavigationManager.NavigateTo($"/items/{credentialId}");}++ /// <summary>+ /// Opens the context menu for the given row at the right-click position.+ /// </summary>+ /// <param name="credentialId">The ID of the credential whose menu to open.</param>+ /// <param name="e">The mouse event containing the cursor position.</param>+ private void OpenRowMenu(Guid credentialId, MouseEventArgs e)+ {+ if (_rowMenus.TryGetValue(credentialId, out var menu))+ {+ menu.Open(e);+ }+ }}diff --git a/apps/server/AliasVault.Client/Main/Pages/Items/Home.razor b/apps/server/AliasVault.Client/Main/Pages/Items/Home.razorindex 541c60431..e1abcf942 100644--- a/apps/server/AliasVault.Client/Main/Pages/Items/Home.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Items/Home.razor@@ -140,7 +140,8 @@ elseCredentials="@FilteredAndSortedItems.ToList()"SortColumn="@TableSortColumn"CurrentSortDirection="@TableSortDirection"- OnTableSortChanged="HandleTableSortChanged" />+ OnTableSortChanged="HandleTableSortChanged"+ OnMutated="LoadItemsAsync" />}else{@@ -197,7 +198,7 @@ else}@foreach (var item in FilteredAndSortedItems){- <ItemCard @key="item.Id" Obj="@item" ShowFolderPath="@IsSearching" />+ <ItemCard @key="item.Id" Obj="@item" ShowFolderPath="@IsSearching" OnMutated="LoadItemsAsync" />}</div>}diff --git a/apps/server/AliasVault.Client/Services/ItemService.cs b/apps/server/AliasVault.Client/Services/ItemService.csindex 489d67f86..6deb4ff68 100644--- a/apps/server/AliasVault.Client/Services/ItemService.cs+++ b/apps/server/AliasVault.Client/Services/ItemService.cs@@ -14,6 +14,7 @@ using System.Linq;using System.Net.Http;using System.Net.Http.Json;using System.Text.Json;+using System.Text.RegularExpressions;using System.Threading.Tasks;using AliasClientDb;using AliasClientDb.Models;@@ -332,6 +333,131 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Confreturn existingItem.Id;}+ /// <summary>+ /// Duplicate an existing item including all fields. Data that is not duplicated is passkeys and field history.+ /// </summary>+ /// <param name="itemId">Id of item to duplicate.</param>+ /// <returns>Guid of the new item, or an empty guid when duplication failed.</returns>+ public async Task<Guid> DuplicateEntryAsync(Guid itemId)+ {+ InvalidateListCache();+ var context = await dbService.GetDbContextAsync();++ var source = await LoadEntryAsync(itemId);+ if (source is null)+ {+ return Guid.Empty;+ }++ var currentDateTime = DateTime.UtcNow;+ var existingNames = await context.Items+ .Where(x => !x.IsDeleted && x.DeletedAt == null)+ .Select(x => x.Name)+ .ToListAsync();++ var newItem = new Item+ {+ Id = Guid.NewGuid(),+ Name = GenerateCopyName(source.Name, existingNames),+ ItemType = source.ItemType,+ LogoId = source.LogoId,+ FolderId = source.FolderId,+ };+ SetInsertTimestamps(newItem, currentDateTime);++ // Copy field values. Custom field definitions are duplicated as well so later+ // edits to the duplicate's custom fields don't affect the original item.+ var definitionMap = new Dictionary<Guid, FieldDefinition>();+ foreach (var fieldValue in source.FieldValues)+ {+ FieldDefinition? newDefinition = null;+ if (fieldValue.FieldDefinition is not null)+ {+ if (!definitionMap.TryGetValue(fieldValue.FieldDefinition.Id, out newDefinition))+ {+ newDefinition = new FieldDefinition+ {+ Id = Guid.NewGuid(),+ FieldType = fieldValue.FieldDefinition.FieldType,+ Label = fieldValue.FieldDefinition.Label,+ IsMultiValue = fieldValue.FieldDefinition.IsMultiValue,+ IsHidden = fieldValue.FieldDefinition.IsHidden,+ EnableHistory = fieldValue.FieldDefinition.EnableHistory,+ Weight = fieldValue.FieldDefinition.Weight,+ ApplicableToTypes = fieldValue.FieldDefinition.ApplicableToTypes,+ };+ SetInsertTimestamps(newDefinition, currentDateTime);+ definitionMap.Add(fieldValue.FieldDefinition.Id, newDefinition);+ context.FieldDefinitions.Add(newDefinition);+ }+ }++ var newFieldValue = new FieldValue+ {+ Id = Guid.NewGuid(),+ ItemId = newItem.Id,+ FieldDefinition = newDefinition,+ FieldDefinitionId = newDefinition?.Id,+ FieldKey = fieldValue.FieldKey,+ Value = fieldValue.Value,+ Weight = fieldValue.Weight,+ };+ SetInsertTimestamps(newFieldValue, currentDateTime);+ newItem.FieldValues.Add(newFieldValue);+ }++ foreach (var attachment in source.Attachments)+ {+ var newAttachment = new Attachment+ {+ Id = Guid.NewGuid(),+ Filename = attachment.Filename,+ Blob = attachment.Blob,+ ItemId = newItem.Id,+ };+ SetInsertTimestamps(newAttachment, currentDateTime);+ newItem.Attachments.Add(newAttachment);+ }++ foreach (var totpCode in source.TotpCodes)+ {+ var newTotpCode = new TotpCode+ {+ Id = Guid.NewGuid(),+ Name = totpCode.Name,+ SecretKey = totpCode.SecretKey,+ ItemId = newItem.Id,+ };+ SetInsertTimestamps(newTotpCode, currentDateTime);+ newItem.TotpCodes.Add(newTotpCode);+ }++ // Copy tag assignments (the tags themselves are shared, not duplicated).+ var sourceItemTags = await context.ItemTags+ .Where(x => x.ItemId == itemId && !x.IsDeleted)+ .ToListAsync();+ foreach (var itemTag in sourceItemTags)+ {+ var newItemTag = new ItemTag+ {+ Id = Guid.NewGuid(),+ ItemId = newItem.Id,+ TagId = itemTag.TagId,+ };+ SetInsertTimestamps(newItemTag, currentDateTime);+ newItem.ItemTags.Add(newItemTag);+ }++ context.Items.Add(newItem);++ if (!await dbService.SaveDatabaseAsync())+ {+ return Guid.Empty;+ }++ return newItem.Id;+ }+/// <summary>/// Load existing item from database./// </summary>@@ -1504,6 +1630,33 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf}}+ /// <summary>+ /// Generate a unique name for a duplicated item: "Name (1)", "Name (2)", etc.+ /// If the source name already ends with a "(n)" suffix, the counter is incremented+ /// instead of stacking suffixes.+ /// </summary>+ /// <param name="sourceName">Name of the item being duplicated.</param>+ /// <param name="existingNames">Names of all active items, used to avoid collisions.</param>+ /// <returns>The generated name, or the source name when it is null or empty.</returns>+ private static string? GenerateCopyName(string? sourceName, List<string?> existingNames)+ {+ if (string.IsNullOrEmpty(sourceName))+ {+ return sourceName;+ }++ var baseName = Regex.Replace(sourceName, " \\(\\d+\\)$", string.Empty);+ var taken = existingNames.OfType<string>().ToHashSet();++ var candidate = $"{baseName} (1)";+ for (var counter = 2; taken.Contains(candidate); counter++)+ {+ candidate = $"{baseName} ({counter})";+ }++ return candidate;+ }+/// <summary>/// Sets timestamps on an entity during insert only if they're not already set./// This preserves timestamps from imported data while setting defaults for new entities.diff --git a/apps/server/Shared/AliasVault.RazorComponents/Tables/SortableTableRow.razor b/apps/server/Shared/AliasVault.RazorComponents/Tables/SortableTableRow.razorindex d3b67dd28..bb9812308 100644--- a/apps/server/Shared/AliasVault.RazorComponents/Tables/SortableTableRow.razor+++ b/apps/server/Shared/AliasVault.RazorComponents/Tables/SortableTableRow.razor@@ -1,4 +1,4 @@-<tr @onclick="HandleClick" class="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 @(OnClick.HasDelegate ? "cursor-pointer" : "") @(Class)">+<tr @onclick="HandleClick" @oncontextmenu="HandleContextMenu" @oncontextmenu:preventDefault="@OnContextMenu.HasDelegate" class="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 @(OnClick.HasDelegate ? "cursor-pointer" : "") @(Class)">@ChildContent</tr>@@ -21,6 +21,13 @@[Parameter]public EventCallback OnClick { get; set; }+ /// <summary>+ /// Gets or sets the callback to invoke when the row is right-clicked.+ /// When set, the browser's default context menu is suppressed for this row.+ /// </summary>+ [Parameter]+ public EventCallback<MouseEventArgs> OnContextMenu { get; set; }+/// <summary>/// Handles the click event./// </summary>@@ -31,4 +38,15 @@await OnClick.InvokeAsync();}}++ /// <summary>+ /// Handles the context menu (right-click) event.+ /// </summary>+ private async Task HandleContextMenu(MouseEventArgs e)+ {+ if (OnContextMenu.HasDelegate)+ {+ await OnContextMenu.InvokeAsync(e);+ }+ }}