From b7806946e9fe63c419a4e0cc0ff3fd3120fc89be Mon Sep 17 00:00:00 2001 From: Iosif Chatzimichail Date: Sun, 26 Jan 2025 00:50:38 +0200 Subject: [PATCH] Add clear method and clear option support to LfRangeFilter --- src/Http/Livewire/LfRangeFilter.php | 25 +++++++++++++++ tests/Feature/LfRangeFilterTest.php | 50 +++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/src/Http/Livewire/LfRangeFilter.php b/src/Http/Livewire/LfRangeFilter.php index fd8ecfe..32563a9 100644 --- a/src/Http/Livewire/LfRangeFilter.php +++ b/src/Http/Livewire/LfRangeFilter.php @@ -32,6 +32,13 @@ public function mount($default = null) public function dispatchEvent() { + // Clear the filter if we are back to default + if ($this->selected === ($this->default ?? $this->min)) { + $this->clearFilters(); + + return; + } + $this->dispatch('filter-updated', field: $this->field, condition: $this->condition, @@ -54,6 +61,24 @@ public function setPresetValues($params) } } + public function clear(): void + { + $this->selected = $this->default ?? $this->min; + + $this->clearFilters(); + } + + #[On('clear-option')] + public function clearOption($tag) + { + if ($tag['field'] !== $this->field) { + return; + } + + $this->selected = $this->default ?? $this->min; + $this->dispatchEvent(); + } + public function render() { return view('statamic-livewire-filters::livewire.filters.'.$this->view); diff --git a/tests/Feature/LfRangeFilterTest.php b/tests/Feature/LfRangeFilterTest.php index 6538c2b..fefbde7 100644 --- a/tests/Feature/LfRangeFilterTest.php +++ b/tests/Feature/LfRangeFilterTest.php @@ -116,6 +116,56 @@ public function it_changes_the_value_of_selected_property_when_slider_changes() ); } + /** @test */ + public function it_can_be_reset_using_the_clear_method() + { + Livewire::test(LfRangeFilter::class, [ + 'field' => 'max_items', + 'blueprint' => 'pages.pages', + 'condition' => 'gte', + 'min' => 1, + 'max' => 4, + 'default' => 2, + ]) + ->set('selected', 3) + ->assertDispatched('filter-updated', + field: 'max_items', + condition: 'gte', + payload: 3, + ) + ->call('clear') + ->assertSet('selected', 2) + ->assertDispatched('clear-filter', + field: 'max_items', + condition: 'gte', + ); + } + + /** @test */ + public function it_can_be_reset_using_the_clear_option_event() + { + Livewire::test(LfRangeFilter::class, [ + 'field' => 'max_items', + 'blueprint' => 'pages.pages', + 'condition' => 'gte', + 'min' => 1, + 'max' => 4, + 'default' => 2, + ]) + ->set('selected', 3) + ->assertDispatched('filter-updated', + field: 'max_items', + condition: 'gte', + payload: 3, + ) + ->dispatch('clear-option', ['field' => 'max_items', 'value' => 3]) + ->assertSet('selected', 2) + ->assertDispatched('clear-filter', + field: 'max_items', + condition: 'gte', + ); + } + /** @test */ public function it_loads_a_param_that_is_preset() {