Skip to content
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

Allow Svelte 5 render slots as snippets #9285

Merged
merged 2 commits into from
Dec 7, 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
5 changes: 5 additions & 0 deletions .changeset/big-shirts-travel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/svelte': patch
---

When using Svelte 5, slots can now be rendered as snippets
7 changes: 6 additions & 1 deletion packages/integrations/svelte/client-v5.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { mount } from 'svelte';
import { add_snippet_symbol } from 'svelte/internal';

// Allow a slot to be rendered as a snippet (dev validation only)
const tagSlotAsSnippet = import.meta.env.DEV ? add_snippet_symbol : (s) => s;

export default (element) => {
return async (Component, props, slotted) => {
Expand Down Expand Up @@ -32,12 +36,13 @@ function createSlotDefinition(key, children) {
/**
* @param {Comment} $$anchor A comment node for slots in Svelte 5
*/
return ($$anchor, _$$slotProps) => {
const fn = ($$anchor, _$$slotProps) => {
const parent = $$anchor.parentNode;
const el = document.createElement('div');
el.innerHTML = `<astro-slot${
key === 'default' ? '' : ` name="${key}"`
}>${children}</astro-slot>`;
parent.insertBefore(el.children[0], $$anchor);
};
return tagSlotAsSnippet(fn);
}
8 changes: 6 additions & 2 deletions packages/integrations/svelte/server-v5.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { render } from 'svelte/server';
import { add_snippet_symbol } from 'svelte/internal';

// Allow a slot to be rendered as a snippet (dev validation only)
const tagSlotAsSnippet = import.meta.env.DEV ? add_snippet_symbol : (s) => s;

function check(Component) {
// Svelte 5 generated components always accept these two props
Expand All @@ -18,10 +22,10 @@ async function renderToStaticMarkup(Component, props, slotted, metadata) {
let $$slots = undefined;
for (const [key, value] of Object.entries(slotted)) {
if (key === 'default') {
children = () => `<${tagName}>${value}</${tagName}>`;
children = tagSlotAsSnippet(() => `<${tagName}>${value}</${tagName}>`);
} else {
$$slots ??= {};
$$slots[key] = () => `<${tagName} name="${key}">${value}</${tagName}>`;
$$slots[key] = tagSlotAsSnippet(() => `<${tagName} name="${key}">${value}</${tagName}>`);
}
}

Expand Down
Loading