Skip to content

[LiveComponent] Send live action arguments to backend #218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/LiveComponent/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
- The Live Component AJAX endpoints now return HTML in all situations
instead of JSON.

- Send live action arguments to backend

## 2.0.0

- Support for `stimulus` version 2 was removed and support for `@hotwired/stimulus`
Expand Down
7 changes: 5 additions & 2 deletions src/LiveComponent/assets/dist/live_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -1070,7 +1070,7 @@ class default_1 extends Controller {
directives.forEach((directive) => {
const _executeAction = () => {
this._clearWaitingDebouncedRenders();
this._makeRequest(directive.action);
this._makeRequest(directive.action, directive.named);
};
let handled = false;
directive.modifiers.forEach((modifier) => {
Expand Down Expand Up @@ -1173,11 +1173,14 @@ class default_1 extends Controller {
}, this.debounceValue || DEFAULT_DEBOUNCE);
}
}
_makeRequest(action) {
_makeRequest(action, args) {
const splitUrl = this.urlValue.split('?');
let [url] = splitUrl;
const [, queryString] = splitUrl;
const params = new URLSearchParams(queryString || '');
if (typeof args === 'object' && Object.keys(args).length > 0) {
params.set('args', new URLSearchParams(args).toString());
}
const fetchOptions = {};
fetchOptions.headers = {
'Accept': 'application/vnd.live-component+json',
Expand Down
8 changes: 6 additions & 2 deletions src/LiveComponent/assets/src/live_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export default class extends Controller {
// taking precedence
this._clearWaitingDebouncedRenders();

this._makeRequest(directive.action);
this._makeRequest(directive.action, directive.named);
}

let handled = false;
Expand Down Expand Up @@ -294,12 +294,16 @@ export default class extends Controller {
}
}

_makeRequest(action: string|null) {
_makeRequest(action: string|null, args: Record<string,unknown>) {
const splitUrl = this.urlValue.split('?');
let [url] = splitUrl
const [, queryString] = splitUrl;
const params = new URLSearchParams(queryString || '');

if (typeof args === 'object' && Object.keys(args).length > 0) {
params.set('args', new URLSearchParams(args).toString());
}

const fetchOptions: RequestInit = {};
fetchOptions.headers = {
'Accept': 'application/vnd.live-component+html',
Expand Down
13 changes: 13 additions & 0 deletions src/LiveComponent/assets/test/controller/action.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ describe('LiveController Action Tests', () => {
data-action="live#action"
data-action-name="save"
>Save</button>

<button data-action="live#action" data-action-name="sendNamedArgs(a=1, b=2, c=3)">Send named args</button>
</div>
`;

Expand Down Expand Up @@ -64,4 +66,15 @@ describe('LiveController Action Tests', () => {

expect(postMock.lastOptions().body.get('comments')).toEqual('hi WEAVER');
});

it('Sends action named args', async () => {
const data = { comments: 'hi' };
const { element } = await startStimulus(template(data));

fetchMock.postOnce('http://localhost/_components/my_component/sendNamedArgs?values=a%3D1%26b%3D2%26c%3D3', {
html: template({ comments: 'hi' }),
});

getByText(element, 'Send named args').click();
});
});
46 changes: 46 additions & 0 deletions src/LiveComponent/src/Attribute/LiveArg.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\LiveComponent\Attribute;

/**
* @author Tomas Norkūnas <[email protected]>
*
* @experimental
*/
#[\Attribute(\Attribute::TARGET_PARAMETER)]
final class LiveArg
{
public function __construct(public ?string $name = null)
{
}

/**
* @return array<string, string>
*/
public static function liveArgs(object $component, string $action): array
{
$method = new \ReflectionMethod($component, $action);
$liveArgs = [];

foreach ($method->getParameters() as $parameter) {
foreach ($parameter->getAttributes(self::class) as $liveArg) {
/** @var LiveArg $attr */
$attr = $liveArg->newInstance();
$parameterName = $parameter->getName();

$liveArgs[$parameterName] = $attr->name ?? $parameterName;
}
}

return $liveArgs;
}
}
17 changes: 14 additions & 3 deletions src/LiveComponent/src/EventListener/LiveComponentSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\LiveComponentHydrator;
use Symfony\UX\TwigComponent\ComponentFactory;
use Symfony\UX\TwigComponent\ComponentRenderer;
Expand Down Expand Up @@ -137,11 +138,21 @@ public function onKernelController(ControllerEvent $event): void

$this->container->get(LiveComponentHydrator::class)->hydrate($component, $data);

$request->attributes->set('_component', $component);

if (!\is_string($queryString = $request->query->get('args'))) {
return;
}

// extra variables to be made available to the controller
// (for "actions" only)
parse_str($request->query->get('values'), $values);
$request->attributes->add($values);
$request->attributes->set('_component', $component);
parse_str($queryString, $args);

foreach (LiveArg::liveArgs($component, $action) as $parameter => $arg) {
if (isset($args[$arg])) {
$request->attributes->set($parameter, $args[$arg]);
}
}
}

public function onKernelView(ViewEvent $event): void
Expand Down
32 changes: 32 additions & 0 deletions src/LiveComponent/src/Resources/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,38 @@ This means that, for example, you can use action autowiring::
// ...
}

Actions & Arguments
^^^^^^^^^^^^^^^^^^^

You can also provide custom arguments to your action::

.. code-block:: twig
<form>
<button data-action="live#action" data-action-name="addItem(id={{ item.id }}, name=CustomItem)">Add Item</button>
</form>

In component for custom arguments to be injected we need to use `#[LiveArg()]` attribute, otherwise it would be
ignored. Optionally you can provide `name` argument like: `[#LiveArg('itemName')]` so it will use custom name from
args but inject to your defined parameter with another name.::

// src/Components/ItemComponent.php
namespace App\Components;

// ...
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Psr\Log\LoggerInterface;

class ItemComponent
{
// ...
#[LiveAction]
public function addItem(#[LiveArg] int $id, #[LiveArg('itemName')] string $name)
{
$this->id = $id;
$this->name = $name;
}
}

Actions and CSRF Protection
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Expand Down
51 changes: 51 additions & 0 deletions src/LiveComponent/tests/Fixture/Component/Component6.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\LiveComponent\Tests\Fixture\Component;

use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

/**
* @author Tomas Norkūnas <[email protected]>
*/
#[AsLiveComponent('component6')]
class Component6
{
use DefaultActionTrait;

#[LiveProp]
public bool $called = false;

#[LiveProp]
public $arg1;

#[LiveProp]
public $arg2;

#[LiveProp]
public $arg3;

#[LiveAction]
public function inject(
#[LiveArg] string $arg1,
#[LiveArg] int $arg2,
#[LiveArg('custom')] float $arg3,
) {
$this->called = true;
$this->arg1 = $arg1;
$this->arg2 = $arg2;
$this->arg3 = $arg3;
}
}
3 changes: 3 additions & 0 deletions src/LiveComponent/tests/Fixture/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component1;
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component2;
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component3;
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component6;
use Symfony\UX\TwigComponent\TwigComponentBundle;
use Twig\Environment;

Expand Down Expand Up @@ -65,12 +66,14 @@ protected function configureContainer(ContainerBuilder $c, LoaderInterface $load
$componentA = $c->register(Component1::class)->setAutoconfigured(true)->setAutowired(true);
$componentB = $c->register(Component2::class)->setAutoconfigured(true)->setAutowired(true);
$componentC = $c->register(Component3::class)->setAutoconfigured(true)->setAutowired(true);
$componentF = $c->register(Component6::class)->setAutoconfigured(true)->setAutowired(true);

if (self::VERSION_ID < 50300) {
// add tag manually
$componentA->addTag('twig.component', ['key' => 'component1'])->addTag('controller.service_arguments');
$componentB->addTag('twig.component', ['key' => 'component2', 'default_action' => 'defaultAction'])->addTag('controller.service_arguments');
$componentC->addTag('twig.component', ['key' => 'component3'])->addTag('controller.service_arguments');
$componentF->addTag('twig.component', ['key' => 'component6'])->addTag('controller.service_arguments');
}

$sessionConfig = self::VERSION_ID < 50300 ? ['storage_id' => 'session.storage.mock_file'] : ['storage_factory_id' => 'session.storage.factory.mock_file'];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<div
{{ init_live_component(this) }}
>
Arg1: {{ this.called ? this.arg1 : 'not provided' }}
Arg2: {{ this.called ? this.arg2 : 'not provided' }}
Arg3: {{ this.called ? this.arg3 : 'not provided' }}
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\UX\LiveComponent\Tests\ContainerBC;
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component1;
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component2;
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component6;
use Symfony\UX\LiveComponent\Tests\Fixture\Entity\Entity1;
use Symfony\UX\TwigComponent\ComponentFactory;
use Zenstruck\Browser\Response\HtmlResponse;
Expand Down Expand Up @@ -215,4 +216,45 @@ public function testCanRedirectFromComponentAction(): void
->assertHeaderEquals('Location', '/')
;
}

public function testInjectsLiveArgs(): void
{
/** @var LiveComponentHydrator $hydrator */
$hydrator = self::getContainer()->get('ux.live_component.component_hydrator');

/** @var ComponentFactory $factory */
$factory = self::getContainer()->get('ux.twig_component.component_factory');

/** @var Component6 $component */
$component = $factory->create('component6');

$dehydrated = $hydrator->dehydrate($component);
$token = null;

$dehydratedWithArgs = array_merge($dehydrated, [
'args' => http_build_query(['arg1' => 'hello', 'arg2' => 666, 'custom' => '33.3']),
]);

$this->browser()
->throwExceptions()
->get('/_components/component6?'.http_build_query($dehydrated))
->assertSuccessful()
->assertHeaderContains('Content-Type', 'html')
->assertContains('Arg1: not provided')
->assertContains('Arg2: not provided')
->assertContains('Arg3: not provided')
->use(function (HtmlResponse $response) use (&$token) {
// get a valid token to use for actions
$token = $response->crawler()->filter('div')->first()->attr('data-live-csrf-value');
})
->post('/_components/component6/inject?'.http_build_query($dehydratedWithArgs), [
'headers' => ['X-CSRF-TOKEN' => $token],
])
->assertSuccessful()
->assertHeaderContains('Content-Type', 'html')
->assertContains('Arg1: hello')
->assertContains('Arg2: 666')
->assertContains('Arg3: 33.3')
;
}
}