|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Rappasoft\LaravelLivewireTables\Traits; |
| 4 | + |
| 5 | +use Rappasoft\LaravelLivewireTables\Views\Column; |
| 6 | + |
| 7 | +/** |
| 8 | + * Trait WithColumnSelect. |
| 9 | + */ |
| 10 | +trait WithColumnSelect |
| 11 | +{ |
| 12 | + public bool $columnSelect = false; |
| 13 | + public array $columnSelectExcluded = []; |
| 14 | + public array $columnSelectEnabled = []; |
| 15 | + |
| 16 | + public function mountWithColumnSelect(): void |
| 17 | + { |
| 18 | + // If the column select is off, make sure to clear the session |
| 19 | + if (! $this->columnSelect && session()->has($this->tableName.'-columnSelectEnabled')) { |
| 20 | + session()->forget($this->tableName.'-columnSelectEnabled'); |
| 21 | + } |
| 22 | + |
| 23 | + // Get a list of visible default columns that are not excluded |
| 24 | + $columns = collect($this->columns()) |
| 25 | + ->filter(fn ($column) => $column->isVisible() && ! $this->isColumnSelectExcluded($column)) |
| 26 | + ->map(fn ($column) => $column->column()) |
| 27 | + ->values() |
| 28 | + ->toArray(); |
| 29 | + |
| 30 | + // Set to either the default set or what is stored in the session |
| 31 | + $this->columnSelectEnabled = session()->get($this->tableName.'-columnSelectEnabled', $columns); |
| 32 | + |
| 33 | + // Check to see if there are any excluded that are already stored in the enabled and remove them |
| 34 | + foreach ($this->columnSelectExcluded as $column) { |
| 35 | + if (! in_array($column, $this->columnSelectEnabled, true)) { |
| 36 | + session([$this->tableName.'-columnSelectEnabled' => $this->columnSelectEnabled[] = $column]); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + public function updatedColumnSelectEnabled(): void |
| 42 | + { |
| 43 | + session([$this->tableName.'-columnSelectEnabled' => $this->columnSelectEnabled]); |
| 44 | + } |
| 45 | + |
| 46 | + public function isColumnSelectEnabled($column): bool |
| 47 | + { |
| 48 | + return in_array($column instanceof Column ? $column->column() : $column, $this->columnSelectEnabled, true); |
| 49 | + } |
| 50 | + |
| 51 | + public function isColumnSelectExcluded($column): bool |
| 52 | + { |
| 53 | + return in_array($column instanceof Column ? $column->column() : $column, $this->columnSelectExcluded, true); |
| 54 | + } |
| 55 | +} |
0 commit comments