Skip to content

[LiveComponent] Fix morphing issues with an Alpine.js component, close #984 #1126

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
Sep 22, 2023
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
9 changes: 9 additions & 0 deletions src/LiveComponent/assets/dist/live_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -1216,6 +1216,15 @@ function executeMorphdom(rootFromElement, rootToElement, modifiedFieldElements,
return true;
}
if (fromEl instanceof HTMLElement && toEl instanceof HTMLElement) {
if (typeof fromEl.__x !== 'undefined') {
if (!window.Alpine) {
throw new Error('Unable to access Alpine.js though the global window.Alpine variable. Please make sure Alpine.js is loaded before Symfony UX LiveComponent.');
}
if (typeof window.Alpine.morph !== 'function') {
throw new Error('Unable to access Alpine.js morph function. Please make sure the Alpine.js Morph plugin is installed and loaded, see https://alpinejs.dev/plugins/morph for more information.');
}
window.Alpine.morph(fromEl.__x, toEl);
}
if (childComponentMap.has(fromEl)) {
const childComponent = childComponentMap.get(fromEl);
childComponent.updateFromNewElementFromParentRender(toEl);
Expand Down
19 changes: 19 additions & 0 deletions src/LiveComponent/assets/src/morphdom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,25 @@ export function executeMorphdom(

// skip special checking if this is, for example, an SVG
if (fromEl instanceof HTMLElement && toEl instanceof HTMLElement) {
// We assume fromEl is an Alpine component if it has `__x` property.
// If it's the case, then we should morph `fromEl` to `ToEl` (thanks to https://alpinejs.dev/plugins/morph)
// in order to keep the component state and UI in sync.
if (typeof fromEl.__x !== 'undefined') {
if (!window.Alpine) {
throw new Error(
'Unable to access Alpine.js though the global window.Alpine variable. Please make sure Alpine.js is loaded before Symfony UX LiveComponent.'
);
}

if (typeof window.Alpine.morph !== 'function') {
throw new Error(
'Unable to access Alpine.js morph function. Please make sure the Alpine.js Morph plugin is installed and loaded, see https://alpinejs.dev/plugins/morph for more information.'
);
}

window.Alpine.morph(fromEl.__x, toEl);
}

if (childComponentMap.has(fromEl)) {
const childComponent = childComponentMap.get(fromEl) as Component;

Expand Down