Repository navigation
Conversation
📊 Packages dist files size differenceThanks for the PR! Here is the difference in size of the packages dist files between the base branch and the PR.
|
||||||||||||
There was a problem hiding this comment.
Cool!
Question: is there an easy way, in your live action, to check if the request was a normal live component call or from custom js? Does that make sense? If custom js, return data, otherwise, do the normal thing. If I understand correctly, the normal thing always happens.
c454a65 to
38a137e
Compare
38a137e to
fddc11f
Compare
smnandre
left a comment
There was a problem hiding this comment.
(if you guys were waiting for me, I'm sorry)
This is such a great PR, @Pechynho! I remember first time you mentioned that idea/need, and I'm very happy to see it implemented that clean-ly :)
🤝
Let's rebase/add changelog (3.9) and ... LGTM 😃
fddc11f to
7a21fc0
Compare
…pt that called an action
| Q | A
| -------------- | ---
| Bug fix? | no
| New feature? | yes
| Deprecations? | no
| Documentation? | yes
| Issues |
| License | MIT
Calling a LiveAction from your own JavaScript with `component.action()` is documented and useful. But the action has no clean way to send a result back to the code that called it. Some examples where this is needed:
- a JavaScript widget (an autocomplete, a map, a chart) asks the component for data;
- an action saves something and the JavaScript needs the new id or a message;
- an action checks something (is this name free?) and the JavaScript shows the answer.
The component already has everything the action needs: its props, its entities, its form. Today the options are:
- **Return a `JsonResponse`:** the client does not see a component response, so it shows the error modal. The component does not re-render, so every `LiveProp` the action changed is lost.
- **Use `dispatchBrowserEvent()`:** it works, but it is a page-wide event, not the answer to the call you awaited. You have to add a listener before the call and remove it after. The data must be JSON, and it is written into an HTML attribute of the render.
This PR adds `LiveResponse::data()`. It works like the `LiveResponse` helpers added in 3.5: the data is sent **with** the render, not instead of it. So the component re-renders as usual, and the changes of the action are kept.
```php
public function search(ProductRepository $repository, #[LiveArg] string $query): LiveResponse
{
$this->query = $query; // still re-rendered on the page
return LiveResponse::data(['total' => $repository->countMatching($query)]);
}
```
```js
const response = await component.action('search', { query: 'lamp' });
const data = await response.getData()?.json();
```
- Arrays, scalars, `null` and `\JsonSerializable` objects are sent as JSON, with the same encoding as `JsonResponse`.
- A string is sent as is, with the content type you give, so any format works: `LiveResponse::data($xml, 'application/xml')`.
- `getData()` returns a standard `Response`, so the data is read with `json()`, `text()`, `blob()` or `arrayBuffer()`. It returns `null` when the action sent no data.
- It uses the same transport as `LiveResponse::downloadFile()`: the data comes after the HTML in the same body, and `X-Live-Html-Length` gives the split. A new `X-Live-Data-Type` header gives its content type.
- The same rules apply as for the other `LiveResponse` helpers: POST only, never from the default action, and the last one wins in a batch.
The public API grows by one static method in PHP and one method in JavaScript.
Similar tools already offer this:
- **Livewire (Laravel):** calling an action from JavaScript, for example `await $wire.getPostCount()`, returns the value that the PHP method returned. The component re-renders as usual (unless the action is marked `#[Renderless]`).
- **Phoenix LiveView:** `pushEvent(event, payload, (reply) => ...)` receives the map returned by `{:reply, map, socket}` from the server, and the view is updated in the same round trip.
This PR brings the same idea to LiveComponent, in the style of the existing `LiveResponse` helpers.
The new tests fail without the change: `LiveResponse::data()` does not exist, the `X-Live-Data-Type` header is missing, and `getData()` is not a function. The PHP and JavaScript test suites pass, and the documentation has a new "Sending Data to JavaScript" section next to the download responses.
7a21fc0 to
1c363cb
Compare
Calling a LiveAction from your own JavaScript with
component.action()is documented and useful. But the action has no clean way to send a result back to the code that called it. Some examples where this is needed:The component already has everything the action needs: its props, its entities, its form. Today the options are:
JsonResponse: the client does not see a component response, so it shows the error modal. The component does not re-render, so everyLivePropthe action changed is lost.dispatchBrowserEvent(): it works, but it is a page-wide event, not the answer to the call you awaited. You have to add a listener before the call and remove it after. The data must be JSON, and it is written into an HTML attribute of the render.This PR adds
LiveResponse::data(). It works like theLiveResponsehelpers added in 3.5: the data is sent with the render, not instead of it. So the component re-renders as usual, and the changes of the action are kept.nulland\JsonSerializableobjects are sent as JSON, with the same encoding asJsonResponse.LiveResponse::data($xml, 'application/xml').getData()returns a standardResponse, so the data is read withjson(),text(),blob()orarrayBuffer(). It returnsnullwhen the action sent no data.LiveResponse::downloadFile(): the data comes after the HTML in the same body, andX-Live-Html-Lengthgives the split. A newX-Live-Data-Typeheader gives its content type.LiveResponsehelpers: POST only, never from the default action, and the last one wins in a batch.The public API grows by one static method in PHP and one method in JavaScript.
Similar tools already offer this:
await $wire.getPostCount(), returns the value that the PHP method returned. The component re-renders as usual (unless the action is marked#[Renderless]).pushEvent(event, payload, (reply) => ...)receives the map returned by{:reply, map, socket}from the server, and the view is updated in the same round trip.This PR brings the same idea to LiveComponent, in the style of the existing
LiveResponsehelpers.#2967 asks for the same use case, by skipping the render when an action returns JSON. In the discussion there, the lost render was a concern, and
LiveResponsehelpers were suggested for this kind of feature. This PR follows that direction, and covers any format, not only JSON.The new tests fail without the change:
LiveResponse::data()does not exist, theX-Live-Data-Typeheader is missing, andgetData()is not a function. The PHP and JavaScript test suites pass, and the documentation has a new "Sending Data to JavaScript" section next to the download responses.