Open katriellucas opened 8 months ago
You can already trim this down by using children
:
But nevertheless an argument could be made for a snippet.bind()
function.
You can already trim this down by using
children
:But nevertheless an argument could be made for a
snippet.bind()
function.
That is correct for when you have only one children, what if you have two and need the label to be between then? What if you need three? A Card component that uses header()
, body()
and footer()
, we might be able to take out body()
with children
but any styling or elements in between might make the other two cumbersome.
What people have wanted elsewhere is the ability to decorate components. This feels like a use case for decorating snippets, i.e. take an existing snippet and return an augmented snippet. Maybe something like this (and similar for components).
<script>
import { decorateSnippet } from 'svelte';
const decorated_foo = decorateSnippet(
foo,
(snippet /* the original snippet */, args /* the arguments passed to the snippet */) =>
snippet('my own argument; ignoring the args')
);
</script>
{#snippet foo(prop)}
..
{/snippet}
<Component foo={} />
That seems unnecessarily verbose for simple cases.
I like @Prinzhorn's suggestion of having a bind
function.
<Chip label="Test" media={icon.bind('blue')} />
Could be called something else, but given that snippets are declared like other functions, this would logically match (even if the generated arguments work differently); Svelte would need to override the existing bind
- not sure if that causes trouble - or declare a separate function.
To add to the discussion, here is another powerful pattern (in my opinion) that would be possible with Snippet parameter/bindings:
This case is even worse because I can't even use the nested children
, it's specially bad if I have different components in the same stack, (sometimes this might be beneficial, like showing a modal on top of a fullscreen one) due to how and where the {@render}
functions might be inside of each component.
PS: I'm not sure if I should have created a new issue for this, if so, please tell me.
What's wrong with this?
<script>
let { label, snippet, data } = $props()
</script>
<div class="chip">
{@render snippet(data)}
{label}
</div>
<Chip label="Test" />
<Chip label="Blue" snippet={icon} data="blue" />
<Chip label="Red" snippet={icon} />
<Chip label="Svelte" snippet={profile} />
<Chip label="Vue" snippet={profile} data="https://upload.wikimedia.org/wikipedia/commons/9/95/Vue.js_Logo_2.svg" />
I would find a bind
function for snippets extremely useful.
It makes programmatic usage of snippets a lot more flexible/easy (I did not find a way to do this in userland so far).
Example: REPL
Right now this is needlessly complicated; at multiple levels the APIs need to be aware of snippet args. Of course one could create new components, but then we are back to Svelte 4 levels of overhead for what could be a very simple thing.
snippet.bind
would have on example aboveI'm going to need a more convincing example I'm afraid — perhaps I'm being dense, but why wouldn't you just write Dialog.svelte
like this?
-<svelte:options accessors />
<script context="module">
import { mount, unmount } from 'svelte';
- import { mountSnippet } from './MountSnippet.svelte';
import Dialog from './Dialog.svelte';
export function showModal(snippet, args) {
return new Promise(resolve => {
const dialog = mount(Dialog, {
target: document.body,
props: {
+ snippet,
+ args,
onclose(e) {
resolve(e.target.returnValue);
unmount(dialog);
}
}
});
- mountSnippet(dialog.ref, snippet, args); // hacky
- dialog.ref.showModal();
});
}
</script>
<script>
- let { ref, children, ...rest } = $props();
+ let { snippet, args, onclose } = $props();
+ function show(node) {
+ node.showModal();
+ }
</script>
-<dialog bind:this={ref} {...rest}>
- {@render children()}
+<dialog use:show {onclose}>
+ {@render snippet(args)}
</dialog>
If you needed to also do <Dialog>...</Dialog>
in places (and expose an API like export function showModal
or whatever), then that's also very easy to do.
Adding things like snippet.bind(...)
pushes us into uncanny valley territory — it really implies that snippet
is Just A Function. If we're going to do that, then we should consider whether we want a true programmatic API for snippets...
mount(App, {
target,
props: {
mySnippet: (firstname, lastname) {
const element = document.createElement('h1');
$effect.pre(() => {
element.textContent = `Hello ${firstname()} ${lastname()}!`;
});
return element;
}
}
});
...and what challenges that would entail. (At the very least, we'd have to find a different solution to #10800.)
why wouldn't you just write Dialog.svelte like this?
It comes down to the points I listed at the start of my comment. You have to design components around this specific use, which is just not good.
Dialog
itself should not need to care about anything except that it can receive children
.
Imagine it's a component from a library and I want to write a separate showModal
utility function on my side (REPL where it's split).
If you fear that the name could lead to confusion, a separate function could be used or a different name. E.g.
snippet.withArgs(...args)
bindSnippet(snippet, ...args) // separate => not quite a "regular" bind
Imagine it's a component from a library and I want to write a separate
showModal
utility function on my side
You'll always need cooperation from the underlying <Dialog>
component because you need either a reference to the element (so you can call element.showModal()
) or an API for that use case, like a modal
prop or an exported function. But assuming you have that, you can do this, which seems... fine? Maybe a new API would make that very slightly more convenient, but the bar for new API is very high.
It occurs to me that the Just A Function approach I sketched above doesn't really work, because of SSR.
you can do this, which seems... fine?
That still adds a lot of overhead and boilerplate.
To use it, the snippet can only have one argument.
If you have an existing snippet that has multiple arguments, the snippet has to be changed to make it conform to this.
It's really not great. Snippets being so much of a black box really limits their usefulness in code as soon as arguments are involved. I see a lot of unused potential here when it comes to more dynamic UI composition.
It occurs to me that the Just A Function approach I sketched above doesn't really work, because of SSR.
A utility function that just converts DOM elements/function returning DOM elements to a snippet could be useful. Though that can be somewhat worked around in userland code.
why wouldn't you just write Dialog.svelte like this?
It comes down to the points I listed at the start of my comment. You have to design components around this specific use, which is just not good.
Dialog
itself should not need to care about anything except that it can receivechildren
. Imagine it's a component from a library and I want to write a separateshowModal
utility function on my side (REPL where it's split).If you fear that the name could lead to confusion, a separate function could be used or a different name. E.g.
snippet.withArgs(...args) bindSnippet(snippet, ...args) // separate => not quite a "regular" bind
I am for something like this. The alternative will be users realizing that when they change their snippet to take arguments, they can no longer simply pass it as an attribute, and will have to move it to a full {#snippet } block just to pass their args:
<AppBar leading={mySnippet} />
"woops i'd like an arg"
<AppBar>
{#snippet leading()}
{@render mySnippet({newArg: "hello"})
{/snippet}
</AppBar>
vs
<AppBar leading={mySnippet.with({newArg: "hello"})} />
Btw, since #12507 (svelte@5.0.0-next.196) snippets aren't signed anymore and you can try to pass any function as a snippet (though you still can get a typing error in TS).
Parameters are getters, so it will look like
<Chip label="Red" media={(anchor) => icon(anchor, () => 'blue')}/>
Btw, since #12507 (svelte@5.0.0-next.196) snippets aren't signed anymore and you can try to pass any function as a snippet (though you still can get a typing error in TS).
Parameters are getters, so it will look like
<Chip label="Red" media={(anchor) => icon(anchor () => 'blue')}/>
Super interesting. This works, but now I can see it "pop in" after the initial render, while the ones using the full {#snippet } block are rendered and ready to go.
Hello,
Btw, since #12507 (svelte@5.0.0-next.196) snippets aren't signed anymore and you can try to pass any function as a snippet (though you still can get a typing error in TS).
Based on that, it's possible to make a function to wrap the boilerplate :
function snip(fn, ...args) {
return (node) => {
fn(node, ...args.map(a => ()=>a ));
}
}
-<Chip label="Red" media={(node) => icon(node, () => 'blue')}/>
+<Chip label="Red" media={snip(icon, 'blue')}/>
I would say that a userland solution like this is only acceptable if we can get guarantees on the snippet types.
Otherwise this is the equivalent of building on top of what used to be svelte/internal
which is not intended and can break at any point.
A first step would probably be that the Snippet
type does not lie about the actual shape of the function.
Also, SSR/CSR complicate things — the functions behave slightly differently in each environment.
Hey, i wanted show what this problem leads me to do.
I want to show this case to underline the usefulness having a feature solving this issue could/would bring.
I have a TabBar
that switches the content of the view above it. I support desktop and mobile, and some of the tabs can be shown in a Sidebar
or the Main
view. These differentiations require me to define many snippet
s to work.
<!-- General Shape of a TabBar Item (button in the TabBar) -->
{#snippet item(item: TabItem, selected: boolean, select: SelectTab)}
<button
class="{selected ? 'text-blue' : 'text-step-700'}
{LAYOUT.platform === 'desktop' ? 'min-w-[5.5rem]' : 'flex-1'}"
onclick={select}
>
<Icon data={item.icon} />
<p>{item.title}</p>
</button>
{/snippet}
<!-- Here I have to define the snippets of the tabs, because of the problem this issue discusses -->
{#snippet itemGroup(selected: boolean, select: SelectTab)}
{@render item(
{
title: "Group",
icon: people_fill,
},
selected,
select,
)}
{/snippet}
<!-- Here I have to create versions of the same snippet, because again, we cannot bind parameters to snippets in code -->
{#snippet viewGroup_Sidebar()}
<GroupTab {group} safearea={safeareaSidebar} />
{/snippet}
{#snippet viewGroup_Main()}
<GroupTab {group} safearea={safeareaMain} />
{/snippet}
<!-- Now imagine that I have 5+ different tabs, not only "Group"... -->
As one can see, this creates VERY redundant code/definitions, and gets out of hand rather quickly.
If LAYOUT.platform
was not "global", but could differ in different parts of the application, then I would need to create EVEN MORE snippets to account for this, such as for the difference in Sidebar
and Main
.
I would like to add another feature that would make things easier.
It would be great to not only allow users to use "prepopulated" snippets in-place, but also allow the same for components.
<script lang="ts">
import Text from "./Text.svelte"
import Child from "./Child.svelte"
</script>
{#snippet text(a: string)}
<p>{a}</p>
{/snippet}
<Child snippet={text("text")} />
<Child snippet={Text({a: "text"})} />
<!-- syntax for this is up for debate -->
I believe this would greatly improve Svelte's composability.
Describe the problem
As of now, if we want to pass a
Snippet
as props to a component, it has to be without parameters, this is due to theSnippet
props expecting a snippet function to be passed. if we want parameters on ourSnippet
function, it needs be nested inside the component as a child.This process can get boring and boilerplatey very quickly, specially with more complex cases were different kinds of
Snippets
are used inside components.Describe the proposed solution
Solution 1
It would be nice if Svelte let us pass parameters directly as props, using the example above, maybe:
or
or even
Personally, Option 2 feels more natural as this is how we already pass functions on Svelte 5 using events such as
onclick
.Solution 2
Some kind of new sintax for such cases might be interesting to think about.
Solution 3
Do nothing. There is an argument on using
{#each}
loops but it feels somewhat overkill for 3 or 4 components.Importance
would make my life easier