Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add drag-and-drop reorder to aliasvault.client custom fields (#1673)

Leendert de Borst7b354b47addc
diff --git a/apps/server/AliasVault.Client/Main/Components/Forms/DraggableCustomFieldsList.razor b/apps/server/AliasVault.Client/Main/Components/Forms/DraggableCustomFieldsList.razor
new file mode 100644
index 000000000..8b7c8f1b4
--- /dev/null
+++ b/apps/server/AliasVault.Client/Main/Components/Forms/DraggableCustomFieldsList.razor
@@ -0,0 +1,186 @@
+@using AliasVault.Client.Main.Models
+@using AliasClientDb.Models
+@using Microsoft.JSInterop
+@inject IJSRuntime JSRuntime
+@implements IAsyncDisposable
+
+@* Draggable Custom Fields List *@
+<div id="@_containerId" class="space-y-4">
+ @foreach (var customField in CustomFields)
+ {
+ <div data-drag-item
+ data-field-key="@customField.FieldKey"
+ class="relative bg-white dark:bg-gray-800 rounded-lg group">
+ @* Draggable label row *@
+ <div class="cursor-grab active:cursor-grabbing">
+ <EditableFieldLabel
+ HtmlFor="@($"custom-{customField.TempId ?? customField.FieldKey}")"
+ Label="@customField.Label"
+ LabelChanged="@((newLabel) => OnLabelChange.InvokeAsync((customField.FieldKey, newLabel)))"
+ OnDelete="@(() => OnDelete.InvokeAsync(customField.FieldKey))"/>
+ </div>
+
+ @* Input field *@
+ @if (customField.FieldType == FieldType.TextArea)
+ {
+ <div class="relative">
+ <textarea
+ id="@($"custom-{customField.TempId ?? customField.FieldKey}")"
+ style="height: 200px;"
+ class="outline-0 shadow-sm bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
+ @bind="customField.Value">
+ </textarea>
+ </div>
+ }
+ else if (customField.IsHidden || customField.FieldType == FieldType.Hidden || customField.FieldType == FieldType.Password)
+ {
+ <EditPasswordFormRow
+ Id="@($"custom-{customField.TempId ?? customField.FieldKey}")"
+ Label=""
+ @bind-Value="customField.Value"
+ ShowPassword="false"/>
+ }
+ else
+ {
+ <div class="relative">
+ <input
+ type="text"
+ id="@($"custom-{customField.TempId ?? customField.FieldKey}")"
+ autocomplete="off"
+ class="outline-0 shadow-sm bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
+ @bind="customField.Value"
+ autocapitalize="off"
+ autocorrect="off"/>
+ </div>
+ }
+ </div>
+ }
+</div>
+
+@code {
+ private readonly string _containerId = $"draggable-fields-{Guid.NewGuid():N}";
+ private IJSObjectReference? _jsModule;
+ private IJSObjectReference? _dragDropInstance;
+ private DotNetObjectReference<DraggableCustomFieldsList>? _dotNetRef;
+
+ /// <summary>
+ /// Gets or sets the list of custom fields to display.
+ /// </summary>
+ [Parameter]
+ public List<SystemFieldEdit> CustomFields { get; set; } = new();
+
+ /// <summary>
+ /// Event callback when fields are reordered.
+ /// </summary>
+ [Parameter]
+ public EventCallback<List<SystemFieldEdit>> OnReorder { get; set; }
+
+ /// <summary>
+ /// Event callback when a field label is changed.
+ /// </summary>
+ [Parameter]
+ public EventCallback<(string fieldKey, string newLabel)> OnLabelChange { get; set; }
+
+ /// <summary>
+ /// Event callback when a field is deleted.
+ /// </summary>
+ [Parameter]
+ public EventCallback<string> OnDelete { get; set; }
+
+ private int _lastFieldCount;
+
+ /// <inheritdoc />
+ protected override async Task OnAfterRenderAsync(bool firstRender)
+ {
+ if (firstRender)
+ {
+ try
+ {
+ _jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>(
+ "import",
+ "./js/modules/dragAndDrop.js"
+ );
+
+ _dotNetRef = DotNetObjectReference.Create(this);
+ _dragDropInstance = await _jsModule.InvokeAsync<IJSObjectReference>(
+ "initDragAndDrop",
+ _containerId,
+ _dotNetRef
+ );
+ _lastFieldCount = CustomFields.Count;
+ }
+ catch (Exception)
+ {
+ // JavaScript module not available - graceful degradation
+ }
+ }
+ else if (_dragDropInstance is not null && CustomFields.Count != _lastFieldCount)
+ {
+ // Refresh drag-drop when items are added or removed
+ try
+ {
+ await _dragDropInstance.InvokeVoidAsync("refresh");
+ _lastFieldCount = CustomFields.Count;
+ }
+ catch (Exception)
+ {
+ // Ignore refresh errors
+ }
+ }
+ }
+
+ /// <summary>
+ /// Called from JavaScript when items are reordered via drag and drop.
+ /// </summary>
+ /// <param name="fromIndex">The original index of the dragged item.</param>
+ /// <param name="toIndex">The target index where the item was dropped.</param>
+ [JSInvokable]
+ public async Task OnItemReordered(int fromIndex, int toIndex)
+ {
+ if (fromIndex < 0 || fromIndex >= CustomFields.Count ||
+ toIndex < 0 || toIndex >= CustomFields.Count ||
+ fromIndex == toIndex)
+ {
+ return;
+ }
+
+ // Reorder the list
+ var reorderedFields = new List<SystemFieldEdit>(CustomFields);
+ var movedItem = reorderedFields[fromIndex];
+ reorderedFields.RemoveAt(fromIndex);
+ reorderedFields.Insert(toIndex, movedItem);
+
+ // Update display order for all fields
+ for (int i = 0; i < reorderedFields.Count; i++)
+ {
+ reorderedFields[i].DisplayOrder = i;
+ }
+
+ await OnReorder.InvokeAsync(reorderedFields);
+ StateHasChanged();
+ }
+
+ /// <inheritdoc />
+ public async ValueTask DisposeAsync()
+ {
+ try
+ {
+ if (_dragDropInstance is not null)
+ {
+ await _dragDropInstance.InvokeVoidAsync("dispose");
+ await _dragDropInstance.DisposeAsync();
+ }
+
+ if (_jsModule is not null)
+ {
+ await _jsModule.DisposeAsync();
+ }
+
+ _dotNetRef?.Dispose();
+ }
+ catch (JSDisconnectedException)
+ {
+ // Connection already closed, ignore
+ }
+ }
+}
diff --git a/apps/server/AliasVault.Client/Main/Models/ItemEdit.cs b/apps/server/AliasVault.Client/Main/Models/ItemEdit.cs
index 4adbbe19d..64f8c3300 100644
--- a/apps/server/AliasVault.Client/Main/Models/ItemEdit.cs
+++ b/apps/server/AliasVault.Client/Main/Models/ItemEdit.cs
@@ -204,7 +204,7 @@ public sealed class ItemEdit
IsHidden = field.IsHidden,
IsMultiValue = false,
EnableHistory = false,
- Weight = 0,
+ Weight = field.DisplayOrder,
CreatedAt = now,
UpdatedAt = now,
};
@@ -217,7 +217,7 @@ public sealed class ItemEdit
FieldDefinition = fieldDefinition,
FieldKey = null,
Value = field.Value,
- Weight = 0,
+ Weight = field.DisplayOrder,
});
}
else
@@ -230,7 +230,7 @@ public sealed class ItemEdit
FieldDefinitionId = field.FieldDefinitionId,
FieldKey = null,
Value = field.Value,
- Weight = 0,
+ Weight = field.DisplayOrder,
};
// Include FieldDefinition with potentially updated label
@@ -242,7 +242,7 @@ public sealed class ItemEdit
IsHidden = field.IsHidden,
IsMultiValue = false,
EnableHistory = false,
- Weight = 0,
+ Weight = field.DisplayOrder,
};
item.FieldValues.Add(fieldValue);
@@ -430,12 +430,12 @@ public sealed class ItemEdit
}
/// <summary>
- /// Gets all custom fields.
+ /// Gets all custom fields sorted by display order.
/// </summary>
- /// <returns>List of custom fields.</returns>
+ /// <returns>List of custom fields sorted by display order.</returns>
public List<SystemFieldEdit> GetCustomFields()
{
- return Fields.Where(f => f.IsCustomField).ToList();
+ return Fields.Where(f => f.IsCustomField).OrderBy(f => f.DisplayOrder).ToList();
}
/// <summary>
diff --git a/apps/server/AliasVault.Client/Main/Pages/Items/AddEdit.razor b/apps/server/AliasVault.Client/Main/Pages/Items/AddEdit.razor
index e0614c246..7ae698c65 100644
--- a/apps/server/AliasVault.Client/Main/Pages/Items/AddEdit.razor
+++ b/apps/server/AliasVault.Client/Main/Pages/Items/AddEdit.razor
@@ -359,7 +359,7 @@ else
</div>
}
- @* Custom Fields Section *@
+ @* Custom Fields Section with Drag-and-Drop Reordering *@
@{
var customFields = Obj.GetCustomFields();
}
@@ -368,34 +368,11 @@ else
<div class="col-span-1 md:col-span-1 lg:col-span-2">
<div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
<h3 class="mb-4 text-xl font-semibold dark:text-white">@Localizer["CustomFieldsSectionHeader"]</h3>
- <div class="grid gap-6">
- @foreach (var customField in customFields)
- {
- <div class="col-span-6">
- <EditableFieldLabel
- HtmlFor="@($"custom-{customField.TempId ?? customField.FieldKey}")"
- Label="@customField.Label"
- LabelChanged="@((newLabel) => Obj.UpdateCustomFieldLabel(customField.FieldKey, newLabel))"
- OnDelete="@(() => Obj.RemoveCustomField(customField.FieldKey))" />
- @if (customField.FieldType == FieldType.TextArea)
- {
- <div class="relative">
- <textarea id="@($"custom-{customField.TempId ?? customField.FieldKey}")" style="height: 200px;" class="outline-0 shadow-sm bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white" @bind="customField.Value"></textarea>
- </div>
- }
- else if (customField.IsHidden || customField.FieldType == FieldType.Hidden || customField.FieldType == FieldType.Password)
- {
- <EditPasswordFormRow Id="@($"custom-{customField.TempId ?? customField.FieldKey}")" Label="" @bind-Value="customField.Value" ShowPassword="false"></EditPasswordFormRow>
- }
- else
- {
- <div class="relative">
- <input type="text" id="@($"custom-{customField.TempId ?? customField.FieldKey}")" autocomplete="off" class="outline-0 shadow-sm bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white" @bind="customField.Value" autocapitalize="off" autocorrect="off">
- </div>
- }
- </div>
- }
- </div>
+ <DraggableCustomFieldsList
+ CustomFields="@customFields"
+ OnReorder="HandleCustomFieldsReorder"
+ OnLabelChange="HandleCustomFieldLabelChange"
+ OnDelete="HandleCustomFieldDelete" />
</div>
</div>
}
@@ -817,6 +794,39 @@ else
StateHasChanged();
}
+ /// <summary>
+ /// Handles custom fields reorder (drag-and-drop).
+ /// Updates the Fields list with the reordered custom fields.
+ /// </summary>
+ private void HandleCustomFieldsReorder(List<SystemFieldEdit> reorderedFields)
+ {
+ // Remove all existing custom fields from the list
+ Obj.Fields.RemoveAll(f => f.IsCustomField);
+
+ // Add the reordered custom fields back
+ Obj.Fields.AddRange(reorderedFields);
+
+ StateHasChanged();
+ }
+
+ /// <summary>
+ /// Handles custom field label change from the draggable list.
+ /// </summary>
+ private void HandleCustomFieldLabelChange((string fieldKey, string newLabel) args)
+ {
+ Obj.UpdateCustomFieldLabel(args.fieldKey, args.newLabel);
+ StateHasChanged();
+ }
+
+ /// <summary>
+ /// Handles custom field deletion from the draggable list.
+ /// </summary>
+ private void HandleCustomFieldDelete(string fieldKey)
+ {
+ Obj.RemoveCustomField(fieldKey);
+ StateHasChanged();
+ }
+
/// <summary>
/// Handles item type change.
/// Clears field values that don't apply to the new item type.
diff --git a/apps/server/AliasVault.Client/wwwroot/css/tailwind.css b/apps/server/AliasVault.Client/wwwroot/css/tailwind.css
index 0d9b9afd6..d396f891f 100644
--- a/apps/server/AliasVault.Client/wwwroot/css/tailwind.css
+++ b/apps/server/AliasVault.Client/wwwroot/css/tailwind.css
@@ -1350,6 +1350,10 @@ video {
animation: spin-ccw 1s linear infinite;
}
+.cursor-grab {
+ cursor: grab;
+}
+
.cursor-not-allowed {
cursor: not-allowed;
}
@@ -3137,6 +3141,10 @@ video {
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
+.active\:cursor-grabbing:active {
+ cursor: grabbing;
+}
+
.disabled\:cursor-not-allowed:disabled {
cursor: not-allowed;
}
diff --git a/apps/server/AliasVault.Client/wwwroot/js/modules/dragAndDrop.js b/apps/server/AliasVault.Client/wwwroot/js/modules/dragAndDrop.js
new file mode 100644
index 000000000..6e8734730
--- /dev/null
+++ b/apps/server/AliasVault.Client/wwwroot/js/modules/dragAndDrop.js
@@ -0,0 +1,266 @@
+/**
+ * Drag and Drop module for reorderable lists in Blazor.
+ * Uses HTML5 Drag and Drop API with placeholder-based visual feedback.
+ */
+
+/**
+ * Initialize drag and drop functionality on a sortable list.
+ * @param {string} containerId - The ID of the container element
+ * @param {object} dotNetRef - Reference to the .NET object for callbacks
+ */
+export function initDragAndDrop(containerId, dotNetRef) {
+ const container = document.getElementById(containerId);
+ if (!container) {
+ console.warn(`DragAndDrop: Container with ID '${containerId}' not found`);
+ return;
+ }
+
+ let draggedItem = null;
+ let draggedIndex = -1;
+ let currentDropIndex = -1;
+ let placeholder = null;
+ let draggedItemHeight = 0;
+
+ /**
+ * Create a placeholder element for visual feedback.
+ * @param {number} height - Height of the placeholder
+ * @returns {HTMLElement} The placeholder element
+ */
+ function createPlaceholder(height) {
+ const el = document.createElement('div');
+ el.className = 'drag-placeholder';
+ el.style.cssText = `
+ height: ${height}px;
+ margin: 8px 0;
+ background: rgba(249, 115, 22, 0.1);
+ border: 2px dashed rgba(249, 115, 22, 0.6);
+ border-radius: 8px;
+ transition: height 0.15s ease-out;
+ `;
+ return el;
+ }
+
+ /**
+ * Get all draggable items in the container (excluding placeholder).
+ * @returns {HTMLElement[]} Array of draggable items
+ */
+ function getItems() {
+ return Array.from(container.querySelectorAll('[data-drag-item]'));
+ }
+
+ /**
+ * Get the index of an item in the container.
+ * @param {HTMLElement} item - The item element
+ * @returns {number} The index of the item
+ */
+ function getItemIndex(item) {
+ return getItems().indexOf(item);
+ }
+
+ /**
+ * Remove the placeholder from the DOM.
+ */
+ function removePlaceholder() {
+ if (placeholder && placeholder.parentNode) {
+ placeholder.parentNode.removeChild(placeholder);
+ }
+ placeholder = null;
+ }
+
+ /**
+ * Insert placeholder at the correct position based on mouse Y position.
+ * @param {number} mouseY - The Y position of the mouse
+ */
+ function updatePlaceholderPosition(mouseY) {
+ const items = getItems();
+ let insertIndex = items.length; // Default to end
+
+ for (let i = 0; i < items.length; i++) {
+ const item = items[i];
+ if (item === draggedItem) continue;
+
+ const rect = item.getBoundingClientRect();
+ const itemMiddle = rect.top + rect.height / 2;
+
+ if (mouseY < itemMiddle) {
+ insertIndex = i;
+ break;
+ }
+ }
+
+ // Adjust index if dragging from above
+ if (draggedIndex < insertIndex) {
+ insertIndex--;
+ }
+
+ // Don't update if position hasn't changed
+ if (insertIndex === currentDropIndex) return;
+ currentDropIndex = insertIndex;
+
+ // Remove existing placeholder
+ removePlaceholder();
+
+ // Create and insert new placeholder (use captured height since original is hidden)
+ placeholder = createPlaceholder(draggedItemHeight);
+
+ // Find the correct DOM position to insert
+ const allItems = getItems();
+ let actualInsertIndex = insertIndex;
+ if (draggedIndex < insertIndex) {
+ actualInsertIndex++; // Account for dragged item still being in DOM
+ }
+
+ if (actualInsertIndex >= allItems.length) {
+ container.appendChild(placeholder);
+ } else {
+ const referenceItem = allItems[actualInsertIndex];
+ if (referenceItem && referenceItem !== draggedItem) {
+ container.insertBefore(placeholder, referenceItem);
+ } else if (actualInsertIndex + 1 < allItems.length) {
+ container.insertBefore(placeholder, allItems[actualInsertIndex + 1]);
+ } else {
+ container.appendChild(placeholder);
+ }
+ }
+ }
+
+ // Add event listeners to all draggable items
+ function setupItems() {
+ getItems().forEach((item, index) => {
+ item.setAttribute('draggable', 'true');
+ item.dataset.index = index;
+
+ item.addEventListener('dragstart', handleDragStart);
+ item.addEventListener('dragend', handleDragEnd);
+ });
+
+ // Container-level events for better drop detection
+ container.addEventListener('dragover', handleContainerDragOver);
+ container.addEventListener('drop', handleContainerDrop);
+ container.addEventListener('dragleave', handleContainerDragLeave);
+ }
+
+ /**
+ * Handle drag start event.
+ * @param {DragEvent} e - The drag event
+ */
+ function handleDragStart(e) {
+ draggedItem = this;
+ draggedIndex = getItemIndex(this);
+ currentDropIndex = draggedIndex;
+
+ // Capture height before hiding
+ draggedItemHeight = this.offsetHeight;
+
+ // Set drag data (required for Firefox)
+ e.dataTransfer.effectAllowed = 'move';
+ e.dataTransfer.setData('text/plain', draggedIndex.toString());
+
+ // Hide the original item after a short delay (to allow the drag image to be captured)
+ setTimeout(() => {
+ this.style.opacity = '0';
+ this.style.height = '0';
+ this.style.margin = '0';
+ this.style.padding = '0';
+ this.style.overflow = 'hidden';
+ }, 0);
+ }
+
+ /**
+ * Handle drag end event.
+ * @param {DragEvent} e - The drag event
+ */
+ function handleDragEnd(e) {
+ if (draggedItem) {
+ draggedItem.style.opacity = '';
+ draggedItem.style.height = '';
+ draggedItem.style.margin = '';
+ draggedItem.style.padding = '';
+ draggedItem.style.overflow = '';
+ }
+
+ removePlaceholder();
+
+ draggedItem = null;
+ draggedIndex = -1;
+ currentDropIndex = -1;
+ }
+
+ /**
+ * Handle drag over on container.
+ * @param {DragEvent} e - The drag event
+ */
+ function handleContainerDragOver(e) {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = 'move';
+
+ if (draggedItem) {
+ updatePlaceholderPosition(e.clientY);
+ }
+ }
+
+ /**
+ * Handle drag leave on container.
+ * @param {DragEvent} e - The drag event
+ */
+ function handleContainerDragLeave(e) {
+ // Only remove placeholder if truly leaving the container
+ const rect = container.getBoundingClientRect();
+ if (e.clientX < rect.left || e.clientX > rect.right ||
+ e.clientY < rect.top || e.clientY > rect.bottom) {
+ removePlaceholder();
+ currentDropIndex = -1;
+ }
+ }
+
+ /**
+ * Handle drop on container.
+ * @param {DragEvent} e - The drag event
+ */
+ function handleContainerDrop(e) {
+ e.preventDefault();
+ e.stopPropagation();
+
+ if (draggedItem && currentDropIndex !== -1 && currentDropIndex !== draggedIndex) {
+ // Notify Blazor of the reorder
+ if (dotNetRef) {
+ dotNetRef.invokeMethodAsync('OnItemReordered', draggedIndex, currentDropIndex);
+ }
+ }
+
+ // Clean up
+ if (draggedItem) {
+ draggedItem.style.opacity = '';
+ draggedItem.style.height = '';
+ draggedItem.style.margin = '';
+ draggedItem.style.padding = '';
+ draggedItem.style.overflow = '';
+ }
+ removePlaceholder();
+
+ draggedItem = null;
+ draggedIndex = -1;
+ currentDropIndex = -1;
+ }
+
+ // Initial setup
+ setupItems();
+
+ // Return cleanup function
+ return {
+ dispose: function () {
+ getItems().forEach(item => {
+ item.removeAttribute('draggable');
+ item.removeEventListener('dragstart', handleDragStart);
+ item.removeEventListener('dragend', handleDragEnd);
+ });
+ container.removeEventListener('dragover', handleContainerDragOver);
+ container.removeEventListener('drop', handleContainerDrop);
+ container.removeEventListener('dragleave', handleContainerDragLeave);
+ },
+ refresh: function () {
+ this.dispose();
+ setupItems();
+ }
+ };
+}