Skip to content

Commit d684e67

Browse files
authored
Only fill current page items
1 parent 67c623f commit d684e67

File tree

1 file changed

+30
-13
lines changed

1 file changed

+30
-13
lines changed

src/Layout/Concerns/WithScroll.php

+30-13
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,7 @@ public function bootWithScroll(): void
2626
public function mountWithScroll(): void
2727
{
2828
if ($this->items->isEmpty()) {
29-
// Make sure to be back on the first page
30-
$this->clear();
31-
32-
// Fetch the first page
33-
$this->fetch();
29+
$this->fillPageItems();
3430
}
3531
}
3632

@@ -53,7 +49,7 @@ public function fetch(): void
5349

5450
$this->nextPage();
5551

56-
$this->fillPageItems();
52+
$this->fillCurrentPageItems();
5753
}
5854

5955
public function clear(): void
@@ -82,17 +78,33 @@ public function onLastPage(): bool
8278

8379
protected function fillPageItems(): void
8480
{
85-
$range = range(1, $this->getScrollLimit());
81+
$range = range(1, $this->getPageFillLimit());
8682

8783
foreach ($range as $page) {
8884
$items = $this->getPageItems($page);
8985

90-
if ($items->isNotEmpty()) {
91-
$this->models = $this->models->merge($items->all())->unique('id');
86+
$this->mergePageItems($items);
87+
88+
Sleep::for(100)->milliseconds();
89+
}
90+
}
91+
92+
protected function fillCurrentPageItems(): void
93+
{
94+
$items = $this->getPageItems();
95+
96+
$this->mergePageItems($items);
97+
}
9298

93-
Sleep::for(100)->milliseconds();
94-
}
99+
protected function mergePageItems(Paginator|Collection $items): void
100+
{
101+
if ($items->isEmpty()) {
102+
return;
95103
}
104+
105+
$this->models = $this->models
106+
->merge($items->filter()->all())
107+
->unique($this->getPageItemKey());
96108
}
97109

98110
protected function getPageItems(?int $page = null): Paginator|LengthAwarePaginator
@@ -101,13 +113,18 @@ protected function getPageItems(?int $page = null): Paginator|LengthAwarePaginat
101113

102114
return $this
103115
->getQuery()
104-
->simplePaginate(perPage: 12, page: $page);
116+
->simplePaginate(perPage: 16, page: $page);
105117
}
106118

107-
protected function getScrollLimit(?int $page = null): int
119+
protected function getPageFillLimit(?int $page = null): int
108120
{
109121
$page ??= $this->getPage() ?? 1;
110122

111123
return Number::clamp($page, min: 1, max: 12);
112124
}
125+
126+
protected function getPageItemKey(): ?string
127+
{
128+
return 'id';
129+
}
113130
}

0 commit comments

Comments
 (0)