Skip to content

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

Tweak clipboard clear for various usecases and make it more robust (#881)

Leendert de Borst3305958e6041
diff --git a/apps/server/AliasVault.Client/Main/Components/ClipboardCountdownBar.razor b/apps/server/AliasVault.Client/Main/Components/ClipboardCountdownBar.razor
index 4684dc2f6..8eae1424f 100644
--- a/apps/server/AliasVault.Client/Main/Components/ClipboardCountdownBar.razor
+++ b/apps/server/AliasVault.Client/Main/Components/ClipboardCountdownBar.razor
@@ -1,34 +1,135 @@
@inject ClipboardCopyService ClipboardCopyService
+@inject JsInteropService JsInteropService
@implements IDisposable
+@using Microsoft.JSInterop
@if (IsVisible)
{
<div class="fixed top-0 left-0 right-0 z-50 h-1 bg-gray-200 dark:bg-gray-700">
- <div class="h-full bg-orange-500 dark:bg-orange-400 transition-all duration-100 ease-linear"
- style="width: @(Progress * 100)%"></div>
+ <div class="h-full @GetBarColorClass() transition-all duration-100 ease-linear @GetAnimationClass()"
+ style="width: @(Progress * 100)%">
+ </div>
</div>
+
+ @if (CurrentStatus == "pending")
+ {
+ <style>
+ @@keyframes custom-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.5; }
+ }
+ .custom-pulse-animation {
+ animation: custom-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
+ }
+ </style>
+ }
}
@code {
private bool IsVisible { get; set; }
private double Progress { get; set; }
+ private string CurrentStatus { get; set; } = "active";
+ private DotNetObjectReference<ClipboardCountdownBar>? _objRef;
/// <inheritdoc />
- protected override void OnInitialized()
+ protected override async void OnInitialized()
{
ClipboardCopyService.OnTimerProgress += HandleTimerProgress;
+
+ // Register for JavaScript status callbacks
+ _objRef = DotNetObjectReference.Create(this);
+ await JsInteropService.RegisterClipboardStatusCallback(_objRef);
}
private void HandleTimerProgress(double progress)
{
Progress = progress;
- IsVisible = progress > 0;
+
+ if (progress > 0)
+ {
+ // Normal countdown in progress
+ IsVisible = true;
+ CurrentStatus = "active";
+ }
+ else
+ {
+ // Countdown completed - only default to pending if not already cleared
+ if (CurrentStatus != "cleared")
+ {
+ IsVisible = true;
+ Progress = 1.0; // Show full bar when pending
+ CurrentStatus = "pending";
+ }
+ }
+
InvokeAsync(StateHasChanged);
}
+ /// <summary>
+ /// Called from JavaScript when clipboard status changes.
+ /// </summary>
+ [JSInvokable]
+ public async Task OnClipboardStatusChange(string status)
+ {
+ Console.WriteLine($"[ClipboardCountdownBar] Status changed to: {status}");
+
+ // Ignore the test 'registered' status
+ if (status == "registered")
+ {
+ return;
+ }
+
+ // Ensure UI updates happen on the UI thread
+ await InvokeAsync(() =>
+ {
+ CurrentStatus = status;
+
+ // Hide the bar when clipboard is cleared
+ if (status == "cleared")
+ {
+ IsVisible = false;
+ Progress = 0;
+ }
+ // Update pending state properly
+ else if (status == "pending")
+ {
+ IsVisible = true;
+ Progress = 1.0;
+ }
+ // Handle active state
+ else if (status == "active")
+ {
+ // Let timer handle active state, but ensure we're visible if we should be
+ }
+
+ StateHasChanged();
+ });
+ }
+
+ private string GetBarColorClass()
+ {
+ return CurrentStatus switch
+ {
+ "pending" => "bg-blue-500 dark:bg-blue-400", // Blue when pending (waiting for focus)
+ _ => "bg-orange-500 dark:bg-orange-400" // Orange when actively counting down or cleared
+ };
+ }
+
+ private string GetAnimationClass()
+ {
+ // Add pulse animation when pending to draw attention
+ return CurrentStatus == "pending" ? "custom-pulse-animation" : "";
+ }
+
/// <inheritdoc />
- public void Dispose()
+ public async void Dispose()
{
ClipboardCopyService.OnTimerProgress -= HandleTimerProgress;
+
+ if (_objRef != null)
+ {
+ await JsInteropService.UnregisterClipboardStatusCallback();
+ _objRef.Dispose();
+ }
}
}
diff --git a/apps/server/AliasVault.Client/Main/Components/Forms/CopyPasteFormRow.razor b/apps/server/AliasVault.Client/Main/Components/Forms/CopyPasteFormRow.razor
index 683b7f340..54267964d 100644
--- a/apps/server/AliasVault.Client/Main/Components/Forms/CopyPasteFormRow.razor
+++ b/apps/server/AliasVault.Client/Main/Components/Forms/CopyPasteFormRow.razor
@@ -15,7 +15,10 @@
@if (Copied)
{
<span class="absolute inset-y-0 right-0 flex items-center pr-3 text-green-500 dark:text-green-400">
- @Localizer["CopiedMessage"]
+ <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
+ <path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z"></path>
+ <path d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"></path>
+ </svg>
</span>
}
</div>
diff --git a/apps/server/AliasVault.Client/Main/Components/Forms/CopyPastePasswordFormRow.razor b/apps/server/AliasVault.Client/Main/Components/Forms/CopyPastePasswordFormRow.razor
index 82861ccf7..202c544f7 100644
--- a/apps/server/AliasVault.Client/Main/Components/Forms/CopyPastePasswordFormRow.razor
+++ b/apps/server/AliasVault.Client/Main/Components/Forms/CopyPastePasswordFormRow.razor
@@ -22,7 +22,10 @@
@if (Copied)
{
<span class="absolute inset-y-0 right-10 flex items-center pr-3 text-green-500 dark:text-green-400">
- Copied!
+ <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
+ <path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z"></path>
+ <path d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"></path>
+ </svg>
</span>
}
</div>
diff --git a/apps/server/AliasVault.Client/Program.cs b/apps/server/AliasVault.Client/Program.cs
index a03a2412e..36f47544e 100644
--- a/apps/server/AliasVault.Client/Program.cs
+++ b/apps/server/AliasVault.Client/Program.cs
@@ -95,7 +95,7 @@ builder.Services.AddScoped<MinDurationLoadingService>();
builder.Services.AddScoped<KeyboardShortcutService>();
builder.Services.AddScoped<JsInteropService>();
builder.Services.AddScoped<EmailService>();
-builder.Services.AddSingleton<ClipboardCopyService>();
+builder.Services.AddScoped<ClipboardCopyService>();
builder.Services.AddScoped<ConfirmModalService>();
builder.Services.AddScoped<QuickCreateStateService>();
builder.Services.AddScoped<LanguageService>();
diff --git a/apps/server/AliasVault.Client/Services/ClipboardCopyService.cs b/apps/server/AliasVault.Client/Services/ClipboardCopyService.cs
index 9c07f10cd..f012080f7 100644
--- a/apps/server/AliasVault.Client/Services/ClipboardCopyService.cs
+++ b/apps/server/AliasVault.Client/Services/ClipboardCopyService.cs
@@ -13,12 +13,13 @@ using Timer = System.Timers.Timer;
/// <summary>
/// Service to manage the clipboard copy UI state across the application.
/// </summary>
-public sealed class ClipboardCopyService : IDisposable
+/// <param name="dbService">Database service to access settings.</param>
+public sealed class ClipboardCopyService(DbService dbService) : IDisposable
{
private string _currentCopiedId = string.Empty;
private Timer? _progressTimer;
+ private Timer? _copiedStateTimer;
private DateTime _clearTime;
- private int _clearDurationSeconds = 5;
/// <summary>
/// Event to notify the application that an item has been copied.
@@ -31,13 +32,9 @@ public sealed class ClipboardCopyService : IDisposable
public event Action<double>? OnTimerProgress;
/// <summary>
- /// Gets or sets the duration in seconds before clipboard is cleared.
+ /// Gets the duration in seconds before clipboard is cleared from settings.
/// </summary>
- public int ClearDurationSeconds
- {
- get => _clearDurationSeconds;
- set => _clearDurationSeconds = value > 0 ? value : 5;
- }
+ public int ClearDurationSeconds => Math.Max(dbService.Settings.ClipboardClearSeconds, 0);
/// <summary>
/// Gets a value indicating whether there is an active progress timer.
@@ -55,11 +52,18 @@ public sealed class ClipboardCopyService : IDisposable
if (!string.IsNullOrEmpty(id))
{
- StartProgressTimer();
+ // Only start progress timer if clipboard clearing is enabled (duration > 0)
+ if (ClearDurationSeconds > 0)
+ {
+ StartProgressTimer();
+ }
+
+ StartCopiedStateTimer();
}
else
{
StopProgressTimer();
+ StopCopiedStateTimer();
}
}
@@ -88,13 +92,20 @@ public sealed class ClipboardCopyService : IDisposable
public void Dispose()
{
StopProgressTimer();
+ StopCopiedStateTimer();
}
private void StartProgressTimer()
{
StopProgressTimer();
- _clearTime = DateTime.UtcNow.AddSeconds(_clearDurationSeconds);
+ var durationSeconds = ClearDurationSeconds;
+ if (durationSeconds <= 0)
+ {
+ return; // Don't start timer if clearing is disabled
+ }
+
+ _clearTime = DateTime.UtcNow.AddSeconds(durationSeconds);
// Progress timer for UI updates only (every 100ms)
_progressTimer = new Timer(100);
@@ -118,18 +129,53 @@ public sealed class ClipboardCopyService : IDisposable
private void UpdateProgress(object? sender, ElapsedEventArgs? e)
{
var remaining = GetRemainingSeconds();
- var progress = remaining / _clearDurationSeconds;
+ var durationSeconds = ClearDurationSeconds;
+
+ if (durationSeconds <= 0)
+ {
+ StopProgressTimer();
+ return;
+ }
+
+ var progress = remaining / durationSeconds;
if (progress <= 0)
{
- // Timer finished, reset UI state
+ // Timer finished, but don't reset if clipboard clear is still pending
+ // The JavaScript will handle clearing and status updates
StopProgressTimer();
- _currentCopiedId = string.Empty;
- OnCopy?.Invoke(_currentCopiedId);
}
else
{
OnTimerProgress?.Invoke(progress);
}
}
+
+ private void StartCopiedStateTimer()
+ {
+ StopCopiedStateTimer();
+
+ // Use settings delay value, or default to 3 seconds if clipboard clearing is disabled (0 seconds)
+ var delaySeconds = ClearDurationSeconds > 0 ? ClearDurationSeconds : 3;
+
+ // Timer to clear the "copied" visual state
+ _copiedStateTimer = new Timer(delaySeconds * 1000); // Convert to milliseconds
+ _copiedStateTimer.Elapsed += OnCopiedStateTimerElapsed;
+ _copiedStateTimer.AutoReset = false; // Only run once
+ _copiedStateTimer.Start();
+ }
+
+ private void StopCopiedStateTimer()
+ {
+ _copiedStateTimer?.Stop();
+ _copiedStateTimer?.Dispose();
+ _copiedStateTimer = null;
+ }
+
+ private void OnCopiedStateTimerElapsed(object? sender, ElapsedEventArgs e)
+ {
+ _currentCopiedId = string.Empty;
+ OnCopy?.Invoke(_currentCopiedId);
+ StopCopiedStateTimer();
+ }
}
diff --git a/apps/server/AliasVault.Client/Services/JsInterop/JsInteropService.cs b/apps/server/AliasVault.Client/Services/JsInterop/JsInteropService.cs
index edb6942af..0c4ea83ba 100644
--- a/apps/server/AliasVault.Client/Services/JsInterop/JsInteropService.cs
+++ b/apps/server/AliasVault.Client/Services/JsInterop/JsInteropService.cs
@@ -115,6 +115,46 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)
public async Task CopyToClipboard(string value) =>
await jsRuntime.InvokeVoidAsync("navigator.clipboard.writeText", value);
+ /// <summary>
+ /// Copy a string to the clipboard and schedule automatic clearing after specified seconds.
+ /// </summary>
+ /// <param name="value">Value to copy to clipboard.</param>
+ /// <param name="clearAfterSeconds">Number of seconds after which to clear the clipboard.</param>
+ /// <returns>True if copy was successful, false otherwise.</returns>
+ public async Task<bool> CopyToClipboardWithClear(string value, int clearAfterSeconds) =>
+ await jsRuntime.InvokeAsync<bool>("copyToClipboardWithClear", value, clearAfterSeconds);
+
+ /// <summary>
+ /// Clear the clipboard safely, handling document focus issues.
+ /// </summary>
+ /// <returns>True if clipboard was cleared successfully, false otherwise.</returns>
+ public async Task<bool> SafeClearClipboard() =>
+ await jsRuntime.InvokeAsync<bool>("safeClearClipboard");
+
+ /// <summary>
+ /// Clear the clipboard by setting it to an empty string.
+ /// </summary>
+ /// <returns>Task.</returns>
+ public async Task ClearClipboard() =>
+ await jsRuntime.InvokeVoidAsync("navigator.clipboard.writeText", string.Empty);
+
+ /// <summary>
+ /// Register a callback for clipboard status changes.
+ /// </summary>
+ /// <typeparam name="TComponent">Component type.</typeparam>
+ /// <param name="objRef">DotNetObjectReference.</param>
+ /// <returns>Task.</returns>
+ public async Task RegisterClipboardStatusCallback<TComponent>(DotNetObjectReference<TComponent> objRef)
+ where TComponent : class =>
+ await jsRuntime.InvokeVoidAsync("registerClipboardStatusCallback", objRef);
+
+ /// <summary>
+ /// Unregister the clipboard status callback.
+ /// </summary>
+ /// <returns>Task.</returns>
+ public async Task UnregisterClipboardStatusCallback() =>
+ await jsRuntime.InvokeVoidAsync("unregisterClipboardStatusCallback");
+
/// <summary>
/// Initializes the top menu.
/// </summary>
diff --git a/apps/server/AliasVault.Client/wwwroot/css/tailwind.css b/apps/server/AliasVault.Client/wwwroot/css/tailwind.css
index 93afadb0e..a0af3333c 100644
--- a/apps/server/AliasVault.Client/wwwroot/css/tailwind.css
+++ b/apps/server/AliasVault.Client/wwwroot/css/tailwind.css
@@ -1735,6 +1735,11 @@ video {
background-color: rgb(249 115 22 / var(--tw-bg-opacity));
}
+.bg-green-500 {
+ --tw-bg-opacity: 1;
+ background-color: rgb(34 197 94 / var(--tw-bg-opacity));
+}
+
.bg-opacity-50 {
--tw-bg-opacity: 0.5;
}
@@ -2896,6 +2901,11 @@ video {
background-color: rgb(113 63 18 / 0.2);
}
+.dark\:bg-green-400:is(.dark *) {
+ --tw-bg-opacity: 1;
+ background-color: rgb(74 222 128 / var(--tw-bg-opacity));
+}
+
.dark\:bg-opacity-80:is(.dark *) {
--tw-bg-opacity: 0.8;
}
diff --git a/apps/server/AliasVault.Client/wwwroot/js/utilities.js b/apps/server/AliasVault.Client/wwwroot/js/utilities.js
index 1c1d8f10e..af357d224 100644
--- a/apps/server/AliasVault.Client/wwwroot/js/utilities.js
+++ b/apps/server/AliasVault.Client/wwwroot/js/utilities.js
@@ -40,6 +40,162 @@ window.clipboardCopy = {
}
};
+// Global clipboard manager with timestamp-based clearing
+window.clipboardManager = {
+ clearByTime: null,
+ clearTimer: null,
+ copiedValue: null,
+ clearPending: false, // Track if clear is pending due to focus issues
+ statusCallback: null, // Callback to notify Blazor of status changes
+
+ // Set up a new clipboard clear schedule
+ scheduleClipboardClear: function(seconds) {
+ // Clear any existing timer
+ if (this.clearTimer) {
+ clearTimeout(this.clearTimer);
+ this.clearTimer = null;
+ }
+
+ // Reset pending state
+ this.clearPending = false;
+ this.notifyStatusChange('active');
+
+ // Set the clear by time
+ this.clearByTime = Date.now() + (seconds * 1000);
+
+ // Try to clear when the time is reached
+ this.clearTimer = setTimeout(() => {
+ this.attemptClipboardClear('timer expired');
+ }, seconds * 1000);
+ },
+
+ // Notify Blazor of status change
+ notifyStatusChange: function(status) {
+ if (this.statusCallback) {
+ try {
+ this.statusCallback.invokeMethodAsync('OnClipboardStatusChange', status);
+ } catch (error) {
+ }
+ }
+ },
+
+ // Attempt to clear the clipboard
+ attemptClipboardClear: function(source) {
+ // Check if we should clear
+ if (!this.clearByTime) {
+ return Promise.resolve(false);
+ }
+
+ const now = Date.now();
+ const timeRemaining = this.clearByTime - now;
+
+ if (timeRemaining > 100) { // Allow 100ms tolerance for timer precision
+ // If called from timer and there's still time, reschedule
+ if (source === 'timer expired' && timeRemaining > 0) {
+ this.clearTimer = setTimeout(() => {
+ this.attemptClipboardClear('timer expired');
+ }, timeRemaining);
+ }
+ return Promise.resolve(false);
+ }
+
+ return navigator.clipboard.writeText('')
+ .then(() => {
+ this.clearByTime = null;
+ this.copiedValue = null;
+ this.clearPending = false;
+ if (this.clearTimer) {
+ clearTimeout(this.clearTimer);
+ this.clearTimer = null;
+ }
+ this.notifyStatusChange('cleared');
+ return true;
+ })
+ .catch((error) => {
+ if (error.name === 'NotAllowedError' || error.message.includes('Document is not focused')) {
+ // Don't clear the clearByTime, we'll retry when we get focus
+ this.clearPending = true;
+ this.notifyStatusChange('pending');
+ return false;
+ }
+ console.warn(`[Clipboard] ❌ ERROR - Failed to clear clipboard from: ${source}`, error);
+ return false;
+ });
+ },
+
+ // Check and clear if needed (called on focus events)
+ checkAndClear: function(source) {
+ if (this.clearByTime && Date.now() >= this.clearByTime) {
+ // Reset pending state when we're actively trying to clear
+ this.clearPending = false;
+ this.notifyStatusChange('active');
+ // Small delay to ensure browser is ready after focus
+ setTimeout(() => {
+ this.attemptClipboardClear(source);
+ }, 100);
+ } else if (this.clearByTime) {
+ const remaining = Math.ceil((this.clearByTime - Date.now()) / 1000);
+ }
+ }
+};
+
+// Copy to clipboard and schedule clear
+window.copyToClipboardWithClear = function(text, clearAfterSeconds) {
+ return navigator.clipboard.writeText(text)
+ .then(() => {
+ if (clearAfterSeconds > 0) {
+ window.clipboardManager.copiedValue = text;
+ window.clipboardManager.scheduleClipboardClear(clearAfterSeconds);
+ }
+ return true;
+ })
+ .catch((error) => {
+ console.error('[Clipboard] ❌ Failed to copy to clipboard:', error);
+ return false;
+ });
+};
+
+// Global focus event listener
+window.addEventListener('focus', () => {
+ window.clipboardManager.checkAndClear('window focus event');
+});
+
+// Global visibility change listener
+document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'visible') {
+ window.clipboardManager.checkAndClear('document became visible');
+ }
+});
+
+// Also check on page visibility API
+document.addEventListener('visibilitychange', () => {
+ if (!document.hidden) {
+ window.clipboardManager.checkAndClear('page no longer hidden');
+ }
+});
+
+// Check when window becomes active (another way to detect focus)
+window.addEventListener('pageshow', () => {
+ window.clipboardManager.checkAndClear('pageshow event');
+});
+
+// Legacy method for compatibility
+window.safeClearClipboard = function() {
+ return window.clipboardManager.attemptClipboardClear('manual clear request');
+};
+
+// Register a callback for clipboard status changes
+window.registerClipboardStatusCallback = function(callback) {
+ window.clipboardManager.statusCallback = callback;
+ // Test the callback immediately to make sure it works
+ window.clipboardManager.notifyStatusChange('registered');
+};
+
+// Unregister the callback
+window.unregisterClipboardStatusCallback = function() {
+ window.clipboardManager.statusCallback = null;
+};
+
// Primarily used by E2E tests.
window.blazorNavigate = (url) => {
Blazor.navigateTo(url);
@@ -304,7 +460,7 @@ const visibilityChangeHandlers = new Map();
/**
* Registers visibility callback that is invoked when the visibility state of the current page/tab changes.
- *
+ *
* @param {any} dotnetHelper
*/
window.registerVisibilityCallback = function (dotnetHelper) {
@@ -312,23 +468,23 @@ window.registerVisibilityCallback = function (dotnetHelper) {
const handler = function() {
dotnetHelper.invokeMethodAsync('OnVisibilityChange', !document.hidden);
};
-
+
visibilityChangeHandlers.set(dotnetHelper, handler);
document.addEventListener("visibilitychange", handler);
-
+
// Initial call to set the correct initial state.
dotnetHelper.invokeMethodAsync('OnVisibilityChange', !document.hidden);
};
/**
* Unregisters any previously registered visibility callbacks to prevent memory leaks.
- *
+ *
* @param {any} dotnetHelper
*/
window.unregisterVisibilityCallback = function (dotnetHelper) {
// Get the stored handler.
const handler = visibilityChangeHandlers.get(dotnetHelper);
-
+
if (handler) {
// Remove the event listener with the same function reference.
document.removeEventListener("visibilitychange", handler);