repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRedirects/SupportRedirects.php
src/Features/SupportRedirects/SupportRedirects.php
<?php namespace Livewire\Features\SupportRedirects; use Livewire\Mechanisms\HandleRequests\HandleRequests; use Livewire\ComponentHook; use Livewire\Component; use function Livewire\on; class SupportRedirects extends ComponentHook { public static $redirectorCacheStack = []; public static $atLeastOneMountedComponentHasRedirected = false; public static function provide() { // Wait until all components have been processed... on('response', function ($response) { // If there was no redirect on a subsequent component update, clear flash session data. if (! static::$atLeastOneMountedComponentHasRedirected && app()->has('session.store')) { session()->forget(session()->get('_flash.new')); } }); on('flush-state', function () { static::$atLeastOneMountedComponentHasRedirected = false; }); } public function boot() { // Put Laravel's redirector aside and replace it with our own custom one. static::$redirectorCacheStack[] = app('redirect'); app()->bind('redirect', function () { $redirector = app(Redirector::class)->component($this->component); if (app()->has('session.store')) { $redirector->setSession(app('session.store')); } return $redirector; }); } public function dehydrate($context) { // Put the old redirector back into the container. app()->instance('redirect', array_pop(static::$redirectorCacheStack)); $to = $this->storeGet('redirect'); $usingNavigate = $this->storeGet('redirectUsingNavigate'); if (is_subclass_of($to, Component::class)) { $to = url()->action($to); } if ($to && ! app(HandleRequests::class)->isLivewireRequest()) { abort(redirect($to)); } if (! $to) return; $context->addEffect('redirect', $to); $usingNavigate && $context->addEffect('redirectUsingNavigate', true); if (! $context->isMounting()) { static::$atLeastOneMountedComponentHasRedirected = true; } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRedirects/UnitTest.php
src/Features/SupportRedirects/UnitTest.php
<?php namespace Livewire\Features\SupportRedirects; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Session; use Livewire\Component; use Livewire\Livewire; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_standard_redirect() { $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirect'); $this->assertEquals('/local', $component->effects['redirect']); } public function test_route_redirect() { $this->registerNamedRoute(); $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirectRoute'); $this->assertEquals('http://localhost/foo', $component->effects['redirect']); } public function test_intended_redirect() { $this->registerNamedRoute(); $component = Livewire::test(TriggersRedirectStub::class); session()->put('url.intended', route('foo')); $component->runAction('triggerRedirectIntended'); $this->assertEquals(route('foo'), $component->effects['redirect']); } public function test_action_redirect() { $this->registerAction(); $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirectAction'); $this->assertEquals('http://localhost/foo', $component->effects['redirect']); } public function test_can_redirect_to_other_component_from_redirect_method() { Route::get('/test', TriggersRedirectStub::class); Livewire::test(new class extends TestComponent { function triggerRedirect() { $this->redirect(TriggersRedirectStub::class); } }) ->call('triggerRedirect') ->assertRedirect(TriggersRedirectStub::class) ->assertRedirect('/test'); } public function test_redirect_helper() { $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirectHelper'); $this->assertEquals(url('foo'), $component->effects['redirect']); } public function test_redirect_helper_using_key_value_with() { $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirectHelperUsingKeyValueWith'); $this->assertEquals(url('foo'), $component->effects['redirect']); $this->assertEquals('livewire-is-awesome', Session::get('success')); } public function test_redirect_helper_using_array_with() { $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirectHelperUsingArrayWith'); $this->assertEquals(url('foo'), $component->effects['redirect']); $this->assertEquals('livewire-is-awesome', Session::get('success')); } public function test_redirect_facade_with_to_method() { $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirectFacadeUsingTo'); $this->assertEquals(url('foo'), $component->effects['redirect']); } public function test_redirect_facade_with_route_method() { $this->registerNamedRoute(); $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirectFacadeUsingRoute'); $this->assertEquals(route('foo'), $component->effects['redirect']); } public function test_redirect_helper_with_route_method() { $this->registerNamedRoute(); $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirectHelperUsingRoute'); $this->assertEquals(route('foo'), $component->effects['redirect']); } public function test_redirect_helper_with_away_method() { $this->registerNamedRoute(); $component = Livewire::test(TriggersRedirectStub::class); $component->runAction('triggerRedirectHelperUsingAway'); $this->assertEquals(route('foo'), $component->effects['redirect']); } public function test_skip_render_on_redirect_by_default() { $component = Livewire::test(SkipsRenderOnRedirect::class)->call('triggerRedirect'); $this->assertEquals('/local', $component->effects['redirect']); $this->assertNull($component->effects['html'] ?? null); } public function test_dont_skip_render_on_redirect_if_config_set() { config()->set('livewire.render_on_redirect', true); $component = Livewire::test(SkipsRenderOnRedirect::class)->call('triggerRedirect'); $this->assertEquals('/local', $component->effects['redirect']); $this->assertStringContainsString('Render has run', $component->html()); } public function test_manually_override_dont_skip_render_on_redirect_using_skip_render_method() { config()->set('livewire.render_on_redirect', true); $component = Livewire::test(RenderOnRedirectWithSkipRenderMethod::class)->call('triggerRedirect'); $this->assertEquals('/local', $component->effects['redirect']); $this->assertNull($component->effects['html'] ?? null); } public function test_flash_data_is_available_after_render() { session()->flash('foo', 'bar'); $this->assertEquals('bar', session()->get('foo')); Livewire::test(RenderOnRedirectWithSkipRenderMethod::class); $this->assertEquals('bar', session()->get('foo')); } public function test_flash_data_is_unavailable_after_subsequent_requests() { session()->flash('foo', 'bar'); $this->assertEquals('bar', session()->get('foo')); $component = Livewire::test(RenderOnRedirectWithSkipRenderMethod::class); $this->assertEquals('bar', session()->get('foo')); $component->call('$refresh'); $this->assertNull(session()->get('foo')); } public function test_flash_data_is_available_after_render_of_multiple_components() { session()->flash('foo', 'bar'); $this->assertEquals('bar', session()->get('foo')); $component1 = Livewire::test(RenderOnRedirectWithSkipRenderMethod::class); $component2 = Livewire::test(RenderOnRedirectWithSkipRenderMethod::class); $this->assertEquals('bar', session()->get('foo')); $component1->call('$refresh'); $this->assertNull(session()->get('foo')); } protected function registerNamedRoute() { Route::get('foo', function () { return true; })->name('foo'); } protected function registerAction() { Route::get('foo', 'HomeController@index')->name('foo'); } } class TriggersRedirectStub extends TestComponent { public function triggerRedirect() { return $this->redirect('/local'); } public function triggerRedirectRoute() { return $this->redirectRoute('foo'); } public function triggerRedirectIntended() { return $this->redirectIntended(); } public function triggerRedirectAction() { return $this->redirectAction('HomeController@index'); } public function triggerRedirectHelper() { return redirect('foo'); } public function triggerRedirectHelperUsingKeyValueWith() { return redirect('foo')->with('success', 'livewire-is-awesome'); } public function triggerRedirectHelperUsingArrayWith() { return redirect('foo')->with([ 'success' => 'livewire-is-awesome' ]); } public function triggerRedirectFacadeUsingTo() { return Redirect::to('foo'); } public function triggerRedirectFacadeUsingRoute() { return Redirect::route('foo'); } public function triggerRedirectHelperUsingRoute() { return redirect()->route('foo'); } public function triggerRedirectHelperUsingAway() { return redirect()->away('foo'); } } class TriggersRedirectOnMountStub extends TestComponent { public function mount() { $this->redirect('/local'); } } class SkipsRenderOnRedirect extends Component { public function triggerRedirect() { return $this->redirect('/local'); } public function render() { return <<<'HTML' <div> Render has run </div> HTML; } } class RenderOnRedirectWithSkipRenderMethod extends Component { function triggerRedirect() { $this->skipRender(); return $this->redirect('/local'); } public function render() { return <<<'HTML' <div> Render has run </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJsEvaluation/SupportJsEvaluation.php
src/Features/SupportJsEvaluation/SupportJsEvaluation.php
<?php namespace Livewire\Features\SupportJsEvaluation; use function Livewire\store; use Livewire\ComponentHook; class SupportJsEvaluation extends ComponentHook { function dehydrate($context) { if (! store($this->component)->has('js')) return; $context->addEffect('xjs', store($this->component)->get('js')); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJsEvaluation/BrowserTest.php
src/Features/SupportJsEvaluation/BrowserTest.php
<?php namespace Livewire\Features\SupportJsEvaluation; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public static function tweakApplicationHook() { return function () { app('livewire.finder')->addLocation(viewPath: __DIR__ . '/fixtures'); }; } public function test_can_toggle_a_purely_js_property_with_a_purely_js_function() { Livewire::visit( new class extends \Livewire\Component { public $show = false; #[BaseJs] function toggle() { return <<<'JS' $wire.show = ! $wire.show; JS; } public function render() { return <<<'HTML' <div> <button @click="$wire.toggle" dusk="toggle">Toggle</button> <div dusk="target" x-show="$wire.show"> Toggle Me! </div> </div> HTML; } }) ->waitUntilMissingText('Toggle Me!') ->assertDontSee('Toggle Me!') ->click('@toggle') ->waitForText('Toggle Me!') ->assertSee('Toggle Me!') ->click('@toggle') ->waitUntilMissingText('Toggle Me!') ->assertDontSee('Toggle Me!') ; } public function test_can_evaluate_js_code_after_an_action_is_performed() { Livewire::visit( new class extends \Livewire\Component { public $show = false; function toggle() { $this->js('$wire.show = true'); } public function render() { return <<<'HTML' <div> <button wire:click="toggle" dusk="toggle">Toggle</button> <div dusk="target" x-show="$wire.show"> Toggle Me! </div> </div> HTML; } }) ->assertDontSee('Toggle Me!') ->waitForLivewire()->click('@toggle') ->waitForText('Toggle Me!') ; } public function test_can_define_js_actions_though_dollar_wire_on_a_component() { Livewire::visit( new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click="$js.test" dusk="test">Test</button> </div> @script <script> $wire.$js('test', () => { window.test = 'through dollar wire' }) </script> @endscript HTML; } } ) ->click('@test') ->assertScript('window.test === "through dollar wire"') ; } public function test_can_define_js_actions_though_dollar_wire_on_a_component_using_direct_propert_assignment() { Livewire::visit( new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click="$js.test" dusk="test">Test</button> </div> @script <script> $wire.$js.test = () => { window.test = 'through dollar wire' } </script> @endscript HTML; } } ) ->click('@test') ->assertScript('window.test === "through dollar wire"') ; } public function test_can_define_js_actions_though_dollar_js_magic_in_a_script() { Livewire::visit( new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click="$js.test" dusk="test">Test</button> </div> @script <script> $js('test', () => { window.test = 'through dollar js' }) </script> @endscript HTML; } } ) ->click('@test') ->assertScript('window.test === "through dollar js"') ; } public function test_can_define_js_actions_though_dollar_js_magic_in_a_sfc_script() { Livewire::visit('sfc-component-with-dollar-js-magic') ->waitForLivewireToLoad() // Pause for a moment to allow the script to be loaded... ->pause(100) ->click('@test') ->assertScript('window.test === "through dollar js"') ; } public function test_can_define_js_actions_though_dollar_js_magic_on_a_mfc_script() { Livewire::visit('mfc-component-with-dollar-js-magic') ->waitForLivewireToLoad() // Pause for a moment to allow the script to be loaded... ->pause(100) ->click('@test') ->assertScript('window.test === "through dollar js"') ; } public function test_can_call_a_defined_js_action_from_wire_click_without_params() { Livewire::visit( new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click="$js.test" dusk="test">Test</button> </div> @script <script> this.$js('test', () => { window.test = 'through wire:click' }) </script> @endscript HTML; } } ) ->click('@test') ->assertScript('window.test === "through wire:click"') ; } public function test_can_call_a_defined_js_action_from_wire_click_with_params() { Livewire::visit( new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click="$js.test('foo','bar')" dusk="test">Test</button> </div> @script <script> this.$js.test = (param1, param2) => { console.log('test', param1, param2); window.test = `through wire:click with params: ${param1}, ${param2}` } </script> @endscript HTML; } } ) ->click('@test') ->assertScript('window.test === "through wire:click with params: foo, bar"') ; } public function test_can_call_a_defined_js_action_from_the_backend_using_the_js_method_without_params() { Livewire::visit( new class extends \Livewire\Component { public function save() { $this->js('test'); } public function render() { return <<<'HTML' <div> <button wire:click="save" dusk="save">Save</button> </div> @script <script> this.$js('test', () => { window.test = 'through backend js method' }) </script> @endscript HTML; } } ) ->waitForLivewire()->click('@save') ->assertScript('window.test === "through backend js method"') ; } public function test_can_call_a_defined_js_action_from_the_backend_using_the_js_method_with_params() { Livewire::visit( new class extends \Livewire\Component { public function save() { $this->js('test', 'foo', 'bar'); } public function render() { return <<<'HTML' <div> <button wire:click="save" dusk="save">Save</button> </div> @script <script> this.$js('test', (param1, param2) => { window.test = `through backend js method with params: ${param1}, ${param2}` }) </script> @endscript HTML; } } ) ->waitForLivewire()->click('@save') ->assertScript('window.test === "through backend js method with params: foo, bar"') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJsEvaluation/BaseJs.php
src/Features/SupportJsEvaluation/BaseJs.php
<?php namespace Livewire\Features\SupportJsEvaluation; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; #[\Attribute] class BaseJs extends LivewireAttribute { function dehydrate($context) { $name = $this->getName(); $stringifiedMethod = $this->component->$name(); $context->pushEffect('js', $stringifiedMethod, $name); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJsEvaluation/HandlesJsEvaluation.php
src/Features/SupportJsEvaluation/HandlesJsEvaluation.php
<?php namespace Livewire\Features\SupportJsEvaluation; use function Livewire\store; trait HandlesJsEvaluation { function js($expression, ...$params) { store($this)->push('js', compact('expression', 'params')); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJsEvaluation/fixtures/sfc-component-with-dollar-js-magic.blade.php
src/Features/SupportJsEvaluation/fixtures/sfc-component-with-dollar-js-magic.blade.php
<?php new class extends \Livewire\Component { // }; ?> <div> <button wire:click="$js.test" dusk="test">Test</button> </div> <script> $js('test', () => { window.test = 'through dollar js' }) </script>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJsEvaluation/fixtures/mfc-component-with-dollar-js-magic/mfc-component-with-dollar-js-magic.blade.php
src/Features/SupportJsEvaluation/fixtures/mfc-component-with-dollar-js-magic/mfc-component-with-dollar-js-magic.blade.php
<div> <button wire:click="$js.test" dusk="test">Test</button> </div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJsEvaluation/fixtures/mfc-component-with-dollar-js-magic/mfc-component-with-dollar-js-magic.php
src/Features/SupportJsEvaluation/fixtures/mfc-component-with-dollar-js-magic/mfc-component-with-dollar-js-magic.php
<?php new class extends \Livewire\Component { // }; ?>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNestingComponents/SupportNestingComponents.php
src/Features/SupportNestingComponents/SupportNestingComponents.php
<?php namespace Livewire\Features\SupportNestingComponents; use function Livewire\trigger; use function Livewire\store; use function Livewire\on; use Livewire\ComponentHook; use Livewire\Drawer\Utils; class SupportNestingComponents extends ComponentHook { static function provide() { on('pre-mount', function ($name, $params, $key, $parent, $hijack, $slots, $attributes) { // If this has already been rendered spoof it... if ($parent && static::hasPreviouslyRenderedChild($parent, $key)) { [$tag, $childId] = static::getPreviouslyRenderedChild($parent, $key); $finish = trigger('mount.stub', $tag, $childId, $params, $parent, $key, $slots, $attributes); $idAttribute = " wire:id=\"{$childId}\""; $nameAttribute = " wire:name=\"{$name}\""; $keyAttribute = $key !== null ? " wire:key=\"{$key}\"" : ''; $html = "<{$tag}{$idAttribute}{$nameAttribute}{$keyAttribute}></{$tag}>"; static::setParentChild($parent, $key, $tag, $childId); $hijack($finish($html)); } }); on('mount', function ($component, $params, $key, $parent) { $start = null; if ($parent && config('app.debug')) $start = microtime(true); static::setParametersToMatchingProperties($component, $params); return function (&$html) use ($component, $key, $parent, $start) { if ($key !== null) { $html = Utils::insertAttributesIntoHtmlRoot($html, [ 'wire:key' => $key, ]); } if ($parent) { if (config('app.debug')) trigger('profile', 'child:'.$component->getId(), $parent->getId(), [$start, microtime(true)]); preg_match('/<([a-zA-Z0-9\-]*)/', $html, $matches, PREG_OFFSET_CAPTURE); $tag = $matches[1][0]; static::setParentChild($parent, $key, $tag, $component->getId()); } }; }); } function hydrate($memo) { $children = $memo['children']; static::setPreviouslyRenderedChildren($this->component, $children); $this->ifThisComponentIsAChildThatHasBeenRemovedByTheParent(function () { // Let's skip its render so that we aren't wasting extra rendering time // on a component that has already been thrown-away by its parent... $this->component->skipRender(); }); } function dehydrate($context) { $skipRender = $this->storeGet('skipRender'); if ($skipRender) $this->keepRenderedChildren(); $this->storeRemovedChildrenToReferenceWhenThoseChildrenHydrateSoWeCanSkipTheirRenderAndAvoideUselessWork(); $context->addMemo('children', $this->getChildren()); } function getChildren() { return $this->storeGet('children', []); } function setChild($key, $tag, $id) { $this->storePush('children', [$tag, $id], $key); } static function setParentChild($parent, $key, $tag, $id) { store($parent)->push('children', [$tag, $id], $key); } static function setPreviouslyRenderedChildren($component, $children) { store($component)->set('previousChildren', $children); } static function hasPreviouslyRenderedChild($parent, $key) { return array_key_exists($key, store($parent)->get('previousChildren', [])); } static function getPreviouslyRenderedChild($parent, $key) { $child = store($parent)->get('previousChildren')[$key]; [$tag, $childId] = $child; // Validate tag name - only allow valid HTML tag characters (letters, numbers, hyphens) // Must start with a letter to be a valid HTML tag if (! preg_match('/^[a-zA-Z][a-zA-Z0-9\-]*$/', $tag)) { throw new \Exception('Invalid Livewire child tag name. Tag names must only contain letters, numbers, and hyphens.'); } // Validate child ID format - only allow alphanumeric and hyphens if (! preg_match('/^[a-zA-Z0-9\-]+$/', $childId)) { throw new \Exception('Invalid Livewire child component ID format.'); } return $child; } function keepRenderedChildren() { $this->storeSet('children', $this->storeGet('previousChildren')); } static function setParametersToMatchingProperties($component, $params) { // Assign all public component properties that have matching parameters. collect(array_intersect_key($params, Utils::getPublicPropertiesDefinedOnSubclass($component))) ->each(function ($value, $property) use ($component) { $component->{$property} = $value; }); } protected function storeRemovedChildrenToReferenceWhenThoseChildrenHydrateSoWeCanSkipTheirRenderAndAvoideUselessWork() { // Get a list of children that we're "removed" in this request... $removedChildren = array_diff_key($this->storeGet('previousChildren', []), $this->getChildren()); foreach ($removedChildren as $key => $child) { store()->push('removedChildren', $key, $child[1]); } } protected function ifThisComponentIsAChildThatHasBeenRemovedByTheParent($callback) { $removedChildren = store()->get('removedChildren', []); if (isset($removedChildren[$this->component->getId()])) { $callback(); store()->unset('removedChildren', $this->component->getId()); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNestingComponents/BrowserTest.php
src/Features/SupportNestingComponents/BrowserTest.php
<?php namespace Livewire\Features\SupportNestingComponents; use Livewire\Attributes\Layout; use Livewire\Component; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_can_add_new_components() { Livewire::visit([ Page::class, 'first-component' => FirstComponent::class, 'second-component' => SecondComponent::class, 'third-component' => ThirdComponent::class, ]) ->assertSee('Page') ->waitForLivewire()->click('@add-first') ->assertSee('First Component Rendered') ->assertDontSee('Second Component Rendered') ->assertDontSee('Third Component Rendered') ->waitForLivewire()->click('@add-second') ->assertSee('First Component Rendered') ->assertSee('Second Component Rendered') ->assertDontSee('Third Component Rendered') ->waitForLivewire()->click('@add-third') ->assertSee('First Component Rendered') ->assertSee('Second Component Rendered') ->assertSee('Third Component Rendered') ->waitForLivewire()->click('@remove-second') ->assertSee('First Component Rendered') ->assertDontSee('Second Component Rendered') ->assertSee('Third Component Rendered') ; } public function test_nested_components_do_not_error_with_empty_elements_on_page() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <div> </div> <button type="button" wire:click="$refresh" dusk="refresh"> Refresh </button> <livewire:child /> <div> </div> </div> HTML; } }, 'child' => new class extends Component { public function render() { return <<<'HTML' <div dusk="child"> Child </div> HTML; } }, ]) ->assertPresent('@child') ->assertSeeIn('@child', 'Child') ->waitForLivewire()->click('@refresh') ->pause(500) ->assertPresent('@child') ->assertSeeIn('@child', 'Child') ->waitForLivewire()->click('@refresh') ->pause(500) ->assertPresent('@child') ->assertSeeIn('@child', 'Child') ; } public function test_nested_components_do_not_error_when_parent_has_custom_layout_and_default_layout_does_not_exist() { config()->set('livewire.component_layout', ''); Livewire::visit([ new class extends Component { #[Layout('layouts.app')] public function render() { return <<<'HTML' <div> <button type="button" wire:click="$refresh" dusk="refresh"> Refresh </button> <livewire:child /> </div> HTML; } }, 'child' => new class extends Component { public function render() { return <<<'HTML' <div dusk="child"> Child </div> HTML; } }, ]) ->assertPresent('@child') ->assertSeeIn('@child', 'Child') ->waitForLivewire()->click('@refresh') ->assertPresent('@child') ->assertSeeIn('@child', 'Child') ; } public function test_nested_components_do_not_error_when_child_deleted() { Livewire::visit([ new class extends Component { public $children = [ 'one', 'two' ]; public function deleteChild($name) { unset($this->children[array_search($name, $this->children)]); } public function render() { return <<<'HTML' <div> <div> </div> @foreach($this->children as $key => $name) <livewire:child wire:key="{{ $key }}" :name="$name" /> @endforeach <div> </div> </div> HTML; } }, 'child' => new class extends Component { public $name = ''; public function render() { return <<<'HTML' <div dusk="child-{{ $name }}"> {{ $name }} <button dusk="delete-{{ $name }}" wire:click="$parent.deleteChild('{{ $name }}')">Delete</button> </div> HTML; } }, ]) ->assertPresent('@child-one') ->assertSeeIn('@child-one', 'one') ->waitForLivewire()->click('@delete-one') ->assertNotPresent('@child-one'); } public function test_lazy_nested_components_do_not_call_boot_method_twice() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <div>Page</div> <livewire:nested-boot-component lazy/> </div> HTML; } }, 'nested-boot-component' => new class extends Component { public $bootCount = 0; public function boot() { $this->increment(); } public function increment() { $this->bootCount ++; } public function render() { return '<div>Boot count: {{ $bootCount }}</div>'; } }]) ->assertSee('Page') ->waitForText('Boot count: 1'); ; } public function test_nested_components_can_be_removed_and_readded_to_dom() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div id="root" x-data> <button dusk="button" @click=" nestedElement = document.getElementById('removable') nestedElement.remove(); setTimeout(() => { document.getElementById('root').appendChild(nestedElement); window.readded = true; }, 750); ">remove and re-add child</button> <div id="removable"> <livewire:child/> </div> </div> HTML; } }, 'child' => new class extends Component { public $clicked = false; public function render() { return <<<'HTML' <div dusk="child"> <button dusk="child-button" wire:click="$set('clicked', true)">child button</button> <p dusk="child-text">@js($clicked)</p> </div> HTML; } }, ]) ->assertPresent('@child') ->assertScript('Livewire.all().length', 2) ->click('@button') ->waitUntil('window.readded', 5, true) ->assertPresent('@child') ->assertScript('Livewire.all().length', 2) ->assertSeeIn('@child-text', 'false') ->waitForLivewire()->click('@child-button') ->assertSeeIn('@child-text', 'true'); } public function test_can_submit_form_using_parent_action_without_permenantly_disabling_form() { Livewire::visit([ new class extends Component { public $textFromChildComponent; public function render() { return <<<'HTML' <div> <livewire:child /> <span dusk="output">{{ $textFromChildComponent }}</span> </div> HTML; } public function submit($text) { $this->textFromChildComponent = $text; } }, 'child' => new class extends Component { public $text; public function render() { return <<<'HTML' <div> <form wire:submit="$parent.submit($wire.text)"> <input type="text" name="test" wire:model="text" dusk="input" /> <button type="submit" dusk="submit-btn">submit</button> </form> </div> HTML; } } ]) ->type('@input', 'hello') ->click('@submit-btn') ->waitForTextIn('@output', 'hello') ->assertAttributeMissing('@input', 'readonly') ->assertAttributeMissing('@submit-btn', 'disabled'); } public function test_can_listen_to_multiple_events_using_at_directive_attribute_from_child_component() { Livewire::visit([ new class extends Component { public $text; public function render() { return <<<'HTML' <div> <livewire:child @foo="foo" @bar="bar" /> <span>{{ $text }}</span> </div> HTML; } public function foo() { $this->text = 'foo'; } public function bar() { $this->text = 'bar'; } }, 'child' => new class extends Component { public function render() { return <<<'HTML' <div> <button type="button" wire:click="$dispatch('foo')" dusk="dispatch-foo-event-btn"> Dispatch Foo </button> <button type="button" wire:click="$dispatch('bar')" dusk="dispatch-bar-event-btn"> Dispatch Bar </button> </div> HTML; } } ]) ->waitForLivewire()->click('@dispatch-bar-event-btn') ->assertSee('bar') ->waitForLivewire()->click('@dispatch-foo-event-btn') ->assertSee('foo'); } public function test_a_child_component_can_be_removed_by_javascript_and_it_does_not_throw_an_error_on_the_next_render() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <button type="button" wire:click="$refresh" dusk="refresh-parent">Refresh</button> <livewire:child /> </div> HTML; } }, 'child' => new class extends Component { public function render() { return <<<'HTML' <div dusk="child"> Child <button type="button" x-on:click="$el.parentElement.remove()" dusk="remove-child">Remove using javascript</button> </div> HTML; } } ]) ->click('@remove-child') ->assertNotPresent('@child') ->waitForLivewire()->click('@refresh-parent') ->assertConsoleLogHasNoErrors(); } } class Page extends Component { public $components = []; public function add($item) { $this->components[$item] = []; } public function remove($item) { unset($this->components[$item]); } public function render() { return <<<'HTML' <div> <div>Page</div> @foreach($components as $component => $params) @livewire($component, $params, key($component)) @endforeach <div> <button dusk="add-first" wire:click="add('first-component')">Add first-component</button> <button dusk="add-second" wire:click="add('second-component')">Add second-component</button> <button dusk="add-third" wire:click="add('third-component')">Add third-component</button> </div> <div> <button dusk="remove-first" wire:click="remove('first-component')">Remove first-component</button> <button dusk="remove-second" wire:click="remove('second-component')">Remove second-component</button> <button dusk="remove-third" wire:click="remove('third-component')">Remove third-component</button> </div> </div> HTML; } } class FirstComponent extends Component { public function render() { return '<div>First Component Rendered</div>'; } } class SecondComponent extends Component { public function render() { return '<div>Second Component Rendered</div>'; } } class ThirdComponent extends Component { public function render() { return '<div>Third Component Rendered</div>'; } } class BootPage extends Component { public function render() { return <<<'HTML' <div> <div>Page</div> <livewire:nested-boot-component lazy/> </div> HTML; } } class NestedBootComponent extends Component { public $bootCount = 0; public function boot() { $this->increment(); } public function increment() { $this->bootCount ++; } public function render() { return '<div>Boot count: {{ $bootCount }}</div>'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNestingComponents/UnitTest.php
src/Features/SupportNestingComponents/UnitTest.php
<?php namespace Livewire\Features\SupportNestingComponents; use Livewire\Component; use function Livewire\store; class UnitTest extends \Tests\TestCase { public function test_parent_renders_child() { app('livewire')->component('parent', ParentComponentForNestingChildStub::class); app('livewire')->component('child', ChildComponentForNestingStub::class); $component = app('livewire')->test('parent'); $this->assertStringContainsString('Child: foo', $component->html()); } public function test_parent_renders_stub_element_in_place_of_child_on_subsequent_renders() { app('livewire')->component('parent', ParentComponentForNestingChildStub::class); app('livewire')->component('child', ChildComponentForNestingStub::class); $component = app('livewire')->test('parent'); $this->assertStringContainsString('Child: foo', $component->html()); $component->runAction('$refresh'); $this->assertStringNotContainsString('Child: foo', $component->html()); } public function test_stub_element_root_element_matches_original_child_component_root_element() { app('livewire')->component('parent', ParentComponentForNestingChildStub::class); app('livewire')->component('child', ChildComponentForNestingStub::class); $component = app('livewire')->test('parent'); $this->assertStringContainsString('span', $component->html()); $component->runAction('$refresh'); $this->assertStringContainsString('span', $component->html()); } public function test_parent_tracks_subsequent_renders_of_children_inside_a_loop() { app('livewire')->component('parent', ParentComponentForNestingChildrenStub::class); app('livewire')->component('child', ChildComponentForNestingStub::class); $component = app('livewire')->test('parent'); $this->assertStringContainsString('Child: foo', $component->html() ); $component->runAction('setChildren', ['foo', 'bar']); $this->assertStringNotContainsString('Child: foo', $component->html()); $this->assertStringContainsString('Child: bar', $component->html()); $component->runAction('setChildren', ['foo', 'bar']); $this->assertStringNotContainsString('Child: foo', $component->html()); $this->assertStringNotContainsString('Child: bar', $component->html()); } public function test_parent_tracks_subsequent_renders_of_children_inside_a_loop_with_colon_wire_key_syntax() { app('livewire')->component('parent', ParentComponentForNestingChildrenWithWireKeyStub::class); app('livewire')->component('child', ChildComponentForNestingStub::class); $component = app('livewire')->test('parent'); $this->assertStringContainsString('Child: foo', $component->html() ); $component->runAction('setChildren', ['foo', 'bar']); $this->assertStringNotContainsString('Child: foo', $component->html()); $this->assertStringContainsString('Child: bar', $component->html() ); $component->runAction('setChildren', ['foo', 'bar']); $this->assertStringNotContainsString('Child: foo', $component->html()); $this->assertStringNotContainsString('Child: bar', $component->html()); } public function test_parent_tracks_subsequent_renders_of_children_inside_a_loop_with_colon_wire_key_having_comma() { app('livewire')->component('parent', ParentComponentForNestingChildrenWithWireKeyHavingCommaStub::class); app('livewire')->component('child', ChildComponentForNestingStub::class); $component = app('livewire')->test('parent'); $this->assertStringContainsString('Child: foo', $component->html() ); $component->runAction('setChildren', ['foo', 'bar']); $this->assertStringNotContainsString('Child: foo', $component->html()); $this->assertStringContainsString('Child: bar', $component->html() ); $component->runAction('setChildren', ['foo', 'bar']); $this->assertStringNotContainsString('Child: foo', $component->html()); $this->assertStringNotContainsString('Child: bar', $component->html()); } public function test_parent_keeps_rendered_children_even_when_skipped_rendering() { app('livewire')->component('parent', ParentComponentForSkipRenderStub::class); app('livewire')->component('child', ChildComponentForNestingStub::class); $component = app('livewire')->test('parent'); $children = $component->snapshot['memo']['children']; $component->runAction('skip'); $this->assertContains($children, $component->snapshot['memo']); } public function test_child_tag_name_with_xss_payload_throws_exception() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Livewire child tag name'); // Create a mock parent component $parent = new ChildComponentForNestingStub(); // Set malicious children data directly in the store store($parent)->set('previousChildren', [ 'child-key' => ['div onclick=alert(1)', 'valid-id'] ]); // This should throw an exception due to invalid tag name SupportNestingComponents::getPreviouslyRenderedChild($parent, 'child-key'); } public function test_child_tag_name_with_spaces_throws_exception() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Livewire child tag name'); $parent = new ChildComponentForNestingStub(); store($parent)->set('previousChildren', [ 'child-key' => ['div class=injected', 'valid-id'] ]); SupportNestingComponents::getPreviouslyRenderedChild($parent, 'child-key'); } public function test_child_tag_name_starting_with_number_throws_exception() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Livewire child tag name'); $parent = new ChildComponentForNestingStub(); store($parent)->set('previousChildren', [ 'child-key' => ['1div', 'valid-id'] ]); SupportNestingComponents::getPreviouslyRenderedChild($parent, 'child-key'); } public function test_child_id_with_invalid_characters_throws_exception() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Livewire child component ID format'); $parent = new ChildComponentForNestingStub(); store($parent)->set('previousChildren', [ 'child-key' => ['div', 'id<script>alert(1)</script>'] ]); SupportNestingComponents::getPreviouslyRenderedChild($parent, 'child-key'); } public function test_valid_custom_element_tag_names_are_allowed() { $parent = new ChildComponentForNestingStub(); store($parent)->set('previousChildren', [ 'child-key' => ['my-custom-element', 'valid-id-123'] ]); // Should not throw an exception $result = SupportNestingComponents::getPreviouslyRenderedChild($parent, 'child-key'); $this->assertEquals(['my-custom-element', 'valid-id-123'], $result); } public function test_valid_standard_html_tags_are_allowed() { $parent = new ChildComponentForNestingStub(); $validTags = ['div', 'span', 'section', 'article', 'h1', 'p', 'ul', 'li']; foreach ($validTags as $tag) { store($parent)->set('previousChildren', [ 'child-key' => [$tag, 'valid-id'] ]); $result = SupportNestingComponents::getPreviouslyRenderedChild($parent, 'child-key'); $this->assertEquals([$tag, 'valid-id'], $result); } } } class ParentComponentForNestingChildStub extends Component { public function render() { return app('view')->make('show-child', [ 'child' => ['name' => 'foo'], ]); } } class ParentComponentForNestingChildrenStub extends Component { public $children = ['foo']; public function setChildren($children) { $this->children = $children; } public function render() { return app('view')->make('show-children', [ 'children' => $this->children, ]); } } class ParentComponentForNestingChildrenWithWireKeyStub extends Component { public $children = ['foo']; public function setChildren($children) { $this->children = $children; } public function render() { return <<<'blade' <div> @foreach ($children as $child) <livewire:child :name="$child" :wire:key="$child" /> @endforeach </div> blade; } } class ParentComponentForNestingChildrenWithWireKeyHavingCommaStub extends Component { public $children = ['foo']; public function setChildren($children) { $this->children = $children; } public function render() { return <<<'blade' <div> @foreach ($children as $child) <livewire:child :name="$child" :wire:key="str_pad($child, 5, '_', STR_PAD_BOTH)" /> @endforeach </div> blade; } } class ChildComponentForNestingStub extends Component { public $name; public function mount($name) { $this->name = $name; } public function render() { return '<span>Child: {{ $this->name }}</span>'; } } class ParentComponentForSkipRenderStub extends Component { public function skip() { $this->skipRender(); } public function render() { return app('view')->make('show-child', [ 'child' => ['name' => 'foo'], ]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAutoInjectedAssets/BrowserTest.php
src/Features/SupportAutoInjectedAssets/BrowserTest.php
<?php namespace Livewire\Features\SupportAutoInjectedAssets; use Livewire\Attributes\Layout; use Livewire\Component; use Livewire\Livewire; use Tests\BrowserTestCase; class BrowserTest extends BrowserTestCase { public function test_livewire_styles_take_preference_over_other_styles() { Livewire::visit(new class extends Component { #[Layout('layouts.app-with-styles')] function render() { return <<<'HTML' <div> <div wire:loading class="show" dusk="loading">Loading</div> <button type="button" wire:click="$refresh" dusk="refresh">Refresh</button> </div> HTML; } }) ->assertNotVisible('@loading') ->waitForLivewire()->click('@refresh') ->assertNotVisible('@loading') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAutoInjectedAssets/UnitTest.php
src/Features/SupportAutoInjectedAssets/UnitTest.php
<?php namespace Livewire\Features\SupportAutoInjectedAssets; use Livewire\Livewire; use Tests\TestComponent; use Tests\TestCase; use Livewire\Mechanisms\FrontendAssets\FrontendAssets; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Blade; use LegacyTests\Browser\Actions\Test; use Livewire\Mechanisms\HandleRequests\EndpointResolver; class UnitTest extends TestCase { public function test_it_injects_livewire_assets_before_closing_tags(): void { $this->compare( $livewireStyles = FrontendAssets::styles(), $livewireScripts = FrontendAssets::scripts(), <<<'HTML' <!doctype html> <html> <head> <meta charset="utf-8"/> <title></title> </head> <body> </body> </html> HTML, <<<HTML <!doctype html> <html> <head> <meta charset="utf-8"/> <title></title> $livewireStyles</head> <body> $livewireScripts</body> </html> HTML); } public function test_it_injects_livewire_assets_html_only(): void { $this->compare( $livewireStyles = FrontendAssets::styles(), $livewireScripts = FrontendAssets::scripts(), <<<'HTML' <html> <yolo /> </html> HTML, <<<HTML <html>$livewireStyles <yolo /> $livewireScripts</html> HTML); } public function test_it_injects_livewire_assets_weirdly_formatted_html(): void { $this->compare( $livewireStyles = FrontendAssets::styles(), $livewireScripts = FrontendAssets::scripts(), <<<'HTML' <!doctype html> <html lang="en" > <head > <meta charset="utf-8"/> <title></title> </head> <body> </body > </html> HTML, <<<HTML <!doctype html> <html lang="en" > <head > <meta charset="utf-8"/> <title></title> $livewireStyles</head> <body> $livewireScripts</body > </html> HTML); } public function test_it_injects_livewire_assets_html_with_header(): void { $this->compare( $livewireStyles = FrontendAssets::styles(), $livewireScripts = FrontendAssets::scripts(), <<<'HTML' <!doctype html> <HTML lang="en" > <Head > <meta charset="utf-8"/> <title></title> </Head> <bOdY> <header class=""></header> </bOdY > </HTML> HTML, <<<HTML <!doctype html> <HTML lang="en" > <Head > <meta charset="utf-8"/> <title></title> $livewireStyles</Head> <bOdY> <header class=""></header> $livewireScripts</bOdY > </HTML> HTML); } public function test_can_disable_auto_injection_using_global_method(): void { $this->markTestIncomplete(); } public function test_can_disable_auto_injection_using_config(): void { config()->set('livewire.inject_assets', false); Livewire::addComponent('test-component', TestComponent::class); Route::get('/with-livewire', TestComponent::class); Route::get('/without-livewire', function () { return Blade::render('<html></html>'); }); $this->get('/without-livewire')->assertDontSee('/livewire/livewire.min.js'); $this->get('/with-livewire')->assertDontSee('/livewire/livewire.min.js'); } public function test_can_force_injection_over_config(): void { config()->set('livewire.inject_assets', false); Route::livewire('/with-livewire', new class Extends TestComponent {}); Route::get('/without-livewire', function () { return '<html></html>'; }); // Check for the appropriate script path based on debug mode $scriptPath = EndpointResolver::scriptPath(! config('app.debug')); \Livewire\Livewire::forceAssetInjection(); $this->get('/with-livewire')->assertSee($scriptPath); \Livewire\Livewire::flushState(); \Livewire\Livewire::forceAssetInjection(); $this->get('/without-livewire')->assertSee($scriptPath); } public function test_only_auto_injects_when_a_livewire_component_was_rendered_on_the_page(): void { Route::livewire('/with-livewire', new class Extends TestComponent {}); Route::get('/without-livewire', function () { return '<html></html>'; }); // Check for the appropriate script path based on debug mode $scriptPath = EndpointResolver::scriptPath(! config('app.debug')); $this->get('/without-livewire')->assertDontSee($scriptPath); $this->get('/with-livewire')->assertSee($scriptPath); } public function test_only_auto_injects_when_persist_was_rendered_on_the_page(): void { Route::get('/with-persist', function () { return Blade::render('<html>@persist("foo") ... @endpersist</html>'); }); Route::get('/without-persist', function () { return '<html></html>'; }); // Check for the appropriate script path based on debug mode $scriptPath = EndpointResolver::scriptPath(! config('app.debug')); $this->get('/without-persist')->assertDontSee($scriptPath); $this->get('/with-persist')->assertSee($scriptPath); } public function test_only_injects_on_full_page_loads(): void { $this->markTestIncomplete(); } public function test_only_inject_when_dev_doesnt_use_livewire_scripts_or_livewire_styles(): void { $this->markTestIncomplete(); } public function test_response_maintains_original_view_after_asset_injection(): void { Livewire::component('foo', new class extends \Livewire\Component { public function render() { return '<div>Foo!</div>'; } }); $view = view('uses-component')->with('variable', 'cheese'); Route::get('/with-livewire', fn() => $view); $response = $this->get('/with-livewire'); $this->assertEquals($view, $response->original); $response ->assertSee('cheese') ->assertViewIs('uses-component') ->assertViewHas('variable', 'cheese'); } protected function compare($forHead, $forBody, string $original, string $expected): void { $this->assertEquals($expected, SupportAutoInjectedAssets::injectAssets($original, $forHead, $forBody)); } public function makeACleanSlate() { \Livewire\Livewire::flushState(); parent::makeACleanSlate(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAutoInjectedAssets/SupportAutoInjectedAssets.php
src/Features/SupportAutoInjectedAssets/SupportAutoInjectedAssets.php
<?php namespace Livewire\Features\SupportAutoInjectedAssets; use Illuminate\Foundation\Http\Events\RequestHandled; use Livewire\ComponentHook; use Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets; use Livewire\Mechanisms\FrontendAssets\FrontendAssets; use function Livewire\on; class SupportAutoInjectedAssets extends ComponentHook { static $hasRenderedAComponentThisRequest = false; static $forceAssetInjection = false; static function provide() { on('flush-state', function () { static::$hasRenderedAComponentThisRequest = false; static::$forceAssetInjection = false; }); app('events')->listen(RequestHandled::class, function ($handled) { // If this is a successful HTML response... if (! str($handled->response->headers->get('content-type'))->contains('text/html')) return; if (! method_exists($handled->response, 'status') || $handled->response->status() !== 200) return; $assetsHead = ''; $assetsBody = ''; // If `@assets` has been used outside of a Livewire component then we need // to process those assets to be injected alongside the other assets... SupportScriptsAndAssets::processNonLivewireAssets(); $assets = array_values(SupportScriptsAndAssets::getAssets()); // If there are additional head assets, inject those... if (count($assets) > 0) { foreach ($assets as $asset) { $assetsHead .= $asset."\n"; } } // If we're injecting Livewire assets... if (static::shouldInjectLivewireAssets()) { $assetsHead .= FrontendAssets::styles()."\n"; $assetsBody .= FrontendAssets::scripts()."\n"; } if ($assetsHead === '' && $assetsBody === '') return; $html = $handled->response->getContent(); if (str($html)->contains('</html>')) { $originalContent = $handled->response->original; $handled->response->setContent(static::injectAssets($html, $assetsHead, $assetsBody)); $handled->response->original = $originalContent; } }); } protected static function shouldInjectLivewireAssets() { if (! static::$forceAssetInjection && config('livewire.inject_assets', true) === false) return false; if ((! static::$hasRenderedAComponentThisRequest) && (! static::$forceAssetInjection)) return false; if (app(FrontendAssets::class)->hasRenderedScripts) return false; return true; } protected static function getLivewireAssets() { $livewireStyles = FrontendAssets::styles(); $livewireScripts = FrontendAssets::scripts(); } public function dehydrate() { static::$hasRenderedAComponentThisRequest = true; } static function injectAssets($html, $assetsHead, $assetsBody) { $html = str($html); if ($html->test('/<\s*\/\s*head\s*>/i') && $html->test('/<\s*\/\s*body\s*>/i')) { return $html ->replaceMatches('/(<\s*\/\s*head\s*>)/i', $assetsHead.'$1') ->replaceMatches('/(<\s*\/\s*body\s*>)/i', $assetsBody.'$1') ->toString(); } return $html ->replaceMatches('/(<\s*html(?:\s[^>])*>)/i', '$1'.$assetsHead) ->replaceMatches('/(<\s*\/\s*html\s*>)/i', $assetsBody.'$1') ->toString(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportDataBinding/BrowserTest.php
src/Features/SupportDataBinding/BrowserTest.php
<?php namespace Livewire\Features\SupportDataBinding; use Tests\BrowserTestCase; use Livewire\Livewire; use Livewire\Component; use Livewire\Attributes\Computed; class BrowserTest extends BrowserTestCase { function test_can_use_wire_dirty() { Livewire::visit(new class extends Component { public $prop = false; public function render() { return <<<'BLADE' <div> <input dusk="checkbox" type="checkbox" wire:model="prop" value="true" /> <div wire:dirty>Unsaved changes...</div> <div wire:dirty.remove>The data is in-sync...</div> </div> BLADE; } }) ->assertSee('The data is in-sync...') ->check('@checkbox') ->pause(50) ->assertDontSee('The data is in-sync') ->assertSee('Unsaved changes...') ->uncheck('@checkbox') ->assertSee('The data is in-sync...') ->assertDontSee('Unsaved changes...') ; } function test_can_use_dollar_dirty_to_check_if_component_is_dirty() { Livewire::visit(new class extends Component { public $title = ''; public function render() { return <<<'BLADE' <div> <input dusk="input" type="text" wire:model="title" /> <div x-show="$wire.$dirty()" dusk="dirty-indicator">Component is dirty</div> </div> BLADE; } }) ->assertNotVisible('@dirty-indicator') ->type('@input', 'Hello') ->pause(50) ->assertVisible('@dirty-indicator'); ; } function test_can_use_dollar_dirty_to_check_if_specific_property_is_dirty() { Livewire::visit(new class extends Component { public $title = ''; public $description = ''; public function render() { return <<<'BLADE' <div> <input dusk="title" type="text" wire:model="title" /> <input dusk="description" type="text" wire:model="description" /> <div x-show="$wire.$dirty('title')" dusk="title-dirty">Title is dirty</div> <div x-show="$wire.$dirty('description')" dusk="description-dirty">Description is dirty</div> </div> BLADE; } }) ->assertNotVisible('@title-dirty') ->assertNotVisible('@description-dirty') ->type('@title', 'Hello') ->pause(50) ->assertVisible('@title-dirty') ->assertNotVisible('@description-dirty') ->type('@description', 'World') ->pause(50) ->assertVisible('@title-dirty') ->assertVisible('@description-dirty') ; } function test_dollar_dirty_clears_after_network_request() { Livewire::visit(new class extends Component { public $title = ''; public function render() { return <<<'BLADE' <div> <input dusk="input" type="text" wire:model="title" /> <button dusk="commit" type="button" wire:click="$commit">Commit</button> <div x-show="$wire.$dirty()" dusk="dirty-indicator">Component is dirty</div> </div> BLADE; } }) ->assertNotVisible('@dirty-indicator') ->type('@input', 'Hello') ->pause(50) ->assertVisible('@dirty-indicator') ->waitForLivewire()->click('@commit') ->pause(50) ->assertNotVisible('@dirty-indicator') ; } function test_can_update_bound_value_from_lifecyle_hook() { Livewire::visit(new class extends Component { public $foo = null; public $bar = null; public function updatedFoo(): void { $this->bar = null; } public function render() { return <<<'BLADE' <div> <select wire:model.live="foo" dusk="fooSelect"> <option value=""></option> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> </select> <select wire:model="bar" dusk="barSelect"> <option value=""></option> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> </select> </div> BLADE; } }) ->select('@barSelect', 'one') ->waitForLivewire()->select('@fooSelect', 'one') ->assertSelected('@barSelect', '') ; } public function updates_dependent_select_options_correctly_when_wire_key_is_applied() { Livewire::visit(new class extends Component { public $parent = 'foo'; public $child = 'bar'; protected $options = [ 'foo' => [ 'bar', ], 'baz' => [ 'qux', ], ]; #[Computed] public function parentOptions(): array { return array_keys($this->options); } #[Computed] public function childOptions(): array { return $this->options[$this->parent]; } public function render(): string { return <<<'blade' <div> <select wire:model.live="parent" dusk="parent"> @foreach($this->parentOptions as $value) <option value="{{ $value }}">{{ $value }}</option> @endforeach </select> <select wire:model="child" dusk="child" wire:key="{{ $parent }}"> <option value>Select</option> @foreach($this->childOptions as $value) <option value="{{ $value }}">{{ $value }}</option> @endforeach </select> </div> blade; } }) ->waitForLivewire()->select('@parent', 'baz') ->assertSelected('@child', '') ->waitForLivewire()->select('@parent', 'foo') ->assertSelected('@child', 'bar'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportCompiledWireKeys/SupportCompiledWireKeys.php
src/Features/SupportCompiledWireKeys/SupportCompiledWireKeys.php
<?php namespace Livewire\Features\SupportCompiledWireKeys; use Illuminate\Support\Facades\Blade; use Livewire\ComponentHook; use function Livewire\on; class SupportCompiledWireKeys extends ComponentHook { public static $loopStack = []; public static $currentLoop = [ 'count' => null, 'index' => null, 'key' => null, ]; public static function provide() { on('flush-state', function () { static::$loopStack = []; static::$currentLoop = [ 'count' => null, 'index' => null, 'key' => null, ]; }); if (! config('livewire.smart_wire_keys', true)) { return; } static::registerPrecompilers(); } public static function registerPrecompilers() { Blade::precompiler(function ($contents) { $contents = static::compile($contents); return $contents; }); } public static function compile($contents) { // Strip out all livewire tag components as we don't want to match any of them... $placeholder = '<__livewire-component-placeholder__>'; $cleanedContents = preg_replace('/<livewire:[^>]+?\/>/is', $placeholder, $contents); // Handle `wire:key` attributes on elements... preg_match_all('/(?<=\s)wire:key\s*=\s*(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')/', $cleanedContents, $keys); foreach ($keys[0] as $index => $key) { $escapedKey = str_replace("'", "\'", $keys[1][$index]); $prefix = "<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processElementKey('{$escapedKey}', get_defined_vars()); ?>"; $contents = str_replace($key, $prefix . $key, $contents); } // Handle `wire:key` attributes on Blade components... $contents = preg_replace( '/(<\?php\s+\$component->withAttributes\(\[.*?\]\);\s*\?>)/s', "$1\n<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey(\$component); ?>\n", $contents ); return $contents; } public static function openLoop() { if (static::$currentLoop['count'] === null) { static::$currentLoop['count'] = 0; } else { static::$currentLoop['count']++; } static::$loopStack[] = static::$currentLoop; static::$currentLoop = [ 'count' => null, 'index' => null, 'key' => null, ]; } public static function startLoop($index) { static::$currentLoop['index'] = $index; } public static function endLoop() { static::$currentLoop = [ 'count' => null, 'index' => null, 'key' => null, ]; } public static function closeLoop() { static::$currentLoop = array_pop(static::$loopStack); } public static function processElementKey($keyString, $data) { $key = Blade::render($keyString, $data); static::$currentLoop['key'] = $key; } public static function processComponentKey($component) { if ($component->attributes->has('wire:key')) { static::$currentLoop['key'] = $component->attributes->get('wire:key'); } } public static function generateKey($deterministicBladeKey, $key = null) { $finalKey = $deterministicBladeKey; $loops = array_merge(static::$loopStack, [static::$currentLoop]); foreach ($loops as $loop) { if (isset($loop['key']) || isset($loop['index'])) { $finalKey .= isset($loop['key']) ? '-' . $loop['key'] : '-' . $loop['index']; } if (isset($loop['count'])) { $finalKey .= '-' . $loop['count']; } } if (isset($key) && $key !== '') { $finalKey .= '-' . $key; } return $finalKey; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportCompiledWireKeys/BrowserTest.php
src/Features/SupportCompiledWireKeys/BrowserTest.php
<?php namespace Livewire\Features\SupportCompiledWireKeys; use Livewire\Livewire; use Livewire\Component; class BrowserTest extends \Tests\BrowserTestCase { protected function defineEnvironment($app) { parent::defineEnvironment($app); $app['config']->set('livewire.smart_wire_keys', true); } public function test_nested_components_with_nested_and_sibling_loops_all_work_without_keys() { Livewire::visit([ new class () extends Component { public $items = ['B', 'D']; public function prepend() { $this->items = ['A','B','D']; } public function insert() { $this->items = ['B','C','D']; } public function append() { $this->items = ['B','D','E']; } public function render() { return <<<'HTML' <div> <button wire:click="prepend" dusk="prepend">Prepend</button> <button wire:click="insert" dusk="insert">Insert</button> <button wire:click="append" dusk="append">Append</button> <div> @foreach ($items as $item) <div wire:key="{{ $item }}"> @foreach ($items as $item2) <div wire:key="{{ $item2 }}"> <livewire:child :item="'loop-1-' . $item . $item2" dusk="child-loop-1-{{ $item }}-{{ $item2 }}" /> </div> @endforeach </div> @endforeach @foreach ($items as $item) <div wire:key="{{ $item }}"> @foreach ($items as $item2) <div wire:key="{{ $item2 }}"> <livewire:child :item="'loop-2-' . $item . $item2" dusk="child-loop-2-{{ $item }}-{{ $item2 }}" /> </div> @endforeach </div> @endforeach </div> </div> HTML; } }, 'child' => new class () extends Component { public $item; public $other; public function render() { return <<<'HTML' <div>Child: {{ $item }} <input wire:model="other" dusk="child-{{$item}}-input" /></div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertSee('Child: loop-1-BB') ->assertSee('Child: loop-1-BD') ->assertSee('Child: loop-1-DB') ->assertSee('Child: loop-1-DD') ->assertSee('Child: loop-2-BB') ->assertSee('Child: loop-2-BD') ->assertSee('Child: loop-2-DB') ->assertSee('Child: loop-2-DD') // Input some values to make sure state is retained... ->type('@child-loop-1-BB-input', '1bb') ->type('@child-loop-1-BD-input', '1bd') ->type('@child-loop-1-DB-input', '1db') ->type('@child-loop-1-DD-input', '1dd') ->type('@child-loop-2-BB-input', '2bb') ->type('@child-loop-2-BD-input', '2bd') ->type('@child-loop-2-DB-input', '2db') ->type('@child-loop-2-DD-input', '2dd') // Test prepending... ->waitForLivewire()->click('@prepend') ->assertConsoleLogHasNoErrors() ->assertSee('Child: loop-1-AA') ->assertSee('Child: loop-1-AB') ->assertSee('Child: loop-1-AD') ->assertSee('Child: loop-1-BA') ->assertSee('Child: loop-1-BB') ->assertSee('Child: loop-1-BD') ->assertSee('Child: loop-1-DA') ->assertSee('Child: loop-1-DB') ->assertSee('Child: loop-1-DD') ->assertSee('Child: loop-2-AA') ->assertSee('Child: loop-2-AB') ->assertSee('Child: loop-2-AD') ->assertSee('Child: loop-2-BA') ->assertSee('Child: loop-2-BB') ->assertSee('Child: loop-2-BD') ->assertSee('Child: loop-2-DA') ->assertSee('Child: loop-2-DB') ->assertSee('Child: loop-2-DD') ->assertValue('@child-loop-1-AA-input', '') ->assertValue('@child-loop-1-AB-input', '') ->assertValue('@child-loop-1-AD-input', '') ->assertValue('@child-loop-1-BA-input', '') ->assertValue('@child-loop-1-BB-input', '1bb') ->assertValue('@child-loop-1-BD-input', '1bd') ->assertValue('@child-loop-1-DA-input', '') ->assertValue('@child-loop-1-DB-input', '1db') ->assertValue('@child-loop-1-DD-input', '1dd') ->assertValue('@child-loop-2-AA-input', '') ->assertValue('@child-loop-2-AB-input', '') ->assertValue('@child-loop-2-AD-input', '') ->assertValue('@child-loop-2-BA-input', '') ->assertValue('@child-loop-2-BB-input', '2bb') ->assertValue('@child-loop-2-BD-input', '2bd') ->assertValue('@child-loop-2-DA-input', '') ->assertValue('@child-loop-2-DB-input', '2db') ->assertValue('@child-loop-2-DD-input', '2dd') // Test inserting... ->waitForLivewire()->click('@insert') ->assertConsoleLogHasNoErrors() ->assertSee('Child: loop-1-BB') ->assertSee('Child: loop-1-BC') ->assertSee('Child: loop-1-BD') ->assertSee('Child: loop-1-CB') ->assertSee('Child: loop-1-CC') ->assertSee('Child: loop-1-CD') ->assertSee('Child: loop-1-DB') ->assertSee('Child: loop-1-DC') ->assertSee('Child: loop-1-DD') ->assertSee('Child: loop-2-BB') ->assertSee('Child: loop-2-BC') ->assertSee('Child: loop-2-BD') ->assertSee('Child: loop-2-CB') ->assertSee('Child: loop-2-CC') ->assertSee('Child: loop-2-CD') ->assertSee('Child: loop-2-DB') ->assertSee('Child: loop-2-DC') ->assertSee('Child: loop-2-DD') ->assertValue('@child-loop-1-BB-input', '1bb') ->assertValue('@child-loop-1-BC-input', '') ->assertValue('@child-loop-1-BD-input', '1bd') ->assertValue('@child-loop-1-CB-input', '') ->assertValue('@child-loop-1-CC-input', '') ->assertValue('@child-loop-1-CD-input', '') ->assertValue('@child-loop-1-DB-input', '1db') ->assertValue('@child-loop-1-DC-input', '') ->assertValue('@child-loop-1-DD-input', '1dd') ->assertValue('@child-loop-2-BB-input', '2bb') ->assertValue('@child-loop-2-BC-input', '') ->assertValue('@child-loop-2-BD-input', '2bd') ->assertValue('@child-loop-2-CB-input', '') ->assertValue('@child-loop-2-CC-input', '') ->assertValue('@child-loop-2-CD-input', '') ->assertValue('@child-loop-2-DB-input', '2db') ->assertValue('@child-loop-2-DC-input', '') ->assertValue('@child-loop-2-DD-input', '2dd') // Test appending... ->waitForLivewire()->click('@append') ->assertConsoleLogHasNoErrors() ->assertSee('Child: loop-1-BB') ->assertSee('Child: loop-1-BD') ->assertSee('Child: loop-1-BE') ->assertSee('Child: loop-1-DB') ->assertSee('Child: loop-1-DD') ->assertSee('Child: loop-1-DE') ->assertSee('Child: loop-1-EB') ->assertSee('Child: loop-1-ED') ->assertSee('Child: loop-1-EE') ->assertSee('Child: loop-2-BB') ->assertSee('Child: loop-2-BD') ->assertSee('Child: loop-2-BE') ->assertSee('Child: loop-2-DB') ->assertSee('Child: loop-2-DD') ->assertSee('Child: loop-2-DE') ->assertSee('Child: loop-2-EB') ->assertSee('Child: loop-2-ED') ->assertSee('Child: loop-2-EE') ->assertValue('@child-loop-1-BB-input', '1bb') ->assertValue('@child-loop-1-BD-input', '1bd') ->assertValue('@child-loop-1-BE-input', '') ->assertValue('@child-loop-1-DB-input', '1db') ->assertValue('@child-loop-1-DD-input', '1dd') ->assertValue('@child-loop-1-DE-input', '') ->assertValue('@child-loop-1-EB-input', '') ->assertValue('@child-loop-1-ED-input', '') ->assertValue('@child-loop-1-EE-input', '') ->assertValue('@child-loop-2-BB-input', '2bb') ->assertValue('@child-loop-2-BD-input', '2bd') ->assertValue('@child-loop-2-BE-input', '') ->assertValue('@child-loop-2-DB-input', '2db') ->assertValue('@child-loop-2-DD-input', '2dd') ->assertValue('@child-loop-2-DE-input', '') ->assertValue('@child-loop-2-EB-input', '') ->assertValue('@child-loop-2-ED-input', '') ->assertValue('@child-loop-2-EE-input', '') ->assertConsoleLogHasNoErrors(); } // https://github.com/livewire/livewire/discussions/9037 public function test_scenario_1_different_root_element_with_lazy_passing() { Livewire::visit([ new class () extends Component { public function render() { return <<<'HTML' <div> <livewire:child lazy /> </div> HTML; } }, 'child' => new class () extends Component { public function placeholder() { return '<section></section>'; } public function render() { return <<<'HTML' <section>child</section> HTML; } }, ]) ->waitForLivewireToLoad() ->waitForText('child') ->assertSee('child') ->assertConsoleLogHasNoErrors(); } // https://github.com/livewire/livewire/discussions/9037 public function test_scenario_1_different_root_element_with_lazy_failing() { Livewire::visit([ new class () extends Component { public function render() { return <<<'HTML' <div> <livewire:child lazy /> </div> HTML; } }, 'child' => new class () extends Component { public function render() { return <<<'HTML' <section>child</section> HTML; } }, ]) ->waitForLivewireToLoad() ->waitForText('child') ->assertSee('child') ->assertConsoleLogHasNoErrors(); } // https://github.com/livewire/livewire/discussions/8921 public function test_scenario_2_keys_in_groups_passing() { Livewire::visit([ new #[\Livewire\Attributes\On('number-updated')] class () extends Component { public function render() { return <<<'HTML' <div> <h1>Section 1</h1> <div> @foreach (range(1, 2) as $number) <livewire:child section="1" :$number :key="$number" /> @endforeach </div> <h1>Section 2</h1> <div> @foreach (range(3, 4) as $number) <livewire:child section="2" :$number :key="$number" /> @endforeach </div> </div> HTML; } }, 'child' => new class () extends Component { public $section; public $number; public function render() { return <<<'HTML' <div> {{ $section }}-{{ $number }} - <button type="button" wire:click="$dispatch('number-updated')" dusk="{{ $section }}-{{ $number }}-button">Change number</button> </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertSee('1-1') ->assertSee('1-2') ->assertSee('2-3') ->assertSee('2-4') ->waitForLivewire()->click('@1-1-button') ->assertConsoleLogHasNoErrors() ->assertSee('1-1') ->assertSee('1-2') ->assertSee('2-3') ->assertSee('2-4'); } // https://github.com/livewire/livewire/discussions/8921 // https://github.com/livewire/livewire/discussions/5935#discussioncomment-11265936 public function test_scenario_2_keys_in_groups_failing() { $this->markTestSkipped('This is skipped because we have decided to not add smart wire keys to nested components if they already have a key. If this scenario keeps being a problem, we can look at fixing this in the future.'); Livewire::visit([ new #[\Livewire\Attributes\On('number-updated')] class () extends Component { public function render() { return <<<'HTML' <div> <h1>Section 1</h1> <div> @foreach (range(1, 2) as $number) <livewire:child section="1" :$number :key="$number" /> @endforeach </div> <h1>Section 2</h1> <div> @foreach (range(1, 2) as $number) <livewire:child section="2" :$number :key="$number" /> @endforeach </div> </div> HTML; } }, 'child' => new class () extends Component { public $section; public $number; public function render() { return <<<'HTML' <div> {{ $section }}-{{ $number }} - <button type="button" wire:click="$dispatch('number-updated')" dusk="{{ $section }}-{{ $number }}-button">Change number</button> </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertSee('1-1') ->assertSee('1-2') ->assertSee('2-1') ->assertSee('2-2') ->waitForLivewire()->click('@1-1-button') ->assertConsoleLogHasNoErrors() ->assertSee('1-1') ->assertSee('1-2') ->assertSee('2-1') ->assertSee('2-2'); } // https://github.com/livewire/livewire/discussions/8877 public function test_scenario_3_keys_on_nested_in_div_passing() { Livewire::visit([ new class () extends Component { public $prepend = false; #[\Livewire\Attributes\Computed] public function numbers() { if ($this->prepend) { return range(0, 2); } return range(1, 2); } public function render() { return <<<'HTML' <div> <button wire:click="$toggle('prepend')" dusk="prepend">Prepend</button> <div> @foreach ($this->numbers as $index => $number) <div wire:key="{{ $number }}"> <livewire:child :$number :key="$number" /> </div> @endforeach </div> </div> HTML; } }, 'child' => new class () extends Component { public $number; public function render() { return <<<'HTML' <div> {{ $number }} </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertSee('1') ->assertSee('2') ->waitForLivewire()->click('@prepend') ->assertConsoleLogHasNoErrors() ->assertSee('0') ->assertSee('1') ->assertSee('2'); } // https://github.com/livewire/livewire/discussions/8877 public function test_scenario_3_keys_on_nested_in_div_failing_1_no_key_on_nested_component() { Livewire::visit([ new class () extends Component { public $prepend = false; #[\Livewire\Attributes\Computed] public function numbers() { if ($this->prepend) { return range(0, 2); } return range(1, 2); } public function render() { return <<<'HTML' <div> <button wire:click="$toggle('prepend')" dusk="prepend">Prepend</button> <div> @foreach ($this->numbers as $index => $number) <div wire:key="{{ $number }}"> <livewire:child :$number /> </div> @endforeach </div> </div> HTML; } }, 'child' => new class () extends Component { public $number; public function render() { return <<<'HTML' <div> {{ $number }} </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertSee('1') ->assertSee('2') ->waitForLivewire()->click('@prepend') ->assertConsoleLogHasNoErrors() ->assertSee('0') ->assertSee('1') ->assertSee('2'); } // https://github.com/livewire/livewire/discussions/8877 // https://github.com/livewire/livewire/discussions/8800 // https://github.com/livewire/livewire/discussions/5935#discussioncomment-7091189 // https://github.com/livewire/livewire/discussions/8928 // https://github.com/livewire/livewire/discussions/8658 // https://github.com/livewire/livewire/discussions/8575 // https://github.com/livewire/livewire/discussions/6698 // https://github.com/livewire/livewire/discussions/6698#discussioncomment-7432437 // https://github.com/livewire/livewire/discussions/7193 // https://github.com/livewire/livewire/discussions/5802 public function test_scenario_3_keys_on_nested_in_div_failing_2_no_key_on_loop_root_element() { Livewire::visit([ new class () extends Component { public $prepend = false; #[\Livewire\Attributes\Computed] public function numbers() { if ($this->prepend) { return range(0, 2); } return range(1, 2); } public function render() { return <<<'HTML' <div> <button wire:click="$toggle('prepend')" dusk="prepend">Prepend</button> <div> @foreach ($this->numbers as $index => $number) <div> <livewire:child :$number :key="$number" /> </div> @endforeach </div> </div> HTML; } }, 'child' => new class () extends Component { public $number; public function render() { return <<<'HTML' <div> {{ $number }} </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertSee('1') ->assertSee('2') ->waitForLivewire()->click('@prepend') ->assertConsoleLogHasNoErrors() ->assertSee('0') ->assertSee('1') ->assertSee('2'); } // https://github.com/livewire/livewire/discussions/8921 public function test_scenario_3_keys_on_nested_in_div_failing_3_incorrect_key_on_loop_root_element() { Livewire::visit([ new class () extends Component { public $prepend = false; #[\Livewire\Attributes\Computed] public function numbers() { if ($this->prepend) { return range(0, 2); } return range(1, 2); } public function render() { return <<<'HTML' <div> <button wire:click="$toggle('prepend')" dusk="prepend">Prepend</button> <div> @foreach ($this->numbers as $index => $number) <div wire:key="number"> <livewire:child :$number :key="$number" /> </div> @endforeach </div> </div> HTML; } }, 'child' => new class () extends Component { public $number; public function render() { return <<<'HTML' <div> {{ $number }} </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertSee('1') ->assertSee('2') ->waitForLivewire()->click('@prepend') ->assertConsoleLogHasNoErrors() ->assertSee('0') ->assertSee('1') ->assertSee('2'); } // https://github.com/livewire/livewire/discussions/7697 public function test_scenario_3_keys_on_nested_in_div_failing_3_using_loop_index_in_key() { Livewire::visit([ new class () extends Component { public $changeNumbers = false; #[\Livewire\Attributes\Computed] public function numbers() { if ($this->changeNumbers) { return [2,1,4,3]; } return [1,2,3,4]; } public function render() { return <<<'HTML' <div> <button wire:click="$toggle('changeNumbers')" dusk="changeNumbers">Change numbers</button> <div> @foreach ($this->numbers as $index => $number) <div wire:key="{{ $number }}"> <livewire:child :$number :key="$index" /> </div> @endforeach </div> </div> HTML; } }, 'child' => new class () extends Component { public $number; public function render() { return <<<'HTML' <div> {{ $number }} </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertSee('1') ->assertSee('2') ->assertSee('3') ->assertSee('4') ->waitForLivewire()->click('@changeNumbers') ->assertConsoleLogHasNoErrors() ->assertSee('2') ->assertSee('1') ->assertSee('4') ->assertSee('3'); } // https://github.com/livewire/livewire/discussions/7282 public function test_scenario_4_conditionally_removed_elements_passing() { Livewire::visit([ new class () extends Component { public bool $showContents = false; public function render() { return <<<'HTML' <div> <div x-init="$el.remove()"> {{ __('Javascript required') }} </div> <button wire:click="$toggle('showContents')" dusk="showContents">Show/Hide</button> <div x-show="$wire.showContents" wire:key="container"> <livewire:child wire:key="test" /> </div> </div> HTML; } }, 'child' => new class () extends Component { public function render() { return <<<'HTML' <div>contents</div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertDontSee('contents') ->waitForLivewire()->click('@showContents') ->assertConsoleLogHasNoErrors() ->assertSee('contents'); } // https://github.com/livewire/livewire/discussions/7282 public function test_scenario_4_conditionally_removed_elements_failing_missing_key_on_wrapping_div() { Livewire::visit([ new class () extends Component { public bool $showContents = false; public function render() { return <<<'HTML' <div> <div x-init="$el.remove()"> {{ __('Javascript required') }} </div> <button wire:click="$toggle('showContents')" dusk="showContents">Show/Hide</button> <div x-show="$wire.showContents"> <livewire:child wire:key="test" /> </div> </div> HTML; } }, 'child' => new class () extends Component { public function render() { return <<<'HTML' <div>contents</div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertDontSee('contents') ->waitForLivewire()->click('@showContents') ->assertConsoleLogHasNoErrors() ->assertSee('contents'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportCompiledWireKeys/UnitTest.php
src/Features/SupportCompiledWireKeys/UnitTest.php
<?php namespace Livewire\Features\SupportCompiledWireKeys; use Illuminate\Support\Facades\Blade; use Livewire\Component; use Livewire\ComponentHookRegistry; use Livewire\Features\SupportMorphAwareBladeCompilation\SupportMorphAwareBladeCompilation; use Livewire\Livewire; use Livewire\Mechanisms\ExtendBlade\ExtendBlade; use PHPUnit\Framework\Attributes\DataProvider; use function Livewire\invade; class UnitTest extends \Tests\TestCase { public function setUp(): void { parent::setUp(); Livewire::flushState(); config()->set('livewire.smart_wire_keys', true); // Reload the features so the config is loaded and the precompilers are registered if required... $this->reloadFeatures(); } public function test_keys_are_not_compiled_when_smart_wire_keys_are_disabled() { Livewire::flushState(); config()->set('livewire.smart_wire_keys', false); // Reload the features so the config is loaded and the precompilers are registered if required... $this->reloadFeatures(); $compiled = $this->compile('<div wire:key="foo">'); $this->assertStringNotContainsString('<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processElementKey', $compiled); } public function test_child_keys_are_correctly_generated() { app('livewire')->component('keys-parent', KeysParent::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParent::class); $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(2, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B', 'lw-XXXXXXXX-0-0-D' ], $childKeys); } public function test_child_keys_are_correctly_generated_when_the_parent_data_is_prepended() { app('livewire')->component('keys-parent', KeysParent::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParent::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('prepend'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(3, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-A', 'lw-XXXXXXXX-0-0-B', 'lw-XXXXXXXX-0-0-D' ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_are_correctly_generated_when_the_parent_data_is_inserted() { app('livewire')->component('keys-parent', KeysParent::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParent::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('insert'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(3, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B', 'lw-XXXXXXXX-0-0-C', 'lw-XXXXXXXX-0-0-D' ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_are_correctly_generated_when_the_parent_data_is_appended() { app('livewire')->component('keys-parent', KeysParent::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParent::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('append'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(3, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B', 'lw-XXXXXXXX-0-0-D', 'lw-XXXXXXXX-0-0-E' ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_in_a_nested_loop_are_correctly_generated() { app('livewire')->component('keys-parent-with-nested-loops', KeysParentWithNestedLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithNestedLoops::class); $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(4, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B-0-B', 'lw-XXXXXXXX-0-0-B-0-D', 'lw-XXXXXXXX-0-0-D-0-B', 'lw-XXXXXXXX-0-0-D-0-D', ], $childKeys); } public function test_child_keys_in_a_nested_loop_are_correctly_generated_when_the_parent_data_is_prepended() { app('livewire')->component('keys-parent-with-nested-loops', KeysParentWithNestedLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithNestedLoops::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('prepend'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(9, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-A-0-A', 'lw-XXXXXXXX-0-0-A-0-B', 'lw-XXXXXXXX-0-0-A-0-D', 'lw-XXXXXXXX-0-0-B-0-A', 'lw-XXXXXXXX-0-0-B-0-B', 'lw-XXXXXXXX-0-0-B-0-D', 'lw-XXXXXXXX-0-0-D-0-A', 'lw-XXXXXXXX-0-0-D-0-B', 'lw-XXXXXXXX-0-0-D-0-D', ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_in_a_nested_loop_are_correctly_generated_when_the_parent_data_is_inserted() { app('livewire')->component('keys-parent-with-nested-loops', KeysParentWithNestedLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithNestedLoops::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('insert'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(9, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B-0-B', 'lw-XXXXXXXX-0-0-B-0-C', 'lw-XXXXXXXX-0-0-B-0-D', 'lw-XXXXXXXX-0-0-C-0-B', 'lw-XXXXXXXX-0-0-C-0-C', 'lw-XXXXXXXX-0-0-C-0-D', 'lw-XXXXXXXX-0-0-D-0-B', 'lw-XXXXXXXX-0-0-D-0-C', 'lw-XXXXXXXX-0-0-D-0-D', ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_in_a_nested_loop_are_correctly_generated_when_the_parent_data_is_appended() { app('livewire')->component('keys-parent-with-nested-loops', KeysParentWithNestedLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithNestedLoops::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('append'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(9, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B-0-B', 'lw-XXXXXXXX-0-0-B-0-D', 'lw-XXXXXXXX-0-0-B-0-E', 'lw-XXXXXXXX-0-0-D-0-B', 'lw-XXXXXXXX-0-0-D-0-D', 'lw-XXXXXXXX-0-0-D-0-E', 'lw-XXXXXXXX-0-0-E-0-B', 'lw-XXXXXXXX-0-0-E-0-D', 'lw-XXXXXXXX-0-0-E-0-E', ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_in_a_sibling_loop_are_correctly_generated() { app('livewire')->component('keys-parent-with-sibling-loops', KeysParentWithSiblingLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithSiblingLoops::class); $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(4, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B', 'lw-XXXXXXXX-0-0-D', 'lw-XXXXXXXX-1-1-B', 'lw-XXXXXXXX-1-1-D', ], $childKeys); } public function test_child_keys_in_a_sibling_loop_are_correctly_generated_when_the_parent_data_is_prepended() { app('livewire')->component('keys-parent-with-sibling-loops', KeysParentWithSiblingLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithSiblingLoops::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('prepend'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(6, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-A', 'lw-XXXXXXXX-0-0-B', 'lw-XXXXXXXX-0-0-D', 'lw-XXXXXXXX-1-1-A', 'lw-XXXXXXXX-1-1-B', 'lw-XXXXXXXX-1-1-D', ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_in_a_sibling_loop_are_correctly_generated_when_the_parent_data_is_inserted() { app('livewire')->component('keys-parent-with-sibling-loops', KeysParentWithSiblingLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithSiblingLoops::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('insert'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(6, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B', 'lw-XXXXXXXX-0-0-C', 'lw-XXXXXXXX-0-0-D', 'lw-XXXXXXXX-1-1-B', 'lw-XXXXXXXX-1-1-C', 'lw-XXXXXXXX-1-1-D', ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_in_a_sibling_loop_are_correctly_generated_when_the_parent_data_is_appended() { app('livewire')->component('keys-parent-with-sibling-loops', KeysParentWithSiblingLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithSiblingLoops::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('append'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(6, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B', 'lw-XXXXXXXX-0-0-D', 'lw-XXXXXXXX-0-0-E', 'lw-XXXXXXXX-1-1-B', 'lw-XXXXXXXX-1-1-D', 'lw-XXXXXXXX-1-1-E', ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_in_sibling_and_nested_loops_are_correctly_generated() { app('livewire')->component('keys-parent-with-sibling-and-nested-loops', KeysParentWithSiblingAndNestedLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithSiblingAndNestedLoops::class); $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(16, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B-0-B', 'lw-XXXXXXXX-0-0-B-0-D', 'lw-XXXXXXXX-1-0-B-1-B', 'lw-XXXXXXXX-1-0-B-1-D', 'lw-XXXXXXXX-0-0-D-0-B', 'lw-XXXXXXXX-0-0-D-0-D', 'lw-XXXXXXXX-1-0-D-1-B', 'lw-XXXXXXXX-1-0-D-1-D', 'lw-XXXXXXXX-2-1-B-0-B', 'lw-XXXXXXXX-2-1-B-0-D', 'lw-XXXXXXXX-3-1-B-1-B', 'lw-XXXXXXXX-3-1-B-1-D', 'lw-XXXXXXXX-2-1-D-0-B', 'lw-XXXXXXXX-2-1-D-0-D', 'lw-XXXXXXXX-3-1-D-1-B', 'lw-XXXXXXXX-3-1-D-1-D', ], $childKeys); } public function test_child_keys_in_sibling_and_nested_loops_are_correctly_generated_when_the_parent_data_is_prepended() { app('livewire')->component('keys-parent-with-sibling-and-nested-loops', KeysParentWithSiblingAndNestedLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithSiblingAndNestedLoops::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('prepend'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(36, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-A-0-A', 'lw-XXXXXXXX-0-0-A-0-B', 'lw-XXXXXXXX-0-0-A-0-D', 'lw-XXXXXXXX-1-0-A-1-A', 'lw-XXXXXXXX-1-0-A-1-B', 'lw-XXXXXXXX-1-0-A-1-D', 'lw-XXXXXXXX-0-0-B-0-A', 'lw-XXXXXXXX-0-0-B-0-B', 'lw-XXXXXXXX-0-0-B-0-D', 'lw-XXXXXXXX-1-0-B-1-A', 'lw-XXXXXXXX-1-0-B-1-B', 'lw-XXXXXXXX-1-0-B-1-D', 'lw-XXXXXXXX-0-0-D-0-A', 'lw-XXXXXXXX-0-0-D-0-B', 'lw-XXXXXXXX-0-0-D-0-D', 'lw-XXXXXXXX-1-0-D-1-A', 'lw-XXXXXXXX-1-0-D-1-B', 'lw-XXXXXXXX-1-0-D-1-D', 'lw-XXXXXXXX-2-1-A-0-A', 'lw-XXXXXXXX-2-1-A-0-B', 'lw-XXXXXXXX-2-1-A-0-D', 'lw-XXXXXXXX-3-1-A-1-A', 'lw-XXXXXXXX-3-1-A-1-B', 'lw-XXXXXXXX-3-1-A-1-D', 'lw-XXXXXXXX-2-1-B-0-A', 'lw-XXXXXXXX-2-1-B-0-B', 'lw-XXXXXXXX-2-1-B-0-D', 'lw-XXXXXXXX-3-1-B-1-A', 'lw-XXXXXXXX-3-1-B-1-B', 'lw-XXXXXXXX-3-1-B-1-D', 'lw-XXXXXXXX-2-1-D-0-A', 'lw-XXXXXXXX-2-1-D-0-B', 'lw-XXXXXXXX-2-1-D-0-D', 'lw-XXXXXXXX-3-1-D-1-A', 'lw-XXXXXXXX-3-1-D-1-B', 'lw-XXXXXXXX-3-1-D-1-D', ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_in_sibling_and_nested_loops_are_correctly_generated_when_the_parent_data_is_inserted() { app('livewire')->component('keys-parent-with-sibling-and-nested-loops', KeysParentWithSiblingAndNestedLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithSiblingAndNestedLoops::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('insert'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(36, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B-0-B', 'lw-XXXXXXXX-0-0-B-0-C', 'lw-XXXXXXXX-0-0-B-0-D', 'lw-XXXXXXXX-1-0-B-1-B', 'lw-XXXXXXXX-1-0-B-1-C', 'lw-XXXXXXXX-1-0-B-1-D', 'lw-XXXXXXXX-0-0-C-0-B', 'lw-XXXXXXXX-0-0-C-0-C', 'lw-XXXXXXXX-0-0-C-0-D', 'lw-XXXXXXXX-1-0-C-1-B', 'lw-XXXXXXXX-1-0-C-1-C', 'lw-XXXXXXXX-1-0-C-1-D', 'lw-XXXXXXXX-0-0-D-0-B', 'lw-XXXXXXXX-0-0-D-0-C', 'lw-XXXXXXXX-0-0-D-0-D', 'lw-XXXXXXXX-1-0-D-1-B', 'lw-XXXXXXXX-1-0-D-1-C', 'lw-XXXXXXXX-1-0-D-1-D', 'lw-XXXXXXXX-2-1-B-0-B', 'lw-XXXXXXXX-2-1-B-0-C', 'lw-XXXXXXXX-2-1-B-0-D', 'lw-XXXXXXXX-3-1-B-1-B', 'lw-XXXXXXXX-3-1-B-1-C', 'lw-XXXXXXXX-3-1-B-1-D', 'lw-XXXXXXXX-2-1-C-0-B', 'lw-XXXXXXXX-2-1-C-0-C', 'lw-XXXXXXXX-2-1-C-0-D', 'lw-XXXXXXXX-3-1-C-1-B', 'lw-XXXXXXXX-3-1-C-1-C', 'lw-XXXXXXXX-3-1-C-1-D', 'lw-XXXXXXXX-2-1-D-0-B', 'lw-XXXXXXXX-2-1-D-0-C', 'lw-XXXXXXXX-2-1-D-0-D', 'lw-XXXXXXXX-3-1-D-1-B', 'lw-XXXXXXXX-3-1-D-1-C', 'lw-XXXXXXXX-3-1-D-1-D', ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_child_keys_in_sibling_and_nested_loops_are_correctly_generated_when_the_parent_data_is_appended() { app('livewire')->component('keys-parent-with-sibling-and-nested-loops', KeysParentWithSiblingAndNestedLoops::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithSiblingAndNestedLoops::class); $childrenBefore = invade($component)->lastState->getSnapshot()['memo']['children']; $component->call('append'); $childrenAfter = invade($component)->lastState->getSnapshot()['memo']['children']; $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(36, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B-0-B', 'lw-XXXXXXXX-0-0-B-0-D', 'lw-XXXXXXXX-0-0-B-0-E', 'lw-XXXXXXXX-1-0-B-1-B', 'lw-XXXXXXXX-1-0-B-1-D', 'lw-XXXXXXXX-1-0-B-1-E', 'lw-XXXXXXXX-0-0-D-0-B', 'lw-XXXXXXXX-0-0-D-0-D', 'lw-XXXXXXXX-0-0-D-0-E', 'lw-XXXXXXXX-1-0-D-1-B', 'lw-XXXXXXXX-1-0-D-1-D', 'lw-XXXXXXXX-1-0-D-1-E', 'lw-XXXXXXXX-0-0-E-0-B', 'lw-XXXXXXXX-0-0-E-0-D', 'lw-XXXXXXXX-0-0-E-0-E', 'lw-XXXXXXXX-1-0-E-1-B', 'lw-XXXXXXXX-1-0-E-1-D', 'lw-XXXXXXXX-1-0-E-1-E', 'lw-XXXXXXXX-2-1-B-0-B', 'lw-XXXXXXXX-2-1-B-0-D', 'lw-XXXXXXXX-2-1-B-0-E', 'lw-XXXXXXXX-3-1-B-1-B', 'lw-XXXXXXXX-3-1-B-1-D', 'lw-XXXXXXXX-3-1-B-1-E', 'lw-XXXXXXXX-2-1-D-0-B', 'lw-XXXXXXXX-2-1-D-0-D', 'lw-XXXXXXXX-2-1-D-0-E', 'lw-XXXXXXXX-3-1-D-1-B', 'lw-XXXXXXXX-3-1-D-1-D', 'lw-XXXXXXXX-3-1-D-1-E', 'lw-XXXXXXXX-2-1-E-0-B', 'lw-XXXXXXXX-2-1-E-0-D', 'lw-XXXXXXXX-2-1-E-0-E', 'lw-XXXXXXXX-3-1-E-1-B', 'lw-XXXXXXXX-3-1-E-1-D', 'lw-XXXXXXXX-3-1-E-1-E', ], $childKeys); // Ensure that the children from before match the children after including ID and element... foreach ($childrenBefore as $key => $childBefore) { $this->assertEquals($childBefore, $childrenAfter[$key]); } } public function test_when_using_a_for_else_statement_child_keys_are_correctly_generated() { app('livewire')->component('keys-parent-with-for-else', KeysParentWithForElse::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithForElse::class); $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(2, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-0-0-B', 'lw-XXXXXXXX-0-0-D' ], $childKeys); } public function test_when_using_a_for_else_statement_and_empty_is_shown_child_keys_are_correctly_generated() { app('livewire')->component('keys-parent-with-for-else', KeysParentWithForElse::class); app('livewire')->component('keys-child', KeysChild::class); $component = Livewire::test(KeysParentWithForElse::class) ->call('empty'); $childKeys = array_keys(invade($component)->lastState->getSnapshot()['memo']['children']); $this->assertEquals(1, count($childKeys)); $this->assertKeysMatchPattern([ 'lw-XXXXXXXX-1', // There should be no loop suffixes here, because the empty block is shown... ], $childKeys); } public function test_loop_stack_defaults_are_correctly_set() { $this->assertEquals([], SupportCompiledWireKeys::$loopStack); $this->assertEquals( [ 'count' => null, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } public function test_we_can_open_a_loop() { SupportCompiledWireKeys::openLoop(); $this->assertEquals( [ [ 'count' => 0, 'index' => null, 'key' => null, ], ], SupportCompiledWireKeys::$loopStack ); $this->assertEquals( [ 'count' => null, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } public function test_we_can_close_a_loop() { SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::closeLoop(); $this->assertEquals( [], SupportCompiledWireKeys::$loopStack ); $this->assertEquals( [ 'count' => 0, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } public function test_we_can_open_a_second_loop_after_the_first_one_is_closed() { SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::closeLoop(); SupportCompiledWireKeys::openLoop(); $this->assertEquals( [ [ 'count' => 1, 'index' => null, 'key' => null, ], ], SupportCompiledWireKeys::$loopStack ); $this->assertEquals( [ 'count' => null, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } public function test_we_can_close_a_second_loop_after_the_first_one_is_closed() { SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::closeLoop(); SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::closeLoop(); $this->assertEquals( [], SupportCompiledWireKeys::$loopStack ); $this->assertEquals( [ 'count' => 1, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } public function test_we_can_open_an_inner_loop_while_the_first_one_is_open() { SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::openLoop(); $this->assertEquals( [ [ 'count' => 0, 'index' => null, 'key' => null, ], [ 'count' => 0, 'index' => null, 'key' => null, ], ], SupportCompiledWireKeys::$loopStack ); $this->assertEquals( [ 'count' => null, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } public function test_we_can_close_an_inner_loop_while_the_first_one_is_open() { SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::closeLoop(); $this->assertEquals( [ [ 'count' => 0, 'index' => null, 'key' => null, ], ], SupportCompiledWireKeys::$loopStack ); $this->assertEquals( [ 'count' => 0, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } public function test_an_inner_loop_is_removed_when_the_outer_loop_is_closed() { SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::closeLoop(); SupportCompiledWireKeys::closeLoop(); $this->assertEquals( [], SupportCompiledWireKeys::$loopStack ); $this->assertEquals( [ 'count' => 0, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } public function test_a_second_outer_loop_is_added_when_the_first_one_is_closed_and_all_inner_loops_are_removed() { SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::closeLoop(); SupportCompiledWireKeys::closeLoop(); SupportCompiledWireKeys::openLoop(); $this->assertEquals( [ [ 'count' => 1, 'index' => null, 'key' => null, ], ], SupportCompiledWireKeys::$loopStack ); $this->assertEquals( [ 'count' => null, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } public function test_a_second_inner_loop_is_added_when_the_first_inner_loop_is_closed() { SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::openLoop(); SupportCompiledWireKeys::closeLoop(); SupportCompiledWireKeys::openLoop(); $this->assertEquals( [ [ 'count' => 0, 'index' => null, 'key' => null, ], [ 'count' => 1, 'index' => null, 'key' => null, ], ], SupportCompiledWireKeys::$loopStack ); $this->assertEquals( [ 'count' => null, 'index' => null, 'key' => null, ], SupportCompiledWireKeys::$currentLoop ); } #[DataProvider('elementsTestProvider')] public function test_we_can_correctly_find_wire_keys_on_elements_only_but_not_blade_or_livewire_components($occurrences, $template) { $compiled = $this->compile($template); $this->assertOccurrences($occurrences, '<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processElementKey', $compiled); } #[DataProvider('bladeComponentsTestProvider')] public function test_we_can_correctly_find_wire_keys_on_blade_components_only_but_not_elements_or_livewire_components($occurrences, $template) { $compiled = $this->compile($template); $this->assertOccurrences($occurrences, '<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey', $compiled); } public static function elementsTestProvider() { return [ [ 1, <<<'HTML' <div wire:key="foo"> </div> HTML ], [ 2, <<<'HTML' <div wire:key="foo"> <div wire:key="bar"> </div> </div> HTML ], [ 0, <<<'HTML' <div> <livewire:child wire:key="foo" /> </div> HTML ], [ 0, <<<'HTML' <div> @foreach ($children as $child) <livewire:child :wire:key="$child, 5, '_', STR_PAD_BOTH)" /> @endforeach </div> HTML ], [ 0, <<<'HTML' <div> @livewire('child', [], key('foo')) </div> HTML ], [ 0,
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireLoading/BrowserTest.php
src/Features/SupportWireLoading/BrowserTest.php
<?php namespace Livewire\Features\SupportWireLoading; use Livewire\Component; use Livewire\Form; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { function test_can_wire_target_to_a_form_object_property() { Livewire::visit(new class extends Component { public PostFormStub $form; public $localText = ''; public function updating() { // Need to delay the update so that Dusk can catch the loading state change in the DOM. usleep(500000); } public function render() { return <<<'HTML' <div> <section> <span wire:loading.remove wire:target="localText"> Loaded localText... </span> <span wire:loading wire:target="localText" > Loading localText... </span> <input type="text" dusk="localInput" wire:model.live.debounce.100ms="localText"> {{ $localText }} </section> <section> <span wire:loading.remove wire:target="form.text"> Loaded form.text... </span> <span wire:loading wire:target="form.text" > Loading form.text... </span> <input type="text" dusk="formInput" wire:model.live.debounce.100ms="form.text"> {{ $form->text }} </section> </div> HTML; } }) ->waitForText('Loaded localText') ->assertSee('Loaded localText') ->type('@localInput', 'Text') ->waitUntilMissingText('Loaded localText') ->assertDontSee('Loaded localText') ->waitForText('Loaded localText') ->assertSee('Loaded localText') ->waitForText('Loaded form.text') ->assertSee('Loaded form.text') ->type('@formInput', 'Text') ->waitUntilMissingText('Loaded form.text') ->assertDontSee('Loaded form.text') ->waitForText('Loaded form.text') ->assertSee('Loaded form.text') ; } function test_wire_loading_remove_works_with_renderless_methods() { Livewire::visit(new class extends Component { #[\Livewire\Attributes\Renderless] public function doSomething() { // Need to delay the update so that Dusk can catch the loading state change in the DOM. usleep(500000); } public function render() { return <<<'HTML' <div> <button wire:click="doSomething" dusk="button"> <span wire:loading.remove>Do something</span> <span wire:loading>...</span> </button> </div> HTML; } }) ->waitForText('Do something') ->click('@button') ->waitForText('...') ->assertDontSee('Do something') ->waitForText('Do something') ->assertDontSee('...') ; } function test_wire_loading_attr_doesnt_conflict_with_exist_one() { Livewire::visit(new class extends Component { public $localText = ''; public function updating() { // Need to delay the update so that Dusk can catch the loading state change in the DOM. usleep(250000); } public function render() { return <<<'HTML' <div> <section> <button disabled dusk="button" wire:loading.attr="disabled" wire:target="localText"> Submit </button> <input type="text" dusk="localInput" wire:model.live.debounce.100ms="localText"> {{ $localText }} </section> </div> HTML; } }) ->waitForText('Submit') ->assertSee('Submit') ->assertAttribute('@button', 'disabled', 'true') ->type('@localInput', 'Text') ->assertAttribute('@button', 'disabled', 'true') ->waitForText('Text') ->assertAttribute('@button', 'disabled', 'true') ; } function test_wire_loading_delay_is_removed_after_being_triggered_once() { /** * The (broken) scenario: * - first request takes LONGER than the wire:loading.delay, so the loader shows (and hides) once * - second request takes SHORTER than the wire:loading.delay, the loader shows, but never hides */ Livewire::visit(new class extends Component { public $stuff; public $count = 0; public function updating() { // Need to delay the update, but only on the first request if ($this->count === 0) { usleep(500000); } $this->count++; } public function render() { return <<<'HTML' <div> <div wire:loading.delay> <span>Loading...</span> </div> <input wire:model.live="stuff" dusk="input" type="text"> </div> HTML; } }) ->type('@input', 'Hello Caleb') ->waitForText('Loading...') ->assertSee('Loading...') ->waitUntilMissingText('Loading...') ->assertDontSee('Loading...') ->type('@input', 'Bye Caleb') ->pause(500) // wait for the loader to show when it shouldn't (second request is fast) ->assertDontSee('Loading...') ; } function test_wire_loading_targets_single_correct_element() { /* * Previously */ Livewire::visit(new class extends Component { public $myModel; public function mount() { $this->myModel = [ 'prop' => 'one', 'prop2' => 'two', ]; } public function updating() { // Need to delay the update so that Dusk can catch the loading state change in the DOM. sleep(2); } public function render() { return <<<'HTML' <div> <input type="text" wire:model.live="myModel.prop" dusk="input"> <div wire:loading wire:target="myModel.prop">Loading "prop"...</div> <input type="text" wire:model.live="myModel.prop2" dusk="input2"> <div wire:loading wire:target="myModel.prop2">Loading "prop2"...</div> <div wire:loading wire:target="myModel">Loading "myModel"...</div> </div> HTML; } }) ->type('@input', 'Foo') ->waitForText('Loading "prop"...') ->assertSee('Loading "prop"...') ->assertSee('Loading "myModel"...') ->assertDontSee('Loading "prop2"...') ->waitUntilMissingText('Loading "prop"...') ->type('@input2', 'Hello Caleb') ->waitForText('Loading "prop2"...') ->assertSee('Loading "prop2"...') ->assertSee('Loading "myModel"...') ->assertDontSee('Loading "prop"...') ; } function test_inverted_wire_target_hides_loading_for_specified_action() { Livewire::visit(new class extends Component { public function render() { return <<<'HTML' <div> <button wire:click="process1Function" dusk="process1Button">Process 1</button> <button wire:click="process2Function" dusk="process2Button">Process 2</button> <button wire:click="resetFunction" dusk="resetButton">Reset</button> <div wire:loading wire:target.except="process1Function, process2Function" dusk="loadingIndicator"> Waiting to process... </div> <div wire:loading wire:target.except="resetFunction" dusk="loadingIndicator2"> Processing... </div> </div> HTML; } public function process1Function() { usleep(500000); // Simulate some processing time. } public function process2Function() { usleep(500000); // Simulate some processing time. } public function resetFunction() { usleep(500000); // Simulate reset time. } }) ->press('@resetButton') ->waitForText('Waiting to process...') ->assertSee('Waiting to process...') ->assertDontSee('Processing...') ->waitUntilMissingText('Waiting to process...') ->press('@process1Button') ->pause(250) ->assertDontSee('Waiting to process...') ->assertSee('Processing...') ->press('@resetButton') ->waitForText('Waiting to process...') ->assertSee('Waiting to process...') ->waitUntilMissingText('Waiting to process...') ->press('@process2Button') ->pause(250) ->assertDontSee('Waiting to process...') ->assertSee('Processing...') ; } function test_wire_target_works_with_multiple_function_including_multiple_params() { Livewire::visit(new class extends Component { public function render() { return <<<'HTML' <div> <button wire:click="processFunction('1', 2)" dusk="process1Button">Process 1 and 2</button> <button wire:click="processFunction('3', 4)" dusk="process2Button">Process 3 adn 4</button> <button wire:click="resetFunction" dusk="resetButton">Reset</button> <div wire:loading wire:target="resetFunction" dusk="loadingIndicator"> Waiting to process... </div> <div wire:loading wire:target="processFunction('1', 2), processFunction('3', 4)" dusk="loadingIndicator2"> Processing... </div> </div> HTML; } public function processFunction(string $value) { usleep(500000); // Simulate some processing time. } public function resetFunction() { usleep(500000); // Simulate reset time. } }) ->press('@resetButton') ->pause(250) ->waitForText('Waiting to process...') ->assertSee('Waiting to process...') ->assertDontSee('Processing...') ->waitUntilMissingText('Waiting to process...') ->press('@process1Button') ->pause(250) ->assertDontSee('Waiting to process...') ->assertSee('Processing...') ->press('@resetButton') ->waitForText('Waiting to process...') ->assertSee('Waiting to process...') ->waitUntilMissingText('Waiting to process...') ->press('@process2Button') ->pause(250) ->assertDontSee('Waiting to process...') ->assertSee('Processing...') ; } function test_wire_target_works_with_multiple_function_multiple_params_using_js_helper() { Livewire::visit(new class extends Component { public function mountAction(string $action, array $params = [], array $context = []) { usleep(500000); // Simulate some processing time. } public function render() { return <<<'HTML' <div> <button wire:click="mountAction('add', {{ \Illuminate\Support\Js::from(['block' => 'name']) }}, { schemaComponent: 'tableFiltersForm.queryBuilder.rules' })" dusk="mountButton">Mount</button> <div wire:loading wire:target="mountAction('add', {{ \Illuminate\Support\Js::from(['block' => 'name']) }}, { schemaComponent: 'tableFiltersForm.queryBuilder.rules' })"> Mounting... </div> </div> HTML; } }) ->assertDontSee('Mounting...') ->press('@mountButton') ->waitForText('Mounting...') ->assertSee('Mounting...') ->pause(400) ->waitUntilMissingText('Mounting...') ->assertDontSee('Mounting...') ; } function test_wire_target_works_with_function_JSONparse_params() { Livewire::visit(new class extends Component { public function render() { return <<<'HTML' <div> <button wire:click="processFunction(@js(['bar' => 'baz']))" dusk="processButton">Process</button> <button wire:click="resetFunction" dusk="resetButton">Reset</button> <div wire:loading wire:target="resetFunction" dusk="loadingIndicator"> Waiting to process... </div> <div wire:loading wire:target="processFunction" dusk="loadingIndicator2"> Processing... </div> </div> HTML; } public function processFunction(mixed $value) { usleep(500000); // Simulate some processing time. } public function resetFunction() { usleep(500000); // Simulate reset time. } }) ->press('@resetButton') ->pause(250) ->waitForText('Waiting to process...') ->assertSee('Waiting to process...') ->assertDontSee('Processing...') ->waitUntilMissingText('Waiting to process...') ->press('@processButton') ->pause(250) ->assertDontSee('Waiting to process...') ->assertSee('Processing...') ; } /** function test_inverted_wire_target_hides_loading_for_file_upload() { Storage::persistentFake('tmp-for-tests'); Livewire::visit(new class extends Component { use WithFileUploads; public $file1, $file2; public function render() { return <<<'HTML' <div> <input type="file" wire:model="file1" dusk="file1Input"> <input type="file" wire:model="file2" dusk="file2Input"> <button wire:click="resetFunction" dusk="resetButton">Reset</button> <div wire:loading wire:target.except="file1" dusk="loadingIndicator"> Waiting to process... </div> </div> HTML; } public function resetFunction() { usleep(500000); // Simulate reset time. } }) ->pause(10000000) ->press('@resetButton') ->waitForText('Waiting to process...') ->assertSee('Waiting to process...') ->waitUntilMissingText('Waiting to process...') ->attach('@file1Input', __DIR__ . '/browser_test_image.png') ->assertDontSee('Waiting to process...') ->attach('@file2Input', __DIR__ . '/browser_test_image.png') ->waitForText('Waiting to process...') ->assertSee('Waiting to process...') ; } */ function test_wire_loading_doesnt_error_when_class_contains_two_consecutive_spaces() { Livewire::visit(new class extends Component { public $myModel; public function mount() { $this->myModel = [ 'prop' => 'one', ]; } public function updating() { // Need to delay the update so that Dusk can catch the loading state change in the DOM. sleep(2); } public function render() { return <<<'HTML' <div> <input type="text" wire:model.live="myModel.prop" dusk="input"> <div wire:loading.class="foo bar" wire:target="myModel.prop">{{ $myModel['prop'] }}</div> </div> HTML; } }) ->type('@input', 'Foo') ->waitForText('Foo') ->assertSee('Foo') ; } function test_wire_loading_targets_exclude_wire_navigate() { Livewire::visit(new class extends Component { public function hydrate() { sleep(1); } public function render() { return <<<'HTML' <div> <a href="/otherpage" wire:navigate dusk="link" class="text-blue-500" wire:loading.class="text-red-500">Link</a> <button type="button" wire:click="$refresh" dusk="refresh-button">Refresh</button> </div> HTML; } }) ->assertHasClass('@link', 'text-blue-500') ->click('@refresh-button') ->pause(5) ->assertHasClass('@link', 'text-red-500') ; } public function test_a_component_can_show_loading_without_showing_island_loading() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { usleep(500 * 1000); // 500ms } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="component-slow-request">Component slow request</button> <div wire:loading.block dusk="component-loading">Loading...</div> <div> @island <button wire:click="slowRequest" dusk="island-slow-request">Island slow request</button> <div wire:loading.block dusk="island-loading">Island loading...</div> @endisland </div> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertMissing('@component-loading') ->assertMissing('@island-loading') ->click('@component-slow-request') // Wait for the Livewire request to start... ->pause(10) ->assertVisible('@component-loading') ->assertMissing('@island-loading') // Wait for the Livewire request to finish... ->waitUntilMissingText('Loading...') ->assertMissing('@component-loading') ->assertMissing('@island-loading') ; } public function test_an_island_can_show_loading_without_showing_component_loading() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { usleep(500 * 1000); // 500ms } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="component-slow-request">Component slow request</button> <div wire:loading.block dusk="component-loading">Loading...</div> <div> @island <button wire:click="slowRequest" dusk="island-slow-request">Island slow request</button> <div wire:loading.block dusk="island-loading">Island loading...</div> @endisland </div> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertMissing('@component-loading') ->assertMissing('@island-loading') ->click('@island-slow-request') // Wait for the Livewire request to start... ->pause(10) ->assertMissing('@component-loading') ->assertVisible('@island-loading') // Wait for the Livewire request to finish... ->waitUntilMissingText('Island loading...') ->assertMissing('@component-loading') ->assertMissing('@island-loading') ; } public function test_an_island_and_component_can_show_different_loading_states() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { usleep(500 * 1000); // 500ms } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="component-slow-request">Component slow request</button> <div wire:loading.block dusk="component-loading">Loading...</div> <div> @island <button wire:click="slowRequest" dusk="island-slow-request">Island slow request</button> <div wire:loading.block dusk="island-loading">Island loading...</div> @endisland </div> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertMissing('@component-loading') ->assertMissing('@island-loading') // Run the component request and then the island request... ->click('@component-slow-request') // Wait for the component request to start... ->pause(10) ->assertVisible('@component-loading') ->assertMissing('@island-loading') // Wait a bit before starting the island request... ->pause(200) ->click('@island-slow-request') // Wait for the island request to start... ->pause(10) ->assertVisible('@component-loading') ->assertVisible('@island-loading') // Wait for the component request to finish... ->waitUntilMissingText('Loading...') ->assertMissing('@component-loading') ->assertVisible('@island-loading') // Wait for the island request to finish... ->waitUntilMissingText('Island loading...') ->assertMissing('@component-loading') ->assertMissing('@island-loading') // Run the island request and then the component request... ->click('@island-slow-request') // Wait for the island request to start... ->pause(10) ->assertMissing('@component-loading') ->assertVisible('@island-loading') // Wait a bit before starting the component request... ->pause(200) ->click('@component-slow-request') // Wait for the component request to start... ->pause(10) ->assertVisible('@component-loading') ->assertVisible('@island-loading') // Wait for the island request to finish... ->waitUntilMissingText('Island loading...') ->assertVisible('@component-loading') ->assertMissing('@island-loading') // Wait for the component request to finish... ->waitUntilMissingText('Loading...') ->assertMissing('@component-loading') ->assertMissing('@island-loading') ; } public function test_a_component_can_show_targeted_loading() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { usleep(500 * 1000); // 500ms } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="component-slow-request">Component slow request</button> <div wire:loading.block dusk="component-loading">Loading...</div> <div wire:loading.block wire:target="slowRequest" dusk="component-loading-targeted">Component loading targeted...</div> <div wire:loading.block wire:target="otherRequest" dusk="component-loading-targeted-other">Component loading targeted other...</div> <div> @island <button wire:click="slowRequest" dusk="island-slow-request">Island slow request</button> <div wire:loading.block dusk="island-loading">Island loading...</div> <div wire:loading.block wire:target="slowRequest" dusk="island-loading-targeted">Island loading targeted...</div> <div wire:loading.block wire:target="otherRequest" dusk="island-loading-targeted-other">Island loading targeted other...</div> @endisland </div> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertMissing('@component-loading') ->assertMissing('@component-loading-targeted') ->assertMissing('@component-loading-targeted-other') ->assertMissing('@island-loading') ->assertMissing('@island-loading-targeted') ->assertMissing('@island-loading-targeted-other') ->click('@component-slow-request') // Wait for the component request to start... ->pause(10) ->assertVisible('@component-loading') ->assertVisible('@component-loading-targeted') ->assertMissing('@component-loading-targeted-other') ->assertMissing('@island-loading') ->assertMissing('@island-loading-targeted') ->assertMissing('@island-loading-targeted-other') // Wait for the component request to finish... ->waitUntilMissingText('Loading...') ->assertMissing('@component-loading') ->assertMissing('@component-loading-targeted') ->assertMissing('@component-loading-targeted-other') ->assertMissing('@island-loading') ->assertMissing('@island-loading-targeted') ->assertMissing('@island-loading-targeted-other') ; } public function test_an_island_can_show_targeted_loading() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { usleep(500 * 1000); // 500ms } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="component-slow-request">Component slow request</button> <div wire:loading.block dusk="component-loading">Loading...</div> <div wire:loading.block wire:target="slowRequest" dusk="component-loading-targeted">Component loading targeted...</div> <div wire:loading.block wire:target="otherRequest" dusk="component-loading-targeted-other">Component loading targeted other...</div> <div> @island <button wire:click="slowRequest" dusk="island-slow-request">Island slow request</button> <div wire:loading.block dusk="island-loading">Island loading...</div> <div wire:loading.block wire:target="slowRequest" dusk="island-loading-targeted">Island loading targeted...</div> <div wire:loading.block wire:target="otherRequest" dusk="island-loading-targeted-other">Island loading targeted other...</div> @endisland </div> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertMissing('@component-loading') ->assertMissing('@component-loading-targeted') ->assertMissing('@component-loading-targeted-other') ->assertMissing('@island-loading') ->assertMissing('@island-loading-targeted') ->assertMissing('@island-loading-targeted-other') ->click('@island-slow-request') // Wait for the island request to start... ->pause(10) ->assertMissing('@component-loading') ->assertMissing('@component-loading-targeted') ->assertMissing('@component-loading-targeted-other') ->assertVisible('@island-loading') ->assertVisible('@island-loading-targeted') ->assertMissing('@island-loading-targeted-other') // Wait for the island request to finish... ->waitUntilMissingText('Island loading...') ->assertMissing('@component-loading') ->assertMissing('@component-loading-targeted') ->assertMissing('@component-loading-targeted-other') ->assertMissing('@island-loading') ->assertMissing('@island-loading-targeted') ->assertMissing('@island-loading-targeted-other') ; } public function test_a_second_component_request_doesnt_cancel_loading() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { usleep(500 * 1000); // 500ms } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="component-slow-request">Component slow request</button> <div wire:loading.block dusk="component-loading">Loading...</div> <div> @island <button wire:click="slowRequest" dusk="island-slow-request">Island slow request</button> <div wire:loading.block dusk="island-loading">Island loading...</div> @endisland </div> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertMissing('@component-loading') ->assertMissing('@island-loading') ->click('@component-slow-request') // Wait for the component request to start... ->pause(10) ->assertVisible('@component-loading') ->assertMissing('@island-loading') // Pause for a bit before starting the second request... ->pause(300) ->click('@component-slow-request') // Wait for the component request to start... ->pause(10) ->assertVisible('@component-loading') ->assertMissing('@island-loading')
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportValidation/HandlesValidation.php
src/Features/SupportValidation/HandlesValidation.php
<?php namespace Livewire\Features\SupportValidation; use function Livewire\invade; use function Livewire\store; use Illuminate\Contracts\Support\Arrayable; use Livewire\Wireable; use Livewire\Exceptions\MissingRulesException; use Livewire\Drawer\Utils; use Illuminate\Validation\ValidationException; use Illuminate\Support\MessageBag; use Illuminate\Support\Facades\Validator; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; use Illuminate\Support\ViewErrorBag; use Livewire\Form; trait HandlesValidation { protected $withValidatorCallback; protected $rulesFromOutside = []; protected $messagesFromOutside = []; protected $validationAttributesFromOutside = []; public function addRulesFromOutside($rules) { $this->rulesFromOutside[] = $rules; } public function addMessagesFromOutside($messages) { $this->messagesFromOutside[] = $messages; } public function addValidationAttributesFromOutside($validationAttributes) { $this->validationAttributesFromOutside[] = $validationAttributes; } public function getErrorBag() { if (! store($this)->has('errorBag')) { $previouslySharedErrors = app('view')->getShared()['errors'] ?? new ViewErrorBag; $this->setErrorBag($previouslySharedErrors->getMessages()); } return store($this)->get('errorBag'); } public function addError($name, $message) { return $this->getErrorBag()->add($name, $message); } public function setErrorBag($bag) { return store($this)->set('errorBag', $bag instanceof MessageBag ? $bag : new MessageBag($bag) ); } public function resetErrorBag($field = null) { $fields = (array) $field; if (empty($fields)) { $errorBag = new MessageBag; $this->setErrorBag($errorBag); return $errorBag; } $this->setErrorBag( $this->errorBagExcept($fields) ); } public function clearValidation($field = null) { $this->resetErrorBag($field); } public function resetValidation($field = null) { $this->resetErrorBag($field); } public function errorBagExcept($field) { $fields = (array) $field; return new MessageBag( collect($this->getErrorBag()) ->reject(function ($messages, $messageKey) use ($fields) { return collect($fields)->some(function ($field) use ($messageKey) { return str($messageKey)->is($field); }); }) ->toArray() ); } public function getRules() { $rulesFromComponent = []; if (method_exists($this, 'rules')) $rulesFromComponent = $this->rules(); else if (property_exists($this, 'rules')) $rulesFromComponent = $this->rules; $rulesFromOutside = array_merge_recursive( ...array_map( fn($i) => value($i), $this->rulesFromOutside ) ); return array_merge($rulesFromComponent, $rulesFromOutside); } protected function getMessages() { $messages = []; if (method_exists($this, 'messages')) $messages = $this->messages(); elseif (property_exists($this, 'messages')) $messages = $this->messages; $messagesFromOutside = array_merge( ...array_map( fn($i) => value($i), $this->messagesFromOutside ) ); return array_merge($messages, $messagesFromOutside); } protected function getValidationAttributes() { $validationAttributes = []; if (method_exists($this, 'validationAttributes')) $validationAttributes = $this->validationAttributes(); elseif (property_exists($this, 'validationAttributes')) $validationAttributes = $this->validationAttributes; $validationAttributesFromOutside = array_merge( ...array_map( fn($i) => value($i), $this->validationAttributesFromOutside ) ); return array_merge($validationAttributes, $validationAttributesFromOutside); } protected function getValidationCustomValues() { if (method_exists($this, 'validationCustomValues')) return $this->validationCustomValues(); if (property_exists($this, 'validationCustomValues')) return $this->validationCustomValues; return []; } public function rulesForModel($name) { if (empty($this->getRules())) return collect(); return collect($this->getRules()) ->filter(function ($value, $key) use ($name) { return Utils::beforeFirstDot($key) === $name; }); } public function hasRuleFor($dotNotatedProperty) { $propertyWithStarsInsteadOfNumbers = $this->ruleWithNumbersReplacedByStars($dotNotatedProperty); // If property has numeric indexes in it, if ($dotNotatedProperty !== $propertyWithStarsInsteadOfNumbers) { return collect($this->getRules())->keys()->contains($propertyWithStarsInsteadOfNumbers); } return collect($this->getRules()) ->keys() ->map(function ($key) { return (string) str($key)->before('.*'); })->contains($dotNotatedProperty); } public function ruleWithNumbersReplacedByStars($dotNotatedProperty) { // Convert foo.0.bar.1 -> foo.*.bar.* return (string) str($dotNotatedProperty) // Replace all numeric indexes with an array wildcard: (.0., .10., .007.) => .*. // In order to match overlapping numerical indexes (foo.1.2.3.4.name), // We need to use a positive look-behind, that's technically all the magic here. // For better understanding, see: https://regexr.com/5d1n3 ->replaceMatches('/(?<=(\.))\d+\./', '*.') // Replace all numeric indexes at the end of the name with an array wildcard // (Same as the previous regex, but ran only at the end of the string) // For better undestanding, see: https://regexr.com/5d1n6 ->replaceMatches('/\.\d+$/', '.*'); } public function missingRuleFor($dotNotatedProperty) { return ! $this->hasRuleFor($dotNotatedProperty); } public function withValidator($callback) { $this->withValidatorCallback = $callback; return $this; } protected function checkRuleMatchesProperty($rules, $data) { collect($rules) ->keys() ->each(function($ruleKey) use ($data) { throw_unless( array_key_exists(Utils::beforeFirstDot($ruleKey), $data), new \Exception('No property found for validation: ['.$ruleKey.']') ); }); } public function validate($rules = null, $messages = [], $attributes = []) { $isUsingGlobalRules = is_null($rules); [$rules, $messages, $attributes] = $this->providedOrGlobalRulesMessagesAndAttributes($rules, $messages, $attributes); $data = $this->prepareForValidation( $this->getDataForValidation($rules) ); $this->checkRuleMatchesProperty($rules, $data); $ruleKeysToShorten = $this->getModelAttributeRuleKeysToShorten($data, $rules); $data = $this->unwrapDataForValidation($data); $validator = Validator::make($data, $rules, $messages, $attributes); if ($this->withValidatorCallback) { call_user_func($this->withValidatorCallback, $validator); $this->withValidatorCallback = null; } $this->shortenModelAttributesInsideValidator($ruleKeysToShorten, $validator); $customValues = $this->getValidationCustomValues(); if (! empty($customValues)) { $validator->addCustomValues($customValues); } if ($this->isRootComponent() && $isUsingGlobalRules) { $validatedData = $this->withFormObjectValidators($validator, fn () => $validator->validate(), fn ($form) => $form->validate()); } else { $validatedData = $validator->validate(); } $this->resetErrorBag(); return $validatedData; } protected function isRootComponent() { // Because this trait is used for form objects as well... return $this instanceof \Livewire\Component; } protected function withFormObjectValidators($validator, $validateSelf, $validateForm) { $cumulativeErrors = new MessageBag; $cumulativeData = []; $formExceptions = []; // First, run sub-validators... foreach ($this->getFormObjects() as $form) { try { // Only run sub-validator if the sub-validator has rules... if (filled($form->getRules())) { $cumulativeData = array_merge($cumulativeData, $validateForm($form)); } } catch (ValidationException $e) { $cumulativeErrors->merge($e->validator->errors()); $formExceptions[] = $e; } } // Now run main validator... try { $cumulativeData = array_merge($cumulativeData, $validateSelf()); } catch (ValidationException $e) { // If the main validator has errors, merge them with subs and rethrow... $e->validator->errors()->merge($cumulativeErrors); throw $e; } // If main validation passed, go through other sub-validation exceptions // and throw the first one with the cumulative messages... foreach ($formExceptions as $e) { $exceptionErrorKeys = $e->validator->errors()->keys(); $remainingErrors = Arr::except($cumulativeErrors->messages(), $exceptionErrorKeys); $e->validator->errors()->merge($remainingErrors); throw $e; } // All validation has passed, we can return the data... return $cumulativeData; } public function validateOnly($field, $rules = null, $messages = [], $attributes = [], $dataOverrides = []) { $property = (string) str($field)->before('.'); // If validating a field in a form object, defer validation to that form object... if ( $this->isRootComponent() && ($form = $this->all()[$property] ?? false) instanceof Form ) { $stripPrefix = (string) str($field)->after('.'); return $form->validateOnly($stripPrefix, $rules, $messages, $attributes, $dataOverrides); } $isUsingGlobalRules = is_null($rules); [$rules, $messages, $attributes] = $this->providedOrGlobalRulesMessagesAndAttributes($rules, $messages, $attributes); // Loop through rules and swap any wildcard '*' with keys from field, then filter down to only // rules that match the field, but return the rules without wildcard characters replaced, // so that custom attributes and messages still work as they need wildcards to work. $rulesForField = collect($rules) ->filter(function($value, $rule) use ($field) { if(! str($field)->is($rule)) { return false; } $fieldArray = str($field)->explode('.'); $ruleArray = str($rule)->explode('.'); for($i = 0; $i < count($fieldArray); $i++) { if(isset($ruleArray[$i]) && $ruleArray[$i] === '*') { $ruleArray[$i] = $fieldArray[$i]; } } $rule = $ruleArray->join('.'); return $field === $rule; }); $ruleForField = $rulesForField->keys()->first(); $rulesForField = $rulesForField->toArray(); $ruleKeysForField = array_keys($rulesForField); $data = array_merge($this->getDataForValidation($rules), $dataOverrides); $data = $this->prepareForValidation($data); $this->checkRuleMatchesProperty($rules, $data); $ruleKeysToShorten = $this->getModelAttributeRuleKeysToShorten($data, $rules); $data = $this->unwrapDataForValidation($data); // If a matching rule is found, then filter collections down to keys specified in the field, // while leaving all other data intact. If a key isn't specified and instead there is a // wildcard '*' then leave that whole collection intact. This ensures that any rules // that depend on other fields/ properties still work. if ($ruleForField) { $ruleArray = str($ruleForField)->explode('.'); $fieldArray = str($field)->explode('.'); $data = $this->filterCollectionDataDownToSpecificKeys($data, $ruleArray, $fieldArray); } $validator = Validator::make($data, $rulesForField, $messages, $attributes); if ($this->withValidatorCallback) { call_user_func($this->withValidatorCallback, $validator); $this->withValidatorCallback = null; } $this->shortenModelAttributesInsideValidator($ruleKeysToShorten, $validator); $customValues = $this->getValidationCustomValues(); if (!empty($customValues)) { $validator->addCustomValues($customValues); } try { $result = $validator->validate(); } catch (ValidationException $e) { $messages = $e->validator->getMessageBag(); invade($e->validator)->messages = $messages->merge( $this->errorBagExcept($ruleKeysForField) ); throw $e; } $this->resetErrorBag($ruleKeysForField); return $result; } protected function filterCollectionDataDownToSpecificKeys($data, $ruleKeys, $fieldKeys) { // Filter data down to specified keys in collections, but leave all other data intact if (count($ruleKeys)) { $ruleKey = $ruleKeys->shift(); $fieldKey = $fieldKeys->shift(); if ($fieldKey == '*') { // If the specified field has a '*', then loop through the collection and keep the whole collection intact. foreach ($data as $key => $value) { $data[$key] = $this->filterCollectionDataDownToSpecificKeys($value, $ruleKeys, $fieldKeys); } } else { // Otherwise filter collection down to a specific key $keyData = data_get($data, $fieldKey, null); if ($ruleKey == '*') { $data = []; } data_set($data, $fieldKey, $this->filterCollectionDataDownToSpecificKeys($keyData, $ruleKeys, $fieldKeys)); } } return $data; } protected function getModelAttributeRuleKeysToShorten($data, $rules) { // If a model ($foo) is a property, and the validation rule is // "foo.bar", then set the attribute to just "bar", so that // the validation message is shortened and more readable. $toShorten = []; foreach ($rules as $key => $value) { $propertyName = Utils::beforeFirstDot($key); if ($data[$propertyName] instanceof Model) { $toShorten[] = $key; } } return $toShorten; } protected function shortenModelAttributesInsideValidator($ruleKeys, $validator) { foreach ($ruleKeys as $key) { if (str($key)->snake()->replace('_', ' ')->is($validator->getDisplayableAttribute($key))) { $validator->addCustomAttributes([$key => $validator->getDisplayableAttribute(Utils::afterFirstDot($key))]); } } } protected function providedOrGlobalRulesMessagesAndAttributes($rules, $messages, $attributes) { $rules = is_null($rules) ? $this->getRules() : $rules; // Before we warn the user about not providing validation rules, // Let's make sure there are no form objects that contain them... $allRules = $rules; if ($this->isRootComponent()) { foreach ($this->getFormObjects() as $form) { $allRules = array_merge($allRules, $form->getRules()); } } throw_if(empty($allRules), new MissingRulesException($this)); $messages = empty($messages) ? $this->getMessages() : $messages; $attributes = empty($attributes) ? $this->getValidationAttributes() : $attributes; return [$rules, $messages, $attributes]; } protected function getDataForValidation($rules) { return Utils::getPublicPropertiesDefinedOnSubclass($this); } protected function unwrapDataForValidation($data) { return collect($data)->map(function ($value) { $synth = app('livewire')->findSynth($value, $this); if ($synth && method_exists($synth, 'unwrapForValidation')) return $synth->unwrapForValidation($value); else if ($value instanceof Arrayable) return $value->toArray(); return $value; })->all(); } protected function prepareForValidation($attributes) { return $attributes; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportValidation/BaseRule.php
src/Features/SupportValidation/BaseRule.php
<?php namespace Livewire\Features\SupportValidation; use Attribute; #[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_ALL)] class BaseRule extends BaseValidate { // This class is kept here for backwards compatibility... }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportValidation/SupportValidation.php
src/Features/SupportValidation/SupportValidation.php
<?php namespace Livewire\Features\SupportValidation; use Livewire\Drawer\Utils; use Illuminate\Validation\ValidationException; use Illuminate\Support\ViewErrorBag; use Livewire\ComponentHook; class SupportValidation extends ComponentHook { function hydrate($memo) { $this->component->setErrorBag( $memo['errors'] ?? [] ); } function render($view, $data) { $errors = (new ViewErrorBag)->put('default', $this->component->getErrorBag()); $revert = Utils::shareWithViews('errors', $errors); return function () use ($revert) { // After the component has rendered, let's revert our global // sharing of the "errors" variable with blade views... $revert(); }; } function renderIsland($name, $view, $data) { $errors = (new ViewErrorBag)->put('default', $this->component->getErrorBag()); $revert = Utils::shareWithViews('errors', $errors); return function () use ($revert) { $revert(); }; } function dehydrate($context) { $errors = $this->component->getErrorBag()->toArray(); // Only persist errors that were born from properties on the component // and not from custom validators (Validator::make) that were run. $context->addMemo('errors', collect($errors) ->filter(function ($value, $key) { return Utils::hasProperty($this->component, $key); }) ->toArray() ); } function exception($e, $stopPropagation) { if (! $e instanceof ValidationException) return; $this->component->setErrorBag($e->validator->errors()); $stopPropagation(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportValidation/TestsValidation.php
src/Features/SupportValidation/TestsValidation.php
<?php namespace Livewire\Features\SupportValidation; use Closure; use Illuminate\Contracts\Validation\Rule; use Illuminate\Contracts\Validation\ValidationRule; use function Livewire\store; use PHPUnit\Framework\Assert as PHPUnit; use Illuminate\Support\Str; use Illuminate\Support\MessageBag; use Illuminate\Support\Arr; trait TestsValidation { function errors() { $validator = store($this->target)->get('testing.validator'); if ($validator) return $validator->errors(); $errors = store($this->target)->get('testing.errors'); if ($errors) return $errors; return new MessageBag; } function failedRules() { $validator = store($this->target)->get('testing.validator'); return $validator ? $validator->failed() : []; } public function assertHasErrors($keys = []) { $errors = $this->errors(); PHPUnit::assertTrue($errors->isNotEmpty(), 'Component has no errors.'); $keys = (array) $keys; foreach ($keys as $key => $value) { if (is_int($key)) { $this->makeErrorAssertion($value); } else { $this->makeErrorAssertion($key, $value); } } return $this; } protected function makeErrorAssertion($key = null, $value = null) { $errors = $this->errors(); $messages = $errors->get($key); $failed = $this->failedRules() ?: []; $failedRules = array_keys(Arr::get($failed, $key, [])); $failedRules = array_map(function (string $rule) { if (is_a($rule, ValidationRule::class, true) || is_a($rule, Rule::class, true)) { return $rule; } return Str::snake($rule); }, $failedRules); PHPUnit::assertTrue($errors->isNotEmpty(), 'Component has no errors.'); if (is_null($value)) { PHPUnit::assertTrue($errors->has($key), "Component missing error: $key"); } elseif ($value instanceof Closure) { PHPUnit::assertTrue($value($failedRules, $messages)); } elseif (is_array($value)) { foreach ((array) $value as $ruleOrMessage) { $this->assertErrorMatchesRuleOrMessage($failedRules, $messages, $key, $ruleOrMessage); } } else { $this->assertErrorMatchesRuleOrMessage($failedRules, $messages, $key, $value); } return $this; } protected function assertErrorMatchesRuleOrMessage($rules, $messages, $key, $ruleOrMessage) { if (Str::contains($ruleOrMessage, ':')){ $ruleOrMessage = Str::before($ruleOrMessage, ':'); } if (in_array($ruleOrMessage, $rules)) { PHPUnit::assertTrue(true); return; } // If the provided rule/message isn't a failed rule, let's check to see if it's a message... PHPUnit::assertContains($ruleOrMessage, $messages, "Component has no matching failed rule or error message [{$ruleOrMessage}] for [{$key}] attribute."); } public function assertHasNoErrors($keys = []) { $errors = $this->errors(); if (empty($keys)) { PHPUnit::assertTrue($errors->isEmpty(), 'Component has errors: "'.implode('", "', $errors->keys()).'"'); return $this; } $keys = (array) $keys; foreach ($keys as $key => $value) { if (is_int($key)) { PHPUnit::assertFalse($errors->has($value), "Component has error: $value"); } else { $failed = $this->failedRules() ?: []; $rules = array_keys(Arr::get($failed, $key, [])); foreach ((array) $value as $rule) { if (Str::contains($rule, ':')){ $rule = Str::before($rule, ':'); } PHPUnit::assertNotContains(Str::studly($rule), $rules, "Component has [{$rule}] errors for [{$key}] attribute."); } } } return $this; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportValidation/UnitTest.php
src/Features/SupportValidation/UnitTest.php
<?php namespace Livewire\Features\SupportValidation; use Tests\TestComponent; use Livewire\Wireable; use Livewire\Livewire; use Livewire\Exceptions\MissingRulesException; use Livewire\Component; use Livewire\Attributes\Validate; use Livewire\Attributes\Rule; use Illuminate\Support\ViewErrorBag; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Collection; class UnitTest extends \Tests\TestCase { public function test_update_triggers_rule_attribute() { Livewire::test(new class extends TestComponent { #[Validate('required')] public $foo = ''; #[Validate('required')] public $bar = ''; function clear() { $this->clearValidation(); } function save() { $this->validate(); } }) ->set('bar', 'testing...') ->assertHasNoErrors() ->set('foo', '') ->assertHasErrors(['foo' => 'required']) ->call('clear') ->assertHasNoErrors() ->call('save') ->assertHasErrors([ 'foo' => 'required', ]); } public function test_deprecated_rule_alias_can_be_used() { Livewire::test(new class extends TestComponent { #[Rule('required')] public $foo = ''; #[Rule('required')] public $bar = ''; function clear() { $this->clearValidation(); } function save() { $this->validate(); } }) ->set('bar', 'testing...') ->assertHasNoErrors() ->set('foo', '') ->assertHasErrors(['foo' => 'required']) ->call('clear') ->assertHasNoErrors() ->call('save') ->assertHasErrors([ 'foo' => 'required', ]); } public function test_validate_can_be_used_without_a_rule() { Livewire::test(new class extends TestComponent { #[Validate] public $foo = ''; public $bar = ''; public function rules() { return [ 'foo' => 'required', 'bar' => 'required', ]; } function clear() { $this->clearValidation(); } function save() { $this->validate(); } }) ->set('foo', 'testing...') ->assertHasNoErrors() ->set('foo', '') ->assertHasErrors(['foo' => 'required']); } public function test_realtime_validation_can_be_opted_out_of() { Livewire::test(new class extends TestComponent { #[Validate('required|min:3', onUpdate: false)] public $foo = ''; #[Validate('required|min:3')] public $bar = ''; function clear() { $this->clearValidation(); } function save() { $this->validate(); } }) ->assertHasNoErrors() ->set('bar', 'te') ->assertHasErrors() ->set('bar', 'testing...') ->assertHasNoErrors() ->set('foo', 'te') ->assertHasNoErrors() ->call('save') ->assertHasErrors(); } public function test_rule_attribute_supports_custom_attribute() { Livewire::test(new class extends TestComponent { #[Validate('required|min:3', attribute: 'The Foo')] public $foo = ''; function clear() { $this->clearValidation(); } function save() { $this->validate(); } }) ->set('foo', 'te') ->assertHasErrors() ->tap(function ($component) { $messages = $component->errors()->getMessages(); $this->assertEquals('The The Foo field must be at least 3 characters.', $messages['foo'][0]); }) ; } public function test_rule_attribute_supports_custom_attribute_as_alias() { Livewire::test(new class extends TestComponent { #[Validate('required|min:3', as: 'The Foo')] public $foo = ''; function clear() { $this->clearValidation(); } function save() { $this->validate(); } }) ->set('foo', 'te') ->assertHasErrors() ->tap(function ($component) { $messages = $component->errors()->getMessages(); $this->assertEquals('The The Foo field must be at least 3 characters.', $messages['foo'][0]); }) ; } public function test_rule_attribute_alias_is_translatable() { Lang::addLines(['translatable.foo' => 'Translated Foo'], App::currentLocale()); Livewire::test(new class extends TestComponent { #[Validate('required|min:3', as: 'translatable.foo')] public $foo = ''; }) ->set('foo', 'te') ->assertHasErrors() ->tap(function ($component) { $messages = $component->errors()->getMessages(); $this->assertEquals('The Translated Foo field must be at least 3 characters.', $messages['foo'][0]); }) ; } public function test_rule_attribute_alias_is_translatable_with_array() { Lang::addLines(['translatable.foo' => 'Translated Foo'], App::currentLocale()); Livewire::test(new class extends TestComponent { #[Validate('required|min:3', as: ['foo' => 'translatable.foo'])] public $foo = ''; }) ->set('foo', 'te') ->assertHasErrors() ->tap(function ($component) { $messages = $component->errors()->getMessages(); $this->assertEquals('The Translated Foo field must be at least 3 characters.', $messages['foo'][0]); }) ; } public function test_rule_attribute_alias_translation_can_be_opted_out() { Lang::addLines(['translatable.foo' => 'Translated Foo'], App::currentLocale()); Livewire::test(new class extends TestComponent { #[Validate('required|min:3', as: 'translatable.foo', translate: false)] public $foo = ''; }) ->set('foo', 'te') ->assertHasErrors() ->tap(function ($component) { $messages = $component->errors()->getMessages(); $this->assertEquals('The translatable.foo field must be at least 3 characters.', $messages['foo'][0]); }) ; } public function test_rule_attribute_supports_custom_messages() { Livewire::test(new class extends TestComponent { #[Validate('min:5', message: 'Your foo is too short.')] public $foo = ''; function clear() { $this->clearValidation(); } function save() { $this->validate(); } }) ->set('foo', 'te') ->assertHasErrors() ->tap(function ($component) { $messages = $component->errors()->getMessages(); $this->assertEquals('Your foo is too short.', $messages['foo'][0]); }) ; } public function test_rule_attribute_supports_custom_messages_when_using_repeated_attributes() { Livewire::test(new class extends TestComponent { #[Validate('required', message: 'Please provide a post title')] #[Validate('min:3', message: 'This title is too short')] public $title = ''; }) ->set('title', '') ->assertHasErrors(['title' => 'required']) ->tap(function ($component) { $messages = $component->errors()->getMessages(); $this->assertEquals('Please provide a post title', $messages['title'][0]); }) ; } public function test_rule_attribute_message_is_translatable() { Lang::addLines(['translatable.foo' => 'Your foo is too short.'], App::currentLocale()); Livewire::test(new class extends TestComponent { #[Validate('min:5', message: 'translatable.foo')] public $foo = ''; }) ->set('foo', 'te') ->assertHasErrors() ->tap(function ($component) { $messages = $component->errors()->getMessages(); $this->assertEquals('Your foo is too short.', $messages['foo'][0]); }) ; } public function test_rule_attribute_message_is_translatable_with_array() { Lang::addLines(['translatable.foo' => 'Your foo is too short.'], App::currentLocale()); Livewire::test(new class extends TestComponent { #[Validate('min:5', message: ['min' => 'translatable.foo'])] public $foo = ''; }) ->set('foo', 'te') ->assertHasErrors() ->tap(function ($component) { $messages = $component->errors()->getMessages(); $this->assertEquals('Your foo is too short.', $messages['foo'][0]); }) ; } public function test_rule_attributes_can_contain_rules_for_multiple_properties() { Livewire::test(new class extends TestComponent { #[Validate(['foo' => 'required', 'bar' => 'required'])] public $foo = ''; public $bar = ''; function clear() { $this->clearValidation(); } function save() { $this->validate(); } }) ->set('bar', '') ->assertHasNoErrors() ->set('foo', '') ->assertHasErrors(['foo' => 'required']) ->call('clear') ->assertHasNoErrors() ->call('save') ->assertHasErrors([ 'foo' => 'required', 'bar' => 'required', ]); } public function test_rule_attributes_can_contain_multiple_rules() { Livewire::test(new class extends TestComponent { #[Validate(['required', 'min:2', 'max:3'])] public $foo = ''; }) ->set('foo', '') ->assertHasErrors(['foo' => 'required']) ->set('foo', '1') ->assertHasErrors(['foo' => 'min']) ->set('foo', '12345') ->assertHasErrors(['foo' => 'max']) ->set('foo', 'ok') ->assertHasNoErrors() ; } public function test_rule_attributes_can_contain_multiple_rules_userland(): void { Livewire::test(new class extends TestComponent { #[\Livewire\Attributes\Validate('required')] #[\Livewire\Attributes\Validate('min:2')] #[\Livewire\Attributes\Validate('max:3')] public $foo = ''; }) ->set('foo', '') ->assertHasErrors(['foo' => 'required']) ->set('foo', '1') ->assertHasErrors(['foo' => 'min']) ->set('foo', '12345') ->assertHasErrors(['foo' => 'max']) ->set('foo', 'ok') ->assertHasNoErrors() ; } public function test_rule_attributes_can_be_repeated() { Livewire::test(new class extends TestComponent { #[Validate('required')] #[Validate('min:2')] #[Validate('max:3')] public $foo = ''; #[ Validate('sometimes'), Validate('max:1') ] public $bar = ''; }) ->set('foo', '') ->assertHasErrors(['foo' => 'required']) ->set('foo', '1') ->assertHasErrors(['foo' => 'min']) ->set('foo', '12345') ->assertHasErrors(['foo' => 'max']) ->set('foo', 'ok') ->assertHasNoErrors() ->set('bar', '12') ->assertHasErrors(['bar' => 'max']) ->set('bar', '1') ->assertHasNoErrors() ; } public function test_validate_with_rules_property() { Livewire::test(ComponentWithRulesProperty::class) ->set('foo', '') ->call('save') ->assertHasErrors(['foo' => 'required']); } public function test_validate_only_with_rules_property() { Livewire::test(ComponentWithRulesProperty::class) ->set('bar', '') ->assertHasErrors(['bar' => 'required']); } public function test_validate_without_rules_property_and_no_args_throws_exception() { $this->expectException(MissingRulesException::class); Livewire::test(ComponentWithoutRulesProperty::class)->call('save'); } public function test_can_validate_collection_properties() { Livewire::test(ComponentWithRulesProperty::class) ->set('foo', 'filled') ->call('save') ->assertHasErrors('baz.*.foo') ->set('baz.0.foo', 123) ->set('baz.1.foo', 456) ->call('save') ->assertHasNoErrors('baz.*.foo'); } public function test_validate_component_properties() { $component = Livewire::test(ForValidation::class); $component->runAction('runValidation'); $this->assertStringNotContainsString('The foo field is required', $component->html()); $this->assertStringContainsString('The bar field is required', $component->html()); } public function test_validate_component_properties_with_custom_message() { $component = Livewire::test(ForValidation::class); $component->runAction('runValidationWithCustomMessage'); $this->assertStringContainsString('Custom Message', $component->html()); } public function test_validate_component_properties_with_custom_message_property() { $component = Livewire::test(ForValidation::class); $component->runAction('runValidationWithMessageProperty'); $this->assertStringContainsString('Custom Message', $component->html()); } public function test_validate_component_properties_with_custom_attribute_property() { $component = Livewire::test(ForValidation::class); $component->runAction('runValidationWithAttributesProperty'); $this->assertStringContainsString('The foobar field is required.', $component->html()); $this->assertStringContainsString('The Items Baz field is required.', $component->html()); } public function test_validate_component_properties_with_custom_attribute() { $component = Livewire::test(ForValidation::class); $component->runAction('runValidationWithCustomAttribute'); $this->assertStringContainsString('The foobar field is required.', $component->html()); } public function test_validate_component_properties_with_custom_value_property() { $component = Livewire::test(ForValidation::class); $component->runAction('runValidationWithCustomValuesProperty'); $this->assertStringContainsString('The bar field is required when foo is my custom value.', $component->html()); } public function test_validate_nested_component_properties() { $component = Livewire::test(ForValidation::class); $component->runAction('runNestedValidation'); $this->assertStringContainsString('The emails.1 field must be a valid email address.', $component->effects['html']); } public function test_validate_deeply_nested_component_properties() { $component = Livewire::test(ForValidation::class); $component->runAction('runDeeplyNestedValidation'); $this->assertStringContainsString('items.1.baz field is required', $component->html()); $this->assertStringNotContainsString('items.0.baz field is required', $component->html()); } public function test_validation_errors_persist_across_requests() { $component = Livewire::test(ForValidation::class); $component->call('runValidation') ->assertSee('The bar field is required') ->set('foo', 'bar') ->assertSee('The bar field is required'); } public function test_old_validation_errors_are_overwritten_if_new_request_has_errors() { $component = Livewire::test(ForValidation::class); $component->call('runValidation') ->set('foo', '') ->call('runValidation') ->call('$refresh') ->assertSee('The foo field is required'); } public function test_old_validation_is_cleared_if_new_validation_passes() { $component = Livewire::test(ForValidation::class); $component ->set('foo', '') ->set('bar', '') ->call('runValidation') ->assertSee('The foo field is required') ->assertSee('The bar field is required') ->set('foo', 'foo') ->set('bar', 'bar') ->call('runValidation') ->assertDontSee('The foo field is required') ->assertDontSee('The bar field is required'); } public function test_can_validate_only_a_specific_field_and_preserve_other_validation_messages() { $component = Livewire::test(ForValidation::class); $component ->set('foo', 'foo') ->set('bar', '') ->call('runValidation') ->assertDontSee('The foo field is required') ->assertSee('The bar field is required') ->set('foo', '') ->call('runValidationOnly', 'foo') ->assertSee('The foo field is required') ->assertSee('The bar field is required'); } public function test_validating_only_a_specific_field_wont_throw_an_error_if_the_field_doesnt_exist() { $component = Livewire::test(ForValidation::class); $component ->set('bar', '') ->call('runValidationOnlyWithFooRules', 'bar') ->assertDontSee('The foo field is required') ->assertDontSee('The bar field is required'); } public function test_validating_only_a_specific_field_wont_throw_an_error_if_the_array_key_doesnt_exist() { $component = Livewire::test(ForValidation::class); $component ->set('items', []) ->call('runDeeplyNestedValidationOnly', 'items.0.baz') ->assertSee('items.0.baz field is required'); } public function test_can_validate_only_a_specific_field_with_custom_message_property() { $component = Livewire::test(ForValidation::class); $component ->set('foo', 'foo') ->set('bar', '') ->call('runValidationOnlyWithMessageProperty', 'foo') ->assertDontSee('Foo Message') // Foo is set, no error ->assertDontSee('Bar Message') // Bar is not being validated, don't show ->set('foo', '') ->call('runValidationOnlyWithMessageProperty', 'bar') ->assertDontSee('Foo Message') // Foo is not being validated, don't show ->assertSee('Bar Message'); // Bar is not set, show message } public function test_can_validate_only_a_specific_field_with_custom_attributes_property() { $component = Livewire::test(ForValidation::class); $component ->call('runValidationOnlyWithAttributesProperty', 'bar') ->assertSee('The foobar field is required.') ->call('runValidationOnlyWithAttributesProperty', 'items.*.baz') // Test wildcard works ->assertSee('The Items Baz field is required.') ->call('runValidationOnlyWithAttributesProperty', 'items.1.baz') // Test specific instance works ->assertSee('The Items Baz field is required.') ; } public function test_can_validate_only_a_specific_field_with_deeply_nested_array() { $component = Livewire::test(ForValidation::class); $component ->runAction('runDeeplyNestedValidationOnly', 'items.0.baz') ->assertDontSee('items.0.baz field is required') ->runAction('runDeeplyNestedValidationOnly', 'items.1.baz') ->assertSee('items.1.baz field is required'); } public function test_old_deeply_nested_wildcard_validation_only_is_cleared_if_new_validation_passes() { $component = Livewire::test(ForValidation::class); $component ->runAction('runDeeplyNestedValidationOnly', 'items.*.baz') ->assertSee('items.1.baz field is required') ->set('items.1.baz', 'blab') ->runAction('runDeeplyNestedValidationOnly', 'items.*.baz') ->assertDontSee('items.1.baz field is required'); } public function test_old_deeply_nested_wildcard_validation_only_is_cleared_if_new_validation_fails() { $component = Livewire::test(ForValidation::class); $component ->runAction('runDeeplyNestedValidationOnly', 'items.*.baz') ->assertSee('items.1.baz field is required') ->set('items.1.baz', 'blab') ->set('items.0.baz', '') ->runAction('runDeeplyNestedValidationOnly', 'items.*.baz') ->assertDontSee('items.1.baz field is required') ->assertSee('items.0.baz field is required'); } public function test_old_deeply_nested_specific_validation_only_is_cleared_if_new_validation_passes() { $component = Livewire::test(ForValidation::class); $component ->runAction('runDeeplyNestedValidationOnly', 'items.1.baz') ->assertSee('items.1.baz field is required') ->set('items.1.baz', 'blab') ->runAction('runDeeplyNestedValidationOnly', 'items.1.baz') ->assertDontSee('items.1.baz field is required'); } public function test_old_deeply_nested_specific_validation_only_is_cleared_if_new_validation_fails() { $component = Livewire::test(ForValidation::class); $component ->runAction('runDeeplyNestedValidationOnly', 'items.1.baz') ->assertSee('items.1.baz field is required') ->set('items.1.baz', 'blab') ->set('items.0.baz', '') ->runAction('runDeeplyNestedValidationOnly', 'items.*.baz') ->assertDontSee('items.1.baz field is required') ->assertSee('items.0.baz field is required'); } public function test_validation_errors_are_shared_for_all_views() { $component = Livewire::test(ForValidation::class); app('view')->share('errors', $errors = new ViewErrorBag); $component ->set('bar', '') ->call('runValidation') ->assertSee('sharedError:The bar field is required'); $this->assertTrue(app('view')->shared('errors') === $errors); } public function test_validation_errors_are_shared_when_redirecting_back_to_full_page_component() { // We apply the web middleware here so that the errors will get shared // from the session to the view via ShareErrorsFromSession middleware Route::get('/full-page-component', ForValidation::class)->middleware('web'); Route::post('/non-livewire-form', function () { request()->validate(['bar' => 'required']); }); $post = $this ->from('/full-page-component') ->followingRedirects() ->post(url('/non-livewire-form')) ->assertSee('sharedError:The bar field is required'); } public function test_multi_word_validation_rules_failing_are_assertable() { $component = Livewire::test(ForValidation::class); $component ->set('foo', 'bar123&*(O)') ->call('runValidationWithMultiWordRule') ->assertHasErrors(['foo' => 'alpha_dash']); } public function test_class_based_validation_rules_failing_are_assertable() { $component = Livewire::test(ForValidation::class); $component ->set('foo', 'barbaz') ->call('runValidationWithClassBasedRule') ->assertHasErrors(['foo' => ValueEqualsFoobar::class]); } public function test_can_assert_has_no_errors_when_no_validation_has_failed_and_specific_keys_are_supplied() { $component = Livewire::test(ForValidation::class); $component ->set('foo', 'foo') ->set('bar', 'bar') ->call('runValidation') ->assertHasNoErrors(['foo' => 'required']); } public function test_multi_word_validation_rules_passing_are_assertable() { $component = Livewire::test(ForValidation::class); $component ->set('foo', 'foo-bar-baz') ->call('runValidationWithMultiWordRule') ->assertHasNoErrors(['foo' => 'alpha_dash']); } public function test_class_based_validation_rules_are_assertable() { $component = Livewire::test(ForValidation::class); $component ->set('foo', 'foobar') ->call('runValidationWithClassBasedRule') ->assertHasNoErrors(['foo' => ValueEqualsFoobar::class]); } public function test_custom_validation_messages_are_cleared_between_validate_only_validations() { $component = Livewire::test(ForValidation::class); // cleared when custom validation passes $component ->set('foo', 'foo') ->set('bar', 'b') ->call('runValidationOnlyWithCustomValidation', 'bar') ->assertDontSee('The bar field is required') ->assertSee('Lengths must be the same') ->set('bar', 'baz') ->call('runValidationOnlyWithCustomValidation', 'bar') ->assertDontSee('The bar field is required') ->assertDontSee('Lengths must be the same'); // cleared when custom validation isn't run $component ->set('foo', 'foo') ->set('bar', 'b') ->call('runValidationOnlyWithCustomValidation', 'bar') ->assertDontSee('The bar field is required') ->assertSee('Lengths must be the same') ->set('bar', '') ->call('runValidationOnlyWithCustomValidation', 'bar') ->assertSee('The bar field is required') ->assertDontSee('Lengths must be the same'); } public function test_validation_fails_when_same_rule_is_used_without_matching() { Livewire::test(ForValidation::class) ->set('password', 'supersecret') ->call('runSameValidation') ->assertSee('The password field must match password confirmation.'); } public function test_validation_passes_when_same_rule_is_used_and_matches() { Livewire::test(ForValidation::class) ->set('password', 'supersecret') ->set('passwordConfirmation', 'supersecret') ->call('runSameValidation') ->assertDontSee('The password field must match password confirmation.'); } public function test_only_data_in_validation_rules_is_returned() { $component = new ForValidation(); $component->bar = 'is required'; $validatedData = $component->runValidationWithoutAllPublicPropertiesAndReturnValidatedData(); $this->assertSame([ 'bar' => $component->bar, ], $validatedData); } public function test_can_assert_validation_errors_on_errors_thrown_from_custom_validator() { $component = Livewire::test(ForValidation::class); $component->call('failFooOnCustomValidator')->assertHasErrors('plop'); } public function test_can_use_withvalidator_method() { $component = Livewire::test(WithValidationMethod::class); $component->assertSetStrict('count', 0)->call('runValidationWithClosure')->assertSetStrict('count', 1); $component = Livewire::test(WithValidationMethod::class); $component->assertSetStrict('count', 0)->call('runValidationWithThisMethod')->assertSetStrict('count', 1); $component = Livewire::test(WithValidationMethod::class); $component->assertSetStrict('count', 0)->call('runValidateOnlyWithClosure')->assertSetStrict('count', 1); $component = Livewire::test(WithValidationMethod::class); $component->assertSetStrict('count', 0)->call('runValidateOnlyWithThisMethod')->assertSetStrict('count', 1); $component = Livewire::test(WithValidationMethod::class); $component->assertSetStrict('count', 0)->call('clearWithValidatorAfterRunningValidateMethod')->assertSetStrict('count', 1); $component = Livewire::test(WithValidationMethod::class); $component->assertSetStrict('count', 0)->call('clearWithValidatorAfterRunningValidateOnlyMethod')->assertSetStrict('count', 1); } public function test_a_set_of_items_will_validate_individually() { Livewire::test(ValidatesOnlyTestComponent::class, ['image' => 'image', 'imageAlt' => 'This is an image']) ->call('runValidateOnly', 'image_alt') ->assertHasNoErrors(['image_alt', 'image_url', 'image']) ->call('runValidateOnly', 'image_url') ->assertHasNoErrors(['image', 'image_url', 'image_alt']) ->call('runValidateOnly', 'image') ->assertHasNoErrors(['image', 'image_url', 'image_alt']); } public function test_a_computed_property_is_able_to_validate() { Livewire::test(ValidatesComputedProperty::class, ['helper' => 10]) ->call('runValidation') ->assertHasNoErrors(['computed']) ->set('helper', -1) ->call('runValidation') ->assertHasErrors(['computed']); $this->expectExceptionMessage('No property found for validation: [missing]'); Livewire::test(ForValidation::class) ->call('runValidationOnlyWithMissingProperty', 'missing'); $this->expectExceptionMessage('No property found for validation: [fail]'); Livewire::test(ValidatesComputedProperty::class) ->call('runValidationRuleWithoutProperty'); } public function test_when_unwrapping_data_for_validation_an_object_is_checked_if_it_is_wireable_first() { $this->markTestSkipped('Not sure we support setting data on a wireable without requiring a ->set method on the wireable...'); Livewire::test(ValidatesWireableProperty::class) ->call('runValidation') ->assertHasErrors('customCollection.0.amount') ->set('customCollection.0.amount', 150) ->call('runValidation') ->assertHasNoErrors('customCollection.0.amount') ; } public function test_adding_validation_error_inside_mount_method() { Livewire::test(AddErrorInMount::class) ->call('addErrors') ->assertSee('first error') ->assertSee('second error') ->assertSee('third error') ->assertHasErrors(['first', 'second', 'third']) ->call('addFilterErrors') ->assertSee('first error') ->assertSee('second error') ->assertHasErrors(['first', 'second']); Livewire::test(AddErrorInMount::class) ->assertSee('first error') ->assertSee('second error') ->assertSee('third error') ->assertHasErrors(['first', 'second', 'third']) ->call('addFilterErrors') ->assertSee('first error') ->assertSee('second error') ->assertHasErrors(['first', 'second']); } } class ComponentWithRulesProperty extends TestComponent { public $foo; public $bar = 'baz'; public $baz; protected $rules = [ 'foo' => 'required', 'bar' => 'required', 'baz.*.foo' => 'numeric', ]; public function mount() { $this->baz = collect([ ['foo' => 'a'], ['foo' => 'b'], ]); } public function updatedBar() { $this->validateOnly('bar'); } public function save() { $this->validate(); } } class ComponentWithoutRulesProperty extends TestComponent { public $foo; public function save() { $this->validate(); } } class ForValidation extends Component { public $foo = 'foo'; public $bar = ''; public $emails = ['foo@bar.com', 'invalid-email']; public $items = [ ['foo' => 'bar', 'baz' => 'blab'], ['foo' => 'bar', 'baz' => ''], ];
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportValidation/BaseValidate.php
src/Features/SupportValidation/BaseValidate.php
<?php namespace Livewire\Features\SupportValidation; use Attribute; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; use function Livewire\wrap; #[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_ALL)] class BaseValidate extends LivewireAttribute { function __construct( public $rule = null, protected $attribute = null, protected $as = null, protected $message = null, protected $onUpdate = true, protected bool $translate = true ) {} function boot() { // If this attribute is added to a "form object", we want to add the rules // to the actual form object, not the base component... $target = $this->subTarget ?: $this->component; $name = $this->subTarget ? $this->getSubName() : $this->getName(); $rules = []; if (is_null($this->rule)) { // Allow "Rule" to be used without a given validation rule. It's purpose is to instead // trigger validation on property updates... } elseif (is_array($this->rule) && count($this->rule) > 0 && ! is_numeric(array_keys($this->rule)[0])) { // Support setting rules by key-value for this and other properties: // For example, #[Validate(['foo' => 'required', 'foo.*' => 'required'])] $rules = $this->rule; } else { $rules[$this->getSubName()] = $this->rule; } if ($this->attribute) { if (is_array($this->attribute)) { $target = $this->subTarget ?? $this->component; $target->addValidationAttributesFromOutside($this->attribute); } else { $target->addValidationAttributesFromOutside([$name => $this->attribute]); } } if ($this->as) { if (is_array($this->as)) { $as = $this->translate ? array_map(fn ($i) => trans($i), $this->as) : $this->as; $target->addValidationAttributesFromOutside($as); } else { $target->addValidationAttributesFromOutside([$name => $this->translate ? trans($this->as) : $this->as]); } } if ($this->message) { if (is_array($this->message)) { $messages = $this->translate ? array_map(fn ($i) => trans($i), $this->message) : $this->message; $target->addMessagesFromOutside($messages); } else { // If a single message was provided, apply it to the first given rule. // There should have only been one rule provided in this case anyways... $rule = head(array_values($rules)); // In the case of "min:5" or something, we only want "min"... $rule = (string) str($rule)->before(':'); $target->addMessagesFromOutside([$name.'.'.$rule => $this->translate ? trans($this->message) : $this->message]); } } $target->addRulesFromOutside($rules); } function update($fullPath, $newValue) { if ($this->onUpdate === false) return; return function () { // If this attribute is added to a "form object", we want to run // the validateOnly method on the form object, not the base component... $target = $this->subTarget ?: $this->component; $name = $this->subTarget ? $this->getSubName() : $this->getName(); // Here we have to run the form object validator from the context // of the base "wrapped" component so that validation works... wrap($this->component)->tap(function () use ($target, $name) { $target->validateOnly($name); }); }; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportReactiveProps/BaseReactive.php
src/Features/SupportReactiveProps/BaseReactive.php
<?php namespace Livewire\Features\SupportReactiveProps; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; use function Livewire\store; #[\Attribute] class BaseReactive extends LivewireAttribute { function __construct() {} protected $originalValueHash; public function mount($params) { $property = $this->getName(); store($this->component)->push('reactiveProps', $property); $this->originalValueHash = crc32(json_encode($this->getValue())); } public function hydrate() { if (SupportReactiveProps::hasPassedInProps($this->component->getId())) { $updatedValue = SupportReactiveProps::getPassedInProp( $this->component->getId(), $this->getName() ); $this->setValue($updatedValue); } $this->originalValueHash = crc32(json_encode($this->getValue())); } public function dehydrate($context) { if ($this->originalValueHash !== crc32(json_encode($this->getValue()))) { throw new CannotMutateReactivePropException($this->component->getName(), $this->getName()); } $context->pushMemo('props', $this->getName()); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportReactiveProps/CannotMutateReactivePropException.php
src/Features/SupportReactiveProps/CannotMutateReactivePropException.php
<?php namespace Livewire\Features\SupportReactiveProps; use Exception; class CannotMutateReactivePropException extends Exception { function __construct($componentName, $propName) { parent::__construct("Cannot mutate reactive prop [{$propName}] in component: [{$componentName}]"); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportReactiveProps/BrowserTest.php
src/Features/SupportReactiveProps/BrowserTest.php
<?php namespace Livewire\Features\SupportReactiveProps; use Livewire\Livewire; use Livewire\Component; class BrowserTest extends \Tests\BrowserTestCase { public function test_can_pass_a_reactive_property_from_parent_to_child() { Livewire::visit([ new class extends Component { public $count = 0; public function inc() { $this->count++; } public function dec() { $this->count--; } public function render() { return <<<'HTML' <div> <h1>Parent count: <span dusk="parent.count">{{ $count }}</span> <button wire:click="dec" dusk="parent.dec">dec</button> <button wire:click="inc" dusk="parent.inc">inc</button> <livewire:child :child-count="$count" /> </div> HTML; } }, 'child' => new class extends Component { #[BaseReactive] public $childCount; public function render() { return <<<'HTML' <div> <h1>Child count: <span dusk="child.count">{{ $childCount }}</span> </div> HTML; } } ]) ->assertSeeIn('@parent.count', 0) ->assertSeeIn('@child.count', 0) ->waitForLivewire()->click('@parent.inc') ->assertSeeIn('@parent.count', 1) ->assertSeeIn('@child.count', 1) ->waitForLivewire()->click('@parent.inc') ->assertSeeIn('@parent.count', 2) ->assertSeeIn('@child.count', 2) ->waitForLivewire()->click('@parent.dec') ->assertSeeIn('@parent.count', 1) ->assertSeeIn('@child.count', 1) ->waitForLivewire()->click('@parent.dec') ->assertSeeIn('@parent.count', 0) ->assertSeeIn('@child.count', 0) ->waitForLivewire()->click('@parent.dec') ->assertSeeIn('@parent.count', -1) ->assertSeeIn('@child.count', -1) ->waitForLivewire()->click('@parent.inc') ->assertSeeIn('@parent.count', 0) ->assertSeeIn('@child.count', 0); } public function test_can_pass_a_reactive_property_from_parent_to_nested_children() { Livewire::visit([ new class extends Component { public $count = 0; public function inc() { $this->count++; } public function render() { return <<<'HTML' <div> <h1>Parent count: <h1 dusk="parent.count">{{ $count }}</h1> <button wire:click="inc" dusk="parent.inc">inc</button> <livewire:child :$count /> </div> HTML; } }, 'child' => new class extends Component { #[BaseReactive] public $count; public function render() { return <<<'HTML' <div> <h2>Child count: <h2 dusk="child.count">{{ $count }}</h2> <livewire:nestedchild :$count /> </div> HTML; } }, 'nestedchild' => new class extends Component { #[BaseReactive] public $count; public function render() { return <<<'HTML' <div> <h3>Nested child count: <h3 dusk="nested-child.count">{{ $count }}</h3> </div> HTML; } } ]) ->assertSeeIn('@parent.count', 0) ->assertSeeIn('@child.count', 0) ->assertSeeIn('@nested-child.count', 0) ->waitForLivewire()->click('@parent.inc') ->assertSeeIn('@parent.count', 1) ->assertSeeIn('@child.count', 1) ->assertSeeIn('@nested-child.count', 1) ->waitForLivewire()->click('@parent.inc') ->assertSeeIn('@parent.count', 2) ->assertSeeIn('@child.count', 2) ->assertSeeIn('@nested-child.count', 2); } public function test_can_throw_exception_cannot_mutate_reactive_prop() { Livewire::visit([ new class extends Component { public $count = 0; public function inc() { $this->count++; } public function render() { return <<<'HTML' <div> <h1>Parent count: <span dusk="parent.count">{{ $count }}</span> <button wire:click="inc" dusk="parent.inc">inc</button> <livewire:child :$count /> </div> HTML; } }, 'child' => new class extends Component { #[BaseReactive] public $count; public function inc() { $this->count++; } public function render() { return <<<'HTML' <div> <h1>Child count: <span dusk="child.count">{{ $count }}</span> <button wire:click="inc" dusk="child.inc">inc</button> </div> HTML; } } ]) ->assertSeeIn('@parent.count', 0) ->assertSeeIn('@child.count', 0) ->waitForLivewire()->click('@parent.inc') ->assertSeeIn('@parent.count', 1) ->assertSeeIn('@child.count', 1) ->waitForLivewire()->click('@child.inc') ->waitFor('#livewire-error') ->click('#livewire-error') ->assertSeeIn('@parent.count', 1) ->assertSeeIn('@child.count', 1); } public function test_can_pass_a_reactive_property_from_parent_to_lazy_child() { Livewire::visit([ new class extends Component { public $count = 0; public function inc() { $this->count++; } public function render() { return <<<'HTML' <div> <h1>Parent count: <span dusk="parent.count">{{ $count }}</span> <button wire:click="inc" dusk="parent.inc">inc</button> <livewire:child :$count lazy /> </div> HTML; } }, 'child' => new class extends Component { #[BaseReactive] public $count; public function inc() { $this->count++; } public function render() { return <<<'HTML' <div> <h1>Child count: <span dusk="child.count">{{ $count }}</span> <button wire:click="inc" dusk="child.inc">inc</button> </div> HTML; } } ]) ->assertSeeIn('@parent.count', 0) ->waitFor('@child.count') ->assertSeeIn('@child.count', 0) ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportReactiveProps/UnitTest.php
src/Features/SupportReactiveProps/UnitTest.php
<?php namespace Livewire\Features\SupportReactiveProps; use Livewire\Livewire; use Livewire\Component; class UnitTest extends \Tests\TestCase { function test_can_pass_prop_to_child_component() { Livewire::test([new class extends Component { public $foo = 'bar'; public function render() { return '<div><livewire:child :oof="$foo" /></div>'; } }, 'child' => new class extends Component { public $oof; public function render() { return '<div>{{ $oof }}</div>'; } }]) ->assertSee('bar'); } function test_can_change_reactive_prop_in_child_component() { $this->markTestSkipped('Unit testing child components isnt supported yet'); $component = Livewire::test([new class extends Component { public $todos = []; public function render() { return '<div><livewire:child :todos="$todos" /></div>'; } }, 'child' => new class extends Component { #[Prop(reactive: true)] public $todos; public function render() { return '<div>Count: {{ count($todos) }}.</div>'; } }]); $component->assertSee('Count: 0.'); $component->set('todos', ['todo 1']); $component->assertSee('Count: 1.'); $component->set('todos', ['todo 1', 'todo 2', 'todo 3']); $component->assertSee('Count: 3.'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportReactiveProps/SupportReactiveProps.php
src/Features/SupportReactiveProps/SupportReactiveProps.php
<?php namespace Livewire\Features\SupportReactiveProps; use function Livewire\on; use Livewire\ComponentHook; class SupportReactiveProps extends ComponentHook { public static $pendingChildParams = []; static function provide() { on('flush-state', fn() => static::$pendingChildParams = []); on('mount.stub', function ($tag, $id, $params, $parent, $key) { static::$pendingChildParams[$id] = $params; }); } static function hasPassedInProps($id) { return isset(static::$pendingChildParams[$id]); } static function getPassedInProp($id, $name) { $params = static::$pendingChildParams[$id] ?? []; return $params[$name] ?? null; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/BrowserTest.php
src/Features/SupportNavigate/BrowserTest.php
<?php namespace Livewire\Features\SupportNavigate; use Laravel\Dusk\Browser; use Livewire\Attributes\On; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\View; use Livewire\Attributes\Layout; use Livewire\Attributes\Url; use Livewire\Component; use Livewire\Drawer\Utils; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public static function tweakApplicationHook() { return function () { View::addNamespace('test-views', __DIR__ . '/test-views'); Livewire::component('query-page', QueryPage::class); Livewire::component('first-page', FirstPage::class); Livewire::component('first-page-child', FirstPageChild::class); Livewire::component('first-page-with-link-outside', FirstPageWithLinkOutside::class); Livewire::component('second-page', SecondPage::class); Livewire::component('third-page', ThirdPage::class); Livewire::component('first-html-attribute-page', FirstHtmlAttributesPage::class); Livewire::component('second-html-attribute-page', SecondHtmlAttributesPage::class); Livewire::component('first-asset-page', FirstAssetPage::class); Livewire::component('second-asset-page', SecondAssetPage::class); Livewire::component('third-asset-page', ThirdAssetPage::class); Livewire::component('first-tracked-asset-page', FirstTrackedAssetPage::class); Livewire::component('second-tracked-asset-page', SecondTrackedAssetPage::class); Livewire::component('second-remote-asset', SecondRemoteAsset::class); Livewire::component('first-scroll-page', FirstScrollPage::class); Livewire::component('second-scroll-page', SecondScrollPage::class); Livewire::component('parent-component', ParentComponent::class); Livewire::component('child-component', ChildComponent::class); Livewire::component('script-component', ScriptComponent::class); Livewire::component('page-with-link-to-an-error-page', PageWithLinkToAnErrorPage::class); Livewire::component('page-with-redirect-to-external-page', PageWithRedirectToExternalPage::class); Livewire::component('page-with-redirect-to-internal-which-has-external-link', PageWithRedirectToInternalWhichHasExternalLinkPage::class); Livewire::component('nav-bar-component', NavBarComponent::class); Livewire::component('first-noscript-page', FirstNoscriptPage::class); Livewire::component('second-noscript-page', SecondNoscriptPage::class); Route::get('/navbar/{page}', NavBarComponent::class)->middleware('web'); Route::get('/query-page', QueryPage::class)->middleware('web'); Route::get('/first', FirstPage::class)->middleware('web'); Route::get('/first-hide-progress', function () { config(['livewire.navigate.show_progress_bar' => false]); return (new FirstPage)(); })->middleware('web'); Route::get('/first-outside', FirstPageWithLinkOutside::class)->middleware('web'); Route::get('/redirect-to-second', fn () => redirect()->to('/second')); Route::get('/second', SecondPage::class)->middleware('web'); Route::get('/third', ThirdPage::class)->middleware('web'); Route::get('/fourth', FourthPage::class)->middleware('web'); Route::get('/first-html-attributes', FirstHtmlAttributesPage::class)->middleware('web'); Route::get('/second-html-attributes', SecondHtmlAttributesPage::class)->middleware('web'); Route::get('/first-asset', FirstAssetPage::class)->middleware('web'); Route::get('/second-asset', SecondAssetPage::class)->middleware('web'); Route::get('/third-asset', ThirdAssetPage::class)->middleware('web'); Route::get('/first-scroll', FirstScrollPage::class)->middleware('web'); Route::get('/second-scroll', SecondScrollPage::class)->middleware('web'); Route::get('/second-remote-asset', SecondRemoteAsset::class)->middleware('web'); Route::get('/first-tracked-asset', FirstTrackedAssetPage::class)->middleware('web'); Route::get('/second-tracked-asset', SecondTrackedAssetPage::class)->middleware('web'); Route::get('/test-navigate-asset.js', function () { return Utils::pretendResponseIsFile(__DIR__ . '/test-views/test-navigate-asset.js'); }); Route::get('/parent', ParentComponent::class)->middleware('web'); Route::get('/page-with-link-to-page-without-livewire', PageWithLinkAway::class); Route::get('/nonce', fn () => self::renderNoncePage('First Nonce Page', 'ABCD1234')); Route::get('/nonce2', fn () => self::renderNoncePage('Second Nonce Page', 'EFGH5678')); Route::get('/page-without-livewire-component', fn () => Blade::render(<<<'HTML' <html> <head> <meta name="empty-layout" content> <script src="/test-navigate-asset.js" data-navigate-track></script> </head> <body> <div dusk="non-livewire-page">This is a page without a livewire component</div> </body> </html> HTML)); Route::get('/page-with-alpine-for-loop', PageWithAlpineForLoop::class); Route::get('/page-with-redirect-to-internal-which-has-external-link', PageWithRedirectToInternalWhichHasExternalLinkPage::class)->middleware('web'); Route::get('/page-with-redirect-to-external-page', PageWithRedirectToExternalPage::class)->middleware('web'); Route::get('/script-component', ScriptComponent::class); Route::get('/first-noscript', FirstNoscriptPage::class)->middleware('web'); Route::get('/second-noscript', SecondNoscriptPage::class)->middleware('web'); Route::get('/no-javascript', fn () => '<div dusk="no-javascript-side">No javascript side triggered.</div>') ->middleware('web')->name('no-javascript'); Route::get('/page-with-link-to-an-error-page', PageWithLinkToAnErrorPage::class)->middleware('web'); }; } public static function renderNoncePage(string $name, string $nonce): string { return Blade::render(<<<'HTML' <html> <head> <meta name="empty-layout" content> <script src="/test-navigate-asset.js" data-navigate-track></script> </head> <body> <div dusk="nonce-page">{{ $name }}</div> <a href="/nonce2" wire:navigate dusk="link">to next nonce page</a> @livewireScripts(['nonce' => $nonce]); </body> </html> HTML, ['name' => $name, 'nonce' => $nonce]); } public function test_back_button_works_with_teleports() { $this->registerComponentTestRoutes([ '/second' => new class extends Component { public function render(){ return <<<'HTML' <div> On second page </div> HTML; } }, ]); Livewire::visit(new class extends Component { public function render(){ return <<<'HTML' <div x-data="{ outerScopeCount: 0 }"> Livewire component... <template x-teleport="body"> <div> <span x-text="outerScopeCount" dusk="target"></span> <button x-on:click="outerScopeCount++" dusk="button">inc</button> </div> </template> <a href="/second" wire:navigate dusk="link">Go to second page</a> </div> HTML; } }) ->assertSeeIn('@target', '0') ->click('@button') ->assertSeeIn('@target', '1') ->click('@link') ->waitForText('On second page') ->back() ->assertDontSee('On second page') ->assertSeeIn('@target', '0') ->click('@button') ->assertSeeIn('@target', '1') ->forward() ->back() ->assertSeeIn('@target', '0') ->click('@button') ->assertSeeIn('@target', '1') ; } public function test_back_button_works_with_teleports_inside_persist() { $this->registerComponentTestRoutes([ '/second' => new class extends Component { public function render(){ return <<<'HTML' <div> <div> On second page </div> @persist('header') <div x-data="{ outerScopeCount: 0 }"> <template x-teleport="body"> <div> <span x-text="outerScopeCount" dusk="target"></span> <button x-on:click="outerScopeCount++" dusk="button">inc</button> </div> </template> </div> @endpersist </div> HTML; } }, ]); Livewire::visit(new class extends Component { public function render(){ return <<<'HTML' <div> <div> On first page </div> @persist('header') <div x-data="{ outerScopeCount: 0 }"> <template x-teleport="body"> <div> <span x-text="outerScopeCount" dusk="target"></span> <button x-on:click="outerScopeCount++" dusk="button">inc</button> </div> </template> </div> @endpersist <a href="/second" wire:navigate dusk="link">Go to second page</a> </div> HTML; } }) ->assertSeeIn('@target', '0') ->click('@button') ->assertSeeIn('@target', '1') ->click('@link') ->waitForText('On second page') ->assertSeeIn('@target', '1') ->click('@button') ->assertSeeIn('@target', '2') ->back() ->assertSeeIn('@target', '2') ->click('@button') ->assertSeeIn('@target', '3') ->forward() ->assertSeeIn('@target', '3') ->click('@button') ->assertSeeIn('@target', '4') ; } public function test_can_configure_progress_bar() { $this->browse(function ($browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->click('@link.to.third') ->waitFor('#nprogress') ->waitForText('Done loading...'); }); $this->browse(function ($browser) { $browser ->visit('/first-hide-progress') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertConsoleLogHasNoErrors() ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->click('@link.to.third') ->pause(500) ->assertScript('return window._lw_dusk_test') ->assertMissing('#nprogress') ->waitForText('Done loading...'); }); } public function test_can_navigate_to_page_without_reloading() { $this->browse(function ($browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->click('@link.to.second') ->waitFor('@link.to.first') ->assertSee('On second') ->assertScript('return window._lw_dusk_test') ->click('@link.to.first') ->waitFor('@link.to.second') ->assertScript('return window._lw_dusk_test') ->assertSee('On first'); }); } public function test_can_navigate_to_page_without_reloading_by_hitting_the_enter_key() { $this->browse(function (Browser $browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->keys('@link.to.second', '{enter}') ->waitFor('@link.to.first') ->assertSee('On second') ->assertScript('return window._lw_dusk_test'); }); } public function test_can_navigate_to_another_page_with_hash_fragment() { $this->browse(function ($browser) { $browser ->visit('/first') ->waitForNavigate()->click('@link.to.hashtag') ->assertFragmentIs('foo'); }); } public function test_navigate_is_not_triggered_on_cmd_and_enter() { $key = PHP_OS_FAMILY === 'Darwin' ? \Facebook\WebDriver\WebDriverKeys::COMMAND : \Facebook\WebDriver\WebDriverKeys::CONTROL; $this->browse(function (Browser $browser) use ($key) { $currentWindowHandles = count($browser->driver->getWindowHandles()); $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->keys('@link.to.second', $key, '{enter}') ->pause(500) // Let navigate run if it was going to (it should not) ->assertSee('On first') ->assertScript('return window._lw_dusk_test'); $this->assertCount($currentWindowHandles + 1, $browser->driver->getWindowHandles()); }); } public function test_can_navigate_to_page_from_child_via_parent_component_without_reloading() { $this->browse(function (Browser $browser) { $browser ->visit('/first') ->assertSee('On first') ->click('@redirect.to.second.from.child') ->waitFor('@link.to.first') ->assertSee('On second') ->click('@link.to.first') ->waitFor('@redirect.to.second.from.child') ->assertSee('On first') ->click('@redirect.to.second.from.child') ->waitFor('@link.to.first') ->assertSee('On second'); }); } public function test_can_redirect_with_reloading_from_a_page_that_was_loaded_by_wire_navigate() { $this->browse(function ($browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->click('@link.to.second') ->waitFor('@link.to.first') ->assertSee('On second') ->assertScript('return window._lw_dusk_test') ->click('@redirect.to.first') ->waitFor('@link.to.second') ->assertScript('return window._lw_dusk_test', false) ->assertSee('On first'); }); } public function test_can_redirect_without_reloading_using_the_helper_from_a_page_that_was_loaded_normally() { $this->browse(function ($browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->click('@redirect.to.second') ->waitFor('@link.to.first') ->assertSee('On second') ->assertScript('return window._lw_dusk_test'); }); } public function test_can_redirect_to_a_page_after_destroying_session() { $this->browse(function ($browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->click('@redirect.to.second.and.destroy.session') ->waitFor('@link.to.first') ->assertSee('On second') ->assertScript('return window._lw_dusk_test') ->assertConsoleLogMissingWarning('Detected multiple instances of Livewire') ->assertConsoleLogMissingWarning('Detected multiple instances of Alpine'); }); } public function test_can_navigate_to_a_page_when_csp_nonce_present(): void { $this->browse(function ($browser) { $browser ->visit('/nonce') ->assertSee('First Nonce Page') ->click('@link') ->waitForText('Second Nonce Page') ->assertConsoleLogMissingWarning('Detected multiple instances of Livewire') ->assertConsoleLogMissingWarning('Detected multiple instances of Alpine'); }); } public function test_can_persist_elements_across_pages() { $this->browse(function ($browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSeeIn('@count', '1') ->click('@increment') ->assertSeeIn('@count', '2') ->click('@link.to.second') ->waitFor('@link.to.first') ->assertSee('On second') ->assertSeeIn('@count', '2') ->click('@increment') ->assertSeeIn('@count', '3') ->assertScript('return window._lw_dusk_test'); }); } public function test_html_element_attributes_are_replaced_on_navigate() { $this->browse(function ($browser) { $browser ->visit('/first-html-attributes') ->assertSee('On first html attributes page') // ->assertAttribute() won't work as it's scoped to the body... ->assertScript('document.documentElement.getAttribute("class")', 'class1') ->assertScript('document.documentElement.getAttribute("attr1")', 'value1') ->assertScript('document.documentElement.hasAttribute("attr2")', false) ->click('@link.to.second') ->waitForText('On second html attributes page') ->assertScript('document.documentElement.getAttribute("class")', 'class2') ->assertScript('document.documentElement.getAttribute("attr2")', 'value2') ->assertScript('document.documentElement.hasAttribute("attr1")', false) ; }); } public function test_new_assets_in_head_are_loaded_and_old_ones_are_not() { $this->browse(function ($browser) { $browser ->visit('/first-asset') ->assertScript('return _lw_dusk_asset_count', 1) ->assertSee('On first') ->waitForNavigate()->click('@link.to.second') ->waitForText('On second') ->assertScript('return _lw_dusk_asset_count', 1) ->waitForNavigate()->click('@link.to.third') ->waitForText('On third') ->assertScript('return _lw_dusk_asset_count', 2); }); } public function test_tracked_assets_reload_the_page_when_they_change() { $this->browse(function ($browser) { $browser ->visit('/first-tracked-asset') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertScript('return _lw_dusk_asset_count', 1) ->assertSee('On first') ->click('@link.to.second') ->waitForText('On second') ->assertScript('return window._lw_dusk_test', false) ->assertScript('return _lw_dusk_asset_count', 1); }); } public function test_can_use_wire_navigate_outside_of_a_livewire_component() { $this->browse(function ($browser) { $browser ->visit('/first-outside') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->click('@outside.link.to.second') ->waitForText('On second') ->assertScript('return window._lw_dusk_test'); }); } public function test_script_runs_on_initial_page_visit() { $this->browse(function ($browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->click('@link.to.second') ->waitFor('@link.to.first') ->assertSee('On second') ->assertScript('window.foo', 'bar') ->assertScript('return window._lw_dusk_test'); }); } public function test_can_navigate_to_component_with_url_attribute_and_update_correctly() { $this->browse(function ($browser) { $browser ->visit('/query-page') ->assertSee('Query: 0') ->click('@link.with.query.1') ->assertSee('Query: 1') ->waitForNavigate()->click('@link.with.query.2') ->assertSee('Query: 2'); }); } public function test_navigate_scrolls_to_top_and_back_preserves_scroll() { $this->browse(function ($browser) { $browser ->visit('/first-scroll') ->assertVisible('@first-target') ->assertNotInViewPort('@first-target') ->scrollTo('@first-target') ->assertInViewPort('@first-target') ->click('@link.to.second') ->waitForText('On second') ->assertNotInViewPort('@second-target') ->scrollTo('@second-target') ->back() ->waitForText('On first') ->assertInViewPort('@first-target') ->forward() ->waitForText('On second') ->assertInViewPort('@second-target') ; }); } public function test_navigate_using_javascript_scrolls_to_top_and_back_preserves_scroll() { $this->browse(function ($browser) { $browser ->visit('/first-scroll') // ->tinker() ->assertVisible('@first-target') ->assertNotInViewPort('@first-target') ->scrollTo('@first-target') ->assertInViewPort('@first-target') ->click('@link.to.second.using.javascript') ->waitForText('On second') ->assertNotInViewPort('@second-target') ->scrollTo('@second-target') ->back() ->waitForText('On first') ->assertInViewPort('@first-target') ->forward() ->waitForText('On second') ->assertInViewPort('@second-target') ; }); } public function test_navigate_preserves_scroll_when_using_preserve_scroll_attribute() { $this->browse(function ($browser) { $browser ->visit('/first-scroll') ->assertVisible('@first-target') ->assertNotInViewPort('@first-target') ->scrollTo('@first-target') ->assertInViewPort('@first-target') ->click('@link.to.second.with.preserve.scroll') ->waitForText('On second') ->assertInViewPort('@second-target') ->back() ->waitForText('On first') ->assertInViewPort('@first-target') ->forward() ->waitForText('On second') ->assertInViewPort('@second-target') ; }); } public function test_navigate_using_javascript_preserves_scroll_when_using_preserve_scroll_option() { $this->browse(function ($browser) { $browser ->visit('/first-scroll') ->assertVisible('@first-target') ->assertNotInViewPort('@first-target') ->scrollTo('@first-target') ->assertInViewPort('@first-target') ->click('@link.to.second.with.preserve.scroll.using.javascript') ->waitForText('On second') ->assertInViewPort('@second-target') ->back() ->waitForText('On first') ->assertInViewPort('@first-target') ->forward() ->waitForText('On second') ->assertInViewPort('@second-target') ; }); } public function test_navigate_back_works_from_page_without_a_livewire_component_that_has_a_script_with_data_navigate_track() { // When using `@vite` on the page without a Livewire component, // it injects a script tag with `data-navigate-track`, // which causes Livewire to be unloaded and the back button no longer work. $this->browse(function ($browser) { $browser ->visit('/page-with-link-to-page-without-livewire') ->assertSee('Link to page without Livewire component') ->assertDontSee('This is a page without a livewire component') ->click('@link.away') ->waitFor('@non-livewire-page') ->assertSee('This is a page without a livewire component') ->assertDontSee('Link to page without Livewire component') ->back() ->waitFor('@page-with-link-away') ->assertSee('Link to page without Livewire component') ->assertDontSee('This is a page without a livewire component') ; }); } public function test_navigate_is_only_triggered_on_left_click() { $this->browse(function ($browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->rightClick('@link.to.second') ->pause(500) // Let navigate run if it was going to (it should not) ->assertSee('On first') ->click('@link.to.second') ->waitFor('@link.to.first') ->assertSee('On second') ; }); } public function test_livewire_navigated_event_is_fired_on_first_page_load() { $this->browse(function ($browser) { $browser ->visit('/second') ->assertSee('On second') ->assertScript('window.foo_navigated', 'bar'); }); } public function test_livewire_before_navigate_event_is_fired_when_click() { $this->browse(function($browser) { $browser ->visit('/fourth') ->assertSee('On fourth') ->assertScript('window.foo', 'bar') ->assertSee('On fourth') ->click('@link.to.first') // first attempt bar -> baz ->assertScript('window.foo', 'baz') ->assertSee('On fourth') ->click('@link.to.first') // second attempt baz -> bat ->assertScript('window.foo', 'bat') ->assertSee('On fourth') ->waitForNavigate()->click('@link.to.first') // finally navigate ->assertSee('On first') ; }); } public function test_livewire_navigated_event_is_fired_after_redirect_without_reloading() { $this->browse(function ($browser) { $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->click('@link.to.second') ->waitFor('@link.to.first') ->assertSee('On second') ->assertScript('window.foo_navigated', 'bar'); }); } public function test_navigate_is_not_triggered_on_cmd_click() { $key = PHP_OS_FAMILY === 'Darwin' ? \Facebook\WebDriver\WebDriverKeys::COMMAND : \Facebook\WebDriver\WebDriverKeys::CONTROL; $this->browse(function (Browser $browser) use ($key) { $currentWindowHandles = count($browser->driver->getWindowHandles()); $browser ->visit('/first') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('On first') ->tap(function ($browser) use ($key) { $browser->driver->getKeyboard()->pressKey($key); }) ->click('@link.to.second') ->tap(function ($browser) use ($key) { $browser->driver->getKeyboard()->releaseKey($key); }) ->pause(500) // Let navigate run if it was going to (it should not) ->assertSee('On first') ->assertScript('return window._lw_dusk_test') ; $this->assertCount($currentWindowHandles + 1, $browser->driver->getWindowHandles()); }); } public function test_events_from_child_components_still_function_after_navigation() { $this->browse(function (Browser $browser) { $browser ->visit('/parent') ->assertSeeNothingIn('@text-child') ->assertSeeNothingIn('@text-parent') ->waitForLivewire()->type('@text-input', 'test') ->waitForTextIn('@text-child', 'test') ->waitForTextIn('@text-parent', 'test') ->waitForNavigate()->click('@home-link') ->assertSeeNothingIn('@text-child') ->assertSeeNothingIn('@text-parent') ->waitForLivewire()->type('@text-input', 'testing') ->waitForTextIn('@text-child', 'testing') ->waitForTextIn('@text-parent', 'testing') ->back() ->waitForTextIn('@text-child', 'test') ->waitForTextIn('@text-parent', 'test') ->waitForLivewire()->type('@text-input', 'testing') ->waitForTextIn('@text-child', 'testing') ->waitForTextIn('@text-parent', 'testing'); }); } public function test_alpine_for_loop_still_functions_after_navigation() { $this->browse(function (Browser $browser) { $browser ->visit('/page-with-alpine-for-loop') ->assertSeeIn('@text', 'a,b,c')
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/SupportNavigate.php
src/Features/SupportNavigate/SupportNavigate.php
<?php namespace Livewire\Features\SupportNavigate; use Livewire\ComponentHook; use Illuminate\Support\Facades\Vite; use Illuminate\Support\Facades\Blade; class SupportNavigate extends ComponentHook { static function provide() { Blade::directive('persist', function ($expression) { return '<?php app("livewire")->forceAssetInjection(); ?><div x-persist="<?php echo e('.$expression.'); ?>">'; }); Blade::directive('endpersist', function ($expression) { return '</div>'; }); app('livewire')->useScriptTagAttributes([ 'data-navigate-once' => true, ]); Vite::useScriptTagAttributes([ 'data-navigate-track' => 'reload', ]); Vite::useStyleTagAttributes([ 'data-navigate-track' => 'reload', ]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/HooksBrowserTest.php
src/Features/SupportNavigate/HooksBrowserTest.php
<?php namespace Livewire\Features\SupportNavigate; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\View; use Livewire\Attributes\Url; use Livewire\Component; use Livewire\Livewire; class HooksBrowserTest extends \Tests\BrowserTestCase { public static function tweakApplicationHook() { return function () { View::addNamespace('test-views', __DIR__ . '/test-views'); Livewire::component('page', NthPage::class); Route::get('/page', NthPage::class)->middleware('web'); }; } public function test_navigation_triggers_lifecycle_hooks() { $this->browse(function ($browser) { $browser ->visit('/page') ->assertScript('return window.__hooks[0].name === "livewire:navigated"') ->assertScript('return window.__hooks[1] === undefined') ->waitForNavigate()->click('@link.to.2') ->assertScript('return window.__hooks[1].name === "livewire:navigate" && window.__hooks[1].detail.history === false && window.__hooks[1].detail.cached === false') ->assertScript('return window.__hooks[2].name === "livewire:navigating"') ->assertScript('return window.__hooks[3].name === "livewire:navigated"') ; }); } public function test_back_and_forward_button_triggers_the_same_lifecycle_hooks_as_a_normal_navigate() { $this->browse(function ($browser) { $browser ->visit('/page') ->assertScript('return window.__hooks[0].name === "livewire:navigated"') ->assertScript('return window.__hooks[1] === undefined') ->waitForNavigate()->click('@link.to.2') ->assertScript('return window.__hooks[1].name === "livewire:navigate" && window.__hooks[1].detail.history === false && window.__hooks[1].detail.cached === false') ->assertScript('return window.__hooks[2].name === "livewire:navigating"') ->assertScript('return window.__hooks[3].name === "livewire:navigated"') ->waitForNavigate()->back() ->assertScript('return window.__hooks[4].name === "livewire:navigate" && window.__hooks[4].detail.history === true && window.__hooks[4].detail.cached === true') ->assertScript('return window.__hooks[5].name === "livewire:navigating"') ->assertScript('return window.__hooks[6].name === "livewire:navigated"') ->waitForNavigate()->forward() ->assertScript('return window.__hooks[7].name === "livewire:navigate" && window.__hooks[7].detail.history === true && window.__hooks[7].detail.cached === true') ->assertScript('return window.__hooks[8].name === "livewire:navigating"') ->assertScript('return window.__hooks[9].name === "livewire:navigated"') ; }); } public function test_back_button_hook_contains_info_about_caching_after_the_cache_runs_out() { $this->browse(function ($browser) { $browser ->visit('/page') ->waitForNavigate()->click('@link.to.2') ->waitForNavigate()->click('@link.to.3') ->waitForNavigate()->click('@link.to.4') ->waitForNavigate()->click('@link.to.5') ->waitForNavigate()->click('@link.to.6') ->waitForNavigate()->click('@link.to.7') ->waitForNavigate()->click('@link.to.8') ->waitForNavigate()->click('@link.to.9') ->waitForNavigate()->click('@link.to.10') ->waitForNavigate()->click('@link.to.11') ->waitForNavigate()->click('@link.to.12') ->waitForNavigate()->back() ->waitForNavigate()->back() ->waitForNavigate()->back() ->waitForNavigate()->back() ->waitForNavigate()->back() ->waitForNavigate()->back() ->waitForNavigate()->back() ->waitForNavigate()->back() ->waitForNavigate()->back() ->waitForNavigate()->back() ->waitForNavigate()->back() ->assertScript('return window.__hooks[64].name === "livewire:navigate" && window.__hooks[64].detail.history === true && window.__hooks[64].detail.cached === false') ; }); } } class NthPage extends Component { #[Url] public $number = 1; public function redirectToPageTwoUsingNavigate() { return $this->redirect('/page?number=2', navigate: true); } public function render() { return <<<'HTML' <div> <div>On page: {{ $number }}</div> <a href="/page?number=1" wire:navigate.hover dusk="link.to.1">Go to first page</a> <a href="/page?number=2" wire:navigate.hover dusk="link.to.2">Go to second page</a> <a href="/page?number=3" wire:navigate.hover dusk="link.to.3">Go to third page</a> <a href="/page?number=4" wire:navigate.hover dusk="link.to.4">Go to fourth page</a> <a href="/page?number=5" wire:navigate.hover dusk="link.to.5">Go to fifth page</a> <a href="/page?number=6" wire:navigate.hover dusk="link.to.6">Go to sixth page</a> <a href="/page?number=7" wire:navigate.hover dusk="link.to.7">Go to seventh page</a> <a href="/page?number=8" wire:navigate.hover dusk="link.to.8">Go to eighth page</a> <a href="/page?number=9" wire:navigate.hover dusk="link.to.9">Go to nineth page</a> <a href="/page?number=10" wire:navigate.hover dusk="link.to.10">Go to tenth page</a> <a href="/page?number=11" wire:navigate.hover dusk="link.to.11">Go to eleventh page</a> <a href="/page?number=11" wire:navigate.hover dusk="link.to.12">Go to twelfth page</a> <button type="button" wire:click="redirectToPageTwoUsingNavigate" dusk="redirect.to.second">Redirect to second page</button> @assets <script> window.__hooks = [] document.addEventListener('livewire:navigate', (e) => { window.__hooks.push({ name: 'livewire:navigate', detail: e.detail }) console.log('livewire:navigate', e.detail) }) document.addEventListener('livewire:navigating', (e) => { window.__hooks.push({ name: 'livewire:navigating', detail: e.detail }) console.log('livewire:navigating', e.detail) }) document.addEventListener('livewire:navigated', (e) => { window.__hooks.push({ name: 'livewire:navigated', detail: e.detail }) console.log('livewire:navigated', e.detail) }) </script> @endassets </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/test-views/layout-with-navigate-outside.blade.php
src/Features/SupportNavigate/test-views/layout-with-navigate-outside.blade.php
<html> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="/test-navigate-asset.js?v=123"></script> </head> <body> <a href="/second" dusk="outside.link.to.second" wire:navigate>Go to second page (outside)</a> {{ $slot }} @stack('scripts') </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/test-views/tracked-layout.blade.php
src/Features/SupportNavigate/test-views/tracked-layout.blade.php
<html> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="/test-navigate-asset.js?v=123" data-navigate-track></script> </head> <body> {{ $slot }} @stack('scripts') </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/test-views/layout.blade.php
src/Features/SupportNavigate/test-views/layout.blade.php
<html> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="/test-navigate-asset.js?v=123"></script> </head> <body> {{ $slot }} @stack('scripts') </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/test-views/html-attributes2.blade.php
src/Features/SupportNavigate/test-views/html-attributes2.blade.php
<html class="class2" attr2="value2" dusk="html"> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="/test-navigate-asset.js?v=123"></script> </head> <body> {{ $slot }} @stack('scripts') </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/test-views/changed-tracked-layout.blade.php
src/Features/SupportNavigate/test-views/changed-tracked-layout.blade.php
<html> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="/test-navigate-asset.js?v=456" data-navigate-track></script> </head> <body> {{ $slot }} @stack('scripts') </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/test-views/html-attributes1.blade.php
src/Features/SupportNavigate/test-views/html-attributes1.blade.php
<html class="class1" attr1="value1" dusk="html"> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="/test-navigate-asset.js?v=123"></script> </head> <body> {{ $slot }} @stack('scripts') </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/test-views/changed-layout.blade.php
src/Features/SupportNavigate/test-views/changed-layout.blade.php
<html> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="/test-navigate-asset.js?v=456"></script> </head> <body> {{ $slot }} @stack('scripts') </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/test-views/layout-with-noscript.blade.php
src/Features/SupportNavigate/test-views/layout-with-noscript.blade.php
<html> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="/test-navigate-asset.js?v=123"></script> <noscript> <meta http-equiv="refresh" content="0;url={{ route('no-javascript') }}"> </noscript> </head> <body> {{ $slot }} @stack('scripts') </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNavigate/test-views/navbar-sidebar.blade.php
src/Features/SupportNavigate/test-views/navbar-sidebar.blade.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .active { background-color: #DDF; } </style> </head> <body> <div> @persist('nav') <ul x-data> <li><a href="/navbar/one" wire:navigate dusk="link.one" x-bind:class="$current($el.href) ? 'active' : null">Link one</a></li> <li><a href="/navbar/two" wire:navigate dusk="link.two" x-bind:class="$current($el.href) ? 'active' : null">Link two</a></li> <li><a href="/navbar/three" wire:navigate dusk="link.three" x-bind:class="$current($el.href) ? 'active' : null">Link three</a></li> <li><a href="/navbar/four" wire:navigate dusk="link.four" x-bind:class="$current($el.href) ? 'active' : null">Link four</a></li> <li><a href="/navbar/five" wire:navigate dusk="link.five" x-bind:class="$current($el.href) ? 'active' : null">Link five</a></li> <li><a href="/navbar/six" wire:navigate dusk="link.six" x-bind:class="$current($el.href) ? 'active' : null">Link six</a></li> <li><a href="/navbar/seven" wire:navigate dusk="link.seven" x-bind:class="$current($el.href) ? 'active' : null">Link seven</a></li> <li><a href="/navbar/eight" wire:navigate dusk="link.eight" x-bind:class="$current($el.href) ? 'active' : null">Link eight</a></li> <li><a href="/navbar/nine" wire:navigate dusk="link.nine" x-bind:class="$current($el.href) ? 'active' : null">Link nine</a></li> <li><a href="/navbar/ten" wire:navigate dusk="link.ten" x-bind:class="$current($el.href) ? 'active' : null">Link ten</a></li> <li><a href="/navbar/eleven" wire:navigate dusk="link.eleven" x-bind:class="$current($el.href) ? 'active' : null">Link eleven</a></li> <li><a href="/navbar/twelve" wire:navigate dusk="link.twelve" x-bind:class="$current($el.href) ? 'active' : null">Link twelve</a></li> <li><a href="/navbar/thirteen" wire:navigate dusk="link.thirteen" x-bind:class="$current($el.href) ? 'active' : null">Link thirteen</a></li> <li><a href="/navbar/fourteen" wire:navigate dusk="link.fourteen" x-bind:class="$current($el.href) ? 'active' : null">Link fourteen</a></li> <li><a href="/navbar/fifteen" wire:navigate dusk="link.fifteen" x-bind:class="$current($el.href) ? 'active' : null">Link fifteen</a></li> </ul> @endpersist </div> <main> {{ $slot }} </main> <script data-navigate-once> document.addEventListener('alpine:init', () => { let state = Alpine.reactive({ href: window.location.href }) document.addEventListener('livewire:navigated', () => { queueMicrotask(() => { state.href = window.location.href }) }) Alpine.magic('current', (el) => (expected = '') => { let strip = (subject) => subject.replace(/^\/|\/$/g, '') return strip(state.href) === strip(expected) }) }) </script> </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTransitions/BrowserTest.php
src/Features/SupportTransitions/BrowserTest.php
<?php namespace Livewire\Features\SupportTransitions; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_can_transition_blade_conditional_dom_segments() { $opacity = 'parseFloat(getComputedStyle(document.querySelector(\'[dusk="target"]\')).opacity, 10)'; $isBlock = 'getComputedStyle(document.querySelector(\'[dusk="target"]\')).display === "block"'; Livewire::visit( new class extends \Livewire\Component { public $show = false; function toggle() { $this->show = ! $this->show; } public function render() { return <<<'HTML' <div> <button wire:click="toggle" dusk="toggle">Toggle</button> @if ($show) <div dusk="target" wire:transition.duration.2000ms> Transition Me! </div> @endif </div> HTML; } }) ->assertDontSee('@target') ->waitForLivewire()->click('@toggle') ->waitFor('@target') ->waitUntil($isBlock) ->waitUntil("$opacity > 0 && $opacity < 1") // In progress. ->waitUntil("$opacity === 1") // Now it's done. ->assertScript($opacity, 1) // Assert that it's done. ->waitForLivewire()->click('@toggle') ->assertPresent('@target') ->assertScript($isBlock, true) // That should not have changed yet. ->waitUntil("$opacity > 0 && $opacity < 1") // In progress. ->waitUntilMissing('@target') ->assertMissing('@target') ; } public function test_elements_the_contain_transition_are_displayed_on_page_load() { Livewire::visit( new class extends \Livewire\Component { public $messages = [ 'message 1', 'message 2', 'message 3', 'message 4', ]; public function addMessage() { $this->messages[] = 'message ' . count($this->messages) + 1; } public function render() { return <<< 'HTML' <div> <ul class="text-xs"> @foreach($messages as $index => $message) <li wire:transition.fade.duration.1000ms dusk="message-{{ $index + 1 }}">{{$message}}</li> @endforeach </ul> <button type="button" wire:click="addMessage" dusk="add-message">Add message</button> </div> HTML; } } ) ->assertVisible('@message-1') ->assertVisible('@message-2') ->assertVisible('@message-3') ->assertVisible('@message-4') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireModelingNestedComponents/BrowserTest.php
src/Features/SupportWireModelingNestedComponents/BrowserTest.php
<?php namespace Livewire\Features\SupportWireModelingNestedComponents; use Illuminate\Database\Eloquent\Model; use Livewire\Attributes\Validate; use Livewire\Form; use Livewire\Livewire; use Sushi\Sushi; /** @group morphing */ class BrowserTest extends \Tests\BrowserTestCase { public function test_can_bind_a_property_from_parent_to_property_from_child() { Livewire::visit([ new class extends \Livewire\Component { public $foo = 0; public function render() { return <<<'HTML' <div> <span dusk="parent">Parent: {{ $foo }}</span> <span x-text="$wire.foo" dusk="parent.ephemeral"></span> <livewire:child wire:model="foo" /> <button wire:click="$refresh" dusk="refresh">refresh</button> </div> HTML; } }, 'child' => new class extends \Livewire\Component { #[BaseModelable] public $bar; public function render() { return <<<'HTML' <div> <span dusk="child">Child: {{ $bar }}</span> <span x-text="$wire.bar" dusk="child.ephemeral"></span> <button wire:click="bar++" dusk="increment">increment</button> </div> HTML; } }, ]) ->assertSeeIn('@parent', 'Parent: 0') ->assertSeeIn('@child', 'Child: 0') ->assertSeeIn('@parent.ephemeral', '0') ->assertSeeIn('@child.ephemeral', '0') ->click('@increment') ->assertSeeIn('@parent', 'Parent: 0') ->assertSeeIn('@child', 'Child: 0') ->assertSeeIn('@parent.ephemeral', '1') ->assertSeeIn('@child.ephemeral', '1') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@parent', 'Parent: 1') ->assertSeeIn('@child', 'Child: 1') ->assertSeeIn('@parent.ephemeral', '1') ->assertSeeIn('@child.ephemeral', '1') ; } public function test_can_bind_a_live_property_from_parent_to_property_from_child() { Livewire::visit([ new class extends \Livewire\Component { public $foo = 0; public function render() { return <<<'HTML' <div> <span dusk="parent">Parent: {{ $foo }}</span> <span x-text="$wire.foo" dusk="parent.ephemeral"></span> <livewire:child wire:model.live="foo" /> <button wire:click="$refresh" dusk="refresh">refresh</button> </div> HTML; } }, 'child' => new class extends \Livewire\Component { #[BaseModelable] public $bar; public function render() { return <<<'HTML' <div> <span dusk="child">Child: {{ $bar }}</span> <span x-text="$wire.bar" dusk="child.ephemeral"></span> <button wire:click="bar++;" dusk="increment">increment</button> </div> HTML; } }, ]) ->assertSeeIn('@parent', 'Parent: 0') ->assertSeeIn('@child', 'Child: 0') ->assertSeeIn('@parent.ephemeral', '0') ->assertSeeIn('@child.ephemeral', '0') ->waitForLivewire()->click('@increment') ->assertSeeIn('@parent', 'Parent: 1') ->assertSeeIn('@child', 'Child: 1') ->assertSeeIn('@parent.ephemeral', '1') ->assertSeeIn('@child.ephemeral', '1') ; } public function test_can_bind_a_property_from_parent_array_to_property_from_child() { Livewire::visit([ new class extends \Livewire\Component { public $foo = ['bar' => 'baz']; public function render() { return <<<'HTML' <div> <span dusk='parent'>Parent: {{ $foo['bar'] }}</span> <span x-text="$wire.foo['bar']" dusk='parent.ephemeral'></span> <livewire:child wire:model='foo.bar' /> <button wire:click='$refresh' dusk='refresh'>refresh</button> </div> HTML; } }, 'child' => new class extends \Livewire\Component { #[BaseModelable] public $bar; public function render() { return <<<'HTML' <div> <span dusk='child'>Child: {{ $bar }}</span> <span x-text='$wire.bar' dusk='child.ephemeral'></span> <input type='text' wire:model='bar' dusk='child.input' /> </div> HTML; } }, ]) ->assertDontSee('Property [$foo.bar] not found') ->assertSeeIn('@parent', 'Parent: baz') ->assertSeeIn('@child', 'Child: baz') ->assertSeeIn('@parent.ephemeral', 'baz') ->assertSeeIn('@child.ephemeral', 'baz') ->type('@child.input', 'qux') ->assertSeeIn('@parent', 'Parent: baz') ->assertSeeIn('@child', 'Child: baz') ->assertSeeIn('@parent.ephemeral', 'qux') ->assertSeeIn('@child.ephemeral', 'qux') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@parent', 'Parent: qux') ->assertSeeIn('@child', 'Child: qux') ->assertSeeIn('@parent.ephemeral', 'qux') ->assertSeeIn('@child.ephemeral', 'qux'); } public function test_can_bind_a_property_from_parent_array_using_a_numeric_index_to_property_from_child() { Livewire::visit([ new class extends \Livewire\Component { public $foo = ['baz']; public function render() { return <<<'HTML' <div> <span dusk='parent'>Parent: {{ $foo[0] }}</span> <span x-text="$wire.foo[0]" dusk='parent.ephemeral'></span> <livewire:child wire:model='foo.0' /> <button wire:click='$refresh' dusk='refresh'>refresh</button> </div> HTML; } }, 'child' => new class extends \Livewire\Component { #[BaseModelable] public $bar; public function render() { return <<<'HTML' <div> <span dusk='child'>Child: {{ $bar }}</span> <span x-text='$wire.bar' dusk='child.ephemeral'></span> <input type='text' wire:model='bar' dusk='child.input' /> </div> HTML; } }, ]) ->assertDontSee('Property [$foo.0] not found') ->assertSeeIn('@parent', 'Parent: baz') ->assertSeeIn('@child', 'Child: baz') ->assertSeeIn('@parent.ephemeral', 'baz') ->assertSeeIn('@child.ephemeral', 'baz') ->type('@child.input', 'qux') ->assertSeeIn('@parent', 'Parent: baz') ->assertSeeIn('@child', 'Child: baz') ->assertSeeIn('@parent.ephemeral', 'qux') ->assertSeeIn('@child.ephemeral', 'qux') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@parent', 'Parent: qux') ->assertSeeIn('@child', 'Child: qux') ->assertSeeIn('@parent.ephemeral', 'qux') ->assertSeeIn('@child.ephemeral', 'qux'); } public function test_can_bind_a_property_from_parent_form_to_property_from_child() { Livewire::visit([ new class extends \Livewire\Component { public CreatePost $form; public function submit() { $this->form->store(); } public function render() { return <<<'HTML' <div> <span dusk='parent'>Parent: {{ $form->title }}</span> <span x-text='$wire.form.title' dusk='parent.ephemeral'></span> <livewire:child wire:model='form.title' /> <button wire:click='$refresh' dusk='refresh'>refresh</button> <button wire:click='submit' dusk='submit'>submit</button> </div> HTML; } }, 'child' => new class extends \Livewire\Component { #[BaseModelable] public $bar; public function render() { return <<<'HTML' <div> <span dusk='child'>Child: {{ $bar }}</span> <span x-text='$wire.bar' dusk='child.ephemeral'></span> <input type='text' wire:model='bar' dusk='child.input' /> </div> HTML; } }, ]) ->assertDontSee('Property [$form.title] not found') ->assertSeeIn('@parent', 'Parent:') ->assertSeeIn('@child', 'Child:') ->assertSeeNothingIn('@parent.ephemeral') ->assertSeeNothingIn('@child.ephemeral') ->type('@child.input', 'foo') ->assertSeeIn('@parent', 'Parent:') ->assertSeeIn('@child', 'Child:') ->assertSeeIn('@parent.ephemeral', 'foo') ->assertSeeIn('@child.ephemeral', 'foo') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@parent', 'Parent: foo') ->assertSeeIn('@child', 'Child: foo') ->assertSeeIn('@parent.ephemeral', 'foo') ->assertSeeIn('@child.ephemeral', 'foo') ->waitForLivewire()->click('@submit') ->assertSeeNothingIn('@parent.ephemeral', '') ->assertSeeNothingIn('@child.ephemeral', '') ; } public function test_can_still_forward_wire_model_attribute() { Livewire::visit([ new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <livewire:child wire:model="foo" class="foo" /> </div> HTML; } }, 'child' => new class extends \Livewire\Component { public function render() { return <<<'HTML' <div {{ $attributes }} dusk="child"> <!-- ... --> </div> HTML; } }, ]) ->assertAttribute('@child', 'wire:model', 'foo') ->assertAttribute('@child', 'class', 'foo') ; } } class CreatePost extends Form { #[Validate('required')] public $title; public function store() { Post::create($this->all()); $this->reset(); } } class Post extends Model { use Sushi; protected $rows = [ ['id' => 1, 'title' => 'foo'], ['id' => 2, 'title' => 'bar'], ]; protected $fillable = ['title']; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireModelingNestedComponents/BaseModelable.php
src/Features/SupportWireModelingNestedComponents/BaseModelable.php
<?php namespace Livewire\Features\SupportWireModelingNestedComponents; use function Livewire\store; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; #[\Attribute] class BaseModelable extends LivewireAttribute { public function mount($params, $parent, $attributes) { if (! $parent) return; $outer = null; foreach ($attributes as $key => $value) { if (str($key)->startsWith('wire:model')) { $outer = $value; store($this->component)->push('bindings-directives', $key, $value); break; } } if ($outer === null) return; $inner = $this->getName(); store($this->component)->push('bindings', $inner, $outer); $this->setValue(data_get($parent, $outer)); } // This update hook is for the following scenario: // An modelable value has changed in the browser. // A network request is triggered from the parent. // The request contains both parent and child component updates. // The parent finishes it's request and the "updated" value is // overridden in the parent's lifecycle (ex. a form field being reset). // Without this hook, the child's value will not honor that change // and will instead still be updated to the old value, even though // the parent changed the bound value. This hook detects if the parent // has provided a value during this request and ensures that it is the // final value for the child's request... function update($fullPath, $newValue) { if (store($this->component)->get('hasBeenSeeded', false)) { $oldValue = $this->getValue(); return function () use ($oldValue) { $this->setValue($oldValue); }; } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireModelingNestedComponents/SupportWireModelingNestedComponents.php
src/Features/SupportWireModelingNestedComponents/SupportWireModelingNestedComponents.php
<?php namespace Livewire\Features\SupportWireModelingNestedComponents; use Livewire\ComponentHook; use Livewire\Drawer\Utils; use function Livewire\on; use function Livewire\store; class SupportWireModelingNestedComponents extends ComponentHook { protected static $outersByComponentId = []; public static function provide() { on('flush-state', fn() => static::$outersByComponentId = []); // On a subsequent request, a parent encounters a child component // with wire:model on it, and that child has already been mounted // in a previous request, capture the value being passed in so we // can later set the child's property if it exists in this request. on('mount.stub', function ($tag, $id, $params, $parent, $key, $slots, $attributes) { $outer = collect($attributes)->first(function ($value, $key) { return str($key)->startsWith('wire:model'); }); if (! $outer) return; static::$outersByComponentId[$id] = [$outer => data_get($parent, $outer)]; }); } public function hydrate($memo) { if (! isset($memo['bindings'])) return; $bindings = $memo['bindings']; $directives = $memo['bindingsDirectives']; // Store the bindings for later dehydration... store($this->component)->set('bindings', $bindings); store($this->component)->set('bindings-directives', $directives); // If this child's parent already rendered its stub, retrieve // the memo'd value and set it. if (! isset(static::$outersByComponentId[$memo['id']])) return; $outers = static::$outersByComponentId[$memo['id']]; foreach ($bindings as $outer => $inner) { store($this->component)->set('hasBeenSeeded', true); $this->component->$inner = $outers[$outer]; } } public function render($view, $data) { return function ($html, $replaceHtml) { $bindings = store($this->component)->get('bindings', false); $directives = store($this->component)->get('bindings-directives', false); if (! $bindings) return; // Currently we can only support a single wire:model bound value, // so we'll just get the first one. But in the future we will // likely want to support named bindings, so we'll keep // this value as an array. $outer = array_keys($bindings)[0]; $inner = array_values($bindings)[0]; $directive = array_values($directives)[0]; // Attach the necessary Alpine directives so that the child and // parent's JS, ephemeral, values are bound. $replaceHtml(Utils::insertAttributesIntoHtmlRoot($html, [ $directive => '$parent.'.$outer, 'x-modelable' => '$wire.'.$inner, ])); }; } public function dehydrate($context) { $bindings = store($this->component)->get('bindings', false); if (! $bindings) return; $directives = store($this->component)->get('bindings-directives'); // Add the bindings metadata to the paylad for later reference... $context->addMemo('bindings', $bindings); $context->addMemo('bindingsDirectives', $directives); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/InitialRender.php
src/Features/SupportTesting/InitialRender.php
<?php namespace Livewire\Features\SupportTesting; use Livewire\Drawer\Utils; class InitialRender extends Render { function __construct( protected RequestBroker $requestBroker, ) {} static function make($requestBroker, $name, $params = [], $fromQueryString = [], $cookies = [], $headers = []) { $instance = new static($requestBroker); return $instance->makeInitialRequest($name, $params, $fromQueryString, $cookies, $headers); } function makeInitialRequest($name, $params, $fromQueryString = [], $cookies = [], $headers = []) { $uri = '/livewire-unit-test-endpoint/'.str()->random(20); $this->registerRouteBeforeExistingRoutes($uri, function () use ($name, $params) { return \Illuminate\Support\Facades\Blade::render('@livewire($name, $params)', [ 'name' => $name, 'params' => $params, ]); }); [$response, $componentInstance, $componentView] = $this->extractComponentAndBladeView(function () use ($uri, $fromQueryString, $cookies, $headers) { return $this->requestBroker->temporarilyDisableExceptionHandlingAndMiddleware(function ($requestBroker) use ($uri, $fromQueryString, $cookies, $headers) { return $requestBroker->addHeaders($headers)->call('GET', $uri, $fromQueryString, $cookies); }); }); app('livewire')->flushState(); $html = $response->getContent(); // Set "original" to Blade view for assertions like "assertViewIs()"... $response->original = $componentView; $snapshot = Utils::extractAttributeDataFromHtml($html, 'wire:snapshot'); $effects = Utils::extractAttributeDataFromHtml($html, 'wire:effects'); return new ComponentState($componentInstance, $response, $componentView, $html, $snapshot, $effects); } private function registerRouteBeforeExistingRoutes($path, $closure) { // To prevent this route from overriding wildcard routes registered within the application, // We have to make sure that this route is registered before other existing routes. $livewireTestingRoute = new \Illuminate\Routing\Route(['GET', 'HEAD'], $path, $closure); $existingRoutes = app('router')->getRoutes(); // Make an empty collection. $runningCollection = new \Illuminate\Routing\RouteCollection; // Add this testing route as the first one. $runningCollection->add($livewireTestingRoute); // Now add the existing routes after it. foreach ($existingRoutes as $route) { $runningCollection->add($route); } // Now set this route collection as THE route collection for the app. app('router')->setRoutes($runningCollection); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/Testable.php
src/Features/SupportTesting/Testable.php
<?php namespace Livewire\Features\SupportTesting; use Livewire\Features\SupportFileDownloads\TestsFileDownloads; use Livewire\Features\SupportValidation\TestsValidation; use Livewire\Features\SupportRedirects\TestsRedirects; use Livewire\Features\SupportEvents\TestsEvents; use Illuminate\Support\Traits\Macroable; use BackedEnum; /** @mixin \Illuminate\Testing\TestResponse */ class Testable { use MakesAssertions, TestsEvents, TestsRedirects, TestsValidation, TestsFileDownloads; use Macroable { Macroable::__call as macroCall; } protected function __construct( protected RequestBroker $requestBroker, protected ComponentState $lastState, ) {} /** * @param string $name * @param array $params * @param array $fromQueryString * @param array $cookies * @param array $headers * * @return static */ static function create($name, $params = [], $fromQueryString = [], $cookies = [], $headers = []) { $name = static::normalizeAndRegisterComponentName($name); $requestBroker = new RequestBroker(app()); $initialState = InitialRender::make( $requestBroker, $name, $params, $fromQueryString, $cookies, $headers, ); return new static($requestBroker, $initialState); } /** * @param string|array<string>|object $name * * @return string */ static function normalizeAndRegisterComponentName($name) { if (is_array($components = $name)) { $firstComponent = array_values($components)[0]; foreach ($components as $key => $value) { if (is_numeric($key)) { app('livewire')->exists($value) || app('livewire')->component($value); } else { app('livewire')->component($key, $value); } } return app('livewire.factory')->resolveComponentName($firstComponent); } elseif (is_object($name)) { $anonymousClassComponent = $name; $name = str()->random(10); app('livewire')->component($name, $anonymousClassComponent); } else { app('livewire')->isDiscoverable($name) || app('livewire')->component($name); } return $name; } /** * @param ?string $driver * * @return void */ static function actingAs(\Illuminate\Contracts\Auth\Authenticatable $user, $driver = null) { if (isset($user->wasRecentlyCreated) && $user->wasRecentlyCreated) { $user->wasRecentlyCreated = false; } auth()->guard($driver)->setUser($user); auth()->shouldUse($driver); } function id() { return $this->lastState->getComponent()->getId(); } /** * @param string $key */ function get($key) { return data_get($this->lastState->getComponent(), $key); } /** * @param bool $stripInitialData * * @return string */ function html($stripInitialData = false) { return $this->lastState->getHtml($stripInitialData); } /** * @param string $name * * @return $this */ function updateProperty($name, $value = null) { return $this->set($name, $value); } /** * @param array $values * * @return $this */ function fill($values) { foreach ($values as $name => $value) { $this->set($name, $value); } return $this; } /** * @param string $name * * @return $this */ function toggle($name) { return $this->set($name, ! $this->get($name)); } /** * @param string|array<string mixed> $name * * @return $this */ function set($name, $value = null) { if (is_array($name)) { foreach ($name as $key => $value) { $this->setProperty($key, $value); } } else { $this->setProperty($name, $value); } return $this; } /** * @param string $name * * @return $this */ function setProperty($name, $value) { if ($value instanceof \Illuminate\Http\UploadedFile) { return $this->upload($name, [$value]); } elseif (is_array($value) && isset($value[0]) && $value[0] instanceof \Illuminate\Http\UploadedFile) { return $this->upload($name, $value, $isMultiple = true); } elseif ($value instanceof BackedEnum) { $value = $value->value; } return $this->update(updates: [$name => $value]); } /** * @param string $method * * @return $this */ function runAction($method, ...$params) { return $this->call($method, ...$params); } /** * @param string $method * * @return $this */ function call($method, ...$params) { if ($method === '$refresh') { return $this->commit(); } if ($method === '$set') { return $this->set(...$params); } return $this->update(calls: [ [ 'method' => $method, 'params' => $params, 'path' => '', ] ]); } /** * @return $this */ function commit() { return $this->update(); } /** * @return $this */ function refresh() { return $this->update(); } /** * @param array $calls * @param array $updates * * @return $this */ function update($calls = [], $updates = []) { $newState = SubsequentRender::make( $this->requestBroker, $this->lastState, $calls, $updates, app('request')->cookies->all() ); $this->lastState = $newState; return $this; } /** * @todo Move me outta here and into the file upload folder somehow... * * @param string $name * @param array $files * @param bool $isMultiple * * @return $this */ function upload($name, $files, $isMultiple = false) { // This method simulates the calls Livewire's JavaScript // normally makes for file uploads. $this->call( '_startUpload', $name, collect($files)->map(function ($file) { return [ 'name' => $file->name, 'size' => $file->getSize(), 'type' => $file->getMimeType(), ]; })->toArray(), $isMultiple, ); // This is where either the pre-signed S3 url or the regular Livewire signed // upload url would do its thing and return a hashed version of the uploaded // file in a tmp directory. $storage = \Livewire\Features\SupportFileUploads\FileUploadConfiguration::storage(); try { $fileHashes = (new \Livewire\Features\SupportFileUploads\FileUploadController)->validateAndStore($files, \Livewire\Features\SupportFileUploads\FileUploadConfiguration::disk()); } catch (\Illuminate\Validation\ValidationException $e) { $this->call('_uploadErrored', $name, json_encode(['errors' => $e->errors()]), $isMultiple); return $this; } $this->call('_finishUpload', $name, $fileHashes, $isMultiple); return $this; } /** * @param string $key */ function viewData($key) { return $this->lastState->getView()->getData()[$key]; } function getData() { return $this->lastState->getSnapshotData(); } function instance() { return $this->lastState->getComponent(); } /** * @return \Livewire\Component */ function invade() { return \Livewire\invade($this->lastState->getComponent()); } /** * @return $this */ function dump() { dump($this->lastState->getHtml()); return $this; } /** * @return void */ function dd() { dd($this->lastState->getHtml()); } /** * @return $this */ function tap($callback) { $callback($this); return $this; } /** * @param string $property */ function __get($property) { if ($property === 'effects') return $this->lastState->getEffects(); if ($property === 'snapshot') return $this->lastState->getSnapshot(); if ($property === 'target') return $this->lastState->getComponent(); return $this->instance()->$property; } /** * @param string $property * @param mixed $value */ function __set($property, $value) { if ($property === 'snapshot') { $this->lastState = new ComponentState( $this->lastState->getComponent(), $this->lastState->getResponse(), $this->lastState->getView(), $this->lastState->getHtml(), $value, $this->lastState->getEffects(), ); return; } $this->setProperty($property, $value); } /** * @param string $method * * @return $this */ function __call($method, $params) { if (static::hasMacro($method)) { return $this->macroCall($method, $params); } $this->lastState->getResponse()->{$method}(...$params); return $this; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/SupportTesting.php
src/Features/SupportTesting/SupportTesting.php
<?php namespace Livewire\Features\SupportTesting; use Illuminate\Validation\ValidationException; use Livewire\ComponentHook; use Livewire\Component; class SupportTesting extends ComponentHook { static function provide() { if (! app()->environment('testing')) return; if (class_exists('Laravel\Dusk\Browser')) { DuskTestable::provide(); } static::registerTestingMacros(); } function dehydrate($context) { $target = $this->component; $errors = $target->getErrorBag(); if (! $errors->isEmpty()) { $this->storeSet('testing.errors', $errors); } } function hydrate() { $this->storeSet('testing.validator', null); } function exception($e, $stopPropagation) { if (! $e instanceof ValidationException) return; $this->storeSet('testing.validator', $e->validator); } protected static function registerTestingMacros() { // Usage: $this->assertSeeLivewire('counter'); \Illuminate\Testing\TestResponse::macro('assertSeeLivewire', function ($component) { if (is_subclass_of($component, Component::class)) { $component = app('livewire.factory')->resolveComponentName($component); } $escapedComponentName = trim(htmlspecialchars(json_encode(['name' => $component])), '{}'); \PHPUnit\Framework\Assert::assertStringContainsString( $escapedComponentName, $this->getContent(), 'Cannot find Livewire component ['.$component.'] rendered on page.' ); return $this; }); // Usage: $this->assertDontSeeLivewire('counter'); \Illuminate\Testing\TestResponse::macro('assertDontSeeLivewire', function ($component) { if (is_subclass_of($component, Component::class)) { $component = app('livewire.factory')->resolveComponentName($component); } $escapedComponentName = trim(htmlspecialchars(json_encode(['name' => $component])), '{}'); \PHPUnit\Framework\Assert::assertStringNotContainsString( $escapedComponentName, $this->getContent(), 'Found Livewire component ['.$component.'] rendered on page.' ); return $this; }); if (class_exists(\Illuminate\Testing\TestView::class)) { \Illuminate\Testing\TestView::macro('assertSeeLivewire', function ($component) { if (is_subclass_of($component, Component::class)) { $component = app('livewire.factory')->resolveComponentName($component); } $escapedComponentName = trim(htmlspecialchars(json_encode(['name' => $component])), '{}'); \PHPUnit\Framework\Assert::assertStringContainsString( $escapedComponentName, $this->rendered, 'Cannot find Livewire component ['.$component.'] rendered on page.' ); return $this; }); \Illuminate\Testing\TestView::macro('assertDontSeeLivewire', function ($component) { if (is_subclass_of($component, Component::class)) { $component = app('livewire.factory')->resolveComponentName($component); } $escapedComponentName = trim(htmlspecialchars(json_encode(['name' => $component])), '{}'); \PHPUnit\Framework\Assert::assertStringNotContainsString( $escapedComponentName, $this->rendered, 'Found Livewire component ['.$component.'] rendered on page.' ); return $this; }); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/SubsequentRender.php
src/Features/SupportTesting/SubsequentRender.php
<?php namespace Livewire\Features\SupportTesting; class SubsequentRender extends Render { function __construct( protected RequestBroker $requestBroker, protected ComponentState $lastState, ) {} static function make($requestBroker, $lastState, $calls = [], $updates = [], $cookies = []) { $instance = new static($requestBroker, $lastState); return $instance->makeSubsequentRequest($calls, $updates, $cookies); } function makeSubsequentRequest($calls = [], $updates = [], $cookies = []) { $uri = app('livewire')->getUpdateUri(); $encodedSnapshot = json_encode($this->lastState->getSnapshot()); $payload = [ 'components' => [ [ 'snapshot' => $encodedSnapshot, 'calls' => $calls, 'updates' => $updates, ], ], ]; [$response, $componentInstance, $componentView] = $this->extractComponentAndBladeView(function () use ($uri, $payload, $cookies) { return $this->requestBroker->temporarilyDisableExceptionHandlingAndMiddleware(function ($requestBroker) use ($uri, $payload, $cookies) { return $requestBroker->addHeaders(['X-Livewire' => true])->call('POST', $uri, $payload, $cookies); }); }); app('livewire')->flushState(); if (! $response->isOk()) { return new ComponentState( $componentInstance, $response, null, '', [], [], ); } $json = $response->json(); // Set "original" to Blade view for assertions like "assertViewIs()"... $response->original = $componentView; $componentResponsePayload = $json['components'][0]; $snapshot = json_decode($componentResponsePayload['snapshot'], true); $effects = $componentResponsePayload['effects']; // If no new HTML has been rendered, let's forward the last known HTML... $html = $effects['html'] ?? $this->lastState->getHtml(stripInitialData: true); $view = $componentView ?? $this->lastState->getView(); return new ComponentState( $componentInstance, $response, $view, $html, $snapshot, $effects, ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/DuskBrowserMacros.php
src/Features/SupportTesting/DuskBrowserMacros.php
<?php namespace Livewire\Features\SupportTesting; use function Livewire\str; use Facebook\WebDriver\WebDriverBy; use PHPUnit\Framework\Assert as PHPUnit; class DuskBrowserMacros { public function assertAttributeMissing() { return function ($selector, $attribute) { /** @var \Laravel\Dusk\Browser $this */ $fullSelector = $this->resolver->format($selector); $actual = $this->resolver->findOrFail($selector)->getAttribute($attribute); PHPUnit::assertNull( $actual, "Did not see expected attribute [{$attribute}] within element [{$fullSelector}]." ); return $this; }; } public function assertNotVisible() { return function ($selector) { /** @var \Laravel\Dusk\Browser $this */ $fullSelector = $this->resolver->format($selector); PHPUnit::assertFalse( $this->resolver->findOrFail($selector)->isDisplayed(), "Element [{$fullSelector}] is visible." ); return $this; }; } public function assertNotPresent() { return function ($selector) { /** @var \Laravel\Dusk\Browser $this */ $fullSelector = $this->resolver->format($selector); PHPUnit::assertTrue( is_null($this->resolver->find($selector)), "Element [{$fullSelector}] is present." ); return $this; }; } public function assertHasClass() { return function ($selector, $className) { /** @var \Laravel\Dusk\Browser $this */ $fullSelector = $this->resolver->format($selector); PHPUnit::assertContains( $className, explode(' ', $this->attribute($selector, 'class')), "Element [{$fullSelector}] missing class [{$className}]." ); return $this; }; } public function assertScript() { return function ($js, $expects = true) { /** @var \Laravel\Dusk\Browser $this */ PHPUnit::assertEquals($expects, head($this->script( str($js)->start('return ') ))); return $this; }; } public function runScript() { return function ($js) { /** @var \Laravel\Dusk\Browser $this */ $this->script([$js]); return $this; }; } public function scrollTo() { return function ($selector) { $this->browser->scrollTo($selector); return $this; }; } public function assertNotInViewPort() { return function ($selector) { /** @var \Laravel\Dusk\Browser $this */ return $this->assertInViewPort($selector, invert: true); }; } public function assertInViewPort() { return function ($selector, $invert = false) { /** @var \Laravel\Dusk\Browser $this */ $fullSelector = $this->resolver->format($selector); $result = $this->script( 'const rect = document.querySelector(\''.$fullSelector.'\').getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) );', $selector )[0]; PHPUnit::assertEquals($invert ? false : true, $result); return $this; }; } public function assertClassMissing() { return function ($selector, $className) { /** @var \Laravel\Dusk\Browser $this */ $fullSelector = $this->resolver->format($selector); PHPUnit::assertNotContains( $className, explode(' ', $this->attribute($selector, 'class')), "Element [{$fullSelector}] has class [{$className}]." ); return $this; }; } public function waitForLivewireToLoad() { return function () { /** @var \Laravel\Dusk\Browser $this */ return $this->waitUsing(6, 25, function () { return $this->driver->executeScript('return !! window.Livewire.initialRenderIsFinished'); }); }; } public function waitForLivewire() { return function ($callback = null) { /** @var \Laravel\Dusk\Browser $this */ $id = str()->random(); $this->script([ "window.duskIsWaitingForLivewireRequest{$id} = true", "window.Livewire.hook('request', ({ respond, succeed, fail }) => { window.duskIsWaitingForLivewireRequest{$id} = true let handle = () => { queueMicrotask(() => { delete window.duskIsWaitingForLivewireRequest{$id} }) } succeed(handle) fail(handle) })", ]); if ($callback) { $callback($this); return $this->waitUsing(6, 25, function () use ($id) { return $this->driver->executeScript("return window.duskIsWaitingForLivewireRequest{$id} === undefined"); }, 'Livewire request was never triggered'); } // If no callback is passed, make ->waitForLivewire a higher-order method. return new class($this, $id) { protected $browser; protected $id; public function __construct($browser, $id) { $this->browser = $browser; $this->id = $id; } public function __call($method, $params) { return tap($this->browser->{$method}(...$params), function ($browser) { $browser->waitUsing(6, 25, function () use ($browser) { return $browser->driver->executeScript("return window.duskIsWaitingForLivewireRequest{$this->id} === undefined"); }, 'Livewire request was never triggered'); }); } }; }; } public function waitForNoLivewire() { return function ($callback = null) { /** @var \Laravel\Dusk\Browser $this */ $id = str()->random(); $this->script([ "window.duskIsWaitingForLivewireRequest{$id} = true", "window.Livewire.hook('request', ({ respond, succeed, fail }) => { window.duskIsWaitingForLivewireRequest{$id} = true let handle = () => { queueMicrotask(() => { delete window.duskIsWaitingForLivewireRequest{$id} }) } succeed(handle) fail(handle) })", ]); if ($callback) { $callback($this); return $this->waitUsing(6, 25, function () use ($id) { return $this->driver->executeScript("return window.duskIsWaitingForLivewireRequest{$id}"); }, 'Livewire request was triggered'); } // If no callback is passed, make ->waitForNoLivewire a higher-order method. return new class($this, $id) { protected $browser; protected $id; public function __construct($browser, $id) { $this->browser = $browser; $this->id = $id; } public function __call($method, $params) { return tap($this->browser->{$method}(...$params), function ($browser) { $browser->waitUsing(6, 25, function () use ($browser) { return $browser->driver->executeScript("return window.duskIsWaitingForLivewireRequest{$this->id}"); }, 'Livewire request was triggered'); }); } }; }; } public function waitForNavigate() { return function ($callback = null) { /** @var \Laravel\Dusk\Browser $this */ $id = str()->random(); $this->script([ "window.duskIsWaitingForLivewireNavigate{$id} = true", "window.handler{$id} = () => { window.duskIsWaitingForLivewireNavigate{$id} = true document.removeEventListener('livewire:navigated', window.handler{$id}) queueMicrotask(() => { delete window.duskIsWaitingForLivewireNavigate{$id} }) }", "document.addEventListener('livewire:navigated', window.handler{$id})", ]); if ($callback) { $callback($this); return $this->waitUsing(6, 25, function () use ($id) { return $this->driver->executeScript("return window.duskIsWaitingForLivewireNavigate{$id} === undefined"); }, 'Livewire navigate was never triggered'); } // If no callback is passed, make ->waitForNavigate a higher-order method. return new class($this, $id) { protected $browser; protected $id; public function __construct($browser, $id) { $this->browser = $browser; $this->id = $id; } public function __call($method, $params) { return tap($this->browser->{$method}(...$params), function ($browser) { $browser->waitUsing(6, 25, function () use ($browser) { return $browser->driver->executeScript("return window.duskIsWaitingForLivewireNavigate{$this->id} === undefined"); }, 'Livewire navigate was never triggered'); }); } }; }; } public function waitForNavigateRequest() { return function ($callback = null) { /** @var \Laravel\Dusk\Browser $this */ $id = str()->random(); $this->script([ "window.duskIsWaitingForLivewireNavigateRequestStarted{$id} = false", "window.duskIsWaitingForLivewireNavigateRequestFinished{$id} = true", 'let cleanupRequest = () => {}', "cleanupRequest = Livewire.hook('navigate.request', () => { window.duskIsWaitingForLivewireNavigateRequestStarted{$id} = true cleanupRequest() })", "window.handler{$id} = () => { if (! window.duskIsWaitingForLivewireNavigateRequestStarted{$id}) { return } window.duskIsWaitingForLivewireNavigateRequestFinished{$id} = true document.removeEventListener('livewire:navigated', window.handler{$id}) queueMicrotask(() => { delete window.duskIsWaitingForLivewireNavigateRequestStarted{$id} delete window.duskIsWaitingForLivewireNavigateRequestFinished{$id} }) }", "document.addEventListener('livewire:navigated', window.handler{$id})", ]); if ($callback) { $callback($this); return $this->waitUsing(6, 25, function () use ($id) { return $this->driver->executeScript("return window.duskIsWaitingForLivewireNavigateRequestFinished{$id} === undefined"); }, 'Livewire navigate request was never completed'); } // If no callback is passed, make ->waitForNavigate a higher-order method. return new class($this, $id) { protected $browser; protected $id; public function __construct($browser, $id) { $this->browser = $browser; $this->id = $id; } public function __call($method, $params) { return tap($this->browser->{$method}(...$params), function ($browser) { $browser->waitUsing(6, 25, function () use ($browser) { return $browser->driver->executeScript("return window.duskIsWaitingForLivewireNavigateRequestFinished{$this->id} === undefined"); }, 'Livewire navigate request was never completed'); }); } }; }; } public function waitForNoNavigateRequest() { return function ($callback = null) { /** @var \Laravel\Dusk\Browser $this */ $id = str()->random(); $this->script([ "window.duskIsWaitingForLivewireNavigateRequestStarted{$id} = true", 'let cleanupRequest = () => {}', "cleanupRequest = Livewire.hook('navigate.request', () => { window.duskIsWaitingForLivewireNavigateRequestStarted{$id} = true cleanupRequest() queueMicrotask(() => { delete window.duskIsWaitingForLivewireNavigateRequestStarted{$id} }) })", ]); if ($callback) { $callback($this); return $this->waitUsing(6, 25, function () use ($id) { return $this->driver->executeScript("return window.duskIsWaitingForLivewireNavigateRequestStarted{$id}"); }, 'Livewire navigate request was completed'); } // If no callback is passed, make ->waitForNavigate a higher-order method. return new class($this, $id) { protected $browser; protected $id; public function __construct($browser, $id) { $this->browser = $browser; $this->id = $id; } public function __call($method, $params) { return tap($this->browser->{$method}(...$params), function ($browser) { $browser->waitUsing(6, 25, function () use ($browser) { return $browser->driver->executeScript("return window.duskIsWaitingForLivewireNavigateRequestStarted{$this->id}"); }, 'Livewire navigate request was completed'); }); } }; }; } public function waitForNavigatePrefetchRequest() { return function ($callback = null) { /** @var \Laravel\Dusk\Browser $this */ $id = str()->random(); $this->script([ "window.duskIsWaitingForLivewireNavigatePrefetchRequest{$id} = true", 'let cleanupPrefetchRequest = () => {}', "cleanupPrefetchRequest = Livewire.hook('navigate.request', () => { window.duskIsWaitingForLivewireNavigatePrefetchRequest{$id} = true cleanupPrefetchRequest() queueMicrotask(() => { delete window.duskIsWaitingForLivewireNavigatePrefetchRequest{$id} }) })", ]); if ($callback) { $callback($this); return $this->waitUsing(6, 25, function () use ($id) { return $this->driver->executeScript("return window.duskIsWaitingForLivewireNavigatePrefetchRequest{$id} === undefined"); }, 'Livewire navigate prefetch request was never triggered'); } // If no callback is passed, make ->waitForNavigatePrefetchRequest a higher-order method. return new class($this, $id) { protected $browser; protected $id; public function __construct($browser, $id) { $this->browser = $browser; $this->id = $id; } public function __call($method, $params) { return tap($this->browser->{$method}(...$params), function ($browser) { $browser->waitUsing(6, 25, function () use ($browser) { return $browser->driver->executeScript("return window.duskIsWaitingForLivewireNavigatePrefetchRequest{$this->id} === undefined"); }, 'Livewire navigate prefetch request was never triggered'); }); } }; }; } public function waitForNoNavigatePrefetchRequest() { // 60ms is the minimum delay for a hover event to trigger a prefetch plus a buffer... return function ($callback = null, $prefetchDelay = 70) { /** @var \Laravel\Dusk\Browser $this */ $id = str()->random(); $this->script([ "window.duskIsWaitingForLivewireNavigatePrefetchRequest{$id} = true", "Livewire.hook('navigate.request', () => { window.duskIsWaitingForLivewireNavigatePrefetchRequest{$id} = true queueMicrotask(() => { delete window.duskIsWaitingForLivewireNavigatePrefetchRequest{$id} }) })", ]); if ($callback) { $callback($this); // Wait for the specified prefetch delay before checking $this->pause($prefetchDelay); return $this->waitUsing(6, 25, function () use ($id) { return $this->driver->executeScript("return window.duskIsWaitingForLivewireNavigatePrefetchRequest{$id}"); }, 'Livewire navigate prefetch request was triggered'); } // If no callback is passed, make ->waitForNoNavigatePrefetchRequest a higher-order method. return new class($this, $id, $prefetchDelay) { protected $browser; protected $id; protected $prefetchDelay; public function __construct($browser, $id, $prefetchDelay) { $this->browser = $browser; $this->id = $id; $this->prefetchDelay = $prefetchDelay; } public function __call($method, $params) { return tap($this->browser->{$method}(...$params), function ($browser) { // Wait for the specified prefetch delay before checking $browser->pause($this->prefetchDelay); $browser->waitUsing(6, 25, function () use ($browser) { return $browser->driver->executeScript("return window.duskIsWaitingForLivewireNavigatePrefetchRequest{$this->id}"); }, 'Livewire navigate prefetch request was triggered'); }); } }; }; } public function online() { return function () { /** @var \Laravel\Dusk\Browser $this */ return tap($this)->script("window.dispatchEvent(new Event('online'))"); }; } public function offline() { return function () { /** @var \Laravel\Dusk\Browser $this */ return tap($this)->script("window.dispatchEvent(new Event('offline'))"); }; } public function selectMultiple() { return function ($field, $values = []) { $element = $this->resolver->resolveForSelection($field); $options = $element->findElements(WebDriverBy::tagName('option')); if (empty($values)) { $maxSelectValues = sizeof($options) - 1; $minSelectValues = rand(0, $maxSelectValues); foreach (range($minSelectValues, $maxSelectValues) as $optValue) { $options[$optValue]->click(); } } else { foreach ($options as $option) { $optValue = (string)$option->getAttribute('value'); if (in_array($optValue, $values)) { $option->click(); } } } return $this; }; } public function assertConsoleLogHasWarning() { return function($expectedMessage){ $logs = $this->driver->manage()->getLog('browser'); $containsError = false; foreach ($logs as $log) { if (! isset($log['message']) || ! isset($log['level']) || $log['level'] !== 'WARNING') continue; if(str($log['message'])->contains($expectedMessage)) { $containsError = true; } } PHPUnit::assertTrue($containsError, "Console log error message \"{$expectedMessage}\" not found"); return $this; }; } public function assertConsoleLogMissingWarning() { return function($expectedMessage){ $logs = $this->driver->manage()->getLog('browser'); $containsError = false; foreach ($logs as $log) { if (! isset($log['message']) || ! isset($log['level']) || $log['level'] !== 'WARNING') continue; if(str($log['message'])->contains($expectedMessage)) { $containsError = true; } } PHPUnit::assertFalse($containsError, "Console log error message \"{$expectedMessage}\" was found"); return $this; }; } public function assertConsoleLogHasNoErrors() { return function(){ $logs = $this->driver->manage()->getLog('browser'); $errors = []; foreach ($logs as $log) { if (! isset($log['message']) || ! isset($log['level']) || $log['level'] !== 'SEVERE') continue; // Ignore favicon.ico if(str($log['message'])->contains('favicon.ico')) continue; $errors[] = $log['message']; } PHPUnit::assertEmpty($errors, "Console log contained errors: " . implode(", ", $errors)); return $this; }; } public function assertConsoleLogHasErrors() { return function(){ $logs = $this->driver->manage()->getLog('browser'); $errors = []; foreach ($logs as $log) { if (! isset($log['message']) || ! isset($log['level']) || $log['level'] !== 'SEVERE') continue; // Ignore favicon.ico if(str($log['message'])->contains('favicon.ico')) continue; $errors[] = $log['message']; } PHPUnit::assertNotEmpty($errors, "Console log contained no errors"); return $this; }; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/Render.php
src/Features/SupportTesting/Render.php
<?php namespace Livewire\Features\SupportTesting; use function Livewire\on; abstract class Render { protected function extractComponentAndBladeView($callback) { $instance = null; $extractedView = null; $offA = on('dehydrate', function ($component) use (&$instance) { $instance = $component; }); $offB = on('render', function ($component, $view) use (&$extractedView) { return function () use ($view, &$extractedView) { $extractedView = $view; }; }); $result = $callback(); $offA(); $offB(); return [$result, $instance, $extractedView]; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/ShowDuskComponent.php
src/Features/SupportTesting/ShowDuskComponent.php
<?php namespace Livewire\Features\SupportTesting; class ShowDuskComponent { public function __invoke($component) { $class = urldecode($component); return app()->call(app('livewire')->new($class)); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/MakesAssertions.php
src/Features/SupportTesting/MakesAssertions.php
<?php namespace Livewire\Features\SupportTesting; use Illuminate\Testing\Constraints\SeeInOrder; use PHPUnit\Framework\Assert as PHPUnit; use Illuminate\Support\Arr; trait MakesAssertions { function assertSee($values, $escape = true, $stripInitialData = true) { foreach (Arr::wrap($values) as $value) { PHPUnit::assertStringContainsString( $escape ? e($value): $value, $this->html($stripInitialData) ); } return $this; } function assertDontSee($values, $escape = true, $stripInitialData = true) { foreach (Arr::wrap($values) as $value) { PHPUnit::assertStringNotContainsString( $escape ? e($value): $value, $this->html($stripInitialData) ); } return $this; } function assertSeeHtml($values) { foreach (Arr::wrap($values) as $value) { PHPUnit::assertStringContainsString( $value, $this->html() ); } return $this; } function assertSeeHtmlInOrder($values) { PHPUnit::assertThat( $values, new SeeInOrder($this->html()) ); return $this; } function assertDontSeeHtml($values) { foreach (Arr::wrap($values) as $value) { PHPUnit::assertStringNotContainsString( $value, $this->html() ); } return $this; } function assertSeeText($value, $escape = true) { $value = Arr::wrap($value); $values = $escape ? array_map('e', ($value)) : $value; $content = $this->html(); tap(strip_tags($content), function ($content) use ($values) { foreach ($values as $value) { PHPUnit::assertStringContainsString((string) $value, $content); } }); return $this; } function assertDontSeeText($value, $escape = true) { $value = Arr::wrap($value); $values = $escape ? array_map('e', ($value)) : $value; $content = $this->html(); tap(strip_tags($content), function ($content) use ($values) { foreach ($values as $value) { PHPUnit::assertStringNotContainsString((string) $value, $content); } }); return $this; } function assertSet($name, $value, $strict = false) { $actual = $this->get($name); if (! is_string($value) && is_callable($value)) { PHPUnit::assertTrue($value($actual)); } else { $strict ? PHPUnit::assertSame($value, $actual) : PHPUnit::assertEquals($value, $actual); } return $this; } function assertNotSet($name, $value, $strict = false) { $actual = $this->get($name); $strict ? PHPUnit::assertNotSame($value, $actual) : PHPUnit::assertNotEquals($value, $actual); return $this; } function assertSetStrict($name, $value) { $this->assertSet($name, $value, true); return $this; } function assertNotSetStrict($name, $value) { $this->assertNotSet($name, $value, true); return $this; } function assertCount($name, $value) { PHPUnit::assertCount($value, $this->get($name)); return $this; } function assertSnapshotSet($name, $value, $strict = false) { $data = $this->lastState->getSnapshotData(); if (is_callable($value)) { PHPUnit::assertTrue($value(data_get($data, $name))); } else { $strict ? PHPUnit::assertSame($value, data_get($data, $name)) : PHPUnit::assertEquals($value, data_get($data, $name)); } return $this; } function assertSnapshotNotSet($name, $value, $strict = false) { $data = $this->lastState->getSnapshotData(); if (is_callable($value)) { PHPUnit::assertFalse($value(data_get($data, $name))); } else { $strict ? PHPUnit::assertNotSame($value, data_get($data, $name)) : PHPUnit::assertNotEquals($value, data_get($data, $name)); } return $this; } function assertSnapshotSetStrict($name, $value) { $this->assertSnapshotSet($name, $value, true); return $this; } function assertSnapshotNotSetStrict($name, $value) { $this->assertSnapshotNotSet($name, $value, true); return $this; } public function assertReturned($value) { $data = data_get($this->lastState->getEffects(), 'returns.0'); if (is_callable($value)) { PHPUnit::assertTrue($value($data)); } else { PHPUnit::assertEquals($value, $data); } return $this; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/ComponentState.php
src/Features/SupportTesting/ComponentState.php
<?php namespace Livewire\Features\SupportTesting; use Livewire\Drawer\Utils; class ComponentState { function __construct( protected $component, protected $response, protected $view, protected $html, protected $snapshot, protected $effects, ) {} function getComponent() { return $this->component; } function getSnapshot() { return $this->snapshot; } function getSnapshotData() { return $this->untupleify($this->snapshot['data']); } function getEffects() { return $this->effects; } function getView() { return $this->view; } function getResponse() { return $this->response; } function untupleify($payload) { $value = Utils::isSyntheticTuple($payload) ? $payload[0] : $payload; if (is_array($value)) { foreach ($value as $key => $child) { $value[$key] = $this->untupleify($child); } } return $value; } function getHtml($stripInitialData = false) { $html = $this->html; if ($stripInitialData) { $removeMe = (string) str($html)->betweenFirst( 'wire:snapshot="', '"' ); $html = str_replace($removeMe, '', $html); $removeMe = (string) str($html)->betweenFirst( 'wire:effects="', '"' ); $html = str_replace($removeMe, '', $html); } return $html; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/UnitTest.php
src/Features/SupportTesting/UnitTest.php
<?php namespace Livewire\Features\SupportTesting; use Illuminate\Contracts\Validation\ValidationRule; use PHPUnit\Framework\ExpectationFailedException; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Route; use Illuminate\Testing\TestResponse; use Illuminate\Testing\TestView; use Livewire\Component; use Livewire\Livewire; use Closure; use Tests\TestComponent; // TODO - Change this to \Tests\TestCase class UnitTest extends \LegacyTests\Unit\TestCase { function test_can_assert_see_livewire_on_standard_blade_view() { Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $fakeClass = new class { function getContent() { return view('render-component', [ 'component' => 'foo', ])->render(); } }; $testResponse = new TestResponse($fakeClass); $testResponse->assertSeeLivewire('foo'); } function test_can_test_component_using_magic_render() { mkdir($this->livewireViewsPath()); file_put_contents($this->livewireViewsPath().'/foo.blade.php', <<<'PHP' <div> Im foo </div> PHP); mkdir($this->livewireClassesPath()); file_put_contents($this->livewireClassesPath().'/Foo.php', <<<'PHP' <?php namespace App\Livewire; use Livewire\Component; class Foo extends Component { // } PHP); Livewire::test('foo')->assertSee('Im foo'); } function test_can_assert_see_livewire_on_standard_blade_view_using_class_name() { Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $fakeClass = new class { function getContent() { return view('render-component', [ 'component' => 'foo', ])->render(); } }; $testResponse = new TestResponse($fakeClass); $testResponse->assertSeeLivewire(\App\Livewire\Foo::class); } function test_assert_see_livewire_fails_when_the_component_is_not_present() { $this->expectException(ExpectationFailedException::class); Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $fakeClass = new class { function getContent() { return view('null-view')->render(); } }; $testResponse = new TestResponse($fakeClass); $testResponse->assertSeeLivewire('foo'); } function test_assert_see_livewire_fails_when_the_component_is_not_present_using_class_name() { $this->expectException(ExpectationFailedException::class); Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $fakeClass = new class { function getContent() { return view('null-view')->render(); } }; $testResponse = new TestResponse($fakeClass); $testResponse->assertSeeLivewire(\App\Livewire\Foo::class); } function test_can_assert_dont_see_livewire_on_standard_blade_view() { $fakeClass = new class { function getContent() { return view('null-view')->render(); } }; $testResponse = new TestResponse($fakeClass); $testResponse->assertDontSeeLivewire('foo'); } function test_assert_dont_see_livewire_fails_when_the_component_is_present() { $this->expectException(ExpectationFailedException::class); Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $fakeClass = new class { function getContent() { return view('render-component', [ 'component' => 'foo', ])->render(); } }; $testResponse = new TestResponse($fakeClass); $testResponse->assertDontSeeLivewire('foo'); } function test_assert_dont_see_livewire_fails_when_the_component_is_present_using_class_name() { $this->expectException(ExpectationFailedException::class); Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $fakeClass = new class { function getContent() { return view('render-component', [ 'component' => 'foo', ])->render(); } }; $testResponse = new TestResponse($fakeClass); $testResponse->assertDontSeeLivewire(\App\Livewire\Foo::class); } function test_can_assert_dont_see_livewire_on_standard_blade_view_using_class_name() { Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $fakeClass = new class { function getContent() { return view('null-view')->render(); } }; $testResponse = new TestResponse($fakeClass); $testResponse->assertDontSeeLivewire(\App\Livewire\Foo::class); } function test_can_assert_see_livewire_on_test_view() { Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $testView = new TestView(view('render-component', [ 'component' => 'foo', ])); $testView->assertSeeLivewire('foo'); } function test_can_assert_see_livewire_on_test_view_refering_by_subfolder_without_dot_index() { Artisan::call('make:livewire', ['name' => 'bar.index', '--class' => true]); $testView = new TestView(view('render-component', [ 'component' => 'bar', ])); $testView->assertSeeLivewire('bar'); } function test_can_assert_dont_see_livewire_on_test_view() { Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $testView = new TestView(view('null-view')); $testView->assertDontSeeLivewire('foo'); } function test_cant_test_non_livewire_components() { $this->expectException(\Exception::class); Livewire::test(\stdClass::class); } function test_livewire_route_works_with_user_route_with_the_same_signature() { Route::get('/{param1}/{param2}', function() { throw new \Exception('I shouldn\'t get executed!'); }); Livewire::test(HasMountArguments::class, ['name' => 'foo']); $this->assertTrue(true); } function test_method_accepts_arguments_to_pass_to_mount() { $component = Livewire::test(HasMountArguments::class, ['name' => 'foo']); $this->assertStringContainsString('foo', $component->html()); } function test_set_multiple_with_array() { Livewire::test(HasMountArguments::class, ['name' => 'foo']) ->set(['name' => 'bar']) ->assertSetStrict('name', 'bar'); } function test_set_for_backed_enums() { Livewire::test(ComponentWithEnums::class) ->set('backedFooBarEnum', BackedFooBarEnum::FOO->value) ->assertSetStrict('backedFooBarEnum', BackedFooBarEnum::FOO) ->set('backedFooBarEnum', BackedFooBarEnum::FOO) ->assertSetStrict('backedFooBarEnum', BackedFooBarEnum::FOO); } function test_assert_set() { $component = Livewire::test(HasMountArguments::class, ['name' => 'foo']) ->assertSet('name', 'foo') ->set('name', 'info') ->assertSet('name', 'info') ->set('name', 'is_array') ->assertSet('name', 'is_array') ->set('name', 0) ->assertSet('name', null) ->assertSetStrict('name', 0) ->assertSet( 'name', function ($propertyValue) { return $propertyValue === 0; } ); $this->expectException(\PHPUnit\Framework\ExpectationFailedException::class); $component->assertSetStrict('name', null); } function test_assert_not_set() { $component = Livewire::test(HasMountArguments::class, ['name' => 'bar']) ->assertNotSet('name', 'foo') ->set('name', 100) ->assertNotSet('name', '1e2', true) ->set('name', 0) ->assertNotSet('name', false, true) ->assertNotSet('name', null, true); $this->expectException(\PHPUnit\Framework\ExpectationFailedException::class); $component->assertNotSet('name', null); } function test_assert_set_strict() { $component = Livewire::test(HasMountArguments::class, ['name' => 'foo']) ->set('name', '') ->assertSetStrict('name', ''); $this->expectException(\PHPUnit\Framework\ExpectationFailedException::class); $component->assertSetStrict('name', null); } function test_assert_not_set_strict() { $component = Livewire::test(HasMountArguments::class, ['name' => 'bar']) ->set('name', '') ->assertNotSetStrict('name', null); $this->expectException(\PHPUnit\Framework\ExpectationFailedException::class); $component->assertNotSetStrict('name', ''); } function test_assert_snapshot_set_strict() { $component = Livewire::test(HasMountArguments::class, ['name' => 'foo']) ->set('name', '') ->assertSnapshotSetStrict('name', ''); $this->expectException(\PHPUnit\Framework\ExpectationFailedException::class); $component->assertSnapshotSetStrict('name', null); } function test_assert_snapshot_not_set_strict() { $component = Livewire::test(HasMountArguments::class, ['name' => 'foo']) ->set('name', '') ->assertSnapshotNotSetStrict('name', null); $this->expectException(\PHPUnit\Framework\ExpectationFailedException::class); $component->assertSnapshotNotSetStrict('name', ''); } function test_assert_count() { Livewire::test(HasMountArgumentsButDoesntPassThemToBladeView::class, ['name' => ['foo']]) ->assertCount('name', 1) ->set('name', ['foo', 'bar']) ->assertCount('name', 2) ->set('name', ['foo', 'bar', 'baz']) ->assertCount('name', 3) ->set('name', []) ->assertCount('name', 0); } function test_assert_see() { Livewire::test(HasMountArguments::class, ['name' => 'should see me']) ->assertSee('should see me'); } function test_assert_see_unescaped() { Livewire::test(HasHtml::class) ->assertSee('<p style', false); } function test_assert_see_multiple() { Livewire::test(HasMountArguments::class, ['name' => 'should see me']) ->assertSee(['should', 'see', 'me']); } function test_assert_see_html() { Livewire::test(HasHtml::class) ->assertSeeHtml('<p style="display: none">Hello HTML</p>'); } function test_assert_dont_see_html() { Livewire::test(HasHtml::class) ->assertDontSeeHtml('<span style="display: none">Hello HTML</span>'); } function test_assert_dont_see() { Livewire::test(HasMountArguments::class, ['name' => 'should see me']) ->assertDontSee('no one should see this'); } function test_assert_dont_see_unescaped() { Livewire::test(HasHtml::class) ->assertDontSee('<span>', false); } function test_assert_dont_see_multiple() { Livewire::test(HasMountArguments::class, ['name' => 'should see me']) ->assertDontSee(['nobody', 'really', 'knows']); } function test_assert_see_doesnt_include_wire_id_and_wire_data_attribute() { /* * See for more info: https://github.com/calebporzio/livewire/issues/62 * Regex test: https://regex101.com/r/UhjREC/2/ */ Livewire::test(HasMountArgumentsButDoesntPassThemToBladeView::class, ['name' => 'shouldnt see me']) ->assertDontSee('shouldnt see me'); } function test_assert_dispatched() { Livewire::test(DispatchesEventsComponentStub::class) ->call('dispatchFoo') ->assertDispatched('foo') ->call('dispatchFooWithParam', 'bar') ->assertDispatched('foo', 'bar') ->call('dispatchFooWithParam', 'info') ->assertDispatched('foo', 'info') ->call('dispatchFooWithParam', 'last') ->assertDispatched('foo', 'last') ->call('dispatchFooWithParam', 'retry') ->assertDispatched('foo', 'retry') ->call('dispatchFooWithParam', 'baz') ->assertDispatched('foo', function ($event, $params) { return $event === 'foo' && $params === ['baz']; }); } function test_assert_dispatched_to() { Livewire::component('some-component', SomeComponentStub::class); Livewire::test(DispatchesEventsComponentStub::class) ->call('dispatchFooToSomeComponent') ->assertDispatchedTo('some-component', 'foo') ->call('dispatchFooToAComponentAsAModel') ->assertDispatchedTo(ComponentWhichReceivesEvent::class, 'foo') ->call('dispatchFooToSomeComponentWithParam', 'bar') ->assertDispatchedTo('some-component', 'foo', 'bar') ->call('dispatchFooToSomeComponentWithParam', 'bar') ->assertDispatchedTo('some-component','foo', function ($event, $params) { return $event === 'foo' && $params === ['bar']; }) ; } function test_assert_not_dispatched() { Livewire::test(DispatchesEventsComponentStub::class) ->assertNotDispatched('foo') ->call('dispatchFoo') ->assertNotDispatched('bar') ->call('dispatchFooWithParam', 'not-bar') ->assertNotDispatched('foo', 'bar') ->call('dispatchFooWithParam', 'foo') ->assertNotDispatched('bar', 'foo') ->call('dispatchFooWithParam', 'baz') ->assertNotDispatched('bar', function ($event, $params) { return $event !== 'bar' && $params === ['baz']; }) ->call('dispatchFooWithParam', 'baz') ->assertNotDispatched('foo', function ($event, $params) { return $event !== 'foo' && $params !== ['bar']; }); } function test_assert_has_errors() { Livewire::test(ValidatesDataWithSubmitStub::class) ->call('submit') ->assertHasErrors() ->assertHasErrors('foo') ->assertHasErrors(['foo']) ->assertHasErrors(['foo' => 'required']) ->assertHasErrors(['foo' => 'The foo field is required.']) ->assertHasErrors(['foo' => 'required', 'bar' => 'required']) ->assertHasErrors(['foo' => 'The foo field is required.', 'bar' => 'The bar field is required.']) ->assertHasErrors(['foo' => ['The foo field is required.'], 'bar' => ['The bar field is required.']]) ->assertHasErrors(['foo' => function ($rules, $messages) { return in_array('required', $rules) && in_array('The foo field is required.', $messages); }]) ; } function test_assert_has_errors_with_validation_class() { Livewire::test(ValidatesDataWithCustomRuleStub::class) ->call('submit') ->assertHasErrors() ->assertHasErrors('foo') ->assertHasErrors(['foo']) ->assertHasErrors(['foo' => CustomValidationRule::class]) ->assertHasErrors(['foo' => 'My custom message']) ->assertHasErrors(['foo' => function ($rules, $messages) { return in_array(CustomValidationRule::class, $rules) && in_array('My custom message', $messages); }]) ->set('foo', true) ->call('submit') ->assertHasNoErrors() ->assertHasNoErrors('foo') ->assertHasNoErrors(['foo']) ->assertHasNoErrors(['foo' => CustomValidationRule::class]) ->assertHasNoErrors(['foo' => 'My custom message']) ; } function test_assert_has_error_with_manually_added_error() { Livewire::test(ValidatesDataWithSubmitStub::class) ->call('manuallyAddError') ->assertHasErrors('bob'); } function test_assert_has_error_with_submit_validation() { Livewire::test(ValidatesDataWithSubmitStub::class) ->call('submit') ->assertHasErrors('foo') ->assertHasErrors(['foo', 'bar']) ->assertHasErrors([ 'foo' => ['required'], 'bar' => ['required'], ]); } function test_assert_has_error_with_real_time_validation() { Livewire::test(ValidatesDataWithRealTimeStub::class) // ->set('foo', 'bar-baz') // ->assertHasNoErrors() ->set('foo', 'bar') ->assertHasErrors('foo') ->assertHasNoErrors('bar') ->assertHasErrors(['foo']) ->assertHasErrors([ 'foo' => ['min'], ]) ->assertHasNoErrors([ 'foo' => ['required'], ]) ->set('bar', '') ->assertHasErrors(['foo', 'bar']); } function test_it_ignores_rules_with_params() { Livewire::test(ValidatesDataWithRulesHasParams::class) ->call('submit') ->assertHasErrors(['foo' => 'min']) ->assertHasErrors(['foo' => 'min:2']) ->set('foo', 'FOO') ->assertHasNoErrors(['foo' => 'min']) ->assertHasNoErrors(['foo' => 'min:2']); } function test_assert_response_of_calling_method() { Livewire::test(ComponentWithMethodThatReturnsData::class) ->call('foo') ->assertReturned('bar') ->assertReturned(fn ($data) => $data === 'bar'); } public function test_can_set_cookies_for_use_with_testing() { // Test both the `withCookies` and `withCookie` methods that Laravel normally provides Livewire::withCookies(['colour' => 'blue']) ->withCookie('name', 'Taylor') ->test(new class extends TestComponent { public $colourCookie = ''; public $nameCookie = ''; public function mount() { $this->colourCookie = request()->cookie('colour'); $this->nameCookie = request()->cookie('name'); } }) ->assertSetStrict('colourCookie', 'blue') ->assertSetStrict('nameCookie', 'Taylor') ; } public function test_can_set_headers_for_use_with_testing() { Livewire::withHeaders(['colour' => 'blue', 'name' => 'Taylor']) ->test(new class extends TestComponent { public $colourHeader = ''; public $nameHeader = ''; public function mount() { $this->colourHeader = request()->header('colour'); $this->nameHeader = request()->header('name'); } }) ->assertSetStrict('colourHeader', 'blue') ->assertSetStrict('nameHeader', 'Taylor') ; } public function test_can_set_cookies_and_use_it_for_testing_subsequent_request() { // Test both the `withCookies` and `withCookie` methods that Laravel normally provides Livewire::withCookies(['colour' => 'blue'])->withCookie('name', 'Taylor') ->test(new class extends TestComponent { public $colourCookie = ''; public $nameCookie = ''; public function setTheCookies() { $this->colourCookie = request()->cookie('colour'); $this->nameCookie = request()->cookie('name'); } }) ->call('setTheCookies') ->assertSetStrict('colourCookie', 'blue') ->assertSetStrict('nameCookie', 'Taylor'); } } class HasMountArguments extends Component { public $name; function mount($name) { $this->name = $name; } function render() { return app('view')->make('show-name-with-this'); } } class HasHtml extends Component { function render() { return '<div><p style="display: none">Hello HTML</p></div>'; } } class SomeComponentStub extends TestComponent { } class HasMountArgumentsButDoesntPassThemToBladeView extends TestComponent { public $name; function mount($name) { $this->name = $name; } } class DispatchesEventsComponentStub extends TestComponent { function dispatchFoo() { $this->dispatch('foo'); } function dispatchFooWithParam($param) { $this->dispatch('foo', $param); } function dispatchFooToSomeComponent() { $this->dispatch('foo')->to('some-component'); } function dispatchFooToSomeComponentWithParam($param) { $this->dispatch('foo', $param)->to('some-component'); } function dispatchFooToAComponentAsAModel() { $this->dispatch('foo')->to(ComponentWhichReceivesEvent::class); } } class CustomValidationRule implements ValidationRule { public function validate(string $attribute, mixed $value, Closure $fail): void { if ($value === false) { $fail('My custom message'); } } } class ValidatesDataWithCustomRuleStub extends TestComponent { public bool $foo = false; function submit() { $this->validate([ 'foo' => new CustomValidationRule, ]); } } class ValidatesDataWithSubmitStub extends TestComponent { public $foo; public $bar; function submit() { $this->validate([ 'foo' => 'required', 'bar' => 'required', ]); } function manuallyAddError() { $this->addError('bob', 'lob'); } } class ValidatesDataWithRealTimeStub extends TestComponent { public $foo; public $bar; function updated($field) { $this->validateOnly($field, [ 'foo' => 'required|min:6', 'bar' => 'required', ]); } } class ValidatesDataWithRulesHasParams extends TestComponent { public $foo, $bar; function submit() { $this->validate([ 'foo' => 'string|min:2', ]); } } class ComponentWhichReceivesEvent extends Component { } class ComponentWithMethodThatReturnsData extends TestComponent { function foo() { return 'bar'; } } class ComponentWithEnums extends TestComponent { public BackedFooBarEnum $backedFooBarEnum; } enum BackedFooBarEnum : string { case FOO = 'foo'; case BAR = 'bar'; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/DuskTestable.php
src/Features/SupportTesting/DuskTestable.php
<?php namespace Livewire\Features\SupportTesting; use Illuminate\Support\Facades\Route; use Laravel\Dusk\Browser; use PHPUnit\Framework\TestCase; use function Livewire\{ invade, on }; use Illuminate\Support\Arr; class DuskTestable { public static $currentTestCase; public static $shortCircuitCreateCall = false; public static $isTestProcess = false; public static $browser; static function provide() { Route::get('livewire-dusk/{component}', ShowDuskComponent::class)->middleware('web'); on('browser.testCase.setUp', function ($testCase) { static::$currentTestCase = $testCase; static::$isTestProcess = true; $tweakApplication = $testCase::tweakApplicationHook(); invade($testCase)->beforeServingApplication(function ($app, $config) use ($tweakApplication) { $config->set('app.debug', true); if (is_callable($tweakApplication)) $tweakApplication(); static::loadTestComponents(); }); }); on('browser.testCase.tearDown', function () { static::wipeRuntimeComponentRegistration(); static::$browser && static::$browser->quit(); static::$currentTestCase = null; }); if (isset($_SERVER['CI']) && class_exists(\Orchestra\Testbench\Dusk\Options::class)) { \Orchestra\Testbench\Dusk\Options::withoutUI(); } \Laravel\Dusk\Browser::mixin(new DuskBrowserMacros); } /** * @return Browser */ static function create($components, $params = [], $queryParams = []) { $components = is_array($components) ? $components : [$components]; $firstComponent = array_shift($components); if (is_string($firstComponent) && ! class_exists($firstComponent)) { // Simple component name (eg. `counter`) $id = $firstComponent; $components = [$firstComponent, ...$components]; } else { if (is_string($firstComponent)) { // Component class name (eg. `App\Livewire\Counter`) $className = $firstComponent; } else { // Anonymous class instance (eg. `new class extends Component {}`) // Remove the runtime '$123' suffix to make the class name stable $className = str()->beforeLast($firstComponent::class, '$'); } // A string ID that can be used in the URL $id = 'a' . substr(md5($className), 0, 8); $components = [$id => $firstComponent, ...$components]; } return static::createBrowser($id, $components, $params, $queryParams)->visit('/livewire-dusk/'.$id.'?'.Arr::query($queryParams)); } static function createBrowser($id, $components, $params = [], $queryParams = []) { if (static::$shortCircuitCreateCall) { throw new class ($components) extends \Exception { public $components; public $isDuskShortcircuit = true; function __construct($components) { $this->components = $components; } }; } [$class, $method] = static::findTestClassAndMethodThatCalledThis(); static::registerComponentsForNextTest([$id, $class, $method]); $testCase = invade(static::$currentTestCase); return static::$browser = $testCase->newBrowser($testCase->createWebDriver()); } static function actingAs(\Illuminate\Contracts\Auth\Authenticatable $user, $driver = null) { // } static function findTestClassAndMethodThatCalledThis() { $traces = debug_backtrace(options: DEBUG_BACKTRACE_IGNORE_ARGS, limit: 10); foreach ($traces as $trace) { if (is_subclass_of($trace['class'], TestCase::class)) { return [$trace['class'], $trace['function']]; } } throw new \Exception; } static function loadTestComponents() { if (static::$isTestProcess) return; $tmp = __DIR__ . '/_runtime_components.json'; if (file_exists($tmp)) { // We can't just "require" this file because of race conditions... [$id, $testClass, $method] = json_decode(file_get_contents($tmp), associative: true); if (! method_exists($testClass, $method)) return; static::$shortCircuitCreateCall = true; $components = null; try { if (\Orchestra\Testbench\phpunit_version_compare('10.0', '>=')) { (new $testClass($method))->$method(); } else { (new $testClass())->$method(); } } catch (\Exception $e) { if (! $e->isDuskShortcircuit) throw $e; $components = $e->components; } static::$shortCircuitCreateCall = false; foreach ($components as $name => $class) { if (is_object($class)) $class = $class::class; if (is_numeric($name)) { app('livewire')->component($class); } else { app('livewire')->component($name, $class); } } } } static function registerComponentsForNextTest($components) { $tmp = __DIR__ . '/_runtime_components.json'; file_put_contents($tmp, json_encode($components, JSON_PRETTY_PRINT)); } static function wipeRuntimeComponentRegistration() { $tmp = __DIR__ . '/_runtime_components.json'; file_exists($tmp) && unlink($tmp); } function breakIntoATinkerShell($browsers, $e) { $sh = new \Psy\Shell(); $sh->add(new \Laravel\Dusk\Console\DuskCommand($this, $e)); $sh->setScopeVariables([ 'browsers' => $browsers, ]); $sh->addInput('dusk'); $sh->setBoundObject($this); $sh->run(); return $sh->getScopeVariables(false); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/RequestBroker.php
src/Features/SupportTesting/RequestBroker.php
<?php namespace Livewire\Features\SupportTesting; use Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling; use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests; use Symfony\Component\HttpKernel\Exception\HttpException; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Contracts\Debug\ExceptionHandler; class RequestBroker { use MakesHttpRequests, InteractsWithExceptionHandling; protected $app; function __construct($app) { $this->app = $app; } function temporarilyDisableExceptionHandlingAndMiddleware($callback) { $cachedHandler = app(ExceptionHandler::class); $cachedShouldSkipMiddleware = $this->app->shouldSkipMiddleware(); $this->withoutExceptionHandling([HttpException::class, AuthorizationException::class])->withoutMiddleware(); $result = $callback($this); $this->app->instance(ExceptionHandler::class, $cachedHandler); if (! $cachedShouldSkipMiddleware) { unset($this->app['middleware.disable']); } return $result; } function withoutHandling($except = []) { return $this->withoutExceptionHandling($except); } function addHeaders(array $headers) { $this->serverVariables = $this->transformHeadersToServerVars($headers); return $this; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php
src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php
<?php namespace Livewire\Features\SupportTesting\Tests; use Symfony\Component\HttpKernel\Exception\HttpException; use Livewire\Component; use Livewire\Livewire; use Tests\TestComponent; class TestableLivewireCanAssertStatusCodesUnitTest extends \Tests\TestCase { function test_can_assert_a_status_code_when_an_exception_is_encountered() { $component = Livewire::test(NotFoundComponent::class); $component->assertStatus(404); } function test_can_assert_a_404_status_code_when_an_exception_is_encountered() { $component = Livewire::test(NotFoundComponent::class); $component->assertNotFound(); } function test_can_assert_a_401_status_code_when_an_exception_is_encountered() { $component = Livewire::test(UnauthorizedComponent::class); $component->assertUnauthorized(); } function test_can_assert_a_403_status_code_when_an_exception_is_encountered() { $component = Livewire::test(ForbiddenComponent::class); $component->assertForbidden(); } function test_can_assert_a_403_status_code_when_an_exception_is_encountered_on_an_action() { $component = Livewire::test(new class extends TestComponent { public function someAction() { throw new \Illuminate\Auth\Access\AuthorizationException; } }); $component ->call('someAction') ->assertForbidden(); } function test_can_assert_status_and_continue_making_livewire_assertions() { Livewire::test(NormalComponent::class) ->assertStatus(200) ->assertSee('Hello!') ->assertSeeHtml('</example>'); } } class NotFoundComponent extends Component { function render() { throw new HttpException(404); } } class UnauthorizedComponent extends Component { function render() { throw new HttpException(401); } } class ForbiddenComponent extends Component { function render() { throw new HttpException(403); } } class NormalComponent extends Component { function render() { return '<example>Hello!</example>'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertViewIsUnitTest.php
src/Features/SupportTesting/Tests/TestableLivewireCanAssertViewIsUnitTest.php
<?php namespace Livewire\Features\SupportTesting\Tests; use Livewire\Livewire; use Tests\TestComponent; class TestableLivewireCanAssertViewIsUnitTest extends \Tests\TestCase { function test_can_assert_view_is() { Livewire::test(ViewComponent::class) ->assertViewIs('null-view'); } } class ViewComponent extends TestComponent { function render() { return view('null-view'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertNoRedirectUnitTest.php
src/Features/SupportTesting/Tests/TestableLivewireCanAssertNoRedirectUnitTest.php
<?php namespace Livewire\Features\SupportTesting\Tests; use Livewire\Livewire; use Tests\TestComponent; class TestableLivewireCanAssertNoRedirectUnitTest extends \Tests\TestCase { function test_can_assert_no_redirect() { $component = Livewire::test(NoRedirectComponent::class); $component->call('performNoRedirect'); $component->assertNoRedirect(); } function test_can_assert_no_redirect_will_fail_if_redirected() { $component = Livewire::test(NoRedirectComponent::class); $this->expectException(\PHPUnit\Framework\AssertionFailedError::class); $component->call('performRedirect'); $component->assertNoRedirect(); } function test_can_assert_no_redirect_on_plain_component() { $component = Livewire::test(PlainRenderingComponent::class); $component->assertNoRedirect(); } } class PlainRenderingComponent extends TestComponent { } class NoRedirectComponent extends TestComponent { function performRedirect() { $this->redirect('/some'); } function performNoRedirect() { $this->dispatch('noRedirect'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/Tests/TestableLivewireCanBeInvaded.php
src/Features/SupportTesting/Tests/TestableLivewireCanBeInvaded.php
<?php namespace Livewire\Features\SupportTesting\Tests; use Livewire\Livewire; use PHPUnit\Framework\Assert as PHPUnit; use Tests\TestComponent; class TestableLivewireCanBeInvaded extends \Tests\TestCase { function test_can_invade_protected_properties() { $component = Livewire::test(new class extends TestComponent { protected string $foo = 'bar'; }); PHPUnit::assertEquals('bar', $component->invade()->foo); } function test_can_invade_protected_functions() { $component = Livewire::test(new class extends TestComponent { protected function foo() : string { return 'bar'; } }); PHPUnit::assertEquals('bar', $component->invade()->foo()); } function test_can_invade_private_properties() { $component = Livewire::test(new class extends TestComponent { private string $foo = 'bar'; }); PHPUnit::assertEquals('bar', $component->invade()->foo); } function test_can_invade_private_functions() { $component = Livewire::test(new class extends TestComponent { private function foo() : string { return 'bar'; } }); PHPUnit::assertEquals('bar', $component->invade()->foo()); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertPropertiesUnitTest.php
src/Features/SupportTesting/Tests/TestableLivewireCanAssertPropertiesUnitTest.php
<?php namespace Livewire\Features\SupportTesting\Tests; use Livewire\Livewire; use Tests\TestComponent; class TestableLivewireCanAssertPropertiesUnitTest extends \Tests\TestCase { function test_can_assert_basic_property_value() { Livewire::test(PropertyTestingComponent::class) ->assertSetStrict('foo', 'bar') ->set('foo', 'baz') ->assertSetStrict('foo', 'baz'); } function test_can_assert_computed_property_value() { Livewire::test(PropertyTestingComponent::class) ->assertSetStrict('bob', 'lob'); } function test_swallows_property_not_found_exceptions() { Livewire::test(PropertyTestingComponent::class) ->assertSetStrict('nonExistentProperty', null); } function test_throws_non_property_not_found_exceptions() { $this->markTestSkipped('In V2 computed properties are "LAZY", what should we do in V3?'); $this->expectException(\Exception::class); Livewire::test(ComputedPropertyWithExceptionTestingComponent::class) ->assertSetStrict('throwsException', null); } } class PropertyTestingComponent extends TestComponent { public $foo = 'bar'; function getBobProperty() { return 'lob'; } } class ComputedPropertyWithExceptionTestingComponent extends TestComponent { function getThrowsExceptionProperty() { throw new \Exception('Test exception'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertRedirectUnitTest.php
src/Features/SupportTesting/Tests/TestableLivewireCanAssertRedirectUnitTest.php
<?php namespace Livewire\Features\SupportTesting\Tests; use Livewire\Livewire; use Tests\TestComponent; class TestableLivewireCanAssertRedirectUnitTest extends \Tests\TestCase { function test_can_assert_a_redirect_without_a_uri() { $component = Livewire::test(RedirectComponent::class); $component->call('performRedirect'); $component->assertRedirect(); } function test_can_assert_a_redirect_with_a_uri() { $component = Livewire::test(RedirectComponent::class); $component->call('performRedirect'); $component->assertRedirect('/some'); } function test_can_detect_failed_redirect() { $component = Livewire::test(RedirectComponent::class); $this->expectException(\PHPUnit\Framework\AssertionFailedError::class); $component->assertRedirect(); } } class RedirectComponent extends TestComponent { function performRedirect() { $this->redirect('/some'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertRedirectToRouteUnitTest.php
src/Features/SupportTesting/Tests/TestableLivewireCanAssertRedirectToRouteUnitTest.php
<?php namespace Livewire\Features\SupportTesting\Tests; use Livewire\Livewire; use Illuminate\Support\Facades\Route; use Tests\TestComponent; class TestableLivewireCanAssertRedirectToRouteUnitTest extends \Tests\TestCase { public function setUp(): void { parent::setUp(); Route::get('foo', function () { return true; })->name('foo'); } function test_can_assert_a_redirect_to_a_route() { $component = Livewire::test(RedirectRouteComponent::class); $component->call('performRedirect'); $component->assertRedirectToRoute('foo'); } function test_can_detect_failed_redirect() { $component = Livewire::test(RedirectRouteComponent::class); $this->expectException(\PHPUnit\Framework\AssertionFailedError::class); $component->assertRedirectToRoute('foo'); } } class RedirectRouteComponent extends TestComponent { function performRedirect() { $this->redirectRoute('foo'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJsModules/SupportJsModules.php
src/Features/SupportJsModules/SupportJsModules.php
<?php namespace Livewire\Features\SupportJsModules; use Illuminate\Support\Facades\Route; use Livewire\ComponentHook; use Livewire\Drawer\Utils; use Livewire\Mechanisms\HandleRequests\EndpointResolver; class SupportJsModules extends ComponentHook { static function provide() { Route::get(EndpointResolver::componentJsPath(), function ($component) { $component = str_replace('----', ':', $component); $component = str_replace('---', '::', $component); $component = str_replace('--', '.', $component); $instance = app('livewire')->new($component); if (! method_exists($instance, 'scriptModuleSrc')) { throw new \Exception('Component '.$component.' does not have a script source.'); } $path = $instance->scriptModuleSrc(); if (! file_exists($path)) { throw new \Exception('Script file not found: '.$path); } $source = file_get_contents($path); $filemtime = filemtime($path); return Utils::pretendResponseIsFileFromString( $source, $filemtime, $component.'.js', ); }); } public function dehydrate($context) { if (! $context->isMounting()) return; if (method_exists($this->component, 'scriptModuleSrc')) { $path = $this->component->scriptModuleSrc(); $filemtime = filemtime($path); $hash = crc32($filemtime); $context->addEffect('scriptModule', $hash); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportQueryString/SupportQueryString.php
src/Features/SupportQueryString/SupportQueryString.php
<?php namespace Livewire\Features\SupportQueryString; use function Livewire\invade; use Livewire\ComponentHook; class SupportQueryString extends ComponentHook { public $queryString; /** * Note: this is support for the legacy syntax... */ function mount() { if (! $queryString = $this->getQueryString()) return; foreach ($queryString as $key => $value) { $key = is_string($key) ? $key : $value; $alias = $value['as'] ?? $key; $history = $value['history'] ?? true; $keep = $value['alwaysShow'] ?? $value['keep'] ?? false; $except = $value['except'] ?? null; $this->component->setPropertyAttribute($key, new BaseUrl(as: $alias, history: $history, keep: $keep, except: $except)); } } public function getQueryString() { if (isset($this->queryString)) return $this->queryString; $component = $this->component; $componentQueryString = []; if (method_exists($component, 'queryString')) $componentQueryString = invade($component)->queryString(); elseif (property_exists($component, 'queryString')) $componentQueryString = invade($component)->queryString; return $this->queryString = collect(class_uses_recursive($class = $component::class)) ->map(function ($trait) use ($class, $component) { $member = 'queryString' . class_basename($trait); if (method_exists($class, $member)) { return invade($component)->{$member}(); } if (property_exists($class, $member)) { return invade($component)->{$member}; } return []; }) ->values() ->mapWithKeys(function ($value) { return $value; }) ->merge($componentQueryString) ->toArray(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportQueryString/BaseUrl.php
src/Features/SupportQueryString/BaseUrl.php
<?php namespace Livewire\Features\SupportQueryString; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; use Livewire\Features\SupportFormObjects\Form; use ReflectionClass; #[\Attribute] class BaseUrl extends LivewireAttribute { public function __construct( public $as = null, public $history = false, public $keep = false, public $except = null, public $nullable = null, ) {} public function mount() { $this->nullable = $this->determineNullability(); $this->setPropertyFromQueryString(); } public function dehydrate($context) { if (! $context->mounting) return; $this->pushQueryStringEffect($context); } protected function determineNullability() { // It's nullable if they passed it in like: #[Url(nullable: true)] if ($this->nullable !== null) return $this->nullable; $reflectionClass = new ReflectionClass($this->getSubTarget() ?? $this->getComponent()); // It's nullable if there's a nullable typehint like: public ?string $foo; if ($this->getSubName() && $reflectionClass->hasProperty($this->getSubName())) { $property = $reflectionClass->getProperty($this->getSubName()); return $property->getType()?->allowsNull() ?? false; } return false; } public function setPropertyFromQueryString() { if ($this->as === null && $this->isOnFormObjectProperty()) { $this->as = $this->getSubName(); } $nonExistentValue = uniqid('__no_exist__', true); $initialValue = $this->getFromUrlQueryString($this->urlName(), $nonExistentValue); if ($initialValue === $nonExistentValue) return; $decoded = is_array($initialValue) ? json_decode(json_encode($initialValue), true) : json_decode($initialValue ?? '', true); // If only part of an array is present in the query string, // we want to merge instead of override the value... if (is_array($decoded) && is_array($original = $this->getValue())) { $decoded = $this->recursivelyMergeArraysWithoutAppendingDuplicateValues($original, $decoded); } // Handle empty strings differently depending on if this // field is considered "nullable" by typehint or API. if ($initialValue === null) { $value = $this->nullable ? null : ''; } else { $value = $decoded === null ? $initialValue : $decoded; } $this->setValue($value, $this->nullable); } protected function recursivelyMergeArraysWithoutAppendingDuplicateValues(&$array1, &$array2) { $merged = $array1; foreach ($array2 as $key => &$value) { if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) { $merged[$key] = $this->recursivelyMergeArraysWithoutAppendingDuplicateValues($merged[$key], $value); } else { $merged[$key] = $value; } } return $merged; } public function pushQueryStringEffect($context) { $queryString = [ 'as' => $this->as, 'use' => $this->history ? 'push' : 'replace', 'alwaysShow' => $this->keep, 'except' => $this->except, ]; $context->pushEffect('url', $queryString, $this->getName()); } public function isOnFormObjectProperty() { $subTarget = $this->getSubTarget(); return $subTarget && is_subclass_of($subTarget, Form::class); } public function urlName() { return $this->as ?? $this->getName(); } public function getFromUrlQueryString($name, $default = null) { if (! app('livewire')->isLivewireRequest()) { $value = request()->query($this->urlName(), $default); // If the property is present in the querystring without a value, then Laravel returns // the $default value. We want to return null in this case, so we can differentiate // between "not present" and "present with no value". If the request is a Livewire // request, we don't have that issue as we use PHP's parse_str function. if (array_key_exists($name, request()->query()) && $value === $default) { return null; } return $value; } // If this is a subsequent ajax request, we can't use Laravel's standard "request()->query()"... return $this->getFromRefererUrlQueryString( request()->header('Referer'), $name, $default ); } public function getFromRefererUrlQueryString($url, $key, $default = null) { $parsedUrl = parse_url($url ?? ''); $query = []; if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $query); } return $query[$key] ?? $default; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportQueryString/BrowserTest.php
src/Features/SupportQueryString/BrowserTest.php
<?php namespace Livewire\Features\SupportQueryString; use Livewire\Livewire; use Livewire\Component; use Livewire\Attributes\Url; use Livewire\Features\SupportTesting\DuskTestable; class BrowserTest extends \Tests\BrowserTestCase { public function test_it_does_not_add_null_values_to_the_query_string_array() { Livewire::visit([ new class extends \Livewire\Component { #[Url] public array $tableFilters = [ 'filter_1' => [ 'value' => null, ], 'filter_2' => [ 'value' => null, ], 'filter_3' => [ 'value' => null, ] ]; public function render() { return <<<'HTML' <div> <input wire:model.live="tableFilters.filter_1.value" type="text" dusk="filter_1" /> <input wire:model.live="tableFilters.filter_2.value" type="text" dusk="filter_2" /> <input wire:model.live="tableFilters.filter_3.value" type="text" dusk="filter_3" /> </div> HTML; } }, ]) ->assertInputValue('@filter_1', '') ->assertInputValue('@filter_2', '') ->assertInputValue('@filter_3', '') ->assertQueryStringMissing('tableFilters') ->type('@filter_1', 'test') ->waitForLivewire() // Wait for the changes to be applied... ->pause(5) ->assertScript( '(new URLSearchParams(window.location.search)).toString()', 'tableFilters%5Bfilter_1%5D%5Bvalue%5D=test' ) ->refresh() ->assertInputValue('@filter_1', 'test') ; } public function test_keep_option_does_not_duplicate_url_query_string_for_array_parameters_on_page_load() { Livewire::withQueryParams([ 'filters' => [ 'startDate' => '2024-01-01', 'endDate' => '2024-09-05', ] ])->visit([ new class extends Component { #[BaseUrl(keep: true)] public array $filters = [ 'startDate' => '', 'endDate' => '', ]; public function render() { return <<<'HTML' <div> <input type="text" dusk="startDate" wire:model.live="filters.startDate" /> <input type="text" dusk="endDate" wire:model.live="filters.endDate" /> </div> HTML; } }, ]) ->assertScript('return window.location.search', '?filters[startDate]=2024-01-01&filters[endDate]=2024-09-05'); } public function test_does_not_duplicate_url_query_string_for_array_parameters_on_page_load() { Livewire::withQueryParams([ 'filters' => [ 'startDate' => '2024-01-01', 'endDate' => '2024-09-05', ] ])->visit([ new class extends Component { #[BaseUrl] public array $filters = [ 'startDate' => '', 'endDate' => '', ]; public function render() { return <<<'HTML' <div> <input type="text" dusk="startDate" wire:model.live="filters.startDate" /> <input type="text" dusk="endDate" wire:model.live="filters.endDate" /> </div> HTML; } }, ]) ->assertScript('return window.location.search', '?filters[startDate]=2024-01-01&filters[endDate]=2024-09-05'); } public function test_keep_option_does_not_duplicate_url_query_string_for_string_parameter_on_page_load() { Livewire::withQueryParams([ 'date' => '2024-01-01', ])->visit([ new class extends Component { #[BaseUrl(keep: true)] public $date = ''; public function render() { return <<<'HTML' <div> <input type="text" dusk="date" wire:model.live="date" /> </div> HTML; } }, ]) ->assertScript('return window.location.search', '?date=2024-01-01'); } public function can_encode_url_containing_spaces_and_commas() { Livewire::visit([ new class extends Component { #[BaseUrl] public $space = ''; #[BaseUrl] public $comma = ''; public function render() { return <<<'HTML' <div> <input type="text" dusk="space" wire:model.live="space" /> <input type="text" dusk="comma" wire:model.live="comma" /> </div> HTML; } }, ]) ->waitForLivewire() ->type('@space', 'foo bar') ->type('@comma', 'foo,bar') ->assertScript('return !! window.location.search.match(/space=foo\+bar/)') ->assertScript('return !! window.location.search.match(/comma=foo\,bar/)'); } public function test_can_encode_url_containing_reserved_characters() { Livewire::visit([ new class extends Component { #[BaseUrl] public $exclamation = ''; #[BaseUrl] public $quote = ''; #[BaseUrl] public $parentheses = ''; #[BaseUrl] public $asterisk = ''; public function render() { return <<<'HTML' <div> <input type="text" dusk="exclamation" wire:model.live="exclamation" /> <input type="text" dusk="quote" wire:model.live="quote" /> <input type="text" dusk="parentheses" wire:model.live="parentheses" /> <input type="text" dusk="asterisk" wire:model.live="asterisk" /> </div> HTML; } }, ]) ->waitForLivewire() ->type('@exclamation', 'foo!') ->type('@parentheses', 'foo(bar)') ->type('@asterisk', 'foo*') // Wait for the changes to be applied... ->pause(5) ->assertScript('return !! window.location.search.match(/exclamation=foo\!/)') ->assertScript('return !! window.location.search.match(/parentheses=foo\(bar\)/)') ->assertScript('return !! window.location.search.match(/asterisk=foo\*/)') ; } public function test_can_use_a_value_other_than_initial_for_except_behavior() { Livewire::visit([ new class extends Component { #[BaseUrl(except: '')] public $search = ''; public function mount() { $this->search = 'foo'; } public function render() { return <<<'HTML' <div> <input type="text" dusk="input" wire:model.live="search" /> </div> HTML; } }, ]) ->assertQueryStringHas('search', 'foo') ->waitForLivewire()->type('@input', 'bar') ->assertQueryStringHas('search', 'bar') ->waitForLivewire()->type('@input', ' ') ->waitForLivewire()->keys('@input', '{backspace}') ->assertQueryStringMissing('search') ; } public function test_except_removes_property_from_query_string_when_original_value_set_from_query_string() { Livewire::withQueryParams(['filter1' => 'some', 'filter2' => 'none'])->visit([ new class extends Component { #[BaseUrl(except: '')] public $filter1 = ''; #[BaseUrl(except: 'all')] public $filter2 = 'all'; public function render() { return <<<'HTML' <div> <select dusk="filter1" wire:model.change="filter1"> <option value="">All</option> <option value="some">Some</option> <option value="none">None</option> </select> <div dusk="output1"> @switch($filter1) @case('') <div>All</div> @case('some') <div>Some</div> @break @endswitch </div> <select dusk="filter2" wire:model.change="filter2"> <option value="all">All</option> <option value="some">Some</option> <option value="none">None</option> </select> <div dusk="output2"> @switch($filter2) @case('all') <div>All</div> @case('some') <div>Some</div> @break @endswitch </div> </div> HTML; } }, ]) ->assertQueryStringHas('filter1', 'some') ->assertDontSeeIn('@output1', 'All') ->assertSeeIn('@output1', 'Some') ->assertQueryStringHas('filter2', 'none') ->assertDontSeeIn('@output2', 'All') ->assertDontSeeIn('@output2', 'Some') ->waitForLivewire()->select('@filter1', '') ->assertQueryStringMissing('filter1') ->assertSeeIn('@output1', 'All') ->assertSeeIn('@output1', 'Some') ->assertQueryStringHas('filter2', 'none') ->assertDontSeeIn('@output2', 'All') ->assertDontSeeIn('@output2', 'Some') ->waitForLivewire()->select('@filter2', 'all') ->assertQueryStringMissing('filter1') ->assertSeeIn('@output1', 'All') ->assertSeeIn('@output1', 'Some') ->assertQueryStringMissing('filter2') ->assertSeeIn('@output2', 'All') ->assertSeeIn('@output2', 'Some') ->waitForLivewire()->select('@filter1', 'none') ->assertQueryStringHas('filter1', 'none') ->assertDontSeeIn('@output1', 'All') ->assertDontSeeIn('@output1', 'Some') ->assertQueryStringMissing('filter2') ->assertSeeIn('@output2', 'All') ->assertSeeIn('@output2', 'Some') ; } public function test_initial_values_loaded_from_querystring_are_not_removed_from_querystring_on_load_if_they_are_different_to_the_default() { Livewire::withQueryParams(['perPage' => 25])->visit([ new class extends Component { #[BaseUrl] public $perPage = '15'; public function render() { return <<<'HTML' <div> <input type="text" dusk="input" wire:model.live="perPage" /> </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertQueryStringHas('perPage', '25') ->assertInputValue('@input', '25') ; } public function test_can_use_except_in_query_string_property() { Livewire::visit([ new class extends Component { protected $queryString = [ 'search' => [ 'except' => '', 'history' => false, ], ]; public $search = ''; public function mount() { $this->search = 'foo'; } public function render() { return <<<'HTML' <div> <input type="text" dusk="input" wire:model.live="search" /> </div> HTML; } }, ]) ->assertQueryStringHas('search', 'foo') ->waitForLivewire()->type('@input', 'bar') ->assertQueryStringHas('search', 'bar') ->waitForLivewire()->type('@input', ' ') ->waitForLivewire()->keys('@input', '{backspace}') ->assertQueryStringMissing('search') ; } public function test_can_use_url_on_form_object_properties() { Livewire::visit([ new class extends Component { public FormObject $form; public function render() { return <<<'HTML' <div> <input type="text" dusk="foo.input" wire:model.live="form.foo" /> <input type="text" dusk="bob.input" wire:model.live="form.bob" /> </div> HTML; } }, ]) ->assertQueryStringMissing('foo') ->assertQueryStringMissing('bob') ->assertQueryStringMissing('aliased') ->waitForLivewire()->type('@foo.input', 'baz') ->assertQueryStringHas('foo', 'baz') ->assertQueryStringMissing('bob') ->assertQueryStringMissing('aliased') ->waitForLivewire()->type('@bob.input', 'law') ->assertQueryStringHas('foo', 'baz') ->assertQueryStringMissing('bob') ->assertQueryStringHas('aliased', 'law') ; } public function test_can_use_url_on_string_backed_enum_object_properties() { Livewire::visit([ new class extends Component { #[BaseUrl] public StringBackedEnumForUrlTesting $foo = StringBackedEnumForUrlTesting::First; public function change() { $this->foo = StringBackedEnumForUrlTesting::Second; } public function render() { return <<<'HTML' <div> <button wire:click="change" dusk="button">Change</button> <h1 dusk="output">{{ $foo }}</h1> </div> HTML; } }, ]) ->assertQueryStringMissing('foo') ->assertSeeIn('@output', 'first') ->waitForLivewire()->click('@button') ->assertQueryStringHas('foo', 'second') ->assertSeeIn('@output', 'second') ->refresh() ->assertQueryStringHas('foo', 'second') ->assertSeeIn('@output', 'second') ; } public function test_can_use_url_on_integer_backed_enum_object_properties() { Livewire::visit([ new class extends Component { #[BaseUrl] public IntegerBackedEnumForUrlTesting $foo = IntegerBackedEnumForUrlTesting::First; public function change() { $this->foo = IntegerBackedEnumForUrlTesting::Second; } public function render() { return <<<'HTML' <div> <button wire:click="change" dusk="button">Change</button> <h1 dusk="output">{{ $foo }}</h1> </div> HTML; } }, ]) ->assertQueryStringMissing('foo') ->assertSeeIn('@output', '1') ->waitForLivewire()->click('@button') ->assertQueryStringHas('foo', '2') ->assertSeeIn('@output', '2') ->refresh() ->assertQueryStringHas('foo', '2') ->assertSeeIn('@output', '2') ; } public function test_can_use_url_on_string_backed_enum_object_properties_with_initial_invalid_value_on_nullable() { Livewire::withQueryParams(['foo' => 'bar']) ->visit([ new class extends Component { #[Url(nullable: true)] public ?StringBackedEnumForUrlTesting $foo; public function change() { $this->foo = StringBackedEnumForUrlTesting::Second; } public function unsetFoo() { $this->foo = null; } public function render() { return <<<'HTML' <div> <button wire:click="change" dusk="button">Change</button> <h1 dusk="output">{{ $foo }}</h1> <button wire:click="unsetFoo" dusk="unsetButton">Unset foo</button> </div> HTML; } }, ]) ->assertQueryStringHas('foo', '') ->assertSee('foo', null) ->waitForLivewire()->click('@button') ->assertQueryStringHas('foo', 'second') ->assertSeeIn('@output', 'second') ->refresh() ->assertQueryStringHas('foo', 'second') ->assertSeeIn('@output', 'second') ; } public function test_can_use_url_on_integer_backed_enum_object_properties_with_initial_invalid_value_on_nullable() { Livewire::withQueryParams(['foo' => 5]) ->visit([ new class extends Component { #[Url(nullable: true)] public ?IntegerBackedEnumForUrlTesting $foo; public function change() { $this->foo = IntegerBackedEnumForUrlTesting::Second; } public function unsetFoo() { $this->foo = null; } public function render() { return <<<'HTML' <div> <button wire:click="change" dusk="button">Change</button> <h1 dusk="output">{{ $foo }}</h1> <button wire:click="unsetFoo" dusk="unsetButton">Unset foo</button> </div> HTML; } }, ]) ->assertQueryStringHas('foo', '') ->assertSee('foo', null) ->waitForLivewire()->click('@button') ->assertQueryStringHas('foo', '2') ->assertSeeIn('@output', '2') ->refresh() ->assertQueryStringHas('foo', '2') ->assertSeeIn('@output', '2') ; } public function test_it_does_not_break_string_typed_properties() { Livewire::withQueryParams(['foo' => 'bar']) ->visit([ new class extends Component { #[BaseUrl] public string $foo = ''; public function render() { return <<<'HTML' <div> <h1 dusk="output">{{ $foo }}</h1> </div> HTML; } }, ]) ->assertSeeIn('@output', 'bar') ; } public function test_can_use_url_on_lazy_component() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <livewire:child lazy /> </div> HTML; } }, 'child' => new class extends Component { #[BaseUrl] public $foo = 'bar'; public function render() { return <<<'HTML' <div> <div>lazy loaded</div> <input type="text" dusk="foo.input" wire:model.live="foo" /> </div> HTML; } }, ]) ->waitForText('lazy loaded') ->assertQueryStringMissing('foo') ->waitForLivewire()->type('@foo.input', 'baz') ->assertQueryStringHas('foo', 'baz') ; } public function test_can_unset_the_array_key_when_using_dot_notation_without_except() { Livewire::visit([ new class extends \Livewire\Component { public array $tableFilters = []; protected function queryString() { return [ 'tableFilters.filter_1.value' => [ 'as' => 'filter', ], ]; } public function clear() { unset($this->tableFilters['filter_1']['value']); } public function render() { return <<<'HTML' <div> <input wire:model.live="tableFilters.filter_1.value" type="text" dusk="filter" /> <span dusk="output">@json($tableFilters)</span> <button dusk="clear" wire:click="clear">Clear</button> </div> HTML; } }, ]) ->assertInputValue('@filter', '') ->waitForLivewire()->type('@filter', 'foo') ->assertSeeIn('@output', '{"filter_1":{"value":"foo"}}') ->waitForLivewire()->click('@clear') ->assertInputValue('@filter', '') ->assertQueryStringMissing('filter') ; } public function test_can_unset_the_array_key_when_with_except() { Livewire::visit([ new class extends \Livewire\Component { public array $tableFilters = []; protected function queryString() { return [ 'tableFilters' => [ 'filter_1' => [ 'value' => [ 'as' => 'filter', 'except' => '', ], ] ], ]; } public function clear() { unset($this->tableFilters['filter_1']['value']); } public function render() { return <<<'HTML' <div> <input wire:model.live="tableFilters.filter_1.value" type="text" dusk="filter" /> <span dusk="output">@json($tableFilters)</span> <button dusk="clear" wire:click="clear">Clear</button> </div> HTML; } }, ]) ->assertInputValue('@filter', '') ->waitForLivewire()->type('@filter', 'foo') ->assertSeeIn('@output', '{"filter_1":{"value":"foo"}}') ->waitForLivewire()->click('@clear') ->assertInputValue('@filter', '') ->assertQueryStringMissing('filter') ; } public function test_can_unset_the_array_key_when_without_except() { Livewire::visit([ new class extends \Livewire\Component { public array $tableFilters = []; protected function queryString() { return [ 'tableFilters' => [ 'filter_1' => [ 'value' => [ 'as' => 'filter', ], ] ], ]; } public function clear() { unset($this->tableFilters['filter_1']['value']); } public function render() { return <<<'HTML' <div> <input wire:model.live="tableFilters.filter_1.value" type="text" dusk="filter" /> <span dusk="output">@json($tableFilters)</span> <button dusk="clear" wire:click="clear">Clear</button> </div> HTML; } }, ]) ->assertInputValue('@filter', '') ->waitForLivewire()->type('@filter', 'foo') ->assertSeeIn('@output', '{"filter_1":{"value":"foo"}}') ->waitForLivewire()->click('@clear') ->assertInputValue('@filter', '') ->assertQueryStringMissing('filter') ; } public function test_can_unset_the_array_key_when_using_dot_notation_with_except() { Livewire::visit([ new class extends \Livewire\Component { public array $tableFilters = []; protected function queryString() { return [ 'tableFilters.filter_1.value' => [ 'as' => 'filter', 'except' => '' ], ]; } public function clear() { unset($this->tableFilters['filter_1']['value']); } public function render() { return <<<'HTML' <div> <input wire:model.live="tableFilters.filter_1.value" type="text" dusk="filter" /> <span dusk="output">@json($tableFilters)</span> <button dusk="clear" wire:click="clear">Clear</button> </div> HTML; } }, ]) ->assertInputValue('@filter', '') ->waitForLivewire()->type('@filter', 'foo') ->assertSeeIn('@output', '{"filter_1":{"value":"foo"}}') ->waitForLivewire()->click('@clear') ->assertInputValue('@filter', '') ->assertQueryStringMissing('filter') ; } public function test_can_handle_empty_querystring_value_as_empty_string() { Livewire::visit([ new class extends Component { #[Url] public $foo; public function setFoo() { $this->foo = 'bar'; } public function unsetFoo() { $this->foo = ''; } public function render() { return <<<'HTML' <div> <button wire:click="setFoo" dusk="setButton">Set foo</button> <button wire:click="unsetFoo" dusk="unsetButton">Unset foo</button> <span dusk="output">@js($foo)</span> </div> HTML; } }, ]) ->assertQueryStringMissing('foo') ->waitForLivewire()->click('@setButton') ->assertSeeIn('@output', '\'bar\'') ->assertQueryStringHas('foo', 'bar') ->refresh() ->assertQueryStringHas('foo', 'bar') ->waitForLivewire()->click('@unsetButton') ->assertSeeIn('@output', '\'\'') ->assertQueryStringHas('foo', '') ->refresh() ->assertSeeIn('@output', '\'\'') ->assertQueryStringHas('foo', ''); } public function test_can_handle_empty_querystring_value_as_null() { Livewire::visit([ new class extends Component { #[Url(nullable: true)] public $foo; public function setFoo() { $this->foo = 'bar'; } public function unsetFoo() { $this->foo = null; } public function render() { return <<<'HTML' <div> <button wire:click="setFoo" dusk="setButton">Set foo</button> <button wire:click="unsetFoo" dusk="unsetButton">Unset foo</button> <span dusk="output">@js($foo)</span> </div> HTML; } }, ]) ->assertQueryStringMissing('foo') ->waitForLivewire()->click('@setButton') ->assertSeeIn('@output', '\'bar\'') ->assertQueryStringHas('foo', 'bar') ->refresh() ->assertQueryStringHas('foo', 'bar') ->waitForLivewire()->click('@unsetButton') ->assertSeeIn('@output', 'null') ->assertQueryStringHas('foo', '') ->refresh() ->assertSeeIn('@output', 'null') ->assertQueryStringHas('foo', ''); } public function test_can_handle_empty_querystring_value_as_null_or_empty_string_based_on_typehinting_of_property() { Livewire::visit([ new class extends Component { #[Url] public ?string $nullableFoo; #[Url] public string $notNullableFoo; #[Url] public $notTypehintingFoo; public function setFoo() { $this->nullableFoo = 'bar'; $this->notNullableFoo = 'bar'; $this->notTypehintingFoo = 'bar'; } public function unsetFoo() { $this->nullableFoo = null; $this->notNullableFoo = ''; $this->notTypehintingFoo = null; } public function render() { return <<<'HTML' <div> <button wire:click="setFoo" dusk="setButton">Set foo</button> <button wire:click="unsetFoo" dusk="unsetButton">Unset foo</button> <span dusk="output-nullableFoo">@js($nullableFoo)</span> <span dusk="output-notNullableFoo">@js($notNullableFoo)</span> <span dusk="output-notTypehintingFoo">@js($notTypehintingFoo)</span> </div> HTML; } }, ]) ->assertQueryStringMissing('nullableFoo') ->assertQueryStringMissing('notNullableFoo') ->assertQueryStringMissing('notTypehintingFoo') ->waitForLivewire()->click('@setButton') ->assertSeeIn('@output-nullableFoo', '\'bar\'') ->assertSeeIn('@output-notNullableFoo', '\'bar\'') ->assertSeeIn('@output-notTypehintingFoo', '\'bar\'') ->assertQueryStringHas('nullableFoo', 'bar') ->assertQueryStringHas('notNullableFoo', 'bar') ->assertQueryStringHas('notTypehintingFoo', 'bar') ->refresh() ->assertQueryStringHas('nullableFoo', 'bar') ->assertQueryStringHas('notNullableFoo', 'bar') ->assertQueryStringHas('notTypehintingFoo', 'bar') ->waitForLivewire()->click('@unsetButton') ->assertSeeIn('@output-nullableFoo', 'null')
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportQueryString/UnitTest.php
src/Features/SupportQueryString/UnitTest.php
<?php namespace Livewire\Features\SupportQueryString; use Livewire\Livewire; use Tests\TestComponent; trait WithSorting { protected function queryStringWithSorting() { return [ 'queryFromTrait', ]; } } class UnitTest extends \Tests\TestCase { function test_can_track_properties_in_the_url() { $component = Livewire::test(new class extends TestComponent { #[BaseUrl] public $count = 1; function increment() { $this->count++; } }); $this->assertTrue(isset($component->effects['url'])); } function test_sub_name_is_null_in_attributes_from_query_string_component_method() { $component = Livewire::test(new class extends TestComponent { protected function queryString() { return [ 'queryFromMethod', ]; } }); $attributes = $component->instance()->getAttributes(); $queryFromMethod = $attributes->first(fn (BaseUrl $attribute) => $attribute->getName() === 'queryFromMethod'); $this->assertEquals(null, $queryFromMethod->getSubName()); } function test_sub_name_is_null_in_attributes_from_query_string_trait_method() { $component = Livewire::test(new class extends TestComponent { use WithSorting; }); $attributes = $component->instance()->getAttributes(); $queryFromTrait = $attributes->first(fn (BaseUrl $attribute) => $attribute->getName() === 'queryFromTrait'); $this->assertEquals(null, $queryFromTrait->getSubName()); } function test_sub_name_is_same_as_name_in_attributes_from_base_url_property_attribute() { $component = Livewire::test(new class extends TestComponent { #[BaseUrl] public $queryFromAttribute; }); $attributes = $component->instance()->getAttributes(); $queryFromAttribute = $attributes->first(fn (BaseUrl $attribute) => $attribute->getName() === 'queryFromAttribute'); $this->assertEquals('queryFromAttribute', $queryFromAttribute->getSubName()); } function test_noexist_query_parameter_is_allowed_value() { $component = Livewire::withQueryParams(['exists' => 'noexist']) ->test(new class extends TestComponent { #[BaseUrl] public $exists; #[BaseUrl] public $noexists; }); $attributes = $component->instance()->getAttributes(); $existsAttribute = $attributes->first(fn (BaseUrl $attribute) => $attribute->getName() === 'exists'); $noexistsAttribute = $attributes->first(fn (BaseUrl $attribute) => $attribute->getName() === 'noexists'); $this->assertEquals('noexist', $existsAttribute->getFromUrlQueryString($existsAttribute->urlName(), 'does not exist')); $this->assertEquals('does not exist', $noexistsAttribute->getFromUrlQueryString($noexistsAttribute->urlName(), 'does not exist')); $this->assertEquals('noexist', $component->instance()->exists); $this->assertEquals('', $component->instance()->noexists); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAttributes/HandlesAttributes.php
src/Features/SupportAttributes/HandlesAttributes.php
<?php namespace Livewire\Features\SupportAttributes; trait HandlesAttributes { protected AttributeCollection $attributes; function getAttributes() { return $this->attributes ??= AttributeCollection::fromComponent($this); } function setPropertyAttribute($property, $attribute) { $attribute->__boot($this, AttributeLevel::PROPERTY, $property); $this->mergeOutsideAttributes(new AttributeCollection([$attribute])); } function mergeOutsideAttributes(AttributeCollection $attributes) { $this->attributes = $this->getAttributes()->concat($attributes); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAttributes/SupportAttributes.php
src/Features/SupportAttributes/SupportAttributes.php
<?php namespace Livewire\Features\SupportAttributes; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; use Livewire\ComponentHook; class SupportAttributes extends ComponentHook { function boot(...$params) { $this->component ->getAttributes() ->whereInstanceOf(LivewireAttribute::class) ->each(function ($attribute) use ($params) { if (method_exists($attribute, 'boot')) { $attribute->boot(...$params); } }); } function mount(...$params) { $this->component ->getAttributes() ->whereInstanceOf(LivewireAttribute::class) ->each(function ($attribute) use ($params) { if (method_exists($attribute, 'mount')) { $attribute->mount(...$params); } }); } function hydrate(...$params) { $this->component ->getAttributes() ->whereInstanceOf(LivewireAttribute::class) ->each(function ($attribute) use ($params) { if (method_exists($attribute, 'hydrate')) { $attribute->hydrate(...$params); } }); } function update($propertyName, $fullPath, $newValue) { $callbacks = $this->component ->getAttributes() ->whereInstanceOf(LivewireAttribute::class) ->filter(fn ($attr) => $attr->getLevel() === AttributeLevel::PROPERTY) // Call "update" on the root property attribute even if it's a deep update... ->filter(fn ($attr) => str($fullPath)->startsWith($attr->getName() . '.') || $fullPath === $attr->getName()) ->map(function ($attribute) use ($fullPath, $newValue) { if (method_exists($attribute, 'update')) { return $attribute->update($fullPath, $newValue); } }); return function (...$params) use ($callbacks) { foreach ($callbacks as $callback) { if (is_callable($callback)) $callback(...$params); } }; } function call($method, $params, $returnEarly) { $callbacks = $this->component ->getAttributes() ->whereInstanceOf(LivewireAttribute::class) ->filter(fn ($attr) => $attr->getLevel() === AttributeLevel::METHOD) ->filter(fn ($attr) => $attr->getName() === $method) ->map(function ($attribute) use ($params, $returnEarly) { if (method_exists($attribute, 'call')) { return $attribute->call($params, $returnEarly); } }); return function (...$params) use ($callbacks) { foreach ($callbacks as $callback) { if (is_callable($callback)) $callback(...$params); } }; } function render(...$params) { $callbacks = $this->component ->getAttributes() ->whereInstanceOf(LivewireAttribute::class) ->map(function ($attribute) use ($params) { if (method_exists($attribute, 'render')) { return $attribute->render(...$params); } }); return function (...$params) use ($callbacks) { foreach ($callbacks as $callback) { if (is_callable($callback)) { $callback(...$params); } } }; } function dehydrate(...$params) { $this->component ->getAttributes() ->whereInstanceOf(LivewireAttribute::class) ->each(function ($attribute) use ($params) { if (method_exists($attribute, 'dehydrate')) { $attribute->dehydrate(...$params); } }); } function destroy(...$params) { $this->component ->getAttributes() ->whereInstanceOf(LivewireAttribute::class) ->each(function ($attribute) use ($params) { if (method_exists($attribute, 'destroy')) { $attribute->destroy(...$params); } }); } function exception(...$params) { $this->component ->getAttributes() ->whereInstanceOf(LivewireAttribute::class) ->each(function ($attribute) use ($params) { if (method_exists($attribute, 'exception')) { $attribute->exception(...$params); } }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAttributes/Attribute.php
src/Features/SupportAttributes/Attribute.php
<?php namespace Livewire\Features\SupportAttributes; use Livewire\Component; abstract class Attribute { protected Component $component; protected $subTarget; protected $subName; protected AttributeLevel $level; protected $levelName; function __boot($component, AttributeLevel $level, $name = null, $subName = null, $subTarget = null) { $this->component = $component; $this->subName = $subName; $this->subTarget = $subTarget; $this->level = $level; $this->levelName = $name; } function getComponent() { return $this->component; } function getSubTarget() { return $this->subTarget; } function getSubName() { return $this->subName; } function getLevel() { return $this->level; } function getName() { return $this->levelName; } function getValue() { if ($this->level !== AttributeLevel::PROPERTY) { throw new \Exception('Can\'t get the value of a non-property attribute.'); } return data_get($this->component->all(), $this->levelName); } function setValue($value, ?bool $nullable = false) { if ($this->level !== AttributeLevel::PROPERTY) { throw new \Exception('Can\'t set the value of a non-property attribute.'); } if ($enum = $this->tryingToSetStringOrIntegerToEnum($value)) { if($nullable) { $value = $enum::tryFrom($value); } else { $value = $enum::from($value); } } data_set($this->component, $this->levelName, $value); } protected function tryingToSetStringOrIntegerToEnum($subject) { if (! is_string($subject) && ! is_int($subject)) return; $target = $this->subTarget ?? $this->component; $name = $this->subName ?? $this->levelName; $property = str($name)->before('.')->toString(); $reflection = new \ReflectionProperty($target, $property); $type = $reflection->getType(); // If the type is available, display its name if ($type instanceof \ReflectionNamedType) { $name = $type->getName(); // If the type is a BackedEnum then return it's name if (is_subclass_of($name, \BackedEnum::class)) { return $name; } } return false; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAttributes/AttributeLevel.php
src/Features/SupportAttributes/AttributeLevel.php
<?php namespace Livewire\Features\SupportAttributes; enum AttributeLevel { case ROOT; case PROPERTY; case METHOD; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAttributes/AttributeCollection.php
src/Features/SupportAttributes/AttributeCollection.php
<?php namespace Livewire\Features\SupportAttributes; use Illuminate\Support\Collection; use ReflectionAttribute; use ReflectionObject; class AttributeCollection extends Collection { static function fromComponent($component, $subTarget = null, $propertyNamePrefix = '') { $instance = new static; $reflected = new ReflectionObject($subTarget ?? $component); foreach (static::getClassAttributesRecursively($reflected) as $attribute) { $instance->push(tap($attribute->newInstance(), function ($attribute) use ($component, $subTarget) { $attribute->__boot($component, AttributeLevel::ROOT, null, null, $subTarget); })); } foreach ($reflected->getMethods() as $method) { foreach ($method->getAttributes(Attribute::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) { $instance->push(tap($attribute->newInstance(), function ($attribute) use ($component, $method, $propertyNamePrefix, $subTarget) { $attribute->__boot($component, AttributeLevel::METHOD, $propertyNamePrefix . $method->getName(), $method->getName(), $subTarget); })); } } foreach ($reflected->getProperties() as $property) { foreach ($property->getAttributes(Attribute::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) { $instance->push(tap($attribute->newInstance(), function ($attribute) use ($component, $property, $propertyNamePrefix, $subTarget) { $attribute->__boot($component, AttributeLevel::PROPERTY, $propertyNamePrefix . $property->getName(), $property->getName(), $subTarget); })); } } return $instance; } protected static function getClassAttributesRecursively($reflected) { $attributes = []; while ($reflected) { foreach ($reflected->getAttributes(Attribute::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) { $attributes[] = $attribute; } $reflected = $reflected->getParentClass(); } return $attributes; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAttributes/UnitTest.php
src/Features/SupportAttributes/UnitTest.php
<?php namespace Livewire\Features\SupportAttributes; use Livewire\Livewire; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_property_attribute_has_access_to_lifecycle_hooks() { Livewire::test(new class extends TestComponent { #[LifecycleHookAttribute] public $count = 0; }) ->assertSetStrict('count', 3); } public function test_can_set_property_hook_manually() { Livewire::test(new class extends TestComponent { function __construct() { $this->setPropertyAttribute('count', new LifecycleHookAttribute); } public $count = 0; }) ->assertSetStrict('count', 3); } public function test_can_set_nested_property_hook_manually() { Livewire::test(new class extends TestComponent { function __construct() { $this->setPropertyAttribute('items.count', new LifecycleHookAttribute); } public $items = ['count' => 0]; }) ->assertSetStrict('items.count', 3); } public function test_non_livewire_attribute_are_ignored() { Livewire::test(new class extends TestComponent { #[NonLivewire] public $count = 0; }) ->assertSetStrict('count', 0); } } #[\Attribute] class LifecycleHookAttribute extends Attribute { function mount() { $this->setValue($this->getValue() + 1); } function hydrate() { $this->setValue($this->getValue() + 1); } function render() { $this->setValue($this->getValue() + 1); } function dehydrate() { $this->setValue($this->getValue() + 1); } } #[\Attribute] class NonLivewire {}
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportDisablingBackButtonCache/DisableBackButtonCacheMiddleware.php
src/Features/SupportDisablingBackButtonCache/DisableBackButtonCacheMiddleware.php
<?php namespace Livewire\Features\SupportDisablingBackButtonCache; use Closure; use Symfony\Component\HttpFoundation\Response; class DisableBackButtonCacheMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); if ($response instanceof Response && SupportDisablingBackButtonCache::$disableBackButtonCache){ $response->headers->add([ 'Pragma' => 'no-cache', 'Expires' => 'Fri, 01 Jan 1990 00:00:00 GMT', 'Cache-Control' => 'no-cache, must-revalidate, no-store, max-age=0, private', ]); // We do flush this in the `SupportDisablingBackButtonCache` hook, but we // need to do it here as well to ensure that unit tests still work... SupportDisablingBackButtonCache::$disableBackButtonCache = false; } return $response; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportDisablingBackButtonCache/HandlesDisablingBackButtonCache.php
src/Features/SupportDisablingBackButtonCache/HandlesDisablingBackButtonCache.php
<?php namespace Livewire\Features\SupportDisablingBackButtonCache; trait HandlesDisablingBackButtonCache { function disableBackButtonCache() { SupportDisablingBackButtonCache::$disableBackButtonCache = true; } function enableBackButtonCache() { SupportDisablingBackButtonCache::$disableBackButtonCache = false; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportDisablingBackButtonCache/UnitTest.php
src/Features/SupportDisablingBackButtonCache/UnitTest.php
<?php namespace Livewire\Features\SupportDisablingBackButtonCache; use Illuminate\Support\Facades\Route; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_ensure_disable_browser_cache_middleware_is_not_applied_to_a_route_that_does_not_contain_a_component() { Route::get('test-route-without-livewire-component', function () { return 'ok'; }); $response = $this->get('test-route-without-livewire-component')->assertSuccessful(); // There are a couple of different headers applied in the middleware, // so just testing for one that isn't normally in a Laravel request $this->assertFalse($response->baseResponse->headers->hasCacheControlDirective('must-revalidate')); } public function test_ensure_browser_cache_middleware_is_applied_to_a_route_that_contains_a_component_with_disable_set_to_true() { Route::get('test-route-containing-livewire-component', DisableBrowserCache::class); $response = $this->get('test-route-containing-livewire-component')->assertSuccessful(); // There are a couple of different headers applied in the middleware, // so just testing for one that isn't normally in a Laravel request $this->assertTrue($response->baseResponse->headers->hasCacheControlDirective('must-revalidate')); } public function test_ensure_disable_browser_cache_middleware_is_disabled_after_a_livewire_request_so_no_following_non_livewire_requests_have_it_enabled() { Route::get('test-route-containing-livewire-component', DisableBrowserCache::class); Route::get('test-route-without-livewire-component', function () { return 'ok'; }); $response = $this->get('test-route-containing-livewire-component')->assertSuccessful(); // There are a couple of different headers applied in the middleware, // so just testing for one that isn't normally in a Laravel request $this->assertTrue($response->baseResponse->headers->hasCacheControlDirective('must-revalidate')); $response = $this->get('test-route-without-livewire-component')->assertSuccessful(); // There are a couple of different headers applied in the middleware, // so just testing for one that isn't normally in a Laravel request $this->assertFalse($response->baseResponse->headers->hasCacheControlDirective('must-revalidate')); } } class DisableBrowserCache extends TestComponent { public function mount() { $this->disableBackButtonCache(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportDisablingBackButtonCache/SupportDisablingBackButtonCache.php
src/Features/SupportDisablingBackButtonCache/SupportDisablingBackButtonCache.php
<?php namespace Livewire\Features\SupportDisablingBackButtonCache; use Livewire\ComponentHook; use function Livewire\on; class SupportDisablingBackButtonCache extends ComponentHook { public static $disableBackButtonCache = false; public static function provide() { on('flush-state', function () { static::$disableBackButtonCache = false; }); $kernel = app()->make(\Illuminate\Contracts\Http\Kernel::class); if ($kernel->hasMiddleware(DisableBackButtonCacheMiddleware::class)) { return; } $kernel->pushMiddleware(DisableBackButtonCacheMiddleware::class); } public function boot() { static::$disableBackButtonCache = true; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/SupportPagination.php
src/Features/SupportPagination/SupportPagination.php
<?php namespace Livewire\Features\SupportPagination; use function Livewire\invade; use Livewire\WithPagination; use Livewire\Features\SupportQueryString\SupportQueryString; use Livewire\ComponentHookRegistry; use Livewire\ComponentHook; use Livewire\Livewire; use Illuminate\Pagination\Paginator; use Illuminate\Pagination\CursorPaginator; use Illuminate\Pagination\Cursor; class SupportPagination extends ComponentHook { static function provide() { app('livewire')->provide(function () { $this->loadViewsFrom(__DIR__.'/views', 'livewire'); $paths = [__DIR__.'/views' => resource_path('views/vendor/livewire')]; $this->publishes($paths, 'livewire'); $this->publishes($paths, 'livewire:pagination'); }); } protected $restoreOverriddenPaginationViews; function skip() { return ! in_array(WithPagination::class, class_uses_recursive($this->component)); } function boot() { $this->setPathResolvers(); $this->setPageResolvers(); $this->overrideDefaultPaginationViews(); } function destroy() { ($this->restoreOverriddenPaginationViews)(); } function overrideDefaultPaginationViews() { $oldDefaultView = Paginator::$defaultView; $oldDefaultSimpleView = Paginator::$defaultSimpleView; $this->restoreOverriddenPaginationViews = function () use ($oldDefaultView, $oldDefaultSimpleView) { Paginator::defaultView($oldDefaultView); Paginator::defaultSimpleView($oldDefaultSimpleView); }; Paginator::defaultView($this->paginationView()); Paginator::defaultSimpleView($this->paginationSimpleView()); } protected function setPathResolvers() { // Setting the path resolver here on the default paginator also works for the cursor paginator... Paginator::currentPathResolver(function () { return Livewire::originalPath(); }); } protected function setPageResolvers() { CursorPaginator::currentCursorResolver(function ($pageName) { $this->ensurePaginatorIsInitialized($pageName, defaultPage: ''); return Cursor::fromEncoded($this->component->paginators[$pageName]); }); Paginator::currentPageResolver(function ($pageName) { $this->ensurePaginatorIsInitialized($pageName); return (int) $this->component->paginators[$pageName]; }); } protected function ensurePaginatorIsInitialized($pageName, $defaultPage = 1) { if (isset($this->component->paginators[$pageName])) return; $queryStringDetails = $this->getQueryStringDetails($pageName); $this->component->paginators[$pageName] = $this->resolvePage($queryStringDetails['as'], $defaultPage); $shouldSkipUrlTracking = in_array( WithoutUrlPagination::class, class_uses_recursive($this->component) ); if ($shouldSkipUrlTracking) return; $this->addUrlHook($pageName, $queryStringDetails); } protected function getQueryStringDetails($pageName) { $pageNameQueryString = data_get($this->getQueryString(), 'paginators.' . $pageName); $pageNameQueryString['as'] ??= $pageName; $pageNameQueryString['history'] ??= true; $pageNameQueryString['keep'] ??= false; return $pageNameQueryString; } protected function resolvePage($alias, $default) { return request()->query($alias, $default); } protected function addUrlHook($pageName, $queryStringDetails) { $key = 'paginators.' . $pageName; $alias = $queryStringDetails['as']; $history = $queryStringDetails['history']; $keep = $queryStringDetails['keep']; $attribute = new PaginationUrl(as: $alias, history: $history, keep: $keep); $this->component->setPropertyAttribute($key, $attribute); // We need to manually call this in case it's a Lazy component, // in which case the `mount()` lifecycle hook isn't called. // This means it can be called twice, but that's fine... $attribute->setPropertyFromQueryString(); } protected function paginationView() { if (method_exists($this->component, 'paginationView')) { return $this->component->paginationView(); } return 'livewire::' . (property_exists($this->component, 'paginationTheme') ? invade($this->component)->paginationTheme : config('livewire.pagination_theme', 'tailwind')); } protected function paginationSimpleView() { if (method_exists($this->component, 'paginationSimpleView')) { return $this->component->paginationSimpleView(); } return 'livewire::simple-' . (property_exists($this->component, 'paginationTheme') ? invade($this->component)->paginationTheme : config('livewire.pagination_theme', 'tailwind')); } protected function getQueryString() { $supportQueryStringHook = ComponentHookRegistry::getHook($this->component, SupportQueryString::class); return $supportQueryStringHook->getQueryString(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/PaginationUrl.php
src/Features/SupportPagination/PaginationUrl.php
<?php namespace Livewire\Features\SupportPagination; use Livewire\Features\SupportQueryString\BaseUrl; #[\Attribute] class PaginationUrl extends BaseUrl { // In the case of Lazy components, the paginator won't resolve and initialize // until the subsequent request. Therefore, we need to override "dehydrate" // so its not blocked on a subsequent request by the "mounting" condition public function dehydrate($context) { $this->pushQueryStringEffect($context); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/BrowserTest.php
src/Features/SupportPagination/BrowserTest.php
<?php namespace Livewire\Features\SupportPagination; use Tests\BrowserTestCase; use Sushi\Sushi; use Livewire\WithoutUrlPagination; use Livewire\WithPagination; use Livewire\Livewire; use Livewire\Component; use Livewire\Attributes\Computed; use Illuminate\Support\Facades\Blade; use Illuminate\Database\Eloquent\Model; class BrowserTest extends BrowserTestCase { public function test_tailwind() { Livewire::visit(new class extends Component { use WithPagination; public function render() { return Blade::render( <<< 'HTML' <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach {{ $posts->links() }} </div> HTML, [ 'posts' => Post::paginate(3), ] ); } }) // Test that going to page 2, then back to page 1 removes "page" from the query string. ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->waitForLivewire()->click('@nextPage.before') ->assertDontSee('Post #3') ->assertSee('Post #4') ->assertSee('Post #5') ->assertSee('Post #6') ->assertQueryStringHas('page', '2') ->waitForLivewire()->click('@previousPage.before') ->assertDontSee('Post #6') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertQueryStringMissing('page') // Test that using the next page button twice (the one at the end of the page numbers) works. ->refresh() ->assertSee('Post #1') ->assertDontSee('Post #4') ->waitForLivewire()->click('@nextPage.after') ->assertDontSee('Post #1') ->assertSee('Post #4') ->assertQueryStringHas('page', '2') ->waitForLivewire()->click('@nextPage.after') ->assertDontSee('Post #4') ->assertSee('Post #7') ->assertQueryStringHas('page', '3') // Test that hitting the back button takes you back to the previous page after a refresh. ->refresh() ->waitForLivewire()->back() ->assertQueryStringHas('page', '2') ->assertDontSee('Post #7') ->assertSee('Post #4') ; } public function test_bootstrap() { Livewire::visit(new class extends Component { use WithPagination; protected $paginationTheme = 'bootstrap'; public function render() { return Blade::render( <<<'HTML' <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach {{ $posts->links() }} </div> HTML, [ 'posts' => Post::paginate(3), ] ); } }) // Test that going to page 2, then back to page 1 removes "page" from the query string. ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->waitForLivewire()->click('@nextPage') ->assertDontSee('Post #1') ->assertSee('Post #4') ->assertQueryStringHas('page', '2') ->waitForLivewire()->click('@nextPage') ->assertDontSee('Post #3') ->assertSee('Post #7') ->assertSee('Post #8') ->assertSee('Post #9') ->assertQueryStringHas('page', '3') ->waitForLivewire()->click('@previousPage') ->waitForLivewire()->click('@previousPage') ->assertDontSee('Post #6') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertQueryStringMissing('page') ; } public function test_cursor_tailwind() { Livewire::visit(new class extends Component { use WithPagination; public function render() { return Blade::render( <<< 'HTML' <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach {{ $posts->links() }} </div> HTML, [ 'posts' => Post::cursorPaginate(3, '*', 'page'), ] ); } }) // Test it can go to second page and return to first one ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->waitForLivewire()->click('@nextPage') ->assertDontSee('Post #3') ->assertSee('Post #4') ->assertSee('Post #5') ->assertSee('Post #6') ->waitForLivewire()->click('@previousPage') ->assertDontSee('Post #6') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') // Test that hitting the back button takes you back to the previous page after a refresh. ->refresh() ->assertSee('Post #1') ->assertDontSee('Post #4') ->waitForLivewire()->click('@nextPage') ->assertDontSee('Post #1') ->assertSee('Post #4') ->waitForLivewire()->click('@nextPage') ->assertDontSee('Post #4') ->assertSee('Post #7') ->refresh() ->waitForLivewire()->back() ->assertDontSee('Post #7') ->assertSee('Post #4') ; } public function test_cursor_bootstrap() { Livewire::visit(new class extends Component { use WithPagination; protected $paginationTheme = 'bootstrap'; public function render() { return Blade::render( <<< 'HTML' <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach {{ $posts->links() }} </div> HTML, [ 'posts' => Post::cursorPaginate(3, '*', 'page'), ] ); } }) // Test it can go to second page and return to first one ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->waitForLivewire()->click('@nextPage') ->assertDontSee('Post #3') ->assertSee('Post #4') ->assertSee('Post #5') ->assertSee('Post #6') ->waitForLivewire()->click('@previousPage') ->assertDontSee('Post #6') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') // Test that hitting the back button takes you back to the previous page after a refresh. ->refresh() ->assertSee('Post #1') ->assertDontSee('Post #4') ->waitForLivewire()->click('@nextPage') ->assertDontSee('Post #1') ->assertSee('Post #4') ->waitForLivewire()->click('@nextPage') ->assertDontSee('Post #4') ->assertSee('Post #7') ->refresh() ->waitForLivewire()->back() ->assertDontSee('Post #7') ->assertSee('Post #4') ; } public function test_it_can_have_two_sets_of_links_for_the_one_paginator_on_a_page_tailwind() { Livewire::visit(new class extends Component { use WithPagination; public function render() { return Blade::render( <<< 'HTML' <div> <div> <div dusk="first-links">{{ $posts->links() }}</div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach <div dusk="second-links">{{ $posts->links() }}</div> </div> </div> HTML, [ 'posts' => Post::paginate(3), ] ); } }) // Ensure everything is good to start with ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') // Assert page 6 can be seen in both sets of links ->assertPresent('[dusk="first-links"] [wire\\:click="gotoPage(6, \'page\')"]') ->assertPresent('[dusk="second-links"] [wire\\:click="gotoPage(6, \'page\')"]') // Click either of the page 10 links, it doesn't matter which ->waitForLivewire()->click('[wire\\:click="gotoPage(10, \'page\')"]') /* * Typically it is the first set of links that break due to morphdom * So we will test the second set of links first, to make sure everything is ok * Then we will check the first set of links */ ->assertNotPresent('[dusk="second-links"] [wire\\:click="gotoPage(6, \'page\')"]') ->assertNotPresent('[dusk="first-links"] [wire\\:click="gotoPage(6, \'page\')"]') ; } public function test_it_can_have_two_sets_of_links_for_the_one_paginator_on_a_page_bootstrap() { Livewire::visit(new class extends Component { use WithPagination; protected $paginationTheme = 'bootstrap'; public function render() { return Blade::render( <<< 'HTML' <div> <div> <div dusk="first-links">{{ $posts->links() }}</div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach <div dusk="second-links">{{ $posts->links() }}</div> </div> </div> HTML, [ 'posts' => Post::paginate(3), ] ); } }) // Ensure everything is good to start with ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') // Assert page 6 can be seen in both sets of links ->assertPresent('[dusk="first-links"] [wire\\:click="gotoPage(6, \'page\')"]') ->assertPresent('[dusk="second-links"] [wire\\:click="gotoPage(6, \'page\')"]') // Click either of the page 10 links, it doesn't matter which ->waitForLivewire()->click('[wire\\:click="gotoPage(10, \'page\')"]') /* * Typically it is the first set of links that break due to morphdom * So we will test the second set of links first, to make sure everything is ok * Then we will check the first set of links */ ->assertNotPresent('[dusk="second-links"] [wire\\:click="gotoPage(6, \'page\')"]') ->assertNotPresent('[dusk="first-links"] [wire\\:click="gotoPage(6, \'page\')"]') ; } public function test_it_calls_pagination_hook_method_when_pagination_changes() { Livewire::visit(new class extends Component { use WithPagination; public $hookOutput = null; public function updatedPage($page) { $this->hookOutput = 'page-is-set-to-' . $page; } public function render() { return Blade::render( <<< 'HTML' <div> <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach {{ $posts->links(null, ['paginatorId' => 2]) }} </div> <span dusk="pagination-hook">{{ $hookOutput }}</span> </div> HTML, [ 'posts' => Post::paginate(3), 'hookOutput' => $this->hookOutput, ] ); } }) // Test that going to page 2, then back to page 1 removes "page" from the query string. ->assertSeeNothingIn('@pagination-hook') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->waitForLivewire()->click('@nextPage.before') ->assertSeeIn('@pagination-hook', 'page-is-set-to-2') ->assertDontSee('Post #3') ->assertSee('Post #4') ->assertSee('Post #5') ->assertSee('Post #6') ->assertQueryStringHas('page', '2') ->waitForLivewire()->click('@previousPage.before') ->assertSeeIn('@pagination-hook', 'page-is-set-to-1') ->assertDontSee('Post #6') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertQueryStringMissing('page') ; } public function test_it_can_have_two_pagination_instances_on_a_page_tailwind() { Livewire::visit(new class extends Component { use WithPagination; public $pageHookOutput = null; public $itemPageHookOutput = null; public function updatedPage($page) { $this->pageHookOutput = 'page-is-set-to-' . $page; } public function updatedItemPage($page) { $this->itemPageHookOutput = 'item-page-is-set-to-' . $page; } public function render() { return Blade::render( <<< 'HTML' <div> <div> <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach </div> {{ $posts->links() }} </div> <span dusk="page-pagination-hook">{{ $pageHookOutput }}</span> <div> <div> @foreach ($items as $item) <h1 wire:key="item-{{ $item->id }}">{{ $item->title }}</h1> @endforeach </div> {{ $items->links() }} </div> <span dusk="item-page-pagination-hook">{{ $itemPageHookOutput }}</span> </div> HTML, [ 'posts' => Post::paginate(3), 'items' => Item::paginate(3, ['*'], 'itemPage'), 'pageHookOutput' => $this->pageHookOutput, 'itemPageHookOutput' => $this->itemPageHookOutput, ] ); } }) ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->assertSee('Item #1') ->assertSee('Item #2') ->assertSee('Item #3') ->assertDontSee('Item #4') // Test Posts paginator ->waitForLivewire()->click('@nextPage.before') ->assertDontSee('Post #3') ->assertSee('Post #4') ->assertSee('Post #5') ->assertSee('Post #6') ->assertQueryStringHas('page', '2') ->assertSee('Item #1') ->assertSee('Item #2') ->assertSee('Item #3') ->assertDontSee('Item #4') ->assertQueryStringMissing('itemPage') ->waitForLivewire()->click('@previousPage.before') ->assertDontSee('Post #6') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertQueryStringMissing('page') ->assertSee('Item #1') ->assertSee('Item #2') ->assertSee('Item #3') ->assertDontSee('Item #4') ->assertQueryStringMissing('itemPage') // Test Items paginator ->waitForLivewire()->click('@nextPage.itemPage.before') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->assertQueryStringMissing('page') ->assertDontSee('Item #3') ->assertSee('Item #4') ->assertSee('Item #5') ->assertSee('Item #6') ->assertQueryStringHas('itemPage', '2') ->waitForLivewire()->click('@previousPage.itemPage.before') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->assertQueryStringMissing('page') ->assertDontSee('Item #6') ->assertSee('Item #1') ->assertSee('Item #2') ->assertSee('Item #3') ->assertQueryStringMissing('itemPage') ; } public function test_it_can_have_two_pagination_instances_on_a_page_bootstrap() { Livewire::visit(new class extends Component { use WithPagination; protected $paginationTheme = 'bootstrap'; public $pageHookOutput = null; public $itemPageHookOutput = null; public function updatedPage($page) { $this->pageHookOutput = 'page-is-set-to-' . $page; } public function updatedItemPage($page) { $this->itemPageHookOutput = 'item-page-is-set-to-' . $page; } public function render() { return Blade::render( <<< 'HTML' <div> <div> <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach </div> {{ $posts->links() }} </div> <span dusk="page-pagination-hook">{{ $pageHookOutput }}</span> <div> <div> @foreach ($items as $item) <h1 wire:key="item-{{ $item->id }}">{{ $item->title }}</h1> @endforeach </div> {{ $items->links() }} </div> <span dusk="item-page-pagination-hook">{{ $itemPageHookOutput }}</span> </div> HTML, [ 'posts' => Post::paginate(3), 'items' => Item::paginate(3, ['*'], 'itemPage'), 'pageHookOutput' => $this->pageHookOutput, 'itemPageHookOutput' => $this->itemPageHookOutput, ] ); } }) ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->assertSee('Item #1') ->assertSee('Item #2') ->assertSee('Item #3') ->assertDontSee('Item #4') // Test Posts paginator ->waitForLivewire()->click('@nextPage') ->assertDontSee('Post #3') ->assertSee('Post #4') ->assertSee('Post #5') ->assertSee('Post #6') ->assertQueryStringHas('page', '2') ->assertSee('Item #1') ->assertSee('Item #2') ->assertSee('Item #3') ->assertDontSee('Item #4') ->assertQueryStringMissing('itemPage') ->waitForLivewire()->click('@previousPage') ->assertDontSee('Post #6') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertQueryStringMissing('page') ->assertSee('Item #1') ->assertSee('Item #2') ->assertSee('Item #3') ->assertDontSee('Item #4') ->assertQueryStringMissing('itemPage') // Test Items paginator ->waitForLivewire()->click('@nextPage.itemPage') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->assertQueryStringMissing('page') ->assertDontSee('Item #3') ->assertSee('Item #4') ->assertSee('Item #5') ->assertSee('Item #6') ->assertQueryStringHas('itemPage', '2') ->waitForLivewire()->click('@previousPage.itemPage') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->assertQueryStringMissing('page') ->assertDontSee('Item #6') ->assertSee('Item #1') ->assertSee('Item #2') ->assertSee('Item #3') ->assertQueryStringMissing('itemPage') ; } public function test_it_calls_pagination_hook_methods_when_pagination_changes_with_multiple_paginators() { Livewire::visit(new class extends Component { use WithPagination; public $pageHookOutput = null; public $itemPageHookOutput = null; public function updatedPage($page) { $this->pageHookOutput = 'page-is-set-to-' . $page; } public function updatedItemPage($page) { $this->itemPageHookOutput = 'item-page-is-set-to-' . $page; } public function render() { return Blade::render( <<< 'HTML' <div> <div> <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach </div> {{ $posts->links() }} </div> <span dusk="page-pagination-hook">{{ $pageHookOutput }}</span> <div> <div> @foreach ($items as $item) <h1 wire:key="item-{{ $item->id }}">{{ $item->title }}</h1> @endforeach </div> {{ $items->links() }} </div> <span dusk="item-page-pagination-hook">{{ $itemPageHookOutput }}</span> </div> HTML, [ 'posts' => Post::paginate(3), 'items' => Item::paginate(3, ['*'], 'itemPage'), 'pageHookOutput' => $this->pageHookOutput, 'itemPageHookOutput' => $this->itemPageHookOutput, ] ); } }) ->assertSeeNothingIn('@page-pagination-hook') ->assertSeeNothingIn('@item-page-pagination-hook') ->assertSee('Post #1') ->assertSee('Item #1') ->waitForLivewire()->click('@nextPage.before') ->assertSeeNothingIn('@item-page-pagination-hook') ->assertSeeIn('@page-pagination-hook', 'page-is-set-to-2') ->assertSee('Post #4') ->assertSee('Item #1') ->waitForLivewire()->click('@nextPage.itemPage.before') ->assertSeeIn('@page-pagination-hook', 'page-is-set-to-2') ->assertSeeIn('@item-page-pagination-hook', 'item-page-is-set-to-2') ->assertSee('Post #4') ->assertSee('Item #4') ->waitForLivewire()->click('@previousPage.itemPage.before') ->assertSeeIn('@page-pagination-hook', 'page-is-set-to-2') ->assertSeeIn('@item-page-pagination-hook', 'item-page-is-set-to-1') ->assertSee('Post #4') ->assertSee('Item #1') ->waitForLivewire()->click('@previousPage.before') ->assertSeeIn('@page-pagination-hook', 'page-is-set-to-1') ->assertSeeIn('@item-page-pagination-hook', 'item-page-is-set-to-1') ->assertSee('Post #1') ->assertSee('Item #1') ; } public function test_it_calls_pagination_hook_methods_when_page_is_kebab_cased() { Livewire::visit(new class extends Component { use WithPagination; public $itemPageHookOutput = null; public function updatedItemPage($page) { $this->itemPageHookOutput = 'item-page-is-set-to-' . $page; } public function render() { return Blade::render( <<< 'HTML' <div> {{ $items->links() }} <span dusk="item-page-pagination-hook">{{ $itemPageHookOutput }}</span> </div> HTML, [ 'items' => Item::paginate(3, ['*'], 'item-page'), 'itemPageHookOutput' => $this->itemPageHookOutput ] ); } }) ->assertSeeNothingIn('@item-page-pagination-hook') ->waitForLivewire()->click('@nextPage.item-page.before') ->assertSeeIn('@item-page-pagination-hook', 'item-page-is-set-to-2'); } public function test_pagination_trait_resolves_query_string_alias_for_page_from_component() { Livewire::withQueryParams(['p' => '2']) ->visit(new class extends Component { use WithPagination; protected $queryString = [ 'paginators.page' => ['as' => 'p'] ]; public function render() { return Blade::render( <<< 'HTML' <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach {{ $posts->links() }} </div> HTML, [ 'posts' => Post::paginate(3), ] ); } }) // Test a deeplink to page 2 with "p" from the query string shows the second page. ->assertDontSee('Post #3') ->assertSee('Post #4') ->assertSee('Post #5') ->assertSee('Post #6') ->assertQueryStringHas('p', '2') ->waitForLivewire()->click('@previousPage.before') ->assertDontSee('Post #4') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertQueryStringHas('p', '1') ; } public function test_pagination_is_tracked_in_query_string_on_lazy_components() { Livewire::withQueryParams(['page' => '2']) ->visit(new #[\Livewire\Attributes\Lazy] class extends Component { use WithPagination; public function render() { return Blade::render( <<< 'HTML' <div> @foreach ($posts as $post) <h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1> @endforeach {{ $posts->links() }} </div> HTML, [ 'posts' => Post::paginate(3), ] ); } }) ->waitForText('Post #4') ->assertDontSee('Post #3') ->assertSee('Post #4') ->assertSee('Post #5') ->assertSee('Post #6') ->assertQueryStringHas('page', '2') ->waitForLivewire()->click('@previousPage.before') ->assertDontSee('Post #4') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertQueryStringHas('page', '1') ; } public function test_it_loads_pagination_on_nested_alpine_tabs() { Livewire::visit(new class extends Component { use WithPagination; public $pageHookOutput = null; public function updatedPage($page) { $this->pageHookOutput = 'page-is-set-to-'.$page; } public function render() { return Blade::render( <<< 'HTML' <div x-data="{ tab: window.location.hash ? window.location.hash.substring(1) : 'general' }"> <nav> <button dusk="general" x-on:click.prevent="tab = 'general'; window.location.hash = 'general'" :class="{ 'tab--active': tab === 'general' }" class="general"> General </button> <button dusk="deals" x-on:click.prevent="tab = 'deals'; window.location.hash = 'deals'" :class="{ 'tab--active': tab === 'deals' }" class="deals"> Deals </button> </nav> <div x-show="tab === 'deals'"> <div x-data="{ dealSubTab: 'posts' }"> <nav> <button x-on:click.prevent="dealSubTab = 'posts'" :class="{ 'tab--active': dealSubTab === 'posts' }"> Posts </button> </nav> <div x-show="dealSubTab === 'posts'"> <div> @foreach ($posts as $post) <h1 wire:key='post-{{ $post->id }}'>{{ $post->title }}</h1> @endforeach </div> {{ $posts->links() }} </div> <span dusk="page-pagination-hook">{{ $pageHookOutput }}</span> </div> </div> </div> HTML, [ 'posts' => Post::paginate(3), 'pageHookOutput' => $this->pageHookOutput, ] ); } }) ->click('@deals') ->assertFragmentIs('deals') ->assertSee('Post #1') ->assertSee('Post #2') ->assertSee('Post #3') ->assertDontSee('Post #4') ->waitForLivewire()->click('@nextPage.before') ->assertSeeIn('@page-pagination-hook', 'page-is-set-to-2') ->assertDontSee('Post #3') ->assertSee('Post #4') ->assertSee('Post #5') ->assertSee('Post #6') ->waitForLivewire()->click('@nextPage.before') ->assertSeeIn('@page-pagination-hook', 'page-is-set-to-3') ->assertDontSee('Post #6') ->assertSee('Post #7')
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/UnitTest.php
src/Features/SupportPagination/UnitTest.php
<?php namespace Livewire\Features\SupportPagination; use Illuminate\Database\Eloquent\Model; use Livewire\Attributes\Computed; use Livewire\Component; use Livewire\Livewire; use Livewire\WithPagination; use Sushi\Sushi; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_can_navigate_to_previous_page() { Livewire::test(ComponentWithPaginationStub::class) ->set('paginators.page', 2) ->call('previousPage') ->assertSetStrict('paginators.page', 1); } public function test_can_navigate_to_next_page() { Livewire::test(ComponentWithPaginationStub::class) ->call('nextPage') ->assertSetStrict('paginators.page', 2); } public function test_can_navigate_to_specific_page() { Livewire::test(ComponentWithPaginationStub::class) ->call('gotoPage', 5) ->assertSetStrict('paginators.page', 5); } public function test_previous_page_cannot_be_less_than_one() { Livewire::test(ComponentWithPaginationStub::class) ->call('previousPage') ->assertSetStrict('paginators.page', 1); } public function test_double_page_value_should_be_casted_to_int() { Livewire::test(ComponentWithPaginationStub::class) ->call('gotoPage', 2.5) ->assertSetStrict('paginators.page', 2); } public function test_can_set_a_custom_links_theme_in_component() { Livewire::test(new class extends Component { use WithPagination; function paginationView() { return 'custom-pagination-theme'; } #[Computed] function posts() { return PaginatorPostTestModel::paginate(); } function render() { return <<<'HTML' <div> @foreach ($this->posts as $post) @endforeach {{ $this->posts->links() }} </div> HTML; } })->assertSee('Custom pagination theme'); } public function test_can_set_a_custom_simple_links_theme_in_component() { Livewire::test(new class extends Component { use WithPagination; function paginationSimpleView() { return 'custom-simple-pagination-theme'; } #[Computed] function posts() { return PaginatorPostTestModel::simplePaginate(); } function render() { return <<<'HTML' <div> @foreach ($this->posts as $post) @endforeach {{ $this->posts->links() }} </div> HTML; } })->assertSee('Custom simple pagination theme'); } public function test_calling_pagination_getPage_before_paginate_method_resolve_the_correct_page_number_in_first_visit_or_after_reload() { Livewire::withQueryParams(['page' => 5])->test(new class extends Component { use WithPagination; public int $page = 1; #[Computed] function posts() { $this->page = $this->getPage(); return PaginatorPostTestModel::paginate(); } function render() { return <<<'HTML' <div> @foreach ($this->posts as $post) @endforeach {{ $this->posts->links() }} </div> HTML; } }) ->assertSetStrict('page', 5) ->assertSetStrict('paginators.page', 5) ->call('gotoPage', 3) ->assertSetStrict('page', 3) ->assertSetStrict('paginators.page', 3); } } class ComponentWithPaginationStub extends TestComponent { use WithPagination; } class PaginatorPostTestModel extends Model { use Sushi; protected $rows = []; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/WithoutUrlPagination.php
src/Features/SupportPagination/WithoutUrlPagination.php
<?php namespace Livewire\Features\SupportPagination; trait WithoutUrlPagination { // }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/HandlesPagination.php
src/Features/SupportPagination/HandlesPagination.php
<?php namespace Livewire\Features\SupportPagination; use Illuminate\Pagination\Paginator; use Illuminate\Support\Str; trait HandlesPagination { public $paginators = []; public function queryStringHandlesPagination() { return collect($this->paginators)->mapWithKeys(function ($page, $pageName) { return ['paginators.'.$pageName => ['history' => true, 'as' => $pageName, 'keep' => false]]; })->toArray(); } public function getPage($pageName = 'page') { return $this->paginators[$pageName] ?? Paginator::resolveCurrentPage($pageName); } public function previousPage($pageName = 'page') { $this->setPage(max(($this->paginators[$pageName] ?? 1) - 1, 1), $pageName); } public function nextPage($pageName = 'page') { $this->setPage(($this->paginators[$pageName] ?? 1) + 1, $pageName); } public function gotoPage($page, $pageName = 'page') { $this->setPage($page, $pageName); } public function resetPage($pageName = 'page') { $this->setPage(1, $pageName); } public function setPage($page, $pageName = 'page') { if (is_numeric($page)) { $page = (int) ($page <= 0 ? 1 : $page); } $beforePaginatorMethod = 'updatingPaginators'; $afterPaginatorMethod = 'updatedPaginators'; $beforeMethod = 'updating' . ucfirst(Str::camel($pageName)); $afterMethod = 'updated' . ucfirst(Str::camel($pageName)); if (method_exists($this, $beforePaginatorMethod)) { $this->{$beforePaginatorMethod}($page, $pageName); } if (method_exists($this, $beforeMethod)) { $this->{$beforeMethod}($page, null); } $this->paginators[$pageName] = $page; if (method_exists($this, $afterPaginatorMethod)) { $this->{$afterPaginatorMethod}($page, $pageName); } if (method_exists($this, $afterMethod)) { $this->{$afterMethod}($page, null); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/views/bootstrap.blade.php
src/Features/SupportPagination/views/bootstrap.blade.php
@php if (! isset($scrollTo)) { $scrollTo = 'body'; } $scrollIntoViewJsSnippet = ($scrollTo !== false) ? <<<JS (\$el.closest('{$scrollTo}') || document.querySelector('{$scrollTo}')).scrollIntoView() JS : ''; @endphp <div> @if ($paginator->hasPages()) <nav class="d-flex justify-items-center justify-content-between"> <div class="d-flex justify-content-between flex-fill d-sm-none"> <ul class="pagination"> {{-- Previous Page Link --}} @if ($paginator->onFirstPage()) <li class="page-item disabled" aria-disabled="true"> <span class="page-link">@lang('pagination.previous')</span> </li> @else <li class="page-item"> <button type="button" dusk="previousPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}" class="page-link" wire:click="previousPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled">@lang('pagination.previous')</button> </li> @endif {{-- Next Page Link --}} @if ($paginator->hasMorePages()) <li class="page-item"> <button type="button" dusk="nextPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}" class="page-link" wire:click="nextPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled">@lang('pagination.next')</button> </li> @else <li class="page-item disabled" aria-disabled="true"> <span class="page-link" aria-hidden="true">@lang('pagination.next')</span> </li> @endif </ul> </div> <div class="d-none flex-sm-fill d-sm-flex align-items-sm-center justify-content-sm-between"> <div> <p class="small text-muted"> {!! __('Showing') !!} <span class="fw-semibold">{{ $paginator->firstItem() }}</span> {!! __('to') !!} <span class="fw-semibold">{{ $paginator->lastItem() }}</span> {!! __('of') !!} <span class="fw-semibold">{{ $paginator->total() }}</span> {!! __('results') !!} </p> </div> <div> <ul class="pagination"> {{-- Previous Page Link --}} @if ($paginator->onFirstPage()) <li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.previous')"> <span class="page-link" aria-hidden="true">&lsaquo;</span> </li> @else <li class="page-item"> <button type="button" dusk="previousPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}" class="page-link" wire:click="previousPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled" aria-label="@lang('pagination.previous')">&lsaquo;</button> </li> @endif {{-- Pagination Elements --}} @foreach ($elements as $element) {{-- "Three Dots" Separator --}} @if (is_string($element)) <li class="page-item disabled" aria-disabled="true"><span class="page-link">{{ $element }}</span></li> @endif {{-- Array Of Links --}} @if (is_array($element)) @foreach ($element as $page => $url) @if ($page == $paginator->currentPage()) <li class="page-item active" wire:key="paginator-{{ $paginator->getPageName() }}-page-{{ $page }}" aria-current="page"><span class="page-link">{{ $page }}</span></li> @else <li class="page-item" wire:key="paginator-{{ $paginator->getPageName() }}-page-{{ $page }}"><button type="button" class="page-link" wire:click="gotoPage({{ $page }}, '{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}">{{ $page }}</button></li> @endif @endforeach @endif @endforeach {{-- Next Page Link --}} @if ($paginator->hasMorePages()) <li class="page-item"> <button type="button" dusk="nextPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}" class="page-link" wire:click="nextPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled" aria-label="@lang('pagination.next')">&rsaquo;</button> </li> @else <li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.next')"> <span class="page-link" aria-hidden="true">&rsaquo;</span> </li> @endif </ul> </div> </div> </nav> @endif </div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/views/tailwind.blade.php
src/Features/SupportPagination/views/tailwind.blade.php
@php if (! isset($scrollTo)) { $scrollTo = 'body'; } $scrollIntoViewJsSnippet = ($scrollTo !== false) ? <<<JS (\$el.closest('{$scrollTo}') || document.querySelector('{$scrollTo}')).scrollIntoView() JS : ''; @endphp <div> @if ($paginator->hasPages()) <nav role="navigation" aria-label="Pagination Navigation" class="flex items-center justify-between"> <div class="flex justify-between flex-1 sm:hidden"> <span> @if ($paginator->onFirstPage()) <span class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 cursor-default leading-5 rounded-md dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:focus:border-blue-700 dark:active:bg-gray-700 dark:active:text-gray-300"> {!! __('pagination.previous') !!} </span> @else <button type="button" wire:click="previousPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled" dusk="previousPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}.before" class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 rounded-md hover:text-gray-500 focus:outline-none focus:ring ring-blue-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:focus:border-blue-700 dark:active:bg-gray-700 dark:active:text-gray-300"> {!! __('pagination.previous') !!} </button> @endif </span> <span> @if ($paginator->hasMorePages()) <button type="button" wire:click="nextPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled" dusk="nextPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}.before" class="relative inline-flex items-center px-4 py-2 ml-3 text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 rounded-md hover:text-gray-500 focus:outline-none focus:ring ring-blue-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:focus:border-blue-700 dark:active:bg-gray-700 dark:active:text-gray-300"> {!! __('pagination.next') !!} </button> @else <span class="relative inline-flex items-center px-4 py-2 ml-3 text-sm font-medium text-gray-500 bg-white border border-gray-300 cursor-default leading-5 rounded-md dark:text-gray-600 dark:bg-gray-800 dark:border-gray-600"> {!! __('pagination.next') !!} </span> @endif </span> </div> <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between"> <div> <p class="text-sm text-gray-700 leading-5 dark:text-gray-400"> <span>{!! __('Showing') !!}</span> <span class="font-medium">{{ $paginator->firstItem() }}</span> <span>{!! __('to') !!}</span> <span class="font-medium">{{ $paginator->lastItem() }}</span> <span>{!! __('of') !!}</span> <span class="font-medium">{{ $paginator->total() }}</span> <span>{!! __('results') !!}</span> </p> </div> <div> <span class="relative z-0 inline-flex rtl:flex-row-reverse rounded-md shadow-sm"> <span> {{-- Previous Page Link --}} @if ($paginator->onFirstPage()) <span aria-disabled="true" aria-label="{{ __('pagination.previous') }}"> <span class="relative inline-flex items-center px-2 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 cursor-default rounded-l-md leading-5 dark:bg-gray-800 dark:border-gray-600" aria-hidden="true"> <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" /> </svg> </span> </span> @else <button type="button" wire:click="previousPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" dusk="previousPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}.after" class="relative inline-flex items-center px-2 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-l-md leading-5 hover:text-gray-400 focus:z-10 focus:outline-none focus:border-blue-300 focus:ring ring-blue-300 active:bg-gray-100 active:text-gray-500 transition ease-in-out duration-150 dark:bg-gray-800 dark:border-gray-600 dark:active:bg-gray-700 dark:focus:border-blue-800" aria-label="{{ __('pagination.previous') }}"> <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" /> </svg> </button> @endif </span> {{-- Pagination Elements --}} @foreach ($elements as $element) {{-- "Three Dots" Separator --}} @if (is_string($element)) <span aria-disabled="true"> <span class="relative inline-flex items-center px-4 py-2 -ml-px text-sm font-medium text-gray-700 bg-white border border-gray-300 cursor-default leading-5 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300">{{ $element }}</span> </span> @endif {{-- Array Of Links --}} @if (is_array($element)) @foreach ($element as $page => $url) <span wire:key="paginator-{{ $paginator->getPageName() }}-page{{ $page }}"> @if ($page == $paginator->currentPage()) <span aria-current="page"> <span class="relative inline-flex items-center px-4 py-2 -ml-px text-sm font-medium text-gray-500 bg-white border border-gray-300 cursor-default leading-5 dark:bg-gray-800 dark:border-gray-600">{{ $page }}</span> </span> @else <button type="button" wire:click="gotoPage({{ $page }}, '{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" class="relative inline-flex items-center px-4 py-2 -ml-px text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 hover:text-gray-500 focus:z-10 focus:outline-none focus:border-blue-300 focus:ring ring-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 dark:hover:text-gray-300 dark:active:bg-gray-700 dark:focus:border-blue-800" aria-label="{{ __('Go to page :page', ['page' => $page]) }}"> {{ $page }} </button> @endif </span> @endforeach @endif @endforeach <span> {{-- Next Page Link --}} @if ($paginator->hasMorePages()) <button type="button" wire:click="nextPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" dusk="nextPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}.after" class="relative inline-flex items-center px-2 py-2 -ml-px text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-r-md leading-5 hover:text-gray-400 focus:z-10 focus:outline-none focus:border-blue-300 focus:ring ring-blue-300 active:bg-gray-100 active:text-gray-500 transition ease-in-out duration-150 dark:bg-gray-800 dark:border-gray-600 dark:active:bg-gray-700 dark:focus:border-blue-800" aria-label="{{ __('pagination.next') }}"> <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" /> </svg> </button> @else <span aria-disabled="true" aria-label="{{ __('pagination.next') }}"> <span class="relative inline-flex items-center px-2 py-2 -ml-px text-sm font-medium text-gray-500 bg-white border border-gray-300 cursor-default rounded-r-md leading-5 dark:bg-gray-800 dark:border-gray-600" aria-hidden="true"> <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" /> </svg> </span> </span> @endif </span> </span> </div> </div> </nav> @endif </div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/views/simple-bootstrap.blade.php
src/Features/SupportPagination/views/simple-bootstrap.blade.php
@php if (! isset($scrollTo)) { $scrollTo = 'body'; } $scrollIntoViewJsSnippet = ($scrollTo !== false) ? <<<JS (\$el.closest('{$scrollTo}') || document.querySelector('{$scrollTo}')).scrollIntoView() JS : ''; @endphp <div> @if ($paginator->hasPages()) <nav> <ul class="pagination"> {{-- Previous Page Link --}} @if ($paginator->onFirstPage()) <li class="page-item disabled" aria-disabled="true"> <span class="page-link">@lang('pagination.previous')</span> </li> @else @if(method_exists($paginator,'getCursorName')) <li class="page-item"> <button dusk="previousPage" type="button" class="page-link" wire:key="cursor-{{ $paginator->getCursorName() }}-{{ $paginator->previousCursor()->encode() }}" wire:click="setPage('{{$paginator->previousCursor()->encode()}}','{{ $paginator->getCursorName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled">@lang('pagination.previous')</button> </li> @else <li class="page-item"> <button type="button" dusk="previousPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}" class="page-link" wire:click="previousPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled">@lang('pagination.previous')</button> </li> @endif @endif {{-- Next Page Link --}} @if ($paginator->hasMorePages()) @if(method_exists($paginator,'getCursorName')) <li class="page-item"> <button dusk="nextPage" type="button" class="page-link" wire:key="cursor-{{ $paginator->getCursorName() }}-{{ $paginator->nextCursor()->encode() }}" wire:click="setPage('{{$paginator->nextCursor()->encode()}}','{{ $paginator->getCursorName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled">@lang('pagination.next')</button> </li> @else <li class="page-item"> <button type="button" dusk="nextPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}" class="page-link" wire:click="nextPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled">@lang('pagination.next')</button> </li> @endif @else <li class="page-item disabled" aria-disabled="true"> <span class="page-link">@lang('pagination.next')</span> </li> @endif </ul> </nav> @endif </div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPagination/views/simple-tailwind.blade.php
src/Features/SupportPagination/views/simple-tailwind.blade.php
@php if (! isset($scrollTo)) { $scrollTo = 'body'; } $scrollIntoViewJsSnippet = ($scrollTo !== false) ? <<<JS (\$el.closest('{$scrollTo}') || document.querySelector('{$scrollTo}')).scrollIntoView() JS : ''; @endphp <div> @if ($paginator->hasPages()) <nav role="navigation" aria-label="Pagination Navigation" class="flex justify-between"> <span> {{-- Previous Page Link --}} @if ($paginator->onFirstPage()) <span class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 cursor-default leading-5 rounded-md dark:text-gray-600 dark:bg-gray-800 dark:border-gray-600"> {!! __('pagination.previous') !!} </span> @else @if(method_exists($paginator,'getCursorName')) <button type="button" dusk="previousPage" wire:key="cursor-{{ $paginator->getCursorName() }}-{{ $paginator->previousCursor()->encode() }}" wire:click="setPage('{{$paginator->previousCursor()->encode()}}','{{ $paginator->getCursorName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled" class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 rounded-md hover:text-gray-500 focus:outline-none focus:ring ring-blue-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:focus:border-blue-700 dark:active:bg-gray-700 dark:active:text-gray-300"> {!! __('pagination.previous') !!} </button> @else <button type="button" wire:click="previousPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled" dusk="previousPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}" class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 rounded-md hover:text-gray-500 focus:outline-none focus:ring ring-blue-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:focus:border-blue-700 dark:active:bg-gray-700 dark:active:text-gray-300"> {!! __('pagination.previous') !!} </button> @endif @endif </span> <span> {{-- Next Page Link --}} @if ($paginator->hasMorePages()) @if(method_exists($paginator,'getCursorName')) <button type="button" dusk="nextPage" wire:key="cursor-{{ $paginator->getCursorName() }}-{{ $paginator->nextCursor()->encode() }}" wire:click="setPage('{{$paginator->nextCursor()->encode()}}','{{ $paginator->getCursorName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled" class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 rounded-md hover:text-gray-500 focus:outline-none focus:ring ring-blue-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:focus:border-blue-700 dark:active:bg-gray-700 dark:active:text-gray-300"> {!! __('pagination.next') !!} </button> @else <button type="button" wire:click="nextPage('{{ $paginator->getPageName() }}')" x-on:click="{{ $scrollIntoViewJsSnippet }}" wire:loading.attr="disabled" dusk="nextPage{{ $paginator->getPageName() == 'page' ? '' : '.' . $paginator->getPageName() }}" class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 rounded-md hover:text-gray-500 focus:outline-none focus:ring ring-blue-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:focus:border-blue-700 dark:active:bg-gray-700 dark:active:text-gray-300"> {!! __('pagination.next') !!} </button> @endif @else <span class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 cursor-default leading-5 rounded-md dark:text-gray-600 dark:bg-gray-800 dark:border-gray-600"> {!! __('pagination.next') !!} </span> @endif </span> </nav> @endif </div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireCurrent/BrowserTest.php
src/Features/SupportWireCurrent/BrowserTest.php
<?php namespace Livewire\Features\SupportWireCurrent; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\View; use Livewire\Attributes\Layout; use Tests\BrowserTestCase; use Livewire\Component; use Livewire\Livewire; class BrowserTest extends BrowserTestCase { public static function tweakApplicationHook() { return function () { View::addNamespace('test-views', __DIR__ . '/test-views'); Livewire::component('first-page', FirstPage::class); Livewire::component('second-page', SecondPage::class); Livewire::component('wire-current-inside-component', WireCurrentInsideComponentPage::class); Route::get('/first', FirstPage::class)->middleware('web')->name('first'); Route::get('/first/sub', FirstSubPage::class)->middleware('web')->name('first.sub'); Route::get('/second', SecondPage::class)->middleware('web')->name('second'); Route::get('/wire-current-inside-component', WireCurrentInsideComponentPage::class)->middleware('web')->name('wire-current-inside-component'); }; } public function test_wire_current_matches_urls_properly() { $this->browse(function ($browser) { $browser ->visit('/first') ->waitForText('On first') ->assertAttributeContains('@link.first', 'class', 'active') ->assertAttributeDoesntContain('@link.sub', 'class', 'active') ->assertAttributeDoesntContain('@link.second', 'class', 'active') ->assertAttributeContains('@link.first.exact', 'class', 'active') ->assertAttributeDoesntContain('@link.sub.exact', 'class', 'active') ->assertAttributeDoesntContain('@link.second.exact', 'class', 'active') ->assertAttributeContains('@link.first.slash', 'class', 'active') ->assertAttributeDoesntContain('@link.first.slash.strict', 'class', 'active') ->assertAttributeContains('@route.link.first', 'class', 'active') ->assertAttributeDoesntContain('@route.link.sub', 'class', 'active') ->assertAttributeDoesntContain('@route.link.second', 'class', 'active') ->assertAttributeContains('@route.link.first.exact', 'class', 'active') ->assertAttributeDoesntContain('@route.link.sub.exact', 'class', 'active') ->assertAttributeDoesntContain('@route.link.second.exact', 'class', 'active') ->assertAttributeContains('@native.link.first', 'class', 'active') ->assertAttributeDoesntContain('@native.link.sub', 'class', 'active') ->assertAttributeDoesntContain('@native.link.second', 'class', 'active') ->assertAttributeContains('@native.link.first.exact', 'class', 'active') ->assertAttributeDoesntContain('@native.link.sub.exact', 'class', 'active') ->assertAttributeDoesntContain('@native.link.second.exact', 'class', 'active') ->click('@link.sub') ->waitForText('On sub') ->assertAttributeContains('@link.first', 'class', 'active') ->assertAttributeContains('@link.sub', 'class', 'active') ->assertAttributeDoesntContain('@link.second', 'class', 'active') ->assertAttributeDoesntContain('@link.first.exact', 'class', 'active') ->assertAttributeContains('@link.sub.exact', 'class', 'active') ->assertAttributeDoesntContain('@link.second.exact', 'class', 'active') ->assertAttributeContains('@link.first.slash', 'class', 'active') ->assertAttributeDoesntContain('@link.first.slash.strict', 'class', 'active') ->assertAttributeContains('@route.link.first', 'class', 'active') ->assertAttributeContains('@route.link.sub', 'class', 'active') ->assertAttributeDoesntContain('@route.link.second', 'class', 'active') ->assertAttributeDoesntContain('@route.link.first.exact', 'class', 'active') ->assertAttributeContains('@route.link.sub.exact', 'class', 'active') ->assertAttributeDoesntContain('@route.link.second.exact', 'class', 'active') ->assertAttributeContains('@native.link.first', 'class', 'active') ->assertAttributeContains('@native.link.sub', 'class', 'active') ->assertAttributeDoesntContain('@native.link.second', 'class', 'active') ->assertAttributeDoesntContain('@native.link.first.exact', 'class', 'active') ->assertAttributeContains('@native.link.sub.exact', 'class', 'active') ->assertAttributeDoesntContain('@native.link.second.exact', 'class', 'active') ->click('@link.second') ->waitForText('On second') ->assertAttributeDoesntContain('@link.first', 'class', 'active') ->assertAttributeDoesntContain('@link.sub', 'class', 'active') ->assertAttributeContains('@link.second', 'class', 'active') ->assertAttributeDoesntContain('@link.first.exact', 'class', 'active') ->assertAttributeDoesntContain('@link.sub.exact', 'class', 'active') ->assertAttributeContains('@link.second.exact', 'class', 'active') ->assertAttributeDoesntContain('@route.link.first', 'class', 'active') ->assertAttributeDoesntContain('@route.link.sub', 'class', 'active') ->assertAttributeContains('@route.link.second', 'class', 'active') ->assertAttributeDoesntContain('@route.link.first.exact', 'class', 'active') ->assertAttributeDoesntContain('@route.link.sub.exact', 'class', 'active') ->assertAttributeContains('@route.link.second.exact', 'class', 'active') ->assertAttributeDoesntContain('@native.link.first', 'class', 'active') ->assertAttributeDoesntContain('@native.link.sub', 'class', 'active') ->assertAttributeContains('@native.link.second', 'class', 'active') ->assertAttributeDoesntContain('@native.link.first.exact', 'class', 'active') ->assertAttributeDoesntContain('@native.link.sub.exact', 'class', 'active') ->assertAttributeContains('@native.link.second.exact', 'class', 'active') ->assertAttributeDoesntContain('@link.first.slash', 'class', 'active') ->assertAttributeDoesntContain('@link.first.slash.strict', 'class', 'active') ; }); } public function test_wire_current_supports_adding_data_current_attribute() { $this->browse(function ($browser) { $browser ->visit('/first') ->waitForText('On first') ->assertAttribute('@link.first', 'data-current', '') ->assertAttributeMissing('@link.sub', 'data-current', '') ->assertAttributeMissing('@link.second', 'data-current', '') ->assertAttribute('@link.first.exact', 'data-current', '') ->assertAttributeMissing('@link.sub.exact', 'data-current', '') ->assertAttributeMissing('@link.second.exact', 'data-current', '') ->click('@link.sub') ->waitForText('On sub') ->assertAttribute('@link.first', 'data-current', '') ->assertAttribute('@link.sub', 'data-current', '') ->assertAttributeMissing('@link.second', 'data-current', '') ->assertAttributeMissing('@link.first.exact', 'data-current', '') ->assertAttribute('@link.sub.exact', 'data-current', '') ->assertAttributeMissing('@link.second.exact', 'data-current', '') ->click('@link.second') ->waitForText('On second') ->assertAttributeMissing('@link.first', 'data-current', '') ->assertAttributeMissing('@link.sub', 'data-current', '') ->assertAttribute('@link.second', 'data-current', '') ->assertAttributeMissing('@link.first.exact', 'data-current', '') ->assertAttributeMissing('@link.sub.exact', 'data-current', '') ->assertAttribute('@link.second.exact', 'data-current', '') ; }); } public function test_wire_current_works_inside_a_component_and_after_an_update() { $this->browse(function ($browser) { $browser ->visit('/wire-current-inside-component') ->waitForText('Current Page') ->assertAttribute('@current', 'data-current', '') ->assertHasClass('@current', 'active') ->waitForLivewire()->click('@refresh') ->waitForText('Current Page') ->assertAttribute('@current', 'data-current', '') ->assertHasClass('@current', 'active') ; }); } } #[Layout('test-views::navbar-sidebar')] class FirstPage extends Component { public function doRedirect($to) { return $this->redirect($to, navigate: true); } public function render() { return <<<'HTML' <div> <div>On first</div> <button type="button" wire:click="$refresh" dusk="refresh">Refresh</button> </div> HTML; } } class FirstSubPage extends Component { #[Layout('test-views::navbar-sidebar')] public function render() { return <<<'HTML' <div> <div>On sub</div> </div> HTML; } } class SecondPage extends Component { #[Layout('test-views::navbar-sidebar')] public function render() { return <<<'HTML' <div> <div>On second</div> </div> HTML; } } class WireCurrentInsideComponentPage extends Component { public function doRedirect($to) { return $this->redirect($to, navigate: true); } public function render() { return <<<'HTML' <div> <a href="/wire-current-inside-component" wire:current="active" dusk="current">Current Page</a> <button type="button" wire:click="$refresh" dusk="refresh">Refresh</button> </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireCurrent/test-views/navbar-sidebar.blade.php
src/Features/SupportWireCurrent/test-views/navbar-sidebar.blade.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .active { background-color: #DDF; } </style> </head> <body> <div> @persist('nav') <ul x-data> <li><a href="/first" wire:navigate dusk="link.first" wire:current="active">Link first</a></li> <li><a href="/first/sub" wire:navigate dusk="link.sub" wire:current="active">Link first/sub</a></li> <li><a href="/second" wire:navigate dusk="link.second" wire:current="active">Link second</a></li> <li><a href="/first" wire:navigate dusk="link.first.exact" wire:current.exact="active">exact: Link first</a></li> <li><a href="/first/sub" wire:navigate dusk="link.sub.exact" wire:current.exact="active">exact: Link first/sub</a></li> <li><a href="/second" wire:navigate dusk="link.second.exact" wire:current.exact="active">exact: Link second</a></li> <li><a href="/first/" wire:navigate dusk="link.first.slash" wire:current="active">Link first (trailing slash without .strict)</a></li> <li><a href="/first/" wire:navigate dusk="link.first.slash.strict" wire:current.strict="active">Link first (trailing slash with .strict)</a></li> <li style="padding-top: 1rem">Route helper:</li> <li><a href="{{ route('first') }}" wire:navigate dusk="route.link.first" wire:current="active">Link first</a></li> <li><a href="{{ route('first.sub') }}" wire:navigate dusk="route.link.sub" wire:current="active">Link first/sub</a></li> <li><a href="{{ route('second') }}" wire:navigate dusk="route.link.second" wire:current="active">Link second</a></li> <li><a href="{{ route('first') }}" wire:navigate dusk="route.link.first.exact" wire:current.exact="active">exact: Link first</a></li> <li><a href="{{ route('first.sub') }}" wire:navigate dusk="route.link.sub.exact" wire:current.exact="active">exact: Link first/sub</a></li> <li><a href="{{ route('second') }}" wire:navigate dusk="route.link.second.exact" wire:current.exact="active">exact: Link second</a></li> <li style="padding-top: 1rem">Non wire:navigate:</li> <li><a href="{{ route('first') }}" dusk="native.link.first" wire:current="active">Link first</a></li> <li><a href="{{ route('first.sub') }}" dusk="native.link.sub" wire:current="active">Link first/sub</a></li> <li><a href="{{ route('second') }}" dusk="native.link.second" wire:current="active">Link second</a></li> <li><a href="{{ route('first') }}" dusk="native.link.first.exact" wire:current.exact="active">exact: Link first</a></li> <li><a href="{{ route('first.sub') }}" dusk="native.link.sub.exact" wire:current.exact="active">exact: Link first/sub</a></li> <li><a href="{{ route('second') }}" dusk="native.link.second.exact" wire:current.exact="active">exact: Link second</a></li> </ul> @endpersist </div> <main> {{ $slot }} </main> </body> </html>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportDataLoading/BrowserTest.php
src/Features/SupportDataLoading/BrowserTest.php
<?php namespace Livewire\Features\SupportDataLoading; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_data_loading_attribute_is_added_to_an_element_when_it_triggers_a_request() { Livewire::visit([ new class extends \Livewire\Component { public function hydrate() { usleep(250 * 1000); // 50ms } public function render() { return <<<'HTML' <div> <button wire:click="$refresh" dusk="refresh1">Refresh</button> <button wire:click="$refresh" dusk="refresh2">Refresh</button> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertAttributeMissing('@refresh1', 'data-loading') ->assertAttributeMissing('@refresh2', 'data-loading') ->click('@refresh1') // Wait for the first request to start... ->pause(6) ->assertAttribute('@refresh1', 'data-loading', 'true') ->assertAttributeMissing('@refresh2', 'data-loading') // Wait for the first request to finish... ->pause(350) ->click('@refresh2') // Wait for the second request to start... ->pause(10) ->assertAttributeMissing('@refresh1', 'data-loading') ->assertAttribute('@refresh2', 'data-loading', 'true') // Wait for the second request to finish... ->pause(350) ->assertAttributeMissing('@refresh1', 'data-loading') ->assertAttributeMissing('@refresh2', 'data-loading') ; } public function test_data_loading_attribute_is_removed_from_an_element_when_its_request_has_finished_but_not_other_elements() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { usleep(200 * 1000); // 500ms } public function slowRequest2() { usleep(250 * 1000); // 500ms } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="slow-request">Slow request</button> <button wire:click="slowRequest2" dusk="slow-request2">Slow request 2</button> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertAttributeMissing('@slow-request', 'data-loading') ->assertAttributeMissing('@slow-request2', 'data-loading') ->click('@slow-request') // Wait for the first request to start... ->pause(10) ->assertAttribute('@slow-request', 'data-loading', 'true') ->assertAttributeMissing('@slow-request2', 'data-loading') // Wait for the first request to start... ->pause(50) // Trigger the second request... ->click('@slow-request2') // Pause for a moment to ensure Livewire has removed the attribute... ->pause(300) ->assertAttributeMissing('@slow-request', 'data-loading') ->assertAttribute('@slow-request2', 'data-loading', 'true') ; } public function test_data_loading_attribute_is_removed_from_an_element_when_its_request_is_cancelled() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { usleep(400 * 1000); // 500ms } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="slow-request">Slow Request</button> </div> @script <script> this.interceptMessage(({ message }) => { setTimeout(() => message.cancel(), 50) }) </script> @endscript HTML; } } ]) ->waitForLivewireToLoad() ->assertAttributeMissing('@slow-request', 'data-loading') ->click('@slow-request') // Wait for the request to start... ->pause(10) ->assertAttribute('@slow-request', 'data-loading', 'true') // The interceptor cancels the request after 200ms... ->pause(50) ->assertAttributeMissing('@slow-request', 'data-loading') ; } public function test_data_loading_attribute_is_not_added_to_poll_directives() { Livewire::visit([ new class extends \Livewire\Component { public function hydrate() { usleep(250 * 1000); // 250ms } public function render() { return <<<'HTML' <div wire:poll.500ms dusk="container"> <div wire:loading dusk="loading">Loading...</div> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertAttributeMissing('@container', 'data-loading') ->waitForText('Loading...') ->assertAttributeMissing('@container', 'data-loading') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNestedComponentListeners/SupportNestedComponentListeners.php
src/Features/SupportNestedComponentListeners/SupportNestedComponentListeners.php
<?php namespace Livewire\Features\SupportNestedComponentListeners; use function Livewire\store; use Livewire\Drawer\Utils; use Livewire\ComponentHook; class SupportNestedComponentListeners extends ComponentHook { public function mount($params, $parent) { // If a Livewire component is passed an attribute with an "@" // (<livewire:child @some-event="handler") // Then turn it into an Alpine listener and add it to a // "attributes" key in the store so it can be added to the // component's memo and passed again to the server on subsequent // requests to ensure it is always added as an HTML attribute // to the root element of the component... foreach ($params as $key => $value) { if (str($key)->startsWith('@')) { // any kebab-cased parameters passed in will have been converted to camelCase // so we need to convert back to kebab to ensure events are valid in html $fullEvent = str($key)->after('@')->kebab(); $attributeKey = 'x-on:'.$fullEvent; $attributeValue = "\$wire.\$parent.".$value; store($this->component)->push('generatedAttributes', $attributeValue, $attributeKey); } } } public function render($view, $data) { return function ($html, $replaceHtml) { $attributes = store($this->component)->get('generatedAttributes', false); if (! $attributes) return; $replaceHtml(Utils::insertAttributesIntoHtmlRoot($html, $attributes)); }; } public function dehydrate($context) { $attributes = store($this->component)->get('generatedAttributes', false); if (! $attributes) return; $attributes && $context->addMemo('generatedAttributes', $attributes); } public function hydrate($memo) { if (! isset($memo['generatedAttributes'])) return; $attributes = $memo['generatedAttributes']; // Store the attributes for later dehydration... store($this->component)->set('generatedAttributes', $attributes); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportNestedComponentListeners/BrowserTest.php
src/Features/SupportNestedComponentListeners/BrowserTest.php
<?php namespace Livewire\Features\SupportNestedComponentListeners; use Livewire\Livewire; use Livewire\Component as BaseComponent; use Tests\BrowserTestCase; class BrowserTest extends BrowserTestCase { function test_can_listen_for_child_events_directly_on_child() { Livewire::visit([ new class extends BaseComponent { public $count = 0; function increment() { $this->count++; } public function render() { return <<<'HTML' <div> <h1 dusk="count">{{ $count }}</h1> <livewire:child @fired="increment" /> </div> HTML; } }, 'child' => new class extends BaseComponent { public function fire() { $this->dispatch('fired'); } public function render() { return <<<'HTML' <div> <button dusk="button" wire:click="fire">fire from child</button> <button dusk="button2" wire:click="$dispatch('fired')">fire from child (directly)</button> </div> HTML; } } ]) ->assertSeeIn('@count', '0') ->click('@button') ->waitForTextIn('@count', '1') ->click('@button') ->waitForTextIn('@count', '2') ->click('@button2') ->waitForTextIn('@count', '3'); } function test_can_dispatch_parameters_to_listeners() { Livewire::visit([ new class extends BaseComponent { public $count = 0; function increment($by = 1) { $this->count = $this->count + $by; } public function render() { return <<<'HTML' <div> <h1 dusk="count">{{ $count }}</h1> <livewire:child @fired="increment($event.detail.by)" /> </div> HTML; } }, 'child' => new class extends BaseComponent { public function render() { return <<<'HTML' <div> <button dusk="button" wire:click="$dispatch('fired', { by: 5 })">fire from child</button> </div> HTML; } } ]) ->assertSeeIn('@count', '0') ->click('@button') ->waitForTextIn('@count', '5'); } function test_can_dispatch_multi_word_event_names() { Livewire::visit([ new class extends BaseComponent { public $count = 0; function increment() { $this->count++; } public function render() { return <<<'HTML' <div> <h1 dusk="count">{{ $count }}</h1> <livewire:child @fired-event="increment" /> </div> HTML; } }, 'child' => new class extends BaseComponent { public function fire() { $this->dispatch('fired-event'); } public function render() { return <<<'HTML' <div> <button dusk="button" wire:click="fire">fire from child</button> <button dusk="button2" wire:click="$dispatch('fired-event')">fire from child (directly)</button> </div> HTML; } } ]) ->assertSeeIn('@count', '0') ->click('@button') ->waitForTextIn('@count', '1') ->click('@button') ->waitForTextIn('@count', '2') ->click('@button2') ->waitForTextIn('@count', '3'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportBladeAttributes/UnitTest.php
src/Features/SupportBladeAttributes/UnitTest.php
<?php namespace Livewire\Features\SupportBladeAttributes; use Illuminate\View\ComponentAttributeBag; use Livewire\Component; use Livewire\Livewire; class UnitTest extends \Tests\TestCase { public function test_it_adds_wire_macro_to_component_attribute_bag() { $bag = new ComponentAttributeBag([ 'wire:model.defer' => 'foo', 'wire:click.debounce.100ms' => 'bar', 'wire:keydown.enter' => 'baz', ]); $this->assertEquals('foo', $bag->wire('model')); $this->assertEquals(['defer'], $bag->wire('model')->modifiers()->toArray()); $this->assertTrue($bag->wire('model')->hasModifier('defer')); $this->assertEquals('wire:model.defer="foo"', $bag->wire('model')->toHtml()); $this->assertEquals('bar', $bag->wire('click')); $this->assertEquals(['debounce', '100ms'], $bag->wire('click')->modifiers()->toArray()); $this->assertEquals('baz', $bag->wire('keydown')); $this->assertEquals(['enter'], $bag->wire('keydown')->modifiers()->toArray()); } public function test_entangle_directive_adds_dot_defer_if_defer_modifier_is_present() { // @todo: Should this be in support entangle feature? $dom = Livewire::test(ComponentWithEntangleDirectiveUsedWithinBladeComponent::class) ->html(); $this->assertStringContainsString("{ foo: window.Livewire.find('", $dom); $this->assertStringContainsString("').entangle('foo') }", $dom); $this->assertStringContainsString("').entangle('bar').live }", $dom); } } class ComponentWithEntangleDirectiveUsedWithinBladeComponent extends Component { public function render() { return <<<'HTML' <div> <x-input wire:model="foo"/> <x-input wire:model.live="bar"/> </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportBladeAttributes/SupportBladeAttributes.php
src/Features/SupportBladeAttributes/SupportBladeAttributes.php
<?php namespace Livewire\Features\SupportBladeAttributes; use Livewire\WireDirective; use Illuminate\View\ComponentAttributeBag; use Livewire\ComponentHook; class SupportBladeAttributes extends ComponentHook { static function provide() { ComponentAttributeBag::macro('wire', function ($name) { $entries = head((array) $this->whereStartsWith('wire:'.$name)); $directive = head(array_keys($entries)); $value = head(array_values($entries)); return new WireDirective($name, $directive, $value); }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportMagicErrors/BrowserTest.php
src/Features/SupportMagicErrors/BrowserTest.php
<?php namespace Livewire\Features\SupportMagicErrors; use Livewire\Attributes\Validate; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_magic_errors_methods_all_returns_the_same_values_as_the_backend_equivalent() { Livewire::visit([ new class extends \Livewire\Component { #[Validate(['min:5', 'integer'])] public $name; #[Validate(['min:5', 'integer'])] public $email; public function save() { $this->validate(); } public function render() { return <<<'HTML' <div> <button wire:click="save" dusk="save">Save</button> <div> <div> <p>messages:</p> <p>Backend: <span dusk="backend-messages">{!! htmlspecialchars(json_encode($errors->messages())) !!}</span></p> <p>Frontend: <span dusk="frontend-messages" x-text="JSON.stringify($wire.errors.messages())"></span></p> </div> <div> <p>keys:</p> <p>Backend: <span dusk="backend-keys">{!! htmlspecialchars(json_encode($errors->keys())) !!}</span></p> <p>Frontend: <span dusk="frontend-keys" x-text="JSON.stringify($wire.errors.keys())"></span></p> </div> <div> <p>has:</p> <p>Backend: <span dusk="backend-has">{!! htmlspecialchars(json_encode($errors->has('name'))) !!}</span></p> <p>Frontend: <span dusk="frontend-has" x-text="JSON.stringify($wire.errors.has('name'))"></span></p> </div> <div> <p>hasAny:</p> <p>Backend: <span dusk="backend-hasAny">{!! htmlspecialchars(json_encode($errors->hasAny(['name', 'email']))) !!}</span></p> <p>Frontend: <span dusk="frontend-hasAny" x-text="JSON.stringify($wire.errors.hasAny(['name', 'email']))"></span></p> </div> <div> <p>missing:</p> <p>Backend: <span dusk="backend-missing">{!! htmlspecialchars(json_encode($errors->missing('name'))) !!}</span></p> <p>Frontend: <span dusk="frontend-missing" x-text="JSON.stringify($wire.errors.missing('name'))"></span></p> </div> <div> <p>first:</p> <p>Backend: <span dusk="backend-first">{!! htmlspecialchars(json_encode($errors->first('name'))) !!}</span></p> <p>Frontend: <span dusk="frontend-first" x-text="JSON.stringify($wire.errors.first('name'))"></span></p> </div> <div> <p>get:</p> <p>Backend: <span dusk="backend-get">{!! htmlspecialchars(json_encode($errors->get('name'))) !!}</span></p> <p>Frontend: <span dusk="frontend-get" x-text="JSON.stringify($wire.errors.get('name'))"></span></p> </div> <div> <p>all:</p> <p>Backend: <span dusk="backend-all">{!! htmlspecialchars(json_encode($errors->all())) !!}</span></p> <p>Frontend: <span dusk="frontend-all" x-text="JSON.stringify($wire.errors.all())"></span></p> </div> <div> <p>isEmpty:</p> <p>Backend: <span dusk="backend-isEmpty">{!! htmlspecialchars(json_encode($errors->isEmpty())) !!}</span></p> <p>Frontend: <span dusk="frontend-isEmpty" x-text="JSON.stringify($wire.errors.isEmpty())"></span></p> </div> <div> <p>isNotEmpty:</p> <p>Backend: <span dusk="backend-isNotEmpty">{!! htmlspecialchars(json_encode($errors->isNotEmpty())) !!}</span></p> <p>Frontend: <span dusk="frontend-isNotEmpty" x-text="JSON.stringify($wire.errors.isNotEmpty())"></span></p> </div> <div> <p>any:</p> <p>Backend: <span dusk="backend-any">{!! htmlspecialchars(json_encode($errors->any())) !!}</span></p> <p>Frontend: <span dusk="frontend-any" x-text="JSON.stringify($wire.errors.any())"></span></p> </div> <div> <p>count:</p> <p>Backend: <span dusk="backend-count">{!! htmlspecialchars(json_encode($errors->count())) !!}</span></p> <p>Frontend: <span dusk="frontend-count" x-text="JSON.stringify($wire.errors.count())"></span></p> </div> </div> </div> HTML; } } ]) // We just want to assert that `$wire.$errors` returns the same values as the backend equivalent... ->tap(function ($browser) { $this->assertEquals($browser->text('@backend-messages'), $browser->text('@frontend-messages')); $this->assertEquals($browser->text('@backend-keys'), $browser->text('@frontend-keys')); $this->assertEquals($browser->text('@backend-has'), $browser->text('@frontend-has')); $this->assertEquals($browser->text('@backend-hasAny'), $browser->text('@frontend-hasAny')); $this->assertEquals($browser->text('@backend-missing'), $browser->text('@frontend-missing')); $this->assertEquals($browser->text('@backend-first'), $browser->text('@frontend-first')); $this->assertEquals($browser->text('@backend-get'), $browser->text('@frontend-get')); $this->assertEquals($browser->text('@backend-all'), $browser->text('@frontend-all')); $this->assertEquals($browser->text('@backend-isEmpty'), $browser->text('@frontend-isEmpty')); $this->assertEquals($browser->text('@backend-isNotEmpty'), $browser->text('@frontend-isNotEmpty')); $this->assertEquals($browser->text('@backend-any'), $browser->text('@frontend-any')); $this->assertEquals($browser->text('@backend-count'), $browser->text('@frontend-count')); }) // Actually run validation and ensure they match... ->waitForLivewire()->click('@save') ->tap(function ($browser) { $this->assertEquals($browser->text('@backend-messages'), $browser->text('@frontend-messages')); $this->assertEquals($browser->text('@backend-keys'), $browser->text('@frontend-keys')); $this->assertEquals($browser->text('@backend-has'), $browser->text('@frontend-has')); $this->assertEquals($browser->text('@backend-hasAny'), $browser->text('@frontend-hasAny')); $this->assertEquals($browser->text('@backend-missing'), $browser->text('@frontend-missing')); $this->assertEquals($browser->text('@backend-first'), $browser->text('@frontend-first')); $this->assertEquals($browser->text('@backend-get'), $browser->text('@frontend-get')); $this->assertEquals($browser->text('@backend-all'), $browser->text('@frontend-all')); $this->assertEquals($browser->text('@backend-isEmpty'), $browser->text('@frontend-isEmpty')); $this->assertEquals($browser->text('@backend-isNotEmpty'), $browser->text('@frontend-isNotEmpty')); $this->assertEquals($browser->text('@backend-any'), $browser->text('@frontend-any')); $this->assertEquals($browser->text('@backend-count'), $browser->text('@frontend-count')); }) ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileDownloads/UnitTest.php
src/Features/SupportFileDownloads/UnitTest.php
<?php namespace Livewire\Features\SupportFileDownloads; use Illuminate\Contracts\Support\Responsable; use Illuminate\Support\Facades\Storage; use Livewire\Component; use Livewire\Livewire; use PHPUnit\Framework\ExpectationFailedException; class UnitTest extends \Tests\TestCase { public function test_can_download_a_file() { Livewire::test(FileDownloadComponent::class) ->call('download') ->assertFileDownloaded() ->assertFileDownloaded('download.txt', 'I\'m the file you should download.', 'text/plain'); } public function test_can_download_a_file_as_stream() { Livewire::test(FileDownloadComponent::class) ->call('streamDownload', 'download.txt') ->assertFileDownloaded('download.txt', 'alpinejs'); } public function can_download_a_responsable(){ Livewire::test(FileDownloadComponent::class) ->call('responsableDownload') ->assertFileDownloaded() ->assertFileDownloaded('download.txt', 'I\'m the file you should download.', 'text/plain'); } public function test_can_download_with_custom_filename() { Livewire::test(FileDownloadComponent::class) ->call('download', 'download.csv') ->assertFileDownloaded('download.csv', 'I\'m the file you should download.'); } public function test_can_download_a_file_as_stream_with_custom_filename() { Livewire::test(FileDownloadComponent::class) ->call('streamDownload', 'download.csv') ->assertFileDownloaded('download.csv', 'alpinejs'); } public function test_can_download_with_custom_filename_and_headers() { Livewire::test(FileDownloadComponent::class) ->call('download', 'download.csv', ['Content-Type' => 'text/csv']) ->assertFileDownloaded('download.csv', 'I\'m the file you should download.', 'text/csv'); } public function test_can_download_a_file_as_stream_with_custom_filename_and_headers() { Livewire::test(FileDownloadComponent::class) ->call('streamDownload', 'download.csv', ['Content-Type' => 'text/csv']) ->assertFileDownloaded('download.csv', 'alpinejs', 'text/csv'); } public function test_can_download_with_custom_japanese_filename() { Livewire::test(FileDownloadComponent::class) ->call('download', 'ダウンロード.csv') ->assertFileDownloaded('ダウンロード.csv', 'I\'m the file you should download.'); } public function test_can_download_a_file_as_stream_with_custom_japanese_filename() { Livewire::test(FileDownloadComponent::class) ->call('streamDownload', 'ダウンロード.csv') ->assertFileDownloaded('ダウンロード.csv', 'alpinejs'); } public function test_can_download_with_custom_japanese_filename_and_headers() { Livewire::test(FileDownloadComponent::class) ->call('download', 'ダウンロード.csv', ['Content-Type' => 'text/csv']) ->assertFileDownloaded('ダウンロード.csv', 'I\'m the file you should download.', 'text/csv'); } public function test_can_download_a_file_as_stream_with_custom_japanese_filename_and_headers() { Livewire::test(FileDownloadComponent::class) ->call('streamDownload', 'ダウンロード.csv', ['Content-Type' => 'text/csv']) ->assertFileDownloaded('ダウンロード.csv', 'alpinejs', 'text/csv'); } public function test_it_refreshes_html_after_download() { Livewire::test(FileDownloadComponent::class) ->call('download') ->assertFileDownloaded() ->assertSeeText('Thanks!'); } public function test_can_assert_that_nothing_was_downloaded() { Livewire::test(FileDownloadComponent::class) ->call('noDownload') ->assertNoFileDownloaded(); } public function test_can_fail_to_assert_that_nothing_was_downloaded() { $this->expectException(ExpectationFailedException::class); Livewire::test(FileDownloadComponent::class) ->call('download') ->assertNoFileDownloaded(); } } class FileDownloadComponent extends Component { public $downloaded = false; public function noDownload() { // } public function download($filename = null, $headers = []) { $this->downloaded = true; return Storage::disk('unit-downloads')->download('download.txt', $filename, $headers); } public function streamDownload($filename = null, $headers = []) { $this->downloaded = true; return response()->streamDownload(function () { echo 'alpinejs'; }, $filename, $headers); } public function responsableDownload() { return new DownloadableResponse(); } public function render() { return <<<'HTML' <div> @if($downloaded) Thanks! @endif </div> HTML; } } class DownloadableResponse implements Responsable { public function toResponse($request) { return Storage::disk('unit-downloads')->download('download.txt'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false