Skip to content

Commit

Permalink
Add support for Svelte 5 @render syntax (#12390)
Browse files Browse the repository at this point in the history
Co-authored-by: Jonas Robertsson <[email protected]>
  • Loading branch information
bluwy and Robertsson authored Nov 6, 2024
1 parent b7e4691 commit 6fd3d59
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/shaggy-kids-juggle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/svelte': patch
---

Adds support for Svelte 5's new `@render` syntax while maintaining backward compatibility with traditional slots.
16 changes: 16 additions & 0 deletions packages/integrations/svelte/client-v5.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ export default (element) => {

let children = undefined;
let $$slots = undefined;
let renderFns = {};


for (const [key, value] of Object.entries(slotted)) {
// Legacy slot support
$$slots ??= {};
if (key === 'default') {
$$slots.default = true;
Expand All @@ -20,6 +24,16 @@ export default (element) => {
render: () => `<astro-slot name="${key}">${value}</astro-slot>`,
}));
}
// @render support for Svelte ^5.0
if (key === 'default') {
renderFns.children = createRawSnippet(() => ({
render: () => `<astro-slot>${value}</astro-slot>`
}));
} else {
renderFns[key] = createRawSnippet(() => ({
render: () => `<astro-slot name="${key}">${value}</astro-slot>`
}));
}
}

const bootstrap = client !== 'only' ? hydrate : mount;
Expand All @@ -28,6 +42,7 @@ export default (element) => {
...props,
children,
$$slots,
...renderFns
});
} else {
const component = bootstrap(Component, {
Expand All @@ -36,6 +51,7 @@ export default (element) => {
...props,
children,
$$slots,
...renderFns
},
});
existingApplications.set(element, component);
Expand Down
9 changes: 9 additions & 0 deletions packages/integrations/svelte/server-v5.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ async function renderToStaticMarkup(Component, props, slotted, metadata) {

let children = undefined;
let $$slots = undefined;
const renderProps = {};

for (const [key, value] of Object.entries(slotted)) {
// Legacy slot support
$$slots ??= {};
if (key === 'default') {
$$slots.default = true;
Expand All @@ -29,13 +32,19 @@ async function renderToStaticMarkup(Component, props, slotted, metadata) {
render: () => `<${tagName} name="${key}">${value}</${tagName}>`,
}));
}
// @render support for Svelte ^5.0
const slotName = key === 'default' ? 'children' : key;
renderProps[slotName] = createRawSnippet(() => ({
render: () => `<${tagName}${key !== 'default' ? ` name="${key}"` : ''}>${value}</${tagName}>`
}));
}

const result = render(Component, {
props: {
...props,
children,
$$slots,
...renderProps
},
});
return { html: result.body };
Expand Down

0 comments on commit 6fd3d59

Please sign in to comment.