@rdlabo/ngx-cdk-scroll-strategies 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,378 +0,0 @@
1
- /**
2
- *
3
- * https://github.com/angular/components/blob/main/src/cdk/scrolling/fixed-size-virtual-scroll.ts
4
- */
5
-
6
- /* eslint-disable @rdlabo/rules/deny-soft-private-modifier */
7
- /* eslint-disable @angular-eslint/directive-selector */
8
- /* eslint-disable @angular-eslint/directive-class-suffix */
9
-
10
- import { coerceNumberProperty, NumberInput } from '@angular/cdk/coercion';
11
- import { Directive, forwardRef, Input, OnChanges } from '@angular/core';
12
- import { Observable, Subject } from 'rxjs';
13
- import { distinctUntilChanged } from 'rxjs/operators';
14
- import { CdkVirtualScrollViewport, VIRTUAL_SCROLL_STRATEGY, VirtualScrollStrategy } from '@angular/cdk/scrolling';
15
-
16
- /** Virtual scrolling strategy for lists with items of known fixed size. */
17
- export class DynamicSizeVirtualScrollStrategy implements VirtualScrollStrategy {
18
- private readonly _scrolledIndexChange = new Subject<number>();
19
-
20
- /** @docs-private Implemented as part of VirtualScrollStrategy. */
21
- scrolledIndexChange: Observable<number> = this._scrolledIndexChange.pipe(distinctUntilChanged());
22
-
23
- /** The attached viewport. */
24
- private _viewport: CdkVirtualScrollViewport | null = null;
25
-
26
- /** The size of the items in the virtually scrolling list. */
27
- private _itemDynamicSize: itemDynamicSize[];
28
-
29
- /** The minimum amount of buffer rendered beyond the viewport (in pixels). */
30
- private _minBufferPx: number;
31
-
32
- /** The number of buffer items to render beyond the edge of the viewport (in pixels). */
33
- private _maxBufferPx: number;
34
-
35
- /** This is added for reverse virtual scroll **/
36
- private _isReverse: boolean;
37
- measureScrollOffset: number = 0;
38
-
39
- /**
40
- * @param itemSize The size of the items in the virtually scrolling list.
41
- * @param minBufferPx The minimum amount of buffer (in pixels) before needing to render more
42
- * @param maxBufferPx The amount of buffer (in pixels) to render when rendering more.
43
- * @param isReverse Added from rdlabo for reverse
44
- */
45
- constructor(itemSize: itemDynamicSize[], minBufferPx: number, maxBufferPx: number, isReverse: boolean) {
46
- this._itemDynamicSize = itemSize;
47
- this._minBufferPx = minBufferPx;
48
- this._maxBufferPx = maxBufferPx;
49
- this._isReverse = isReverse;
50
- }
51
-
52
- /**
53
- * Attaches this scroll strategy to a viewport.
54
- * @param viewport The viewport to attach this strategy to.
55
- */
56
- attach(viewport: CdkVirtualScrollViewport) {
57
- this._viewport = viewport;
58
- this._updateTotalContentSize();
59
- this._updateRenderedRange();
60
- }
61
-
62
- /** Detaches this scroll strategy from the currently attached viewport. */
63
- detach() {
64
- this._scrolledIndexChange.complete();
65
- this._viewport = null;
66
- }
67
-
68
- /**
69
- * Update the item size and buffer size.
70
- * @param itemDynamicSize The size of the items in the virtually scrolling list.
71
- * @param minBufferPx The minimum amount of buffer (in pixels) before needing to render more
72
- * @param maxBufferPx The amount of buffer (in pixels) to render when rendering more.
73
- * @param isReverse
74
- */
75
- updateItemAndBufferSize(itemDynamicSize: itemDynamicSize[], minBufferPx: number, maxBufferPx: number, isReverse: boolean) {
76
- // if (maxBufferPx < minBufferPx && (typeof ngDevMode === 'undefined' || ngDevMode)) {
77
- if (maxBufferPx < minBufferPx) {
78
- throw Error('CDK virtual scroll: maxBufferPx must be greater than or equal to minBufferPx');
79
- }
80
- this._itemDynamicSize = itemDynamicSize;
81
- this._minBufferPx = minBufferPx;
82
- this._maxBufferPx = maxBufferPx;
83
- this._isReverse = isReverse;
84
- this._updateTotalContentSize();
85
- this._updateRenderedRange();
86
- }
87
-
88
- /** @docs-private Implemented as part of VirtualScrollStrategy. */
89
- onContentScrolled() {
90
- this._updateRenderedRange();
91
- }
92
-
93
- /** @docs-private Implemented as part of VirtualScrollStrategy. */
94
- onDataLengthChanged() {
95
- this._updateTotalContentSize();
96
- this._updateRenderedRange();
97
- }
98
-
99
- /** @docs-private Implemented as part of VirtualScrollStrategy. */
100
- onContentRendered() {
101
- /* no-op */
102
- }
103
-
104
- /** @docs-private Implemented as part of VirtualScrollStrategy. */
105
- onRenderedOffsetChanged() {
106
- /* no-op */
107
- }
108
-
109
- /**
110
- * Scroll to the offset for the given index.
111
- * @param index The index of the element to scroll to.
112
- * @param behavior The ScrollBehavior to use when scrolling.
113
- */
114
- scrollToIndex(index: number, behavior: ScrollBehavior): void {
115
- if (this._viewport) {
116
- const size = sumItemSize(this._itemDynamicSize, index);
117
- this._viewport.scrollToOffset(size, behavior);
118
- }
119
- }
120
-
121
- /** Update the viewport's total content size. */
122
- private _updateTotalContentSize() {
123
- if (!this._viewport) {
124
- return;
125
- }
126
-
127
- const size = sumItemSize(this._itemDynamicSize, this._viewport.getDataLength());
128
- this._viewport.setTotalContentSize(size);
129
- }
130
-
131
- /** Update the viewport's rendered range. */
132
- private _updateRenderedRange() {
133
- if (!this._viewport) {
134
- return;
135
- }
136
- if (this._viewport.getViewportSize() === 0) {
137
- // DOM is not ready yet. We should check again once the viewport is visible.
138
- requestAnimationFrame(() => this._viewport?.checkViewportSize());
139
- return;
140
- }
141
-
142
- const renderedRange = this._viewport.getRenderedRange();
143
- const newRange = { start: renderedRange.start, end: renderedRange.end };
144
- const viewportSize = this._viewport.getViewportSize();
145
- const dataLength = this._viewport.getDataLength();
146
-
147
- // Reverse offset if _isReverse
148
- let scrollOffset = !this._isReverse
149
- ? this._viewport.measureScrollOffset()
150
- : Math.max(0, this._viewport.getElementRef().nativeElement.scrollTop * -1);
151
-
152
- // let firstVisibleIndex = this._itemDynamicSize > 0 ? scrollOffset / this._itemDynamicSize : 0;
153
- let firstVisibleIndex = this._itemDynamicSize.length > 0 ? Math.floor(calcIndex(this._itemDynamicSize, scrollOffset)) : 0;
154
-
155
- // If user scrolls to the bottom of the list and data changes to a smaller list
156
- if (newRange.end > dataLength) {
157
- // We have to recalculate the first visible index based on new data length and viewport size.
158
- const maxVisibleItems = Math.ceil(calcIndex(this._itemDynamicSize, viewportSize));
159
- const newVisibleIndex = Math.max(0, Math.min(firstVisibleIndex, dataLength - maxVisibleItems));
160
-
161
- // If first visible index changed we must update scroll offset to handle start/end buffers
162
- // Current range must also be adjusted to cover the new position (bottom of new list).
163
- if (firstVisibleIndex != newVisibleIndex) {
164
- firstVisibleIndex = newVisibleIndex;
165
- // scrollOffset = newVisibleIndex * this._itemDynamicSize;
166
- scrollOffset = sumItemSize(this._itemDynamicSize, newVisibleIndex);
167
- newRange.start = Math.floor(firstVisibleIndex);
168
- }
169
-
170
- newRange.end = Math.max(0, Math.min(dataLength, newRange.start + maxVisibleItems));
171
- }
172
-
173
- // const startBuffer = scrollOffset - newRange.start * this._itemDynamicSize;
174
- const startBuffer = scrollOffset - sumItemSize(this._itemDynamicSize, newRange.start);
175
- if (startBuffer < this._minBufferPx && newRange.start != 0) {
176
- // const expandStart = Math.ceil((this._maxBufferPx - startBuffer) / this._itemDynamicSize);
177
- const expandStart = Math.ceil(calcIndex(this._itemDynamicSize, this._maxBufferPx - startBuffer, newRange.start, true));
178
- newRange.start = Math.max(0, newRange.start - expandStart);
179
- // newRange.end = Math.min(dataLength, Math.ceil(firstVisibleIndex + (viewportSize + this._minBufferPx) / this._itemDynamicSize));
180
- newRange.end = Math.min(
181
- dataLength,
182
- Math.ceil(firstVisibleIndex + calcIndex(this._itemDynamicSize, viewportSize + this._minBufferPx, firstVisibleIndex)) + 1, // firstVisibleIndexを削った影響
183
- );
184
-
185
- // console.log(
186
- // 'expandStart',
187
- // firstVisibleIndex,
188
- // '"' + newRange.start + '-' + newRange.end + '"',
189
- // dataLength,
190
- // viewportSize + this._minBufferPx,
191
- // Math.ceil(firstVisibleIndex + calcIndex(this._itemDynamicSize, viewportSize + this._minBufferPx, firstVisibleIndex)),
192
- // );
193
- } else {
194
- // const endBuffer = newRange.end * this._itemSize - (scrollOffset + viewportSize);
195
- const endBuffer = Math.max(sumItemSize(this._itemDynamicSize, newRange.end) - (scrollOffset + viewportSize), 0);
196
- if (endBuffer < this._minBufferPx && newRange.end != dataLength) {
197
- // const expandEnd = Math.ceil((this._maxBufferPx - endBuffer) / this._itemDynamicSize);
198
- const expandEnd =
199
- endBuffer === 0 && newRange.start < newRange.end && dataLength - 1 > newRange.end
200
- ? // When endBuffer is 0, but not the last item:
201
- dataLength - newRange.end
202
- : Math.ceil(calcIndex(this._itemDynamicSize, this._maxBufferPx - endBuffer, newRange.end));
203
-
204
- if (expandEnd > 0) {
205
- newRange.end = Math.min(dataLength, newRange.end + expandEnd);
206
- // Math.floor(firstVisibleIndex - this._minBufferPx / this._itemSize),
207
- newRange.start = Math.max(
208
- 0,
209
- Math.floor(firstVisibleIndex - calcIndex(this._itemDynamicSize, this._minBufferPx, firstVisibleIndex, true)),
210
- );
211
- // console.log(
212
- // 'expandEnd',
213
- // firstVisibleIndex,
214
- // '"' + newRange.start + '-' + newRange.end + '"',
215
- // dataLength,
216
- // Math.ceil(firstVisibleIndex + calcIndex(this._itemDynamicSize, viewportSize + this._minBufferPx, firstVisibleIndex)),
217
- // );
218
- }
219
- }
220
- }
221
-
222
- if (newRange.start === 0 && newRange.end === 0 && dataLength > 0) {
223
- // have items but not rendered, set start index to 0
224
- newRange.end = dataLength;
225
- }
226
-
227
- if (firstVisibleIndex === 0 && newRange.start > firstVisibleIndex) {
228
- // This is bug fix. If newRange.start > firstVisibleIndex, can't visible '0'
229
- newRange.start = firstVisibleIndex;
230
- }
231
-
232
- if (newRange.start > newRange.end) {
233
- // This is bug fix. If newRange.start > newRange.end, it will cause infinite loop.
234
- newRange.end = Math.min(
235
- dataLength,
236
- Math.ceil(newRange.start + calcIndex(this._itemDynamicSize, viewportSize + this._minBufferPx, newRange.start)),
237
- );
238
- }
239
-
240
- this._viewport.setRenderedRange(newRange);
241
- // this._viewport.setRenderedContentOffset(this._itemDynamicSize * newRange.start);
242
- if (!this._isReverse) {
243
- this._viewport.setRenderedContentOffset(sumItemSize(this._itemDynamicSize, newRange.start));
244
- } else {
245
- let offset = Math.min(0, sumItemSize(this._itemDynamicSize, newRange.start) * -1);
246
- if (offset === 0) {
247
- offset = 0;
248
- }
249
- this._viewport.setRenderedContentOffset(offset);
250
- }
251
- this.measureScrollOffset = scrollOffset;
252
- this._scrolledIndexChange.next(firstVisibleIndex);
253
- }
254
- }
255
-
256
- /**
257
- * Provider factory for `FixedSizeVirtualScrollStrategy` that simply extracts the already created
258
- * `FixedSizeVirtualScrollStrategy` from the given directive.
259
- * @param fixedSizeDir The instance of `CdkFixedSizeVirtualScroll` to extract the
260
- * `FixedSizeVirtualScrollStrategy` from.
261
- */
262
- export function _dynamicSizeVirtualScrollStrategyFactory(fixedSizeDir: CdkDynamicSizeVirtualScroll) {
263
- return fixedSizeDir._scrollStrategy;
264
- }
265
-
266
- export type itemDynamicSize = { itemSize: number } & Record<string, string | number>;
267
-
268
- export const sumItemSize = (dynamicSize: itemDynamicSize[], endIndex: number): number => {
269
- return dynamicSize.slice(0, endIndex).reduce((acc, item) => acc + item.itemSize, 0);
270
- };
271
-
272
- /**
273
- * TODO: 計算方法の見直し
274
- * 0.5 = 0個目の半分はマイナスの計算が生まれるため、1個目からカウント
275
- */
276
- export const calcIndex = (dynamicSize: itemDynamicSize[], itemSizeRange: number, startIndex = 0, isReverse = false): number => {
277
- let sum = 0;
278
- let diffIndex = 0;
279
- const item = isReverse ? structuredClone(dynamicSize).reverse() : dynamicSize;
280
- if (isReverse) {
281
- startIndex = dynamicSize.length - startIndex;
282
- }
283
- const calcIndex = item.reduce((acc, currentValue, index) => {
284
- if (index < startIndex) {
285
- return acc;
286
- }
287
- if (acc !== -1) {
288
- // 既に見つかった場合、何もしない
289
- return acc;
290
- }
291
- sum += currentValue.itemSize;
292
- if (sum >= itemSizeRange) {
293
- if (sum === itemSizeRange) {
294
- return index - startIndex;
295
- }
296
-
297
- const diff = sum - itemSizeRange;
298
- const getOver = item[index].itemSize - diff;
299
- diffIndex = getOver / item[index].itemSize;
300
- return Math.max(0, index - 1 + diffIndex - startIndex);
301
- } else if (index === item.length - 1) {
302
- return index - startIndex;
303
- }
304
- return acc;
305
- }, -1);
306
- return calcIndex === -1 ? 0 : calcIndex;
307
- };
308
-
309
- /** A virtual scroll strategy that supports fixed-size items. */
310
- @Directive({
311
- selector: 'cdk-virtual-scroll-viewport[itemDynamicSizes]',
312
- standalone: true,
313
- providers: [
314
- {
315
- provide: VIRTUAL_SCROLL_STRATEGY,
316
- useFactory: _dynamicSizeVirtualScrollStrategyFactory,
317
- deps: [forwardRef(() => CdkDynamicSizeVirtualScroll)],
318
- },
319
- ],
320
- })
321
- export class CdkDynamicSizeVirtualScroll implements OnChanges {
322
- /** The size of the items in the list (in pixels). */
323
- @Input()
324
- get itemDynamicSizes(): itemDynamicSize[] {
325
- return this._itemDynamicSizes;
326
- }
327
- set itemDynamicSizes(value: itemDynamicSize[]) {
328
- // coerceNumberProperty
329
- this._itemDynamicSizes = value;
330
- }
331
- _itemDynamicSizes: itemDynamicSize[] = [];
332
-
333
- /**
334
- * The minimum amount of buffer rendered beyond the viewport (in pixels).
335
- * If the amount of buffer dips below this number, more items will be rendered. Defaults to 100px.
336
- */
337
- @Input()
338
- get minBufferPx(): number {
339
- return this._minBufferPx;
340
- }
341
- set minBufferPx(value: NumberInput) {
342
- this._minBufferPx = coerceNumberProperty(value);
343
- }
344
- _minBufferPx = 100;
345
-
346
- /**
347
- * The number of pixels worth of buffer to render for when rendering new items. Defaults to 200px.
348
- */
349
- @Input()
350
- get maxBufferPx(): number {
351
- return this._maxBufferPx;
352
- }
353
- set maxBufferPx(value: NumberInput) {
354
- this._maxBufferPx = coerceNumberProperty(value);
355
- }
356
- _maxBufferPx = 200;
357
-
358
- @Input()
359
- get isReverse(): boolean {
360
- return this._isReverse;
361
- }
362
- set isReverse(value: boolean) {
363
- this._isReverse = value;
364
- }
365
- _isReverse = false;
366
-
367
- /** The scroll strategy used by this directive. */
368
- _scrollStrategy = new DynamicSizeVirtualScrollStrategy(this.itemDynamicSizes, this.minBufferPx, this.maxBufferPx, this.isReverse);
369
-
370
- ngOnChanges() {
371
- this._scrollStrategy.updateItemAndBufferSize(this.itemDynamicSizes, this.minBufferPx, this.maxBufferPx, this.isReverse);
372
- }
373
-
374
- /** For isReverse scroll. Because virtualScroll.measureScrollOffset is not work. **/
375
- get scrollOffset(): number {
376
- return this._scrollStrategy.measureScrollOffset;
377
- }
378
- }
@@ -1,16 +0,0 @@
1
- import { TestBed } from '@angular/core/testing';
2
-
3
- import { DynamicSizeVirtualScrollService } from './dynamic-size-virtual-scroll.service';
4
-
5
- describe('DynamicSizeVirtualScrollService', () => {
6
- let service: DynamicSizeVirtualScrollService;
7
-
8
- beforeEach(() => {
9
- TestBed.configureTestingModule({});
10
- service = TestBed.inject(DynamicSizeVirtualScrollService);
11
- });
12
-
13
- it('should be created', () => {
14
- expect(service).toBeTruthy();
15
- });
16
- });
@@ -1,98 +0,0 @@
1
- import { computed, Injectable, Signal } from '@angular/core';
2
- import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
3
- import { itemDynamicSize } from './dynamic-size-virtual-scroll-strategy';
4
-
5
- @Injectable({
6
- providedIn: 'root',
7
- })
8
- export class DynamicSizeVirtualScrollService {
9
- readonly mergeScrollY = 160;
10
-
11
- constructor() {}
12
-
13
- onInit(virtualScroll: CdkVirtualScrollViewport, latestScrollOffset: number) {
14
- if (latestScrollOffset > 0) {
15
- virtualScroll.scrollToOffset(latestScrollOffset);
16
- }
17
- }
18
-
19
- onDestroy(virtualScroll: CdkVirtualScrollViewport): number {
20
- return virtualScroll.measureScrollOffset('top');
21
- }
22
-
23
- getBindDynamicItemHeight($calcDynamicItemSize: Signal<itemDynamicSize[]>): Signal<string[]> {
24
- return computed<string[]>(() => {
25
- return $calcDynamicItemSize().map((item) => {
26
- return item['source'] === 'temporary' ? 'auto' : item.itemSize + 'px';
27
- });
28
- });
29
- }
30
-
31
- async scrollToTopSmooth(virtualScroll: CdkVirtualScrollViewport): Promise<void> {
32
- await this.scrollToPoint(virtualScroll, 0, 0, 400);
33
- }
34
-
35
- isEnableMerge(virtualScroll: CdkVirtualScrollViewport): boolean {
36
- return virtualScroll.getRenderedRange().start === 0 && virtualScroll.measureScrollOffset('top') < this.mergeScrollY;
37
- }
38
-
39
- refreshViewport(virtualScroll: CdkVirtualScrollViewport): void {
40
- virtualScroll.scrollToOffset(0);
41
- virtualScroll.setRenderedContentOffset(0);
42
- virtualScroll.setRenderedRange({ start: 0, end: 0 });
43
- }
44
-
45
- // https://github.com/ionic-team/ionic-framework/blob/main/core/src/components/content/content.tsx#L357C3-L404C4
46
- async scrollToPoint(
47
- el: CdkVirtualScrollViewport,
48
- x: number | undefined | null,
49
- y: number | undefined | null,
50
- duration = 0,
51
- ): Promise<void> {
52
- if (duration < 32) {
53
- if (y != null) {
54
- el.scrollToOffset(y);
55
- }
56
- if (x != null) {
57
- el.scrollToOffset(x);
58
- }
59
- return;
60
- }
61
-
62
- let resolve!: () => void;
63
- let startTime = 0;
64
- const promise = new Promise<void>((r) => (resolve = r));
65
- const fromY = el.measureScrollOffset('top');
66
- const fromX = el.measureScrollOffset('left');
67
-
68
- const deltaY = y != null ? y - fromY : 0;
69
- const deltaX = x != null ? x - fromX : 0;
70
-
71
- // scroll loop
72
- const step = (timeStamp: number) => {
73
- const linearTime = Math.min(1, (timeStamp - startTime) / duration) - 1;
74
- const easedT = Math.pow(linearTime, 3) + 1;
75
-
76
- if (deltaY !== 0) {
77
- el.scrollToOffset(Math.floor(easedT * deltaY + fromY));
78
- }
79
- if (deltaX !== 0) {
80
- el.scrollToOffset(Math.floor(easedT * deltaX + fromX));
81
- }
82
-
83
- if (easedT < 1) {
84
- // do not use DomController here
85
- // must use nativeRaf in order to fire in the next frame
86
- requestAnimationFrame(step);
87
- } else {
88
- resolve();
89
- }
90
- };
91
- // chill out for a frame first
92
- requestAnimationFrame((ts) => {
93
- startTime = ts;
94
- step(ts);
95
- });
96
- return promise;
97
- }
98
- }
package/tsconfig.lib.json DELETED
@@ -1,14 +0,0 @@
1
- /* To learn more about this file see: https://angular.io/config/tsconfig. */
2
- {
3
- "extends": "../../tsconfig.json",
4
- "compilerOptions": {
5
- "outDir": "../../out-tsc/lib",
6
- "declaration": true,
7
- "declarationMap": true,
8
- "inlineSources": true,
9
- "types": []
10
- },
11
- "exclude": [
12
- "**/*.spec.ts"
13
- ]
14
- }
@@ -1,10 +0,0 @@
1
- /* To learn more about this file see: https://angular.io/config/tsconfig. */
2
- {
3
- "extends": "./tsconfig.lib.json",
4
- "compilerOptions": {
5
- "declarationMap": false
6
- },
7
- "angularCompilerOptions": {
8
- "compilationMode": "partial"
9
- }
10
- }
@@ -1,14 +0,0 @@
1
- /* To learn more about this file see: https://angular.io/config/tsconfig. */
2
- {
3
- "extends": "../../tsconfig.json",
4
- "compilerOptions": {
5
- "outDir": "../../out-tsc/spec",
6
- "types": [
7
- "jasmine"
8
- ]
9
- },
10
- "include": [
11
- "**/*.spec.ts",
12
- "**/*.d.ts"
13
- ]
14
- }