| | | 1 | | using Microsoft.AspNetCore.Components; |
| | | 2 | | using Microsoft.JSInterop; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using Pomodoro.Web.Components.History; |
| | | 5 | | using Pomodoro.Web.Models; |
| | | 6 | | using Pomodoro.Web.Services; |
| | | 7 | | using System.Threading; |
| | | 8 | | |
| | | 9 | | namespace Pomodoro.Web.Pages; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Code-behind for History page |
| | | 13 | | /// Displays activity history with summary cards and timeline |
| | | 14 | | /// </summary> |
| | | 15 | | public class HistoryBase : ComponentBase, IAsyncDisposable |
| | | 16 | | { |
| | | 17 | | #region Services (Dependency Injection) |
| | | 18 | | |
| | | 19 | | [Inject] |
| | 1878 | 20 | | protected IActivityService ActivityService { get; set; } = default!; |
| | | 21 | | |
| | | 22 | | [Inject] |
| | 316 | 23 | | protected IJSRuntime JSRuntime { get; set; } = default!; |
| | | 24 | | |
| | | 25 | | [Inject] |
| | 568 | 26 | | protected IInfiniteScrollInterop InfiniteScrollInterop { get; set; } = default!; |
| | | 27 | | |
| | | 28 | | [Inject] |
| | 752 | 29 | | protected ILogger<HistoryBase> Logger { get; set; } = default!; |
| | | 30 | | |
| | | 31 | | [Inject] |
| | 493 | 32 | | protected IHistoryStatsService HistoryStatsService { get; set; } = default!; |
| | | 33 | | |
| | | 34 | | [Inject] |
| | 317 | 35 | | protected HistoryPagePresenterService HistoryPagePresenterService { get; set; } = default!; |
| | | 36 | | |
| | | 37 | | [Inject] |
| | 472 | 38 | | protected ILocalDateTimeService LocalDateTimeService { get; set; } = default!; |
| | | 39 | | |
| | | 40 | | #endregion |
| | | 41 | | |
| | | 42 | | #region State |
| | | 43 | | |
| | 615 | 44 | | protected DateTime SelectedDate { get; set; } = DateTime.Now.Date; |
| | 357 | 45 | | protected DateTime SelectedWeekStart { get; set; } |
| | 468 | 46 | | protected HistoryTab ActiveTab { get; set; } = HistoryTab.Daily; |
| | 797 | 47 | | protected List<ActivityRecord> CurrentActivities { get; set; } = new(); |
| | 779 | 48 | | protected DailyStatsSummary CurrentStats { get; set; } = new(); |
| | 200 | 49 | | protected WeeklyStats? WeeklyStats { get; set; } |
| | 351 | 50 | | protected Dictionary<DateTime, int> WeeklyFocusMinutes { get; set; } = new(); |
| | 351 | 51 | | protected Dictionary<DateTime, int> WeeklyBreakMinutes { get; set; } = new(); |
| | 560 | 52 | | protected int CurrentSkip { get; set; } |
| | 734 | 53 | | protected bool HasMoreActivities { get; set; } |
| | 305 | 54 | | protected bool IsLoadingMore { get; set; } |
| | 344 | 55 | | protected int PageSize { get; } = 20; |
| | | 56 | | |
| | | 57 | | /// <summary> |
| | | 58 | | /// Component parameter for testing: Sets initial active tab |
| | | 59 | | /// </summary> |
| | | 60 | | [Parameter] |
| | 345 | 61 | | public HistoryTab InitialActiveTab { get; set; } = HistoryTab.Daily; |
| | | 62 | | |
| | | 63 | | /// <summary> |
| | | 64 | | /// Component parameter for testing: Sets the initial weekly stats |
| | | 65 | | /// </summary> |
| | | 66 | | [Parameter] |
| | 177 | 67 | | public WeeklyStats? InitialWeeklyStats { get; set; } |
| | | 68 | | |
| | | 69 | | /// <summary> |
| | | 70 | | /// Component parameter for testing: Sets whether there are more activities to load |
| | | 71 | | /// </summary> |
| | | 72 | | [Parameter] |
| | 330 | 73 | | public bool InitialHasMoreActivities { get; set; } = false; |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Component parameter for testing: Sets whether more activities are loading |
| | | 77 | | /// </summary> |
| | | 78 | | [Parameter] |
| | 324 | 79 | | public bool InitialIsLoadingMore { get; set; } = false; |
| | | 80 | | |
| | | 81 | | /// <summary> |
| | | 82 | | /// Component parameter for testing: Sets the initial activities list |
| | | 83 | | /// </summary> |
| | | 84 | | [Parameter] |
| | 496 | 85 | | public List<ActivityRecord> InitialActivities { get; set; } = new(); |
| | | 86 | | |
| | | 87 | | /// <summary> |
| | | 88 | | /// Component parameter for testing: Sets the initial current stats |
| | | 89 | | /// </summary> |
| | | 90 | | [Parameter] |
| | 165 | 91 | | public DailyStatsSummary? InitialCurrentStats { get; set; } |
| | | 92 | | |
| | | 93 | | /// <summary> |
| | | 94 | | /// Component parameter for testing: Sets the initial selected date |
| | | 95 | | /// </summary> |
| | | 96 | | [Parameter] |
| | 165 | 97 | | public DateTime? InitialSelectedDate { get; set; } |
| | | 98 | | |
| | | 99 | | /// <summary> |
| | | 100 | | /// Component parameter for testing: Sets the initial selected week start |
| | | 101 | | /// </summary> |
| | | 102 | | [Parameter] |
| | 165 | 103 | | public DateTime? InitialSelectedWeekStart { get; set; } |
| | | 104 | | |
| | | 105 | | // Infinite scroll state |
| | | 106 | | private DotNetObjectReference<HistoryBase>? _dotNetRef; |
| | | 107 | | private bool _observerInitialized; |
| | | 108 | | private bool _isDisposed; |
| | | 109 | | private bool _isCallbackInProgress; |
| | 158 | 110 | | private SemaphoreSlim _observerSetupLock = new SemaphoreSlim(1, 1); |
| | | 111 | | |
| | | 112 | | #endregion |
| | | 113 | | |
| | | 114 | | #region Lifecycle Methods |
| | | 115 | | |
| | | 116 | | protected override void OnParametersSet() |
| | 163 | 117 | | { |
| | 163 | 118 | | base.OnParametersSet(); |
| | | 119 | | |
| | | 120 | | // Set protected properties from component parameters for testing purposes |
| | | 121 | | // This allows tests to control conditional rendering paths |
| | 163 | 122 | | if (InitialActiveTab != HistoryTab.Daily) |
| | 11 | 123 | | { |
| | 11 | 124 | | ActiveTab = InitialActiveTab; |
| | 11 | 125 | | } |
| | | 126 | | |
| | 163 | 127 | | if (InitialWeeklyStats != null) |
| | 7 | 128 | | { |
| | 7 | 129 | | WeeklyStats = InitialWeeklyStats; |
| | 7 | 130 | | } |
| | | 131 | | |
| | 163 | 132 | | HasMoreActivities = InitialHasMoreActivities; |
| | | 133 | | |
| | 163 | 134 | | IsLoadingMore = InitialIsLoadingMore; |
| | | 135 | | |
| | 163 | 136 | | if (InitialActivities != null && InitialActivities.Count > 0) |
| | 6 | 137 | | { |
| | 6 | 138 | | CurrentActivities = InitialActivities; |
| | 6 | 139 | | } |
| | | 140 | | |
| | 163 | 141 | | if (InitialCurrentStats != null) |
| | 1 | 142 | | { |
| | 1 | 143 | | CurrentStats = InitialCurrentStats; |
| | 1 | 144 | | } |
| | | 145 | | |
| | 163 | 146 | | if (InitialSelectedDate.HasValue) |
| | 1 | 147 | | { |
| | 1 | 148 | | SelectedDate = InitialSelectedDate.Value; |
| | 1 | 149 | | } |
| | | 150 | | |
| | 163 | 151 | | if (InitialSelectedWeekStart.HasValue) |
| | 1 | 152 | | { |
| | 1 | 153 | | SelectedWeekStart = InitialSelectedWeekStart.Value; |
| | 1 | 154 | | } |
| | 163 | 155 | | } |
| | | 156 | | |
| | | 157 | | protected override async Task OnInitializedAsync() |
| | 157 | 158 | | { |
| | | 159 | | // Subscribe to activity changes |
| | 157 | 160 | | ActivityService.OnActivityChanged += OnActivityChanged; |
| | | 161 | | |
| | | 162 | | // Initialize activity service if needed |
| | 157 | 163 | | await ActivityService.InitializeAsync(); |
| | | 164 | | |
| | | 165 | | // Initialize SelectedDate and SelectedWeekStart to client's local date |
| | 157 | 166 | | var localDate = await LocalDateTimeService.GetLocalDateAsync(); |
| | 157 | 167 | | SelectedDate = localDate; |
| | 157 | 168 | | SelectedWeekStart = WeekNavigatorBase.GetWeekStart(localDate); |
| | | 169 | | |
| | | 170 | | // Load initial data |
| | 157 | 171 | | await LoadDataAsync(); |
| | 157 | 172 | | } |
| | | 173 | | |
| | | 174 | | protected override async Task OnAfterRenderAsync(bool firstRender) |
| | 238 | 175 | | { |
| | | 176 | | // Always recreate DotNetObjectReference if it's null, not just on first render |
| | | 177 | | // This prevents memory leaks if component is re-rendered after a failed initialization |
| | 238 | 178 | | if (_dotNetRef == null) |
| | 157 | 179 | | { |
| | 157 | 180 | | _dotNetRef = DotNetObjectReference.Create(this); |
| | 157 | 181 | | } |
| | | 182 | | |
| | | 183 | | // Set up intersection observer when conditions are met |
| | 238 | 184 | | if (ShouldSetupInfiniteScrollObserver()) |
| | 47 | 185 | | { |
| | | 186 | | // Small delay ensures DOM update cycle completes before observer creation |
| | 47 | 187 | | await Task.Delay(50); |
| | 47 | 188 | | await SetupInfiniteScrollObserverAsync(retryCount: 0); |
| | 35 | 189 | | } |
| | 226 | 190 | | } |
| | | 191 | | |
| | | 192 | | /// <summary> |
| | | 193 | | /// Determines if the infinite scroll observer should be set up |
| | | 194 | | /// </summary> |
| | | 195 | | /// <returns>True if observer setup should be attempted</returns> |
| | | 196 | | private bool ShouldSetupInfiniteScrollObserver() |
| | 238 | 197 | | { |
| | | 198 | | // Only attempt if: |
| | | 199 | | // 1. Component is not disposed |
| | | 200 | | // 2. There are more activities to load |
| | | 201 | | // 3. Observer is not already initialized |
| | | 202 | | // 4. DotNet reference is available |
| | | 203 | | // 5. Currently in Daily view (which has timeline) |
| | 238 | 204 | | return !_isDisposed && |
| | 238 | 205 | | HasMoreActivities && |
| | 238 | 206 | | !_observerInitialized && |
| | 238 | 207 | | _dotNetRef != null && |
| | 238 | 208 | | ActiveTab == HistoryTab.Daily; |
| | 238 | 209 | | } |
| | | 210 | | |
| | | 211 | | /// <summary> |
| | | 212 | | /// Sets up the Intersection Observer for infinite scroll |
| | | 213 | | /// </summary> |
| | | 214 | | /// <param name="retryCount">Current retry attempt (0-2 for max 3 attempts)</param> |
| | | 215 | | private async Task SetupInfiniteScrollObserverAsync(int retryCount = 0) |
| | 58 | 216 | | { |
| | 58 | 217 | | if (!await CanProceedWithObserverSetupAsync()) |
| | 11 | 218 | | { |
| | 11 | 219 | | return; |
| | | 220 | | } |
| | | 221 | | |
| | 35 | 222 | | await ExecuteObserverSetupWithLockAsync(retryCount); |
| | 46 | 223 | | } |
| | | 224 | | |
| | | 225 | | /// <summary> |
| | | 226 | | /// Determines if observer setup can proceed |
| | | 227 | | /// </summary> |
| | | 228 | | /// <returns>True if setup can proceed, false otherwise</returns> |
| | | 229 | | private async Task<bool> CanProceedWithObserverSetupAsync() |
| | 58 | 230 | | { |
| | 58 | 231 | | return await AcquireObserverLockAsync(); |
| | 46 | 232 | | } |
| | | 233 | | |
| | | 234 | | /// <summary> |
| | | 235 | | /// Executes the observer setup with proper lock management |
| | | 236 | | /// </summary> |
| | | 237 | | /// <param name="retryCount">Current retry attempt</param> |
| | | 238 | | private async Task ExecuteObserverSetupWithLockAsync(int retryCount) |
| | 35 | 239 | | { |
| | | 240 | | try |
| | 35 | 241 | | { |
| | 35 | 242 | | var setupResult = await TryCreateObserverAsync(retryCount); |
| | | 243 | | |
| | 35 | 244 | | if (ShouldRetryObserverSetup(setupResult)) |
| | 10 | 245 | | { |
| | 10 | 246 | | await HandleRetryAsync(setupResult); |
| | 10 | 247 | | return; |
| | | 248 | | } |
| | 25 | 249 | | } |
| | | 250 | | finally |
| | 35 | 251 | | { |
| | 35 | 252 | | ReleaseObserverLockIfHeld(); |
| | 35 | 253 | | } |
| | 35 | 254 | | } |
| | | 255 | | |
| | | 256 | | /// <summary> |
| | | 257 | | /// Determines if observer setup should be retried |
| | | 258 | | /// </summary> |
| | | 259 | | /// <param name="setupResult">The result of the observer setup attempt</param> |
| | | 260 | | /// <returns>True if retry is needed, false otherwise</returns> |
| | | 261 | | private bool ShouldRetryObserverSetup(ObserverSetupResult setupResult) |
| | 35 | 262 | | { |
| | 35 | 263 | | return setupResult.ShouldRetry && !_isDisposed && !_observerInitialized; |
| | 35 | 264 | | } |
| | | 265 | | |
| | | 266 | | /// <summary> |
| | | 267 | | /// Acquires the observer setup lock |
| | | 268 | | /// </summary> |
| | | 269 | | /// <returns>True if lock was acquired, false if another setup is in progress</returns> |
| | | 270 | | private async Task<bool> AcquireObserverLockAsync() |
| | 58 | 271 | | { |
| | | 272 | | // Prevent concurrent initialization attempts using async lock |
| | 58 | 273 | | if (!await _observerSetupLock.WaitAsync(0)) |
| | 11 | 274 | | { |
| | 11 | 275 | | Logger.LogDebug("Infinite scroll observer setup already in progress, skipping"); |
| | 11 | 276 | | return false; |
| | | 277 | | } |
| | | 278 | | |
| | 35 | 279 | | return true; |
| | 46 | 280 | | } |
| | | 281 | | |
| | | 282 | | /// <summary> |
| | | 283 | | /// Handles the retry logic for observer setup |
| | | 284 | | /// </summary> |
| | | 285 | | /// <param name="setupResult">The result of the observer setup attempt</param> |
| | | 286 | | private async Task HandleRetryAsync(ObserverSetupResult setupResult) |
| | 10 | 287 | | { |
| | | 288 | | // Release lock before retry to allow retry to acquire it |
| | 10 | 289 | | _observerSetupLock.Release(); |
| | 10 | 290 | | await ExecuteRetryAsync(setupResult.NextRetryCount, setupResult.BackoffDelay); |
| | 10 | 291 | | } |
| | | 292 | | |
| | | 293 | | /// <summary> |
| | | 294 | | /// Releases the observer lock if it's still held |
| | | 295 | | /// </summary> |
| | | 296 | | private void ReleaseObserverLockIfHeld() |
| | 35 | 297 | | { |
| | | 298 | | // Only release if we didn't already release for retry |
| | 35 | 299 | | if (_observerSetupLock.CurrentCount == 0) |
| | 25 | 300 | | { |
| | 25 | 301 | | _observerSetupLock.Release(); |
| | 25 | 302 | | } |
| | 35 | 303 | | } |
| | | 304 | | |
| | | 305 | | /// <summary> |
| | | 306 | | /// Attempts to create the infinite scroll observer |
| | | 307 | | /// </summary> |
| | | 308 | | /// <param name="retryCount">Current retry attempt</param> |
| | | 309 | | /// <returns>Setup result indicating success and whether retry is needed</returns> |
| | | 310 | | private async Task<ObserverSetupResult> TryCreateObserverAsync(int retryCount) |
| | 35 | 311 | | { |
| | 35 | 312 | | var result = new ObserverSetupResult(); |
| | | 313 | | |
| | | 314 | | try |
| | 35 | 315 | | { |
| | 35 | 316 | | if (!await IsIntersectionObserverSupportedAsync()) |
| | 11 | 317 | | { |
| | 11 | 318 | | return result; |
| | | 319 | | } |
| | | 320 | | |
| | 24 | 321 | | var success = await CreateObserverWithInteropAsync(); |
| | | 322 | | |
| | 23 | 323 | | HandleObserverCreationResult(success, retryCount, result); |
| | 23 | 324 | | } |
| | 1 | 325 | | catch (Exception ex) |
| | 1 | 326 | | { |
| | 1 | 327 | | Logger.LogError(ex, "Failed to initialize infinite scroll observer"); |
| | 1 | 328 | | } |
| | | 329 | | |
| | 24 | 330 | | return result; |
| | 35 | 331 | | } |
| | | 332 | | |
| | | 333 | | /// <summary> |
| | | 334 | | /// Checks if Intersection Observer API is supported |
| | | 335 | | /// </summary> |
| | | 336 | | /// <returns>True if supported, false otherwise</returns> |
| | | 337 | | private async Task<bool> IsIntersectionObserverSupportedAsync() |
| | 35 | 338 | | { |
| | 35 | 339 | | var supported = await InfiniteScrollInterop.IsSupportedAsync(); |
| | 35 | 340 | | if (!supported) |
| | 11 | 341 | | { |
| | 11 | 342 | | Logger.LogWarning("Intersection Observer API not supported"); |
| | 11 | 343 | | } |
| | 35 | 344 | | return supported; |
| | 35 | 345 | | } |
| | | 346 | | |
| | | 347 | | /// <summary> |
| | | 348 | | /// Creates the observer using interop |
| | | 349 | | /// </summary> |
| | | 350 | | /// <returns>True if creation was successful, false otherwise</returns> |
| | | 351 | | private async Task<bool> CreateObserverWithInteropAsync() |
| | 24 | 352 | | { |
| | 24 | 353 | | return await InfiniteScrollInterop.CreateObserverAsync( |
| | 24 | 354 | | Constants.UI.InfiniteScrollSentinelId, |
| | 24 | 355 | | DotNetObjectReference.Create((object)_dotNetRef!.Value), |
| | 24 | 356 | | Constants.UI.TimelineScrollContainerId, |
| | 24 | 357 | | Constants.UI.InfiniteScrollRootMargin, |
| | 24 | 358 | | Constants.UI.InfiniteScrollTimeoutMs); |
| | 23 | 359 | | } |
| | | 360 | | |
| | | 361 | | /// <summary> |
| | | 362 | | /// Handles the result of observer creation |
| | | 363 | | /// </summary> |
| | | 364 | | /// <param name="success">Whether observer creation was successful</param> |
| | | 365 | | /// <param name="retryCount">Current retry attempt</param> |
| | | 366 | | /// <param name="result">Result object to update</param> |
| | | 367 | | private void HandleObserverCreationResult(bool success, int retryCount, ObserverSetupResult result) |
| | 23 | 368 | | { |
| | 23 | 369 | | if (success) |
| | 12 | 370 | | { |
| | 12 | 371 | | _observerInitialized = true; |
| | 12 | 372 | | Logger.LogDebug("Infinite scroll observer initialized"); |
| | 12 | 373 | | } |
| | | 374 | | else |
| | 11 | 375 | | { |
| | 11 | 376 | | HandleObserverCreationFailure(retryCount, result); |
| | 11 | 377 | | } |
| | 23 | 378 | | } |
| | | 379 | | |
| | | 380 | | /// <summary> |
| | | 381 | | /// Handles failure of observer creation |
| | | 382 | | /// </summary> |
| | | 383 | | /// <param name="retryCount">Current retry attempt</param> |
| | | 384 | | /// <param name="result">Result object to update</param> |
| | | 385 | | private void HandleObserverCreationFailure(int retryCount, ObserverSetupResult result) |
| | 11 | 386 | | { |
| | 11 | 387 | | if (retryCount < 2) |
| | 10 | 388 | | { |
| | 10 | 389 | | SetupRetryParameters(retryCount, result); |
| | 10 | 390 | | Logger.LogDebug("Observer setup failed, retrying in {Delay}ms (attempt {Attempt}/3)", |
| | 10 | 391 | | result.BackoffDelay, result.NextRetryCount + 1); |
| | 10 | 392 | | } |
| | | 393 | | else |
| | 1 | 394 | | { |
| | 1 | 395 | | Logger.LogWarning("Infinite scroll observer setup failed after 3 attempts"); |
| | 1 | 396 | | } |
| | 11 | 397 | | } |
| | | 398 | | |
| | | 399 | | /// <summary> |
| | | 400 | | /// Sets up retry parameters |
| | | 401 | | /// </summary> |
| | | 402 | | /// <param name="retryCount">Current retry attempt</param> |
| | | 403 | | /// <param name="result">Result object to update</param> |
| | | 404 | | private void SetupRetryParameters(int retryCount, ObserverSetupResult result) |
| | 10 | 405 | | { |
| | 10 | 406 | | result.ShouldRetry = true; |
| | 10 | 407 | | result.NextRetryCount = retryCount + 1; |
| | 10 | 408 | | result.BackoffDelay = 100 * (retryCount + 1); |
| | 10 | 409 | | } |
| | | 410 | | |
| | | 411 | | /// <summary> |
| | | 412 | | /// Executes retry attempt with proper locking |
| | | 413 | | /// </summary> |
| | | 414 | | /// <param name="nextRetryCount">Next retry attempt number</param> |
| | | 415 | | /// <param name="backoffDelay">Delay before retry in milliseconds</param> |
| | | 416 | | private async Task ExecuteRetryAsync(int nextRetryCount, int backoffDelay) |
| | 11 | 417 | | { |
| | 11 | 418 | | await Task.Delay(backoffDelay); |
| | | 419 | | |
| | | 420 | | // Re-acquire lock for retry attempt |
| | 11 | 421 | | if (!await _observerSetupLock.WaitAsync(0)) |
| | 1 | 422 | | { |
| | 1 | 423 | | Logger.LogDebug("Observer retry skipped - another setup is already in progress"); |
| | 1 | 424 | | return; |
| | | 425 | | } |
| | | 426 | | |
| | | 427 | | try |
| | 10 | 428 | | { |
| | | 429 | | // Check again if observer is still not initialized before retrying |
| | | 430 | | // This prevents race condition where another thread initialized it during delay |
| | 10 | 431 | | if (!_observerInitialized) |
| | 10 | 432 | | { |
| | 10 | 433 | | await SetupInfiniteScrollObserverAsync(nextRetryCount); |
| | 10 | 434 | | } |
| | 10 | 435 | | } |
| | | 436 | | finally |
| | 10 | 437 | | { |
| | 10 | 438 | | _observerSetupLock.Release(); |
| | 10 | 439 | | } |
| | 11 | 440 | | } |
| | | 441 | | |
| | | 442 | | /// <summary> |
| | | 443 | | /// Result of observer setup attempt |
| | | 444 | | /// </summary> |
| | | 445 | | private class ObserverSetupResult |
| | | 446 | | { |
| | 45 | 447 | | public bool ShouldRetry { get; set; } |
| | 30 | 448 | | public int NextRetryCount { get; set; } |
| | 30 | 449 | | public int BackoffDelay { get; set; } |
| | | 450 | | } |
| | | 451 | | |
| | | 452 | | /// <summary> |
| | | 453 | | /// Callback from JavaScript when sentinel element is visible |
| | | 454 | | /// </summary> |
| | | 455 | | [JSInvokable] |
| | | 456 | | public async Task OnSentinelIntersecting() |
| | 21 | 457 | | { |
| | 21 | 458 | | if (_isDisposed || _isCallbackInProgress || _dotNetRef == null || IsLoadingMore || !HasMoreActivities) |
| | 14 | 459 | | { |
| | 14 | 460 | | return; |
| | | 461 | | } |
| | | 462 | | |
| | 7 | 463 | | _isCallbackInProgress = true; |
| | | 464 | | try |
| | 7 | 465 | | { |
| | 7 | 466 | | await LoadMoreActivitiesAsync(); |
| | 2 | 467 | | } |
| | 5 | 468 | | catch (Exception ex) |
| | 5 | 469 | | { |
| | 5 | 470 | | Logger.LogError(ex, "Failed to load more activities on sentinel intersect"); |
| | | 471 | | // Don't re-throw - JS side already handles cleanup in the catch block |
| | | 472 | | // Add delay before allowing next callback to prevent rapid retries on errors |
| | 5 | 473 | | await Task.Delay(1000); |
| | 5 | 474 | | } |
| | | 475 | | finally |
| | 7 | 476 | | { |
| | 7 | 477 | | _isCallbackInProgress = false; |
| | 7 | 478 | | } |
| | 21 | 479 | | } |
| | | 480 | | |
| | | 481 | | private void OnActivityChanged() |
| | 6 | 482 | | { |
| | 6 | 483 | | SafeTaskRunner.RunAndForget(async () => |
| | 6 | 484 | | { |
| | 6 | 485 | | await InvokeAsync(async () => |
| | 6 | 486 | | { |
| | 6 | 487 | | await LoadDataAsync(); |
| | 6 | 488 | | StateHasChanged(); |
| | 12 | 489 | | }); |
| | 12 | 490 | | }, Logger, "OnActivityChanged"); |
| | 6 | 491 | | } |
| | | 492 | | |
| | | 493 | | private async Task LoadDataAsync() |
| | 177 | 494 | | { |
| | 177 | 495 | | var today = AppState.GetCurrentDayKey(); |
| | 177 | 496 | | var selectedDate = SelectedDate.Date; |
| | | 497 | | |
| | | 498 | | // Reset pagination state when loading new date |
| | 177 | 499 | | CurrentSkip = 0; |
| | | 500 | | |
| | | 501 | | // Reset observer state when loading new date |
| | 177 | 502 | | _observerInitialized = false; |
| | | 503 | | |
| | | 504 | | // Load activities for selected date (Daily view) - initial page only using async pagination |
| | 177 | 505 | | CurrentActivities = await ActivityService.GetActivitiesPagedAsync( |
| | 177 | 506 | | selectedDate, selectedDate.AddDays(1), 0, PageSize); |
| | | 507 | | |
| | | 508 | | // Update skip to reflect loaded count |
| | 177 | 509 | | CurrentSkip = CurrentActivities.Count; |
| | | 510 | | |
| | | 511 | | // Calculate stats for selected date (use all activities for accurate stats) |
| | 177 | 512 | | var allActivitiesForDate = ActivityService.GetActivitiesForDate(selectedDate); |
| | 177 | 513 | | CurrentStats = CalculateStats(allActivitiesForDate); |
| | | 514 | | |
| | | 515 | | // Check if there are more activities to load |
| | 177 | 516 | | var totalCount = await ActivityService.GetActivityCountAsync(selectedDate, selectedDate.AddDays(1)); |
| | 177 | 517 | | HasMoreActivities = CurrentSkip < totalCount; |
| | | 518 | | |
| | | 519 | | // Log for debugging |
| | 177 | 520 | | Logger.LogDebug(Constants.Messages.LogHistoryLoadDataFormat, |
| | 177 | 521 | | selectedDate, today, selectedDate == today); |
| | 177 | 522 | | Logger.LogDebug(Constants.Messages.LogHistoryStatsFormat, |
| | 177 | 523 | | CurrentActivities.Count, CurrentStats.PomodoroCount, CurrentStats.FocusMinutes); |
| | | 524 | | |
| | | 525 | | // Use SelectedWeekStart for weekly data (independent from daily view) |
| | 177 | 526 | | var weekStart = SelectedWeekStart; |
| | 177 | 527 | | var weekEnd = weekStart.AddDays(6); // Friday |
| | | 528 | | |
| | | 529 | | // Load weekly data for chart (Saturday to Friday week) |
| | 177 | 530 | | WeeklyFocusMinutes = ActivityService.GetDailyFocusMinutes(weekStart, weekEnd); |
| | 177 | 531 | | WeeklyBreakMinutes = ActivityService.GetDailyBreakMinutes(weekStart, weekEnd); |
| | | 532 | | |
| | | 533 | | // Load weekly statistics |
| | 177 | 534 | | WeeklyStats = await ActivityService.GetWeeklyStatsAsync(weekStart); |
| | | 535 | | |
| | | 536 | | // Observer will be set up in OnAfterRenderAsync after DOM is fully updated |
| | | 537 | | // This ensures sentinel element exists before observer is created |
| | 177 | 538 | | } |
| | | 539 | | |
| | | 540 | | private DailyStatsSummary CalculateStats(List<ActivityRecord> activities) |
| | 177 | 541 | | { |
| | 177 | 542 | | return HistoryStatsService.CalculateStats(activities); |
| | 177 | 543 | | } |
| | | 544 | | |
| | | 545 | | /// <summary> |
| | | 546 | | /// Format focus time for display |
| | | 547 | | /// </summary> |
| | | 548 | | protected string FormatFocusTime(int minutes) |
| | 2 | 549 | | { |
| | 2 | 550 | | return HistoryPagePresenterService.FormatFocusTime(minutes); |
| | 2 | 551 | | } |
| | | 552 | | |
| | | 553 | | #endregion |
| | | 554 | | |
| | | 555 | | #region Event Handlers |
| | | 556 | | |
| | | 557 | | protected async Task HandleDateChanged(DateTime newDate) |
| | 10 | 558 | | { |
| | 10 | 559 | | SelectedDate = newDate; |
| | 10 | 560 | | CurrentSkip = 0; |
| | | 561 | | |
| | | 562 | | // Explicitly destroy observer before resetting state |
| | 10 | 563 | | if (_observerInitialized) |
| | 3 | 564 | | { |
| | | 565 | | try |
| | 3 | 566 | | { |
| | 3 | 567 | | await InfiniteScrollInterop.DestroyObserverAsync(Constants.UI.InfiniteScrollSentinelId); |
| | 1 | 568 | | } |
| | 2 | 569 | | catch (Exception ex) |
| | 2 | 570 | | { |
| | 2 | 571 | | Logger.LogWarning(ex, "Failed to destroy observer on date change"); |
| | 2 | 572 | | } |
| | 3 | 573 | | } |
| | | 574 | | |
| | 10 | 575 | | _observerInitialized = false; |
| | 10 | 576 | | await LoadDataAsync(); |
| | 10 | 577 | | StateHasChanged(); |
| | 10 | 578 | | } |
| | | 579 | | |
| | | 580 | | protected async Task HandleTabChanged(HistoryTab newTab) |
| | 11 | 581 | | { |
| | 11 | 582 | | ActiveTab = newTab; |
| | | 583 | | |
| | | 584 | | // Clean up observer when leaving Daily view |
| | 11 | 585 | | if (newTab != HistoryTab.Daily && _observerInitialized) |
| | 4 | 586 | | { |
| | | 587 | | try |
| | 4 | 588 | | { |
| | 4 | 589 | | await InfiniteScrollInterop.DestroyObserverAsync(Constants.UI.InfiniteScrollSentinelId); |
| | 2 | 590 | | } |
| | 2 | 591 | | catch (Exception ex) |
| | 2 | 592 | | { |
| | 2 | 593 | | Logger.LogWarning(ex, "Failed to destroy observer on tab change"); |
| | 2 | 594 | | } |
| | 4 | 595 | | _observerInitialized = false; |
| | 4 | 596 | | } |
| | | 597 | | |
| | 11 | 598 | | StateHasChanged(); |
| | 11 | 599 | | } |
| | | 600 | | |
| | | 601 | | protected async Task HandleWeekChanged(DateTime newWeekStart) |
| | 4 | 602 | | { |
| | 4 | 603 | | SelectedWeekStart = newWeekStart; |
| | 4 | 604 | | await LoadDataAsync(); |
| | 4 | 605 | | StateHasChanged(); |
| | 4 | 606 | | } |
| | | 607 | | |
| | | 608 | | /// <summary> |
| | | 609 | | /// Loads more activities with lazy loading |
| | | 610 | | /// </summary> |
| | | 611 | | protected async Task LoadMoreActivitiesAsync() |
| | 11 | 612 | | { |
| | 14 | 613 | | if (IsLoadingMore || !HasMoreActivities) return; |
| | | 614 | | |
| | | 615 | | try |
| | 8 | 616 | | { |
| | 8 | 617 | | IsLoadingMore = true; |
| | 8 | 618 | | StateHasChanged(); |
| | | 619 | | |
| | 8 | 620 | | var newActivities = await ActivityService.GetActivitiesPagedAsync( |
| | 8 | 621 | | SelectedDate, |
| | 8 | 622 | | SelectedDate.AddDays(1), |
| | 8 | 623 | | CurrentSkip, |
| | 8 | 624 | | PageSize); |
| | | 625 | | |
| | 3 | 626 | | CurrentActivities.AddRange(newActivities); |
| | 3 | 627 | | CurrentSkip += newActivities.Count; |
| | | 628 | | |
| | | 629 | | // Check if there are more activities |
| | 3 | 630 | | var totalCount = await ActivityService.GetActivityCountAsync(SelectedDate, SelectedDate.AddDays(1)); |
| | 3 | 631 | | HasMoreActivities = CurrentSkip < totalCount; |
| | | 632 | | |
| | | 633 | | // Note: Observer doesn't need re-initialization here because the sentinel element |
| | | 634 | | // remains in the DOM. As new activities are added above it, it moves further down |
| | | 635 | | // the page and will trigger again when scrolled into view. |
| | | 636 | | |
| | | 637 | | // After loading more items, the sentinel moves down the page. |
| | | 638 | | // The observer will automatically detect when it comes back into view. |
| | 3 | 639 | | } |
| | | 640 | | finally |
| | 8 | 641 | | { |
| | 8 | 642 | | IsLoadingMore = false; |
| | 8 | 643 | | StateHasChanged(); |
| | 8 | 644 | | } |
| | 6 | 645 | | } |
| | | 646 | | |
| | | 647 | | #endregion |
| | | 648 | | |
| | | 649 | | #region IAsyncDisposable |
| | | 650 | | |
| | | 651 | | public async ValueTask DisposeAsync() |
| | 175 | 652 | | { |
| | 175 | 653 | | _isDisposed = true; |
| | 175 | 654 | | _observerSetupLock?.Dispose(); |
| | | 655 | | |
| | 175 | 656 | | ActivityService.OnActivityChanged -= OnActivityChanged; |
| | | 657 | | |
| | | 658 | | // Clean up JavaScript observer |
| | 175 | 659 | | if (_dotNetRef != null) |
| | 172 | 660 | | { |
| | | 661 | | try |
| | 172 | 662 | | { |
| | 172 | 663 | | await InfiniteScrollInterop.DestroyObserverAsync(Constants.UI.InfiniteScrollSentinelId); |
| | 158 | 664 | | } |
| | 14 | 665 | | catch (Exception ex) |
| | 14 | 666 | | { |
| | 14 | 667 | | Logger.LogWarning(ex, "Failed to destroy observer by ID, attempting to destroy all"); |
| | | 668 | | try |
| | 14 | 669 | | { |
| | 14 | 670 | | await InfiniteScrollInterop.DestroyAllObserversAsync(); |
| | 8 | 671 | | } |
| | 6 | 672 | | catch (Exception fallbackEx) |
| | 6 | 673 | | { |
| | 6 | 674 | | Logger.LogWarning(fallbackEx, "Failed to destroy all observers during disposal"); |
| | 6 | 675 | | } |
| | 14 | 676 | | } |
| | | 677 | | |
| | 172 | 678 | | _dotNetRef.Dispose(); |
| | 172 | 679 | | } |
| | 175 | 680 | | } |
| | | 681 | | |
| | | 682 | | #endregion |
| | | 683 | | } |