Skip to content

[LiveComponent] Support JSONResponse for LiveActions #2967

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

Open
wants to merge 5 commits into
base: 2.x
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions src/LiveComponent/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

## 2.29.0

- Added `JSONResponse` support (LiveAction functions) in LiveComponent.

## 2.28.0

- Add new modifiers for input validations, useful to prevent unnecessary HTTP requests:
Expand Down
7 changes: 7 additions & 0 deletions src/LiveComponent/assets/dist/live_controller.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ declare class export_default$2{
constructor(response: Response);
getBody(): Promise<string>;
getLiveUrl(): string | null;
checkResponseType(): Promise<{
type: 'json' | 'html' | 'invalid';
body: string;
}>;
}

declare class export_default$1{
Expand Down Expand Up @@ -81,6 +85,9 @@ type ComponentHooks = {
connect: (component: Component) => MaybePromise;
disconnect: (component: Component) => MaybePromise;
'request:started': (requestConfig: any) => MaybePromise;
'render:started': (backendResponseBody: string, backendResponse: export_default$2, controls: {
shouldRender: boolean;
}) => MaybePromise;
'render:finished': (component: Component) => MaybePromise;
'response:error': (backendResponse: export_default$2, controls: {
displayError: boolean;
Expand Down
47 changes: 37 additions & 10 deletions src/LiveComponent/assets/dist/live_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,24 @@ var BackendResponse_default = class {
}
return this.liveUrl;
}
async checkResponseType() {
const contentType = this.response.headers.get("Content-Type") || "";
const headers = this.response.headers;
const text = await this.getBody();
const trimmed = text.trim();
if (contentType.includes("application/json")) {
try {
JSON.parse(trimmed);
return { type: "json", body: trimmed };
} catch {
}
}
const isValidHtml = trimmed.length > 0 && (contentType.includes("application/vnd.live-component+html") || headers.get("X-Live-Redirect") !== null);
if (isValidHtml) {
return { type: "html", body: trimmed };
}
return { type: "invalid", body: trimmed };
}
};

// src/Util/getElementAsTagText.ts
Expand Down Expand Up @@ -2005,23 +2023,32 @@ var Component = class {
this.isRequestPending = false;
this.backendRequest.promise.then(async (response) => {
const backendResponse = new BackendResponse_default(response);
const html = await backendResponse.getBody();
const result = await backendResponse.checkResponseType();
if (result.type === "json") {
this.backendRequest = null;
thisPromiseResolve(backendResponse);
if (this.isRequestPending) {
this.isRequestPending = false;
this.performRequest();
}
return response;
}
for (const input of Object.values(this.pendingFiles)) {
input.value = "";
}
const headers = backendResponse.response.headers;
if (!headers.get("Content-Type")?.includes("application/vnd.live-component+html") && !headers.get("X-Live-Redirect")) {
const backendResponseBody = result.body;
if (result.type === "invalid") {
const controls = { displayError: true };
this.valueStore.pushPendingPropsBackToDirty();
this.hooks.triggerHook("response:error", backendResponse, controls);
if (controls.displayError) {
this.renderError(html);
this.renderError(backendResponseBody);
}
this.backendRequest = null;
thisPromiseResolve(backendResponse);
return response;
}
this.processRerender(html, backendResponse);
this.processRerender(backendResponseBody, backendResponse);
const liveUrl = backendResponse.getLiveUrl();
if (liveUrl) {
history.replaceState(
Expand All @@ -2039,9 +2066,9 @@ var Component = class {
return response;
});
}
processRerender(html, backendResponse) {
processRerender(backendResponseBody, backendResponse) {
const controls = { shouldRender: true };
this.hooks.triggerHook("render:started", html, backendResponse, controls);
this.hooks.triggerHook("render:started", backendResponseBody, backendResponse, controls);
if (!controls.shouldRender) {
return;
}
Expand All @@ -2060,7 +2087,7 @@ var Component = class {
});
let newElement;
try {
newElement = htmlToElement(html);
newElement = htmlToElement(backendResponseBody);
if (!newElement.matches("[data-controller~=live]")) {
throw new Error("A live component template must contain a single root controller element.");
}
Expand Down Expand Up @@ -2130,7 +2157,7 @@ var Component = class {
}, this.calculateDebounce(debounce));
}
// inspired by Livewire!
renderError(html) {
renderError(backendResponseBody) {
let modal = document.getElementById("live-component-error");
if (modal) {
modal.innerHTML = "";
Expand All @@ -2156,7 +2183,7 @@ var Component = class {
document.body.style.overflow = "hidden";
if (iframe.contentWindow) {
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.write(backendResponseBody);
iframe.contentWindow.document.close();
}
const closeModal = (modal2) => {
Expand Down
27 changes: 27 additions & 0 deletions src/LiveComponent/assets/src/Backend/BackendResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,31 @@ export default class {

return this.liveUrl;
}

async checkResponseType(): Promise<{ type: 'json' | 'html' | 'invalid'; body: string }> {
const contentType = this.response.headers.get('Content-Type') || '';
const headers = this.response.headers;

const text = await this.getBody();
const trimmed = text.trim();

if (contentType.includes('application/json')) {
try {
JSON.parse(trimmed);
return { type: 'json', body: trimmed };
} catch {
// not valid JSON
}
}

const isValidHtml =
trimmed.length > 0 &&
(contentType.includes('application/vnd.live-component+html') || headers.get('X-Live-Redirect') !== null);

if (isValidHtml) {
return { type: 'html', body: trimmed };
}

return { type: 'invalid', body: trimmed };
}
}
46 changes: 29 additions & 17 deletions src/LiveComponent/assets/src/Component/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ export type ComponentHooks = {
connect: (component: Component) => MaybePromise;
disconnect: (component: Component) => MaybePromise;
'request:started': (requestConfig: any) => MaybePromise;
'render:started': (
backendResponseBody: string,
backendResponse: BackendResponse,
controls: { shouldRender: boolean }
) => MaybePromise;
'render:finished': (component: Component) => MaybePromise;
'response:error': (backendResponse: BackendResponse, controls: { displayError: boolean }) => MaybePromise;
'loading.state:started': (element: HTMLElement, request: BackendRequest) => MaybePromise;
Expand Down Expand Up @@ -300,34 +305,43 @@ export default class Component {

this.backendRequest.promise.then(async (response) => {
const backendResponse = new BackendResponse(response);
const html = await backendResponse.getBody();
const result = await backendResponse.checkResponseType();

// clear sent files inputs
if (result.type === 'json') {
this.backendRequest = null;
thisPromiseResolve(backendResponse);

if (this.isRequestPending) {
this.isRequestPending = false;
this.performRequest();
}
return response;
}

// Clear all file inputs
for (const input of Object.values(this.pendingFiles)) {
input.value = '';
}

const backendResponseBody = result.body;

// if the response does not contain a component, render as an error
const headers = backendResponse.response.headers;
if (
!headers.get('Content-Type')?.includes('application/vnd.live-component+html') &&
!headers.get('X-Live-Redirect')
) {
if (result.type === 'invalid') {
const controls = { displayError: true };
this.valueStore.pushPendingPropsBackToDirty();
this.hooks.triggerHook('response:error', backendResponse, controls);

if (controls.displayError) {
this.renderError(html);
this.renderError(backendResponseBody);
}

this.backendRequest = null;
thisPromiseResolve(backendResponse);

return response;
}

this.processRerender(html, backendResponse);
// HTML processing
this.processRerender(backendResponseBody, backendResponse);
const liveUrl = backendResponse.getLiveUrl();
if (liveUrl) {
history.replaceState(
Expand All @@ -337,11 +351,9 @@ export default class Component {
);
}

// finally resolve this promise
this.backendRequest = null;
thisPromiseResolve(backendResponse);

// do we already have another request pending?
if (this.isRequestPending) {
this.isRequestPending = false;
this.performRequest();
Expand All @@ -351,9 +363,9 @@ export default class Component {
});
}

private processRerender(html: string, backendResponse: BackendResponse) {
private processRerender(backendResponseBody: string, backendResponse: BackendResponse) {
const controls = { shouldRender: true };
this.hooks.triggerHook('render:started', html, backendResponse, controls);
this.hooks.triggerHook('render:started', backendResponseBody, backendResponse, controls);
// used to notify that the component doesn't live on the page anymore
if (!controls.shouldRender) {
return;
Expand Down Expand Up @@ -387,7 +399,7 @@ export default class Component {

let newElement: HTMLElement;
try {
newElement = htmlToElement(html);
newElement = htmlToElement(backendResponseBody);

if (!newElement.matches('[data-controller~=live]')) {
throw new Error('A live component template must contain a single root controller element.');
Expand Down Expand Up @@ -477,7 +489,7 @@ export default class Component {
}

// inspired by Livewire!
private renderError(html: string): void {
private renderError(backendResponseBody: string): void {
let modal = document.getElementById('live-component-error');
if (modal) {
modal.innerHTML = '';
Expand Down Expand Up @@ -505,7 +517,7 @@ export default class Component {
document.body.style.overflow = 'hidden';
if (iframe.contentWindow) {
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.write(backendResponseBody);
iframe.contentWindow.document.close();
}

Expand Down
Loading
Loading