blob: 0a55d5e2a126773ad3459fd3131843f667224db6 (
plain)
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
|
<?php
namespace Lightscale\LaralightTables;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\Attributes\Url;
use Illuminate\Pagination\Paginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;
use Exception;
abstract class TableComponent extends Component
{
use WithPagination;
// Config
protected $paginationTheme = 'bootstrap';
protected $model = null;
protected int $defaultPageSize = 10;
// Properties
#[Url]
public string $search = '';
#[Url]
public int $pageSize;
public array $activeColumns = [];
public function mount()
{
$this->setDefaultActiveColumns();
$this->setDefaultPageSize();
}
protected function setDefaultPageSize(): void
{
if (!isset($this->pageSize)) {
$this->pageSize = $this->defaultPageSize;
}
}
protected function setDefaultActiveColumns(): void
{
foreach($this->getColumns() as $column) {
$this->activeColumns[] = $column->name;
}
}
protected function isSearching(): bool
{
$search = $this->getToolbar()->getSearch();
return $search !== null && Str::length($this->search) >= $search->getMinLength();
}
public function updatedSearch(): void
{
if ($this->isSearching()) {
$this->resetPage();
}
}
protected function toolbar(): ?Toolbar
{
return null;
}
private ?Toolbar $toolbarCache;
protected function getToolbar(): ?Toolbar
{
if (!isset($this->_toolbar)) {
$this->toolbar = $this->toolbar();
}
return $this->toolbar;
}
protected function query() : Builder
{
if($this->model === null) {
throw new Exception('Requires $model to be set or query() method to be overridden');
}
return $this->model::query();
}
abstract protected function columns() : array;
protected function search(Builder $builder, string $search) : void {}
protected function buildQuery() : Builder
{
$query = $this->query();
if ($this->isSearching()) {
$this->search($query, $this->search);
}
return $query;
}
private ?Collection $columnsCache = null;
public function getColumns()
{
if($this->columnsCache === null) {
$this->columnsCache = collect($this->columns())->each(
fn($c) => $c->setTable($this)
);
}
return $this->columnsCache;
}
public function render()
{
$data = $this->buildQuery()->paginate($this->pageSize);
$allColumns = $this->getColumns();
$columns = $allColumns->filter(fn($c) => in_array($c->name,$this->activeColumns));
$toolbar = $this->toolbar();
Paginator::defaultView('laralight-tables::pagination');
return view('laralight-tables::table', compact(
'data', 'allColumns', 'columns', 'toolbar',
));
}
}
|