-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVirtualizeExt.cs
More file actions
480 lines (386 loc) · 17.5 KB
/
VirtualizeExt.cs
File metadata and controls
480 lines (386 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.Web.Virtualization;
using Microsoft.JSInterop;
using Prius.Core;
// ReSharper disable StaticMemberInGenericType
namespace Ecm.Common.Web.Controls
{
/// <summary>
/// Provides functionality for rendering a virtualized list of items.
/// </summary>
/// <typeparam name="TItem">The <c>context</c> type for the items being rendered.</typeparam>
public sealed class VirtualizeExt<TItem> : ComponentBase, IVirtualizeExt, IVirtualizeExtJsCallbacks, IAsyncDisposable
{
private VirtualizeExtJsInterop _jsInterop;
private ElementReference _spacerBefore;
private ElementReference _spacerAfter;
private int _itemsBefore;
private int _visibleItemCapacity;
private int _itemCount;
private int _loadedItemsStartIndex;
private int _lastRenderedItemCount;
private int _lastRenderedPlaceholderCount;
private float _itemSize;
private IEnumerable<TItem> _loadedItems;
private CancellationTokenSource _refreshCts;
private Exception _refreshException;
private ItemsProviderDelegate<TItem> _itemsProvider = default!;
private RenderFragment<TItem> _itemTemplate;
private RenderFragment<PlaceholderContext> _placeholder;
[Inject]
private IJSRuntime JsRuntime { get; set; } = default!;
/// <summary>
/// Gets or sets the item template for the list.
/// </summary>
[Parameter]
public RenderFragment<TItem> ChildContent { get; set; }
/// <summary>
/// Gets or sets the item template for the list.
/// </summary>
[Parameter]
public RenderFragment<TItem> ItemContent { get; set; }
/// <summary>
/// Gets or sets the template for items that have not yet been loaded in memory.
/// </summary>
[Parameter]
public RenderFragment<PlaceholderContext> Placeholder { get; set; }
/// <summary>
/// Gets the size of each item in pixels. Defaults to 50px.
/// </summary>
[Parameter]
public float ItemSize { get; set; } = 50f;
/// <summary>
/// Gets or sets the function providing items to the list.
/// </summary>
[Parameter]
public ItemsProviderDelegate<TItem> ItemsProvider { get; set; }
/// <summary>
/// Gets or sets the fixed item source.
/// </summary>
[Parameter]
public ICollection<TItem> Items { get; set; }
/// <summary>
/// Gets or sets a value that determines how many additional items will be rendered
/// before and after the visible region. This help to reduce the frequency of rendering
/// during scrolling. However, higher values mean that more elements will be present
/// in the page.
/// </summary>
[Parameter]
public int OverscanCount { get; set; } = 3;
[Parameter]
public string Id { get; set; }
/// <summary>
/// Instructs the component to re-request data from its <see cref="ItemsProvider"/>.
/// This is useful if external data may have changed. There is no need to call this
/// when using <see cref="Items"/>.
/// </summary>
/// <returns>A <see cref="Task"/> representing the completion of the operation.</returns>
public async Task RefreshDataAsync()
{
// We don't auto-render after this operation because in the typical use case, the
// host component calls this from one of its lifecycle methods, and will naturally
// re-render afterwards anyway. It's not desirable to re-render twice.
await RefreshDataCoreAsync(renderOnSuccess: false);
}
/// <inheritdoc />
protected override void OnParametersSet()
{
if (ItemSize <= 0)
{
throw new InvalidOperationException(
$"{GetType()} requires a positive value for parameter '{nameof(ItemSize)}'.");
}
if (_itemSize <= 0)
{
_itemSize = ItemSize;
}
if (ItemsProvider != null)
{
if (Items != null)
{
throw new InvalidOperationException(
$"{GetType()} can only accept one item source from its parameters. " +
$"Do not supply both '{nameof(Items)}' and '{nameof(ItemsProvider)}'.");
}
_itemsProvider = ItemsProvider;
}
else if (Items != null)
{
_itemsProvider = DefaultItemsProvider;
// When we have a fixed set of in-memory data, it doesn't cost anything to
// re-query it on each cycle, so do that. This means the developer can add/remove
// items in the collection and see the UI update without having to call RefreshDataAsync.
var refreshTask = RefreshDataCoreAsync(renderOnSuccess: false);
// We know it's synchronous and has its own error handling
Debug.Assert(refreshTask.IsCompletedSuccessfully);
}
else
{
throw new InvalidOperationException(
$"{GetType()} requires either the '{nameof(Items)}' or '{nameof(ItemsProvider)}' parameters to be specified " +
$"and non-null.");
}
_itemTemplate = ItemContent ?? ChildContent;
_placeholder = Placeholder ?? DefaultPlaceholder;
}
private bool _loadScroll;
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
_jsInterop = new VirtualizeExtJsInterop(this, JsRuntime);
await _jsInterop.InitializeAsync(_spacerBefore, _spacerAfter);
}
if (_loadedItems == null || Id.IsNullOrWhiteSpace())
return;
if (!_loadScroll)
{
await SaveScroll();
return;
}
_loadScroll = false;
if (!SavedScrolls.ContainsKey(Id))
return;
var savedScroll = SavedScrolls.ValueOrDefault(Id);
var scroll = await GetCurrentScroll();
if (scroll == savedScroll)
return;
await JsRuntime.InvokeVoidAsync("setScroll", Id, savedScroll);
}
public async Task SaveScroll()
{
if (_loadedItems == null || Id.IsNullOrWhiteSpace())
return;
SavedScrolls[Id] = await GetCurrentScroll();
}
private async Task<decimal> GetCurrentScroll()
{
return await JsRuntime.InvokeAsync<decimal>("getScroll", Id);
}
/// <inheritdoc />
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
if (_refreshException != null)
{
var oldRefreshException = _refreshException;
_refreshException = null;
throw oldRefreshException;
}
builder.OpenElement(0, "div");
builder.AddAttribute(1, "style", GetSpacerStyle(_itemsBefore));
builder.AddElementReferenceCapture(2, elementReference => _spacerBefore = elementReference);
builder.CloseElement();
var lastItemIndex = Math.Min(_itemsBefore + _visibleItemCapacity, _itemCount);
var renderIndex = _itemsBefore;
var placeholdersBeforeCount = Math.Min(_loadedItemsStartIndex, lastItemIndex);
builder.OpenRegion(3);
// Render placeholders before the loaded items.
for (; renderIndex < placeholdersBeforeCount; renderIndex++)
{
// This is a rare case where it's valid for the sequence number to be programmatically incremented.
// This is only true because we know for certain that no other content will be alongside it.
builder.AddContent(renderIndex, _placeholder, new PlaceholderContext(renderIndex, _itemSize));
}
builder.CloseRegion();
_lastRenderedItemCount = 0;
// Render the loaded items.
if (_loadedItems != null && _itemTemplate != null)
{
var itemsToShow = _loadedItems
.Skip(_itemsBefore - _loadedItemsStartIndex)
.Take(lastItemIndex - _loadedItemsStartIndex);
builder.OpenRegion(4);
foreach (var item in itemsToShow)
{
_itemTemplate(item)(builder);
_lastRenderedItemCount++;
}
renderIndex += _lastRenderedItemCount;
builder.CloseRegion();
}
_lastRenderedPlaceholderCount = Math.Max(0, lastItemIndex - _itemsBefore - _lastRenderedItemCount);
builder.OpenRegion(5);
// Render the placeholders after the loaded items.
for (; renderIndex < lastItemIndex; renderIndex++)
{
builder.AddContent(renderIndex, _placeholder, new PlaceholderContext(renderIndex, _itemSize));
}
builder.CloseRegion();
var itemsAfter = Math.Max(0, _itemCount - _visibleItemCapacity - _itemsBefore);
builder.OpenElement(6, "div");
builder.AddAttribute(7, "style", GetSpacerStyle(itemsAfter));
builder.AddElementReferenceCapture(8, elementReference => _spacerAfter = elementReference);
builder.CloseElement();
}
private string GetSpacerStyle(int itemsInSpacer)
=> $"height: {(itemsInSpacer * _itemSize).ToString(CultureInfo.InvariantCulture)}px;";
void IVirtualizeExtJsCallbacks.OnBeforeSpacerVisible(float spacerSize, float spacerSeparation, float containerSize)
{
CalcualteItemDistribution(spacerSize, spacerSeparation, containerSize, out var itemsBefore, out var visibleItemCapacity);
// Since we know the before spacer is now visible, we absolutely have to slide the window up
// by at least one element. If we're not doing that, the previous item size info we had must
// have been wrong, so just move along by one in that case to trigger an update and apply the
// new size info.
if (itemsBefore == _itemsBefore && itemsBefore > 0)
{
itemsBefore--;
}
UpdateItemDistribution(itemsBefore, visibleItemCapacity);
}
void IVirtualizeExtJsCallbacks.OnAfterSpacerVisible(float spacerSize, float spacerSeparation, float containerSize)
{
CalcualteItemDistribution(spacerSize, spacerSeparation, containerSize, out var itemsAfter, out var visibleItemCapacity);
var itemsBefore = Math.Max(0, _itemCount - itemsAfter - visibleItemCapacity);
// Since we know the after spacer is now visible, we absolutely have to slide the window down
// by at least one element. If we're not doing that, the previous item size info we had must
// have been wrong, so just move along by one in that case to trigger an update and apply the
// new size info.
if (itemsBefore == _itemsBefore && itemsBefore < _itemCount - visibleItemCapacity)
{
itemsBefore++;
}
UpdateItemDistribution(itemsBefore, visibleItemCapacity);
}
private void CalcualteItemDistribution(
float spacerSize,
float spacerSeparation,
float containerSize,
out int itemsInSpacer,
out int visibleItemCapacity)
{
if (_lastRenderedItemCount > 0)
{
_itemSize = (spacerSeparation - (_lastRenderedPlaceholderCount * _itemSize)) / _lastRenderedItemCount;
}
if (_itemSize <= 0)
{
// At this point, something unusual has occurred, likely due to misuse of this component.
// Reset the calculated item size to the user-provided item size.
_itemSize = ItemSize;
}
itemsInSpacer = Math.Max(0, (int)Math.Floor(spacerSize / _itemSize) - OverscanCount);
visibleItemCapacity = (int)Math.Ceiling(containerSize / _itemSize) + 2 * OverscanCount;
}
private void UpdateItemDistribution(int itemsBefore, int visibleItemCapacity)
{
// If the itemcount just changed to a lower number, and we're already scrolled past the end of the new
// reduced set of items, clamp the scroll position to the new maximum
if (itemsBefore + visibleItemCapacity > _itemCount)
{
itemsBefore = Math.Max(0, _itemCount - visibleItemCapacity);
}
// If anything about the offset changed, re-render
if (itemsBefore != _itemsBefore || visibleItemCapacity != _visibleItemCapacity)
{
_itemsBefore = itemsBefore;
_visibleItemCapacity = visibleItemCapacity;
var refreshTask = RefreshDataCoreAsync(renderOnSuccess: true);
if (!refreshTask.IsCompleted)
{
StateHasChanged();
}
}
}
private async ValueTask RefreshDataCoreAsync(bool renderOnSuccess)
{
_refreshCts?.Cancel();
CancellationToken cancellationToken;
if (_itemsProvider == DefaultItemsProvider)
{
// If we're using the DefaultItemsProvider (because the developer supplied a fixed
// Items collection) we know it will complete synchronously, and there's no point
// instantiating a new CancellationTokenSource
_refreshCts = null;
cancellationToken = CancellationToken.None;
}
else
{
_refreshCts = new CancellationTokenSource();
cancellationToken = _refreshCts.Token;
}
var start = _itemsBefore;
if (!Id.IsNullOrWhiteSpace())
{
if (SavedItemsBefore.ContainsKey(Id))
{
start = SavedItemsBefore.ValueOrDefault(Id);
_loadScroll = true;
}
SavedItemsBefore.Remove(Id);
}
var request = new ItemsProviderRequest(start, _visibleItemCapacity, cancellationToken);
try
{
var result = await _itemsProvider(request);
// Only apply result if the task was not canceled.
if (!cancellationToken.IsCancellationRequested)
{
if (result.TotalItemCount > 0 && request.StartIndex >= result.TotalItemCount)
{
if (!Id.IsNullOrWhiteSpace())
{
SavedItemsBefore[Id] = Math.Max(0, result.TotalItemCount - _visibleItemCapacity);
await RefreshDataCoreAsync(renderOnSuccess);
}
return;
}
_itemCount = result.TotalItemCount;
_loadedItems = result.Items;
_loadedItemsStartIndex = request.StartIndex;
if (renderOnSuccess)
{
StateHasChanged();
}
}
}
catch (Exception e)
{
if (e is OperationCanceledException oce && oce.CancellationToken == cancellationToken)
{
// No-op; we canceled the operation, so it's fine to suppress this exception.
}
else
{
// Cache this exception so the renderer can throw it.
_refreshException = e;
// Re-render the component to throw the exception.
StateHasChanged();
}
}
}
private ValueTask<ItemsProviderResult<TItem>> DefaultItemsProvider(ItemsProviderRequest request)
{
return ValueTask.FromResult(new ItemsProviderResult<TItem>(
Items!.Skip(request.StartIndex).Take(request.Count),
Items!.Count));
}
private RenderFragment DefaultPlaceholder(PlaceholderContext context) => (builder) =>
{
builder.OpenElement(0, "div");
builder.AddAttribute(1, "style", $"height: {_itemSize.ToString(CultureInfo.InvariantCulture)}px;");
builder.CloseElement();
};
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
_refreshCts?.Cancel();
if (_jsInterop != null)
{
await _jsInterop.DisposeAsync();
}
if (!Id.IsNullOrWhiteSpace())
SavedItemsBefore[Id] = _itemsBefore;
}
private static readonly Dictionary<string, int> SavedItemsBefore = new();
private static readonly Dictionary<string, decimal> SavedScrolls = new();
}
}