sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
78.56k stars 4.12k forks source link

Svelte 5: Avoiding `{#snippet}` boilerplate with the ability to pass parameters #10678

Open katriellucas opened 7 months ago

katriellucas commented 7 months ago

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 the Snippet props expecting a snippet function to be passed. if we want parameters on our Snippet 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:

// Option 1
<Chip label="Test" media={icon('blue')} />

or

// Option 2
<Chip label="Test" media={() => icon('blue')} />

or even

// Option 3
<Chip label="Test" media={(() => icon('blue'))()} />

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.

<Chip label="Blue">
  {@render icon('blue') on media} // where Chip must have a "media" prop, show an error if doesn't
</Chip>

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

Prinzhorn commented 7 months ago

You can already trim this down by using children:

https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAA7WVYW_bNhCG_8pVLWAbsE0nxYpWs4O1-zRgn7ah-1AVBS3S0tUUSZBUFEPwf9-RspM48QJ3wADD1onvezw-pI99tkElfZZ_6TPNG5nl2Udrs2kWdjYG_laqICn2pnVlfLP0pUMbbgoNgI01LsCvNVrYONPAaM5iMB9so0Iv2b280P1rr9FaGQBLo8elUcbBCorMSVFkkz1pwtLfVnCLsvtk7lZFtoAFXL2jT5HBXaO0p3d1CDZnrOu6efd2blzFrheLBSMjiToUoSZRdMRJA8CyRFcqCWVM-J405e7w4A6_xECt-lTPniXXMqajp54dSt6fLsA6E8GNW6fSCmJNnopqrTJczDvcYiMF8lRejGyMWGmaxmjPrtjVmv2ZIH373VRmnoo_EMCmAu_KVU_J9ycLglpiVYdjxFV8tBtbZOxZrctXsxkwBn_XPMBvEGrUW8Aw8oBCcpXDeN0GEEZ6PQrQGbedJFvaTMXXUlHuv6QPNFHMfjrwSbWSBtIaV33azsn-ueyPuLEnqtGanKNz2gHHg_yI-Jz2c3tGOPrBTfjAPvzEKNP8u0-b8O06bsOhttns5jHFj1Sa0zwgFbmbwvfWB1C4lVCbDobTDpZ7D5tWlwEpff6faY4nsLqBy5g-0l5OdjBdzPdU_n9STme1k6ClFBAMnU76FnxHh3WLWnBYczGBo-nf2J6nm_7W_S9OaiHdKbHYpqLjjDfBPmN90XTkfep74P2C9fPzUo--H24y58kPbeZxAT7slExz0vAUYvvpY1QEgd6qiB-1Qi1nGyXvfh6GGu4q1DMX-1EO7-3wPmUe8tGd0RiBG5Qiy4Nr5X56f8XEuS-9YxR1237gM4WyRiWIC-yp674hMtaPJ09umaXAWygV_RmJJxnsU6DHJOOh3_Ypd6qcnE-RzGOGIw-usNIzDLLxOZRSU0844FgbR6lz8EahgCt7B5Xju5PBmeMCW_8A60W-Q6fP4e31vdpyIVBXOV2JF_H-uv8HWgimot4HAAA=

But nevertheless an argument could be made for a snippet.bind() function.

katriellucas commented 7 months ago

You can already trim this down by using children:

https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAA7WVYW_bNhCG_8pVLWAbsE0nxYpWs4O1-zRgn7ah-1AVBS3S0tUUSZBUFEPwf9-RspM48QJ3wADD1onvezw-pI99tkElfZZ_6TPNG5nl2Udrs2kWdjYG_laqICn2pnVlfLP0pUMbbgoNgI01LsCvNVrYONPAaM5iMB9so0Iv2b280P1rr9FaGQBLo8elUcbBCorMSVFkkz1pwtLfVnCLsvtk7lZFtoAFXL2jT5HBXaO0p3d1CDZnrOu6efd2blzFrheLBSMjiToUoSZRdMRJA8CyRFcqCWVM-J405e7w4A6_xECt-lTPniXXMqajp54dSt6fLsA6E8GNW6fSCmJNnopqrTJczDvcYiMF8lRejGyMWGmaxmjPrtjVmv2ZIH373VRmnoo_EMCmAu_KVU_J9ycLglpiVYdjxFV8tBtbZOxZrctXsxkwBn_XPMBvEGrUW8Aw8oBCcpXDeN0GEEZ6PQrQGbedJFvaTMXXUlHuv6QPNFHMfjrwSbWSBtIaV33azsn-ueyPuLEnqtGanKNz2gHHg_yI-Jz2c3tGOPrBTfjAPvzEKNP8u0-b8O06bsOhttns5jHFj1Sa0zwgFbmbwvfWB1C4lVCbDobTDpZ7D5tWlwEpff6faY4nsLqBy5g-0l5OdjBdzPdU_n9STme1k6ClFBAMnU76FnxHh3WLWnBYczGBo-nf2J6nm_7W_S9OaiHdKbHYpqLjjDfBPmN90XTkfep74P2C9fPzUo--H24y58kPbeZxAT7slExz0vAUYvvpY1QEgd6qiB-1Qi1nGyXvfh6GGu4q1DMX-1EO7-3wPmUe8tGd0RiBG5Qiy4Nr5X56f8XEuS-9YxR1237gM4WyRiWIC-yp674hMtaPJ09umaXAWygV_RmJJxnsU6DHJOOh3_Ypd6qcnE-RzGOGIw-usNIzDLLxOZRSU0844FgbR6lz8EahgCt7B5Xju5PBmeMCW_8A60W-Q6fP4e31vdpyIVBXOV2JF_H-uv8HWgimot4HAAA=

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.

image image

dummdidumm commented 7 months ago

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={} />
brunnerh commented 7 months ago

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.

katriellucas commented 6 months ago

To add to the discussion, here is another powerful pattern (in my opinion) that would be possible with Snippet parameter/bindings:

Svelte 5 Repl

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.

Rich-Harris commented 5 months ago

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" />
brunnerh commented 5 months ago

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.

Effect that snippet.bind would have on example above `App.svelte` ```diff async function onEditName(user) { const data = $state({ name: user.name }); - const result = await showModal(nameEditor, data); + const result = await showModal(nameEditor.bind(data)); if (result == 'ok') user.name = data.name; } ``` `Dialog.svelte` ```diff - import { mountSnippet } from './MountSnippet.svelte'; ... - export function showModal(snippet, args) { + export function showModal(snippet) { return new Promise(resolve => { const dialog = mount(Dialog, { target: document.body, props: { + children: snippet, onclose(e) { resolve(e.target.returnValue); unmount(dialog); } } }); - mountSnippet(dialog.ref, snippet, args); // hacky dialog.ref.showModal(); }); } ``` `MountSnippet.svelte` ```diff - - - - - {@render snippet(args)} ```
Rich-Harris commented 5 months ago

I'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.)

brunnerh commented 5 months ago

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
Rich-Harris commented 5 months ago

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.

brunnerh commented 5 months ago

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.

pauldemarco commented 2 weeks ago

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

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"})} />
7nik commented 2 weeks ago

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')}/>

REPL

pauldemarco commented 2 weeks ago

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')}/>

REPL

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.