Skip to content

Commit

Permalink
Add hide table option (#1914)
Browse files Browse the repository at this point in the history
* Initial Commit

* Fix styling

* Further adjustments

* Fix styling

* Improve Tests - Extend PetsTable

* Fix styling

---------

Co-authored-by: lrljoe <[email protected]>
  • Loading branch information
lrljoe and lrljoe authored Sep 1, 2024
1 parent 570abdc commit 1f076af
Show file tree
Hide file tree
Showing 17 changed files with 250 additions and 293 deletions.
78 changes: 78 additions & 0 deletions docs/misc/hiding-the-table.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
---
title: Hiding The Table (beta)
weight: 8
---

You may wish to hide the table on load. To do so, you should use the following in the mount method. Note that this is in mount, not boot nor configure!

```php
public function mount()
{
$this->setShouldBeHidden();
}
```

### Using Events To Display/Hide

For example, you may have a "Sales" table that you wish to hide by default:
```php
class SalesTable extends DataTableComponent
{
public string $tableName = 'sales'; // Required to keep the call specific

public function mount()
{
$this->setShouldBeHidden(); // Defaults the table to be hidden, note that this is in MOUNT and not CONFIGURE
}

// Configure/Columns/Filters etc
}
```

The Table allows for different approaches, out-of-the-box it supports the more efficient client-side listeners.

However - should you wish to use Livewire listeners in your table component, for example if you wish to pass more detail into the Table then you can:

```php
#[On('showTable.{tableName}')]
public function showTable(): void
{
$this->setShouldBeDisplayed();
}

#[On('hideTable.{tableName}')]
public function hideTable(): void
{
$this->setShouldBeHidden();
}
```


### Secondary Table
Below are the two approaches. Note that you can customise the Livewire "On" to pass additional details should you wish.

#### Using Client Side Listeners
```php
Column::make('Show')
->label(
fn($row, Column $column) => "<button x-on:click=\"\$dispatch('show-table',{'tableName': 'sales' })\">Show Sales Table</button>"
)->html(),
Column::make('Hide')
->label(
fn($row, Column $column) => "<button x-on:click=\"\$dispatch('hide-table',{'tableName': 'sales' })\">Hide Sales Table</button>"
)->html(),
```


#### Using Livewire "On" Style Listeners:
```php
Column::make('Show')
->label(
fn($row, Column $column) => "<button x-on:click=\"\$dispatch('showTable.sales')\">Show Sales Table</button>"
)->html(),
Column::make('Hide')
->label(
fn($row, Column $column) => "<button x-on:click=\"\$dispatch('hideTable.sales')\">Hide Sales Table</button>"
)->html(),

```
16 changes: 16 additions & 0 deletions resources/js/laravel-livewire-tables.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
document.addEventListener('alpine:init', () => {

Alpine.data('laravellivewiretable', (wire, showBulkActionsAlpine, tableID, primaryKeyName) => ({
shouldBeDisplayed: wire.entangle('shouldBeDisplayed'),
tableName: wire.entangle('tableName'),
dataTableFingerprint: wire.entangle('dataTableFingerprint'),
listeners: [],
childElementOpen: false,
filtersOpen: wire.entangle('filterSlideDownDefaultVisible'),
Expand Down Expand Up @@ -207,6 +210,18 @@ document.addEventListener('alpine:init', () => {
}
this.selectedItems = [...new Set(tempSelectedItems)];
},
showTable(eventTableName = '', eventTableFingerpint = '')
{
if ((eventTableName != '' && eventTableName === this.tableName) || (eventTableFingerprint != '' && eventTableFingerpint === this.dataTableFingerprint)) {
this.shouldBeDisplayed = true;
}
},
hideTable(eventTableName = '', eventTableFingerpint = '')
{
if ((eventTableName != '' && eventTableName === this.tableName) || (eventTableFingerprint != '' && eventTableFingerpint === this.dataTableFingerprint)) {
this.shouldBeDisplayed = false;
}
},
destroy() {
this.listeners.forEach((listener) => {
listener();
Expand Down Expand Up @@ -373,6 +388,7 @@ document.addEventListener('alpine:init', () => {


Alpine.data('tableWrapper', (wire, showBulkActionsAlpine) => ({
shouldBeDisplayed: wire.entangle('shouldBeDisplayed'),
listeners: [],
childElementOpen: false,
filtersOpen: wire.entangle('filterSlideDownDefaultVisible'),
Expand Down
2 changes: 1 addition & 1 deletion resources/js/laravel-livewire-tables.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion resources/views/datatable.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
@php($isBootstrap4 = $this->isBootstrap4)
@php($isBootstrap5 = $this->isBootstrap5)

<div x-data="laravellivewiretable($wire, '{{ $this->showBulkActionsDropdownAlpine() }}', '{{ $tableId }}', '{{ $primaryKey }}')">
<div x-data="laravellivewiretable($wire, '{{ $this->showBulkActionsDropdownAlpine() }}', '{{ $tableId }}', '{{ $primaryKey }}')" x-cloak x-show="shouldBeDisplayed" x-on:show-table.window="showTable(event.detail.tableName ?? '', event.detail.tableFingerpint ?? '')" x-on:hide-table.window="hideTable(event.detail.tableName ?? '', event.detail.tableFingerpint ?? '')">
<x-livewire-tables::wrapper :component="$this" :tableName="$tableName" :$primaryKey :$isTailwind :$isBootstrap :$isBootstrap4 :$isBootstrap5>
@if($this->hasActions && !$this->showActionsInToolbar)
<x-livewire-tables::includes.actions/>
Expand Down
8 changes: 6 additions & 2 deletions src/Traits/ComponentUtilities.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use Livewire\Attributes\Locked;
use Rappasoft\LaravelLivewireTables\Exceptions\DataTableConfigurationException;
use Rappasoft\LaravelLivewireTables\Traits\Configuration\ComponentConfiguration;
use Rappasoft\LaravelLivewireTables\Traits\Helpers\ComponentHelpers;
Expand All @@ -27,7 +28,8 @@ trait ComponentUtilities

protected string $tableName = 'table';

protected ?string $dataTableFingerprint;
#[Locked]
public ?string $dataTableFingerprint;

protected bool $offlineIndicatorStatus = true;

Expand Down Expand Up @@ -61,6 +63,8 @@ public function mountComponentUtilities(): void
if (is_null($this->theme)) {
$this->setTheme();
}
$this->generateDataTableFingerprint();

}

/**
Expand All @@ -81,7 +85,7 @@ public function bootedComponentUtilities(): void

// Make sure a primary key is set
if (! $this->hasPrimaryKey()) {
throw new DataTableConfigurationException('You must set a primary key using setPrimaryKey in the configure method.');
throw new DataTableConfigurationException('You must set a primary key using setPrimaryKey in the configure method, or configuring/configured lifecycle hooks');
}

}
Expand Down
15 changes: 15 additions & 0 deletions src/Traits/Configuration/TableAttributeConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,19 @@ public function setTableRowUrlTarget(\Closure $callback): self

return $this;
}

public function setShouldBeDisplayedStatus(bool $status): void
{
$this->shouldBeDisplayed = $status;
}

public function setShouldBeDisplayed(): void
{
$this->setShouldBeDisplayedStatus(true);
}

public function setShouldBeHidden(): void
{
$this->setShouldBeDisplayedStatus(false);
}
}
2 changes: 1 addition & 1 deletion src/Traits/Helpers/ComponentHelpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ trait ComponentHelpers
{
public function getDataTableFingerprint(): string
{
return $this->dataTableFingerprint ?? $this->generateDataTableFingerprint();
return $this->dataTableFingerprint ?? ($this->dataTableFingerprint = $this->generateDataTableFingerprint());
}

public function setBuilder(Builder $builder): void
Expand Down
6 changes: 6 additions & 0 deletions src/Traits/Helpers/TableAttributeHelpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,10 @@ public function getTableRowUrlTarget(int|Model $row): ?string
{
return isset($this->trUrlTargetCallback) ? call_user_func($this->trUrlTargetCallback, $row) : null;
}

#[Computed]
public function getShouldBeDisplayed(): bool
{
return $this->shouldBeDisplayed;
}
}
3 changes: 3 additions & 0 deletions src/Traits/WithTableAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Rappasoft\LaravelLivewireTables\Traits;

use Closure;
use Livewire\Attributes\On;
use Rappasoft\LaravelLivewireTables\Traits\Configuration\TableAttributeConfiguration;
use Rappasoft\LaravelLivewireTables\Traits\Helpers\TableAttributeHelpers;

Expand Down Expand Up @@ -32,4 +33,6 @@ trait WithTableAttributes
protected ?\Closure $trUrlCallback;

protected ?\Closure $trUrlTargetCallback;

public bool $shouldBeDisplayed = true;
}
1 change: 1 addition & 0 deletions tests/Http/Livewire/PetsTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Rappasoft\LaravelLivewireTables\Tests\Http\Livewire;

use Illuminate\Database\Eloquent\Builder;
use Livewire\Attributes\On;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Tests\Models\Breed;
use Rappasoft\LaravelLivewireTables\Tests\Models\Pet;
Expand Down
139 changes: 1 addition & 138 deletions tests/Http/Livewire/PetsTableAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,8 @@

namespace Rappasoft\LaravelLivewireTables\Tests\Http\Livewire;

use Illuminate\Database\Eloquent\Builder;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Tests\Models\Breed;
use Rappasoft\LaravelLivewireTables\Tests\Models\Pet;
use Rappasoft\LaravelLivewireTables\Tests\Models\Species;
use Rappasoft\LaravelLivewireTables\Views\Column;
use Rappasoft\LaravelLivewireTables\Views\Columns\ImageColumn;
use Rappasoft\LaravelLivewireTables\Views\Columns\LinkColumn;
use Rappasoft\LaravelLivewireTables\Views\Filters\DateFilter;
use Rappasoft\LaravelLivewireTables\Views\Filters\DateTimeFilter;
use Rappasoft\LaravelLivewireTables\Views\Filters\MultiSelectDropdownFilter;
use Rappasoft\LaravelLivewireTables\Views\Filters\MultiSelectFilter;
use Rappasoft\LaravelLivewireTables\Views\Filters\NumberFilter;
use Rappasoft\LaravelLivewireTables\Views\Filters\SelectFilter;
use Rappasoft\LaravelLivewireTables\Views\Filters\TextFilter;

class PetsTableAttributes extends DataTableComponent
class PetsTableAttributes extends PetsTable
{
public $model = Pet::class;

public function configure(): void
{
$this->setPrimaryKey('id')
Expand Down Expand Up @@ -49,123 +31,4 @@ public function configure(): void
});

}

public function columns(): array
{
return [
Column::make('ID', 'id')
->sortable()
->setSortingPillTitle('Key')
->setSortingPillDirections('0-9', '9-0'),
Column::make('Sort')
->sortable()
->excludeFromColumnSelect(),
Column::make('Name')
->sortable()
->secondaryHeader($this->getFilterByKey('pet_name_filter'))
->footerFilter('pet_name_filter')
->searchable(),

Column::make('Age'),

Column::make('Breed', 'breed.name')
->secondaryHeaderFilter('breed')
->footer($this->getFilterByKey('breed'))
->sortable(
fn (Builder $query, string $direction) => $query->orderBy('pets.id', $direction)
)
->searchable(
fn (Builder $query, $searchTerm) => $query->orWhere('breed.name', $searchTerm)
),

Column::make('Other')
->label(function ($row, Column $column) {
return 'Other';
})
->footer(function ($rows) {
return 'Count: '.$rows->count();
}),

LinkColumn::make('Link')
->title(fn ($row) => 'Edit')
->location(fn ($row) => 'http://www.google.com')
->attributes(fn ($row) => [
'class' => 'rounded-full',
'alt' => $row->name.' Avatar',
]),
ImageColumn::make('RowImg')
->location(fn ($row) => 'test'.$row->id)
->attributes(fn ($row) => [
'class' => 'rounded-full',
'alt' => $row->name.' Avatar',
]),
Column::make('Last Visit', 'last_visit')
->sortable()
->deselected(),
];
}

public function filters(): array
{
return [
MultiSelectFilter::make('Breed')
->options(
Breed::query()
->orderBy('name')
->get()
->keyBy('id')
->map(fn ($breed) => $breed->name)
->toArray()
)
->filter(function (Builder $builder, array $values) {
return $builder->whereIn('breed_id', $values);
}),
MultiSelectDropdownFilter::make('Species')
->options(
Species::query()
->orderBy('name')
->get()
->keyBy('id')
->map(fn ($species) => $species->name)
->toArray()
)
->filter(function (Builder $builder, array $values) {
return $builder->whereIn('species_id', $values);
}),
NumberFilter::make('Breed ID', 'breed_id_filter')
->filter(function (Builder $builder, string $value) {
return $builder->where('breed_id', '=', $value);
}),

TextFilter::make('Pet Name', 'pet_name_filter')
->filter(function (Builder $builder, string $value) {
return $builder->where('pets.name', '=', $value);
}),

DateFilter::make('Last Visit After Date', 'last_visit_date_filter')
->filter(function (Builder $builder, string $value) {
return $builder->whereDate('pets.last_visit', '=>', $value);
}),

DateTimeFilter::make('Last Visit Before DateTime', 'last_visit_datetime_filter')
->filter(function (Builder $builder, string $value) {
return $builder->whereDate('pets.last_visit', '<=', $value);
}),

SelectFilter::make('Breed SelectFilter', 'breed_select_filter')
->options(
Breed::query()
->orderBy('name')
->get()
->keyBy('id')
->map(fn ($breed) => $breed->name)
->toArray()
)
->filter(function (Builder $builder, string $value) {
return $builder->where('breed_id', $value);
})
->setCustomFilterLabel('livewire-tables::tests.testFilterLabel')
->setFilterPillBlade('livewire-tables::tests.testFilterPills'),
];
}
}
Loading

0 comments on commit 1f076af

Please sign in to comment.